Skip to content

Commit 247e567

Browse files
committed
Don't return a slice pointing to a deceased stack address
1 parent 102bf52 commit 247e567

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src-self-hosted/translate_c.zig

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -691,8 +691,9 @@ fn transStringLiteral(
691691
const bytes_ptr = ZigClangStringLiteral_getString_bytes_begin_size(stmt, &len);
692692
const str = bytes_ptr[0..len];
693693

694+
var char_buf: [4]u8 = undefined;
694695
len = 0;
695-
for (str) |c| len += escapeChar(c).len;
696+
for (str) |c| len += escapeChar(c, &char_buf).len;
696697

697698
const buf = try rp.c.a().alloc(u8, len + "c\"\"".len);
698699
buf[0] = 'c';
@@ -725,33 +726,35 @@ fn transStringLiteral(
725726

726727
fn escapedStringLen(s: []const u8) usize {
727728
var len: usize = 0;
728-
for (s) |c| len += escapeChar(c).len;
729+
var char_buf: [4]u8 = undefined;
730+
for (s) |c| len += escapeChar(c, &char_buf).len;
729731
return len;
730732
}
731733

732734
fn writeEscapedString(buf: []u8, s: []const u8) void {
735+
var char_buf: [4]u8 = undefined;
733736
var i: usize = 0;
734737
for (s) |c| {
735-
const escaped = escapeChar(c);
738+
const escaped = escapeChar(c, &char_buf);
736739
std.mem.copy(u8, buf[i..], escaped);
737740
i += escaped.len;
738741
}
739742
}
740743

741-
fn escapeChar(c: u8) []const u8 {
744+
// Returns either a string literal or a slice of `buf`.
745+
fn escapeChar(c: u8, char_buf: *[4]u8) []const u8 {
742746
// TODO: https://github.com/ziglang/zig/issues/2749
743-
switch (c) {
747+
const escaped = switch (c) {
744748
// Printable ASCII except for ' " \
745-
' ', '!', '#'...'&', '('...'[', ']'...'~' => return ([_]u8{c})[0..],
746-
'\'', '\"', '\\' => return ([_]u8{ '\\', c })[0..],
749+
' ', '!', '#'...'&', '('...'[', ']'...'~' => ([_]u8{c})[0..],
750+
'\'', '\"', '\\' => ([_]u8{ '\\', c })[0..],
747751
'\n' => return "\\n"[0..],
748752
'\r' => return "\\r"[0..],
749753
'\t' => return "\\t"[0..],
750-
else => {
751-
var buf: [4]u8 = undefined;
752-
return std.fmt.bufPrint(buf[0..], "\\x{x:2}", c) catch unreachable;
753-
},
754-
}
754+
else => return std.fmt.bufPrint(char_buf[0..], "\\x{x:2}", c) catch unreachable,
755+
};
756+
std.mem.copy(u8, char_buf, escaped);
757+
return char_buf[0..escaped.len];
755758
}
756759

757760
fn transCCast(

0 commit comments

Comments
 (0)