From 99b9be7a34e1b64edf0c1abb3d358cd4ecd2ba7e Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Sun, 9 Jun 2024 19:37:57 -0700 Subject: [PATCH] Sentinel-terminate file contents (#11738) --- src/sys.zig | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/sys.zig b/src/sys.zig index d9a4ce3bc4..828004f0d4 100644 --- a/src/sys.zig +++ b/src/sys.zig @@ -2958,7 +2958,7 @@ pub const File = struct { /// 2. Open a file for reading /// 2. Read the file to a buffer /// 3. Return the File handle and the buffer - pub fn readFromUserInput(dir_fd: anytype, input_path: anytype, allocator: std.mem.Allocator) Maybe([]u8) { + pub fn readFromUserInput(dir_fd: anytype, input_path: anytype, allocator: std.mem.Allocator) Maybe([:0]u8) { var buf: bun.PathBuffer = undefined; const normalized = bun.path.joinAbsStringBufZ( bun.fs.FileSystem.instance.top_level_dir, @@ -2972,7 +2972,7 @@ pub const File = struct { /// 1. Open a file for reading /// 2. Read the file to a buffer /// 3. Return the File handle and the buffer - pub fn readFileFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe(struct { File, []u8 }) { + pub fn readFileFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe(struct { File, [:0]u8 }) { const ElementType = std.meta.Elem(@TypeOf(path)); const rc = brk: { @@ -3000,14 +3000,22 @@ pub const File = struct { return .{ .err = err }; } - return .{ .result = .{ this, result.bytes.items } }; + if (result.bytes.items.len == 0) { + // Don't allocate an empty string. + // We won't be modifying an empty slice, anyway. + return .{ .result = .{ this, @ptrCast(@constCast("")) } }; + } + + result.bytes.append(0) catch bun.outOfMemory(); + + return .{ .result = .{ this, result.bytes.items[0 .. result.bytes.items.len - 1 :0] } }; } /// 1. Open a file for reading relative to a directory /// 2. Read the file to a buffer /// 3. Close the file /// 4. Return the buffer - pub fn readFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe([]u8) { + pub fn readFrom(dir_fd: anytype, path: anytype, allocator: std.mem.Allocator) Maybe([:0]u8) { const file, const bytes = switch (readFileFrom(dir_fd, path, allocator)) { .err => |err| return .{ .err = err }, .result => |result| result,