From bf236a7dd673c7a39e2b4c64d77b30625cbb398f Mon Sep 17 00:00:00 2001 From: PhaseMage Date: Sat, 4 Dec 2021 09:16:49 -0800 Subject: [PATCH] Fix another test failure, small cleanups --- lib/std/process.zig | 19 ++++++++++++++++++- src/main.zig | 17 +++++------------ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/lib/std/process.zig b/lib/std/process.zig index a0dd04f5c801..c3a1293043fd 100644 --- a/lib/std/process.zig +++ b/lib/std/process.zig @@ -312,11 +312,15 @@ pub fn ArgIteratorGeneral(comptime options: ArgIteratorGeneralOptions) type { allocator: Allocator, index: usize = 0, cmd_line: []const u8, + + /// Should the cmd_line field be free'd (using the allocator) on deinit()? free_cmd_line_on_deinit: bool, + /// buffer MUST be long enough to hold the cmd_line plus a null terminator. + /// buffer will we free'd (using the allocator) on deinit() + buffer: []u8, start: usize = 0, end: usize = 0, - buffer: []u8, pub const Self = @This(); @@ -336,6 +340,19 @@ pub fn ArgIteratorGeneral(comptime options: ArgIteratorGeneralOptions) type { }; } + /// cmd_line_utf8 will be free'd (with the allocator) on deinit() + pub fn initTakeOwnership(allocator: Allocator, cmd_line_utf8: []const u8) InitError!Self { + var buffer = try allocator.alloc(u8, cmd_line_utf8.len + 1); + errdefer allocator.free(buffer); + + return Self{ + .allocator = allocator, + .cmd_line = cmd_line_utf8, + .free_cmd_line_on_deinit = true, + .buffer = buffer, + }; + } + /// cmd_line_utf16le MUST be encoded UTF16-LE, and is converted to UTF-8 in an internal buffer pub fn initUtf16le(allocator: Allocator, cmd_line_utf16le: [*:0]const u16) InitUtf16leError!Self { var utf16le_slice = cmd_line_utf16le[0..mem.len(cmd_line_utf16le)]; diff --git a/src/main.zig b/src/main.zig index e6a7dd947bb4..240df12412e7 100644 --- a/src/main.zig +++ b/src/main.zig @@ -4095,25 +4095,18 @@ pub const ClangArgIterator = struct { var response_file = try fs.cwd().openFile(resp_file_path, .{ .read = true, }); - var cmd_line_len = try response_file.getEndPos(); + const cmd_line_len = try response_file.getEndPos(); - if (cmd_line_len >= std.math.maxInt(usize)) + // Size of ResponseFile and an additional null terminator must fit in a usize + if (cmd_line_len >= (std.math.maxInt(usize) - 1)) return error.ResponseFileTooLarge; var cmd_line = try allocator.alloc(u8, @intCast(usize, cmd_line_len)); errdefer allocator.free(cmd_line); - cmd_line_len = try response_file.readAll(cmd_line); + const cmd_line_read_len = try response_file.readAll(cmd_line); - var buffer = try allocator.alloc(u8, cmd_line_len + 1); - errdefer allocator.free(buffer); - - return ArgIteratorResponseFile{ - .allocator = allocator, - .cmd_line = cmd_line[0..cmd_line_len], - .free_cmd_line_on_deinit = true, - .buffer = buffer, - }; + return ArgIteratorResponseFile.initTakeOwnership(allocator, cmd_line[0..cmd_line_read_len]); } fn next(self: *ClangArgIterator) !void {