Skip to content

Commit 1acb1fb

Browse files
committed
Make sure llvm strings are null-terminated
1 parent 002277b commit 1acb1fb

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src-self-hosted/stage1.zig

+16-4
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,15 @@ fn printCpusForArch(arch_name: []const u8, show_dependencies: bool) !void {
617617
}
618618
}
619619

620+
fn toNullTerminatedStringAlloc(allocator: *std.mem.Allocator, str: []const u8) ![:0]const u8 {
621+
var buffer = try std.Buffer.init(allocator, str);
622+
623+
const len = buffer.len();
624+
625+
// Don't deinit since we steal all the buffer's memory here.
626+
return buffer.list.toOwnedSlice()[0..len :0];
627+
}
628+
620629
const Stage2TargetDetails = struct {
621630
allocator: *std.mem.Allocator,
622631
target_details: std.target.TargetDetails,
@@ -643,8 +652,8 @@ const Stage2TargetDetails = struct {
643652
.target_details = .{
644653
.cpu = cpu,
645654
},
646-
.llvm_cpu_str = cpu.name,
647-
.llvm_features_str = "",
655+
.llvm_cpu_str = try toNullTerminatedStringAlloc(allocator, cpu.name),
656+
.llvm_features_str = try toNullTerminatedStringAlloc(allocator, ""),
648657
.builtin_str = builtin_str_buffer.toOwnedSlice(),
649658
};
650659
}
@@ -672,13 +681,16 @@ const Stage2TargetDetails = struct {
672681

673682
try builtin_str_buffer.append("}};");
674683

684+
// This is needed here because llvm_features_buffer.len() is no longer valid after toOwnedSlice().
685+
const llvm_features_buffer_len = llvm_features_buffer.len();
686+
675687
return Self{
676688
.allocator = allocator,
677689
.target_details = std.target.TargetDetails{
678690
.features = features,
679691
},
680-
.llvm_cpu_str = "",
681-
.llvm_features_str = llvm_features_buffer.toOwnedSlice(),
692+
.llvm_cpu_str = try toNullTerminatedStringAlloc(allocator, ""),
693+
.llvm_features_str = llvm_features_buffer.toOwnedSlice()[0..llvm_features_buffer_len :0],
682694
.builtin_str = builtin_str_buffer.toOwnedSlice(),
683695
};
684696
}

0 commit comments

Comments
 (0)