authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-02-09 18:27:50-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-02-09 18:27:50-05:00
loga2bd9f8912ade5149855dc6e2371aaae49093660
tree04dab23f1d6d730b5266506422daf820124fa139
parente7bf8f3f04efc280a76a3a38b4e6d470d279e41a

std lib: modify allocator idiom

Before we accepted a nullable allocator for some stuff like opening files. Now we require an allocator. Use the mem.FixedBufferAllocator pattern if a bound on the amount to allocate is known. This also establishes the pattern that usually an allocator is the first argument to a function (possibly after "self"). fix docs for std.cstr.addNullByte self hosted compiler: * only build docs when explicitly asked to * clean up main * stub out zig fmt

15 files changed, 103 insertions(+), 136 deletions(-)

build.zig-1
......@@ -78,7 +78,6 @@ pub fn build(b: &Builder) !void {
7878 exe.linkSystemLibrary("c");
7979
8080 b.default_step.dependOn(&exe.step);
81 b.default_step.dependOn(docs_step);
8281
8382 const skip_self_hosted = b.option(bool, "skip-self-hosted", "Main test suite skips building self hosted compiler") ?? false;
8483 if (!skip_self_hosted) {
doc/docgen.zig+3-3
......@@ -31,10 +31,10 @@ pub fn main() !void {
3131 const out_file_name = try (args_it.next(allocator) ?? @panic("expected output arg"));
3232 defer allocator.free(out_file_name);
3333
34 var in_file = try io.File.openRead(in_file_name, allocator);
34 var in_file = try io.File.openRead(allocator, in_file_name);
3535 defer in_file.close();
3636
37 var out_file = try io.File.openWrite(out_file_name, allocator);
37 var out_file = try io.File.openWrite(allocator, out_file_name);
3838 defer out_file.close();
3939
4040 var file_in_stream = io.FileInStream.init(&in_file);
......@@ -723,7 +723,7 @@ fn genHtml(allocator: &mem.Allocator, tokenizer: &Tokenizer, toc: &Toc, out: var
723723 try out.print("<pre><code class=\"zig\">{}</code></pre>", escaped_source);
724724 const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", code.name);
725725 const tmp_source_file_name = try os.path.join(allocator, tmp_dir_name, name_plus_ext);
726 try io.writeFile(tmp_source_file_name, trimmed_raw_source, null);
726 try io.writeFile(allocator, tmp_source_file_name, trimmed_raw_source);
727727
728728 switch (code.id) {
729729 Code.Id.Exe => |expected_outcome| {
example/cat/main.zig+1-1
......@@ -20,7 +20,7 @@ pub fn main() !void {
2020 } else if (arg[0] == '-') {
2121 return usage(exe);
2222 } else {
23 var file = io.File.openRead(arg, null) catch |err| {
23 var file = io.File.openRead(allocator, arg) catch |err| {
2424 warn("Unable to open file: {}\n", @errorName(err));
2525 return err;
2626 };
src-self-hosted/main.zig+35-30
......@@ -16,15 +16,6 @@ const c = @import("c.zig");
1616
1717const default_zig_cache_name = "zig-cache";
1818
19pub fn main() !void {
20 main2() catch |err| {
21 if (err != error.InvalidCommandLineArguments) {
22 warn("{}\n", @errorName(err));
23 }
24 return err;
25 };
26}
27
2819const Cmd = enum {
2920 None,
3021 Build,
......@@ -35,21 +26,25 @@ const Cmd = enum {
3526 Targets,
3627};
3728
38fn badArgs(comptime format: []const u8, args: ...) error {
39 var stderr = try io.getStdErr();
29fn badArgs(comptime format: []const u8, args: ...) noreturn {
30 var stderr = io.getStdErr() catch std.os.exit(1);
4031 var stderr_stream_adapter = io.FileOutStream.init(&stderr);
4132 const stderr_stream = &stderr_stream_adapter.stream;
42 try stderr_stream.print(format ++ "\n\n", args);
43 try printUsage(&stderr_stream_adapter.stream);
44 return error.InvalidCommandLineArguments;
33 stderr_stream.print(format ++ "\n\n", args) catch std.os.exit(1);
34 printUsage(&stderr_stream_adapter.stream) catch std.os.exit(1);
35 std.os.exit(1);
4536}
4637
47pub fn main2() !void {
38pub fn main() !void {
4839 const allocator = std.heap.c_allocator;
4940
5041 const args = try os.argsAlloc(allocator);
5142 defer os.argsFree(allocator, args);
5243
44 if (args.len >= 2 and mem.eql(u8, args[1], "fmt")) {
45 return fmtMain(allocator, args[2..]);
46 }
47
5348 var cmd = Cmd.None;
5449 var build_kind: Module.Kind = undefined;
5550 var build_mode: builtin.Mode = builtin.Mode.Debug;
......@@ -169,7 +164,7 @@ pub fn main2() !void {
169164 } else if (mem.eql(u8, arg, "--pkg-end")) {
170165 @panic("TODO --pkg-end");
171166 } else if (arg_i + 1 >= args.len) {
172 return badArgs("expected another argument after {}", arg);
167 badArgs("expected another argument after {}", arg);
173168 } else {
174169 arg_i += 1;
175170 if (mem.eql(u8, arg, "--output")) {
......@@ -184,7 +179,7 @@ pub fn main2() !void {
184179 } else if (mem.eql(u8, args[arg_i], "off")) {
185180 color = ErrColor.Off;
186181 } else {
187 return badArgs("--color options are 'auto', 'on', or 'off'");
182 badArgs("--color options are 'auto', 'on', or 'off'");
188183 }
189184 } else if (mem.eql(u8, arg, "--emit")) {
190185 if (mem.eql(u8, args[arg_i], "asm")) {
......@@ -194,7 +189,7 @@ pub fn main2() !void {
194189 } else if (mem.eql(u8, args[arg_i], "llvm-ir")) {
195190 emit_file_type = Emit.LlvmIr;
196191 } else {
197 return badArgs("--emit options are 'asm', 'bin', or 'llvm-ir'");
192 badArgs("--emit options are 'asm', 'bin', or 'llvm-ir'");
198193 }
199194 } else if (mem.eql(u8, arg, "--name")) {
200195 out_name_arg = args[arg_i];
......@@ -262,7 +257,7 @@ pub fn main2() !void {
262257 } else if (mem.eql(u8, arg, "--test-cmd")) {
263258 @panic("TODO --test-cmd");
264259 } else {
265 return badArgs("invalid argument: {}", arg);
260 badArgs("invalid argument: {}", arg);
266261 }
267262 }
268263 } else if (cmd == Cmd.None) {
......@@ -285,18 +280,18 @@ pub fn main2() !void {
285280 cmd = Cmd.Test;
286281 build_kind = Module.Kind.Exe;
287282 } else {
288 return badArgs("unrecognized command: {}", arg);
283 badArgs("unrecognized command: {}", arg);
289284 }
290285 } else switch (cmd) {
291286 Cmd.Build, Cmd.TranslateC, Cmd.Test => {
292287 if (in_file_arg == null) {
293288 in_file_arg = arg;
294289 } else {
295 return badArgs("unexpected extra parameter: {}", arg);
290 badArgs("unexpected extra parameter: {}", arg);
296291 }
297292 },
298293 Cmd.Version, Cmd.Zen, Cmd.Targets => {
299 return badArgs("unexpected extra parameter: {}", arg);
294 badArgs("unexpected extra parameter: {}", arg);
300295 },
301296 Cmd.None => unreachable,
302297 }
......@@ -333,15 +328,15 @@ pub fn main2() !void {
333328// }
334329
335330 switch (cmd) {
336 Cmd.None => return badArgs("expected command"),
331 Cmd.None => badArgs("expected command"),
337332 Cmd.Zen => return printZen(),
338333 Cmd.Build, Cmd.Test, Cmd.TranslateC => {
339334 if (cmd == Cmd.Build and in_file_arg == null and objects.len == 0 and asm_files.len == 0) {
340 return badArgs("expected source file argument or at least one --object or --assembly argument");
335 badArgs("expected source file argument or at least one --object or --assembly argument");
341336 } else if ((cmd == Cmd.TranslateC or cmd == Cmd.Test) and in_file_arg == null) {
342 return badArgs("expected source file argument");
337 badArgs("expected source file argument");
343338 } else if (cmd == Cmd.Build and build_kind == Module.Kind.Obj and objects.len != 0) {
344 return badArgs("When building an object file, --object arguments are invalid");
339 badArgs("When building an object file, --object arguments are invalid");
345340 }
346341
347342 const root_name = switch (cmd) {
......@@ -351,9 +346,9 @@ pub fn main2() !void {
351346 } else if (in_file_arg) |in_file_path| {
352347 const basename = os.path.basename(in_file_path);
353348 var it = mem.split(basename, ".");
354 break :x it.next() ?? return badArgs("file name cannot be empty");
349 break :x it.next() ?? badArgs("file name cannot be empty");
355350 } else {
356 return badArgs("--name [name] not provided and unable to infer");
351 badArgs("--name [name] not provided and unable to infer");
357352 }
358353 },
359354 Cmd.Test => "test",
......@@ -428,7 +423,7 @@ pub fn main2() !void {
428423 module.linker_rdynamic = rdynamic;
429424
430425 if (mmacosx_version_min != null and mios_version_min != null) {
431 return badArgs("-mmacosx-version-min and -mios-version-min options not allowed together");
426 badArgs("-mmacosx-version-min and -mios-version-min options not allowed together");
432427 }
433428
434429 if (mmacosx_version_min) |ver| {
......@@ -477,6 +472,7 @@ fn printUsage(stream: var) !void {
477472 \\ build-exe [source] create executable from source or object files
478473 \\ build-lib [source] create library from source or object files
479474 \\ build-obj [source] create object from source or assembly
475 \\ fmt [file] parse file and render in canonical zig format
480476 \\ translate-c [source] convert c code to zig code
481477 \\ targets list available compilation targets
482478 \\ test [source] create and run a test build
......@@ -564,6 +560,15 @@ fn printZen() !void {
564560 );
565561}
566562
563fn fmtMain(allocator: &mem.Allocator, file_paths: []const []const u8) !void {
564 for (file_paths) |file_path| {
565 var file = try io.File.openRead(allocator, file_path);
566 defer file.close();
567
568 warn("opened {} (todo tokenize and parse and render)\n", file_path);
569 }
570}
571
567572/// Caller must free result
568573fn resolveZigLibDir(allocator: &mem.Allocator, zig_install_prefix_arg: ?[]const u8) ![]u8 {
569574 if (zig_install_prefix_arg) |zig_install_prefix| {
......@@ -588,7 +593,7 @@ fn testZigInstallPrefix(allocator: &mem.Allocator, test_path: []const u8) ![]u8
588593 const test_index_file = try os.path.join(allocator, test_zig_dir, "std", "index.zig");
589594 defer allocator.free(test_index_file);
590595
591 var file = try io.File.openRead(test_index_file, allocator);
596 var file = try io.File.openRead(allocator, test_index_file);
592597 file.close();
593598
594599 return test_zig_dir;
src-self-hosted/module.zig+1-1
......@@ -213,7 +213,7 @@ pub const Module = struct {
213213 };
214214 errdefer self.allocator.free(root_src_real_path);
215215
216 const source_code = io.readFileAllocExtra(root_src_real_path, self.allocator, 3) catch |err| {
216 const source_code = io.readFileAllocExtra(self.allocator, root_src_real_path, 3) catch |err| {
217217 try printError("unable to open '{}': {}", root_src_real_path, err);
218218 return err;
219219 };
std/build.zig+1-1
......@@ -1890,7 +1890,7 @@ pub const WriteFileStep = struct {
18901890 warn("unable to make path {}: {}\n", full_path_dir, @errorName(err));
18911891 return err;
18921892 };
1893 io.writeFile(full_path, self.data, self.builder.allocator) catch |err| {
1893 io.writeFile(self.builder.allocator, full_path, self.data) catch |err| {
18941894 warn("unable to write {}: {}\n", full_path, @errorName(err));
18951895 return err;
18961896 };
std/cstr.zig+1-2
......@@ -39,8 +39,7 @@ fn testCStrFnsImpl() void {
3939 assert(len(c"123456789") == 9);
4040}
4141
42/// Returns a mutable slice with exactly the same size which is guaranteed to
43/// have a null byte after it.
42/// Returns a mutable slice with 1 more byte of length which is a null byte.
4443/// Caller owns the returned memory.
4544pub fn addNullByte(allocator: &mem.Allocator, slice: []const u8) ![]u8 {
4645 const result = try allocator.alloc(u8, slice.len + 1);
std/debug/index.zig+1-1
......@@ -265,7 +265,7 @@ pub fn openSelfDebugInfo(allocator: &mem.Allocator) !&ElfStackTrace {
265265}
266266
267267fn printLineFromFile(allocator: &mem.Allocator, out_stream: var, line_info: &const LineInfo) !void {
268 var f = try io.File.openRead(line_info.file_name, allocator);
268 var f = try io.File.openRead(allocator, line_info.file_name);
269269 defer f.close();
270270 // TODO fstat and make sure that the file has the correct size
271271
std/io.zig+19-28
......@@ -110,19 +110,16 @@ pub const File = struct {
110110
111111 const OpenError = os.WindowsOpenError || os.PosixOpenError;
112112
113 /// `path` may need to be copied in memory to add a null terminating byte. In this case
114 /// a fixed size buffer of size std.os.max_noalloc_path_len is an attempted solution. If the fixed
115 /// size buffer is too small, and the provided allocator is null, error.NameTooLong is returned.
116 /// otherwise if the fixed size buffer is too small, allocator is used to obtain the needed memory.
113 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
117114 /// Call close to clean up.
118 pub fn openRead(path: []const u8, allocator: ?&mem.Allocator) OpenError!File {
115 pub fn openRead(allocator: &mem.Allocator, path: []const u8) OpenError!File {
119116 if (is_posix) {
120117 const flags = system.O_LARGEFILE|system.O_RDONLY;
121 const fd = try os.posixOpen(path, flags, 0, allocator);
118 const fd = try os.posixOpen(allocator, path, flags, 0);
122119 return openHandle(fd);
123120 } else if (is_windows) {
124 const handle = try os.windowsOpen(path, system.GENERIC_READ, system.FILE_SHARE_READ,
125 system.OPEN_EXISTING, system.FILE_ATTRIBUTE_NORMAL, allocator);
121 const handle = try os.windowsOpen(allocator, path, system.GENERIC_READ, system.FILE_SHARE_READ,
122 system.OPEN_EXISTING, system.FILE_ATTRIBUTE_NORMAL);
126123 return openHandle(handle);
127124 } else {
128125 unreachable;
......@@ -130,25 +127,22 @@ pub const File = struct {
130127 }
131128
132129 /// Calls `openWriteMode` with 0o666 for the mode.
133 pub fn openWrite(path: []const u8, allocator: ?&mem.Allocator) !File {
134 return openWriteMode(path, 0o666, allocator);
130 pub fn openWrite(allocator: &mem.Allocator, path: []const u8) !File {
131 return openWriteMode(allocator, path, 0o666);
135132
136133 }
137134
138 /// `path` may need to be copied in memory to add a null terminating byte. In this case
139 /// a fixed size buffer of size std.os.max_noalloc_path_len is an attempted solution. If the fixed
140 /// size buffer is too small, and the provided allocator is null, error.NameTooLong is returned.
141 /// otherwise if the fixed size buffer is too small, allocator is used to obtain the needed memory.
135 /// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
142136 /// Call close to clean up.
143 pub fn openWriteMode(path: []const u8, mode: usize, allocator: ?&mem.Allocator) !File {
137 pub fn openWriteMode(allocator: &mem.Allocator, path: []const u8, mode: usize) !File {
144138 if (is_posix) {
145139 const flags = system.O_LARGEFILE|system.O_WRONLY|system.O_CREAT|system.O_CLOEXEC|system.O_TRUNC;
146 const fd = try os.posixOpen(path, flags, mode, allocator);
140 const fd = try os.posixOpen(allocator, path, flags, mode);
147141 return openHandle(fd);
148142 } else if (is_windows) {
149 const handle = try os.windowsOpen(path, system.GENERIC_WRITE,
143 const handle = try os.windowsOpen(allocator, path, system.GENERIC_WRITE,
150144 system.FILE_SHARE_WRITE|system.FILE_SHARE_READ|system.FILE_SHARE_DELETE,
151 system.CREATE_ALWAYS, system.FILE_ATTRIBUTE_NORMAL, allocator);
145 system.CREATE_ALWAYS, system.FILE_ATTRIBUTE_NORMAL);
152146 return openHandle(handle);
153147 } else {
154148 unreachable;
......@@ -521,24 +515,21 @@ pub fn OutStream(comptime Error: type) type {
521515 };
522516}
523517
524/// `path` may need to be copied in memory to add a null terminating byte. In this case
525/// a fixed size buffer of size `std.os.max_noalloc_path_len` is an attempted solution. If the fixed
526/// size buffer is too small, and the provided allocator is null, `error.NameTooLong` is returned.
527/// otherwise if the fixed size buffer is too small, allocator is used to obtain the needed memory.
528pub fn writeFile(path: []const u8, data: []const u8, allocator: ?&mem.Allocator) !void {
529 var file = try File.openWrite(path, allocator);
518/// `path` needs to be copied in memory to add a null terminating byte, hence the allocator.
519pub fn writeFile(allocator: &mem.Allocator, path: []const u8, data: []const u8) !void {
520 var file = try File.openWrite(allocator, path);
530521 defer file.close();
531522 try file.write(data);
532523}
533524
534525/// On success, caller owns returned buffer.
535pub fn readFileAlloc(path: []const u8, allocator: &mem.Allocator) ![]u8 {
536 return readFileAllocExtra(path, allocator, 0);
526pub fn readFileAlloc(allocator: &mem.Allocator, path: []const u8) ![]u8 {
527 return readFileAllocExtra(allocator, path, 0);
537528}
538529/// On success, caller owns returned buffer.
539530/// Allocates extra_len extra bytes at the end of the file buffer, which are uninitialized.
540pub fn readFileAllocExtra(path: []const u8, allocator: &mem.Allocator, extra_len: usize) ![]u8 {
541 var file = try File.openRead(path, allocator);
531pub fn readFileAllocExtra(allocator: &mem.Allocator, path: []const u8, extra_len: usize) ![]u8 {
532 var file = try File.openRead(allocator, path);
542533 defer file.close();
543534
544535 const size = try file.getEndPos();
std/io_test.zig+2-2
......@@ -13,7 +13,7 @@ test "write a file, read it, then delete it" {
1313 rng.fillBytes(data[0..]);
1414 const tmp_file_name = "temp_test_file.txt";
1515 {
16 var file = try io.File.openWrite(tmp_file_name, allocator);
16 var file = try io.File.openWrite(allocator, tmp_file_name);
1717 defer file.close();
1818
1919 var file_out_stream = io.FileOutStream.init(&file);
......@@ -25,7 +25,7 @@ test "write a file, read it, then delete it" {
2525 try buf_stream.flush();
2626 }
2727 {
28 var file = try io.File.openRead(tmp_file_name, allocator);
28 var file = try io.File.openRead(allocator, tmp_file_name);
2929 defer file.close();
3030
3131 const file_size = try file.getEndPos();
std/os/child_process.zig+17-11
......@@ -360,11 +360,14 @@ pub const ChildProcess = struct {
360360 errdefer if (self.stderr_behavior == StdIo.Pipe) { destroyPipe(stderr_pipe); };
361361
362362 const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore);
363 const dev_null_fd = if (any_ignore)
364 try os.posixOpen("/dev/null", posix.O_RDWR, 0, null)
365 else
366 undefined
367 ;
363 const dev_null_fd = if (any_ignore) blk: {
364 const dev_null_path = "/dev/null";
365 var fixed_buffer_mem: [dev_null_path.len + 1]u8 = undefined;
366 var fixed_allocator = mem.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
367 break :blk try os.posixOpen(&fixed_allocator.allocator, "/dev/null", posix.O_RDWR, 0);
368 } else blk: {
369 break :blk undefined;
370 };
368371 defer { if (any_ignore) os.close(dev_null_fd); }
369372
370373 var env_map_owned: BufMap = undefined;
......@@ -466,12 +469,15 @@ pub const ChildProcess = struct {
466469 self.stdout_behavior == StdIo.Ignore or
467470 self.stderr_behavior == StdIo.Ignore);
468471
469 const nul_handle = if (any_ignore)
470 try os.windowsOpen("NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ,
471 windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null)
472 else
473 undefined
474 ;
472 const nul_handle = if (any_ignore) blk: {
473 const nul_file_path = "NUL";
474 var fixed_buffer_mem: [nul_file_path.len + 1]u8 = undefined;
475 var fixed_allocator = mem.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
476 break :blk try os.windowsOpen(&fixed_allocator.allocator, "NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ,
477 windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL);
478 } else blk: {
479 break :blk undefined;
480 };
475481 defer { if (any_ignore) os.close(nul_handle); }
476482 if (any_ignore) {
477483 try windowsSetHandleInfo(nul_handle, windows.HANDLE_FLAG_INHERIT, 0);
std/os/index.zig+14-30
......@@ -15,7 +15,6 @@ pub const posix = switch(builtin.os) {
1515 else => @compileError("Unsupported OS"),
1616};
1717
18pub const max_noalloc_path_len = 1024;
1918pub const ChildProcess = @import("child_process.zig").ChildProcess;
2019pub const path = @import("path.zig");
2120
......@@ -265,32 +264,14 @@ pub const PosixOpenError = error {
265264 Unexpected,
266265};
267266
268/// ::file_path may need to be copied in memory to add a null terminating byte. In this case
269/// a fixed size buffer of size ::max_noalloc_path_len is an attempted solution. If the fixed
270/// size buffer is too small, and the provided allocator is null, ::error.NameTooLong is returned.
271/// otherwise if the fixed size buffer is too small, allocator is used to obtain the needed memory.
267/// ::file_path needs to be copied in memory to add a null terminating byte.
272268/// Calls POSIX open, keeps trying if it gets interrupted, and translates
273269/// the return value into zig errors.
274pub fn posixOpen(file_path: []const u8, flags: u32, perm: usize, allocator: ?&Allocator) PosixOpenError!i32 {
275 var stack_buf: [max_noalloc_path_len]u8 = undefined;
276 var path0: []u8 = undefined;
277 var need_free = false;
278
279 if (file_path.len < stack_buf.len) {
280 path0 = stack_buf[0..file_path.len + 1];
281 } else if (allocator) |a| {
282 path0 = try a.alloc(u8, file_path.len + 1);
283 need_free = true;
284 } else {
285 return error.NameTooLong;
286 }
287 defer if (need_free) {
288 (??allocator).free(path0);
289 };
290 mem.copy(u8, path0, file_path);
291 path0[file_path.len] = 0;
270pub fn posixOpen(allocator: &Allocator, file_path: []const u8, flags: u32, perm: usize) PosixOpenError!i32 {
271 const path_with_null = try cstr.addNullByte(allocator, file_path);
272 defer allocator.free(path_with_null);
292273
293 return posixOpenC(path0.ptr, flags, perm);
274 return posixOpenC(path_with_null.ptr, flags, perm);
294275}
295276
296277pub fn posixOpenC(file_path: &const u8, flags: u32, perm: usize) !i32 {
......@@ -784,11 +765,11 @@ pub fn copyFileMode(allocator: &Allocator, source_path: []const u8, dest_path: [
784765 try getRandomBytes(rand_buf[0..]);
785766 b64_fs_encoder.encode(tmp_path[dest_path.len..], rand_buf);
786767
787 var out_file = try io.File.openWriteMode(tmp_path, mode, allocator);
768 var out_file = try io.File.openWriteMode(allocator, tmp_path, mode);
788769 defer out_file.close();
789770 errdefer _ = deleteFile(allocator, tmp_path);
790771
791 var in_file = try io.File.openRead(source_path, allocator);
772 var in_file = try io.File.openRead(allocator, source_path);
792773 defer in_file.close();
793774
794775 var buf: [page_size]u8 = undefined;
......@@ -1074,7 +1055,7 @@ pub const Dir = struct {
10741055 };
10751056
10761057 pub fn open(allocator: &Allocator, dir_path: []const u8) !Dir {
1077 const fd = try posixOpen(dir_path, posix.O_RDONLY|posix.O_DIRECTORY|posix.O_CLOEXEC, 0, allocator);
1058 const fd = try posixOpen(allocator, dir_path, posix.O_RDONLY|posix.O_DIRECTORY|posix.O_CLOEXEC, 0);
10781059 return Dir {
10791060 .allocator = allocator,
10801061 .fd = fd,
......@@ -1642,13 +1623,16 @@ pub fn unexpectedErrorWindows(err: windows.DWORD) (error{Unexpected}) {
16421623pub fn openSelfExe() !io.File {
16431624 switch (builtin.os) {
16441625 Os.linux => {
1645 return io.File.openRead("/proc/self/exe", null);
1626 const proc_file_path = "/proc/self/exe";
1627 var fixed_buffer_mem: [proc_file_path.len + 1]u8 = undefined;
1628 var fixed_allocator = mem.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
1629 return io.File.openRead(&fixed_allocator.allocator, proc_file_path);
16461630 },
16471631 Os.macosx, Os.ios => {
1648 var fixed_buffer_mem: [darwin.PATH_MAX]u8 = undefined;
1632 var fixed_buffer_mem: [darwin.PATH_MAX * 2]u8 = undefined;
16491633 var fixed_allocator = mem.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
16501634 const self_exe_path = try selfExePath(&fixed_allocator.allocator);
1651 return io.File.openRead(self_exe_path, null);
1635 return io.File.openRead(&fixed_allocator.allocator, self_exe_path);
16521636 },
16531637 else => @compileError("Unsupported OS"),
16541638 }
std/os/path.zig+1-1
......@@ -1161,7 +1161,7 @@ pub fn real(allocator: &Allocator, pathname: []const u8) ![]u8 {
11611161 return allocator.shrink(u8, result_buf, cstr.len(result_buf.ptr));
11621162 },
11631163 Os.linux => {
1164 const fd = try os.posixOpen(pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0, allocator);
1164 const fd = try os.posixOpen(allocator, pathname, posix.O_PATH|posix.O_NONBLOCK|posix.O_CLOEXEC, 0);
11651165 defer os.close(fd);
11661166
11671167 var buf: ["/proc/self/fd/-2147483648".len]u8 = undefined;
std/os/windows/util.zig+6-23
......@@ -89,34 +89,17 @@ pub const OpenError = error {
8989 PipeBusy,
9090 Unexpected,
9191 OutOfMemory,
92 NameTooLong,
9392};
9493
95/// `file_path` may need to be copied in memory to add a null terminating byte. In this case
96/// a fixed size buffer of size ::max_noalloc_path_len is an attempted solution. If the fixed
97/// size buffer is too small, and the provided allocator is null, ::error.NameTooLong is returned.
98/// otherwise if the fixed size buffer is too small, allocator is used to obtain the needed memory.
99pub fn windowsOpen(file_path: []const u8, desired_access: windows.DWORD, share_mode: windows.DWORD,
100 creation_disposition: windows.DWORD, flags_and_attrs: windows.DWORD, allocator: ?&mem.Allocator)
94/// `file_path` needs to be copied in memory to add a null terminating byte, hence the allocator.
95pub fn windowsOpen(allocator: &mem.Allocator, file_path: []const u8, desired_access: windows.DWORD, share_mode: windows.DWORD,
96 creation_disposition: windows.DWORD, flags_and_attrs: windows.DWORD)
10197 OpenError!windows.HANDLE
10298{
103 var stack_buf: [os.max_noalloc_path_len]u8 = undefined;
104 var path0: []u8 = undefined;
105 var need_free = false;
106 defer if (need_free) (??allocator).free(path0);
107
108 if (file_path.len < stack_buf.len) {
109 path0 = stack_buf[0..file_path.len + 1];
110 } else if (allocator) |a| {
111 path0 = try a.alloc(u8, file_path.len + 1);
112 need_free = true;
113 } else {
114 return error.NameTooLong;
115 }
116 mem.copy(u8, path0, file_path);
117 path0[file_path.len] = 0;
99 const path_with_null = try cstr.addNullByte(allocator, file_path);
100 defer allocator.free(path_with_null);
118101
119 const result = windows.CreateFileA(path0.ptr, desired_access, share_mode, null, creation_disposition,
102 const result = windows.CreateFileA(path_with_null.ptr, desired_access, share_mode, null, creation_disposition,
120103 flags_and_attrs, null);
121104
122105 if (result == windows.INVALID_HANDLE_VALUE) {
test/tests.zig+1-1
......@@ -1049,7 +1049,7 @@ pub const GenHContext = struct {
10491049 warn("Test {}/{} {}...", self.test_index+1, self.context.test_index, self.name);
10501050
10511051 const full_h_path = b.pathFromRoot(self.h_path);
1052 const actual_h = try io.readFileAlloc(full_h_path, b.allocator);
1052 const actual_h = try io.readFileAlloc(b.allocator, full_h_path);
10531053
10541054 for (self.case.expected_lines.toSliceConst()) |expected_line| {
10551055 if (mem.indexOf(u8, actual_h, expected_line) == null) {