From 2a05ca1c9449fb26beaa948402e2742dee680137 Mon Sep 17 00:00:00 2001 From: Layne Gustafson Date: Sat, 28 Mar 2020 20:40:13 -0400 Subject: [PATCH 01/89] Conv macro string concat to ++ --- src-self-hosted/translate_c.zig | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index 3235ac90c0..1d8a2679f3 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -5782,6 +5782,18 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8, op_id = .Mod; op_token = try appendToken(c, .Percent, "%"); }, + .StringLiteral => { + op_id = .ArrayCat; + op_token = try appendToken(c, .PlusPlus, "++"); + + _ = it.prev(); + }, + .Identifier => { + op_id = .ArrayCat; + op_token = try appendToken(c, .PlusPlus, "++"); + + _ = it.prev(); + }, else => { _ = it.prev(); return node; From a55897106e34c55b02aeb5a5256e7da34f253de5 Mon Sep 17 00:00:00 2001 From: Layne Gustafson Date: Sat, 28 Mar 2020 20:40:26 -0400 Subject: [PATCH 02/89] Add macro string concat tests --- test/translate_c.zig | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/test/translate_c.zig b/test/translate_c.zig index 9890c4034e..8c84526a49 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -2808,4 +2808,43 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return if (x > y) x else y; \\} }); + + cases.add("string concatenation in macros", + \\#define FOO "hello" + \\#define BAR FOO " world" + \\#define BAZ "oh, " FOO + , &[_][]const u8{ + \\pub const FOO = "hello"; + , + \\pub const BAR = FOO ++ " world"; + , + \\pub const BAZ = "oh, " ++ FOO; + }); + + cases.add("string concatenation in macros: two defines", + \\#define FOO "hello" + \\#define BAZ " world" + \\#define BAR FOO BAZ + , &[_][]const u8{ + \\pub const FOO = "hello"; + , + \\pub const BAZ = " world"; + , + \\pub const BAR = FOO ++ BAZ; + }); + + cases.add("string concatenation in macros: two strings", + \\#define FOO "a" "b" + \\#define BAR FOO "c" + , &[_][]const u8{ + \\pub const FOO = "a" ++ "b"; + , + \\pub const BAR = FOO ++ "c"; + }); + + cases.add("string concatenation in macros: three strings", + \\#define FOO "a" "b" "c" + , &[_][]const u8{ + \\pub const FOO = "a" ++ ("b" ++ "c"); + }); } From 2b0d66736acdd156ec15a983c1f7d51d69c51559 Mon Sep 17 00:00:00 2001 From: Sebastian <15335529+Sobeston@users.noreply.github.com> Date: Sat, 28 Mar 2020 23:07:49 +0000 Subject: [PATCH 03/89] tcpConnectToHost - fixed compilation error before: ``` std\net.zig:403:23: error: type '@TypeOf(std.net.getAddressList).ReturnType.ErrorSet!*std.net.AddressList' does not support field access const addrs = list.addrs.toSliceConst(); ^ ``` --- lib/std/net.zig | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/std/net.zig b/lib/std/net.zig index 0a789b0dde..74b5173c57 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -397,13 +397,12 @@ pub const AddressList = struct { /// All memory allocated with `allocator` will be freed before this function returns. pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16) !fs.File { - const list = getAddressList(allocator, name, port); + const list = try getAddressList(allocator, name, port); defer list.deinit(); - const addrs = list.addrs.toSliceConst(); - if (addrs.len == 0) return error.UnknownHostName; + if (list.addrs.len == 0) return error.UnknownHostName; - return tcpConnectToAddress(addrs[0], port); + return tcpConnectToAddress(list.addrs[0]); } pub fn tcpConnectToAddress(address: Address) !fs.File { From d1202b1f6627eb1d8955fc8157685871bafe0d24 Mon Sep 17 00:00:00 2001 From: xackus <14938807+xackus@users.noreply.github.com> Date: Sun, 29 Mar 2020 06:54:23 +0200 Subject: [PATCH 04/89] fix overflow in parseFloat --- lib/std/fmt/parse_float.zig | 4 +++- lib/std/json/test.zig | 8 +++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/std/fmt/parse_float.zig b/lib/std/fmt/parse_float.zig index 0268ca96cc..14844e27c8 100644 --- a/lib/std/fmt/parse_float.zig +++ b/lib/std/fmt/parse_float.zig @@ -306,7 +306,7 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { State.Exponent => { if (isDigit(c)) { - if (exponent < std.math.maxInt(i32)) { + if (exponent < std.math.maxInt(i32) / 10) { exponent *= 10; exponent += @intCast(i32, c - '0'); } @@ -417,6 +417,8 @@ test "fmt.parseFloat" { expectEqual((try parseFloat(T, "inF")), std.math.inf(T)); expectEqual((try parseFloat(T, "-INF")), -std.math.inf(T)); + expectEqual(try parseFloat(T, "0.4e0066999999999999999999999999999999999999999999999999999"), std.math.inf(T)); + if (T != f16) { expect(approxEq(T, try parseFloat(T, "1e-2"), 0.01, epsilon)); expect(approxEq(T, try parseFloat(T, "1234e-2"), 12.34, epsilon)); diff --git a/lib/std/json/test.zig b/lib/std/json/test.zig index 6873fa038a..5d46b75a48 100644 --- a/lib/std/json/test.zig +++ b/lib/std/json/test.zig @@ -1751,11 +1751,9 @@ test "i_number_double_huge_neg_exp" { } test "i_number_huge_exp" { - return error.SkipZigTest; - // FIXME Integer overflow in parseFloat - // any( - // \\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006] - // ); + any( + \\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006] + ); } test "i_number_neg_int_huge_exp" { From 38a1af5d4fbe5994d6d8a93512e9332529958473 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 29 Mar 2020 10:31:35 -0400 Subject: [PATCH 05/89] zig cc: -O0 also counts as debug mode --- src/main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index a7a9b41950..f5e7e03b37 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -688,7 +688,9 @@ static int main0(int argc, char **argv) { strcmp(it.only_arg, "O4") == 0) { build_mode = BuildModeFastRelease; - } else if (strcmp(it.only_arg, "Og") == 0) { + } else if (strcmp(it.only_arg, "Og") == 0 || + strcmp(it.only_arg, "O0") == 0) + { build_mode = BuildModeDebug; } else { for (size_t i = 0; i < it.other_args_len; i += 1) { From c70471fae617fb91ca0a323f079574a3caaa7775 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 29 Mar 2020 10:33:37 -0400 Subject: [PATCH 06/89] enable now-passing test cases These can now be enabled thanks to bug fixes that landed in LLVM 10. --- lib/std/json.zig | 3 --- test/stage1/behavior/atomics.zig | 2 -- 2 files changed, 5 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index 49afb6bea6..88f07d0aae 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1658,9 +1658,6 @@ test "parse into tagged union" { } test "parseFree descends into tagged union" { - // tagged unions are broken on arm64: https://github.com/ziglang/zig/issues/4492 - if (std.builtin.arch == .aarch64) return error.SkipZigTest; - var fail_alloc = testing.FailingAllocator.init(testing.allocator, 1); const options = ParseOptions{ .allocator = &fail_alloc.allocator }; const T = union(enum) { diff --git a/test/stage1/behavior/atomics.zig b/test/stage1/behavior/atomics.zig index 680b1a2797..f9703e7308 100644 --- a/test/stage1/behavior/atomics.zig +++ b/test/stage1/behavior/atomics.zig @@ -190,8 +190,6 @@ fn testAtomicRmwInt() void { _ = @atomicRmw(u8, &x, .Xor, 2, .SeqCst); expect(x == 0xfd); - // TODO https://github.com/ziglang/zig/issues/4724 - if (builtin.arch == .mipsel) return; _ = @atomicRmw(u8, &x, .Max, 1, .SeqCst); expect(x == 0xfd); _ = @atomicRmw(u8, &x, .Min, 1, .SeqCst); From 5aa281250723c159aa0429941c16b046bba6d316 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 29 Mar 2020 13:17:21 -0400 Subject: [PATCH 07/89] linking is now aware -lm is provided by mingw-w64 --- src/link.cpp | 9 +++++++-- src/target.cpp | 9 +++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/link.cpp b/src/link.cpp index 1a454531b5..693aaca0e3 100644 --- a/src/link.cpp +++ b/src/link.cpp @@ -1903,7 +1903,7 @@ static void construct_linker_job_elf(LinkJob *lj) { // libc is linked specially continue; } - if (buf_eql_str(link_lib->name, "c++") || buf_eql_str(link_lib->name, "c++abi")) { + if (target_is_libcpp_lib_name(g->zig_target, buf_ptr(link_lib->name))) { // libc++ is linked specially continue; } @@ -2470,7 +2470,12 @@ static void construct_linker_job_coff(LinkJob *lj) { if (buf_eql_str(link_lib->name, "c")) { continue; } - if (buf_eql_str(link_lib->name, "c++") || buf_eql_str(link_lib->name, "c++abi")) { + if (target_is_libcpp_lib_name(g->zig_target, buf_ptr(link_lib->name))) { + // libc++ is linked specially + continue; + } + if (g->libc == nullptr && target_is_libc_lib_name(g->zig_target, buf_ptr(link_lib->name))) { + // these libraries are always linked below when targeting glibc continue; } bool is_sys_lib = is_mingw_link_lib(link_lib->name); diff --git a/src/target.cpp b/src/target.cpp index 59b1addc33..0307216834 100644 --- a/src/target.cpp +++ b/src/target.cpp @@ -1207,6 +1207,15 @@ bool target_is_libc_lib_name(const ZigTarget *target, const char *name) { if (strcmp(name, "c") == 0) return true; + if (target_abi_is_gnu(target->abi) && target->os == OsWindows) { + // mingw-w64 + + if (strcmp(name, "m") == 0) + return true; + + return false; + } + if (target_abi_is_gnu(target->abi) || target_abi_is_musl(target->abi) || target_os_is_darwin(target->os)) { if (strcmp(name, "m") == 0) return true; From 6809222d32e204ac46ee7b7b86a6ba5ebce955e6 Mon Sep 17 00:00:00 2001 From: xackus <14938807+xackus@users.noreply.github.com> Date: Sun, 29 Mar 2020 07:02:41 +0200 Subject: [PATCH 08/89] cleanup parse_float.zig --- lib/std/fmt/parse_float.zig | 118 +++++++++++++++--------------------- 1 file changed, 48 insertions(+), 70 deletions(-) diff --git a/lib/std/fmt/parse_float.zig b/lib/std/fmt/parse_float.zig index 14844e27c8..2495a140d3 100644 --- a/lib/std/fmt/parse_float.zig +++ b/lib/std/fmt/parse_float.zig @@ -30,6 +30,7 @@ // - Does not handle denormals const std = @import("../std.zig"); +const ascii = std.ascii; const max_digits = 25; @@ -190,14 +191,6 @@ const ParseResult = enum { MinusInf, }; -inline fn isDigit(c: u8) bool { - return c >= '0' and c <= '9'; -} - -inline fn isSpace(c: u8) bool { - return (c >= 0x09 and c <= 0x13) or c == 0x20; -} - fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { var digit_index: usize = 0; var negative = false; @@ -207,52 +200,49 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { var state = State.MaybeSign; var i: usize = 0; - loop: while (i < s.len) { + while (i < s.len) { const c = s[i]; switch (state) { - State.MaybeSign => { - state = State.LeadingMantissaZeros; + .MaybeSign => { + state = .LeadingMantissaZeros; if (c == '+') { i += 1; } else if (c == '-') { n.negative = true; i += 1; - } else if (isDigit(c) or c == '.') { + } else if (ascii.isDigit(c) or c == '.') { // continue } else { return error.InvalidCharacter; } }, - - State.LeadingMantissaZeros => { + .LeadingMantissaZeros => { if (c == '0') { i += 1; } else if (c == '.') { i += 1; - state = State.LeadingFractionalZeros; + state = .LeadingFractionalZeros; } else { - state = State.MantissaIntegral; + state = .MantissaIntegral; } }, - - State.LeadingFractionalZeros => { + .LeadingFractionalZeros => { if (c == '0') { i += 1; if (n.exponent > std.math.minInt(i32)) { n.exponent -= 1; } } else { - state = State.MantissaFractional; + state = .MantissaFractional; } }, - - State.MantissaIntegral => { - if (isDigit(c)) { + .MantissaIntegral => { + if (ascii.isDigit(c)) { if (digit_index < max_digits) { n.mantissa *%= 10; - n.mantissa += s[i] - '0'; + n.mantissa += c - '0'; digit_index += 1; } else if (n.exponent < std.math.maxInt(i32)) { n.exponent += 1; @@ -261,14 +251,13 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { i += 1; } else if (c == '.') { i += 1; - state = State.MantissaFractional; + state = .MantissaFractional; } else { - state = State.MantissaFractional; + state = .MantissaFractional; } }, - - State.MantissaFractional => { - if (isDigit(c)) { + .MantissaFractional => { + if (ascii.isDigit(c)) { if (digit_index < max_digits) { n.mantissa *%= 10; n.mantissa += c - '0'; @@ -279,13 +268,12 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { i += 1; } else if (c == 'e' or c == 'E') { i += 1; - state = State.ExponentSign; + state = .ExponentSign; } else { - state = State.ExponentSign; + state = .ExponentSign; } }, - - State.ExponentSign => { + .ExponentSign => { if (c == '+') { i += 1; } else if (c == '-') { @@ -293,19 +281,17 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { i += 1; } - state = State.LeadingExponentZeros; + state = .LeadingExponentZeros; }, - - State.LeadingExponentZeros => { + .LeadingExponentZeros => { if (c == '0') { i += 1; } else { - state = State.Exponent; + state = .Exponent; } }, - - State.Exponent => { - if (isDigit(c)) { + .Exponent => { + if (ascii.isDigit(c)) { if (exponent < std.math.maxInt(i32) / 10) { exponent *= 10; exponent += @intCast(i32, c - '0'); @@ -323,29 +309,21 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { n.exponent += exponent; if (n.mantissa == 0) { - return if (n.negative) ParseResult.MinusZero else ParseResult.PlusZero; + return if (n.negative) .MinusZero else .PlusZero; } else if (n.exponent > 309) { - return if (n.negative) ParseResult.MinusInf else ParseResult.PlusInf; + return if (n.negative) .MinusInf else .PlusInf; } else if (n.exponent < -328) { - return if (n.negative) ParseResult.MinusZero else ParseResult.PlusZero; + return if (n.negative) .MinusZero else .PlusZero; } - return ParseResult.Ok; -} - -inline fn isLower(c: u8) bool { - return c -% 'a' < 26; -} - -inline fn toUpper(c: u8) u8 { - return if (isLower(c)) (c & 0x5f) else c; + return .Ok; } fn caseInEql(a: []const u8, b: []const u8) bool { if (a.len != b.len) return false; for (a) |_, i| { - if (toUpper(a[i]) != toUpper(b[i])) { + if (ascii.toUpper(a[i]) != ascii.toUpper(b[i])) { return false; } } @@ -373,11 +351,11 @@ pub fn parseFloat(comptime T: type, s: []const u8) !T { }; return switch (try parseRepr(s, &r)) { - ParseResult.Ok => convertRepr(T, r), - ParseResult.PlusZero => 0.0, - ParseResult.MinusZero => -@as(T, 0.0), - ParseResult.PlusInf => std.math.inf(T), - ParseResult.MinusInf => -std.math.inf(T), + .Ok => convertRepr(T, r), + .PlusZero => 0.0, + .MinusZero => -@as(T, 0.0), + .PlusInf => std.math.inf(T), + .MinusInf => -std.math.inf(T), }; } @@ -396,26 +374,26 @@ test "fmt.parseFloat" { testing.expectError(error.InvalidCharacter, parseFloat(T, "1abc")); expectEqual(try parseFloat(T, "0"), 0.0); - expectEqual((try parseFloat(T, "0")), 0.0); - expectEqual((try parseFloat(T, "+0")), 0.0); - expectEqual((try parseFloat(T, "-0")), 0.0); + expectEqual(try parseFloat(T, "0"), 0.0); + expectEqual(try parseFloat(T, "+0"), 0.0); + expectEqual(try parseFloat(T, "-0"), 0.0); - expectEqual((try parseFloat(T, "0e0")), 0); - expectEqual((try parseFloat(T, "2e3")), 2000.0); - expectEqual((try parseFloat(T, "1e0")), 1.0); - expectEqual((try parseFloat(T, "-2e3")), -2000.0); - expectEqual((try parseFloat(T, "-1e0")), -1.0); - expectEqual((try parseFloat(T, "1.234e3")), 1234); + expectEqual(try parseFloat(T, "0e0"), 0); + expectEqual(try parseFloat(T, "2e3"), 2000.0); + expectEqual(try parseFloat(T, "1e0"), 1.0); + expectEqual(try parseFloat(T, "-2e3"), -2000.0); + expectEqual(try parseFloat(T, "-1e0"), -1.0); + expectEqual(try parseFloat(T, "1.234e3"), 1234); expect(approxEq(T, try parseFloat(T, "3.141"), 3.141, epsilon)); expect(approxEq(T, try parseFloat(T, "-3.141"), -3.141, epsilon)); - expectEqual((try parseFloat(T, "1e-700")), 0); - expectEqual((try parseFloat(T, "1e+700")), std.math.inf(T)); + expectEqual(try parseFloat(T, "1e-700"), 0); + expectEqual(try parseFloat(T, "1e+700"), std.math.inf(T)); expectEqual(@bitCast(Z, try parseFloat(T, "nAn")), @bitCast(Z, std.math.nan(T))); - expectEqual((try parseFloat(T, "inF")), std.math.inf(T)); - expectEqual((try parseFloat(T, "-INF")), -std.math.inf(T)); + expectEqual(try parseFloat(T, "inF"), std.math.inf(T)); + expectEqual(try parseFloat(T, "-INF"), -std.math.inf(T)); expectEqual(try parseFloat(T, "0.4e0066999999999999999999999999999999999999999999999999999"), std.math.inf(T)); From f9f7deaeda20b212ae4daea0009a904beccdf828 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 29 Mar 2020 20:58:59 -0400 Subject: [PATCH 09/89] linking against c++ does not trigger system library directories --- src/main.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index f5e7e03b37..05ba1ab40f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1371,15 +1371,17 @@ static int main0(int argc, char **argv) { return print_error_usage(arg0); } - bool any_non_c_link_libs = false; + bool any_system_lib_dependencies = false; for (size_t i = 0; i < link_libs.length; i += 1) { - if (!target_is_libc_lib_name(&target, link_libs.at(i))) { - any_non_c_link_libs = true; + if (!target_is_libc_lib_name(&target, link_libs.at(i)) && + !target_is_libcpp_lib_name(&target, link_libs.at(i))) + { + any_system_lib_dependencies = true; break; } } - if (target.is_native_os && any_non_c_link_libs) { + if (target.is_native_os && any_system_lib_dependencies) { Error err; Stage2NativePaths paths; if ((err = stage2_detect_native_paths(&paths))) { From de9933761c56287a27f3c348a99434ddab175094 Mon Sep 17 00:00:00 2001 From: Michael Raymond Date: Sat, 28 Mar 2020 15:44:40 +0000 Subject: [PATCH 10/89] std.zig.render: fix newlines before DocComments --- lib/std/zig/parser_test.zig | 29 +++++++++++++++++++++++++++++ lib/std/zig/render.zig | 6 +++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index daeb197913..136e323fe6 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -373,6 +373,35 @@ test "zig fmt: correctly move doc comments on struct fields" { ); } +test "zig fmt: correctly space struct fields with doc comments" { + try testTransform( + \\pub const S = struct { + \\ /// A + \\ a: u8, + \\ /// B + \\ /// B (cont) + \\ b: u8, + \\ + \\ + \\ /// C + \\ c: u8, + \\}; + \\ + , + \\pub const S = struct { + \\ /// A + \\ a: u8, + \\ /// B + \\ /// B (cont) + \\ b: u8, + \\ + \\ /// C + \\ c: u8, + \\}; + \\ + ); +} + test "zig fmt: doc comments on param decl" { try testCanonical( \\pub const Allocator = struct { diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 37d058bebf..c5e5201680 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -187,12 +187,16 @@ fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *as const first_token = node.firstToken(); var prev_token = first_token; if (prev_token == 0) return; + var newline_threshold: usize = 2; while (tree.tokens.at(prev_token - 1).id == .DocComment) { + if (tree.tokenLocation(tree.tokens.at(prev_token - 1).end, prev_token).line == 1) { + newline_threshold += 1; + } prev_token -= 1; } const prev_token_end = tree.tokens.at(prev_token - 1).end; const loc = tree.tokenLocation(prev_token_end, first_token); - if (loc.line >= 2) { + if (loc.line >= newline_threshold) { try stream.writeByte('\n'); start_col.* = 0; } From 356ef3840fcfc5065713fd20908eba0eb7648b66 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Mon, 30 Mar 2020 21:24:08 +1100 Subject: [PATCH 11/89] std: update for linux 5.6 release --- lib/std/os/bits/linux.zig | 139 +++++++++++++++++++++++++---- lib/std/os/bits/linux/arm-eabi.zig | 2 + lib/std/os/bits/linux/arm64.zig | 2 + lib/std/os/bits/linux/i386.zig | 2 + lib/std/os/bits/linux/mipsel.zig | 2 + lib/std/os/bits/linux/riscv64.zig | 2 + lib/std/os/bits/linux/x86_64.zig | 2 + lib/std/os/linux.zig | 4 +- 8 files changed, 134 insertions(+), 21 deletions(-) diff --git a/lib/std/os/bits/linux.zig b/lib/std/os/bits/linux.zig index 89364909c9..3a2040b440 100644 --- a/lib/std/os/bits/linux.zig +++ b/lib/std/os/bits/linux.zig @@ -88,11 +88,29 @@ pub const FUTEX_PRIVATE_FLAG = 128; pub const FUTEX_CLOCK_REALTIME = 256; -pub const PROT_NONE = 0; -pub const PROT_READ = 1; -pub const PROT_WRITE = 2; -pub const PROT_EXEC = 4; +/// page can not be accessed +pub const PROT_NONE = 0x0; + +/// page can be read +pub const PROT_READ = 0x1; + +/// page can be written +pub const PROT_WRITE = 0x2; + +/// page can be executed +pub const PROT_EXEC = 0x4; + +/// page may be used for atomic ops +pub const PROT_SEM = switch (builtin.arch) { + // TODO: also xtensa + .mips, .mipsel, .mips64, .mips64el => 0x10, + else => 0x8, +}; + +/// mprotect flag: extend change to start of growsdown vma pub const PROT_GROWSDOWN = 0x01000000; + +/// mprotect flag: extend change to end of growsup vma pub const PROT_GROWSUP = 0x02000000; /// Share changes @@ -617,6 +635,11 @@ pub const CLONE_IO = 0x80000000; /// Clear any signal handler and reset to SIG_DFL. pub const CLONE_CLEAR_SIGHAND = 0x100000000; +// cloning flags intersect with CSIGNAL so can be used with unshare and clone3 syscalls only. + +/// New time namespace +pub const CLONE_NEWTIME = 0x00000080; + pub const EFD_SEMAPHORE = 1; pub const EFD_CLOEXEC = O_CLOEXEC; pub const EFD_NONBLOCK = O_NONBLOCK; @@ -1125,7 +1148,8 @@ pub const io_uring_params = extern struct { sq_thread_cpu: u32, sq_thread_idle: u32, features: u32, - resv: [4]u32, + wq_fd: u32, + resv: [3]u32, sq_off: io_sqring_offsets, cq_off: io_cqring_offsets, }; @@ -1135,6 +1159,8 @@ pub const io_uring_params = extern struct { pub const IORING_FEAT_SINGLE_MMAP = 1 << 0; pub const IORING_FEAT_NODROP = 1 << 1; pub const IORING_FEAT_SUBMIT_STABLE = 1 << 2; +pub const IORING_FEAT_RW_CUR_POS = 1 << 3; +pub const IORING_FEAT_CUR_PERSONALITY = 1 << 4; // io_uring_params.flags @@ -1150,6 +1176,12 @@ pub const IORING_SETUP_SQ_AFF = 1 << 2; /// app defines CQ size pub const IORING_SETUP_CQSIZE = 1 << 3; +/// clamp SQ/CQ ring sizes +pub const IORING_SETUP_CLAMP = 1 << 4; + +/// attach to existing wq +pub const IORING_SETUP_ATTACH_WQ = 1 << 5; + pub const io_sqring_offsets = extern struct { /// offset of ring head head: u32, @@ -1192,7 +1224,7 @@ pub const io_cqring_offsets = extern struct { }; pub const io_uring_sqe = extern struct { - opcode: u8, + opcode: IORING_OP, flags: u8, ioprio: u16, fd: i32, @@ -1212,31 +1244,53 @@ pub const io_uring_sqe = extern struct { timeout_flags: u32, accept_flags: u32, cancel_flags: u32, + open_flags: u32, + statx_flags: u32, + fadvise_flags: u32, }; union2: union2, user_data: u64, pub const union3 = extern union { - buf_index: u16, + struct1: extern struct { + /// index into fixed buffers, if used + buf_index: u16, + + /// personality to use, if used + personality: u16, + }, __pad2: [3]u64, }; union3: union3, }; +pub const IOSQE_BIT = extern enum { + FIXED_FILE, + IO_DRAIN, + IO_LINK, + IO_HARDLINK, + ASYNC, + + _, +}; + // io_uring_sqe.flags /// use fixed fileset -pub const IOSQE_FIXED_FILE = 1 << 0; +pub const IOSQE_FIXED_FILE = 1 << IOSQE_BIT.FIXED_FILE; /// issue after inflight IO -pub const IOSQE_IO_DRAIN = 1 << 1; +pub const IOSQE_IO_DRAIN = 1 << IOSQE_BIT.IO_DRAIN; /// links next sqe -pub const IOSQE_IO_LINK = 1 << 2; +pub const IOSQE_IO_LINK = 1 << IOSQE_BIT.IO_LINK; /// like LINK, but stronger -pub const IOSQE_IO_HARDLINK = 1 << 3; +pub const IOSQE_IO_HARDLINK = 1 << IOSQE_BIT.IO_HARDLINK; -pub const IORING_OP = extern enum { +/// always go async +pub const IOSQE_ASYNC = 1 << IOSQE_BIT.ASYNC; + +pub const IORING_OP = extern enum(u8) { NOP, READV, WRITEV, @@ -1254,6 +1308,19 @@ pub const IORING_OP = extern enum { ASYNC_CANCEL, LINK_TIMEOUT, CONNECT, + FALLOCATE, + OPENAT, + CLOSE, + FILES_UPDATE, + STATX, + READ, + WRITE, + FADVISE, + MADVISE, + SEND, + RECV, + OPENAT2, + EPOLL_CTL, _, }; @@ -1283,13 +1350,21 @@ pub const IORING_ENTER_GETEVENTS = 1 << 0; pub const IORING_ENTER_SQ_WAKEUP = 1 << 1; // io_uring_register opcodes and arguments -pub const IORING_REGISTER_BUFFERS = 0; -pub const IORING_UNREGISTER_BUFFERS = 1; -pub const IORING_REGISTER_FILES = 2; -pub const IORING_UNREGISTER_FILES = 3; -pub const IORING_REGISTER_EVENTFD = 4; -pub const IORING_UNREGISTER_EVENTFD = 5; -pub const IORING_REGISTER_FILES_UPDATE = 6; +pub const IORING_REGISTER = extern enum(u32) { + REGISTER_BUFFERS, + UNREGISTER_BUFFERS, + REGISTER_FILES, + UNREGISTER_FILES, + REGISTER_EVENTFD, + UNREGISTER_EVENTFD, + REGISTER_FILES_UPDATE, + REGISTER_EVENTFD_ASYNC, + REGISTER_PROBE, + REGISTER_PERSONALITY, + UNREGISTER_PERSONALITY, + + _, +}; pub const io_uring_files_update = struct { offset: u32, @@ -1297,6 +1372,32 @@ pub const io_uring_files_update = struct { fds: u64, }; +pub const IO_URING_OP_SUPPORTED = 1 << 0; + +pub const io_uring_probe_op = struct { + op: IORING_OP, + + resv: u8, + + /// IO_URING_OP_* flags + flags: u16, + + resv2: u32, +}; + +pub const io_uring_probe = struct { + /// last opcode supported + last_op: IORING_OP, + + /// Number of io_uring_probe_op following + ops_len: u8, + + resv: u16, + resv2: u32[3], + + // Followed by up to `ops_len` io_uring_probe_op structures +}; + pub const utsname = extern struct { sysname: [64:0]u8, nodename: [64:0]u8, diff --git a/lib/std/os/bits/linux/arm-eabi.zig b/lib/std/os/bits/linux/arm-eabi.zig index de71607c30..1824263fa4 100644 --- a/lib/std/os/bits/linux/arm-eabi.zig +++ b/lib/std/os/bits/linux/arm-eabi.zig @@ -400,6 +400,8 @@ pub const SYS_fsmount = 432; pub const SYS_fspick = 433; pub const SYS_pidfd_open = 434; pub const SYS_clone3 = 435; +pub const SYS_openat2 = 437; +pub const SYS_pidfd_getfd = 438; pub const SYS_breakpoint = 0x0f0001; pub const SYS_cacheflush = 0x0f0002; diff --git a/lib/std/os/bits/linux/arm64.zig b/lib/std/os/bits/linux/arm64.zig index 386e889873..79a363f844 100644 --- a/lib/std/os/bits/linux/arm64.zig +++ b/lib/std/os/bits/linux/arm64.zig @@ -302,6 +302,8 @@ pub const SYS_fsmount = 432; pub const SYS_fspick = 433; pub const SYS_pidfd_open = 434; pub const SYS_clone3 = 435; +pub const SYS_openat2 = 437; +pub const SYS_pidfd_getfd = 438; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/bits/linux/i386.zig b/lib/std/os/bits/linux/i386.zig index 2585785b13..233340f6a1 100644 --- a/lib/std/os/bits/linux/i386.zig +++ b/lib/std/os/bits/linux/i386.zig @@ -434,6 +434,8 @@ pub const SYS_fsopen = 430; pub const SYS_fsconfig = 431; pub const SYS_fsmount = 432; pub const SYS_fspick = 433; +pub const SYS_openat2 = 437; +pub const SYS_pidfd_getfd = 438; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/bits/linux/mipsel.zig b/lib/std/os/bits/linux/mipsel.zig index 638a4b1de7..4ef7619745 100644 --- a/lib/std/os/bits/linux/mipsel.zig +++ b/lib/std/os/bits/linux/mipsel.zig @@ -375,6 +375,8 @@ pub const SYS_pkey_free = (SYS_Linux + 365); pub const SYS_statx = (SYS_Linux + 366); pub const SYS_rseq = (SYS_Linux + 367); pub const SYS_io_pgetevents = (SYS_Linux + 368); +pub const SYS_openat2 = (SYS_Linux + 437); +pub const SYS_pidfd_getfd = (SYS_Linux + 438); pub const O_CREAT = 0o0400; pub const O_EXCL = 0o02000; diff --git a/lib/std/os/bits/linux/riscv64.zig b/lib/std/os/bits/linux/riscv64.zig index e0c10ef7c0..75c67517e4 100644 --- a/lib/std/os/bits/linux/riscv64.zig +++ b/lib/std/os/bits/linux/riscv64.zig @@ -297,6 +297,8 @@ pub const SYS_fsmount = 432; pub const SYS_fspick = 433; pub const SYS_pidfd_open = 434; pub const SYS_clone3 = 435; +pub const SYS_openat2 = 437; +pub const SYS_pidfd_getfd = 438; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/bits/linux/x86_64.zig b/lib/std/os/bits/linux/x86_64.zig index e92591d94e..96984c7c5a 100644 --- a/lib/std/os/bits/linux/x86_64.zig +++ b/lib/std/os/bits/linux/x86_64.zig @@ -362,6 +362,8 @@ pub const SYS_fsmount = 432; pub const SYS_fspick = 433; pub const SYS_pidfd_open = 434; pub const SYS_clone3 = 435; +pub const SYS_openat2 = 437; +pub const SYS_pidfd_getfd = 438; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/linux.zig b/lib/std/os/linux.zig index ae48d831cf..2e1437e6a9 100644 --- a/lib/std/os/linux.zig +++ b/lib/std/os/linux.zig @@ -1169,8 +1169,8 @@ pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, si return syscall6(SYS_io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8); } -pub fn io_uring_register(fd: i32, opcode: u32, arg: ?*const c_void, nr_args: u32) usize { - return syscall4(SYS_io_uring_register, @bitCast(usize, @as(isize, fd)), opcode, @ptrToInt(arg), nr_args); +pub fn io_uring_register(fd: i32, opcode: IORING_REGISTER, arg: ?*const c_void, nr_args: u32) usize { + return syscall4(SYS_io_uring_register, @bitCast(usize, @as(isize, fd)), @enumToInt(opcode), @ptrToInt(arg), nr_args); } pub fn memfd_create(name: [*:0]const u8, flags: u32) usize { From 9bc8a1e1d0a032e2666e2a5420211cc4b052de56 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Mon, 30 Mar 2020 21:35:32 +1100 Subject: [PATCH 12/89] std: add some missing errnos on linux --- lib/std/os/bits/linux/errno-generic.zig | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/std/os/bits/linux/errno-generic.zig b/lib/std/os/bits/linux/errno-generic.zig index 741f76fdee..53b32db6fc 100644 --- a/lib/std/os/bits/linux/errno-generic.zig +++ b/lib/std/os/bits/linux/errno-generic.zig @@ -368,6 +368,33 @@ pub const ENOMEDIUM = 123; /// Wrong medium type pub const EMEDIUMTYPE = 124; +/// Operation canceled +pub const ECANCELED = 125; + +/// Required key not available +pub const ENOKEY = 126; + +/// Key has expired +pub const EKEYEXPIRED = 127; + +/// Key has been revoked +pub const EKEYREVOKED = 128; + +/// Key was rejected by service +pub const EKEYREJECTED = 129; + +// for robust mutexes +/// Owner died +pub const EOWNERDEAD = 130; +/// State not recoverable +pub const ENOTRECOVERABLE = 131; + +/// Operation not possible due to RF-kill +pub const ERFKILL = 132; + +/// Memory page has hardware error +pub const EHWPOISON = 133; + // nameserver query return codes /// DNS server returned answer with no data From 1ef6f068f57d1e0075c695149494420a4e387c7e Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Mon, 30 Mar 2020 11:55:21 +0200 Subject: [PATCH 13/89] compiler-rt: Implement all the shift builtins * Unify all the code paths with a generic function * Add some EABI aliases Closes #4853 --- lib/std/special/compiler_rt.zig | 13 +- lib/std/special/compiler_rt/ashldi3_test.zig | 32 +++++ lib/std/special/compiler_rt/ashlti3.zig | 41 ------ lib/std/special/compiler_rt/ashlti3_test.zig | 4 +- lib/std/special/compiler_rt/ashrdi3_test.zig | 55 ++++++++ lib/std/special/compiler_rt/ashrti3.zig | 42 ------ lib/std/special/compiler_rt/ashrti3_test.zig | 6 +- lib/std/special/compiler_rt/lshrdi3_test.zig | 55 ++++++++ lib/std/special/compiler_rt/lshrti3.zig | 41 ------ lib/std/special/compiler_rt/lshrti3_test.zig | 4 +- lib/std/special/compiler_rt/shift.zig | 130 +++++++++++++++++++ 11 files changed, 288 insertions(+), 135 deletions(-) create mode 100644 lib/std/special/compiler_rt/ashldi3_test.zig delete mode 100644 lib/std/special/compiler_rt/ashlti3.zig create mode 100644 lib/std/special/compiler_rt/ashrdi3_test.zig delete mode 100644 lib/std/special/compiler_rt/ashrti3.zig create mode 100644 lib/std/special/compiler_rt/lshrdi3_test.zig delete mode 100644 lib/std/special/compiler_rt/lshrti3.zig create mode 100644 lib/std/special/compiler_rt/shift.zig diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index f0cf85a7a9..1f68d928c2 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -69,9 +69,12 @@ comptime { @export(@import("compiler_rt/divdf3.zig").__divdf3, .{ .name = "__divdf3", .linkage = linkage }); @export(@import("compiler_rt/divtf3.zig").__divtf3, .{ .name = "__divtf3", .linkage = linkage }); - @export(@import("compiler_rt/ashlti3.zig").__ashlti3, .{ .name = "__ashlti3", .linkage = linkage }); - @export(@import("compiler_rt/lshrti3.zig").__lshrti3, .{ .name = "__lshrti3", .linkage = linkage }); - @export(@import("compiler_rt/ashrti3.zig").__ashrti3, .{ .name = "__ashrti3", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__ashldi3, .{ .name = "__ashldi3", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__ashlti3, .{ .name = "__ashlti3", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__ashrdi3, .{ .name = "__ashrdi3", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__ashrti3, .{ .name = "__ashrti3", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__lshrdi3, .{ .name = "__lshrdi3", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__lshrti3, .{ .name = "__lshrti3", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsidf, .{ .name = "__floatsidf", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsisf, .{ .name = "__floatsisf", .linkage = linkage }); @@ -229,6 +232,10 @@ comptime { @export(@import("compiler_rt/divsf3.zig").__aeabi_fdiv, .{ .name = "__aeabi_fdiv", .linkage = linkage }); @export(@import("compiler_rt/divdf3.zig").__aeabi_ddiv, .{ .name = "__aeabi_ddiv", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__aeabi_llsl, .{ .name = "__aeabi_llsl", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__aeabi_lasr, .{ .name = "__aeabi_lasr", .linkage = linkage }); + @export(@import("compiler_rt/shift.zig").__aeabi_llsr, .{ .name = "__aeabi_llsr", .linkage = linkage }); + @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpeq, .{ .name = "__aeabi_fcmpeq", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmplt, .{ .name = "__aeabi_fcmplt", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmple, .{ .name = "__aeabi_fcmple", .linkage = linkage }); diff --git a/lib/std/special/compiler_rt/ashldi3_test.zig b/lib/std/special/compiler_rt/ashldi3_test.zig new file mode 100644 index 0000000000..547c315b24 --- /dev/null +++ b/lib/std/special/compiler_rt/ashldi3_test.zig @@ -0,0 +1,32 @@ +const __ashldi3 = @import("shift.zig").__ashldi3; +const testing = @import("std").testing; + +fn test__ashldi3(a: i64, b: i32, expected: u64) void { + const x = __ashldi3(a, b); + testing.expectEqual(@bitCast(i64, expected), x); +} + +test "ashldi3" { + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 0, 0x123456789ABCDEF); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 1, 0x2468ACF13579BDE); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 2, 0x48D159E26AF37BC); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 3, 0x91A2B3C4D5E6F78); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 4, 0x123456789ABCDEF0); + + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 28, 0x789ABCDEF0000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 29, 0xF13579BDE0000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 30, 0xE26AF37BC0000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 31, 0xC4D5E6F780000000); + + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 32, 0x89ABCDEF00000000); + + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 33, 0x13579BDE00000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 34, 0x26AF37BC00000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 35, 0x4D5E6F7800000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 36, 0x9ABCDEF000000000); + + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 60, 0xF000000000000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 61, 0xE000000000000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 62, 0xC000000000000000); + test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 63, 0x8000000000000000); +} diff --git a/lib/std/special/compiler_rt/ashlti3.zig b/lib/std/special/compiler_rt/ashlti3.zig deleted file mode 100644 index e3bc60bbb9..0000000000 --- a/lib/std/special/compiler_rt/ashlti3.zig +++ /dev/null @@ -1,41 +0,0 @@ -const builtin = @import("builtin"); -const compiler_rt = @import("../compiler_rt.zig"); - -pub fn __ashlti3(a: i128, b: i32) callconv(.C) i128 { - var input = twords{ .all = a }; - var result: twords = undefined; - - if (b > 63) { - // 64 <= b < 128 - result.s.low = 0; - result.s.high = input.s.low << @intCast(u6, b - 64); - } else { - // 0 <= b < 64 - if (b == 0) return a; - result.s.low = input.s.low << @intCast(u6, b); - result.s.high = input.s.low >> @intCast(u6, 64 - b); - result.s.high |= input.s.high << @intCast(u6, b); - } - - return result.all; -} - -const twords = extern union { - all: i128, - s: S, - - const S = if (builtin.endian == .Little) - struct { - low: u64, - high: u64, - } - else - struct { - high: u64, - low: u64, - }; -}; - -test "import ashlti3" { - _ = @import("ashlti3_test.zig"); -} diff --git a/lib/std/special/compiler_rt/ashlti3_test.zig b/lib/std/special/compiler_rt/ashlti3_test.zig index 4ba21c138e..a4510f52d7 100644 --- a/lib/std/special/compiler_rt/ashlti3_test.zig +++ b/lib/std/special/compiler_rt/ashlti3_test.zig @@ -1,9 +1,9 @@ -const __ashlti3 = @import("ashlti3.zig").__ashlti3; +const __ashlti3 = @import("shift.zig").__ashlti3; const testing = @import("std").testing; fn test__ashlti3(a: i128, b: i32, expected: i128) void { const x = __ashlti3(a, b); - testing.expect(x == expected); + testing.expectEqual(expected, x); } test "ashlti3" { diff --git a/lib/std/special/compiler_rt/ashrdi3_test.zig b/lib/std/special/compiler_rt/ashrdi3_test.zig new file mode 100644 index 0000000000..3ba30edbfe --- /dev/null +++ b/lib/std/special/compiler_rt/ashrdi3_test.zig @@ -0,0 +1,55 @@ +const __ashrdi3 = @import("shift.zig").__ashrdi3; +const testing = @import("std").testing; + +fn test__ashrdi3(a: i64, b: i32, expected: u64) void { + const x = __ashrdi3(a, b); + testing.expectEqual(@bitCast(i64, expected), x); +} + +test "ashrdi3" { + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 0, 0x123456789ABCDEF); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 1, 0x91A2B3C4D5E6F7); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 2, 0x48D159E26AF37B); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 3, 0x2468ACF13579BD); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 4, 0x123456789ABCDE); + + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 28, 0x12345678); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 29, 0x91A2B3C); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 30, 0x48D159E); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 31, 0x2468ACF); + + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 32, 0x1234567); + + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 33, 0x91A2B3); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 34, 0x48D159); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 35, 0x2468AC); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 36, 0x123456); + + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 60, 0); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 61, 0); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 62, 0); + test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 63, 0); + + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 0, 0xFEDCBA9876543210); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 1, 0xFF6E5D4C3B2A1908); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 2, 0xFFB72EA61D950C84); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 3, 0xFFDB97530ECA8642); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 4, 0xFFEDCBA987654321); + + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 28, 0xFFFFFFFFEDCBA987); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 29, 0xFFFFFFFFF6E5D4C3); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 30, 0xFFFFFFFFFB72EA61); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 31, 0xFFFFFFFFFDB97530); + + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 32, 0xFFFFFFFFFEDCBA98); + + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 33, 0xFFFFFFFFFF6E5D4C); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 34, 0xFFFFFFFFFFB72EA6); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 35, 0xFFFFFFFFFFDB9753); + test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 36, 0xFFFFFFFFFFEDCBA9); + + test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 60, 0xFFFFFFFFFFFFFFFA); + test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 61, 0xFFFFFFFFFFFFFFFD); + test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 62, 0xFFFFFFFFFFFFFFFE); + test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 63, 0xFFFFFFFFFFFFFFFF); +} diff --git a/lib/std/special/compiler_rt/ashrti3.zig b/lib/std/special/compiler_rt/ashrti3.zig deleted file mode 100644 index 1cbe24fdeb..0000000000 --- a/lib/std/special/compiler_rt/ashrti3.zig +++ /dev/null @@ -1,42 +0,0 @@ -const builtin = @import("builtin"); -const compiler_rt = @import("../compiler_rt.zig"); - -pub fn __ashrti3(a: i128, b: i32) callconv(.C) i128 { - var input = twords{ .all = a }; - var result: twords = undefined; - - if (b > 63) { - // 64 <= b < 128 - result.s.low = input.s.high >> @intCast(u6, b - 64); - result.s.high = input.s.high >> 63; - } else { - // 0 <= b < 64 - if (b == 0) return a; - result.s.low = input.s.high << @intCast(u6, 64 - b); - // Avoid sign-extension here - result.s.low |= @bitCast(i64, @bitCast(u64, input.s.low) >> @intCast(u6, b)); - result.s.high = input.s.high >> @intCast(u6, b); - } - - return result.all; -} - -const twords = extern union { - all: i128, - s: S, - - const S = if (builtin.endian == .Little) - struct { - low: i64, - high: i64, - } - else - struct { - high: i64, - low: i64, - }; -}; - -test "import ashrti3" { - _ = @import("ashrti3_test.zig"); -} diff --git a/lib/std/special/compiler_rt/ashrti3_test.zig b/lib/std/special/compiler_rt/ashrti3_test.zig index 6a7565e557..43d5d11910 100644 --- a/lib/std/special/compiler_rt/ashrti3_test.zig +++ b/lib/std/special/compiler_rt/ashrti3_test.zig @@ -1,11 +1,9 @@ -const __ashrti3 = @import("ashrti3.zig").__ashrti3; +const __ashrti3 = @import("shift.zig").__ashrti3; const testing = @import("std").testing; fn test__ashrti3(a: i128, b: i32, expected: i128) void { const x = __ashrti3(a, b); - // @import("std").debug.warn("got 0x{x}\nexp 0x{x}\n", .{@truncate(u64, - // @bitCast(u128, x) >> 64), @truncate(u64, @bitCast(u128, expected)) >> 64}); - testing.expect(x == expected); + testing.expectEqual(expected, x); } test "ashrti3" { diff --git a/lib/std/special/compiler_rt/lshrdi3_test.zig b/lib/std/special/compiler_rt/lshrdi3_test.zig new file mode 100644 index 0000000000..906d428d1e --- /dev/null +++ b/lib/std/special/compiler_rt/lshrdi3_test.zig @@ -0,0 +1,55 @@ +const __lshrdi3 = @import("shift.zig").__lshrdi3; +const testing = @import("std").testing; + +fn test__lshrdi3(a: i64, b: i32, expected: u64) void { + const x = __lshrdi3(a, b); + testing.expectEqual(@bitCast(i64, expected), x); +} + +test "lshrdi3" { + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 0, 0x123456789ABCDEF); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 1, 0x91A2B3C4D5E6F7); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 2, 0x48D159E26AF37B); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 3, 0x2468ACF13579BD); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 4, 0x123456789ABCDE); + + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 28, 0x12345678); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 29, 0x91A2B3C); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 30, 0x48D159E); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 31, 0x2468ACF); + + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 32, 0x1234567); + + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 33, 0x91A2B3); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 34, 0x48D159); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 35, 0x2468AC); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 36, 0x123456); + + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 60, 0); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 61, 0); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 62, 0); + test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 63, 0); + + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 0, 0xFEDCBA9876543210); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 1, 0x7F6E5D4C3B2A1908); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 2, 0x3FB72EA61D950C84); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 3, 0x1FDB97530ECA8642); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 4, 0xFEDCBA987654321); + + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 28, 0xFEDCBA987); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 29, 0x7F6E5D4C3); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 30, 0x3FB72EA61); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 31, 0x1FDB97530); + + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 32, 0xFEDCBA98); + + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 33, 0x7F6E5D4C); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 34, 0x3FB72EA6); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 35, 0x1FDB9753); + test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 36, 0xFEDCBA9); + + test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 60, 0xA); + test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 61, 0x5); + test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 62, 0x2); + test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 63, 0x1); +} diff --git a/lib/std/special/compiler_rt/lshrti3.zig b/lib/std/special/compiler_rt/lshrti3.zig deleted file mode 100644 index e1c2bb5bd3..0000000000 --- a/lib/std/special/compiler_rt/lshrti3.zig +++ /dev/null @@ -1,41 +0,0 @@ -const builtin = @import("builtin"); -const compiler_rt = @import("../compiler_rt.zig"); - -pub fn __lshrti3(a: i128, b: i32) callconv(.C) i128 { - var input = twords{ .all = a }; - var result: twords = undefined; - - if (b > 63) { - // 64 <= b < 128 - result.s.low = input.s.high >> @intCast(u6, b - 64); - result.s.high = 0; - } else { - // 0 <= b < 64 - if (b == 0) return a; - result.s.low = input.s.high << @intCast(u6, 64 - b); - result.s.low |= input.s.low >> @intCast(u6, b); - result.s.high = input.s.high >> @intCast(u6, b); - } - - return result.all; -} - -const twords = extern union { - all: i128, - s: S, - - const S = if (builtin.endian == .Little) - struct { - low: u64, - high: u64, - } - else - struct { - high: u64, - low: u64, - }; -}; - -test "import lshrti3" { - _ = @import("lshrti3_test.zig"); -} diff --git a/lib/std/special/compiler_rt/lshrti3_test.zig b/lib/std/special/compiler_rt/lshrti3_test.zig index 60f83d816e..c0aa191a6f 100644 --- a/lib/std/special/compiler_rt/lshrti3_test.zig +++ b/lib/std/special/compiler_rt/lshrti3_test.zig @@ -1,9 +1,9 @@ -const __lshrti3 = @import("lshrti3.zig").__lshrti3; +const __lshrti3 = @import("shift.zig").__lshrti3; const testing = @import("std").testing; fn test__lshrti3(a: i128, b: i32, expected: i128) void { const x = __lshrti3(a, b); - testing.expect(x == expected); + testing.expectEqual(expected, x); } test "lshrti3" { diff --git a/lib/std/special/compiler_rt/shift.zig b/lib/std/special/compiler_rt/shift.zig new file mode 100644 index 0000000000..e21042e14e --- /dev/null +++ b/lib/std/special/compiler_rt/shift.zig @@ -0,0 +1,130 @@ +const std = @import("std"); +const builtin = std.builtin; +const Log2Int = std.math.Log2Int; + +fn Dwords(comptime T: type, comptime signed_half: bool) type { + return extern union { + pub const HalfTU = std.meta.IntType(false, @divExact(T.bit_count, 2)); + pub const HalfTS = std.meta.IntType(true, @divExact(T.bit_count, 2)); + pub const HalfT = if (signed_half) HalfTS else HalfTU; + + all: T, + s: if (builtin.endian == .Little) + struct { low: HalfT, high: HalfT } + else + struct { high: HalfT, low: HalfT }, + }; +} + +// Arithmetic shift left +// Precondition: 0 <= b < bits_in_dword +pub fn ashlXi3(comptime T: type, a: T, b: i32) T { + const dwords = Dwords(T, false); + const S = Log2Int(dwords.HalfT); + + const input = dwords{ .all = a }; + var output: dwords = undefined; + + if (b >= dwords.HalfT.bit_count) { + output.s.low = 0; + output.s.high = input.s.low << @intCast(S, b - dwords.HalfT.bit_count); + } else if (b == 0) { + return a; + } else { + output.s.low = input.s.low << @intCast(S, b); + output.s.high = input.s.high << @intCast(S, b); + output.s.high |= input.s.low >> @intCast(S, dwords.HalfT.bit_count - b); + } + + return output.all; +} + +// Arithmetic shift right +// Precondition: 0 <= b < T.bit_count +pub fn ashrXi3(comptime T: type, a: T, b: i32) T { + const dwords = Dwords(T, true); + const S = Log2Int(dwords.HalfT); + + const input = dwords{ .all = a }; + var output: dwords = undefined; + + if (b >= dwords.HalfT.bit_count) { + output.s.high = input.s.high >> (dwords.HalfT.bit_count - 1); + output.s.low = input.s.high >> @intCast(S, b - dwords.HalfT.bit_count); + } else if (b == 0) { + return a; + } else { + output.s.high = input.s.high >> @intCast(S, b); + output.s.low = input.s.high << @intCast(S, dwords.HalfT.bit_count - b); + // Avoid sign-extension here + output.s.low |= @bitCast( + dwords.HalfT, + @bitCast(dwords.HalfTU, input.s.low) >> @intCast(S, b), + ); + } + + return output.all; +} + +// Logical shift right +// Precondition: 0 <= b < T.bit_count +pub fn lshrXi3(comptime T: type, a: T, b: i32) T { + const dwords = Dwords(T, false); + const S = Log2Int(dwords.HalfT); + + const input = dwords{ .all = a }; + var output: dwords = undefined; + + if (b >= dwords.HalfT.bit_count) { + output.s.high = 0; + output.s.low = input.s.high >> @intCast(S, b - dwords.HalfT.bit_count); + } else if (b == 0) { + return a; + } else { + output.s.high = input.s.high >> @intCast(S, b); + output.s.low = input.s.high << @intCast(S, dwords.HalfT.bit_count - b); + output.s.low |= input.s.low >> @intCast(S, b); + } + + return output.all; +} + +pub fn __ashldi3(a: i64, b: i32) callconv(.C) i64 { + return @call(.{ .modifier = .always_inline }, ashlXi3, .{ i64, a, b }); +} +pub fn __ashlti3(a: i128, b: i32) callconv(.C) i128 { + return @call(.{ .modifier = .always_inline }, ashlXi3, .{ i128, a, b }); +} +pub fn __ashrdi3(a: i64, b: i32) callconv(.C) i64 { + return @call(.{ .modifier = .always_inline }, ashrXi3, .{ i64, a, b }); +} +pub fn __ashrti3(a: i128, b: i32) callconv(.C) i128 { + return @call(.{ .modifier = .always_inline }, ashrXi3, .{ i128, a, b }); +} +pub fn __lshrdi3(a: i64, b: i32) callconv(.C) i64 { + return @call(.{ .modifier = .always_inline }, lshrXi3, .{ i64, a, b }); +} +pub fn __lshrti3(a: i128, b: i32) callconv(.C) i128 { + return @call(.{ .modifier = .always_inline }, lshrXi3, .{ i128, a, b }); +} + +pub fn __aeabi_llsl(a: i64, b: i32) callconv(.AAPCS) i64 { + return __ashldi3(a, b); +} +pub fn __aeabi_lasr(a: i64, b: i32) callconv(.AAPCS) i64 { + return __ashrdi3(a, b); +} +pub fn __aeabi_llsr(a: i64, b: i32) callconv(.AAPCS) i64 { + return __lshrdi3(a, b); +} + +test "" { + _ = @import("ashrdi3_test.zig"); + _ = @import("ashrti3_test.zig"); + + _ = @import("ashldi3_test.zig"); + _ = @import("ashlti3_test.zig"); + + _ = @import("lshrdi3_test.zig"); + _ = @import("lshrti3_test.zig"); +} From 607892a30d88df492551b6aa301b65ba7d63ccd9 Mon Sep 17 00:00:00 2001 From: Brian Cain Date: Sun, 29 Mar 2020 23:53:02 -0500 Subject: [PATCH 14/89] Create an "LLD_LIBDIRS" var to override lld loc --- cmake/Findlld.cmake | 1 + 1 file changed, 1 insertion(+) diff --git a/cmake/Findlld.cmake b/cmake/Findlld.cmake index 4c69d51b24..e27605a54d 100644 --- a/cmake/Findlld.cmake +++ b/cmake/Findlld.cmake @@ -24,6 +24,7 @@ else() string(TOUPPER ${_libname_} _prettylibname_) find_library(LLD_${_prettylibname_}_LIB NAMES ${_libname_} PATHS + ${LLD_LIBDIRS} /usr/lib/llvm-10/lib /usr/local/llvm100/lib /mingw64/lib From 8cad45349510b2995a49fc907bdc3c8bf86aa21b Mon Sep 17 00:00:00 2001 From: daurnimator Date: Mon, 30 Mar 2020 23:06:59 +1100 Subject: [PATCH 15/89] std: fix compile error since WinsockError was changed --- lib/std/os/windows.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index 813a77c275..b65d80fb7a 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -893,7 +893,7 @@ pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA { var wsadata: ws2_32.WSADATA = undefined; return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) { 0 => wsadata, - else => |err| unexpectedWSAError(@intToEnum(WinsockError, err)), + else => |err| unexpectedWSAError(@intToEnum(ws2_32.WinsockError, @intCast(u16, err))), }; } @@ -1292,7 +1292,7 @@ pub fn unexpectedError(err: Win32Error) std.os.UnexpectedError { return error.Unexpected; } -pub fn unexpectedWSAError(err: WinsockError) std.os.UnexpectedError { +pub fn unexpectedWSAError(err: ws2_32.WinsockError) std.os.UnexpectedError { return unexpectedError(@intToEnum(Win32Error, @enumToInt(err))); } From c1cc1ebc35f7a56669db2f88b6d4ff8f1603ec59 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Mon, 30 Mar 2020 13:27:19 +0200 Subject: [PATCH 16/89] ir: Avoid constant-folding ptr to sentinels Constant-folding the pointers to the expected sentinel value have some big problems: it hides the real content of the array, makes the pointer to the sentinel point to a completely different memory region and treats it like a const value even when the underlying array is mutable. Fixes #4840 --- src/ir.cpp | 9 ++------- test/stage1/behavior/array.zig | 19 ++++++++++++++----- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index 4d5cfccabe..3a5c9737ee 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -20880,13 +20880,8 @@ static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemP if (instr_is_comptime(casted_elem_index)) { uint64_t index = bigint_as_u64(&casted_elem_index->value->data.x_bigint); if (array_type->id == ZigTypeIdArray) { - uint64_t array_len = array_type->data.array.len; - if (index == array_len && array_type->data.array.sentinel != nullptr) { - ZigType *elem_type = array_type->data.array.child_type; - IrInstGen *sentinel_elem = ir_const(ira, &elem_ptr_instruction->base.base, elem_type); - copy_const_val(ira->codegen, sentinel_elem->value, array_type->data.array.sentinel); - return ir_get_ref(ira, &elem_ptr_instruction->base.base, sentinel_elem, true, false); - } + uint64_t array_len = array_type->data.array.len + + (array_type->data.array.sentinel != nullptr); if (index >= array_len) { ir_add_error_node(ira, elem_ptr_instruction->base.base.source_node, buf_sprintf("index %" ZIG_PRI_u64 " outside array of size %" ZIG_PRI_u64, diff --git a/test/stage1/behavior/array.zig b/test/stage1/behavior/array.zig index 792c0e70d1..d5ca44f0a2 100644 --- a/test/stage1/behavior/array.zig +++ b/test/stage1/behavior/array.zig @@ -31,14 +31,23 @@ fn getArrayLen(a: []const u32) usize { test "array with sentinels" { const S = struct { fn doTheTest(is_ct: bool) void { - var zero_sized: [0:0xde]u8 = [_:0xde]u8{}; - expectEqual(@as(u8, 0xde), zero_sized[0]); - // Disabled at runtime because of - // https://github.com/ziglang/zig/issues/4372 if (is_ct) { + var zero_sized: [0:0xde]u8 = [_:0xde]u8{}; + // Disabled at runtime because of + // https://github.com/ziglang/zig/issues/4372 + expectEqual(@as(u8, 0xde), zero_sized[0]); var reinterpreted = @ptrCast(*[1]u8, &zero_sized); expectEqual(@as(u8, 0xde), reinterpreted[0]); } + var arr: [3:0x55]u8 = undefined; + // Make sure the sentinel pointer is pointing after the last element + if (!is_ct) { + const sentinel_ptr = @ptrToInt(&arr[3]); + const last_elem_ptr = @ptrToInt(&arr[2]); + expectEqual(@as(usize, 1), sentinel_ptr - last_elem_ptr); + } + // Make sure the sentinel is writeable + arr[3] = 0x55; } }; @@ -372,7 +381,7 @@ test "access the null element of a null terminated array" { const S = struct { fn doTheTest() void { var array: [4:0]u8 = .{ 'a', 'o', 'e', 'u' }; - comptime expect(array[4] == 0); + expect(array[4] == 0); var len: usize = 4; expect(array[len] == 0); } From 3be720a729e20720a033f2cf1958311a0112d1f4 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Mon, 30 Mar 2020 21:56:09 +1100 Subject: [PATCH 17/89] std: mem span functions can take an optional pointer --- lib/std/mem.zig | 52 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 14 deletions(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index fa2794160b..7fd94c227b 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -512,36 +512,54 @@ pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T { /// the constness of the input type. `[*c]` pointers are assumed to be 0-terminated, /// and assumed to not allow null. pub fn Span(comptime T: type) type { - var ptr_info = @typeInfo(T).Pointer; - switch (ptr_info.size) { - .One => switch (@typeInfo(ptr_info.child)) { - .Array => |info| { - ptr_info.child = info.child; - ptr_info.sentinel = info.sentinel; - }, - else => @compileError("invalid type given to std.mem.Span"), + switch(@typeInfo(T)) { + .Optional => |optional_info| { + return ?Span(optional_info.child); }, - .C => { - ptr_info.sentinel = 0; - ptr_info.is_allowzero = false; + .Pointer => |ptr_info| { + var new_ptr_info = ptr_info; + switch (ptr_info.size) { + .One => switch (@typeInfo(ptr_info.child)) { + .Array => |info| { + new_ptr_info.child = info.child; + new_ptr_info.sentinel = info.sentinel; + }, + else => @compileError("invalid type given to std.mem.Span"), + }, + .C => { + new_ptr_info.sentinel = 0; + new_ptr_info.is_allowzero = false; + }, + .Many, .Slice => {}, + } + new_ptr_info.size = .Slice; + return @Type(std.builtin.TypeInfo{ .Pointer = new_ptr_info }); }, - .Many, .Slice => {}, + else => @compileError("invalid type given to std.mem.Span"), } - ptr_info.size = .Slice; - return @Type(std.builtin.TypeInfo{ .Pointer = ptr_info }); } test "Span" { testing.expect(Span(*[5]u16) == []u16); + testing.expect(Span(?*[5]u16) == ?[]u16); testing.expect(Span(*const [5]u16) == []const u16); + testing.expect(Span(?*const [5]u16) == ?[]const u16); testing.expect(Span([]u16) == []u16); + testing.expect(Span(?[]u16) == ?[]u16); testing.expect(Span([]const u8) == []const u8); + testing.expect(Span(?[]const u8) == ?[]const u8); testing.expect(Span([:1]u16) == [:1]u16); + testing.expect(Span(?[:1]u16) == ?[:1]u16); testing.expect(Span([:1]const u8) == [:1]const u8); + testing.expect(Span(?[:1]const u8) == ?[:1]const u8); testing.expect(Span([*:1]u16) == [:1]u16); + testing.expect(Span(?[*:1]u16) == ?[:1]u16); testing.expect(Span([*:1]const u8) == [:1]const u8); + testing.expect(Span(?[*:1]const u8) == ?[:1]const u8); testing.expect(Span([*c]u16) == [:0]u16); + testing.expect(Span(?[*c]u16) == ?[:0]u16); testing.expect(Span([*c]const u8) == [:0]const u8); + testing.expect(Span(?[*c]const u8) == ?[:0]const u8); } /// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and @@ -553,6 +571,9 @@ test "Span" { /// length value is used instead of the sentinel. pub fn span(ptr: var) Span(@TypeOf(ptr)) { const Result = Span(@TypeOf(ptr)); + if (@typeInfo(@TypeOf(ptr)) == .Optional and ptr == null) { + return null; + } const l = len(ptr); if (@typeInfo(Result).Pointer.sentinel) |s| { return ptr[0..l :s]; @@ -573,6 +594,9 @@ test "span" { /// rather than using the length. pub fn spanZ(ptr: var) Span(@TypeOf(ptr)) { const Result = Span(@TypeOf(ptr)); + if (@typeInfo(@TypeOf(ptr)) == .Optional and ptr == null) { + return null; + } const l = lenZ(ptr); if (@typeInfo(Result).Pointer.sentinel) |s| { return ptr[0..l :s]; From ef419dd72d3fc9ec1454099367bd8d43f1b5037b Mon Sep 17 00:00:00 2001 From: Sebastian <15335529+Sobeston@users.noreply.github.com> Date: Mon, 30 Mar 2020 02:57:50 +0100 Subject: [PATCH 18/89] mem.zeroes .Array improvements Before (when given an array with many elements): ``` zig\std\mem.zig:345:13: error: evaluation exceeded 1000 backwards branches for (array) |*element| { ^ ``` related to https://github.com/ziglang/zig/issues/4847#issuecomment-605721461 --- lib/std/mem.zig | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 7fd94c227b..446683abdb 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -341,11 +341,7 @@ pub fn zeroes(comptime T: type) T { } }, .Array => |info| { - var array: T = undefined; - for (array) |*element| { - element.* = zeroes(info.child); - } - return array; + return [_]info.child{zeroes(info.child)} ** info.len; }, .Vector, .ErrorUnion, From b980568c810fda4c014da42be8e5108b4cbadb7c Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Mar 2020 13:01:53 -0400 Subject: [PATCH 19/89] add peer type resolution for mixed-const []T and *[N]T closes #4766 This commit also fixes the implementation of some utility functions for adjusting properties of pointer types. Previously these functions would incorrectly drop vector, sentinel, and inference metadata. --- src/ir.cpp | 78 +++++++++++++++++++++++++++-------- test/stage1/behavior/cast.zig | 15 +++++++ 2 files changed, 76 insertions(+), 17 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index 3a5c9737ee..b9a14d0fe1 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -231,6 +231,7 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op); static IrInstSrc *ir_lval_wrap(IrBuilderSrc *irb, Scope *scope, IrInstSrc *value, LVal lval, ResultLoc *result_loc); static IrInstSrc *ir_expr_wrap(IrBuilderSrc *irb, Scope *scope, IrInstSrc *inst, ResultLoc *result_loc); static ZigType *adjust_ptr_align(CodeGen *g, ZigType *ptr_type, uint32_t new_align); +static ZigType *adjust_ptr_const(CodeGen *g, ZigType *ptr_type, bool is_const); static ZigType *adjust_slice_align(CodeGen *g, ZigType *slice_type, uint32_t new_align); static Error buf_read_value_bytes(IrAnalyze *ira, CodeGen *codegen, AstNode *source_node, uint8_t *buf, ZigValue *val); static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ZigValue *val); @@ -11844,6 +11845,7 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT bool any_are_null = (prev_inst->value->type->id == ZigTypeIdNull); bool convert_to_const_slice = false; + bool make_the_slice_const = false; for (; i < instruction_count; i += 1) { IrInstGen *cur_inst = instructions[i]; ZigType *cur_type = cur_inst->value->type; @@ -12357,12 +12359,12 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT ZigType *slice_type = (prev_type->id == ZigTypeIdErrorUnion) ? prev_type->data.error_union.payload_type : prev_type; ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry; - if ((slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 || - !cur_type->data.pointer.is_const) && - types_match_const_cast_only(ira, - slice_ptr_type->data.pointer.child_type, + if (types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type, array_type->data.array.child_type, source_node, false).id == ConstCastResultIdOk) { + bool const_ok = (slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 || + !cur_type->data.pointer.is_const); + if (!const_ok) make_the_slice_const = true; convert_to_const_slice = false; continue; } @@ -12391,12 +12393,12 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT break; } ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry; - if ((slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 || - !prev_type->data.pointer.is_const) && - types_match_const_cast_only(ira, - slice_ptr_type->data.pointer.child_type, + if (types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type, array_type->data.array.child_type, source_node, false).id == ConstCastResultIdOk) { + bool const_ok = (slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 || + !prev_type->data.pointer.is_const); + if (!const_ok) make_the_slice_const = true; prev_inst = cur_inst; convert_to_const_slice = false; continue; @@ -12408,8 +12410,6 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT cur_type->data.pointer.child_type->id == ZigTypeIdArray && prev_type->id == ZigTypeIdPointer && prev_type->data.pointer.ptr_len == PtrLenSingle && prev_type->data.pointer.child_type->id == ZigTypeIdArray && - (cur_type->data.pointer.is_const || !prev_type->data.pointer.is_const || - prev_type->data.pointer.child_type->data.array.len == 0) && ( prev_type->data.pointer.child_type->data.array.sentinel == nullptr || (cur_type->data.pointer.child_type->data.array.sentinel != nullptr && @@ -12421,6 +12421,9 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT prev_type->data.pointer.child_type->data.array.child_type, source_node, !cur_type->data.pointer.is_const).id == ConstCastResultIdOk) { + bool const_ok = (cur_type->data.pointer.is_const || !prev_type->data.pointer.is_const || + prev_type->data.pointer.child_type->data.array.len == 0); + if (!const_ok) make_the_slice_const = true; prev_inst = cur_inst; convert_to_const_slice = true; continue; @@ -12429,8 +12432,6 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT prev_type->data.pointer.child_type->id == ZigTypeIdArray && cur_type->id == ZigTypeIdPointer && cur_type->data.pointer.ptr_len == PtrLenSingle && cur_type->data.pointer.child_type->id == ZigTypeIdArray && - (prev_type->data.pointer.is_const || !cur_type->data.pointer.is_const || - cur_type->data.pointer.child_type->data.array.len == 0) && ( cur_type->data.pointer.child_type->data.array.sentinel == nullptr || (prev_type->data.pointer.child_type->data.array.sentinel != nullptr && @@ -12442,6 +12443,9 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT cur_type->data.pointer.child_type->data.array.child_type, source_node, !prev_type->data.pointer.is_const).id == ConstCastResultIdOk) { + bool const_ok = (prev_type->data.pointer.is_const || !cur_type->data.pointer.is_const || + cur_type->data.pointer.child_type->data.array.len == 0); + if (!const_ok) make_the_slice_const = true; convert_to_const_slice = true; continue; } @@ -12486,7 +12490,7 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT src_assert(array_type->id == ZigTypeIdArray, source_node); ZigType *ptr_type = get_pointer_to_type_extra2( ira->codegen, array_type->data.array.child_type, - prev_inst->value->type->data.pointer.is_const, false, + prev_inst->value->type->data.pointer.is_const || make_the_slice_const, false, PtrLenUnknown, 0, 0, 0, false, VECTOR_INDEX_NONE, nullptr, array_type->data.array.sentinel); @@ -12537,6 +12541,26 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT return ira->codegen->builtin_types.entry_invalid; return get_optional_type(ira->codegen, prev_inst->value->type); } + } else if (make_the_slice_const) { + ZigType *slice_type; + if (prev_inst->value->type->id == ZigTypeIdErrorUnion) { + slice_type = prev_inst->value->type->data.error_union.payload_type; + } else if (is_slice(prev_inst->value->type)) { + slice_type = prev_inst->value->type; + } else { + zig_unreachable(); + } + ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry; + ZigType *adjusted_ptr_type = adjust_ptr_const(ira->codegen, slice_ptr_type, make_the_slice_const); + ZigType *adjusted_slice_type = get_slice_type(ira->codegen, adjusted_ptr_type); + if (prev_inst->value->type->id == ZigTypeIdErrorUnion) { + return get_error_union_type(ira->codegen, prev_inst->value->type->data.error_union.err_set_type, + adjusted_slice_type); + } else if (is_slice(prev_inst->value->type)) { + return adjusted_slice_type; + } else { + zig_unreachable(); + } } else { return prev_inst->value->type; } @@ -20708,24 +20732,44 @@ static ZigType *adjust_slice_align(CodeGen *g, ZigType *slice_type, uint32_t new static ZigType *adjust_ptr_len(CodeGen *g, ZigType *ptr_type, PtrLen ptr_len) { assert(ptr_type->id == ZigTypeIdPointer); - return get_pointer_to_type_extra(g, + return get_pointer_to_type_extra2(g, ptr_type->data.pointer.child_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, ptr_len, ptr_type->data.pointer.explicit_alignment, ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes, - ptr_type->data.pointer.allow_zero); + ptr_type->data.pointer.allow_zero, + ptr_type->data.pointer.vector_index, + ptr_type->data.pointer.inferred_struct_field, + ptr_type->data.pointer.sentinel); } static ZigType *adjust_ptr_allow_zero(CodeGen *g, ZigType *ptr_type, bool allow_zero) { assert(ptr_type->id == ZigTypeIdPointer); - return get_pointer_to_type_extra(g, + return get_pointer_to_type_extra2(g, ptr_type->data.pointer.child_type, ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile, ptr_type->data.pointer.ptr_len, ptr_type->data.pointer.explicit_alignment, ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes, - allow_zero); + allow_zero, + ptr_type->data.pointer.vector_index, + ptr_type->data.pointer.inferred_struct_field, + ptr_type->data.pointer.sentinel); +} + +static ZigType *adjust_ptr_const(CodeGen *g, ZigType *ptr_type, bool is_const) { + assert(ptr_type->id == ZigTypeIdPointer); + return get_pointer_to_type_extra2(g, + ptr_type->data.pointer.child_type, + is_const, ptr_type->data.pointer.is_volatile, + ptr_type->data.pointer.ptr_len, + ptr_type->data.pointer.explicit_alignment, + ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes, + ptr_type->data.pointer.allow_zero, + ptr_type->data.pointer.vector_index, + ptr_type->data.pointer.inferred_struct_field, + ptr_type->data.pointer.sentinel); } static Error compute_elem_align(IrAnalyze *ira, ZigType *elem_type, uint32_t base_ptr_align, diff --git a/test/stage1/behavior/cast.zig b/test/stage1/behavior/cast.zig index b7bcb92c44..0d4836a5a2 100644 --- a/test/stage1/behavior/cast.zig +++ b/test/stage1/behavior/cast.zig @@ -790,3 +790,18 @@ test "assignment to optional pointer result loc" { var foo: struct { ptr: ?*c_void } = .{ .ptr = &global_struct }; expect(foo.ptr.? == @ptrCast(*c_void, &global_struct)); } + +test "peer type resolve string lit with sentinel-terminated mutable slice" { + var array: [4:0]u8 = undefined; + array[4] = 0; // TODO remove this when #4372 is solved + var slice: [:0]u8 = array[0..4 :0]; + comptime expect(@TypeOf(slice, "hi") == [:0]const u8); + comptime expect(@TypeOf("hi", slice) == [:0]const u8); +} + +test "peer type resolve array pointers, one of them const" { + var array1: [4]u8 = undefined; + const array2: [5]u8 = undefined; + comptime expect(@TypeOf(&array1, &array2) == []const u8); + comptime expect(@TypeOf(&array2, &array1) == []const u8); +} From 9e7ae062492d4b41564832d37408336e36165e67 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Mar 2020 14:23:22 -0400 Subject: [PATCH 20/89] std lib API deprecations for the upcoming 0.6.0 release See #3811 --- doc/docgen.zig | 69 +++++--- doc/langref.html.in | 4 +- lib/std/atomic/queue.zig | 2 +- lib/std/atomic/stack.zig | 2 +- lib/std/buffer.zig | 33 ++-- lib/std/build.zig | 43 +++-- lib/std/build/emit_raw.zig | 12 +- lib/std/build/run.zig | 6 +- lib/std/build/translate_c.zig | 2 +- lib/std/build/write_file.zig | 4 +- lib/std/c.zig | 1 - lib/std/child_process.zig | 24 +-- lib/std/coff.zig | 4 +- lib/std/crypto/gimli.zig | 2 + lib/std/debug.zig | 15 +- lib/std/dwarf.zig | 14 +- lib/std/dynamic_library.zig | 20 ++- lib/std/event/loop.zig | 4 +- lib/std/fs.zig | 206 +++++++++++++---------- lib/std/fs/file.zig | 2 +- lib/std/fs/get_app_data_dir.zig | 2 +- lib/std/fs/path.zig | 22 ++- lib/std/fs/watch.zig | 2 +- lib/std/heap.zig | 3 +- lib/std/http/headers.zig | 16 +- lib/std/io.zig | 13 +- lib/std/io/buffered_atomic_file.zig | 3 +- lib/std/io/c_out_stream.zig | 2 +- lib/std/io/in_stream.zig | 8 +- lib/std/json.zig | 2 +- lib/std/json/write_stream.zig | 2 +- lib/std/mem.zig | 11 +- lib/std/net.zig | 26 +-- lib/std/os.zig | 140 +++++++++------ lib/std/os/linux/vdso.zig | 6 +- lib/std/os/test.zig | 16 +- lib/std/os/windows.zig | 6 +- lib/std/pdb.zig | 2 +- lib/std/process.zig | 14 +- lib/std/rand.zig | 32 ++-- lib/std/sort.zig | 4 +- lib/std/special/build_runner.zig | 6 +- lib/std/thread.zig | 2 +- lib/std/zig/render.zig | 2 +- lib/std/zig/system.zig | 16 +- src-self-hosted/codegen.zig | 26 +-- src-self-hosted/compilation.zig | 6 +- src-self-hosted/dep_tokenizer.zig | 38 ++--- src-self-hosted/ir.zig | 8 +- src-self-hosted/libc_installation.zig | 14 +- src-self-hosted/link.zig | 18 +- src-self-hosted/main.zig | 14 +- src-self-hosted/stage2.zig | 37 ++-- src-self-hosted/test.zig | 12 +- src-self-hosted/translate_c.zig | 4 +- src-self-hosted/util.zig | 4 +- src-self-hosted/value.zig | 4 +- test/cli.zig | 11 +- test/src/compare_output.zig | 8 +- test/src/run_translated_c.zig | 4 +- test/src/translate_c.zig | 6 +- test/stage1/behavior/cast.zig | 2 +- test/stage1/behavior/pointers.zig | 2 +- test/standalone/brace_expansion/main.zig | 20 +-- test/standalone/guess_number/main.zig | 2 +- test/tests.zig | 46 ++--- tools/merge_anal_dumps.zig | 24 +-- tools/process_headers.zig | 8 +- tools/update_clang_options.zig | 2 +- tools/update_glibc.zig | 14 +- 70 files changed, 597 insertions(+), 564 deletions(-) diff --git a/doc/docgen.zig b/doc/docgen.zig index 32ad0cdc5d..be62cab076 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -1048,7 +1048,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var allocator, &[_][]const u8{ tmp_dir_name, name_plus_ext }, ); - try io.writeFile(tmp_source_file_name, trimmed_raw_source); + try fs.cwd().writeFile(tmp_source_file_name, trimmed_raw_source); switch (code.id) { Code.Id.Exe => |expected_outcome| code_block: { @@ -1106,18 +1106,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var } } if (expected_outcome == .BuildFail) { - const result = try ChildProcess.exec( - allocator, - build_args.toSliceConst(), - null, - &env_map, - max_doc_file_size, - ); + const result = try ChildProcess.exec(.{ + .allocator = allocator, + .argv = build_args.span(), + .env_map = &env_map, + .max_output_bytes = max_doc_file_size, + }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); - for (build_args.toSliceConst()) |arg| + for (build_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1126,7 +1125,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, else => { warn("{}\nThe following command crashed:\n", .{result.stderr}); - for (build_args.toSliceConst()) |arg| + for (build_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1138,7 +1137,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var try out.print("\n{}\n", .{colored_stderr}); break :code_block; } - const exec_result = exec(allocator, &env_map, build_args.toSliceConst()) catch + const exec_result = exec(allocator, &env_map, build_args.span()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{}); if (code.target_str) |triple| { @@ -1167,7 +1166,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var var exited_with_signal = false; const result = if (expected_outcome == ExpectedOutcome.Fail) blk: { - const result = try ChildProcess.exec(allocator, run_args, null, &env_map, max_doc_file_size); + const result = try ChildProcess.exec(.{ + .allocator = allocator, + .argv = run_args, + .env_map = &env_map, + .max_output_bytes = max_doc_file_size, + }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { @@ -1234,7 +1238,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var try test_args.appendSlice(&[_][]const u8{ "-target", triple }); try out.print(" -target {}", .{triple}); } - const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed", .{}); + const result = exec(allocator, &env_map, test_args.span()) catch return parseError(tokenizer, code.source_token, "test failed", .{}); const escaped_stderr = try escapeHtml(allocator, result.stderr); const escaped_stdout = try escapeHtml(allocator, result.stdout); try out.print("\n{}{}\n", .{ escaped_stderr, escaped_stdout }); @@ -1268,12 +1272,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var try out.print(" --release-small", .{}); }, } - const result = try ChildProcess.exec(allocator, test_args.toSliceConst(), null, &env_map, max_doc_file_size); + const result = try ChildProcess.exec(.{ + .allocator = allocator, + .argv = test_args.span(), + .env_map = &env_map, + .max_output_bytes = max_doc_file_size, + }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); - for (test_args.toSliceConst()) |arg| + for (test_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1282,7 +1291,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, else => { warn("{}\nThe following command crashed:\n", .{result.stderr}); - for (test_args.toSliceConst()) |arg| + for (test_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1326,12 +1335,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, } - const result = try ChildProcess.exec(allocator, test_args.toSliceConst(), null, &env_map, max_doc_file_size); + const result = try ChildProcess.exec(.{ + .allocator = allocator, + .argv = test_args.span(), + .env_map = &env_map, + .max_output_bytes = max_doc_file_size, + }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); - for (test_args.toSliceConst()) |arg| + for (test_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1340,7 +1354,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, else => { warn("{}\nThe following command crashed:\n", .{result.stderr}); - for (test_args.toSliceConst()) |arg| + for (test_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1418,12 +1432,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var } if (maybe_error_match) |error_match| { - const result = try ChildProcess.exec(allocator, build_args.toSliceConst(), null, &env_map, max_doc_file_size); + const result = try ChildProcess.exec(.{ + .allocator = allocator, + .argv = build_args.span(), + .env_map = &env_map, + .max_output_bytes = max_doc_file_size, + }); switch (result.term) { .Exited => |exit_code| { if (exit_code == 0) { warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr}); - for (build_args.toSliceConst()) |arg| + for (build_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1432,7 +1451,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var }, else => { warn("{}\nThe following command crashed:\n", .{result.stderr}); - for (build_args.toSliceConst()) |arg| + for (build_args.span()) |arg| warn("{} ", .{arg}) else warn("\n", .{}); @@ -1447,7 +1466,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var const colored_stderr = try termColor(allocator, escaped_stderr); try out.print("\n{}", .{colored_stderr}); } else { - _ = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{}); + _ = exec(allocator, &env_map, build_args.span()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{}); } if (!code.is_inline) { try out.print("\n", .{}); @@ -1484,7 +1503,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var try test_args.appendSlice(&[_][]const u8{ "-target", triple }); try out.print(" -target {}", .{triple}); } - const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed", .{}); + const result = exec(allocator, &env_map, test_args.span()) catch return parseError(tokenizer, code.source_token, "test failed", .{}); const escaped_stderr = try escapeHtml(allocator, result.stderr); const escaped_stdout = try escapeHtml(allocator, result.stdout); try out.print("\n{}{}\n", .{ escaped_stderr, escaped_stdout }); @@ -1497,7 +1516,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var } fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult { - const result = try ChildProcess.exec2(.{ + const result = try ChildProcess.exec(.{ .allocator = allocator, .argv = args, .env_map = env_map, diff --git a/doc/langref.html.in b/doc/langref.html.in index f98b9d674f..3d38d67e00 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -4953,7 +4953,7 @@ const mem = std.mem; test "cast *[1][*]const u8 to [*]const ?[*]const u8" { const window_name = [1][*]const u8{"window name"}; const x: [*]const ?[*]const u8 = &window_name; - assert(mem.eql(u8, std.mem.toSliceConst(u8, @ptrCast([*:0]const u8, x[0].?)), "window name")); + assert(mem.eql(u8, std.mem.spanZ(@ptrCast([*:0]const u8, x[0].?)), "window name")); } {#code_end#} {#header_close#} @@ -9310,7 +9310,7 @@ test "string literal to constant slice" {

Sometimes the lifetime of a pointer may be more complicated. For example, when using - {#syntax#}std.ArrayList(T).toSlice(){#endsyntax#}, the returned slice has a lifetime that remains + {#syntax#}std.ArrayList(T).span(){#endsyntax#}, the returned slice has a lifetime that remains valid until the next time the list is resized, such as by appending new elements.

diff --git a/lib/std/atomic/queue.zig b/lib/std/atomic/queue.zig index 52e200e7a2..be0894d5cf 100644 --- a/lib/std/atomic/queue.zig +++ b/lib/std/atomic/queue.zig @@ -227,7 +227,7 @@ fn startPuts(ctx: *Context) u8 { var r = std.rand.DefaultPrng.init(0xdeadbeef); while (put_count != 0) : (put_count -= 1) { std.time.sleep(1); // let the os scheduler be our fuzz - const x = @bitCast(i32, r.random.scalar(u32)); + const x = @bitCast(i32, r.random.int(u32)); const node = ctx.allocator.create(Queue(i32).Node) catch unreachable; node.* = .{ .prev = undefined, diff --git a/lib/std/atomic/stack.zig b/lib/std/atomic/stack.zig index 092dce15b0..db749ecaac 100644 --- a/lib/std/atomic/stack.zig +++ b/lib/std/atomic/stack.zig @@ -150,7 +150,7 @@ fn startPuts(ctx: *Context) u8 { var r = std.rand.DefaultPrng.init(0xdeadbeef); while (put_count != 0) : (put_count -= 1) { std.time.sleep(1); // let the os scheduler be our fuzz - const x = @bitCast(i32, r.random.scalar(u32)); + const x = @bitCast(i32, r.random.int(u32)); const node = ctx.allocator.create(Stack(i32).Node) catch unreachable; node.* = Stack(i32).Node{ .next = undefined, diff --git a/lib/std/buffer.zig b/lib/std/buffer.zig index a1e29ef51a..7971820770 100644 --- a/lib/std/buffer.zig +++ b/lib/std/buffer.zig @@ -43,7 +43,7 @@ pub const Buffer = struct { /// Must deinitialize with deinit. pub fn initFromBuffer(buffer: Buffer) !Buffer { - return Buffer.init(buffer.list.allocator, buffer.toSliceConst()); + return Buffer.init(buffer.list.allocator, buffer.span()); } /// Buffer takes ownership of the passed in slice. The slice must have been @@ -81,15 +81,8 @@ pub const Buffer = struct { return self.list.span()[0..self.len() :0]; } - /// Deprecated: use `span` - pub fn toSlice(self: Buffer) [:0]u8 { - return self.span(); - } - - /// Deprecated: use `span` - pub fn toSliceConst(self: Buffer) [:0]const u8 { - return self.span(); - } + pub const toSlice = @compileError("deprecated; use span()"); + pub const toSliceConst = @compileError("deprecated; use span()"); pub fn shrink(self: *Buffer, new_len: usize) void { assert(new_len <= self.len()); @@ -120,17 +113,17 @@ pub const Buffer = struct { pub fn append(self: *Buffer, m: []const u8) !void { const old_len = self.len(); try self.resize(old_len + m.len); - mem.copy(u8, self.list.toSlice()[old_len..], m); + mem.copy(u8, self.list.span()[old_len..], m); } pub fn appendByte(self: *Buffer, byte: u8) !void { const old_len = self.len(); try self.resize(old_len + 1); - self.list.toSlice()[old_len] = byte; + self.list.span()[old_len] = byte; } pub fn eql(self: Buffer, m: []const u8) bool { - return mem.eql(u8, self.toSliceConst(), m); + return mem.eql(u8, self.span(), m); } pub fn startsWith(self: Buffer, m: []const u8) bool { @@ -147,7 +140,7 @@ pub const Buffer = struct { pub fn replaceContents(self: *Buffer, m: []const u8) !void { try self.resize(m.len); - mem.copy(u8, self.list.toSlice(), m); + mem.copy(u8, self.list.span(), m); } pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) { @@ -171,17 +164,17 @@ test "simple Buffer" { try buf.append(" "); try buf.append("world"); testing.expect(buf.eql("hello world")); - testing.expect(mem.eql(u8, mem.toSliceConst(u8, buf.toSliceConst().ptr), buf.toSliceConst())); + testing.expect(mem.eql(u8, mem.spanZ(buf.span().ptr), buf.span())); var buf2 = try Buffer.initFromBuffer(buf); defer buf2.deinit(); - testing.expect(buf.eql(buf2.toSliceConst())); + testing.expect(buf.eql(buf2.span())); testing.expect(buf.startsWith("hell")); testing.expect(buf.endsWith("orld")); try buf2.resize(4); - testing.expect(buf.startsWith(buf2.toSlice())); + testing.expect(buf.startsWith(buf2.span())); } test "Buffer.initSize" { @@ -189,7 +182,7 @@ test "Buffer.initSize" { defer buf.deinit(); testing.expect(buf.len() == 3); try buf.append("hello"); - testing.expect(mem.eql(u8, buf.toSliceConst()[3..], "hello")); + testing.expect(mem.eql(u8, buf.span()[3..], "hello")); } test "Buffer.initCapacity" { @@ -201,7 +194,7 @@ test "Buffer.initCapacity" { try buf.append("hello"); testing.expect(buf.len() == 5); testing.expect(buf.capacity() == old_cap); - testing.expect(mem.eql(u8, buf.toSliceConst(), "hello")); + testing.expect(mem.eql(u8, buf.span(), "hello")); } test "Buffer.print" { @@ -221,5 +214,5 @@ test "Buffer.outStream" { const y: i32 = 1234; try buf_stream.print("x: {}\ny: {}\n", .{ x, y }); - testing.expect(mem.eql(u8, buffer.toSlice(), "x: 42\ny: 1234\n")); + testing.expect(mem.eql(u8, buffer.span(), "x: 42\ny: 1234\n")); } diff --git a/lib/std/build.zig b/lib/std/build.zig index c603fd861b..858f6bd6f0 100644 --- a/lib/std/build.zig +++ b/lib/std/build.zig @@ -355,7 +355,7 @@ pub const Builder = struct { } } - for (wanted_steps.toSliceConst()) |s| { + for (wanted_steps.span()) |s| { try self.makeOneStep(s); } } @@ -372,7 +372,7 @@ pub const Builder = struct { const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step); const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls); - for (self.installed_files.toSliceConst()) |installed_file| { + for (self.installed_files.span()) |installed_file| { const full_path = self.getInstallPath(installed_file.dir, installed_file.path); if (self.verbose) { warn("rm {}\n", .{full_path}); @@ -390,7 +390,7 @@ pub const Builder = struct { } s.loop_flag = true; - for (s.dependencies.toSlice()) |dep| { + for (s.dependencies.span()) |dep| { self.makeOneStep(dep) catch |err| { if (err == error.DependencyLoopDetected) { warn(" {}\n", .{s.name}); @@ -405,7 +405,7 @@ pub const Builder = struct { } fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step { - for (self.top_level_steps.toSliceConst()) |top_level_step| { + for (self.top_level_steps.span()) |top_level_step| { if (mem.eql(u8, top_level_step.step.name, name)) { return &top_level_step.step; } @@ -470,7 +470,7 @@ pub const Builder = struct { return null; }, UserValue.Scalar => |s| return &[_][]const u8{s}, - UserValue.List => |lst| return lst.toSliceConst(), + UserValue.List => |lst| return lst.span(), }, } } @@ -866,7 +866,7 @@ pub const Builder = struct { pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 { // TODO report error for ambiguous situations const exe_extension = @as(CrossTarget, .{}).exeFileExt(); - for (self.search_prefixes.toSliceConst()) |search_prefix| { + for (self.search_prefixes.span()) |search_prefix| { for (names) |name| { if (fs.path.isAbsolute(name)) { return name; @@ -1010,7 +1010,7 @@ pub const Builder = struct { .desc = tok_it.rest(), }); } - return list.toSliceConst(); + return list.span(); } fn getPkgConfigList(self: *Builder) ![]const PkgConfigPkg { @@ -1395,7 +1395,7 @@ pub const LibExeObjStep = struct { if (isLibCLibrary(name)) { return self.is_linking_libc; } - for (self.link_objects.toSliceConst()) |link_object| { + for (self.link_objects.span()) |link_object| { switch (link_object) { LinkObject.SystemLib => |n| if (mem.eql(u8, n, name)) return true, else => continue, @@ -1599,10 +1599,7 @@ pub const LibExeObjStep = struct { self.main_pkg_path = dir_path; } - /// Deprecated; just set the field directly. - pub fn setDisableGenH(self: *LibExeObjStep, is_disabled: bool) void { - self.emit_h = !is_disabled; - } + pub const setDisableGenH = @compileError("deprecated; set the emit_h field directly"); pub fn setLibCFile(self: *LibExeObjStep, libc_file: ?[]const u8) void { self.libc_file = libc_file; @@ -1762,7 +1759,7 @@ pub const LibExeObjStep = struct { self.include_dirs.append(IncludeDir{ .OtherStep = other }) catch unreachable; // Inherit dependency on system libraries - for (other.link_objects.toSliceConst()) |link_object| { + for (other.link_objects.span()) |link_object| { switch (link_object) { .SystemLib => |name| self.linkSystemLibrary(name), else => continue, @@ -1802,7 +1799,7 @@ pub const LibExeObjStep = struct { if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder)); - for (self.link_objects.toSlice()) |link_object| { + for (self.link_objects.span()) |link_object| { switch (link_object) { .StaticPath => |static_path| { try zig_args.append("--object"); @@ -1855,7 +1852,7 @@ pub const LibExeObjStep = struct { builder.allocator, &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) }, ); - try std.io.writeFile(build_options_file, self.build_options_contents.toSliceConst()); + try fs.cwd().writeFile(build_options_file, self.build_options_contents.span()); try zig_args.append("--pkg-begin"); try zig_args.append("build_options"); try zig_args.append(builder.pathFromRoot(build_options_file)); @@ -1978,7 +1975,7 @@ pub const LibExeObjStep = struct { try mcpu_buffer.append(feature.name); } } - try zig_args.append(mcpu_buffer.toSliceConst()); + try zig_args.append(mcpu_buffer.span()); } if (self.target.dynamic_linker.get()) |dynamic_linker| { @@ -2040,7 +2037,7 @@ pub const LibExeObjStep = struct { try zig_args.append("--test-cmd-bin"); }, } - for (self.packages.toSliceConst()) |pkg| { + for (self.packages.span()) |pkg| { try zig_args.append("--pkg-begin"); try zig_args.append(pkg.name); try zig_args.append(builder.pathFromRoot(pkg.path)); @@ -2057,7 +2054,7 @@ pub const LibExeObjStep = struct { try zig_args.append("--pkg-end"); } - for (self.include_dirs.toSliceConst()) |include_dir| { + for (self.include_dirs.span()) |include_dir| { switch (include_dir) { .RawPath => |include_path| { try zig_args.append("-I"); @@ -2075,18 +2072,18 @@ pub const LibExeObjStep = struct { } } - for (self.lib_paths.toSliceConst()) |lib_path| { + for (self.lib_paths.span()) |lib_path| { try zig_args.append("-L"); try zig_args.append(lib_path); } - for (self.c_macros.toSliceConst()) |c_macro| { + for (self.c_macros.span()) |c_macro| { try zig_args.append("-D"); try zig_args.append(c_macro); } if (self.target.isDarwin()) { - for (self.framework_dirs.toSliceConst()) |dir| { + for (self.framework_dirs.span()) |dir| { try zig_args.append("-F"); try zig_args.append(dir); } @@ -2146,12 +2143,12 @@ pub const LibExeObjStep = struct { } if (self.kind == Kind.Test) { - try builder.spawnChild(zig_args.toSliceConst()); + try builder.spawnChild(zig_args.span()); } else { try zig_args.append("--cache"); try zig_args.append("on"); - const output_dir_nl = try builder.execFromStep(zig_args.toSliceConst(), &self.step); + const output_dir_nl = try builder.execFromStep(zig_args.span(), &self.step); const build_output_dir = mem.trimRight(u8, output_dir_nl, "\r\n"); if (self.output_dir) |output_dir| { diff --git a/lib/std/build/emit_raw.zig b/lib/std/build/emit_raw.zig index 8b4747e8a7..367da2f747 100644 --- a/lib/std/build/emit_raw.zig +++ b/lib/std/build/emit_raw.zig @@ -72,7 +72,7 @@ const BinaryElfOutput = struct { newSegment.binaryOffset = 0; newSegment.firstSection = null; - for (self.sections.toSlice()) |section| { + for (self.sections.span()) |section| { if (sectionWithinSegment(section, phdr)) { if (section.segment) |sectionSegment| { if (sectionSegment.elfOffset > newSegment.elfOffset) { @@ -92,7 +92,7 @@ const BinaryElfOutput = struct { } } - sort.sort(*BinaryElfSegment, self.segments.toSlice(), segmentSortCompare); + sort.sort(*BinaryElfSegment, self.segments.span(), segmentSortCompare); if (self.segments.len > 0) { const firstSegment = self.segments.at(0); @@ -105,19 +105,19 @@ const BinaryElfOutput = struct { const basePhysicalAddress = firstSegment.physicalAddress; - for (self.segments.toSlice()) |segment| { + for (self.segments.span()) |segment| { segment.binaryOffset = segment.physicalAddress - basePhysicalAddress; } } } - for (self.sections.toSlice()) |section| { + for (self.sections.span()) |section| { if (section.segment) |segment| { section.binaryOffset = segment.binaryOffset + (section.elfOffset - segment.elfOffset); } } - sort.sort(*BinaryElfSection, self.sections.toSlice(), sectionSortCompare); + sort.sort(*BinaryElfSection, self.sections.span(), sectionSortCompare); return self; } @@ -165,7 +165,7 @@ fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !v var binary_elf_output = try BinaryElfOutput.parse(allocator, elf_file); defer binary_elf_output.deinit(); - for (binary_elf_output.sections.toSlice()) |section| { + for (binary_elf_output.sections.span()) |section| { try writeBinaryElfSection(elf_file, out_file, section); } } diff --git a/lib/std/build/run.zig b/lib/std/build/run.zig index 3276de9d19..3a2dc2a2a3 100644 --- a/lib/std/build/run.zig +++ b/lib/std/build/run.zig @@ -139,7 +139,7 @@ pub const RunStep = struct { const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root; var argv_list = ArrayList([]const u8).init(self.builder.allocator); - for (self.argv.toSlice()) |arg| { + for (self.argv.span()) |arg| { switch (arg) { Arg.Bytes => |bytes| try argv_list.append(bytes), Arg.Artifact => |artifact| { @@ -153,7 +153,7 @@ pub const RunStep = struct { } } - const argv = argv_list.toSliceConst(); + const argv = argv_list.span(); const child = std.ChildProcess.init(argv, self.builder.allocator) catch unreachable; defer child.deinit(); @@ -289,7 +289,7 @@ pub const RunStep = struct { } fn addPathForDynLibs(self: *RunStep, artifact: *LibExeObjStep) void { - for (artifact.link_objects.toSliceConst()) |link_object| { + for (artifact.link_objects.span()) |link_object| { switch (link_object) { .OtherStep => |other| { if (other.target.isWindows() and other.isDynamicLibrary()) { diff --git a/lib/std/build/translate_c.zig b/lib/std/build/translate_c.zig index e9e61b190f..73e395d951 100644 --- a/lib/std/build/translate_c.zig +++ b/lib/std/build/translate_c.zig @@ -71,7 +71,7 @@ pub const TranslateCStep = struct { try argv_list.append(self.source.getPath(self.builder)); - const output_path_nl = try self.builder.execFromStep(argv_list.toSliceConst(), &self.step); + const output_path_nl = try self.builder.execFromStep(argv_list.span(), &self.step); const output_path = mem.trimRight(u8, output_path_nl, "\r\n"); self.out_basename = fs.path.basename(output_path); diff --git a/lib/std/build/write_file.zig b/lib/std/build/write_file.zig index 0c3f628457..7389923dc3 100644 --- a/lib/std/build/write_file.zig +++ b/lib/std/build/write_file.zig @@ -59,7 +59,7 @@ pub const WriteFileStep = struct { // new random bytes when WriteFileStep implementation is modified // in a non-backwards-compatible way. hash.update("eagVR1dYXoE7ARDP"); - for (self.files.toSliceConst()) |file| { + for (self.files.span()) |file| { hash.update(file.basename); hash.update(file.bytes); hash.update("|"); @@ -80,7 +80,7 @@ pub const WriteFileStep = struct { }; var dir = try fs.cwd().openDir(self.output_dir, .{}); defer dir.close(); - for (self.files.toSliceConst()) |file| { + for (self.files.span()) |file| { dir.writeFile(file.basename, file.bytes) catch |err| { warn("unable to write {} into {}: {}\n", .{ file.basename, diff --git a/lib/std/c.zig b/lib/std/c.zig index a229fedaa2..303fa58fae 100644 --- a/lib/std/c.zig +++ b/lib/std/c.zig @@ -174,7 +174,6 @@ pub extern "c" fn realloc(?*c_void, usize) ?*c_void; pub extern "c" fn free(*c_void) void; pub extern "c" fn posix_memalign(memptr: **c_void, alignment: usize, size: usize) c_int; -// Deprecated pub extern "c" fn futimes(fd: fd_t, times: *[2]timeval) c_int; pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int; diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig index 008fc34ff6..3013133b11 100644 --- a/lib/std/child_process.zig +++ b/lib/std/child_process.zig @@ -175,29 +175,11 @@ pub const ChildProcess = struct { stderr: []u8, }; - /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. - /// If it succeeds, the caller owns result.stdout and result.stderr memory. - /// TODO deprecate in favor of exec2 - pub fn exec( - allocator: *mem.Allocator, - argv: []const []const u8, - cwd: ?[]const u8, - env_map: ?*const BufMap, - max_output_bytes: usize, - ) !ExecResult { - return exec2(.{ - .allocator = allocator, - .argv = argv, - .cwd = cwd, - .env_map = env_map, - .max_output_bytes = max_output_bytes, - }); - } + pub const exec2 = @compileError("deprecated: exec2 is renamed to exec"); /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. /// If it succeeds, the caller owns result.stdout and result.stderr memory. - /// TODO rename to exec - pub fn exec2(args: struct { + pub fn exec(args: struct { allocator: *mem.Allocator, argv: []const []const u8, cwd: ?[]const u8 = null, @@ -370,7 +352,7 @@ pub const ChildProcess = struct { const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const dev_null_fd = if (any_ignore) - os.openC("/dev/null", os.O_RDWR, 0) catch |err| switch (err) { + os.openZ("/dev/null", os.O_RDWR, 0) catch |err| switch (err) { error.PathAlreadyExists => unreachable, error.NoSpaceLeft => unreachable, error.FileTooBig => unreachable, diff --git a/lib/std/coff.zig b/lib/std/coff.zig index 2e17f46454..d89019eec6 100644 --- a/lib/std/coff.zig +++ b/lib/std/coff.zig @@ -145,7 +145,7 @@ pub const Coff = struct { blk: while (i < debug_dir_entry_count) : (i += 1) { const debug_dir_entry = try in.readStruct(DebugDirectoryEntry); if (debug_dir_entry.type == IMAGE_DEBUG_TYPE_CODEVIEW) { - for (self.sections.toSlice()) |*section| { + for (self.sections.span()) |*section| { const section_start = section.header.virtual_address; const section_size = section.header.misc.virtual_size; const rva = debug_dir_entry.address_of_raw_data; @@ -211,7 +211,7 @@ pub const Coff = struct { } pub fn getSection(self: *Coff, comptime name: []const u8) ?*Section { - for (self.sections.toSlice()) |*sec| { + for (self.sections.span()) |*sec| { if (mem.eql(u8, sec.header.name[0..name.len], name)) { return sec; } diff --git a/lib/std/crypto/gimli.zig b/lib/std/crypto/gimli.zig index 30304f59cf..be789d8953 100644 --- a/lib/std/crypto/gimli.zig +++ b/lib/std/crypto/gimli.zig @@ -23,10 +23,12 @@ pub const State = struct { const Self = @This(); + /// TODO follow the span() convention instead of having this and `toSliceConst` pub fn toSlice(self: *Self) []u8 { return mem.sliceAsBytes(self.data[0..]); } + /// TODO follow the span() convention instead of having this and `toSlice` pub fn toSliceConst(self: *Self) []const u8 { return mem.sliceAsBytes(self.data[0..]); } diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 94475515e7..35c13809f7 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -735,7 +735,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) ! for (present) |_| { const name_offset = try pdb_stream.inStream().readIntLittle(u32); const name_index = try pdb_stream.inStream().readIntLittle(u32); - const name = mem.toSlice(u8, @ptrCast([*:0]u8, name_bytes.ptr + name_offset)); + const name = mem.spanZ(@ptrCast([*:0]u8, name_bytes.ptr + name_offset)); if (mem.eql(u8, name, "/names")) { break :str_tab_index name_index; } @@ -1131,7 +1131,7 @@ pub const DebugInfo = struct { const obj_di = try self.allocator.create(ModuleDebugInfo); errdefer self.allocator.destroy(obj_di); - const macho_path = mem.toSliceConst(u8, std.c._dyld_get_image_name(i)); + const macho_path = mem.spanZ(std.c._dyld_get_image_name(i)); obj_di.* = openMachODebugInfo(self.allocator, macho_path) catch |err| switch (err) { error.FileNotFound => return error.MissingDebugInfo, else => return err, @@ -1254,10 +1254,7 @@ pub const DebugInfo = struct { if (context.address >= seg_start and context.address < seg_end) { // Android libc uses NULL instead of an empty string to mark the // main program - context.name = if (info.dlpi_name) |dlpi_name| - mem.toSliceConst(u8, dlpi_name) - else - ""; + context.name = if (info.dlpi_name) |dlpi_name| mem.spanZ(dlpi_name) else ""; context.base_address = info.dlpi_addr; // Stop the iteration return error.Found; @@ -1426,7 +1423,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) { return SymbolInfo{}; assert(symbol.ofile.?.n_strx < self.strings.len); - const o_file_path = mem.toSliceConst(u8, self.strings.ptr + symbol.ofile.?.n_strx); + const o_file_path = mem.spanZ(self.strings.ptr + symbol.ofile.?.n_strx); // Check if its debug infos are already in the cache var o_file_di = self.ofiles.getValue(o_file_path) orelse @@ -1483,7 +1480,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) { const mod_index = for (self.sect_contribs) |sect_contrib| { if (sect_contrib.Section > self.coff.sections.len) continue; // Remember that SectionContribEntry.Section is 1-based. - coff_section = &self.coff.sections.toSlice()[sect_contrib.Section - 1]; + coff_section = &self.coff.sections.span()[sect_contrib.Section - 1]; const vaddr_start = coff_section.header.virtual_address + sect_contrib.Offset; const vaddr_end = vaddr_start + sect_contrib.Size; @@ -1510,7 +1507,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) { const vaddr_start = coff_section.header.virtual_address + proc_sym.CodeOffset; const vaddr_end = vaddr_start + proc_sym.CodeSize; if (relocated_address >= vaddr_start and relocated_address < vaddr_end) { - break mem.toSliceConst(u8, @ptrCast([*:0]u8, proc_sym) + @sizeOf(pdb.ProcSym)); + break mem.spanZ(@ptrCast([*:0]u8, proc_sym) + @sizeOf(pdb.ProcSym)); } }, else => {}, diff --git a/lib/std/dwarf.zig b/lib/std/dwarf.zig index d198886b11..95403bc109 100644 --- a/lib/std/dwarf.zig +++ b/lib/std/dwarf.zig @@ -82,7 +82,7 @@ const Die = struct { }; fn getAttr(self: *const Die, id: u64) ?*const FormValue { - for (self.attrs.toSliceConst()) |*attr| { + for (self.attrs.span()) |*attr| { if (attr.id == id) return &attr.value; } return null; @@ -375,7 +375,7 @@ fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64 } fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry { - for (abbrev_table.toSliceConst()) |*table_entry| { + for (abbrev_table.span()) |*table_entry| { if (table_entry.abbrev_code == abbrev_code) return table_entry; } return null; @@ -399,7 +399,7 @@ pub const DwarfInfo = struct { } fn getSymbolName(di: *DwarfInfo, address: u64) ?[]const u8 { - for (di.func_list.toSliceConst()) |*func| { + for (di.func_list.span()) |*func| { if (func.pc_range) |range| { if (address >= range.start and address < range.end) { return func.name; @@ -588,7 +588,7 @@ pub const DwarfInfo = struct { } fn findCompileUnit(di: *DwarfInfo, target_address: u64) !*const CompileUnit { - for (di.compile_unit_list.toSlice()) |*compile_unit| { + for (di.compile_unit_list.span()) |*compile_unit| { if (compile_unit.pc_range) |range| { if (target_address >= range.start and target_address < range.end) return compile_unit; } @@ -636,7 +636,7 @@ pub const DwarfInfo = struct { /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found, /// seeks in the stream and parses it. fn getAbbrevTable(di: *DwarfInfo, abbrev_offset: u64) !*const AbbrevTable { - for (di.abbrev_table_list.toSlice()) |*header| { + for (di.abbrev_table_list.span()) |*header| { if (header.offset == abbrev_offset) { return &header.table; } @@ -690,7 +690,7 @@ pub const DwarfInfo = struct { .attrs = ArrayList(Die.Attr).init(di.allocator()), }; try result.attrs.resize(table_entry.attrs.len); - for (table_entry.attrs.toSliceConst()) |attr, i| { + for (table_entry.attrs.span()) |attr, i| { result.attrs.items[i] = Die.Attr{ .id = attr.attr_id, .value = try parseFormValue(di.allocator(), in_stream, attr.form_id, is_64), @@ -757,7 +757,7 @@ pub const DwarfInfo = struct { } var file_entries = ArrayList(FileEntry).init(di.allocator()); - var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address); + var prog = LineNumberProgram.init(default_is_stmt, include_directories.span(), &file_entries, target_address); while (true) { const file_name = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize)); diff --git a/lib/std/dynamic_library.zig b/lib/std/dynamic_library.zig index 0d14f8d032..110d476b10 100644 --- a/lib/std/dynamic_library.zig +++ b/lib/std/dynamic_library.zig @@ -254,9 +254,11 @@ pub const ElfDynLib = struct { }; } + pub const openC = @compileError("deprecated: renamed to openZ"); + /// Trusts the file. Malicious file will be able to execute arbitrary code. - pub fn openC(path_c: [*:0]const u8) !ElfDynLib { - return open(mem.toSlice(u8, path_c)); + pub fn openZ(path_c: [*:0]const u8) !ElfDynLib { + return open(mem.spanZ(path_c)); } /// Trusts the file @@ -285,7 +287,7 @@ pub const ElfDynLib = struct { if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue; if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == self.syms[i].st_shndx) continue; - if (!mem.eql(u8, name, mem.toSliceConst(u8, self.strings + self.syms[i].st_name))) continue; + if (!mem.eql(u8, name, mem.spanZ(self.strings + self.syms[i].st_name))) continue; if (maybe_versym) |versym| { if (!checkver(self.verdef.?, versym[i], vername, self.strings)) continue; @@ -316,7 +318,7 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [ def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next); } const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux); - return mem.eql(u8, vername, mem.toSliceConst(u8, strings + aux.vda_name)); + return mem.eql(u8, vername, mem.spanZ(strings + aux.vda_name)); } pub const WindowsDynLib = struct { @@ -329,7 +331,9 @@ pub const WindowsDynLib = struct { return openW(&path_w); } - pub fn openC(path_c: [*:0]const u8) !WindowsDynLib { + pub const openC = @compileError("deprecated: renamed to openZ"); + + pub fn openZ(path_c: [*:0]const u8) !WindowsDynLib { const path_w = try windows.cStrToPrefixedFileW(path_c); return openW(&path_w); } @@ -362,10 +366,12 @@ pub const DlDynlib = struct { pub fn open(path: []const u8) !DlDynlib { const path_c = try os.toPosixPath(path); - return openC(&path_c); + return openZ(&path_c); } - pub fn openC(path_c: [*:0]const u8) !DlDynlib { + pub const openC = @compileError("deprecated: renamed to openZ"); + + pub fn openZ(path_c: [*:0]const u8) !DlDynlib { return DlDynlib{ .handle = system.dlopen(path_c, system.RTLD_LAZY) orelse { return error.FileNotFound; diff --git a/lib/std/event/loop.zig b/lib/std/event/loop.zig index 7db6fe98de..0a5cf2a6e7 100644 --- a/lib/std/event/loop.zig +++ b/lib/std/event/loop.zig @@ -1096,10 +1096,10 @@ pub const Loop = struct { msg.result = noasync os.preadv(msg.fd, msg.iov, msg.offset); }, .open => |*msg| { - msg.result = noasync os.openC(msg.path, msg.flags, msg.mode); + msg.result = noasync os.openZ(msg.path, msg.flags, msg.mode); }, .openat => |*msg| { - msg.result = noasync os.openatC(msg.fd, msg.path, msg.flags, msg.mode); + msg.result = noasync os.openatZ(msg.fd, msg.path, msg.flags, msg.mode); }, .faccessat => |*msg| { msg.result = noasync os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags); diff --git a/lib/std/fs.zig b/lib/std/fs.zig index 077e668188..95f1b08bd9 100644 --- a/lib/std/fs.zig +++ b/lib/std/fs.zig @@ -11,13 +11,18 @@ const math = std.math; pub const path = @import("fs/path.zig"); pub const File = @import("fs/file.zig").File; +// TODO audit these APIs with respect to Dir and absolute paths + pub const symLink = os.symlink; -pub const symLinkC = os.symlinkC; +pub const symLinkZ = os.symlinkZ; +pub const symLinkC = @compileError("deprecated: renamed to symlinkZ"); pub const rename = os.rename; -pub const renameC = os.renameC; +pub const renameZ = os.renameZ; +pub const renameC = @compileError("deprecated: renamed to renameZ"); pub const renameW = os.renameW; pub const realpath = os.realpath; -pub const realpathC = os.realpathC; +pub const realpathZ = os.realpathZ; +pub const realpathC = @compileError("deprecated: renamed to realpathZ"); pub const realpathW = os.realpathW; pub const getAppDataDir = @import("fs/get_app_data_dir.zig").getAppDataDir; @@ -120,7 +125,7 @@ pub const AtomicFile = struct { file: File, // TODO either replace this with rand_buf or use []u16 on Windows tmp_path_buf: [TMP_PATH_LEN:0]u8, - dest_path: []const u8, + dest_basename: []const u8, file_open: bool, file_exists: bool, close_dir_on_deinit: bool, @@ -131,17 +136,23 @@ pub const AtomicFile = struct { const RANDOM_BYTES = 12; const TMP_PATH_LEN = base64.Base64Encoder.calcSize(RANDOM_BYTES); - /// TODO rename this. Callers should go through Dir API - pub fn init2(dest_path: []const u8, mode: File.Mode, dir: Dir, close_dir_on_deinit: bool) InitError!AtomicFile { + /// Note that the `Dir.atomicFile` API may be more handy than this lower-level function. + pub fn init( + dest_basename: []const u8, + mode: File.Mode, + dir: Dir, + close_dir_on_deinit: bool, + ) InitError!AtomicFile { var rand_buf: [RANDOM_BYTES]u8 = undefined; var tmp_path_buf: [TMP_PATH_LEN:0]u8 = undefined; + // TODO: should be able to use TMP_PATH_LEN here. tmp_path_buf[base64.Base64Encoder.calcSize(RANDOM_BYTES)] = 0; while (true) { try crypto.randomBytes(rand_buf[0..]); base64_encoder.encode(&tmp_path_buf, &rand_buf); - const file = dir.createFileC( + const file = dir.createFileZ( &tmp_path_buf, .{ .mode = mode, .exclusive = true }, ) catch |err| switch (err) { @@ -152,7 +163,7 @@ pub const AtomicFile = struct { return AtomicFile{ .file = file, .tmp_path_buf = tmp_path_buf, - .dest_path = dest_path, + .dest_basename = dest_basename, .file_open = true, .file_exists = true, .close_dir_on_deinit = close_dir_on_deinit, @@ -161,11 +172,6 @@ pub const AtomicFile = struct { } } - /// Deprecated. Use `Dir.atomicFile`. - pub fn init(dest_path: []const u8, mode: File.Mode) InitError!AtomicFile { - return cwd().atomicFile(dest_path, .{ .mode = mode }); - } - /// always call deinit, even after successful finish() pub fn deinit(self: *AtomicFile) void { if (self.file_open) { @@ -173,7 +179,7 @@ pub const AtomicFile = struct { self.file_open = false; } if (self.file_exists) { - self.dir.deleteFileC(&self.tmp_path_buf) catch {}; + self.dir.deleteFileZ(&self.tmp_path_buf) catch {}; self.file_exists = false; } if (self.close_dir_on_deinit) { @@ -189,12 +195,12 @@ pub const AtomicFile = struct { self.file_open = false; } if (std.Target.current.os.tag == .windows) { - const dest_path_w = try os.windows.sliceToPrefixedFileW(self.dest_path); + const dest_path_w = try os.windows.sliceToPrefixedFileW(self.dest_basename); const tmp_path_w = try os.windows.cStrToPrefixedFileW(&self.tmp_path_buf); try os.renameatW(self.dir.fd, &tmp_path_w, self.dir.fd, &dest_path_w, os.windows.TRUE); self.file_exists = false; } else { - const dest_path_c = try os.toPosixPath(self.dest_path); + const dest_path_c = try os.toPosixPath(self.dest_basename); try os.renameatZ(self.dir.fd, &self.tmp_path_buf, self.dir.fd, &dest_path_c); self.file_exists = false; } @@ -213,7 +219,7 @@ pub fn makeDirAbsolute(absolute_path: []const u8) !void { /// Same as `makeDirAbsolute` except the parameter is a null-terminated UTF8-encoded string. pub fn makeDirAbsoluteZ(absolute_path_z: [*:0]const u8) !void { - assert(path.isAbsoluteC(absolute_path_z)); + assert(path.isAbsoluteZ(absolute_path_z)); return os.mkdirZ(absolute_path_z, default_new_dir_mode); } @@ -224,18 +230,25 @@ pub fn makeDirAbsoluteW(absolute_path_w: [*:0]const u16) !void { os.windows.CloseHandle(handle); } -/// Deprecated; use `Dir.deleteDir`. -pub fn deleteDir(dir_path: []const u8) !void { +pub const deleteDir = @compileError("deprecated; use dir.deleteDir or deleteDirAbsolute"); +pub const deleteDirC = @compileError("deprecated; use dir.deleteDirZ or deleteDirAbsoluteZ"); +pub const deleteDirW = @compileError("deprecated; use dir.deleteDirW or deleteDirAbsoluteW"); + +/// Same as `Dir.deleteDir` except the path is absolute. +pub fn deleteDirAbsolute(dir_path: []const u8) !void { + assert(path.isAbsolute(dir_path)); return os.rmdir(dir_path); } -/// Deprecated; use `Dir.deleteDirC`. -pub fn deleteDirC(dir_path: [*:0]const u8) !void { - return os.rmdirC(dir_path); +/// Same as `deleteDirAbsolute` except the path parameter is null-terminated. +pub fn deleteDirAbsoluteZ(dir_path: [*:0]const u8) !void { + assert(path.isAbsoluteZ(dir_path)); + return os.rmdirZ(dir_path); } -/// Deprecated; use `Dir.deleteDirW`. -pub fn deleteDirW(dir_path: [*:0]const u16) !void { +/// Same as `deleteDirAbsolute` except the path parameter is WTF-16 and target OS is assumed Windows. +pub fn deleteDirAbsoluteW(dir_path: [*:0]const u16) !void { + assert(path.isAbsoluteWindowsW(dir_path)); return os.rmdirW(dir_path); } @@ -412,7 +425,7 @@ pub const Dir = struct { const next_index = self.index + linux_entry.reclen(); self.index = next_index; - const name = mem.toSlice(u8, @ptrCast([*:0]u8, &linux_entry.d_name)); + const name = mem.spanZ(@ptrCast([*:0]u8, &linux_entry.d_name)); // skip . and .. entries if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) { @@ -573,8 +586,7 @@ pub const Dir = struct { return self.openFileZ(&path_c, flags); } - /// Deprecated; use `openFileZ`. - pub const openFileC = openFileZ; + pub const openFileC = @compileError("deprecated: renamed to openFileZ"); /// Same as `openFile` but the path parameter is null-terminated. pub fn openFileZ(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File { @@ -592,7 +604,7 @@ pub const Dir = struct { const fd = if (need_async_thread and !flags.always_blocking) try std.event.Loop.instance.?.openatZ(self.fd, sub_path, os_flags, 0) else - try os.openatC(self.fd, sub_path, os_flags, 0); + try os.openatZ(self.fd, sub_path, os_flags, 0); return File{ .handle = fd, .io_mode = .blocking, @@ -625,11 +637,13 @@ pub const Dir = struct { return self.createFileW(&path_w, flags); } const path_c = try os.toPosixPath(sub_path); - return self.createFileC(&path_c, flags); + return self.createFileZ(&path_c, flags); } + pub const createFileC = @compileError("deprecated: renamed to createFileZ"); + /// Same as `createFile` but the path parameter is null-terminated. - pub fn createFileC(self: Dir, sub_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File { + pub fn createFileZ(self: Dir, sub_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File { if (builtin.os.tag == .windows) { const path_w = try os.windows.cStrToPrefixedFileW(sub_path_c); return self.createFileW(&path_w, flags); @@ -642,7 +656,7 @@ pub const Dir = struct { const fd = if (need_async_thread) try std.event.Loop.instance.?.openatZ(self.fd, sub_path_c, os_flags, flags.mode) else - try os.openatC(self.fd, sub_path_c, os_flags, flags.mode); + try os.openatZ(self.fd, sub_path_c, os_flags, flags.mode); return File{ .handle = fd, .io_mode = .blocking }; } @@ -664,27 +678,16 @@ pub const Dir = struct { }); } - /// Deprecated; call `openFile` directly. - pub fn openRead(self: Dir, sub_path: []const u8) File.OpenError!File { - return self.openFile(sub_path, .{}); - } - - /// Deprecated; call `openFileZ` directly. - pub fn openReadC(self: Dir, sub_path: [*:0]const u8) File.OpenError!File { - return self.openFileZ(sub_path, .{}); - } - - /// Deprecated; call `openFileW` directly. - pub fn openReadW(self: Dir, sub_path: [*:0]const u16) File.OpenError!File { - return self.openFileW(sub_path, .{}); - } + pub const openRead = @compileError("deprecated in favor of openFile"); + pub const openReadC = @compileError("deprecated in favor of openFileZ"); + pub const openReadW = @compileError("deprecated in favor of openFileW"); pub fn makeDir(self: Dir, sub_path: []const u8) !void { try os.mkdirat(self.fd, sub_path, default_new_dir_mode); } pub fn makeDirZ(self: Dir, sub_path: [*:0]const u8) !void { - try os.mkdiratC(self.fd, sub_path, default_new_dir_mode); + try os.mkdiratZ(self.fd, sub_path, default_new_dir_mode); } pub fn makeDirW(self: Dir, sub_path: [*:0]const u16) !void { @@ -758,20 +761,22 @@ pub const Dir = struct { return self.openDirW(&sub_path_w, args); } else { const sub_path_c = try os.toPosixPath(sub_path); - return self.openDirC(&sub_path_c, args); + return self.openDirZ(&sub_path_c, args); } } + pub const openDirC = @compileError("deprecated: renamed to openDirZ"); + /// Same as `openDir` except the parameter is null-terminated. - pub fn openDirC(self: Dir, sub_path_c: [*:0]const u8, args: OpenDirOptions) OpenError!Dir { + pub fn openDirZ(self: Dir, sub_path_c: [*:0]const u8, args: OpenDirOptions) OpenError!Dir { if (builtin.os.tag == .windows) { const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c); return self.openDirW(&sub_path_w, args); } else if (!args.iterate) { const O_PATH = if (@hasDecl(os, "O_PATH")) os.O_PATH else 0; - return self.openDirFlagsC(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC | O_PATH); + return self.openDirFlagsZ(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC | O_PATH); } else { - return self.openDirFlagsC(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC); + return self.openDirFlagsZ(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC); } } @@ -787,11 +792,11 @@ pub const Dir = struct { } /// `flags` must contain `os.O_DIRECTORY`. - fn openDirFlagsC(self: Dir, sub_path_c: [*:0]const u8, flags: u32) OpenError!Dir { + fn openDirFlagsZ(self: Dir, sub_path_c: [*:0]const u8, flags: u32) OpenError!Dir { const result = if (need_async_thread) std.event.Loop.instance.?.openatZ(self.fd, sub_path_c, flags, 0) else - os.openatC(self.fd, sub_path_c, flags, 0); + os.openatZ(self.fd, sub_path_c, flags, 0); const fd = result catch |err| switch (err) { error.FileTooBig => unreachable, // can't happen for directories error.IsDir => unreachable, // we're providing O_DIRECTORY @@ -809,7 +814,7 @@ pub const Dir = struct { .fd = undefined, }; - const path_len_bytes = @intCast(u16, mem.toSliceConst(u16, sub_path_w).len * 2); + const path_len_bytes = @intCast(u16, mem.lenZ(sub_path_w) * 2); var nt_name = w.UNICODE_STRING{ .Length = path_len_bytes, .MaximumLength = path_len_bytes, @@ -867,9 +872,11 @@ pub const Dir = struct { }; } + pub const deleteFileC = @compileError("deprecated: renamed to deleteFileZ"); + /// Same as `deleteFile` except the parameter is null-terminated. - pub fn deleteFileC(self: Dir, sub_path_c: [*:0]const u8) DeleteFileError!void { - os.unlinkatC(self.fd, sub_path_c, 0) catch |err| switch (err) { + pub fn deleteFileZ(self: Dir, sub_path_c: [*:0]const u8) DeleteFileError!void { + os.unlinkatZ(self.fd, sub_path_c, 0) catch |err| switch (err) { error.DirNotEmpty => unreachable, // not passing AT_REMOVEDIR else => |e| return e, }; @@ -908,12 +915,12 @@ pub const Dir = struct { return self.deleteDirW(&sub_path_w); } const sub_path_c = try os.toPosixPath(sub_path); - return self.deleteDirC(&sub_path_c); + return self.deleteDirZ(&sub_path_c); } /// Same as `deleteDir` except the parameter is null-terminated. - pub fn deleteDirC(self: Dir, sub_path_c: [*:0]const u8) DeleteDirError!void { - os.unlinkatC(self.fd, sub_path_c, os.AT_REMOVEDIR) catch |err| switch (err) { + pub fn deleteDirZ(self: Dir, sub_path_c: [*:0]const u8) DeleteDirError!void { + os.unlinkatZ(self.fd, sub_path_c, os.AT_REMOVEDIR) catch |err| switch (err) { error.IsDir => unreachable, // not possible since we pass AT_REMOVEDIR else => |e| return e, }; @@ -933,12 +940,14 @@ pub const Dir = struct { /// Asserts that the path parameter has no null bytes. pub fn readLink(self: Dir, sub_path: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { const sub_path_c = try os.toPosixPath(sub_path); - return self.readLinkC(&sub_path_c, buffer); + return self.readLinkZ(&sub_path_c, buffer); } + pub const readLinkC = @compileError("deprecated: renamed to readLinkZ"); + /// Same as `readLink`, except the `pathname` parameter is null-terminated. - pub fn readLinkC(self: Dir, sub_path_c: [*:0]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { - return os.readlinkatC(self.fd, sub_path_c, buffer); + pub fn readLinkZ(self: Dir, sub_path_c: [*:0]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { + return os.readlinkatZ(self.fd, sub_path_c, buffer); } /// On success, caller owns returned buffer. @@ -956,7 +965,7 @@ pub const Dir = struct { max_bytes: usize, comptime A: u29, ) ![]align(A) u8 { - var file = try self.openRead(file_path); + var file = try self.openFile(file_path, .{}); defer file.close(); const size = math.cast(usize, try file.getEndPos()) catch math.maxInt(usize); @@ -1280,9 +1289,9 @@ pub const Dir = struct { pub fn atomicFile(self: Dir, dest_path: []const u8, options: AtomicFileOptions) !AtomicFile { if (path.dirname(dest_path)) |dirname| { const dir = try self.openDir(dirname, .{}); - return AtomicFile.init2(path.basename(dest_path), options.mode, dir, true); + return AtomicFile.init(path.basename(dest_path), options.mode, dir, true); } else { - return AtomicFile.init2(dest_path, options.mode, self, false); + return AtomicFile.init(dest_path, options.mode, self, false); } } }; @@ -1309,9 +1318,11 @@ pub fn openFileAbsolute(absolute_path: []const u8, flags: File.OpenFlags) File.O return cwd().openFile(absolute_path, flags); } +pub const openFileAbsoluteC = @compileError("deprecated: renamed to openFileAbsoluteZ"); + /// Same as `openFileAbsolute` but the path parameter is null-terminated. -pub fn openFileAbsoluteC(absolute_path_c: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File { - assert(path.isAbsoluteC(absolute_path_c)); +pub fn openFileAbsoluteZ(absolute_path_c: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File { + assert(path.isAbsoluteZ(absolute_path_c)); return cwd().openFileZ(absolute_path_c, flags); } @@ -1332,10 +1343,12 @@ pub fn createFileAbsolute(absolute_path: []const u8, flags: File.CreateFlags) Fi return cwd().createFile(absolute_path, flags); } +pub const createFileAbsoluteC = @compileError("deprecated: renamed to createFileAbsoluteZ"); + /// Same as `createFileAbsolute` but the path parameter is null-terminated. -pub fn createFileAbsoluteC(absolute_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File { - assert(path.isAbsoluteC(absolute_path_c)); - return cwd().createFileC(absolute_path_c, flags); +pub fn createFileAbsoluteZ(absolute_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File { + assert(path.isAbsoluteZ(absolute_path_c)); + return cwd().createFileZ(absolute_path_c, flags); } /// Same as `createFileAbsolute` but the path parameter is WTF-16 encoded. @@ -1353,10 +1366,12 @@ pub fn deleteFileAbsolute(absolute_path: []const u8) DeleteFileError!void { return cwd().deleteFile(absolute_path); } +pub const deleteFileAbsoluteC = @compileError("deprecated: renamed to deleteFileAbsoluteZ"); + /// Same as `deleteFileAbsolute` except the parameter is null-terminated. -pub fn deleteFileAbsoluteC(absolute_path_c: [*:0]const u8) DeleteFileError!void { - assert(path.isAbsoluteC(absolute_path_c)); - return cwd().deleteFileC(absolute_path_c); +pub fn deleteFileAbsoluteZ(absolute_path_c: [*:0]const u8) DeleteFileError!void { + assert(path.isAbsoluteZ(absolute_path_c)); + return cwd().deleteFileZ(absolute_path_c); } /// Same as `deleteFileAbsolute` except the parameter is WTF-16 encoded. @@ -1384,6 +1399,21 @@ pub fn deleteTreeAbsolute(absolute_path: []const u8) !void { return dir.deleteTree(path.basename(absolute_path)); } +/// Same as `Dir.readLink`, except it asserts the path is absolute. +pub fn readLinkAbsolute(pathname: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { + assert(path.isAbsolute(pathname)); + return os.readlink(pathname, buffer); +} + +/// Same as `readLink`, except the path parameter is null-terminated. +pub fn readLinkAbsoluteZ(pathname_c: [*]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { + assert(path.isAbsoluteZ(pathname_c)); + return os.readlinkZ(pathname_c, buffer); +} + +pub const readLink = @compileError("deprecated; use Dir.readLink or readLinkAbsolute"); +pub const readLinkC = @compileError("deprecated; use Dir.readLinkZ or readLinkAbsoluteZ"); + pub const Walker = struct { stack: std.ArrayList(StackItem), name_buffer: std.Buffer, @@ -1411,7 +1441,7 @@ pub const Walker = struct { while (true) { if (self.stack.len == 0) return null; // `top` becomes invalid after appending to `self.stack`. - const top = &self.stack.toSlice()[self.stack.len - 1]; + const top = &self.stack.span()[self.stack.len - 1]; const dirname_len = top.dirname_len; if (try top.dir_it.next()) |base| { self.name_buffer.shrink(dirname_len); @@ -1432,8 +1462,8 @@ pub const Walker = struct { } return Entry{ .dir = top.dir_it.dir, - .basename = self.name_buffer.toSliceConst()[dirname_len + 1 ..], - .path = self.name_buffer.toSliceConst(), + .basename = self.name_buffer.span()[dirname_len + 1 ..], + .path = self.name_buffer.span(), .kind = base.kind, }; } else { @@ -1475,31 +1505,21 @@ pub fn walkPath(allocator: *Allocator, dir_path: []const u8) !Walker { return walker; } -/// Deprecated; use `Dir.readLink`. -pub fn readLink(pathname: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { - return os.readlink(pathname, buffer); -} - -/// Deprecated; use `Dir.readLinkC`. -pub fn readLinkC(pathname_c: [*]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 { - return os.readlinkC(pathname_c, buffer); -} - pub const OpenSelfExeError = os.OpenError || os.windows.CreateFileError || SelfExePathError; pub fn openSelfExe() OpenSelfExeError!File { if (builtin.os.tag == .linux) { - return openFileAbsoluteC("/proc/self/exe", .{}); + return openFileAbsoluteZ("/proc/self/exe", .{}); } if (builtin.os.tag == .windows) { const wide_slice = selfExePathW(); const prefixed_path_w = try os.windows.wToPrefixedFileW(wide_slice); - return cwd().openReadW(&prefixed_path_w); + return cwd().openFileW(&prefixed_path_w, .{}); } var buf: [MAX_PATH_BYTES]u8 = undefined; const self_exe_path = try selfExePath(&buf); buf[self_exe_path.len] = 0; - return openFileAbsoluteC(self_exe_path[0..self_exe_path.len :0].ptr, .{}); + return openFileAbsoluteZ(self_exe_path[0..self_exe_path.len :0].ptr, .{}); } test "openSelfExe" { @@ -1533,23 +1553,23 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 { var u32_len: u32 = out_buffer.len; const rc = std.c._NSGetExecutablePath(out_buffer, &u32_len); if (rc != 0) return error.NameTooLong; - return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer)); + return mem.spanZ(@ptrCast([*:0]u8, out_buffer)); } switch (builtin.os.tag) { - .linux => return os.readlinkC("/proc/self/exe", out_buffer), + .linux => return os.readlinkZ("/proc/self/exe", out_buffer), .freebsd, .dragonfly => { var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC, os.KERN_PROC_PATHNAME, -1 }; var out_len: usize = out_buffer.len; try os.sysctl(&mib, out_buffer, &out_len, null, 0); // TODO could this slice from 0 to out_len instead? - return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer)); + return mem.spanZ(@ptrCast([*:0]u8, out_buffer)); }, .netbsd => { var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC_ARGS, -1, os.KERN_PROC_PATHNAME }; var out_len: usize = out_buffer.len; try os.sysctl(&mib, out_buffer, &out_len, null, 0); // TODO could this slice from 0 to out_len instead? - return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer)); + return mem.spanZ(@ptrCast([*:0]u8, out_buffer)); }, .windows => { const utf16le_slice = selfExePathW(); @@ -1564,7 +1584,7 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 { /// The result is UTF16LE-encoded. pub fn selfExePathW() [:0]const u16 { const image_path_name = &os.windows.peb().ProcessParameters.ImagePathName; - return mem.toSliceConst(u16, @ptrCast([*:0]const u16, image_path_name.Buffer)); + return mem.spanZ(@ptrCast([*:0]const u16, image_path_name.Buffer)); } /// `selfExeDirPath` except allocates the result on the heap. diff --git a/lib/std/fs/file.zig b/lib/std/fs/file.zig index c4991a81ff..b158be0a9b 100644 --- a/lib/std/fs/file.zig +++ b/lib/std/fs/file.zig @@ -89,7 +89,7 @@ pub const File = struct { if (self.isTty()) { if (self.handle == os.STDOUT_FILENO or self.handle == os.STDERR_FILENO) { // Use getenvC to workaround https://github.com/ziglang/zig/issues/3511 - if (os.getenvC("TERM")) |term| { + if (os.getenvZ("TERM")) |term| { if (std.mem.eql(u8, term, "dumb")) return false; } diff --git a/lib/std/fs/get_app_data_dir.zig b/lib/std/fs/get_app_data_dir.zig index 31aab590d8..e104aa99e9 100644 --- a/lib/std/fs/get_app_data_dir.zig +++ b/lib/std/fs/get_app_data_dir.zig @@ -24,7 +24,7 @@ pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataD )) { os.windows.S_OK => { defer os.windows.ole32.CoTaskMemFree(@ptrCast(*c_void, dir_path_ptr)); - const global_dir = unicode.utf16leToUtf8Alloc(allocator, mem.toSliceConst(u16, dir_path_ptr)) catch |err| switch (err) { + const global_dir = unicode.utf16leToUtf8Alloc(allocator, mem.spanZ(dir_path_ptr)) catch |err| switch (err) { error.UnexpectedSecondSurrogateHalf => return error.AppDataDirUnavailable, error.ExpectedSecondSurrogateHalf => return error.AppDataDirUnavailable, error.DanglingSurrogateHalf => return error.AppDataDirUnavailable, diff --git a/lib/std/fs/path.zig b/lib/std/fs/path.zig index 35bc9b53b0..ba375645d5 100644 --- a/lib/std/fs/path.zig +++ b/lib/std/fs/path.zig @@ -128,11 +128,13 @@ test "join" { testJoinPosix(&[_][]const u8{ "a/", "/c" }, "a/c"); } -pub fn isAbsoluteC(path_c: [*:0]const u8) bool { +pub const isAbsoluteC = @compileError("deprecated: renamed to isAbsoluteZ"); + +pub fn isAbsoluteZ(path_c: [*:0]const u8) bool { if (builtin.os.tag == .windows) { - return isAbsoluteWindowsC(path_c); + return isAbsoluteWindowsZ(path_c); } else { - return isAbsolutePosixC(path_c); + return isAbsolutePosixZ(path_c); } } @@ -172,19 +174,23 @@ pub fn isAbsoluteWindows(path: []const u8) bool { } pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool { - return isAbsoluteWindowsImpl(u16, mem.toSliceConst(u16, path_w)); + return isAbsoluteWindowsImpl(u16, mem.spanZ(path_w)); } -pub fn isAbsoluteWindowsC(path_c: [*:0]const u8) bool { - return isAbsoluteWindowsImpl(u8, mem.toSliceConst(u8, path_c)); +pub const isAbsoluteWindowsC = @compileError("deprecated: renamed to isAbsoluteWindowsZ"); + +pub fn isAbsoluteWindowsZ(path_c: [*:0]const u8) bool { + return isAbsoluteWindowsImpl(u8, mem.spanZ(path_c)); } pub fn isAbsolutePosix(path: []const u8) bool { return path.len > 0 and path[0] == sep_posix; } -pub fn isAbsolutePosixC(path_c: [*:0]const u8) bool { - return isAbsolutePosix(mem.toSliceConst(u8, path_c)); +pub const isAbsolutePosixC = @compileError("deprecated: renamed to isAbsolutePosixZ"); + +pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool { + return isAbsolutePosix(mem.spanZ(path_c)); } test "isAbsoluteWindows" { diff --git a/lib/std/fs/watch.zig b/lib/std/fs/watch.zig index 96fe1538e4..8c5a983735 100644 --- a/lib/std/fs/watch.zig +++ b/lib/std/fs/watch.zig @@ -326,7 +326,7 @@ pub fn Watch(comptime V: type) type { var basename_with_null_consumed = false; defer if (!basename_with_null_consumed) self.allocator.free(basename_with_null); - const wd = try os.inotify_add_watchC( + const wd = try os.inotify_add_watchZ( self.os_data.inotify_fd, dirname_with_null.ptr, os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_EXCL_UNLINK, diff --git a/lib/std/heap.zig b/lib/std/heap.zig index 8c79249d4b..e4a409b218 100644 --- a/lib/std/heap.zig +++ b/lib/std/heap.zig @@ -51,8 +51,7 @@ var wasm_page_allocator_state = Allocator{ .shrinkFn = WasmPageAllocator.shrink, }; -/// Deprecated. Use `page_allocator`. -pub const direct_allocator = page_allocator; +pub const direct_allocator = @compileError("deprecated; use std.heap.page_allocator"); const PageAllocator = struct { fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 { diff --git a/lib/std/http/headers.zig b/lib/std/http/headers.zig index 1e1e71e3eb..a455843539 100644 --- a/lib/std/http/headers.zig +++ b/lib/std/http/headers.zig @@ -129,7 +129,7 @@ pub const Headers = struct { self.index.deinit(); } { - for (self.data.toSliceConst()) |entry| { + for (self.data.span()) |entry| { entry.deinit(); } self.data.deinit(); @@ -141,14 +141,14 @@ pub const Headers = struct { errdefer other.deinit(); try other.data.ensureCapacity(self.data.len); try other.index.initCapacity(self.index.entries.len); - for (self.data.toSliceConst()) |entry| { + for (self.data.span()) |entry| { try other.append(entry.name, entry.value, entry.never_index); } return other; } pub fn toSlice(self: Self) []const HeaderEntry { - return self.data.toSliceConst(); + return self.data.span(); } pub fn append(self: *Self, name: []const u8, value: []const u8, never_index: ?bool) !void { @@ -279,7 +279,7 @@ pub const Headers = struct { const buf = try allocator.alloc(HeaderEntry, dex.len); var n: usize = 0; - for (dex.toSliceConst()) |idx| { + for (dex.span()) |idx| { buf[n] = self.data.at(idx); n += 1; } @@ -302,7 +302,7 @@ pub const Headers = struct { // adapted from mem.join const total_len = blk: { var sum: usize = dex.len - 1; // space for separator(s) - for (dex.toSliceConst()) |idx| + for (dex.span()) |idx| sum += self.data.at(idx).value.len; break :blk sum; }; @@ -334,7 +334,7 @@ pub const Headers = struct { } } { // fill up indexes again; we know capacity is fine from before - for (self.data.toSliceConst()) |entry, i| { + for (self.data.span()) |entry, i| { var dex = &self.index.get(entry.name).?.value; dex.appendAssumeCapacity(i); } @@ -495,8 +495,8 @@ test "Headers.getIndices" { try h.append("set-cookie", "y=2", null); testing.expect(null == h.getIndices("not-present")); - testing.expectEqualSlices(usize, &[_]usize{0}, h.getIndices("foo").?.toSliceConst()); - testing.expectEqualSlices(usize, &[_]usize{ 1, 2 }, h.getIndices("set-cookie").?.toSliceConst()); + testing.expectEqualSlices(usize, &[_]usize{0}, h.getIndices("foo").?.span()); + testing.expectEqualSlices(usize, &[_]usize{ 1, 2 }, h.getIndices("set-cookie").?.span()); } test "Headers.get" { diff --git a/lib/std/io.zig b/lib/std/io.zig index 243dd5ca95..69cc4a923a 100644 --- a/lib/std/io.zig +++ b/lib/std/io.zig @@ -128,16 +128,6 @@ pub const BufferedAtomicFile = @import("io/buffered_atomic_file.zig").BufferedAt pub const StreamSource = @import("io/stream_source.zig").StreamSource; -/// Deprecated; use `std.fs.Dir.writeFile`. -pub fn writeFile(path: []const u8, data: []const u8) !void { - return fs.cwd().writeFile(path, data); -} - -/// Deprecated; use `std.fs.Dir.readFileAlloc`. -pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 { - return fs.cwd().readFileAlloc(allocator, path, math.maxInt(usize)); -} - /// An OutStream that doesn't write to anything. pub const null_out_stream = @as(NullOutStream, .{ .context = {} }); @@ -153,3 +143,6 @@ test "null_out_stream" { test "" { _ = @import("io/test.zig"); } + +pub const writeFile = @compileError("deprecated: use std.fs.Dir.writeFile with math.maxInt(usize)"); +pub const readFileAlloc = @compileError("deprecated: use std.fs.Dir.readFileAlloc"); diff --git a/lib/std/io/buffered_atomic_file.zig b/lib/std/io/buffered_atomic_file.zig index e2f8c75af0..b450a578ce 100644 --- a/lib/std/io/buffered_atomic_file.zig +++ b/lib/std/io/buffered_atomic_file.zig @@ -15,6 +15,7 @@ pub const BufferedAtomicFile = struct { /// TODO when https://github.com/ziglang/zig/issues/2761 is solved /// this API will not need an allocator + /// TODO integrate this with Dir API pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile { var self = try allocator.create(BufferedAtomicFile); self.* = BufferedAtomicFile{ @@ -25,7 +26,7 @@ pub const BufferedAtomicFile = struct { }; errdefer allocator.destroy(self); - self.atomic_file = try fs.AtomicFile.init(dest_path, File.default_mode); + self.atomic_file = try fs.cwd().atomicFile(dest_path, .{}); errdefer self.atomic_file.deinit(); self.file_stream = self.atomic_file.file.outStream(); diff --git a/lib/std/io/c_out_stream.zig b/lib/std/io/c_out_stream.zig index 106fc601a2..3b5e44bf75 100644 --- a/lib/std/io/c_out_stream.zig +++ b/lib/std/io/c_out_stream.zig @@ -36,7 +36,7 @@ test "" { const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile; defer { _ = std.c.fclose(out_file); - fs.cwd().deleteFileC(filename) catch {}; + fs.cwd().deleteFileZ(filename) catch {}; } const out_stream = &io.COutStream.init(out_file).stream; diff --git a/lib/std/io/in_stream.zig b/lib/std/io/in_stream.zig index d1d24ab427..045b0daae0 100644 --- a/lib/std/io/in_stream.zig +++ b/lib/std/io/in_stream.zig @@ -48,13 +48,7 @@ pub fn InStream( if (amt_read < buf.len) return error.EndOfStream; } - /// Deprecated: use `readAllArrayList`. - pub fn readAllBuffer(self: Self, buffer: *Buffer, max_size: usize) !void { - buffer.list.shrink(0); - try self.readAllArrayList(&buffer.list, max_size); - errdefer buffer.shrink(0); - try buffer.list.append(0); - } + pub const readAllBuffer = @compileError("deprecated; use readAllArrayList()"); /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found. /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned diff --git a/lib/std/json.zig b/lib/std/json.zig index 88f07d0aae..c127d962dd 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1944,7 +1944,7 @@ pub const Parser = struct { } fn pushToParent(p: *Parser, value: *const Value) !void { - switch (p.stack.toSlice()[p.stack.len - 1]) { + switch (p.stack.span()[p.stack.len - 1]) { // Object Parent -> [ ..., object, , value ] Value.String => |key| { _ = p.stack.pop(); diff --git a/lib/std/json/write_stream.zig b/lib/std/json/write_stream.zig index f4d171011c..cbe556dcfc 100644 --- a/lib/std/json/write_stream.zig +++ b/lib/std/json/write_stream.zig @@ -211,7 +211,7 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { .String => |inner| try self.emitString(inner), .Array => |inner| { try self.beginArray(); - for (inner.toSliceConst()) |elem| { + for (inner.span()) |elem| { try self.arrayElem(); try self.emitJson(elem); } diff --git a/lib/std/mem.zig b/lib/std/mem.zig index 446683abdb..d4d0a83f46 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -492,15 +492,8 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool { return true; } -/// Deprecated. Use `spanZ`. -pub fn toSliceConst(comptime T: type, ptr: [*:0]const T) [:0]const T { - return ptr[0..lenZ(ptr) :0]; -} - -/// Deprecated. Use `spanZ`. -pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T { - return ptr[0..lenZ(ptr) :0]; -} +pub const toSliceConst = @compileError("deprecated; use std.mem.spanZ"); +pub const toSlice = @compileError("deprecated; use std.mem.spanZ"); /// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and /// returns a slice. If there is a sentinel on the input type, there will be a diff --git a/lib/std/net.zig b/lib/std/net.zig index 74b5173c57..5b39b8cbd4 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -490,7 +490,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !* if (info.canonname) |n| { if (result.canon_name == null) { - result.canon_name = try mem.dupe(arena, u8, mem.toSliceConst(u8, n)); + result.canon_name = try mem.dupe(arena, u8, mem.spanZ(n)); } } i += 1; @@ -514,7 +514,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !* result.canon_name = canon.toOwnedSlice(); } - for (lookup_addrs.toSliceConst()) |lookup_addr, i| { + for (lookup_addrs.span()) |lookup_addr, i| { result.addrs[i] = lookup_addr.addr; assert(result.addrs[i].getPort() == port); } @@ -567,7 +567,7 @@ fn linuxLookupName( // No further processing is needed if there are fewer than 2 // results or if there are only IPv4 results. if (addrs.len == 1 or family == os.AF_INET) return; - const all_ip4 = for (addrs.toSliceConst()) |addr| { + const all_ip4 = for (addrs.span()) |addr| { if (addr.addr.any.family != os.AF_INET) break false; } else true; if (all_ip4) return; @@ -579,7 +579,7 @@ fn linuxLookupName( // So far the label/precedence table cannot be customized. // This implementation is ported from musl libc. // A more idiomatic "ziggy" implementation would be welcome. - for (addrs.toSlice()) |*addr, i| { + for (addrs.span()) |*addr, i| { var key: i32 = 0; var sa6: os.sockaddr_in6 = undefined; @memset(@ptrCast([*]u8, &sa6), 0, @sizeOf(os.sockaddr_in6)); @@ -644,7 +644,7 @@ fn linuxLookupName( key |= (MAXADDRS - @intCast(i32, i)) << DAS_ORDER_SHIFT; addr.sortkey = key; } - std.sort.sort(LookupAddr, addrs.toSlice(), addrCmpLessThan); + std.sort.sort(LookupAddr, addrs.span(), addrCmpLessThan); } const Policy = struct { @@ -803,7 +803,7 @@ fn linuxLookupNameFromHosts( family: os.sa_family_t, port: u16, ) !void { - const file = fs.openFileAbsoluteC("/etc/hosts", .{}) catch |err| switch (err) { + const file = fs.openFileAbsoluteZ("/etc/hosts", .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied, @@ -887,7 +887,7 @@ fn linuxLookupNameFromDnsSearch( const search = if (rc.search.isNull() or dots >= rc.ndots or mem.endsWith(u8, name, ".")) &[_]u8{} else - rc.search.toSliceConst(); + rc.search.span(); var canon_name = name; @@ -900,14 +900,14 @@ fn linuxLookupNameFromDnsSearch( // name is not a CNAME record) and serves as a buffer for passing // the full requested name to name_from_dns. try canon.resize(canon_name.len); - mem.copy(u8, canon.toSlice(), canon_name); + mem.copy(u8, canon.span(), canon_name); try canon.appendByte('.'); var tok_it = mem.tokenize(search, " \t"); while (tok_it.next()) |tok| { canon.shrink(canon_name.len + 1); try canon.append(tok); - try linuxLookupNameFromDns(addrs, canon, canon.toSliceConst(), family, rc, port); + try linuxLookupNameFromDns(addrs, canon, canon.span(), family, rc, port); if (addrs.len != 0) return; } @@ -1000,7 +1000,7 @@ fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void { }; errdefer rc.deinit(); - const file = fs.openFileAbsoluteC("/etc/resolv.conf", .{}) catch |err| switch (err) { + const file = fs.openFileAbsoluteZ("/etc/resolv.conf", .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.AccessDenied, @@ -1079,9 +1079,9 @@ fn resMSendRc( defer ns_list.deinit(); try ns_list.resize(rc.ns.len); - const ns = ns_list.toSlice(); + const ns = ns_list.span(); - for (rc.ns.toSliceConst()) |iplit, i| { + for (rc.ns.span()) |iplit, i| { ns[i] = iplit.addr; assert(ns[i].getPort() == 53); if (iplit.addr.any.family != os.AF_INET) { @@ -1265,7 +1265,7 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8) var tmp: [256]u8 = undefined; // Returns len of compressed name. strlen to get canon name. _ = try os.dn_expand(packet, data, &tmp); - const canon_name = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &tmp)); + const canon_name = mem.spanZ(@ptrCast([*:0]const u8, &tmp)); if (isValidHostName(canon_name)) { try ctx.canon.replaceContents(canon_name); } diff --git a/lib/std/os.zig b/lib/std/os.zig index dc032badea..f1184094db 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -163,7 +163,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void { } fn getRandomBytesDevURandom(buf: []u8) !void { - const fd = try openC("/dev/urandom", O_RDONLY | O_CLOEXEC, 0); + const fd = try openZ("/dev/urandom", O_RDONLY | O_CLOEXEC, 0); defer close(fd); const st = try fstat(fd); @@ -853,13 +853,15 @@ pub const OpenError = error{ /// TODO support windows pub fn open(file_path: []const u8, flags: u32, perm: usize) OpenError!fd_t { const file_path_c = try toPosixPath(file_path); - return openC(&file_path_c, flags, perm); + return openZ(&file_path_c, flags, perm); } +pub const openC = @compileError("deprecated: renamed to openZ"); + /// Open and possibly create a file. Keeps trying if it gets interrupted. /// See also `open`. /// TODO support windows -pub fn openC(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t { +pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t { while (true) { const rc = system.open(file_path, flags, perm); switch (errno(rc)) { @@ -895,14 +897,16 @@ pub fn openC(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t { /// TODO support windows pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: u32, mode: mode_t) OpenError!fd_t { const file_path_c = try toPosixPath(file_path); - return openatC(dir_fd, &file_path_c, flags, mode); + return openatZ(dir_fd, &file_path_c, flags, mode); } +pub const openatC = @compileError("deprecated: renamed to openatZ"); + /// Open and possibly create a file. Keeps trying if it gets interrupted. /// `file_path` is relative to the open directory handle `dir_fd`. /// See also `openat`. /// TODO support windows -pub fn openatC(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) OpenError!fd_t { +pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) OpenError!fd_t { while (true) { const rc = system.openat(dir_fd, file_path, flags, mode); switch (errno(rc)) { @@ -959,8 +963,7 @@ pub const ExecveError = error{ NameTooLong, } || UnexpectedError; -/// Deprecated in favor of `execveZ`. -pub const execveC = execveZ; +pub const execveC = @compileError("deprecated: use execveZ"); /// Like `execve` except the parameters are null-terminated, /// matching the syscall API on all targets. This removes the need for an allocator. @@ -992,8 +995,7 @@ pub fn execveZ( } } -/// Deprecated in favor of `execvpeZ`. -pub const execvpeC = execvpeZ; +pub const execvpeC = @compileError("deprecated in favor of execvpeZ"); pub const Arg0Expand = enum { expand, @@ -1012,7 +1014,7 @@ pub fn execvpeZ_expandArg0( }, envp: [*:null]const ?[*:0]const u8, ) ExecveError { - const file_slice = mem.toSliceConst(u8, file); + const file_slice = mem.spanZ(file); if (mem.indexOfScalar(u8, file_slice, '/') != null) return execveZ(file, child_argv, envp); const PATH = getenvZ("PATH") orelse "/usr/local/bin:/bin/:/usr/bin"; @@ -1076,7 +1078,7 @@ pub fn execvpe_expandArg0( mem.set(?[*:0]u8, argv_buf, null); defer { for (argv_buf) |arg| { - const arg_buf = if (arg) |ptr| mem.toSlice(u8, ptr) else break; + const arg_buf = if (arg) |ptr| mem.spanZ(ptr) else break; allocator.free(arg_buf); } allocator.free(argv_buf); @@ -1189,20 +1191,19 @@ pub fn getenv(key: []const u8) ?[]const u8 { return null; } -/// Deprecated in favor of `getenvZ`. -pub const getenvC = getenvZ; +pub const getenvC = @compileError("Deprecated in favor of `getenvZ`"); /// Get an environment variable with a null-terminated name. /// See also `getenv`. pub fn getenvZ(key: [*:0]const u8) ?[]const u8 { if (builtin.link_libc) { const value = system.getenv(key) orelse return null; - return mem.toSliceConst(u8, value); + return mem.spanZ(value); } if (builtin.os.tag == .windows) { @compileError("std.os.getenvZ is unavailable for Windows because environment string is in WTF-16 format. See std.process.getEnvVarOwned for cross-platform API or std.os.getenvW for Windows-specific API."); } - return getenv(mem.toSliceConst(u8, key)); + return getenv(mem.spanZ(key)); } /// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name. @@ -1211,7 +1212,7 @@ pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 { if (builtin.os.tag != .windows) { @compileError("std.os.getenvW is a Windows-only API"); } - const key_slice = mem.toSliceConst(u16, key); + const key_slice = mem.spanZ(key); const ptr = windows.peb().ProcessParameters.Environment; var i: usize = 0; while (ptr[i] != 0) { @@ -1250,7 +1251,7 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 { break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len)); }; switch (err) { - 0 => return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer.ptr)), + 0 => return mem.spanZ(@ptrCast([*:0]u8, out_buffer.ptr)), EFAULT => unreachable, EINVAL => unreachable, ENOENT => return error.CurrentWorkingDirectoryUnlinked, @@ -1288,13 +1289,15 @@ pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError! } else { const target_path_c = try toPosixPath(target_path); const sym_link_path_c = try toPosixPath(sym_link_path); - return symlinkC(&target_path_c, &sym_link_path_c); + return symlinkZ(&target_path_c, &sym_link_path_c); } } +pub const symlinkC = @compileError("deprecated: renamed to symlinkZ"); + /// This is the same as `symlink` except the parameters are null-terminated pointers. /// See also `symlink`. -pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void { +pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void { if (builtin.os.tag == .windows) { const target_path_w = try windows.cStrToPrefixedFileW(target_path); const sym_link_path_w = try windows.cStrToPrefixedFileW(sym_link_path); @@ -1323,10 +1326,12 @@ pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLin pub fn symlinkat(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void { const target_path_c = try toPosixPath(target_path); const sym_link_path_c = try toPosixPath(sym_link_path); - return symlinkatC(target_path_c, newdirfd, sym_link_path_c); + return symlinkatZ(target_path_c, newdirfd, sym_link_path_c); } -pub fn symlinkatC(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:0]const u8) SymLinkError!void { +pub const symlinkatC = @compileError("deprecated: renamed to symlinkatZ"); + +pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:0]const u8) SymLinkError!void { switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) { 0 => return, EFAULT => unreachable, @@ -1375,12 +1380,14 @@ pub fn unlink(file_path: []const u8) UnlinkError!void { return windows.DeleteFileW(&file_path_w); } else { const file_path_c = try toPosixPath(file_path); - return unlinkC(&file_path_c); + return unlinkZ(&file_path_c); } } +pub const unlinkC = @compileError("deprecated: renamed to unlinkZ"); + /// Same as `unlink` except the parameter is a null terminated UTF8-encoded string. -pub fn unlinkC(file_path: [*:0]const u8) UnlinkError!void { +pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void { if (builtin.os.tag == .windows) { const file_path_w = try windows.cStrToPrefixedFileW(file_path); return windows.DeleteFileW(&file_path_w); @@ -1417,11 +1424,13 @@ pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!vo return unlinkatW(dirfd, &file_path_w, flags); } const file_path_c = try toPosixPath(file_path); - return unlinkatC(dirfd, &file_path_c, flags); + return unlinkatZ(dirfd, &file_path_c, flags); } +pub const unlinkatC = @compileError("deprecated: renamed to unlinkatZ"); + /// Same as `unlinkat` but `file_path` is a null-terminated string. -pub fn unlinkatC(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void { +pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void { if (builtin.os.tag == .windows) { const file_path_w = try windows.cStrToPrefixedFileW(file_path_c); return unlinkatW(dirfd, &file_path_w, flags); @@ -1459,7 +1468,7 @@ pub fn unlinkatW(dirfd: fd_t, sub_path_w: [*:0]const u16, flags: u32) UnlinkatEr else @as(w.ULONG, w.FILE_DELETE_ON_CLOSE | w.FILE_NON_DIRECTORY_FILE); - const path_len_bytes = @intCast(u16, mem.toSliceConst(u16, sub_path_w).len * 2); + const path_len_bytes = @intCast(u16, mem.lenZ(sub_path_w) * 2); var nt_name = w.UNICODE_STRING{ .Length = path_len_bytes, .MaximumLength = path_len_bytes, @@ -1543,12 +1552,14 @@ pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void { } else { const old_path_c = try toPosixPath(old_path); const new_path_c = try toPosixPath(new_path); - return renameC(&old_path_c, &new_path_c); + return renameZ(&old_path_c, &new_path_c); } } +pub const renameC = @compileError("deprecated: renamed to renameZ"); + /// Same as `rename` except the parameters are null-terminated byte arrays. -pub fn renameC(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void { +pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void { if (builtin.os.tag == .windows) { const old_path_w = try windows.cStrToPrefixedFileW(old_path); const new_path_w = try windows.cStrToPrefixedFileW(new_path); @@ -1715,11 +1726,13 @@ pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!v return mkdiratW(dir_fd, &sub_dir_path_w, mode); } else { const sub_dir_path_c = try toPosixPath(sub_dir_path); - return mkdiratC(dir_fd, &sub_dir_path_c, mode); + return mkdiratZ(dir_fd, &sub_dir_path_c, mode); } } -pub fn mkdiratC(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirError!void { +pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ"); + +pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirError!void { if (builtin.os.tag == .windows) { const sub_dir_path_w = try windows.cStrToPrefixedFileW(sub_dir_path); return mkdiratW(dir_fd, &sub_dir_path_w, mode); @@ -1810,12 +1823,14 @@ pub fn rmdir(dir_path: []const u8) DeleteDirError!void { return windows.RemoveDirectoryW(&dir_path_w); } else { const dir_path_c = try toPosixPath(dir_path); - return rmdirC(&dir_path_c); + return rmdirZ(&dir_path_c); } } +pub const rmdirC = @compileError("deprecated: renamed to rmdirZ"); + /// Same as `rmdir` except the parameter is null-terminated. -pub fn rmdirC(dir_path: [*:0]const u8) DeleteDirError!void { +pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void { if (builtin.os.tag == .windows) { const dir_path_w = try windows.cStrToPrefixedFileW(dir_path); return windows.RemoveDirectoryW(&dir_path_w); @@ -1857,12 +1872,14 @@ pub fn chdir(dir_path: []const u8) ChangeCurDirError!void { @compileError("TODO implement chdir for Windows"); } else { const dir_path_c = try toPosixPath(dir_path); - return chdirC(&dir_path_c); + return chdirZ(&dir_path_c); } } +pub const chdirC = @compileError("deprecated: renamed to chdirZ"); + /// Same as `chdir` except the parameter is null-terminated. -pub fn chdirC(dir_path: [*:0]const u8) ChangeCurDirError!void { +pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void { if (builtin.os.tag == .windows) { const dir_path_w = try windows.cStrToPrefixedFileW(dir_path); @compileError("TODO implement chdir for Windows"); @@ -1919,12 +1936,14 @@ pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 { @compileError("TODO implement readlink for Windows"); } else { const file_path_c = try toPosixPath(file_path); - return readlinkC(&file_path_c, out_buffer); + return readlinkZ(&file_path_c, out_buffer); } } +pub const readlinkC = @compileError("deprecated: renamed to readlinkZ"); + /// Same as `readlink` except `file_path` is null-terminated. -pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 { +pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 { if (builtin.os.tag == .windows) { const file_path_w = try windows.cStrToPrefixedFileW(file_path); @compileError("TODO implement readlink for Windows"); @@ -1945,7 +1964,9 @@ pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 } } -pub fn readlinkatC(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 { +pub const readlinkatC = @compileError("deprecated: renamed to readlinkatZ"); + +pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 { if (builtin.os.tag == .windows) { const file_path_w = try windows.cStrToPrefixedFileW(file_path); @compileError("TODO implement readlink for Windows"); @@ -2553,10 +2574,12 @@ const FStatAtError = FStatError || error{NameTooLong}; pub fn fstatat(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError![]Stat { const pathname_c = try toPosixPath(pathname); - return fstatatC(dirfd, &pathname_c, flags); + return fstatatZ(dirfd, &pathname_c, flags); } -pub fn fstatatC(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!Stat { +pub const fstatatC = @compileError("deprecated: renamed to fstatatZ"); + +pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!Stat { var stat: Stat = undefined; switch (errno(system.fstatat(dirfd, pathname, &stat, flags))) { 0 => return stat, @@ -2668,11 +2691,13 @@ pub const INotifyAddWatchError = error{ /// add a watch to an initialized inotify instance pub fn inotify_add_watch(inotify_fd: i32, pathname: []const u8, mask: u32) INotifyAddWatchError!i32 { const pathname_c = try toPosixPath(pathname); - return inotify_add_watchC(inotify_fd, &pathname_c, mask); + return inotify_add_watchZ(inotify_fd, &pathname_c, mask); } +pub const inotify_add_watchC = @compileError("deprecated: renamed to inotify_add_watchZ"); + /// Same as `inotify_add_watch` except pathname is null-terminated. -pub fn inotify_add_watchC(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 { +pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 { const rc = system.inotify_add_watch(inotify_fd, pathname, mask); switch (errno(rc)) { 0 => return @intCast(i32, rc), @@ -2829,11 +2854,10 @@ pub fn access(path: []const u8, mode: u32) AccessError!void { return; } const path_c = try toPosixPath(path); - return accessC(&path_c, mode); + return accessZ(&path_c, mode); } -/// Deprecated in favor of `accessZ`. -pub const accessC = accessZ; +pub const accessC = @compileError("Deprecated in favor of `accessZ`"); /// Same as `access` except `path` is null-terminated. pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void { @@ -2920,7 +2944,7 @@ pub fn faccessatW(dirfd: fd_t, sub_path_w: [*:0]const u16, mode: u32, flags: u32 return; } - const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) { + const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) { error.Overflow => return error.NameTooLong, }; var nt_name = windows.UNICODE_STRING{ @@ -3019,7 +3043,9 @@ pub fn sysctl( } } -pub fn sysctlbynameC( +pub const sysctlbynameC = @compileError("deprecated: renamed to sysctlbynameZ"); + +pub fn sysctlbynameZ( name: [*:0]const u8, oldp: ?*c_void, oldlenp: ?*usize, @@ -3224,23 +3250,25 @@ pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathE return realpathW(&pathname_w, out_buffer); } const pathname_c = try toPosixPath(pathname); - return realpathC(&pathname_c, out_buffer); + return realpathZ(&pathname_c, out_buffer); } +pub const realpathC = @compileError("deprecated: renamed realpathZ"); + /// Same as `realpath` except `pathname` is null-terminated. -pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 { +pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 { if (builtin.os.tag == .windows) { const pathname_w = try windows.cStrToPrefixedFileW(pathname); return realpathW(&pathname_w, out_buffer); } if (builtin.os.tag == .linux and !builtin.link_libc) { - const fd = try openC(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0); + const fd = try openZ(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0); defer close(fd); var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined; const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", .{fd}) catch unreachable; - return readlinkC(@ptrCast([*:0]const u8, proc_path.ptr), out_buffer); + return readlinkZ(@ptrCast([*:0]const u8, proc_path.ptr), out_buffer); } const result_path = std.c.realpath(pathname, out_buffer) orelse switch (std.c._errno().*) { EINVAL => unreachable, @@ -3255,7 +3283,7 @@ pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP EIO => return error.InputOutput, else => |err| return unexpectedErrno(@intCast(usize, err)), }; - return mem.toSlice(u8, result_path); + return mem.spanZ(result_path); } /// Same as `realpath` except `pathname` is null-terminated and UTF16LE-encoded. @@ -3564,7 +3592,7 @@ pub const GetHostNameError = error{PermissionDenied} || UnexpectedError; pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 { if (builtin.link_libc) { switch (errno(system.gethostname(name_buffer, name_buffer.len))) { - 0 => return mem.toSlice(u8, @ptrCast([*:0]u8, name_buffer)), + 0 => return mem.spanZ(@ptrCast([*:0]u8, name_buffer)), EFAULT => unreachable, ENAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this EPERM => return error.PermissionDenied, @@ -3573,7 +3601,7 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 { } if (builtin.os.tag == .linux) { const uts = uname(); - const hostname = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &uts.nodename)); + const hostname = mem.spanZ(@ptrCast([*:0]const u8, &uts.nodename)); mem.copy(u8, name_buffer, hostname); return name_buffer[0..hostname.len]; } @@ -4260,7 +4288,9 @@ pub const MemFdCreateError = error{ SystemOutdated, } || UnexpectedError; -pub fn memfd_createC(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t { +pub const memfd_createC = @compileError("deprecated: renamed to memfd_createZ"); + +pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t { // memfd_create is available only in glibc versions starting with 2.27. const use_c = std.c.versionCheck(.{ .major = 2, .minor = 27, .patch = 0 }).ok; const sys = if (use_c) std.c else linux; @@ -4291,7 +4321,7 @@ fn toMemFdPath(name: []const u8) ![MFD_MAX_NAME_LEN:0]u8 { pub fn memfd_create(name: []const u8, flags: u32) !fd_t { const name_t = try toMemFdPath(name); - return memfd_createC(&name_t, flags); + return memfd_createZ(&name_t, flags); } pub fn getrusage(who: i32) rusage { diff --git a/lib/std/os/linux/vdso.zig b/lib/std/os/linux/vdso.zig index beb98a063d..27c56d6c42 100644 --- a/lib/std/os/linux/vdso.zig +++ b/lib/std/os/linux/vdso.zig @@ -22,7 +22,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { }) { const this_ph = @intToPtr(*elf.Phdr, ph_addr); switch (this_ph.p_type) { - // On WSL1 as well as older kernels, the VDSO ELF image is pre-linked in the upper half + // On WSL1 as well as older kernels, the VDSO ELF image is pre-linked in the upper half // of the memory space (e.g. p_vaddr = 0xffffffffff700000 on WSL1). // Wrapping operations are used on this line as well as subsequent calculations relative to base // (lines 47, 78) to ensure no overflow check is tripped. @@ -70,7 +70,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == syms[i].st_shndx) continue; const sym_name = @ptrCast([*:0]const u8, strings + syms[i].st_name); - if (!mem.eql(u8, name, mem.toSliceConst(u8, sym_name))) continue; + if (!mem.eql(u8, name, mem.spanZ(sym_name))) continue; if (maybe_versym) |versym| { if (!checkver(maybe_verdef.?, versym[i], vername, strings)) continue; @@ -93,5 +93,5 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [ } const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux); const vda_name = @ptrCast([*:0]const u8, strings + aux.vda_name); - return mem.eql(u8, vername, mem.toSliceConst(u8, vda_name)); + return mem.eql(u8, vername, mem.spanZ(vda_name)); } diff --git a/lib/std/os/test.zig b/lib/std/os/test.zig index 154932d9c5..9c5ee44e88 100644 --- a/lib/std/os/test.zig +++ b/lib/std/os/test.zig @@ -18,8 +18,8 @@ const AtomicOrder = builtin.AtomicOrder; test "makePath, put some files in it, deleteTree" { try fs.cwd().makePath("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c"); - try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense"); - try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah"); + try fs.cwd().writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense"); + try fs.cwd().writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah"); try fs.cwd().deleteTree("os_test_tmp"); if (fs.cwd().openDir("os_test_tmp", .{})) |dir| { @panic("expected error"); @@ -36,8 +36,8 @@ test "access file" { expect(err == error.FileNotFound); } - try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", ""); - try os.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", os.F_OK); + try fs.cwd().writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", ""); + try fs.cwd().access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{}); try fs.cwd().deleteTree("os_test_tmp"); } @@ -65,12 +65,12 @@ test "sendfile" { }, }; - var src_file = try dir.createFileC("sendfile1.txt", .{ .read = true }); + var src_file = try dir.createFileZ("sendfile1.txt", .{ .read = true }); defer src_file.close(); try src_file.writevAll(&vecs); - var dest_file = try dir.createFileC("sendfile2.txt", .{ .read = true }); + var dest_file = try dir.createFileZ("sendfile2.txt", .{ .read = true }); defer dest_file.close(); const header1 = "header1\n"; @@ -192,12 +192,12 @@ test "AtomicFile" { \\ this is a test file ; { - var af = try fs.AtomicFile.init(test_out_file, File.default_mode); + var af = try fs.cwd().atomicFile(test_out_file, .{}); defer af.deinit(); try af.file.writeAll(test_content); try af.finish(); } - const content = try io.readFileAlloc(testing.allocator, test_out_file); + const content = try fs.cwd().readFileAlloc(testing.allocator, test_out_file, 9999); defer testing.allocator.free(content); expect(mem.eql(u8, content, test_content)); diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index b65d80fb7a..f6186acc8d 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -118,7 +118,7 @@ pub fn OpenFileW( var result: HANDLE = undefined; - const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) { + const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) { error.Overflow => return error.NameTooLong, }; var nt_name = UNICODE_STRING{ @@ -685,7 +685,7 @@ pub fn CreateDirectoryW( sub_path_w: [*:0]const u16, sa: ?*SECURITY_ATTRIBUTES, ) CreateDirectoryError!HANDLE { - const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) { + const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) { error.Overflow => return error.NameTooLong, }; var nt_name = UNICODE_STRING{ @@ -1214,7 +1214,7 @@ pub fn nanoSecondsToFileTime(ns: i64) FILETIME { } pub fn cStrToPrefixedFileW(s: [*:0]const u8) ![PATH_MAX_WIDE:0]u16 { - return sliceToPrefixedFileW(mem.toSliceConst(u8, s)); + return sliceToPrefixedFileW(mem.spanZ(s)); } pub fn sliceToPrefixedFileW(s: []const u8) ![PATH_MAX_WIDE:0]u16 { diff --git a/lib/std/pdb.zig b/lib/std/pdb.zig index 93fef0b16d..422a51a800 100644 --- a/lib/std/pdb.zig +++ b/lib/std/pdb.zig @@ -649,7 +649,7 @@ const MsfStream = struct { while (true) { const byte = try self.inStream().readByte(); if (byte == 0) { - return list.toSlice(); + return list.span(); } try list.append(byte); } diff --git a/lib/std/process.zig b/lib/std/process.zig index 084aec4c49..89e9cea8d6 100644 --- a/lib/std/process.zig +++ b/lib/std/process.zig @@ -83,7 +83,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { for (environ) |env| { if (env) |ptr| { - const pair = mem.toSlice(u8, ptr); + const pair = mem.spanZ(ptr); var parts = mem.separate(pair, "="); const key = parts.next().?; const value = parts.next().?; @@ -176,7 +176,7 @@ pub const ArgIteratorPosix = struct { const s = os.argv[self.index]; self.index += 1; - return mem.toSlice(u8, s); + return mem.spanZ(s); } pub fn skip(self: *ArgIteratorPosix) bool { @@ -401,7 +401,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 { var i: usize = 0; while (i < count) : (i += 1) { - result_slice[i] = mem.toSlice(u8, argv[i]); + result_slice[i] = mem.spanZ(argv[i]); } return result_slice; @@ -422,8 +422,8 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 { try slice_list.append(arg.len); } - const contents_slice = contents.toSliceConst(); - const slice_sizes = slice_list.toSliceConst(); + const contents_slice = contents.span(); + const slice_sizes = slice_list.span(); const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len); const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len); const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes); @@ -636,7 +636,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0] fn callback(info: *os.dl_phdr_info, size: usize, list: *List) !void { const name = info.dlpi_name orelse return; if (name[0] == '/') { - const item = try mem.dupeZ(list.allocator, u8, mem.toSliceConst(u8, name)); + const item = try mem.dupeZ(list.allocator, u8, mem.spanZ(name)); errdefer list.allocator.free(item); try list.append(item); } @@ -657,7 +657,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0] var i: u32 = 0; while (i < img_count) : (i += 1) { const name = std.c._dyld_get_image_name(i); - const item = try mem.dupeZ(allocator, u8, mem.toSliceConst(u8, name)); + const item = try mem.dupeZ(allocator, u8, mem.spanZ(name)); errdefer allocator.free(item); try paths.append(item); } diff --git a/lib/std/rand.zig b/lib/std/rand.zig index ede46e3065..5b4655bc5d 100644 --- a/lib/std/rand.zig +++ b/lib/std/rand.zig @@ -59,7 +59,7 @@ pub const Random = struct { return @bitCast(T, unsigned_result); } - /// Constant-time implementation off ::uintLessThan. + /// Constant-time implementation off `uintLessThan`. /// The results of this function may be biased. pub fn uintLessThanBiased(r: *Random, comptime T: type, less_than: T) T { comptime assert(T.is_signed == false); @@ -73,13 +73,13 @@ pub const Random = struct { } /// Returns an evenly distributed random unsigned integer `0 <= i < less_than`. - /// This function assumes that the underlying ::fillFn produces evenly distributed values. + /// This function assumes that the underlying `fillFn` produces evenly distributed values. /// Within this assumption, the runtime of this function is exponentially distributed. - /// If ::fillFn were backed by a true random generator, + /// If `fillFn` were backed by a true random generator, /// the runtime of this function would technically be unbounded. - /// However, if ::fillFn is backed by any evenly distributed pseudo random number generator, + /// However, if `fillFn` is backed by any evenly distributed pseudo random number generator, /// this function is guaranteed to return. - /// If you need deterministic runtime bounds, use `::uintLessThanBiased`. + /// If you need deterministic runtime bounds, use `uintLessThanBiased`. pub fn uintLessThan(r: *Random, comptime T: type, less_than: T) T { comptime assert(T.is_signed == false); comptime assert(T.bit_count <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation! @@ -116,7 +116,7 @@ pub const Random = struct { return @intCast(T, m >> Small.bit_count); } - /// Constant-time implementation off ::uintAtMost. + /// Constant-time implementation off `uintAtMost`. /// The results of this function may be biased. pub fn uintAtMostBiased(r: *Random, comptime T: type, at_most: T) T { assert(T.is_signed == false); @@ -128,7 +128,7 @@ pub const Random = struct { } /// Returns an evenly distributed random unsigned integer `0 <= i <= at_most`. - /// See ::uintLessThan, which this function uses in most cases, + /// See `uintLessThan`, which this function uses in most cases, /// for commentary on the runtime of this function. pub fn uintAtMost(r: *Random, comptime T: type, at_most: T) T { assert(T.is_signed == false); @@ -139,7 +139,7 @@ pub const Random = struct { return r.uintLessThan(T, at_most + 1); } - /// Constant-time implementation off ::intRangeLessThan. + /// Constant-time implementation off `intRangeLessThan`. /// The results of this function may be biased. pub fn intRangeLessThanBiased(r: *Random, comptime T: type, at_least: T, less_than: T) T { assert(at_least < less_than); @@ -157,7 +157,7 @@ pub const Random = struct { } /// Returns an evenly distributed random integer `at_least <= i < less_than`. - /// See ::uintLessThan, which this function uses in most cases, + /// See `uintLessThan`, which this function uses in most cases, /// for commentary on the runtime of this function. pub fn intRangeLessThan(r: *Random, comptime T: type, at_least: T, less_than: T) T { assert(at_least < less_than); @@ -174,7 +174,7 @@ pub const Random = struct { } } - /// Constant-time implementation off ::intRangeAtMostBiased. + /// Constant-time implementation off `intRangeAtMostBiased`. /// The results of this function may be biased. pub fn intRangeAtMostBiased(r: *Random, comptime T: type, at_least: T, at_most: T) T { assert(at_least <= at_most); @@ -192,7 +192,7 @@ pub const Random = struct { } /// Returns an evenly distributed random integer `at_least <= i <= at_most`. - /// See ::uintLessThan, which this function uses in most cases, + /// See `uintLessThan`, which this function uses in most cases, /// for commentary on the runtime of this function. pub fn intRangeAtMost(r: *Random, comptime T: type, at_least: T, at_most: T) T { assert(at_least <= at_most); @@ -209,15 +209,9 @@ pub const Random = struct { } } - /// TODO: deprecated. use ::boolean or ::int instead. - pub fn scalar(r: *Random, comptime T: type) T { - return if (T == bool) r.boolean() else r.int(T); - } + pub const scalar = @compileError("deprecated; use boolean() or int() instead"); - /// TODO: deprecated. renamed to ::intRangeLessThan - pub fn range(r: *Random, comptime T: type, start: T, end: T) T { - return r.intRangeLessThan(T, start, end); - } + pub const range = @compileError("deprecated; use intRangeLessThan()"); /// Return a floating point value evenly distributed in the range [0, 1). pub fn float(r: *Random, comptime T: type) T { diff --git a/lib/std/sort.zig b/lib/std/sort.zig index 938c5e98f1..3447a05769 100644 --- a/lib/std/sort.zig +++ b/lib/std/sort.zig @@ -1227,13 +1227,13 @@ test "sort fuzz testing" { var fixed_buffer_mem: [100 * 1024]u8 = undefined; fn fuzzTest(rng: *std.rand.Random) !void { - const array_size = rng.range(usize, 0, 1000); + const array_size = rng.intRangeLessThan(usize, 0, 1000); var array = try testing.allocator.alloc(IdAndValue, array_size); defer testing.allocator.free(array); // populate with random data for (array) |*item, index| { item.id = index; - item.value = rng.range(i32, 0, 100); + item.value = rng.intRangeLessThan(i32, 0, 100); } sort(IdAndValue, array, cmpByValue); diff --git a/lib/std/special/build_runner.zig b/lib/std/special/build_runner.zig index 974247e2a1..665d47c1bd 100644 --- a/lib/std/special/build_runner.zig +++ b/lib/std/special/build_runner.zig @@ -116,7 +116,7 @@ pub fn main() !void { if (builder.validateUserInputDidItFail()) return usageAndErr(builder, true, stderr_stream); - builder.make(targets.toSliceConst()) catch |err| { + builder.make(targets.span()) catch |err| { switch (err) { error.InvalidStepName => { return usageAndErr(builder, true, stderr_stream); @@ -151,7 +151,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void { , .{builder.zig_exe}); const allocator = builder.allocator; - for (builder.top_level_steps.toSliceConst()) |top_level_step| { + for (builder.top_level_steps.span()) |top_level_step| { const name = if (&top_level_step.step == builder.default_step) try fmt.allocPrint(allocator, "{} (default)", .{top_level_step.step.name}) else @@ -174,7 +174,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void { if (builder.available_options_list.len == 0) { try out_stream.print(" (none)\n", .{}); } else { - for (builder.available_options_list.toSliceConst()) |option| { + for (builder.available_options_list.span()) |option| { const name = try fmt.allocPrint(allocator, " -D{}=[{}]", .{ option.name, Builder.typeIdName(option.type_id), diff --git a/lib/std/thread.zig b/lib/std/thread.zig index e11d13d4a8..5f6fb5abae 100644 --- a/lib/std/thread.zig +++ b/lib/std/thread.zig @@ -464,7 +464,7 @@ pub const Thread = struct { var count: c_int = undefined; var count_len: usize = @sizeOf(c_int); const name = if (comptime std.Target.current.isDarwin()) "hw.logicalcpu" else "hw.ncpu"; - os.sysctlbynameC(name, &count, &count_len, null, 0) catch |err| switch (err) { + os.sysctlbynameZ(name, &count, &count_len, null, 0) catch |err| switch (err) { error.NameTooLong, error.UnknownName => unreachable, else => |e| return e, }; diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index c5e5201680..1fe02dce08 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -1531,7 +1531,7 @@ fn renderExpression( try renderToken(tree, stream, callconv_rparen, indent, start_col, Space.Space); // ) } else if (cc_rewrite_str) |str| { try stream.writeAll("callconv("); - try stream.writeAll(mem.toSliceConst(u8, str)); + try stream.writeAll(mem.spanZ(str)); try stream.writeAll(") "); } diff --git a/lib/std/zig/system.zig b/lib/std/zig/system.zig index 5c47b68838..1da2002f95 100644 --- a/lib/std/zig/system.zig +++ b/lib/std/zig/system.zig @@ -119,7 +119,7 @@ pub const NativePaths = struct { } fn deinitArray(array: *ArrayList([:0]u8)) void { - for (array.toSlice()) |item| { + for (array.span()) |item| { array.allocator.free(item); } array.deinit(); @@ -201,7 +201,7 @@ pub const NativeTargetInfo = struct { switch (Target.current.os.tag) { .linux => { const uts = std.os.uname(); - const release = mem.toSliceConst(u8, &uts.release); + const release = mem.spanZ(&uts.release); // The release field may have several other fields after the // kernel version const kernel_version = if (mem.indexOfScalar(u8, release, '-')) |pos| @@ -265,7 +265,7 @@ pub const NativeTargetInfo = struct { // The osproductversion sysctl was introduced first with // High Sierra, thankfully that's also the baseline that Zig // supports - std.os.sysctlbynameC( + std.os.sysctlbynameZ( "kern.osproductversion", &product_version, &size, @@ -460,7 +460,7 @@ pub const NativeTargetInfo = struct { return result; } - const env_file = std.fs.openFileAbsoluteC("/usr/bin/env", .{}) catch |err| switch (err) { + const env_file = std.fs.openFileAbsoluteZ("/usr/bin/env", .{}) catch |err| switch (err) { error.NoSpaceLeft => unreachable, error.NameTooLong => unreachable, error.PathAlreadyExists => unreachable, @@ -512,7 +512,7 @@ pub const NativeTargetInfo = struct { fn glibcVerFromSO(so_path: [:0]const u8) !std.builtin.Version { var link_buf: [std.os.PATH_MAX]u8 = undefined; - const link_name = std.os.readlinkC(so_path.ptr, &link_buf) catch |err| switch (err) { + const link_name = std.os.readlinkZ(so_path.ptr, &link_buf) catch |err| switch (err) { error.AccessDenied => return error.GnuLibCVersionUnavailable, error.FileSystem => return error.FileSystem, error.SymLinkLoop => return error.SymLinkLoop, @@ -736,7 +736,7 @@ pub const NativeTargetInfo = struct { ); const sh_name_off = elfInt(is_64, need_bswap, sh32.sh_name, sh64.sh_name); // TODO this pointer cast should not be necessary - const sh_name = mem.toSliceConst(u8, @ptrCast([*:0]u8, shstrtab[sh_name_off..].ptr)); + const sh_name = mem.spanZ(@ptrCast([*:0]u8, shstrtab[sh_name_off..].ptr)); if (mem.eql(u8, sh_name, ".dynstr")) { break :find_dyn_str .{ .offset = elfInt(is_64, need_bswap, sh32.sh_offset, sh64.sh_offset), @@ -751,7 +751,7 @@ pub const NativeTargetInfo = struct { const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, shstrtab_len); const strtab = strtab_buf[0..strtab_read_len]; // TODO this pointer cast should not be necessary - const rpath_list = mem.toSliceConst(u8, @ptrCast([*:0]u8, strtab[rpoff..].ptr)); + const rpath_list = mem.spanZ(@ptrCast([*:0]u8, strtab[rpoff..].ptr)); var it = mem.tokenize(rpath_list, ":"); while (it.next()) |rpath| { var dir = fs.cwd().openDir(rpath, .{}) catch |err| switch (err) { @@ -776,7 +776,7 @@ pub const NativeTargetInfo = struct { defer dir.close(); var link_buf: [std.os.PATH_MAX]u8 = undefined; - const link_name = std.os.readlinkatC( + const link_name = std.os.readlinkatZ( dir.fd, glibc_so_basename, &link_buf, diff --git a/src-self-hosted/codegen.zig b/src-self-hosted/codegen.zig index 74eff90dc8..e10d66d1f6 100644 --- a/src-self-hosted/codegen.zig +++ b/src-self-hosted/codegen.zig @@ -25,10 +25,10 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) const context = llvm_handle.node.data; - const module = llvm.ModuleCreateWithNameInContext(comp.name.toSliceConst(), context) orelse return error.OutOfMemory; + const module = llvm.ModuleCreateWithNameInContext(comp.name.span(), context) orelse return error.OutOfMemory; defer llvm.DisposeModule(module); - llvm.SetTarget(module, comp.llvm_triple.toSliceConst()); + llvm.SetTarget(module, comp.llvm_triple.span()); llvm.SetDataLayout(module, comp.target_layout_str); if (comp.target.getObjectFormat() == .coff) { @@ -54,15 +54,15 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) const runtime_version = 0; const compile_unit_file = llvm.CreateFile( dibuilder, - comp.name.toSliceConst(), - comp.root_package.root_src_dir.toSliceConst(), + comp.name.span(), + comp.root_package.root_src_dir.span(), ) orelse return error.OutOfMemory; const is_optimized = comp.build_mode != .Debug; const compile_unit = llvm.CreateCompileUnit( dibuilder, DW.LANG_C99, compile_unit_file, - producer.toSliceConst(), + producer.span(), is_optimized, flags, runtime_version, @@ -109,14 +109,14 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) if (llvm.TargetMachineEmitToFile( comp.target_machine, module, - output_path.toSliceConst(), + output_path.span(), llvm.EmitBinary, &err_msg, is_debug, is_small, )) { if (std.debug.runtime_safety) { - std.debug.panic("unable to write object file {}: {s}\n", .{ output_path.toSliceConst(), err_msg }); + std.debug.panic("unable to write object file {}: {s}\n", .{ output_path.span(), err_msg }); } return error.WritingObjectFileFailed; } @@ -127,7 +127,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) llvm.DumpModule(ofile.module); } if (comp.verbose_link) { - std.debug.warn("created {}\n", .{output_path.toSliceConst()}); + std.debug.warn("created {}\n", .{output_path.span()}); } } @@ -150,7 +150,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code) const llvm_fn_type = try fn_val.base.typ.getLlvmType(ofile.arena, ofile.context); const llvm_fn = llvm.AddFunction( ofile.module, - fn_val.symbol_name.toSliceConst(), + fn_val.symbol_name.span(), llvm_fn_type, ) orelse return error.OutOfMemory; @@ -211,7 +211,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code) const cur_ret_ptr = if (fn_type_normal.return_type.handleIsPtr()) llvm.GetParam(llvm_fn, 0) else null; // build all basic blocks - for (code.basic_block_list.toSlice()) |bb| { + for (code.basic_block_list.span()) |bb| { bb.llvm_block = llvm.AppendBasicBlockInContext( ofile.context, llvm_fn, @@ -226,7 +226,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code) // TODO set up error return tracing // TODO allocate temporary stack values - const var_list = fn_type.non_key.Normal.variable_list.toSliceConst(); + const var_list = fn_type.non_key.Normal.variable_list.span(); // create debug variable declarations for variables and allocate all local variables for (var_list) |var_scope, i| { const var_type = switch (var_scope.data) { @@ -306,9 +306,9 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code) //} } - for (code.basic_block_list.toSlice()) |current_block| { + for (code.basic_block_list.span()) |current_block| { llvm.PositionBuilderAtEnd(ofile.builder, current_block.llvm_block); - for (current_block.instruction_list.toSlice()) |instruction| { + for (current_block.instruction_list.span()) |instruction| { if (instruction.ref_count == 0 and !instruction.hasSideEffects()) continue; instruction.llvm_value = try instruction.render(ofile, fn_val); diff --git a/src-self-hosted/compilation.zig b/src-self-hosted/compilation.zig index 03e71c102d..5e2b9ad899 100644 --- a/src-self-hosted/compilation.zig +++ b/src-self-hosted/compilation.zig @@ -465,7 +465,7 @@ pub const Compilation = struct { comp.target_machine = llvm.CreateTargetMachine( comp.llvm_target, - comp.llvm_triple.toSliceConst(), + comp.llvm_triple.span(), target_specific_cpu_args orelse "", target_specific_cpu_features orelse "", opt_level, @@ -1106,7 +1106,7 @@ pub const Compilation = struct { } } - for (self.link_libs_list.toSliceConst()) |existing_lib| { + for (self.link_libs_list.span()) |existing_lib| { if (mem.eql(u8, name, existing_lib.name)) { return existing_lib; } @@ -1371,7 +1371,7 @@ fn analyzeFnType( var params = ArrayList(Type.Fn.Param).init(comp.gpa()); var params_consumed = false; defer if (!params_consumed) { - for (params.toSliceConst()) |param| { + for (params.span()) |param| { param.typ.base.deref(comp); } params.deinit(); diff --git a/src-self-hosted/dep_tokenizer.zig b/src-self-hosted/dep_tokenizer.zig index e0c67694e1..6eba0c759c 100644 --- a/src-self-hosted/dep_tokenizer.zig +++ b/src-self-hosted/dep_tokenizer.zig @@ -89,7 +89,7 @@ pub const Tokenizer = struct { }, .target_colon => |*target| switch (char) { '\n', '\r' => { - const bytes = target.toSlice(); + const bytes = target.span(); if (bytes.len != 0) { self.state = State{ .lhs = {} }; return Token{ .id = .target, .bytes = bytes }; @@ -103,7 +103,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - const bytes = target.toSlice(); + const bytes = target.span(); if (bytes.len != 0) { self.state = State{ .rhs = {} }; return Token{ .id = .target, .bytes = bytes }; @@ -115,7 +115,7 @@ pub const Tokenizer = struct { }, .target_colon_reverse_solidus => |*target| switch (char) { '\n', '\r' => { - const bytes = target.toSlice(); + const bytes = target.span(); if (bytes.len != 0) { self.state = State{ .lhs = {} }; return Token{ .id = .target, .bytes = bytes }; @@ -175,7 +175,7 @@ pub const Tokenizer = struct { }, .prereq_quote => |*prereq| switch (char) { '"' => { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.index += 1; self.state = State{ .rhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; @@ -187,12 +187,12 @@ pub const Tokenizer = struct { }, .prereq => |*prereq| switch (char) { '\t', ' ' => { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.state = State{ .rhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; }, '\n', '\r' => { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.state = State{ .lhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; }, @@ -207,7 +207,7 @@ pub const Tokenizer = struct { }, .prereq_continuation => |*prereq| switch (char) { '\n' => { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.index += 1; self.state = State{ .rhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; @@ -225,7 +225,7 @@ pub const Tokenizer = struct { }, .prereq_continuation_linefeed => |prereq| switch (char) { '\n' => { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.index += 1; self.state = State{ .rhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; @@ -249,7 +249,7 @@ pub const Tokenizer = struct { .rhs_continuation_linefeed, => {}, .target => |target| { - return self.errorPosition(idx, target.toSlice(), "incomplete target", .{}); + return self.errorPosition(idx, target.span(), "incomplete target", .{}); }, .target_reverse_solidus, .target_dollar_sign, @@ -258,7 +258,7 @@ pub const Tokenizer = struct { return self.errorIllegalChar(idx, self.bytes[idx], "incomplete escape", .{}); }, .target_colon => |target| { - const bytes = target.toSlice(); + const bytes = target.span(); if (bytes.len != 0) { self.index += 1; self.state = State{ .rhs = {} }; @@ -268,7 +268,7 @@ pub const Tokenizer = struct { self.state = State{ .lhs = {} }; }, .target_colon_reverse_solidus => |target| { - const bytes = target.toSlice(); + const bytes = target.span(); if (bytes.len != 0) { self.index += 1; self.state = State{ .rhs = {} }; @@ -278,20 +278,20 @@ pub const Tokenizer = struct { self.state = State{ .lhs = {} }; }, .prereq_quote => |prereq| { - return self.errorPosition(idx, prereq.toSlice(), "incomplete quoted prerequisite", .{}); + return self.errorPosition(idx, prereq.span(), "incomplete quoted prerequisite", .{}); }, .prereq => |prereq| { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.state = State{ .lhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; }, .prereq_continuation => |prereq| { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.state = State{ .lhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; }, .prereq_continuation_linefeed => |prereq| { - const bytes = prereq.toSlice(); + const bytes = prereq.span(); self.state = State{ .lhs = {} }; return Token{ .id = .prereq, .bytes = bytes }; }, @@ -300,7 +300,7 @@ pub const Tokenizer = struct { } fn errorf(self: *Tokenizer, comptime fmt: []const u8, args: var) Error { - self.error_text = (try std.Buffer.allocPrint(&self.arena.allocator, fmt, args)).toSlice(); + self.error_text = (try std.Buffer.allocPrint(&self.arena.allocator, fmt, args)).span(); return Error.InvalidInput; } @@ -312,7 +312,7 @@ pub const Tokenizer = struct { try printCharValues(&out, bytes); try buffer.append("'"); try buffer.outStream().print(" at position {}", .{position - (bytes.len - 1)}); - self.error_text = buffer.toSlice(); + self.error_text = buffer.span(); return Error.InvalidInput; } @@ -322,7 +322,7 @@ pub const Tokenizer = struct { try printUnderstandableChar(&buffer, char); try buffer.outStream().print(" at position {}", .{position}); if (fmt.len != 0) try buffer.outStream().print(": " ++ fmt, args); - self.error_text = buffer.toSlice(); + self.error_text = buffer.span(); return Error.InvalidInput; } @@ -865,7 +865,7 @@ fn depTokenizer(input: []const u8, expect: []const u8) !void { try buffer.append("}"); i += 1; } - const got: []const u8 = buffer.toSlice(); + const got: []const u8 = buffer.span(); if (std.mem.eql(u8, expect, got)) { testing.expect(true); diff --git a/src-self-hosted/ir.zig b/src-self-hosted/ir.zig index 7ad9e0ccc4..ce3d9080ba 100644 --- a/src-self-hosted/ir.zig +++ b/src-self-hosted/ir.zig @@ -965,9 +965,9 @@ pub const Code = struct { pub fn dump(self: *Code) void { var bb_i: usize = 0; - for (self.basic_block_list.toSliceConst()) |bb| { + for (self.basic_block_list.span()) |bb| { std.debug.warn("{s}_{}:\n", .{ bb.name_hint, bb.debug_id }); - for (bb.instruction_list.toSliceConst()) |instr| { + for (bb.instruction_list.span()) |instr| { std.debug.warn(" ", .{}); instr.dump(); std.debug.warn("\n", .{}); @@ -978,7 +978,7 @@ pub const Code = struct { /// returns a ref-incremented value, or adds a compile error pub fn getCompTimeResult(self: *Code, comp: *Compilation) !*Value { const bb = self.basic_block_list.at(0); - for (bb.instruction_list.toSliceConst()) |inst| { + for (bb.instruction_list.span()) |inst| { if (inst.cast(Inst.Return)) |ret_inst| { const ret_value = ret_inst.params.return_value; if (ret_value.isCompTime()) { @@ -2585,6 +2585,6 @@ pub fn analyze(comp: *Compilation, old_code: *Code, expected_type: ?*Type) !*Cod return ira.irb.finish(); } - ira.irb.code.return_type = try ira.resolvePeerTypes(expected_type, ira.src_implicit_return_type_list.toSliceConst()); + ira.irb.code.return_type = try ira.resolvePeerTypes(expected_type, ira.src_implicit_return_type_list.span()); return ira.irb.finish(); } diff --git a/src-self-hosted/libc_installation.zig b/src-self-hosted/libc_installation.zig index 996f705060..9aa7b39c9b 100644 --- a/src-self-hosted/libc_installation.zig +++ b/src-self-hosted/libc_installation.zig @@ -54,7 +54,7 @@ pub const LibCInstallation = struct { } } - const contents = try std.io.readFileAlloc(allocator, libc_file); + const contents = try std.fs.cwd().readFileAlloc(allocator, libc_file, std.math.maxInt(usize)); defer allocator.free(contents); var it = std.mem.tokenize(contents, "\n"); @@ -229,7 +229,7 @@ pub const LibCInstallation = struct { "-xc", dev_null, }; - const exec_res = std.ChildProcess.exec2(.{ + const exec_res = std.ChildProcess.exec(.{ .allocator = allocator, .argv = &argv, .max_output_bytes = 1024 * 1024, @@ -335,7 +335,7 @@ pub const LibCInstallation = struct { const stream = result_buf.outStream(); try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version }); - var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -382,7 +382,7 @@ pub const LibCInstallation = struct { const stream = result_buf.outStream(); try stream.print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir }); - var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -437,7 +437,7 @@ pub const LibCInstallation = struct { const stream = result_buf.outStream(); try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir }); - var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -475,7 +475,7 @@ pub const LibCInstallation = struct { try result_buf.append("\\include"); - var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -522,7 +522,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 { defer allocator.free(arg1); const argv = [_][]const u8{ cc_exe, arg1 }; - const exec_res = std.ChildProcess.exec2(.{ + const exec_res = std.ChildProcess.exec(.{ .allocator = allocator, .argv = &argv, .max_output_bytes = 1024 * 1024, diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index e67b307097..ee2ef53d22 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -36,7 +36,7 @@ pub fn link(comp: *Compilation) !void { ctx.args = std.ArrayList([*:0]const u8).init(&ctx.arena.allocator); ctx.link_msg = std.Buffer.initNull(&ctx.arena.allocator); - ctx.out_file_path = try std.Buffer.init(&ctx.arena.allocator, comp.name.toSliceConst()); + ctx.out_file_path = try std.Buffer.init(&ctx.arena.allocator, comp.name.span()); switch (comp.kind) { .Exe => { try ctx.out_file_path.append(comp.target.exeFileExt()); @@ -70,7 +70,7 @@ pub fn link(comp: *Compilation) !void { try constructLinkerArgs(&ctx); if (comp.verbose_link) { - for (ctx.args.toSliceConst()) |arg, i| { + for (ctx.args.span()) |arg, i| { const space = if (i == 0) "" else " "; std.debug.warn("{}{s}", .{ space, arg }); } @@ -78,7 +78,7 @@ pub fn link(comp: *Compilation) !void { } const extern_ofmt = toExternObjectFormatType(comp.target.getObjectFormat()); - const args_slice = ctx.args.toSlice(); + const args_slice = ctx.args.span(); { // LLD is not thread-safe, so we grab a global lock. @@ -91,7 +91,7 @@ pub fn link(comp: *Compilation) !void { // TODO capture these messages and pass them through the system, reporting them through the // event system instead of printing them directly here. // perhaps try to parse and understand them. - std.debug.warn("{}\n", .{ctx.link_msg.toSliceConst()}); + std.debug.warn("{}\n", .{ctx.link_msg.span()}); } return error.LinkFailed; } @@ -173,7 +173,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void { //} try ctx.args.append("-o"); - try ctx.args.append(ctx.out_file_path.toSliceConst()); + try ctx.args.append(ctx.out_file_path.span()); if (ctx.link_in_crt) { const crt1o = if (ctx.comp.is_static) "crt1.o" else "Scrt1.o"; @@ -291,7 +291,7 @@ fn constructLinkerArgsCoff(ctx: *Context) !void { const is_library = ctx.comp.kind == .Lib; - const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", .{ctx.out_file_path.toSliceConst()}); + const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", .{ctx.out_file_path.span()}); try ctx.args.append(@ptrCast([*:0]const u8, out_arg.ptr)); if (ctx.comp.haveLibC()) { @@ -394,7 +394,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void { } try ctx.args.append("-o"); - try ctx.args.append(ctx.out_file_path.toSliceConst()); + try ctx.args.append(ctx.out_file_path.span()); if (shared) { try ctx.args.append("-headerpad_max_install_names"); @@ -432,7 +432,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void { // TODO //if (ctx.comp.target == Target.Native) { - // for (ctx.comp.link_libs_list.toSliceConst()) |lib| { + // for (ctx.comp.link_libs_list.span()) |lib| { // if (mem.eql(u8, lib.name, "c")) { // // on Darwin, libSystem has libc in it, but also you have to use it // // to make syscalls because the syscall numbers are not documented @@ -482,7 +482,7 @@ fn addFnObjects(ctx: *Context) !void { ctx.comp.gpa().destroy(node); continue; }; - try ctx.args.append(fn_val.containing_object.toSliceConst()); + try ctx.args.append(fn_val.containing_object.span()); it = node.next; } } diff --git a/src-self-hosted/main.zig b/src-self-hosted/main.zig index f5faa26615..fb96e0260a 100644 --- a/src-self-hosted/main.zig +++ b/src-self-hosted/main.zig @@ -421,7 +421,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co process.exit(1); } - try ZigCompiler.setLlvmArgv(allocator, mllvm_flags.toSliceConst()); + try ZigCompiler.setLlvmArgv(allocator, mllvm_flags.span()); const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch process.exit(1); defer allocator.free(zig_lib_dir); @@ -448,14 +448,14 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co comp.override_libc = &override_libc; } - for (system_libs.toSliceConst()) |lib| { + for (system_libs.span()) |lib| { _ = try comp.addLinkLib(lib, true); } comp.version = version; comp.is_test = false; comp.linker_script = linker_script; - comp.clang_argv = clang_argv_buf.toSliceConst(); + comp.clang_argv = clang_argv_buf.span(); comp.strip = strip; comp.verbose_tokenize = verbose_tokenize; @@ -488,8 +488,8 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co comp.emit_asm = emit_asm; comp.emit_llvm_ir = emit_llvm_ir; comp.emit_h = emit_h; - comp.assembly_files = assembly_files.toSliceConst(); - comp.link_objects = link_objects.toSliceConst(); + comp.assembly_files = assembly_files.span(); + comp.link_objects = link_objects.span(); comp.start(); processBuildEvents(comp, color); @@ -683,7 +683,7 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void { }; var group = event.Group(FmtError!void).init(allocator); - for (input_files.toSliceConst()) |file_path| { + for (input_files.span()) |file_path| { try group.call(fmtPath, .{ &fmt, file_path, check_flag }); } try group.wait(); @@ -898,7 +898,7 @@ const CliPkg = struct { } pub fn deinit(self: *CliPkg) void { - for (self.children.toSliceConst()) |child| { + for (self.children.span()) |child| { child.deinit(); } self.children.deinit(); diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 2c4fe99abe..8e7a0150a3 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -185,14 +185,14 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void { const argc_usize = @intCast(usize, argc); var arg_i: usize = 0; while (arg_i < argc_usize) : (arg_i += 1) { - try args_list.append(mem.toSliceConst(u8, argv[arg_i])); + try args_list.append(mem.spanZ(argv[arg_i])); } stdout = std.io.getStdOut().outStream(); stderr_file = std.io.getStdErr(); stderr = stderr_file.outStream(); - const args = args_list.toSliceConst()[2..]; + const args = args_list.span()[2..]; var color: errmsg.Color = .Auto; var stdin_flag: bool = false; @@ -285,7 +285,7 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void { .allocator = allocator, }; - for (input_files.toSliceConst()) |file_path| { + for (input_files.span()) |file_path| { try fmtPath(&fmt, file_path, check_flag); } if (fmt.any_error) { @@ -318,7 +318,8 @@ fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool) FmtError!void { if (fmt.seen.exists(file_path)) return; try fmt.seen.put(file_path); - const source_code = io.readFileAlloc(fmt.allocator, file_path) catch |err| switch (err) { + const max = std.math.maxInt(usize); + const source_code = fs.cwd().readFileAlloc(fmt.allocator, file_path, max) catch |err| switch (err) { error.IsDir, error.AccessDenied => { // TODO make event based (and dir.next()) var dir = try fs.cwd().openDir(file_path, .{ .iterate = true }); @@ -450,7 +451,7 @@ export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextRes const textz = std.Buffer.init(&self.handle.arena.allocator, self.handle.error_text) catch @panic("failed to create .d tokenizer error text"); return stage2_DepNextResult{ .type_id = .error_, - .textz = textz.toSlice().ptr, + .textz = textz.span().ptr, }; }; const token = otoken orelse { @@ -465,7 +466,7 @@ export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextRes .target => .target, .prereq => .prereq, }, - .textz = textz.toSlice().ptr, + .textz = textz.span().ptr, }; } @@ -572,7 +573,7 @@ fn detectNativeCpuWithLLVM( var result = Target.Cpu.baseline(arch); if (llvm_cpu_name_z) |cpu_name_z| { - const llvm_cpu_name = mem.toSliceConst(u8, cpu_name_z); + const llvm_cpu_name = mem.spanZ(cpu_name_z); for (arch.allCpuModels()) |model| { const this_llvm_name = model.llvm_name orelse continue; @@ -593,7 +594,7 @@ fn detectNativeCpuWithLLVM( const all_features = arch.allFeaturesList(); if (llvm_cpu_features_opt) |llvm_cpu_features| { - var it = mem.tokenize(mem.toSliceConst(u8, llvm_cpu_features), ","); + var it = mem.tokenize(mem.spanZ(llvm_cpu_features), ","); while (it.next()) |decorated_llvm_feat| { var op: enum { add, @@ -688,9 +689,9 @@ fn stage2CrossTarget( mcpu_oz: ?[*:0]const u8, dynamic_linker_oz: ?[*:0]const u8, ) !CrossTarget { - const zig_triple = if (zig_triple_oz) |zig_triple_z| mem.toSliceConst(u8, zig_triple_z) else "native"; - const mcpu = if (mcpu_oz) |mcpu_z| mem.toSliceConst(u8, mcpu_z) else null; - const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.toSliceConst(u8, dl_z) else null; + const zig_triple = if (zig_triple_oz) |zig_triple_z| mem.spanZ(zig_triple_z) else "native"; + const mcpu = if (mcpu_oz) |mcpu_z| mem.spanZ(mcpu_z) else null; + const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.spanZ(dl_z) else null; var diags: CrossTarget.ParseOptions.Diagnostics = .{}; const target: CrossTarget = CrossTarget.parse(.{ .arch_os_abi = zig_triple, @@ -814,7 +815,7 @@ const Stage2LibCInstallation = extern struct { export fn stage2_libc_parse(stage1_libc: *Stage2LibCInstallation, libc_file_z: [*:0]const u8) Error { stderr_file = std.io.getStdErr(); stderr = stderr_file.outStream(); - const libc_file = mem.toSliceConst(u8, libc_file_z); + const libc_file = mem.spanZ(libc_file_z); var libc = LibCInstallation.parse(std.heap.c_allocator, libc_file, stderr) catch |err| switch (err) { error.ParseError => return .SemanticAnalyzeFail, error.DiskQuota => return .DiskQuota, @@ -995,7 +996,7 @@ const Stage2Target = extern struct { \\ ); - assert(mem.endsWith(u8, llvm_features_buffer.toSliceConst(), ",")); + assert(mem.endsWith(u8, llvm_features_buffer.span(), ",")); llvm_features_buffer.shrink(llvm_features_buffer.len() - 1); var os_builtin_str_buffer = try std.Buffer.allocPrint(allocator, @@ -1120,7 +1121,7 @@ const Stage2Target = extern struct { try os_builtin_str_buffer.append("};\n"); try cache_hash.append( - os_builtin_str_buffer.toSlice()[os_builtin_str_ver_start_index..os_builtin_str_buffer.len()], + os_builtin_str_buffer.span()[os_builtin_str_ver_start_index..os_builtin_str_buffer.len()], ); const glibc_or_darwin_version = blk: { @@ -1232,10 +1233,10 @@ fn stage2DetectNativePaths(stage1_paths: *Stage2NativePaths) !void { var paths = try std.zig.system.NativePaths.detect(std.heap.c_allocator); errdefer paths.deinit(); - try convertSlice(paths.include_dirs.toSlice(), &stage1_paths.include_dirs_ptr, &stage1_paths.include_dirs_len); - try convertSlice(paths.lib_dirs.toSlice(), &stage1_paths.lib_dirs_ptr, &stage1_paths.lib_dirs_len); - try convertSlice(paths.rpaths.toSlice(), &stage1_paths.rpaths_ptr, &stage1_paths.rpaths_len); - try convertSlice(paths.warnings.toSlice(), &stage1_paths.warnings_ptr, &stage1_paths.warnings_len); + try convertSlice(paths.include_dirs.span(), &stage1_paths.include_dirs_ptr, &stage1_paths.include_dirs_len); + try convertSlice(paths.lib_dirs.span(), &stage1_paths.lib_dirs_ptr, &stage1_paths.lib_dirs_len); + try convertSlice(paths.rpaths.span(), &stage1_paths.rpaths_ptr, &stage1_paths.rpaths_len); + try convertSlice(paths.warnings.span(), &stage1_paths.warnings_ptr, &stage1_paths.warnings_len); } fn convertSlice(slice: [][:0]u8, ptr: *[*][*:0]u8, len: *usize) !void { diff --git a/src-self-hosted/test.zig b/src-self-hosted/test.zig index b146d6607a..9038b8128d 100644 --- a/src-self-hosted/test.zig +++ b/src-self-hosted/test.zig @@ -88,8 +88,7 @@ pub const TestContext = struct { try std.fs.cwd().makePath(dirname); } - // TODO async I/O - try std.io.writeFile(file1_path, source); + try std.fs.cwd().writeFile(file1_path, source); var comp = try Compilation.create( &self.zig_compiler, @@ -122,8 +121,7 @@ pub const TestContext = struct { try std.fs.cwd().makePath(dirname); } - // TODO async I/O - try std.io.writeFile(file1_path, source); + try std.fs.cwd().writeFile(file1_path, source); var comp = try Compilation.create( &self.zig_compiler, @@ -156,7 +154,11 @@ pub const TestContext = struct { .Ok => { const argv = [_][]const u8{exe_file}; // TODO use event loop - const child = try std.ChildProcess.exec(allocator, argv, null, null, 1024 * 1024); + const child = try std.ChildProcess.exec(.{ + .allocator = allocator, + .argv = argv, + .max_output_bytes = 1024 * 1024, + }); switch (child.term) { .Exited => |code| { if (code != 0) { diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index 1d8a2679f3..f1d7d66546 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -235,7 +235,7 @@ pub const Context = struct { /// Convert a null-terminated C string to a slice allocated in the arena fn str(c: *Context, s: [*:0]const u8) ![]u8 { - return mem.dupe(c.a(), u8, mem.toSliceConst(u8, s)); + return mem.dupe(c.a(), u8, mem.spanZ(s)); } /// Convert a clang source location to a file:line:column string @@ -5851,7 +5851,7 @@ fn parseCPrefixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8, fn tokenSlice(c: *Context, token: ast.TokenIndex) []u8 { const tok = c.tree.tokens.at(token); - const slice = c.source_buffer.toSlice()[tok.start..tok.end]; + const slice = c.source_buffer.span()[tok.start..tok.end]; return if (mem.startsWith(u8, slice, "@\"")) slice[2 .. slice.len - 1] else diff --git a/src-self-hosted/util.zig b/src-self-hosted/util.zig index ec68823ebd..4699b453ef 100644 --- a/src-self-hosted/util.zig +++ b/src-self-hosted/util.zig @@ -19,8 +19,8 @@ pub fn getDarwinArchString(self: Target) [:0]const u8 { pub fn llvmTargetFromTriple(triple: std.Buffer) !*llvm.Target { var result: *llvm.Target = undefined; var err_msg: [*:0]u8 = undefined; - if (llvm.GetTargetFromTriple(triple.toSlice(), &result, &err_msg) != 0) { - std.debug.warn("triple: {s} error: {s}\n", .{ triple.toSlice(), err_msg }); + if (llvm.GetTargetFromTriple(triple.span(), &result, &err_msg) != 0) { + std.debug.warn("triple: {s} error: {s}\n", .{ triple.span(), err_msg }); return error.UnsupportedTarget; } return result; diff --git a/src-self-hosted/value.zig b/src-self-hosted/value.zig index 03c0db0c3c..c2d91eecab 100644 --- a/src-self-hosted/value.zig +++ b/src-self-hosted/value.zig @@ -156,7 +156,7 @@ pub const Value = struct { const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context); const llvm_fn = llvm.AddFunction( ofile.module, - self.symbol_name.toSliceConst(), + self.symbol_name.span(), llvm_fn_type, ) orelse return error.OutOfMemory; @@ -241,7 +241,7 @@ pub const Value = struct { const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context); const llvm_fn = llvm.AddFunction( ofile.module, - self.symbol_name.toSliceConst(), + self.symbol_name.span(), llvm_fn_type, ) orelse return error.OutOfMemory; diff --git a/test/cli.zig b/test/cli.zig index 4c067d16ae..3af78e1857 100644 --- a/test/cli.zig +++ b/test/cli.zig @@ -59,7 +59,12 @@ fn printCmd(cwd: []const u8, argv: []const []const u8) void { fn exec(cwd: []const u8, argv: []const []const u8) !ChildProcess.ExecResult { const max_output_size = 100 * 1024; - const result = ChildProcess.exec(a, argv, cwd, null, max_output_size) catch |err| { + const result = ChildProcess.exec(.{ + .allocator = a, + .argv = argv, + .cwd = cwd, + .max_output_bytes = max_output_size, + }) catch |err| { std.debug.warn("The following command failed:\n", .{}); printCmd(cwd, argv); return err; @@ -101,7 +106,7 @@ fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void { const example_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.zig" }); const example_s_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.s" }); - try std.io.writeFile(example_zig_path, + try fs.cwd().writeFile(example_zig_path, \\// Type your code here, or load an example. \\export fn square(num: i32) i32 { \\ return num * num; @@ -124,7 +129,7 @@ fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void { }; _ = try exec(dir_path, &args); - const out_asm = try std.io.readFileAlloc(a, example_s_path); + const out_asm = try std.fs.cwd().readFileAlloc(a, example_s_path, std.math.maxInt(usize)); testing.expect(std.mem.indexOf(u8, out_asm, "square:") != null); testing.expect(std.mem.indexOf(u8, out_asm, "mov\teax, edi") != null); testing.expect(std.mem.indexOf(u8, out_asm, "imul\teax, edi") != null); diff --git a/test/src/compare_output.zig b/test/src/compare_output.zig index ae994a0697..110eb6068e 100644 --- a/test/src/compare_output.zig +++ b/test/src/compare_output.zig @@ -91,7 +91,7 @@ pub const CompareOutputContext = struct { const b = self.b; const write_src = b.addWriteFiles(); - for (case.sources.toSliceConst()) |src_file| { + for (case.sources.span()) |src_file| { write_src.add(src_file.filename, src_file.source); } @@ -105,7 +105,7 @@ pub const CompareOutputContext = struct { } const exe = b.addExecutable("test", null); - exe.addAssemblyFileFromWriteFileStep(write_src, case.sources.toSliceConst()[0].filename); + exe.addAssemblyFileFromWriteFileStep(write_src, case.sources.span()[0].filename); const run = exe.run(); run.addArgs(case.cli_args); @@ -125,7 +125,7 @@ pub const CompareOutputContext = struct { if (mem.indexOf(u8, annotated_case_name, filter) == null) continue; } - const basename = case.sources.toSliceConst()[0].filename; + const basename = case.sources.span()[0].filename; const exe = b.addExecutableFromWriteFileStep("test", write_src, basename); exe.setBuildMode(mode); if (case.link_libc) { @@ -146,7 +146,7 @@ pub const CompareOutputContext = struct { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } - const basename = case.sources.toSliceConst()[0].filename; + const basename = case.sources.span()[0].filename; const exe = b.addExecutableFromWriteFileStep("test", write_src, basename); if (case.link_libc) { exe.linkSystemLibrary("c"); diff --git a/test/src/run_translated_c.zig b/test/src/run_translated_c.zig index 14b0ce593c..74c841a1f3 100644 --- a/test/src/run_translated_c.zig +++ b/test/src/run_translated_c.zig @@ -82,13 +82,13 @@ pub const RunTranslatedCContext = struct { } const write_src = b.addWriteFiles(); - for (case.sources.toSliceConst()) |src_file| { + for (case.sources.span()) |src_file| { write_src.add(src_file.filename, src_file.source); } const translate_c = b.addTranslateC(.{ .write_file = .{ .step = write_src, - .basename = case.sources.toSliceConst()[0].filename, + .basename = case.sources.span()[0].filename, }, }); translate_c.step.name = b.fmt("{} translate-c", .{annotated_case_name}); diff --git a/test/src/translate_c.zig b/test/src/translate_c.zig index 9a6bd0d323..7b0a98f845 100644 --- a/test/src/translate_c.zig +++ b/test/src/translate_c.zig @@ -105,20 +105,20 @@ pub const TranslateCContext = struct { } const write_src = b.addWriteFiles(); - for (case.sources.toSliceConst()) |src_file| { + for (case.sources.span()) |src_file| { write_src.add(src_file.filename, src_file.source); } const translate_c = b.addTranslateC(.{ .write_file = .{ .step = write_src, - .basename = case.sources.toSliceConst()[0].filename, + .basename = case.sources.span()[0].filename, }, }); translate_c.step.name = annotated_case_name; translate_c.setTarget(case.target); - const check_file = translate_c.addCheckFile(case.expected_lines.toSliceConst()); + const check_file = translate_c.addCheckFile(case.expected_lines.span()); self.step.dependOn(&check_file.step); } diff --git a/test/stage1/behavior/cast.zig b/test/stage1/behavior/cast.zig index 0d4836a5a2..7b5f0e8fae 100644 --- a/test/stage1/behavior/cast.zig +++ b/test/stage1/behavior/cast.zig @@ -329,7 +329,7 @@ fn testCastPtrOfArrayToSliceAndPtr() void { test "cast *[1][*]const u8 to [*]const ?[*]const u8" { const window_name = [1][*]const u8{"window name"}; const x: [*]const ?[*]const u8 = &window_name; - expect(mem.eql(u8, std.mem.toSliceConst(u8, @ptrCast([*:0]const u8, x[0].?)), "window name")); + expect(mem.eql(u8, std.mem.spanZ(@ptrCast([*:0]const u8, x[0].?)), "window name")); } test "@intCast comptime_int" { diff --git a/test/stage1/behavior/pointers.zig b/test/stage1/behavior/pointers.zig index fbce9731f0..6b86c2f6ac 100644 --- a/test/stage1/behavior/pointers.zig +++ b/test/stage1/behavior/pointers.zig @@ -225,7 +225,7 @@ test "null terminated pointer" { var zero_ptr: [*:0]const u8 = @ptrCast([*:0]const u8, &array_with_zero); var no_zero_ptr: [*]const u8 = zero_ptr; var zero_ptr_again = @ptrCast([*:0]const u8, no_zero_ptr); - expect(std.mem.eql(u8, std.mem.toSliceConst(u8, zero_ptr_again), "hello")); + expect(std.mem.eql(u8, std.mem.spanZ(zero_ptr_again), "hello")); } }; S.doTheTest(); diff --git a/test/standalone/brace_expansion/main.zig b/test/standalone/brace_expansion/main.zig index e1d2ee6673..603eeb43e1 100644 --- a/test/standalone/brace_expansion/main.zig +++ b/test/standalone/brace_expansion/main.zig @@ -131,11 +131,11 @@ fn expandString(input: []const u8, output: *Buffer) !void { try expandNode(root, &result_list); try output.resize(0); - for (result_list.toSliceConst()) |buf, i| { + for (result_list.span()) |buf, i| { if (i != 0) { try output.appendByte(' '); } - try output.append(buf.toSliceConst()); + try output.append(buf.span()); } } @@ -157,20 +157,20 @@ fn expandNode(node: Node, output: *ArrayList(Buffer)) ExpandNodeError!void { var child_list_b = ArrayList(Buffer).init(global_allocator); try expandNode(b_node, &child_list_b); - for (child_list_a.toSliceConst()) |buf_a| { - for (child_list_b.toSliceConst()) |buf_b| { + for (child_list_a.span()) |buf_a| { + for (child_list_b.span()) |buf_b| { var combined_buf = try Buffer.initFromBuffer(buf_a); - try combined_buf.append(buf_b.toSliceConst()); + try combined_buf.append(buf_b.span()); try output.append(combined_buf); } } }, Node.List => |list| { - for (list.toSliceConst()) |child_node| { + for (list.span()) |child_node| { var child_list = ArrayList(Buffer).init(global_allocator); try expandNode(child_node, &child_list); - for (child_list.toSliceConst()) |buf| { + for (child_list.span()) |buf| { try output.append(buf); } } @@ -196,8 +196,8 @@ pub fn main() !void { var result_buf = try Buffer.initSize(global_allocator, 0); defer result_buf.deinit(); - try expandString(stdin_buf.toSlice(), &result_buf); - try stdout_file.write(result_buf.toSliceConst()); + try expandString(stdin_buf.span(), &result_buf); + try stdout_file.write(result_buf.span()); } test "invalid inputs" { @@ -256,5 +256,5 @@ fn expectExpansion(test_input: []const u8, expected_result: []const u8) void { expandString(test_input, &result) catch unreachable; - testing.expectEqualSlices(u8, expected_result, result.toSlice()); + testing.expectEqualSlices(u8, expected_result, result.span()); } diff --git a/test/standalone/guess_number/main.zig b/test/standalone/guess_number/main.zig index 14babcd145..5a82ec81ee 100644 --- a/test/standalone/guess_number/main.zig +++ b/test/standalone/guess_number/main.zig @@ -17,7 +17,7 @@ pub fn main() !void { const seed = std.mem.readIntNative(u64, &seed_bytes); var prng = std.rand.DefaultPrng.init(seed); - const answer = prng.random.range(u8, 0, 100) + 1; + const answer = prng.random.intRangeLessThan(u8, 0, 100) + 1; while (true) { try stdout.print("\nGuess a number between 1 and 100: ", .{}); diff --git a/test/tests.zig b/test/tests.zig index 567df58387..28459d84c1 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -583,7 +583,7 @@ pub const StackTracesContext = struct { warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); - const child = std.ChildProcess.init(args.toSliceConst(), b.allocator) catch unreachable; + const child = std.ChildProcess.init(args.span(), b.allocator) catch unreachable; defer child.deinit(); child.stdin_behavior = .Ignore; @@ -592,7 +592,7 @@ pub const StackTracesContext = struct { child.env_map = b.env_map; if (b.verbose) { - printInvocation(args.toSliceConst()); + printInvocation(args.span()); } child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) }); @@ -614,23 +614,23 @@ pub const StackTracesContext = struct { code, expect_code, }); - printInvocation(args.toSliceConst()); + printInvocation(args.span()); return error.TestFailed; } }, .Signal => |signum| { warn("Process {} terminated on signal {}\n", .{ full_exe_path, signum }); - printInvocation(args.toSliceConst()); + printInvocation(args.span()); return error.TestFailed; }, .Stopped => |signum| { warn("Process {} stopped on signal {}\n", .{ full_exe_path, signum }); - printInvocation(args.toSliceConst()); + printInvocation(args.span()); return error.TestFailed; }, .Unknown => |code| { warn("Process {} terminated unexpectedly with error code {}\n", .{ full_exe_path, code }); - printInvocation(args.toSliceConst()); + printInvocation(args.span()); return error.TestFailed; }, } @@ -785,7 +785,7 @@ pub const CompileErrorContext = struct { } else { try zig_args.append("build-obj"); } - const root_src_basename = self.case.sources.toSliceConst()[0].filename; + const root_src_basename = self.case.sources.span()[0].filename; try zig_args.append(self.write_src.getOutputPath(root_src_basename)); zig_args.append("--name") catch unreachable; @@ -809,10 +809,10 @@ pub const CompileErrorContext = struct { warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name }); if (b.verbose) { - printInvocation(zig_args.toSliceConst()); + printInvocation(zig_args.span()); } - const child = std.ChildProcess.init(zig_args.toSliceConst(), b.allocator) catch unreachable; + const child = std.ChildProcess.init(zig_args.span(), b.allocator) catch unreachable; defer child.deinit(); child.env_map = b.env_map; @@ -822,11 +822,11 @@ pub const CompileErrorContext = struct { child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) }); - var stdout_buf = Buffer.initNull(b.allocator); - var stderr_buf = Buffer.initNull(b.allocator); + var stdout_buf = ArrayList(u8).init(b.allocator); + var stderr_buf = ArrayList(u8).init(b.allocator); - child.stdout.?.inStream().readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable; - child.stderr.?.inStream().readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable; + child.stdout.?.inStream().readAllArrayList(&stdout_buf, max_stdout_size) catch unreachable; + child.stderr.?.inStream().readAllArrayList(&stderr_buf, max_stdout_size) catch unreachable; const term = child.wait() catch |err| { debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) }); @@ -834,19 +834,19 @@ pub const CompileErrorContext = struct { switch (term) { .Exited => |code| { if (code == 0) { - printInvocation(zig_args.toSliceConst()); + printInvocation(zig_args.span()); return error.CompilationIncorrectlySucceeded; } }, else => { warn("Process {} terminated unexpectedly\n", .{b.zig_exe}); - printInvocation(zig_args.toSliceConst()); + printInvocation(zig_args.span()); return error.TestFailed; }, } - const stdout = stdout_buf.toSliceConst(); - const stderr = stderr_buf.toSliceConst(); + const stdout = stdout_buf.span(); + const stderr = stderr_buf.span(); if (stdout.len != 0) { warn( @@ -875,12 +875,12 @@ pub const CompileErrorContext = struct { if (!ok) { warn("\n======== Expected these compile errors: ========\n", .{}); - for (self.case.expected_errors.toSliceConst()) |expected| { + for (self.case.expected_errors.span()) |expected| { warn("{}\n", .{expected}); } } } else { - for (self.case.expected_errors.toSliceConst()) |expected| { + for (self.case.expected_errors.span()) |expected| { if (mem.indexOf(u8, stderr, expected) == null) { warn( \\ @@ -980,7 +980,7 @@ pub const CompileErrorContext = struct { if (mem.indexOf(u8, annotated_case_name, filter) == null) return; } const write_src = b.addWriteFiles(); - for (case.sources.toSliceConst()) |src_file| { + for (case.sources.span()) |src_file| { write_src.add(src_file.filename, src_file.source); } @@ -1027,7 +1027,7 @@ pub const StandaloneContext = struct { zig_args.append("--verbose") catch unreachable; } - const run_cmd = b.addSystemCommand(zig_args.toSliceConst()); + const run_cmd = b.addSystemCommand(zig_args.span()); const log_step = b.addLog("PASS {}\n", .{annotated_case_name}); log_step.step.dependOn(&run_cmd.step); @@ -1127,7 +1127,7 @@ pub const GenHContext = struct { const full_h_path = self.obj.getOutputHPath(); const actual_h = try io.readFileAlloc(b.allocator, full_h_path); - for (self.case.expected_lines.toSliceConst()) |expected_line| { + for (self.case.expected_lines.span()) |expected_line| { if (mem.indexOf(u8, actual_h, expected_line) == null) { warn( \\ @@ -1188,7 +1188,7 @@ pub const GenHContext = struct { } const write_src = b.addWriteFiles(); - for (case.sources.toSliceConst()) |src_file| { + for (case.sources.span()) |src_file| { write_src.add(src_file.filename, src_file.source); } diff --git a/tools/merge_anal_dumps.zig b/tools/merge_anal_dumps.zig index e0e71696d6..3399c15fd7 100644 --- a/tools/merge_anal_dumps.zig +++ b/tools/merge_anal_dumps.zig @@ -183,13 +183,13 @@ const Dump = struct { try mergeSameStrings(&self.zig_version, zig_version); try mergeSameStrings(&self.root_name, root_name); - for (params.get("builds").?.value.Array.toSliceConst()) |json_build| { + for (params.get("builds").?.value.Array.span()) |json_build| { const target = json_build.Object.get("target").?.value.String; try self.targets.append(target); } // Merge files. If the string matches, it's the same file. - const other_files = root.Object.get("files").?.value.Array.toSliceConst(); + const other_files = root.Object.get("files").?.value.Array.span(); var other_file_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_files) |other_file, i| { const gop = try self.file_map.getOrPut(other_file.String); @@ -201,7 +201,7 @@ const Dump = struct { } // Merge AST nodes. If the file id, line, and column all match, it's the same AST node. - const other_ast_nodes = root.Object.get("astNodes").?.value.Array.toSliceConst(); + const other_ast_nodes = root.Object.get("astNodes").?.value.Array.span(); var other_ast_node_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_ast_nodes) |other_ast_node_json, i| { const other_file_id = jsonObjInt(other_ast_node_json, "file"); @@ -221,9 +221,9 @@ const Dump = struct { // convert fields lists for (other_ast_nodes) |other_ast_node_json, i| { const my_node_index = other_ast_node_to_mine.get(i).?.value; - const my_node = &self.node_list.toSlice()[my_node_index]; + const my_node = &self.node_list.span()[my_node_index]; if (other_ast_node_json.Object.get("fields")) |fields_json_kv| { - const other_fields = fields_json_kv.value.Array.toSliceConst(); + const other_fields = fields_json_kv.value.Array.span(); my_node.fields = try self.a().alloc(usize, other_fields.len); for (other_fields) |other_field_index, field_i| { const other_index = @intCast(usize, other_field_index.Integer); @@ -233,7 +233,7 @@ const Dump = struct { } // Merge errors. If the AST Node matches, it's the same error value. - const other_errors = root.Object.get("errors").?.value.Array.toSliceConst(); + const other_errors = root.Object.get("errors").?.value.Array.span(); var other_error_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_errors) |other_error_json, i| { const other_src_id = jsonObjInt(other_error_json, "src"); @@ -253,7 +253,7 @@ const Dump = struct { // First we identify all the simple types and merge those. // Example: void, type, noreturn // We can also do integers and floats. - const other_types = root.Object.get("types").?.value.Array.toSliceConst(); + const other_types = root.Object.get("types").?.value.Array.span(); var other_types_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_types) |other_type_json, i| { const type_kind = jsonObjInt(other_type_json, "kind"); @@ -336,7 +336,7 @@ const Dump = struct { try jw.objectField("builds"); try jw.beginArray(); - for (self.targets.toSliceConst()) |target| { + for (self.targets.span()) |target| { try jw.arrayElem(); try jw.beginObject(); try jw.objectField("target"); @@ -349,7 +349,7 @@ const Dump = struct { try jw.objectField("types"); try jw.beginArray(); - for (self.type_list.toSliceConst()) |t| { + for (self.type_list.span()) |t| { try jw.arrayElem(); try jw.beginObject(); @@ -379,7 +379,7 @@ const Dump = struct { try jw.objectField("errors"); try jw.beginArray(); - for (self.error_list.toSliceConst()) |zig_error| { + for (self.error_list.span()) |zig_error| { try jw.arrayElem(); try jw.beginObject(); @@ -395,7 +395,7 @@ const Dump = struct { try jw.objectField("astNodes"); try jw.beginArray(); - for (self.node_list.toSliceConst()) |node| { + for (self.node_list.span()) |node| { try jw.arrayElem(); try jw.beginObject(); @@ -425,7 +425,7 @@ const Dump = struct { try jw.objectField("files"); try jw.beginArray(); - for (self.file_list.toSliceConst()) |file| { + for (self.file_list.span()) |file| { try jw.arrayElem(); try jw.emitString(file); } diff --git a/tools/process_headers.zig b/tools/process_headers.zig index 7c9befcffa..65c5701106 100644 --- a/tools/process_headers.zig +++ b/tools/process_headers.zig @@ -324,7 +324,7 @@ pub fn main() !void { }, .os = .linux, }; - search: for (search_paths.toSliceConst()) |search_path| { + search: for (search_paths.span()) |search_path| { var sub_path: []const []const u8 = undefined; switch (vendor) { .musl => { @@ -414,13 +414,13 @@ pub fn main() !void { try contents_list.append(contents); } } - std.sort.sort(*Contents, contents_list.toSlice(), Contents.hitCountLessThan); + std.sort.sort(*Contents, contents_list.span(), Contents.hitCountLessThan); var best_contents = contents_list.popOrNull().?; if (best_contents.hit_count > 1) { // worth it to make it generic const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, generic_name, path_kv.key }); try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?); - try std.io.writeFile(full_path, best_contents.bytes); + try std.fs.cwd().writeFile(full_path, best_contents.bytes); best_contents.is_generic = true; while (contents_list.popOrNull()) |contender| { if (contender.hit_count > 1) { @@ -447,7 +447,7 @@ pub fn main() !void { }); const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, out_subpath, path_kv.key }); try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?); - try std.io.writeFile(full_path, contents.bytes); + try std.fs.cwd().writeFile(full_path, contents.bytes); } } } diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index b673fa0503..1baf4fbea0 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -239,7 +239,7 @@ pub fn main() anyerror!void { try std.fmt.allocPrint(allocator, "-I={}/clang/include/clang/Driver", .{llvm_src_root}), }; - const child_result = try std.ChildProcess.exec2(.{ + const child_result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &child_args, .max_output_bytes = 100 * 1024 * 1024, diff --git a/tools/update_glibc.zig b/tools/update_glibc.zig index 4a5b1751a2..d118b1482e 100644 --- a/tools/update_glibc.zig +++ b/tools/update_glibc.zig @@ -223,15 +223,15 @@ pub fn main() !void { var list = std.ArrayList([]const u8).init(allocator); var it = global_fn_set.iterator(); while (it.next()) |kv| try list.append(kv.key); - std.sort.sort([]const u8, list.toSlice(), strCmpLessThan); - break :blk list.toSliceConst(); + std.sort.sort([]const u8, list.span(), strCmpLessThan); + break :blk list.span(); }; const global_ver_list = blk: { var list = std.ArrayList([]const u8).init(allocator); var it = global_ver_set.iterator(); while (it.next()) |kv| try list.append(kv.key); - std.sort.sort([]const u8, list.toSlice(), versionLessThan); - break :blk list.toSliceConst(); + std.sort.sort([]const u8, list.span(), versionLessThan); + break :blk list.span(); }; { const vers_txt_path = try fs.path.join(allocator, &[_][]const u8{ glibc_out_dir, "vers.txt" }); @@ -264,13 +264,13 @@ pub fn main() !void { for (abi_lists) |*abi_list, abi_index| { const kv = target_functions.get(@ptrToInt(abi_list)).?; const fn_vers_list = &kv.value.fn_vers_list; - for (kv.value.list.toSliceConst()) |*ver_fn| { + for (kv.value.list.span()) |*ver_fn| { const gop = try fn_vers_list.getOrPut(ver_fn.name); if (!gop.found_existing) { gop.kv.value = std.ArrayList(usize).init(allocator); } const ver_index = global_ver_set.get(ver_fn.ver).?.value; - if (std.mem.indexOfScalar(usize, gop.kv.value.toSliceConst(), ver_index) == null) { + if (std.mem.indexOfScalar(usize, gop.kv.value.span(), ver_index) == null) { try gop.kv.value.append(ver_index); } } @@ -297,7 +297,7 @@ pub fn main() !void { try abilist_txt.writeByte('\n'); continue; }; - for (kv.value.toSliceConst()) |ver_index, it_i| { + for (kv.value.span()) |ver_index, it_i| { if (it_i != 0) try abilist_txt.writeByte(' '); try abilist_txt.print("{d}", .{ver_index}); } From 6408766d6b55d228a305b877f28f45c1587f7d39 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Mar 2020 15:50:53 -0400 Subject: [PATCH 21/89] linking: remove check for target_supports_libunwind I'm not sure why this was ever there. Maybe it was working around a problem with LLVM 9. Anyway this fixes linking C++ code for 32 bit arm and riscv. --- src/link.cpp | 8 ++------ src/target.cpp | 13 ------------- src/target.hpp | 1 - 3 files changed, 2 insertions(+), 20 deletions(-) diff --git a/src/link.cpp b/src/link.cpp index 693aaca0e3..ed6275ec3a 100644 --- a/src/link.cpp +++ b/src/link.cpp @@ -1947,15 +1947,11 @@ static void construct_linker_job_elf(LinkJob *lj) { lj->args.append("-lpthread"); } } else if (target_is_glibc(g->zig_target)) { - if (target_supports_libunwind(g->zig_target)) { - lj->args.append(build_libunwind(g, lj->build_dep_prog_node)); - } + lj->args.append(build_libunwind(g, lj->build_dep_prog_node)); add_glibc_libs(lj); lj->args.append(get_libc_crt_file(g, "libc_nonshared.a", lj->build_dep_prog_node)); } else if (target_is_musl(g->zig_target)) { - if (target_supports_libunwind(g->zig_target)) { - lj->args.append(build_libunwind(g, lj->build_dep_prog_node)); - } + lj->args.append(build_libunwind(g, lj->build_dep_prog_node)); lj->args.append(build_musl(g, lj->build_dep_prog_node)); } else if (g->libcpp_link_lib != nullptr) { lj->args.append(build_libunwind(g, lj->build_dep_prog_node)); diff --git a/src/target.cpp b/src/target.cpp index 0307216834..4430adfe5a 100644 --- a/src/target.cpp +++ b/src/target.cpp @@ -1295,19 +1295,6 @@ const char *target_arch_musl_name(ZigLLVM_ArchType arch) { } } -bool target_supports_libunwind(const ZigTarget *target) { - switch (target->arch) { - case ZigLLVM_arm: - case ZigLLVM_armeb: - case ZigLLVM_riscv32: - case ZigLLVM_riscv64: - return false; - default: - return true; - } - return true; -} - bool target_libc_needs_crti_crtn(const ZigTarget *target) { if (target->arch == ZigLLVM_riscv32 || target->arch == ZigLLVM_riscv64 || target_is_android(target)) { return false; diff --git a/src/target.hpp b/src/target.hpp index c3f8530e02..898fa90203 100644 --- a/src/target.hpp +++ b/src/target.hpp @@ -119,7 +119,6 @@ bool target_supports_stack_probing(const ZigTarget *target); bool target_supports_sanitize_c(const ZigTarget *target); bool target_has_debug_info(const ZigTarget *target); const char *target_arch_musl_name(ZigLLVM_ArchType arch); -bool target_supports_libunwind(const ZigTarget *target); uint32_t target_arch_pointer_bit_width(ZigLLVM_ArchType arch); uint32_t target_arch_largest_atomic_bits(ZigLLVM_ArchType arch); From cfedd3aca286881510e4a298756d4a5676e22137 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Mar 2020 17:42:30 -0400 Subject: [PATCH 22/89] revert detection of rtti and exceptions This caused link errors in c++ code because it was not correct to pass these flags to child codegens. And that was the only reason to detect these flags. Otherwise we can safely rely on non-explicitly-detected flag forwarding. --- src-self-hosted/clang_options_data.zig | 36 +++----------------------- src-self-hosted/stage2.zig | 4 --- src/all_types.hpp | 2 -- src/codegen.cpp | 16 ------------ src/main.cpp | 18 ------------- src/stage2.h | 4 --- tools/update_clang_options.zig | 16 ------------ 7 files changed, 4 insertions(+), 92 deletions(-) diff --git a/src-self-hosted/clang_options_data.zig b/src-self-hosted/clang_options_data.zig index 14dcec4fb1..d8bd020431 100644 --- a/src-self-hosted/clang_options_data.zig +++ b/src-self-hosted/clang_options_data.zig @@ -2554,14 +2554,7 @@ flagpd1("femulated-tls"), flagpd1("fencode-extended-block-signature"), sepd1("ferror-limit"), flagpd1("fescaping-block-tail-calls"), -.{ - .name = "fexceptions", - .syntax = .flag, - .zig_equivalent = .exceptions, - .pd1 = true, - .pd2 = false, - .psl = false, -}, +flagpd1("fexceptions"), flagpd1("fexperimental-isel"), flagpd1("fexperimental-new-constant-interpreter"), flagpd1("fexperimental-new-pass-manager"), @@ -2765,14 +2758,7 @@ flagpd1("fno-elide-type"), flagpd1("fno-eliminate-unused-debug-symbols"), flagpd1("fno-emulated-tls"), flagpd1("fno-escaping-block-tail-calls"), -.{ - .name = "fno-exceptions", - .syntax = .flag, - .zig_equivalent = .no_exceptions, - .pd1 = true, - .pd2 = false, - .psl = false, -}, +flagpd1("fno-exceptions"), flagpd1("fno-experimental-isel"), flagpd1("fno-experimental-new-pass-manager"), flagpd1("fno-fast-math"), @@ -2861,14 +2847,7 @@ flagpd1("fno-rewrite-includes"), flagpd1("fno-ropi"), flagpd1("fno-rounding-math"), flagpd1("fno-rtlib-add-rpath"), -.{ - .name = "fno-rtti", - .syntax = .flag, - .zig_equivalent = .no_rtti, - .pd1 = true, - .pd2 = false, - .psl = false, -}, +flagpd1("fno-rtti"), flagpd1("fno-rtti-data"), flagpd1("fno-rwpi"), flagpd1("fno-sanitize-address-poison-custom-array-cookie"), @@ -3016,14 +2995,7 @@ flagpd1("fno-frontend-optimize"), flagpd1("fropi"), flagpd1("frounding-math"), flagpd1("frtlib-add-rpath"), -.{ - .name = "frtti", - .syntax = .flag, - .zig_equivalent = .rtti, - .pd1 = true, - .pd2 = false, - .psl = false, -}, +flagpd1("frtti"), flagpd1("frwpi"), flagpd1("fsanitize-address-globals-dead-stripping"), flagpd1("fsanitize-address-poison-custom-array-cookie"), diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 8e7a0150a3..fcf9634097 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -1286,10 +1286,6 @@ pub const ClangArgIterator = extern struct { sanitize, linker_script, verbose_cmds, - exceptions, - no_exceptions, - rtti, - no_rtti, for_linker, linker_input_z, }; diff --git a/src/all_types.hpp b/src/all_types.hpp index 6c7b465025..f51a9c0572 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -2262,8 +2262,6 @@ struct CodeGen { bool emit_asm; bool emit_llvm_ir; bool test_is_evented; - bool cpp_rtti; - bool cpp_exceptions; CodeModel code_model; Buf *root_out_name; diff --git a/src/codegen.cpp b/src/codegen.cpp index f02253fb1a..d36e398bf7 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -8784,8 +8784,6 @@ static Error define_builtin_compile_vars(CodeGen *g) { cache_bool(&cache_hash, g->is_test_build); cache_bool(&cache_hash, g->is_single_threaded); cache_bool(&cache_hash, g->test_is_evented); - cache_bool(&cache_hash, g->cpp_rtti); - cache_bool(&cache_hash, g->cpp_exceptions); cache_int(&cache_hash, g->code_model); cache_int(&cache_hash, g->zig_target->is_native_os); cache_int(&cache_hash, g->zig_target->is_native_cpu); @@ -9259,14 +9257,6 @@ void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_pa case CSourceKindAsm: break; } - if (source_kind == CSourceKindCpp) { - if (!g->cpp_rtti) { - args.append("-fno-rtti"); - } - if (!g->cpp_exceptions) { - args.append("-fno-exceptions"); - } - } for (size_t i = 0; i < g->zig_target->llvm_cpu_features_asm_len; i += 1) { args.append(g->zig_target->llvm_cpu_features_asm_ptr[i]); } @@ -9714,8 +9704,6 @@ Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose cache_bool(cache_hash, g->have_sanitize_c); cache_bool(cache_hash, want_valgrind_support(g)); cache_bool(cache_hash, g->function_sections); - cache_bool(cache_hash, g->cpp_rtti); - cache_bool(cache_hash, g->cpp_exceptions); cache_int(cache_hash, g->code_model); for (size_t arg_i = 0; arg_i < g->clang_argv_len; arg_i += 1) { @@ -10550,8 +10538,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) { cache_bool(ch, g->emit_bin); cache_bool(ch, g->emit_llvm_ir); cache_bool(ch, g->emit_asm); - cache_bool(ch, g->cpp_rtti); - cache_bool(ch, g->cpp_exceptions); cache_usize(ch, g->version_major); cache_usize(ch, g->version_minor); cache_usize(ch, g->version_patch); @@ -10856,8 +10842,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o parent_gen->build_mode, parent_gen->zig_lib_dir, libc, get_global_cache_dir(), false, child_progress_node); child_gen->root_out_name = buf_create_from_str(name); child_gen->disable_gen_h = true; - child_gen->cpp_rtti = parent_gen->cpp_rtti; - child_gen->cpp_exceptions = parent_gen->cpp_exceptions; child_gen->want_stack_check = WantStackCheckDisabled; child_gen->want_sanitize_c = WantCSanitizeDisabled; child_gen->verbose_tokenize = parent_gen->verbose_tokenize; diff --git a/src/main.cpp b/src/main.cpp index 05ba1ab40f..c95a512210 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -458,8 +458,6 @@ static int main0(int argc, char **argv) { bool only_preprocess = false; bool ensure_libc_on_non_freestanding = false; bool ensure_libcpp_on_non_freestanding = false; - bool cpp_rtti = true; - bool cpp_exceptions = true; ZigList llvm_argv = {0}; llvm_argv.append("zig (LLVM option parsing)"); @@ -724,18 +722,6 @@ static int main0(int argc, char **argv) { verbose_cc = true; verbose_link = true; break; - case Stage2ClangArgExceptions: - cpp_exceptions = true; - break; - case Stage2ClangArgNoExceptions: - cpp_exceptions = false; - break; - case Stage2ClangArgRtti: - cpp_rtti = true; - break; - case Stage2ClangArgNoRtti: - cpp_rtti = false; - break; case Stage2ClangArgForLinker: linker_args.append(buf_create_from_str(it.only_arg)); break; @@ -1331,8 +1317,6 @@ static int main0(int argc, char **argv) { LinkLib *link_lib = codegen_add_link_lib(g, buf_create_from_str(link_libs.at(i))); link_lib->provided_explicitly = true; } - g->cpp_rtti = cpp_rtti; - g->cpp_exceptions = cpp_exceptions; g->subsystem = subsystem; g->valgrind_support = valgrind_support; g->want_pic = want_pic; @@ -1481,8 +1465,6 @@ static int main0(int argc, char **argv) { } CodeGen *g = codegen_create(main_pkg_path, zig_root_source_file, &target, out_type, build_mode, override_lib_dir, libc, cache_dir_buf, cmd == CmdTest, root_progress_node); - g->cpp_rtti = cpp_rtti; - g->cpp_exceptions = cpp_exceptions; if (llvm_argv.length >= 2) codegen_set_llvm_argv(g, llvm_argv.items + 1, llvm_argv.length - 2); g->valgrind_support = valgrind_support; g->link_eh_frame_hdr = link_eh_frame_hdr; diff --git a/src/stage2.h b/src/stage2.h index 5cea30dbab..54355ea735 100644 --- a/src/stage2.h +++ b/src/stage2.h @@ -345,10 +345,6 @@ enum Stage2ClangArg { Stage2ClangArgSanitize, Stage2ClangArgLinkerScript, Stage2ClangArgVerboseCmds, - Stage2ClangArgExceptions, - Stage2ClangArgNoExceptions, - Stage2ClangArgRtti, - Stage2ClangArgNoRtti, Stage2ClangArgForLinker, Stage2ClangArgLinkerInputZ, }; diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index 1baf4fbea0..f5b483e667 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -174,22 +174,6 @@ const known_options = [_]KnownOpt{ .name = "###", .ident = "verbose_cmds", }, - .{ - .name = "fexceptions", - .ident = "exceptions", - }, - .{ - .name = "fno-exceptions", - .ident = "no_exceptions", - }, - .{ - .name = "frtti", - .ident = "rtti", - }, - .{ - .name = "fno-rtti", - .ident = "no_rtti", - }, }; const blacklisted_options = [_][]const u8{}; From f6f03cd90f5c0a8cce7981b16f384b088f41c319 Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Tue, 31 Mar 2020 00:19:19 +0200 Subject: [PATCH 23/89] compiler-rt: implement clear_cache for arm32-linux --- lib/std/special/compiler_rt.zig | 2 +- lib/std/special/compiler_rt/clear_cache.zig | 46 +++++++++------------ 2 files changed, 20 insertions(+), 28 deletions(-) diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index 1f68d928c2..44db926b5f 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -11,7 +11,7 @@ comptime { switch (builtin.arch) { .i386, .x86_64 => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{ .name = "__zig_probe_stack", .linkage = linkage }), - .aarch64, .aarch64_be, .aarch64_32 => { + .aarch64, .aarch64_be, .aarch64_32, .arm, .armeb, .thumb, .thumbeb => { @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ .name = "__clear_cache", .linkage = linkage }); }, else => {}, diff --git a/lib/std/special/compiler_rt/clear_cache.zig b/lib/std/special/compiler_rt/clear_cache.zig index 77470251d1..5d09a7692d 100644 --- a/lib/std/special/compiler_rt/clear_cache.zig +++ b/lib/std/special/compiler_rt/clear_cache.zig @@ -45,33 +45,25 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { @compileError("TODO"); // FlushInstructionCache(GetCurrentProcess(), start, end - start); } else if (arm32 and !apple) { - @compileError("TODO"); - //#if defined(__FreeBSD__) || defined(__NetBSD__) - // struct arm_sync_icache_args arg; - // - // arg.addr = (uintptr_t)start; - // arg.len = (uintptr_t)end - (uintptr_t)start; - // - // sysarch(ARM_SYNC_ICACHE, &arg); - //#elif defined(__linux__) - //// We used to include asm/unistd.h for the __ARM_NR_cacheflush define, but - //// it also brought many other unused defines, as well as a dependency on - //// kernel headers to be installed. - //// - //// This value is stable at least since Linux 3.13 and should remain so for - //// compatibility reasons, warranting it's re-definition here. - //#define __ARM_NR_cacheflush 0x0f0002 - // register int start_reg __asm("r0") = (int)(intptr_t)start; - // const register int end_reg __asm("r1") = (int)(intptr_t)end; - // const register int flags __asm("r2") = 0; - // const register int syscall_nr __asm("r7") = __ARM_NR_cacheflush; - // __asm __volatile("svc 0x0" - // : "=r"(start_reg) - // : "r"(syscall_nr), "r"(start_reg), "r"(end_reg), "r"(flags)); - // assert(start_reg == 0 && "Cache flush syscall failed."); - //#else - // compilerrt_abort(); - //#endif + if (os == .freebsd or os == .netbsd) { + // struct arm_sync_icache_args arg; + // + // arg.addr = (uintptr_t)start; + // arg.len = (uintptr_t)end - (uintptr_t)start; + // + // sysarch(ARM_SYNC_ICACHE, &arg); + @compileError("TODO: implement for NetBSD/FreeBSD"); + } else if (os == .linux) { + const result = std.os.linux.syscall3( + std.os.linux.SYS_cacheflush, + start, + end, + 0, + ); + std.debug.assert(result == 0); + } else { + @compileError("compilerrt_abort"); + } } else if (os == .linux and mips) { @compileError("TODO"); //const uintptr_t start_int = (uintptr_t)start; From 44aadaff591446c863a40d78e0c2deb1f56e736e Mon Sep 17 00:00:00 2001 From: Kelly Boothby Date: Mon, 30 Mar 2020 18:29:48 -0700 Subject: [PATCH 24/89] added unit tests to demonstrate #4769 and related bugs --- test/stage1/behavior.zig | 3 +++ test/stage1/behavior/bugs/4769_a.zig | 1 + test/stage1/behavior/bugs/4769_b.zig | 1 + test/stage1/behavior/bugs/4769_c.zig | 1 + 4 files changed, 6 insertions(+) create mode 100644 test/stage1/behavior/bugs/4769_a.zig create mode 100644 test/stage1/behavior/bugs/4769_b.zig create mode 100644 test/stage1/behavior/bugs/4769_c.zig diff --git a/test/stage1/behavior.zig b/test/stage1/behavior.zig index dfc4321500..c3407db3e6 100644 --- a/test/stage1/behavior.zig +++ b/test/stage1/behavior.zig @@ -41,6 +41,9 @@ comptime { _ = @import("behavior/bugs/3586.zig"); _ = @import("behavior/bugs/3742.zig"); _ = @import("behavior/bugs/4560.zig"); + _ = @import("behavior/bugs/4769_a.zig"); + _ = @import("behavior/bugs/4769_b.zig"); + _ = @import("behavior/bugs/4769_c.zig"); _ = @import("behavior/bugs/394.zig"); _ = @import("behavior/bugs/421.zig"); _ = @import("behavior/bugs/529.zig"); diff --git a/test/stage1/behavior/bugs/4769_a.zig b/test/stage1/behavior/bugs/4769_a.zig new file mode 100644 index 0000000000..ab0c01417a --- /dev/null +++ b/test/stage1/behavior/bugs/4769_a.zig @@ -0,0 +1 @@ +// \ No newline at end of file diff --git a/test/stage1/behavior/bugs/4769_b.zig b/test/stage1/behavior/bugs/4769_b.zig new file mode 100644 index 0000000000..23b2513f17 --- /dev/null +++ b/test/stage1/behavior/bugs/4769_b.zig @@ -0,0 +1 @@ +//! \ No newline at end of file diff --git a/test/stage1/behavior/bugs/4769_c.zig b/test/stage1/behavior/bugs/4769_c.zig new file mode 100644 index 0000000000..4894ddf7e8 --- /dev/null +++ b/test/stage1/behavior/bugs/4769_c.zig @@ -0,0 +1 @@ +/// \ No newline at end of file From 1111d3ad13b6e2af855b50c15bdbafcfc12b52c0 Mon Sep 17 00:00:00 2001 From: Kelly Boothby Date: Mon, 30 Mar 2020 18:18:06 -0700 Subject: [PATCH 25/89] fixed bugs hitting EOF immediately after //, /// or //! --- src/tokenizer.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index 22d63568bf..b4e9d910d9 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -1494,9 +1494,17 @@ void tokenize(Buf *buf, Tokenization *out) { tokenize_error(&t, "unexpected EOF"); break; case TokenizeStateLineComment: + break; case TokenizeStateSawSlash2: + cancel_token(&t); + break; case TokenizeStateSawSlash3: + set_token_id(&t, t.cur_tok, TokenIdDocComment); + end_token(&t); + break; case TokenizeStateSawSlashBang: + set_token_id(&t, t.cur_tok, TokenIdContainerDocComment); + end_token(&t); break; } if (t.state != TokenizeStateError) { From 83ff94b1cc761a4f8a222314b26700b13de100a9 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Mar 2020 23:15:07 -0400 Subject: [PATCH 26/89] compiler-rt: don't export __clear_cache when no impl available --- lib/std/special/compiler_rt.zig | 25 ++++++++++++++++++--- lib/std/special/compiler_rt/clear_cache.zig | 9 ++------ 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index 44db926b5f..6cdc127137 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -10,10 +10,29 @@ comptime { const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong; switch (builtin.arch) { - .i386, .x86_64 => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{ .name = "__zig_probe_stack", .linkage = linkage }), - .aarch64, .aarch64_be, .aarch64_32, .arm, .armeb, .thumb, .thumbeb => { - @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ .name = "__clear_cache", .linkage = linkage }); + .i386, + .x86_64, + => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{ + .name = "__zig_probe_stack", + .linkage = linkage, + }), + + .aarch64, + .aarch64_be, + .aarch64_32, + => @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ + .name = "__clear_cache", + .linkage = linkage, + }), + + .arm, .armeb, .thumb, .thumbeb => switch (builtin.os.tag) { + .linux => @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ + .name = "__clear_cache", + .linkage = linkage, + }), + else => {}, }, + else => {}, } diff --git a/lib/std/special/compiler_rt/clear_cache.zig b/lib/std/special/compiler_rt/clear_cache.zig index 5d09a7692d..984ef7e7ac 100644 --- a/lib/std/special/compiler_rt/clear_cache.zig +++ b/lib/std/special/compiler_rt/clear_cache.zig @@ -54,15 +54,10 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { // sysarch(ARM_SYNC_ICACHE, &arg); @compileError("TODO: implement for NetBSD/FreeBSD"); } else if (os == .linux) { - const result = std.os.linux.syscall3( - std.os.linux.SYS_cacheflush, - start, - end, - 0, - ); + const result = std.os.linux.syscall3(std.os.linux.SYS_cacheflush, start, end, 0); std.debug.assert(result == 0); } else { - @compileError("compilerrt_abort"); + @compileError("no __clear_cache implementation available for this target"); } } else if (os == .linux and mips) { @compileError("TODO"); From 45dc2587a395c02afb12f1781f3539d4bc77c225 Mon Sep 17 00:00:00 2001 From: Ali Ahmed Date: Mon, 30 Mar 2020 18:59:43 -0700 Subject: [PATCH 27/89] Fix Readme to point to llvm for brew commands * Homebrew has updated llvm to point to llvm@10 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ac9e8208ae..fd8e51da17 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,8 @@ make install ##### MacOS ``` -brew install cmake llvm@10 -brew outdated llvm@10 || brew upgrade llvm@10 +brew install cmake llvm +brew outdated llvm || brew upgrade llvm mkdir build cd build cmake .. -DCMAKE_PREFIX_PATH=$(brew --prefix llvm) From 3a0875d9e805e524a12756ff975fedb0d94fb217 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 00:01:09 +1100 Subject: [PATCH 28/89] std: have json tests take options parameter --- lib/std/json.zig | 56 ++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index c127d962dd..0bc9e50d05 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -2390,7 +2390,7 @@ pub fn stringify( unreachable; } -fn teststringify(expected: []const u8, value: var) !void { +fn teststringify(expected: []const u8, value: var, options: StringifyOptions) !void { const ValidationOutStream = struct { const Self = @This(); pub const OutStream = std.io.OutStream(*Self, Error, write); @@ -2442,55 +2442,55 @@ fn teststringify(expected: []const u8, value: var) !void { }; var vos = ValidationOutStream.init(expected); - try stringify(value, StringifyOptions{}, vos.outStream()); + try stringify(value, options, vos.outStream()); if (vos.expected_remaining.len > 0) return error.NotEnoughData; } test "stringify basic types" { - try teststringify("false", false); - try teststringify("true", true); - try teststringify("null", @as(?u8, null)); - try teststringify("null", @as(?*u32, null)); - try teststringify("42", 42); - try teststringify("4.2e+01", 42.0); - try teststringify("42", @as(u8, 42)); - try teststringify("42", @as(u128, 42)); - try teststringify("4.2e+01", @as(f32, 42)); - try teststringify("4.2e+01", @as(f64, 42)); + try teststringify("false", false, StringifyOptions{}); + try teststringify("true", true, StringifyOptions{}); + try teststringify("null", @as(?u8, null), StringifyOptions{}); + try teststringify("null", @as(?*u32, null), StringifyOptions{}); + try teststringify("42", 42, StringifyOptions{}); + try teststringify("4.2e+01", 42.0, StringifyOptions{}); + try teststringify("42", @as(u8, 42), StringifyOptions{}); + try teststringify("42", @as(u128, 42), StringifyOptions{}); + try teststringify("4.2e+01", @as(f32, 42), StringifyOptions{}); + try teststringify("4.2e+01", @as(f64, 42), StringifyOptions{}); } test "stringify string" { - try teststringify("\"hello\"", "hello"); - try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r"); - try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}"); - try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}"); - try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}"); - try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}"); - try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}"); - try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}"); - try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}"); - try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}"); - try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}"); + try teststringify("\"hello\"", "hello", StringifyOptions{}); + try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{}); + try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{}); + try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{}); + try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{}); + try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{}); + try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{}); + try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{}); + try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{}); + try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{}); + try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{}); } test "stringify tagged unions" { try teststringify("42", union(enum) { Foo: u32, Bar: bool, - }{ .Foo = 42 }); + }{ .Foo = 42 }, StringifyOptions{}); } test "stringify struct" { try teststringify("{\"foo\":42}", struct { foo: u32, - }{ .foo = 42 }); + }{ .foo = 42 }, StringifyOptions{}); } test "stringify struct with void field" { try teststringify("{\"foo\":42}", struct { foo: u32, bar: void = {}, - }{ .foo = 42 }); + }{ .foo = 42 }, StringifyOptions{}); } test "stringify array of structs" { @@ -2501,7 +2501,7 @@ test "stringify array of structs" { MyStruct{ .foo = 42 }, MyStruct{ .foo = 100 }, MyStruct{ .foo = 1000 }, - }); + }, StringifyOptions{}); } test "stringify struct with custom stringifier" { @@ -2517,5 +2517,5 @@ test "stringify struct with custom stringifier" { try stringify(42, options, out_stream); try out_stream.writeAll("]"); } - }{ .foo = 42 }); + }{ .foo = 42 }, StringifyOptions{}); } From 48e7c6cca67bcd9f41c2742c83353b03c52f9b50 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 00:53:14 +1100 Subject: [PATCH 29/89] std: add whitespace control to json.stringify --- lib/std/json.zig | 138 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 124 insertions(+), 14 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index 0bc9e50d05..a1af2e0c45 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -2241,7 +2241,45 @@ test "string copy option" { } pub const StringifyOptions = struct { - // TODO: indentation options? + pub const Whitespace = struct { + /// How many indentation levels deep are we? + indent_level: usize = 0, + + pub const Indentation = union(enum) { + Space: u8, + Tab: void, + }; + + /// What character(s) should be used for indentation? + indent: Indentation = Indentation{ .Space = 4 }, + + fn outputIndent( + whitespace: @This(), + out_stream: var, + ) @TypeOf(out_stream).Error!void { + var char: u8 = undefined; + var n_chars: usize = undefined; + switch (whitespace.indent) { + .Space => |n_spaces| { + char = ' '; + n_chars = n_spaces; + }, + .Tab => { + char = '\t'; + n_chars = 1; + }, + } + n_chars *= whitespace.indent_level; + try out_stream.writeByteNTimes(char, n_chars); + } + + /// After a colon, should whitespace be inserted? + separator: bool = true, + }; + + /// Controls the whitespace emitted + whitespace: ?Whitespace = null, + // TODO: make escaping '/' in strings optional? // TODO: allow picking if []u8 is string or array? }; @@ -2297,8 +2335,12 @@ pub fn stringify( return value.jsonStringify(options, out_stream); } - try out_stream.writeAll("{"); + try out_stream.writeByte('{'); comptime var field_output = false; + var child_options = options; + if (child_options.whitespace) |*child_whitespace| { + child_whitespace.indent_level += 1; + } inline for (S.fields) |Field, field_i| { // don't include void fields if (Field.field_type == void) continue; @@ -2306,14 +2348,28 @@ pub fn stringify( if (!field_output) { field_output = true; } else { - try out_stream.writeAll(","); + try out_stream.writeByte(','); + } + if (child_options.whitespace) |child_whitespace| { + try out_stream.writeByte('\n'); + try child_whitespace.outputIndent(out_stream); } - try stringify(Field.name, options, out_stream); - try out_stream.writeAll(":"); - try stringify(@field(value, Field.name), options, out_stream); + try out_stream.writeByte(':'); + if (child_options.whitespace) |child_whitespace| { + if (child_whitespace.separator) { + try out_stream.writeByte(' '); + } + } + try stringify(@field(value, Field.name), child_options, out_stream); } - try out_stream.writeAll("}"); + if (field_output) { + if (options.whitespace) |whitespace| { + try out_stream.writeByte('\n'); + try whitespace.outputIndent(out_stream); + } + } + try out_stream.writeByte('}'); return; }, .Pointer => |ptr_info| switch (ptr_info.size) { @@ -2330,7 +2386,7 @@ pub fn stringify( // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972) .Slice => { if (ptr_info.child == u8 and std.unicode.utf8ValidateSlice(value)) { - try out_stream.writeAll("\""); + try out_stream.writeByte('\"'); var i: usize = 0; while (i < value.len) : (i += 1) { switch (value[i]) { @@ -2368,18 +2424,32 @@ pub fn stringify( }, } } - try out_stream.writeAll("\""); + try out_stream.writeByte('\"'); return; } - try out_stream.writeAll("["); + try out_stream.writeByte('['); + var child_options = options; + if (child_options.whitespace) |*whitespace| { + whitespace.indent_level += 1; + } for (value) |x, i| { if (i != 0) { - try out_stream.writeAll(","); + try out_stream.writeByte(','); } - try stringify(x, options, out_stream); + if (child_options.whitespace) |child_whitespace| { + try out_stream.writeByte('\n'); + try child_whitespace.outputIndent(out_stream); + } + try stringify(x, child_options, out_stream); } - try out_stream.writeAll("]"); + if (value.len != 0) { + if (options.whitespace) |whitespace| { + try out_stream.writeByte('\n'); + try whitespace.outputIndent(out_stream); + } + } + try out_stream.writeByte(']'); return; }, else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"), @@ -2486,6 +2556,46 @@ test "stringify struct" { }{ .foo = 42 }, StringifyOptions{}); } +test "stringify struct with indentation" { + try teststringify( + \\{ + \\ "foo": 42, + \\ "bar": [ + \\ 1, + \\ 2, + \\ 3 + \\ ] + \\} + , + struct { + foo: u32, + bar: [3]u32, + }{ + .foo = 42, + .bar = .{ 1, 2, 3 }, + }, + StringifyOptions{ + .whitespace = .{}, + }, + ); + try teststringify( + "{\n\t\"foo\":42,\n\t\"bar\":[\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n}", + struct { + foo: u32, + bar: [3]u32, + }{ + .foo = 42, + .bar = .{ 1, 2, 3 }, + }, + StringifyOptions{ + .whitespace = .{ + .indent = .Tab, + .separator = false, + }, + }, + ); +} + test "stringify struct with void field" { try teststringify("{\"foo\":42}", struct { foo: u32, @@ -2515,7 +2625,7 @@ test "stringify struct with custom stringifier" { ) !void { try out_stream.writeAll("[\"something special\","); try stringify(42, options, out_stream); - try out_stream.writeAll("]"); + try out_stream.writeByte(']'); } }{ .foo = 42 }, StringifyOptions{}); } From e88543a504af4808a3ab7ee169d4b17faa645e5b Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 01:26:44 +1100 Subject: [PATCH 30/89] std: add jsonStringify trait to json Value objects --- lib/std/json.zig | 105 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/lib/std/json.zig b/lib/std/json.zig index a1af2e0c45..3274196f27 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1233,6 +1233,57 @@ pub const Value = union(enum) { Array: Array, Object: ObjectMap, + pub fn jsonStringify( + value: @This(), + options: StringifyOptions, + out_stream: var, + ) @TypeOf(out_stream).Error!void { + switch (value) { + .Null => try out_stream.writeAll("null"), + .Bool => |inner| try stringify(inner, options, out_stream), + .Integer => |inner| try stringify(inner, options, out_stream), + .Float => |inner| try stringify(inner, options, out_stream), + .String => |inner| try stringify(inner, options, out_stream), + .Array => |inner| try stringify(inner.span(), options, out_stream), + .Object => |inner| { + try out_stream.writeByte('{'); + var field_output = false; + var child_options = options; + if (child_options.whitespace) |*child_whitespace| { + child_whitespace.indent_level += 1; + } + var it = inner.iterator(); + while (it.next()) |entry| { + if (!field_output) { + field_output = true; + } else { + try out_stream.writeByte(','); + } + if (child_options.whitespace) |child_whitespace| { + try out_stream.writeByte('\n'); + try child_whitespace.outputIndent(out_stream); + } + + try stringify(entry.key, options, out_stream); + try out_stream.writeByte(':'); + if (child_options.whitespace) |child_whitespace| { + if (child_whitespace.separator) { + try out_stream.writeByte(' '); + } + } + try stringify(entry.value, child_options, out_stream); + } + if (field_output) { + if (options.whitespace) |whitespace| { + try out_stream.writeByte('\n'); + try whitespace.outputIndent(out_stream); + } + } + try out_stream.writeByte('}'); + }, + } + } + pub fn dump(self: Value) void { var held = std.debug.getStderrMutex().acquire(); defer held.release(); @@ -1270,6 +1321,60 @@ pub const Value = union(enum) { } }; +test "Value.jsonStringify" { + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + try @as(Value, .Null).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "null"); + } + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + try (Value{ .Bool = true }).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "true"); + } + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + try (Value{ .Integer = 42 }).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "42"); + } + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + try (Value{ .Float = 42 }).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "4.2e+01"); + } + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + try (Value{ .String = "weeee" }).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "\"weeee\""); + } + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + try (Value{ + .Array = Array.fromOwnedSlice(undefined, &[_]Value{ + .{ .Integer = 1 }, + .{ .Integer = 2 }, + .{ .Integer = 3 }, + }), + }).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "[1,2,3]"); + } + { + var buffer: [10]u8 = undefined; + var fbs = std.io.fixedBufferStream(&buffer); + var obj = ObjectMap.init(testing.allocator); + defer obj.deinit(); + try obj.putNoClobber("a", .{ .String = "b" }); + try (Value{ .Object = obj }).jsonStringify(.{}, fbs.outStream()); + testing.expectEqualSlices(u8, fbs.getWritten(), "{\"a\":\"b\"}"); + } +} + pub const ParseOptions = struct { allocator: ?*Allocator = null, From 5a053247e2c5cfb21af2dfdd3d7ffa56c33f7b67 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 01:36:30 +1100 Subject: [PATCH 31/89] std: use stringify from Value.dump; remove other dump helpers --- lib/std/json.zig | 30 +----------------------------- 1 file changed, 1 insertion(+), 29 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index 3274196f27..98e800edc6 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1289,35 +1289,7 @@ pub const Value = union(enum) { defer held.release(); const stderr = std.debug.getStderrStream(); - self.dumpStream(stderr, 1024) catch return; - } - - pub fn dumpIndent(self: Value, comptime indent: usize) void { - if (indent == 0) { - self.dump(); - } else { - var held = std.debug.getStderrMutex().acquire(); - defer held.release(); - - const stderr = std.debug.getStderrStream(); - self.dumpStreamIndent(indent, stderr, 1024) catch return; - } - } - - pub fn dumpStream(self: @This(), stream: var, comptime max_depth: usize) !void { - var w = std.json.WriteStream(@TypeOf(stream).Child, max_depth).init(stream); - w.newline = ""; - w.one_indent = ""; - w.space = ""; - try w.emitJson(self); - } - - pub fn dumpStreamIndent(self: @This(), comptime indent: usize, stream: var, comptime max_depth: usize) !void { - var one_indent = " " ** indent; - - var w = std.json.WriteStream(@TypeOf(stream).Child, max_depth).init(stream); - w.one_indent = one_indent; - try w.emitJson(self); + std.json.stringify(self, std.json.StringifyOptions{ .whitespace = null }, stderr) catch return; } }; From 17f5d04bedb7a3cf06e8b0a7a1e8d13a3f2635f5 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 01:37:08 +1100 Subject: [PATCH 32/89] std: use json.stringify logic in some json.WriteStream code paths --- lib/std/json/write_stream.zig | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/lib/std/json/write_stream.zig b/lib/std/json/write_stream.zig index cbe556dcfc..07af75219e 100644 --- a/lib/std/json/write_stream.zig +++ b/lib/std/json/write_stream.zig @@ -140,11 +140,7 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { pub fn emitBool(self: *Self, value: bool) !void { assert(self.state[self.state_index] == State.Value); - if (value) { - try self.stream.writeAll("true"); - } else { - try self.stream.writeAll("false"); - } + try std.json.stringify(value, std.json.StringifyOptions{}, self.stream); self.popState(); } @@ -185,20 +181,8 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { } fn writeEscapedString(self: *Self, string: []const u8) !void { - try self.stream.writeByte('"'); - for (string) |s| { - switch (s) { - '"' => try self.stream.writeAll("\\\""), - '\t' => try self.stream.writeAll("\\t"), - '\r' => try self.stream.writeAll("\\r"), - '\n' => try self.stream.writeAll("\\n"), - 8 => try self.stream.writeAll("\\b"), - 12 => try self.stream.writeAll("\\f"), - '\\' => try self.stream.writeAll("\\\\"), - else => try self.stream.writeByte(s), - } - } - try self.stream.writeByte('"'); + assert(std.unicode.utf8ValidateSlice(string)); + try std.json.stringify(string, std.json.StringifyOptions{}, self.stream); } /// Writes the complete json into the output stream From edf487b12645ced9e0745deb32b47c594f1f3072 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 20:30:57 +1100 Subject: [PATCH 33/89] std: add options to std.json.stringfy to control escaping --- lib/std/json.zig | 93 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 65 insertions(+), 28 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index 98e800edc6..6a82d4c9d6 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -2357,10 +2357,38 @@ pub const StringifyOptions = struct { /// Controls the whitespace emitted whitespace: ?Whitespace = null, - // TODO: make escaping '/' in strings optional? + /// Should '/' be escaped in strings? + escape_solidus: bool = false, + + /// Should unicode characters be escaped in strings? + escape_unicode: bool = false, + // TODO: allow picking if []u8 is string or array? }; +fn outputUnicodeEscape( + codepoint: u21, + out_stream: var, +) !void { + if (codepoint <= 0xFFFF) { + // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), + // then it may be represented as a six-character sequence: a reverse solidus, followed + // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. + try out_stream.writeAll("\\u"); + try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); + } else { + assert(codepoint <= 0x10FFFF); + // To escape an extended character that is not in the Basic Multilingual Plane, + // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair. + const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800; + const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00; + try out_stream.writeAll("\\u"); + try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); + try out_stream.writeAll("\\u"); + try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); + } +} + pub fn stringify( value: var, options: StringifyOptions, @@ -2467,12 +2495,21 @@ pub fn stringify( var i: usize = 0; while (i < value.len) : (i += 1) { switch (value[i]) { - // normal ascii characters - 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => try out_stream.writeAll(value[i .. i + 1]), - // control characters with short escapes + // normal ascii character + 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => |c| try out_stream.writeByte(c), + // only 2 characters that *must* be escaped '\\' => try out_stream.writeAll("\\\\"), '\"' => try out_stream.writeAll("\\\""), - '/' => try out_stream.writeAll("\\/"), + // solidus is optional to escape + '/' => { + if (options.escape_solidus) { + try out_stream.writeAll("\\/"); + } else { + try out_stream.writeByte('\\'); + } + }, + // control characters with short escapes + // TODO: option to switch between unicode and 'short' forms? 0x8 => try out_stream.writeAll("\\b"), 0xC => try out_stream.writeAll("\\f"), '\n' => try out_stream.writeAll("\\n"), @@ -2480,22 +2517,12 @@ pub fn stringify( '\t' => try out_stream.writeAll("\\t"), else => { const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable; - const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable; - if (codepoint <= 0xFFFF) { - // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), - // then it may be represented as a six-character sequence: a reverse solidus, followed - // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. - try out_stream.writeAll("\\u"); - try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); + // control characters (only things left with 1 byte length) should always be printed as unicode escapes + if (ulen == 1 or options.escape_unicode) { + const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable; + try outputUnicodeEscape(codepoint, out_stream); } else { - // To escape an extended character that is not in the Basic Multilingual Plane, - // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair. - const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800; - const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00; - try out_stream.writeAll("\\u"); - try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); - try out_stream.writeAll("\\u"); - try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream); + try out_stream.writeAll(value[i .. i + ulen]); } i += ulen - 1; }, @@ -2609,15 +2636,25 @@ test "stringify basic types" { test "stringify string" { try teststringify("\"hello\"", "hello", StringifyOptions{}); try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{}); + try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{ .escape_unicode = true }); try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{}); - try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{}); - try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{}); - try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{}); - try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{}); - try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{}); - try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{}); - try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{}); - try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{}); + try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{80}\"", "with unicode\u{80}", StringifyOptions{}); + try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{FF}\"", "with unicode\u{FF}", StringifyOptions{}); + try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{100}\"", "with unicode\u{100}", StringifyOptions{}); + try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{800}\"", "with unicode\u{800}", StringifyOptions{}); + try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{8000}\"", "with unicode\u{8000}", StringifyOptions{}); + try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{D799}\"", "with unicode\u{D799}", StringifyOptions{}); + try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{10000}\"", "with unicode\u{10000}", StringifyOptions{}); + try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\u{10FFFF}\"", "with unicode\u{10FFFF}", StringifyOptions{}); + try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{ .escape_unicode = true }); } test "stringify tagged unions" { From 62fbb6b87406d8dd0b256ca42246b86972cd2faf Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 20:58:46 +1100 Subject: [PATCH 34/89] std: allow picking between serialising []u8 as string or array --- lib/std/json.zig | 45 +++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index 6a82d4c9d6..0934a97d26 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -2357,13 +2357,22 @@ pub const StringifyOptions = struct { /// Controls the whitespace emitted whitespace: ?Whitespace = null, - /// Should '/' be escaped in strings? - escape_solidus: bool = false, + /// Should []u8 be serialised as a string? or an array? + pub const StringOptions = union(enum) { + Array, - /// Should unicode characters be escaped in strings? - escape_unicode: bool = false, + /// String output options + const StringOutputOptions = struct { + /// Should '/' be escaped in strings? + escape_solidus: bool = false, - // TODO: allow picking if []u8 is string or array? + /// Should unicode characters be escaped in strings? + escape_unicode: bool = false, + }; + String: StringOutputOptions, + }; + + string: StringOptions = StringOptions{ .String = .{} }, }; fn outputUnicodeEscape( @@ -2490,7 +2499,7 @@ pub fn stringify( }, // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972) .Slice => { - if (ptr_info.child == u8 and std.unicode.utf8ValidateSlice(value)) { + if (ptr_info.child == u8 and options.string == .String and std.unicode.utf8ValidateSlice(value)) { try out_stream.writeByte('\"'); var i: usize = 0; while (i < value.len) : (i += 1) { @@ -2502,7 +2511,7 @@ pub fn stringify( '\"' => try out_stream.writeAll("\\\""), // solidus is optional to escape '/' => { - if (options.escape_solidus) { + if (options.string.String.escape_solidus) { try out_stream.writeAll("\\/"); } else { try out_stream.writeByte('\\'); @@ -2518,7 +2527,7 @@ pub fn stringify( else => { const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable; // control characters (only things left with 1 byte length) should always be printed as unicode escapes - if (ulen == 1 or options.escape_unicode) { + if (ulen == 1 or options.string.String.escape_unicode) { const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable; try outputUnicodeEscape(codepoint, out_stream); } else { @@ -2636,25 +2645,25 @@ test "stringify basic types" { test "stringify string" { try teststringify("\"hello\"", "hello", StringifyOptions{}); try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{}); - try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{}); - try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{80}\"", "with unicode\u{80}", StringifyOptions{}); - try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{FF}\"", "with unicode\u{FF}", StringifyOptions{}); - try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{100}\"", "with unicode\u{100}", StringifyOptions{}); - try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{800}\"", "with unicode\u{800}", StringifyOptions{}); - try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{8000}\"", "with unicode\u{8000}", StringifyOptions{}); - try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{D799}\"", "with unicode\u{D799}", StringifyOptions{}); - try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{10000}\"", "with unicode\u{10000}", StringifyOptions{}); - try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); try teststringify("\"with unicode\u{10FFFF}\"", "with unicode\u{10FFFF}", StringifyOptions{}); - try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{ .escape_unicode = true }); + try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } }); } test "stringify tagged unions" { From a32d88f12c65b48c8861748f0879bcb1b5be61d0 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 20:37:48 +1100 Subject: [PATCH 35/89] std: add support to std.json.stringify for null literals --- lib/std/json.zig | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/std/json.zig b/lib/std/json.zig index 0934a97d26..12020e6e25 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1239,7 +1239,7 @@ pub const Value = union(enum) { out_stream: var, ) @TypeOf(out_stream).Error!void { switch (value) { - .Null => try out_stream.writeAll("null"), + .Null => try stringify(null, options, out_stream), .Bool => |inner| try stringify(inner, options, out_stream), .Integer => |inner| try stringify(inner, options, out_stream), .Float => |inner| try stringify(inner, options, out_stream), @@ -2414,11 +2414,14 @@ pub fn stringify( .Bool => { return out_stream.writeAll(if (value) "true" else "false"); }, + .Null => { + return out_stream.writeAll("null"); + }, .Optional => { if (value) |payload| { return try stringify(payload, options, out_stream); } else { - return out_stream.writeAll("null"); + return try stringify(null, options, out_stream); } }, .Enum => { From 42cabe436675dd20d67de533e534df4f5cf46cd2 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 02:03:23 +1100 Subject: [PATCH 36/89] std: use json.StringifyOptions.Whitespace from json.WriteStream --- lib/std/json/write_stream.zig | 58 ++++++++++++----------------------- 1 file changed, 19 insertions(+), 39 deletions(-) diff --git a/lib/std/json/write_stream.zig b/lib/std/json/write_stream.zig index 07af75219e..ef53e5d5e0 100644 --- a/lib/std/json/write_stream.zig +++ b/lib/std/json/write_stream.zig @@ -21,14 +21,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { pub const Stream = OutStream; - /// The string used for indenting. - one_indent: []const u8 = " ", - - /// The string used as a newline character. - newline: []const u8 = "\n", - - /// The string used as spacing. - space: []const u8 = " ", + whitespace: std.json.StringifyOptions.Whitespace = std.json.StringifyOptions.Whitespace{ + .indent_level = 0, + .indent = .{ .Space = 1 }, + }, stream: OutStream, state_index: usize, @@ -49,12 +45,14 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField try self.stream.writeByte('['); self.state[self.state_index] = State.ArrayStart; + self.whitespace.indent_level += 1; } pub fn beginObject(self: *Self) !void { assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField try self.stream.writeByte('{'); self.state[self.state_index] = State.ObjectStart; + self.whitespace.indent_level += 1; } pub fn arrayElem(self: *Self) !void { @@ -90,8 +88,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { self.pushState(.Value); try self.indent(); try self.writeEscapedString(name); - try self.stream.writeAll(":"); - try self.stream.writeAll(self.space); + try self.stream.writeByte(':'); + if (self.whitespace.separator) { + try self.stream.writeByte(' '); + } }, } } @@ -103,10 +103,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { .ObjectStart => unreachable, .Object => unreachable, .ArrayStart => { + self.whitespace.indent_level -= 1; try self.stream.writeByte(']'); self.popState(); }, .Array => { + self.whitespace.indent_level -= 1; try self.indent(); self.popState(); try self.stream.writeByte(']'); @@ -121,10 +123,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { .ArrayStart => unreachable, .Array => unreachable, .ObjectStart => { + self.whitespace.indent_level -= 1; try self.stream.writeByte('}'); self.popState(); }, .Object => { + self.whitespace.indent_level -= 1; try self.indent(); self.popState(); try self.stream.writeByte('}'); @@ -187,39 +191,15 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { /// Writes the complete json into the output stream pub fn emitJson(self: *Self, json: std.json.Value) Stream.Error!void { - switch (json) { - .Null => try self.emitNull(), - .Bool => |inner| try self.emitBool(inner), - .Integer => |inner| try self.emitNumber(inner), - .Float => |inner| try self.emitNumber(inner), - .String => |inner| try self.emitString(inner), - .Array => |inner| { - try self.beginArray(); - for (inner.span()) |elem| { - try self.arrayElem(); - try self.emitJson(elem); - } - try self.endArray(); - }, - .Object => |inner| { - try self.beginObject(); - var it = inner.iterator(); - while (it.next()) |entry| { - try self.objectField(entry.key); - try self.emitJson(entry.value); - } - try self.endObject(); - }, - } + try json.jsonStringify(std.json.StringifyOptions{ + .whitespace = self.whitespace, + }, self.stream); } fn indent(self: *Self) !void { assert(self.state_index >= 1); - try self.stream.writeAll(self.newline); - var i: usize = 0; - while (i < self.state_index - 1) : (i += 1) { - try self.stream.writeAll(self.one_indent); - } + try self.stream.writeByte('\n'); + try self.whitespace.outputIndent(self.stream); } fn pushState(self: *Self, state: State) void { From 7a3d700fd9d6dcdb559aaae9159af6725b28defb Mon Sep 17 00:00:00 2001 From: daurnimator Date: Tue, 25 Feb 2020 02:07:06 +1100 Subject: [PATCH 37/89] std: introduce json.WriteStream.stringify --- lib/std/json/write_stream.zig | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/lib/std/json/write_stream.zig b/lib/std/json/write_stream.zig index ef53e5d5e0..60974a207e 100644 --- a/lib/std/json/write_stream.zig +++ b/lib/std/json/write_stream.zig @@ -138,13 +138,13 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { pub fn emitNull(self: *Self) !void { assert(self.state[self.state_index] == State.Value); - try self.stream.writeAll("null"); + try self.stringify(null); self.popState(); } pub fn emitBool(self: *Self, value: bool) !void { assert(self.state[self.state_index] == State.Value); - try std.json.stringify(value, std.json.StringifyOptions{}, self.stream); + try self.stringify(value); self.popState(); } @@ -186,14 +186,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { fn writeEscapedString(self: *Self, string: []const u8) !void { assert(std.unicode.utf8ValidateSlice(string)); - try std.json.stringify(string, std.json.StringifyOptions{}, self.stream); + try self.stringify(string); } /// Writes the complete json into the output stream pub fn emitJson(self: *Self, json: std.json.Value) Stream.Error!void { - try json.jsonStringify(std.json.StringifyOptions{ - .whitespace = self.whitespace, - }, self.stream); + try self.stringify(json); } fn indent(self: *Self) !void { @@ -210,6 +208,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type { fn popState(self: *Self) void { self.state_index -= 1; } + + fn stringify(self: *Self, value: var) !void { + try std.json.stringify(value, std.json.StringifyOptions{ + .whitespace = self.whitespace, + }, self.stream); + } }; } From 839d85e4405aef4856d1a35a6580226e997cc369 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 30 Mar 2020 21:41:54 -0400 Subject: [PATCH 38/89] fixes to 32-bit handling, to support 32-bit arm --- lib/std/zig/system.zig | 16 ++++++++++------ src-self-hosted/translate_c.zig | 26 +++++++++++++++++++++++--- src/link.cpp | 1 + src/os.cpp | 4 ++-- 4 files changed, 36 insertions(+), 11 deletions(-) diff --git a/lib/std/zig/system.zig b/lib/std/zig/system.zig index 1da2002f95..c65e8911dc 100644 --- a/lib/std/zig/system.zig +++ b/lib/std/zig/system.zig @@ -622,9 +622,10 @@ pub const NativeTargetInfo = struct { const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset); const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz); if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong; - _ = try preadMin(file, result.dynamic_linker.buffer[0..p_filesz], p_offset, p_filesz); - // PT_INTERP includes a null byte in p_filesz. - const len = p_filesz - 1; + const filesz = @intCast(usize, p_filesz); + _ = try preadMin(file, result.dynamic_linker.buffer[0..filesz], p_offset, filesz); + // PT_INTERP includes a null byte in filesz. + const len = filesz - 1; // dynamic_linker.max_byte is "max", not "len". // We know it will fit in u8 because we check against dynamic_linker.buffer.len above. result.dynamic_linker.max_byte = @intCast(u8, len - 1); @@ -645,7 +646,7 @@ pub const NativeTargetInfo = struct { { var dyn_off = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset); const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz); - const dyn_size: u64 = if (is_64) @sizeOf(elf.Elf64_Dyn) else @sizeOf(elf.Elf32_Dyn); + const dyn_size: usize = if (is_64) @sizeOf(elf.Elf64_Dyn) else @sizeOf(elf.Elf32_Dyn); const dyn_num = p_filesz / dyn_size; var dyn_buf: [16 * @sizeOf(elf.Elf64_Dyn)]u8 align(@alignOf(elf.Elf64_Dyn)) = undefined; var dyn_i: usize = 0; @@ -751,7 +752,10 @@ pub const NativeTargetInfo = struct { const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, shstrtab_len); const strtab = strtab_buf[0..strtab_read_len]; // TODO this pointer cast should not be necessary - const rpath_list = mem.spanZ(@ptrCast([*:0]u8, strtab[rpoff..].ptr)); + const rpoff_usize = std.math.cast(usize, rpoff) catch |err| switch (err) { + error.Overflow => return error.InvalidElfFile, + }; + const rpath_list = mem.spanZ(@ptrCast([*:0]u8, strtab[rpoff_usize..].ptr)); var it = mem.tokenize(rpath_list, ":"); while (it.next()) |rpath| { var dir = fs.cwd().openDir(rpath, .{}) catch |err| switch (err) { @@ -811,7 +815,7 @@ pub const NativeTargetInfo = struct { } fn preadMin(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize { - var i: u64 = 0; + var i: usize = 0; while (i < min_read_len) { const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) { error.OperationAborted => unreachable, // Windows-only diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index f1d7d66546..f8eec3578f 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -3845,7 +3845,9 @@ fn transCreateNodePtrType( } fn transCreateNodeAPInt(c: *Context, int: *const ZigClangAPSInt) !*ast.Node { - const num_limbs = ZigClangAPSInt_getNumWords(int); + const num_limbs = math.cast(usize, ZigClangAPSInt_getNumWords(int)) catch |err| switch (err) { + error.Overflow => return error.OutOfMemory, + }; var aps_int = int; const is_negative = ZigClangAPSInt_isSigned(int) and ZigClangAPSInt_isNegative(int); if (is_negative) @@ -3855,8 +3857,26 @@ fn transCreateNodeAPInt(c: *Context, int: *const ZigClangAPSInt) !*ast.Node { big.negate(); defer big.deinit(); const data = ZigClangAPSInt_getRawData(aps_int); - var i: @TypeOf(num_limbs) = 0; - while (i < num_limbs) : (i += 1) big.limbs[i] = data[i]; + switch (@sizeOf(std.math.big.Limb)) { + 8 => { + var i: usize = 0; + while (i < num_limbs) : (i += 1) { + big.limbs[i] = data[i]; + } + }, + 4 => { + var limb_i: usize = 0; + var data_i: usize = 0; + while (limb_i < num_limbs) : ({ + limb_i += 2; + data_i += 1; + }) { + big.limbs[limb_i] = @truncate(u32, data[data_i]); + big.limbs[limb_i + 1] = @truncate(u32, data[data_i] >> 32); + } + }, + else => @compileError("unimplemented"), + } const str = big.toString(c.a(), 10) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => unreachable, diff --git a/src/link.cpp b/src/link.cpp index ed6275ec3a..0d7a8a410b 100644 --- a/src/link.cpp +++ b/src/link.cpp @@ -651,6 +651,7 @@ static const char *build_libunwind(CodeGen *parent, Stage2ProgressNode *progress if (parent->is_single_threaded) { c_file->args.append("-D_LIBUNWIND_HAS_NO_THREADS"); } + c_file->args.append("-Wno-bitwise-conditional-parentheses"); c_source_files.append(c_file); } child_gen->c_source_files = c_source_files; diff --git a/src/os.cpp b/src/os.cpp index 872c0270f1..a1deb0f611 100644 --- a/src/os.cpp +++ b/src/os.cpp @@ -1097,8 +1097,8 @@ static Error set_file_times(OsFile file, OsTimeStamp ts) { return ErrorNone; #else struct timespec times[2] = { - { (time_t)ts.sec, (time_t)ts.nsec }, - { (time_t)ts.sec, (time_t)ts.nsec }, + { (time_t)ts.sec, (long)ts.nsec }, + { (time_t)ts.sec, (long)ts.nsec }, }; if (futimens(file, times) == -1) { switch (errno) { From 63409cf422c71fee64c55f2b77999ee94366400f Mon Sep 17 00:00:00 2001 From: daurnimator Date: Mon, 2 Mar 2020 23:30:53 +1100 Subject: [PATCH 39/89] std: linux syscall numbers are now an extensible enum --- lib/std/os.zig | 2 +- lib/std/os/bits/linux/arm-eabi.zig | 802 +++++++++--------- lib/std/os/bits/linux/arm64.zig | 589 +++++++------- lib/std/os/bits/linux/i386.zig | 854 ++++++++++---------- lib/std/os/bits/linux/mipsel.zig | 747 ++++++++--------- lib/std/os/bits/linux/riscv64.zig | 592 +++++++------- lib/std/os/bits/linux/x86_64.zig | 704 ++++++++-------- lib/std/os/linux.zig | 454 +++++------ lib/std/os/linux/arm-eabi.zig | 32 +- lib/std/os/linux/arm64.zig | 30 +- lib/std/os/linux/i386.zig | 34 +- lib/std/os/linux/mipsel.zig | 34 +- lib/std/os/linux/riscv64.zig | 30 +- lib/std/os/linux/tls.zig | 8 +- lib/std/os/linux/x86_64.zig | 30 +- lib/std/special/compiler_rt/clear_cache.zig | 2 +- 16 files changed, 2484 insertions(+), 2460 deletions(-) diff --git a/lib/std/os.zig b/lib/std/os.zig index f1184094db..e9e3b449f2 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -2065,7 +2065,7 @@ pub fn isatty(handle: fd_t) bool { } if (builtin.os.tag == .linux) { var wsz: linux.winsize = undefined; - return linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0; + return linux.syscall3(.ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0; } unreachable; } diff --git a/lib/std/os/bits/linux/arm-eabi.zig b/lib/std/os/bits/linux/arm-eabi.zig index 1824263fa4..7dd6941b5b 100644 --- a/lib/std/os/bits/linux/arm-eabi.zig +++ b/lib/std/os/bits/linux/arm-eabi.zig @@ -9,406 +9,410 @@ const sigset_t = linux.sigset_t; const uid_t = linux.uid_t; const gid_t = linux.gid_t; -pub const SYS_restart_syscall = 0; -pub const SYS_exit = 1; -pub const SYS_fork = 2; -pub const SYS_read = 3; -pub const SYS_write = 4; -pub const SYS_open = 5; -pub const SYS_close = 6; -pub const SYS_creat = 8; -pub const SYS_link = 9; -pub const SYS_unlink = 10; -pub const SYS_execve = 11; -pub const SYS_chdir = 12; -pub const SYS_mknod = 14; -pub const SYS_chmod = 15; -pub const SYS_lchown = 16; -pub const SYS_lseek = 19; -pub const SYS_getpid = 20; -pub const SYS_mount = 21; -pub const SYS_setuid = 23; -pub const SYS_getuid = 24; -pub const SYS_ptrace = 26; -pub const SYS_pause = 29; -pub const SYS_access = 33; -pub const SYS_nice = 34; -pub const SYS_sync = 36; -pub const SYS_kill = 37; -pub const SYS_rename = 38; -pub const SYS_mkdir = 39; -pub const SYS_rmdir = 40; -pub const SYS_dup = 41; -pub const SYS_pipe = 42; -pub const SYS_times = 43; -pub const SYS_brk = 45; -pub const SYS_setgid = 46; -pub const SYS_getgid = 47; -pub const SYS_geteuid = 49; -pub const SYS_getegid = 50; -pub const SYS_acct = 51; -pub const SYS_umount2 = 52; -pub const SYS_ioctl = 54; -pub const SYS_fcntl = 55; -pub const SYS_setpgid = 57; -pub const SYS_umask = 60; -pub const SYS_chroot = 61; -pub const SYS_ustat = 62; -pub const SYS_dup2 = 63; -pub const SYS_getppid = 64; -pub const SYS_getpgrp = 65; -pub const SYS_setsid = 66; -pub const SYS_sigaction = 67; -pub const SYS_setreuid = 70; -pub const SYS_setregid = 71; -pub const SYS_sigsuspend = 72; -pub const SYS_sigpending = 73; -pub const SYS_sethostname = 74; -pub const SYS_setrlimit = 75; -pub const SYS_getrusage = 77; -pub const SYS_gettimeofday = 78; -pub const SYS_settimeofday = 79; -pub const SYS_getgroups = 80; -pub const SYS_setgroups = 81; -pub const SYS_symlink = 83; -pub const SYS_readlink = 85; -pub const SYS_uselib = 86; -pub const SYS_swapon = 87; -pub const SYS_reboot = 88; -pub const SYS_munmap = 91; -pub const SYS_truncate = 92; -pub const SYS_ftruncate = 93; -pub const SYS_fchmod = 94; -pub const SYS_fchown = 95; -pub const SYS_getpriority = 96; -pub const SYS_setpriority = 97; -pub const SYS_statfs = 99; -pub const SYS_fstatfs = 100; -pub const SYS_syslog = 103; -pub const SYS_setitimer = 104; -pub const SYS_getitimer = 105; -pub const SYS_stat = 106; -pub const SYS_lstat = 107; -pub const SYS_fstat = 108; -pub const SYS_vhangup = 111; -pub const SYS_wait4 = 114; -pub const SYS_swapoff = 115; -pub const SYS_sysinfo = 116; -pub const SYS_fsync = 118; -pub const SYS_sigreturn = 119; -pub const SYS_clone = 120; -pub const SYS_setdomainname = 121; -pub const SYS_uname = 122; -pub const SYS_adjtimex = 124; -pub const SYS_mprotect = 125; -pub const SYS_sigprocmask = 126; -pub const SYS_init_module = 128; -pub const SYS_delete_module = 129; -pub const SYS_quotactl = 131; -pub const SYS_getpgid = 132; -pub const SYS_fchdir = 133; -pub const SYS_bdflush = 134; -pub const SYS_sysfs = 135; -pub const SYS_personality = 136; -pub const SYS_setfsuid = 138; -pub const SYS_setfsgid = 139; -pub const SYS__llseek = 140; -pub const SYS_getdents = 141; -pub const SYS__newselect = 142; -pub const SYS_flock = 143; -pub const SYS_msync = 144; -pub const SYS_readv = 145; -pub const SYS_writev = 146; -pub const SYS_getsid = 147; -pub const SYS_fdatasync = 148; -pub const SYS__sysctl = 149; -pub const SYS_mlock = 150; -pub const SYS_munlock = 151; -pub const SYS_mlockall = 152; -pub const SYS_munlockall = 153; -pub const SYS_sched_setparam = 154; -pub const SYS_sched_getparam = 155; -pub const SYS_sched_setscheduler = 156; -pub const SYS_sched_getscheduler = 157; -pub const SYS_sched_yield = 158; -pub const SYS_sched_get_priority_max = 159; -pub const SYS_sched_get_priority_min = 160; -pub const SYS_sched_rr_get_interval = 161; -pub const SYS_nanosleep = 162; -pub const SYS_mremap = 163; -pub const SYS_setresuid = 164; -pub const SYS_getresuid = 165; -pub const SYS_poll = 168; -pub const SYS_nfsservctl = 169; -pub const SYS_setresgid = 170; -pub const SYS_getresgid = 171; -pub const SYS_prctl = 172; -pub const SYS_rt_sigreturn = 173; -pub const SYS_rt_sigaction = 174; -pub const SYS_rt_sigprocmask = 175; -pub const SYS_rt_sigpending = 176; -pub const SYS_rt_sigtimedwait = 177; -pub const SYS_rt_sigqueueinfo = 178; -pub const SYS_rt_sigsuspend = 179; -pub const SYS_pread64 = 180; -pub const SYS_pwrite64 = 181; -pub const SYS_chown = 182; -pub const SYS_getcwd = 183; -pub const SYS_capget = 184; -pub const SYS_capset = 185; -pub const SYS_sigaltstack = 186; -pub const SYS_sendfile = 187; -pub const SYS_vfork = 190; -pub const SYS_ugetrlimit = 191; -pub const SYS_mmap2 = 192; -pub const SYS_truncate64 = 193; -pub const SYS_ftruncate64 = 194; -pub const SYS_stat64 = 195; -pub const SYS_lstat64 = 196; -pub const SYS_fstat64 = 197; -pub const SYS_lchown32 = 198; -pub const SYS_getuid32 = 199; -pub const SYS_getgid32 = 200; -pub const SYS_geteuid32 = 201; -pub const SYS_getegid32 = 202; -pub const SYS_setreuid32 = 203; -pub const SYS_setregid32 = 204; -pub const SYS_getgroups32 = 205; -pub const SYS_setgroups32 = 206; -pub const SYS_fchown32 = 207; -pub const SYS_setresuid32 = 208; -pub const SYS_getresuid32 = 209; -pub const SYS_setresgid32 = 210; -pub const SYS_getresgid32 = 211; -pub const SYS_chown32 = 212; -pub const SYS_setuid32 = 213; -pub const SYS_setgid32 = 214; -pub const SYS_setfsuid32 = 215; -pub const SYS_setfsgid32 = 216; -pub const SYS_getdents64 = 217; -pub const SYS_pivot_root = 218; -pub const SYS_mincore = 219; -pub const SYS_madvise = 220; -pub const SYS_fcntl64 = 221; -pub const SYS_gettid = 224; -pub const SYS_readahead = 225; -pub const SYS_setxattr = 226; -pub const SYS_lsetxattr = 227; -pub const SYS_fsetxattr = 228; -pub const SYS_getxattr = 229; -pub const SYS_lgetxattr = 230; -pub const SYS_fgetxattr = 231; -pub const SYS_listxattr = 232; -pub const SYS_llistxattr = 233; -pub const SYS_flistxattr = 234; -pub const SYS_removexattr = 235; -pub const SYS_lremovexattr = 236; -pub const SYS_fremovexattr = 237; -pub const SYS_tkill = 238; -pub const SYS_sendfile64 = 239; -pub const SYS_futex = 240; -pub const SYS_sched_setaffinity = 241; -pub const SYS_sched_getaffinity = 242; -pub const SYS_io_setup = 243; -pub const SYS_io_destroy = 244; -pub const SYS_io_getevents = 245; -pub const SYS_io_submit = 246; -pub const SYS_io_cancel = 247; -pub const SYS_exit_group = 248; -pub const SYS_lookup_dcookie = 249; -pub const SYS_epoll_create = 250; -pub const SYS_epoll_ctl = 251; -pub const SYS_epoll_wait = 252; -pub const SYS_remap_file_pages = 253; -pub const SYS_set_tid_address = 256; -pub const SYS_timer_create = 257; -pub const SYS_timer_settime = 258; -pub const SYS_timer_gettime = 259; -pub const SYS_timer_getoverrun = 260; -pub const SYS_timer_delete = 261; -pub const SYS_clock_settime = 262; -pub const SYS_clock_gettime = 263; -pub const SYS_clock_getres = 264; -pub const SYS_clock_nanosleep = 265; -pub const SYS_statfs64 = 266; -pub const SYS_fstatfs64 = 267; -pub const SYS_tgkill = 268; -pub const SYS_utimes = 269; -pub const SYS_fadvise64_64 = 270; -pub const SYS_arm_fadvise64_64 = 270; -pub const SYS_pciconfig_iobase = 271; -pub const SYS_pciconfig_read = 272; -pub const SYS_pciconfig_write = 273; -pub const SYS_mq_open = 274; -pub const SYS_mq_unlink = 275; -pub const SYS_mq_timedsend = 276; -pub const SYS_mq_timedreceive = 277; -pub const SYS_mq_notify = 278; -pub const SYS_mq_getsetattr = 279; -pub const SYS_waitid = 280; -pub const SYS_socket = 281; -pub const SYS_bind = 282; -pub const SYS_connect = 283; -pub const SYS_listen = 284; -pub const SYS_accept = 285; -pub const SYS_getsockname = 286; -pub const SYS_getpeername = 287; -pub const SYS_socketpair = 288; -pub const SYS_send = 289; -pub const SYS_sendto = 290; -pub const SYS_recv = 291; -pub const SYS_recvfrom = 292; -pub const SYS_shutdown = 293; -pub const SYS_setsockopt = 294; -pub const SYS_getsockopt = 295; -pub const SYS_sendmsg = 296; -pub const SYS_recvmsg = 297; -pub const SYS_semop = 298; -pub const SYS_semget = 299; -pub const SYS_semctl = 300; -pub const SYS_msgsnd = 301; -pub const SYS_msgrcv = 302; -pub const SYS_msgget = 303; -pub const SYS_msgctl = 304; -pub const SYS_shmat = 305; -pub const SYS_shmdt = 306; -pub const SYS_shmget = 307; -pub const SYS_shmctl = 308; -pub const SYS_add_key = 309; -pub const SYS_request_key = 310; -pub const SYS_keyctl = 311; -pub const SYS_semtimedop = 312; -pub const SYS_vserver = 313; -pub const SYS_ioprio_set = 314; -pub const SYS_ioprio_get = 315; -pub const SYS_inotify_init = 316; -pub const SYS_inotify_add_watch = 317; -pub const SYS_inotify_rm_watch = 318; -pub const SYS_mbind = 319; -pub const SYS_get_mempolicy = 320; -pub const SYS_set_mempolicy = 321; -pub const SYS_openat = 322; -pub const SYS_mkdirat = 323; -pub const SYS_mknodat = 324; -pub const SYS_fchownat = 325; -pub const SYS_futimesat = 326; -pub const SYS_fstatat64 = 327; -pub const SYS_unlinkat = 328; -pub const SYS_renameat = 329; -pub const SYS_linkat = 330; -pub const SYS_symlinkat = 331; -pub const SYS_readlinkat = 332; -pub const SYS_fchmodat = 333; -pub const SYS_faccessat = 334; -pub const SYS_pselect6 = 335; -pub const SYS_ppoll = 336; -pub const SYS_unshare = 337; -pub const SYS_set_robust_list = 338; -pub const SYS_get_robust_list = 339; -pub const SYS_splice = 340; -pub const SYS_sync_file_range2 = 341; -pub const SYS_arm_sync_file_range = 341; -pub const SYS_tee = 342; -pub const SYS_vmsplice = 343; -pub const SYS_move_pages = 344; -pub const SYS_getcpu = 345; -pub const SYS_epoll_pwait = 346; -pub const SYS_kexec_load = 347; -pub const SYS_utimensat = 348; -pub const SYS_signalfd = 349; -pub const SYS_timerfd_create = 350; -pub const SYS_eventfd = 351; -pub const SYS_fallocate = 352; -pub const SYS_timerfd_settime = 353; -pub const SYS_timerfd_gettime = 354; -pub const SYS_signalfd4 = 355; -pub const SYS_eventfd2 = 356; -pub const SYS_epoll_create1 = 357; -pub const SYS_dup3 = 358; -pub const SYS_pipe2 = 359; -pub const SYS_inotify_init1 = 360; -pub const SYS_preadv = 361; -pub const SYS_pwritev = 362; -pub const SYS_rt_tgsigqueueinfo = 363; -pub const SYS_perf_event_open = 364; -pub const SYS_recvmmsg = 365; -pub const SYS_accept4 = 366; -pub const SYS_fanotify_init = 367; -pub const SYS_fanotify_mark = 368; -pub const SYS_prlimit64 = 369; -pub const SYS_name_to_handle_at = 370; -pub const SYS_open_by_handle_at = 371; -pub const SYS_clock_adjtime = 372; -pub const SYS_syncfs = 373; -pub const SYS_sendmmsg = 374; -pub const SYS_setns = 375; -pub const SYS_process_vm_readv = 376; -pub const SYS_process_vm_writev = 377; -pub const SYS_kcmp = 378; -pub const SYS_finit_module = 379; -pub const SYS_sched_setattr = 380; -pub const SYS_sched_getattr = 381; -pub const SYS_renameat2 = 382; -pub const SYS_seccomp = 383; -pub const SYS_getrandom = 384; -pub const SYS_memfd_create = 385; -pub const SYS_bpf = 386; -pub const SYS_execveat = 387; -pub const SYS_userfaultfd = 388; -pub const SYS_membarrier = 389; -pub const SYS_mlock2 = 390; -pub const SYS_copy_file_range = 391; -pub const SYS_preadv2 = 392; -pub const SYS_pwritev2 = 393; -pub const SYS_pkey_mprotect = 394; -pub const SYS_pkey_alloc = 395; -pub const SYS_pkey_free = 396; -pub const SYS_statx = 397; -pub const SYS_rseq = 398; -pub const SYS_io_pgetevents = 399; -pub const SYS_migrate_pages = 400; -pub const SYS_kexec_file_load = 401; -pub const SYS_clock_gettime64 = 403; -pub const SYS_clock_settime64 = 404; -pub const SYS_clock_adjtime64 = 405; -pub const SYS_clock_getres_time64 = 406; -pub const SYS_clock_nanosleep_time64 = 407; -pub const SYS_timer_gettime64 = 408; -pub const SYS_timer_settime64 = 409; -pub const SYS_timerfd_gettime64 = 410; -pub const SYS_timerfd_settime64 = 411; -pub const SYS_utimensat_time64 = 412; -pub const SYS_pselect6_time64 = 413; -pub const SYS_ppoll_time64 = 414; -pub const SYS_io_pgetevents_time64 = 416; -pub const SYS_recvmmsg_time64 = 417; -pub const SYS_mq_timedsend_time64 = 418; -pub const SYS_mq_timedreceive_time64 = 419; -pub const SYS_semtimedop_time64 = 420; -pub const SYS_rt_sigtimedwait_time64 = 421; -pub const SYS_futex_time64 = 422; -pub const SYS_sched_rr_get_interval_time64 = 423; -pub const SYS_pidfd_send_signal = 424; -pub const SYS_io_uring_setup = 425; -pub const SYS_io_uring_enter = 426; -pub const SYS_io_uring_register = 427; -pub const SYS_open_tree = 428; -pub const SYS_move_mount = 429; -pub const SYS_fsopen = 430; -pub const SYS_fsconfig = 431; -pub const SYS_fsmount = 432; -pub const SYS_fspick = 433; -pub const SYS_pidfd_open = 434; -pub const SYS_clone3 = 435; -pub const SYS_openat2 = 437; -pub const SYS_pidfd_getfd = 438; +pub const SYS = extern enum(usize) { + restart_syscall = 0, + exit = 1, + fork = 2, + read = 3, + write = 4, + open = 5, + close = 6, + creat = 8, + link = 9, + unlink = 10, + execve = 11, + chdir = 12, + mknod = 14, + chmod = 15, + lchown = 16, + lseek = 19, + getpid = 20, + mount = 21, + setuid = 23, + getuid = 24, + ptrace = 26, + pause = 29, + access = 33, + nice = 34, + sync = 36, + kill = 37, + rename = 38, + mkdir = 39, + rmdir = 40, + dup = 41, + pipe = 42, + times = 43, + brk = 45, + setgid = 46, + getgid = 47, + geteuid = 49, + getegid = 50, + acct = 51, + umount2 = 52, + ioctl = 54, + fcntl = 55, + setpgid = 57, + umask = 60, + chroot = 61, + ustat = 62, + dup2 = 63, + getppid = 64, + getpgrp = 65, + setsid = 66, + sigaction = 67, + setreuid = 70, + setregid = 71, + sigsuspend = 72, + sigpending = 73, + sethostname = 74, + setrlimit = 75, + getrusage = 77, + gettimeofday = 78, + settimeofday = 79, + getgroups = 80, + setgroups = 81, + symlink = 83, + readlink = 85, + uselib = 86, + swapon = 87, + reboot = 88, + munmap = 91, + truncate = 92, + ftruncate = 93, + fchmod = 94, + fchown = 95, + getpriority = 96, + setpriority = 97, + statfs = 99, + fstatfs = 100, + syslog = 103, + setitimer = 104, + getitimer = 105, + stat = 106, + lstat = 107, + fstat = 108, + vhangup = 111, + wait4 = 114, + swapoff = 115, + sysinfo = 116, + fsync = 118, + sigreturn = 119, + clone = 120, + setdomainname = 121, + uname = 122, + adjtimex = 124, + mprotect = 125, + sigprocmask = 126, + init_module = 128, + delete_module = 129, + quotactl = 131, + getpgid = 132, + fchdir = 133, + bdflush = 134, + sysfs = 135, + personality = 136, + setfsuid = 138, + setfsgid = 139, + _llseek = 140, + getdents = 141, + _newselect = 142, + flock = 143, + msync = 144, + readv = 145, + writev = 146, + getsid = 147, + fdatasync = 148, + _sysctl = 149, + mlock = 150, + munlock = 151, + mlockall = 152, + munlockall = 153, + sched_setparam = 154, + sched_getparam = 155, + sched_setscheduler = 156, + sched_getscheduler = 157, + sched_yield = 158, + sched_get_priority_max = 159, + sched_get_priority_min = 160, + sched_rr_get_interval = 161, + nanosleep = 162, + mremap = 163, + setresuid = 164, + getresuid = 165, + poll = 168, + nfsservctl = 169, + setresgid = 170, + getresgid = 171, + prctl = 172, + rt_sigreturn = 173, + rt_sigaction = 174, + rt_sigprocmask = 175, + rt_sigpending = 176, + rt_sigtimedwait = 177, + rt_sigqueueinfo = 178, + rt_sigsuspend = 179, + pread64 = 180, + pwrite64 = 181, + chown = 182, + getcwd = 183, + capget = 184, + capset = 185, + sigaltstack = 186, + sendfile = 187, + vfork = 190, + ugetrlimit = 191, + mmap2 = 192, + truncate64 = 193, + ftruncate64 = 194, + stat64 = 195, + lstat64 = 196, + fstat64 = 197, + lchown32 = 198, + getuid32 = 199, + getgid32 = 200, + geteuid32 = 201, + getegid32 = 202, + setreuid32 = 203, + setregid32 = 204, + getgroups32 = 205, + setgroups32 = 206, + fchown32 = 207, + setresuid32 = 208, + getresuid32 = 209, + setresgid32 = 210, + getresgid32 = 211, + chown32 = 212, + setuid32 = 213, + setgid32 = 214, + setfsuid32 = 215, + setfsgid32 = 216, + getdents64 = 217, + pivot_root = 218, + mincore = 219, + madvise = 220, + fcntl64 = 221, + gettid = 224, + readahead = 225, + setxattr = 226, + lsetxattr = 227, + fsetxattr = 228, + getxattr = 229, + lgetxattr = 230, + fgetxattr = 231, + listxattr = 232, + llistxattr = 233, + flistxattr = 234, + removexattr = 235, + lremovexattr = 236, + fremovexattr = 237, + tkill = 238, + sendfile64 = 239, + futex = 240, + sched_setaffinity = 241, + sched_getaffinity = 242, + io_setup = 243, + io_destroy = 244, + io_getevents = 245, + io_submit = 246, + io_cancel = 247, + exit_group = 248, + lookup_dcookie = 249, + epoll_create = 250, + epoll_ctl = 251, + epoll_wait = 252, + remap_file_pages = 253, + set_tid_address = 256, + timer_create = 257, + timer_settime = 258, + timer_gettime = 259, + timer_getoverrun = 260, + timer_delete = 261, + clock_settime = 262, + clock_gettime = 263, + clock_getres = 264, + clock_nanosleep = 265, + statfs64 = 266, + fstatfs64 = 267, + tgkill = 268, + utimes = 269, + fadvise64_64 = 270, + arm_fadvise64_64 = 270, + pciconfig_iobase = 271, + pciconfig_read = 272, + pciconfig_write = 273, + mq_open = 274, + mq_unlink = 275, + mq_timedsend = 276, + mq_timedreceive = 277, + mq_notify = 278, + mq_getsetattr = 279, + waitid = 280, + socket = 281, + bind = 282, + connect = 283, + listen = 284, + accept = 285, + getsockname = 286, + getpeername = 287, + socketpair = 288, + send = 289, + sendto = 290, + recv = 291, + recvfrom = 292, + shutdown = 293, + setsockopt = 294, + getsockopt = 295, + sendmsg = 296, + recvmsg = 297, + semop = 298, + semget = 299, + semctl = 300, + msgsnd = 301, + msgrcv = 302, + msgget = 303, + msgctl = 304, + shmat = 305, + shmdt = 306, + shmget = 307, + shmctl = 308, + add_key = 309, + request_key = 310, + keyctl = 311, + semtimedop = 312, + vserver = 313, + ioprio_set = 314, + ioprio_get = 315, + inotify_init = 316, + inotify_add_watch = 317, + inotify_rm_watch = 318, + mbind = 319, + get_mempolicy = 320, + set_mempolicy = 321, + openat = 322, + mkdirat = 323, + mknodat = 324, + fchownat = 325, + futimesat = 326, + fstatat64 = 327, + unlinkat = 328, + renameat = 329, + linkat = 330, + symlinkat = 331, + readlinkat = 332, + fchmodat = 333, + faccessat = 334, + pselect6 = 335, + ppoll = 336, + unshare = 337, + set_robust_list = 338, + get_robust_list = 339, + splice = 340, + sync_file_range2 = 341, + arm_sync_file_range = 341, + tee = 342, + vmsplice = 343, + move_pages = 344, + getcpu = 345, + epoll_pwait = 346, + kexec_load = 347, + utimensat = 348, + signalfd = 349, + timerfd_create = 350, + eventfd = 351, + fallocate = 352, + timerfd_settime = 353, + timerfd_gettime = 354, + signalfd4 = 355, + eventfd2 = 356, + epoll_create1 = 357, + dup3 = 358, + pipe2 = 359, + inotify_init1 = 360, + preadv = 361, + pwritev = 362, + rt_tgsigqueueinfo = 363, + perf_event_open = 364, + recvmmsg = 365, + accept4 = 366, + fanotify_init = 367, + fanotify_mark = 368, + prlimit64 = 369, + name_to_handle_at = 370, + open_by_handle_at = 371, + clock_adjtime = 372, + syncfs = 373, + sendmmsg = 374, + setns = 375, + process_vm_readv = 376, + process_vm_writev = 377, + kcmp = 378, + finit_module = 379, + sched_setattr = 380, + sched_getattr = 381, + renameat2 = 382, + seccomp = 383, + getrandom = 384, + memfd_create = 385, + bpf = 386, + execveat = 387, + userfaultfd = 388, + membarrier = 389, + mlock2 = 390, + copy_file_range = 391, + preadv2 = 392, + pwritev2 = 393, + pkey_mprotect = 394, + pkey_alloc = 395, + pkey_free = 396, + statx = 397, + rseq = 398, + io_pgetevents = 399, + migrate_pages = 400, + kexec_file_load = 401, + clock_gettime64 = 403, + clock_settime64 = 404, + clock_adjtime64 = 405, + clock_getres_time64 = 406, + clock_nanosleep_time64 = 407, + timer_gettime64 = 408, + timer_settime64 = 409, + timerfd_gettime64 = 410, + timerfd_settime64 = 411, + utimensat_time64 = 412, + pselect6_time64 = 413, + ppoll_time64 = 414, + io_pgetevents_time64 = 416, + recvmmsg_time64 = 417, + mq_timedsend_time64 = 418, + mq_timedreceive_time64 = 419, + semtimedop_time64 = 420, + rt_sigtimedwait_time64 = 421, + futex_time64 = 422, + sched_rr_get_interval_time64 = 423, + pidfd_send_signal = 424, + io_uring_setup = 425, + io_uring_enter = 426, + io_uring_register = 427, + open_tree = 428, + move_mount = 429, + fsopen = 430, + fsconfig = 431, + fsmount = 432, + fspick = 433, + pidfd_open = 434, + clone3 = 435, + openat2 = 437, + pidfd_getfd = 438, -pub const SYS_breakpoint = 0x0f0001; -pub const SYS_cacheflush = 0x0f0002; -pub const SYS_usr26 = 0x0f0003; -pub const SYS_usr32 = 0x0f0004; -pub const SYS_set_tls = 0x0f0005; -pub const SYS_get_tls = 0x0f0006; + breakpoint = 0x0f0001, + cacheflush = 0x0f0002, + usr26 = 0x0f0003, + usr32 = 0x0f0004, + set_tls = 0x0f0005, + get_tls = 0x0f0006, + + _, +}; pub const MMAP2_UNIT = 4096; diff --git a/lib/std/os/bits/linux/arm64.zig b/lib/std/os/bits/linux/arm64.zig index 79a363f844..7e745a51d8 100644 --- a/lib/std/os/bits/linux/arm64.zig +++ b/lib/std/os/bits/linux/arm64.zig @@ -10,300 +10,303 @@ const uid_t = linux.uid_t; const gid_t = linux.gid_t; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; +pub const SYS = extern enum(usize) { + io_setup = 0, + io_destroy = 1, + io_submit = 2, + io_cancel = 3, + io_getevents = 4, + setxattr = 5, + lsetxattr = 6, + fsetxattr = 7, + getxattr = 8, + lgetxattr = 9, + fgetxattr = 10, + listxattr = 11, + llistxattr = 12, + flistxattr = 13, + removexattr = 14, + lremovexattr = 15, + fremovexattr = 16, + getcwd = 17, + lookup_dcookie = 18, + eventfd2 = 19, + epoll_create1 = 20, + epoll_ctl = 21, + epoll_pwait = 22, + dup = 23, + dup3 = 24, + fcntl = 25, + inotify_init1 = 26, + inotify_add_watch = 27, + inotify_rm_watch = 28, + ioctl = 29, + ioprio_set = 30, + ioprio_get = 31, + flock = 32, + mknodat = 33, + mkdirat = 34, + unlinkat = 35, + symlinkat = 36, + linkat = 37, + renameat = 38, + umount2 = 39, + mount = 40, + pivot_root = 41, + nfsservctl = 42, + statfs = 43, + fstatfs = 44, + truncate = 45, + ftruncate = 46, + fallocate = 47, + faccessat = 48, + chdir = 49, + fchdir = 50, + chroot = 51, + fchmod = 52, + fchmodat = 53, + fchownat = 54, + fchown = 55, + openat = 56, + close = 57, + vhangup = 58, + pipe2 = 59, + quotactl = 60, + getdents64 = 61, + lseek = 62, + read = 63, + write = 64, + readv = 65, + writev = 66, + pread64 = 67, + pwrite64 = 68, + preadv = 69, + pwritev = 70, + sendfile = 71, + pselect6 = 72, + ppoll = 73, + signalfd4 = 74, + vmsplice = 75, + splice = 76, + tee = 77, + readlinkat = 78, + fstatat = 79, + fstat = 80, + sync = 81, + fsync = 82, + fdatasync = 83, + sync_file_range2 = 84, + sync_file_range = 84, + timerfd_create = 85, + timerfd_settime = 86, + timerfd_gettime = 87, + utimensat = 88, + acct = 89, + capget = 90, + capset = 91, + personality = 92, + exit = 93, + exit_group = 94, + waitid = 95, + set_tid_address = 96, + unshare = 97, + futex = 98, + set_robust_list = 99, + get_robust_list = 100, + nanosleep = 101, + getitimer = 102, + setitimer = 103, + kexec_load = 104, + init_module = 105, + delete_module = 106, + timer_create = 107, + timer_gettime = 108, + timer_getoverrun = 109, + timer_settime = 110, + timer_delete = 111, + clock_settime = 112, + clock_gettime = 113, + clock_getres = 114, + clock_nanosleep = 115, + syslog = 116, + ptrace = 117, + sched_setparam = 118, + sched_setscheduler = 119, + sched_getscheduler = 120, + sched_getparam = 121, + sched_setaffinity = 122, + sched_getaffinity = 123, + sched_yield = 124, + sched_get_priority_max = 125, + sched_get_priority_min = 126, + sched_rr_get_interval = 127, + restart_syscall = 128, + kill = 129, + tkill = 130, + tgkill = 131, + sigaltstack = 132, + rt_sigsuspend = 133, + rt_sigaction = 134, + rt_sigprocmask = 135, + rt_sigpending = 136, + rt_sigtimedwait = 137, + rt_sigqueueinfo = 138, + rt_sigreturn = 139, + setpriority = 140, + getpriority = 141, + reboot = 142, + setregid = 143, + setgid = 144, + setreuid = 145, + setuid = 146, + setresuid = 147, + getresuid = 148, + setresgid = 149, + getresgid = 150, + setfsuid = 151, + setfsgid = 152, + times = 153, + setpgid = 154, + getpgid = 155, + getsid = 156, + setsid = 157, + getgroups = 158, + setgroups = 159, + uname = 160, + sethostname = 161, + setdomainname = 162, + getrlimit = 163, + setrlimit = 164, + getrusage = 165, + umask = 166, + prctl = 167, + getcpu = 168, + gettimeofday = 169, + settimeofday = 170, + adjtimex = 171, + getpid = 172, + getppid = 173, + getuid = 174, + geteuid = 175, + getgid = 176, + getegid = 177, + gettid = 178, + sysinfo = 179, + mq_open = 180, + mq_unlink = 181, + mq_timedsend = 182, + mq_timedreceive = 183, + mq_notify = 184, + mq_getsetattr = 185, + msgget = 186, + msgctl = 187, + msgrcv = 188, + msgsnd = 189, + semget = 190, + semctl = 191, + semtimedop = 192, + semop = 193, + shmget = 194, + shmctl = 195, + shmat = 196, + shmdt = 197, + socket = 198, + socketpair = 199, + bind = 200, + listen = 201, + accept = 202, + connect = 203, + getsockname = 204, + getpeername = 205, + sendto = 206, + recvfrom = 207, + setsockopt = 208, + getsockopt = 209, + shutdown = 210, + sendmsg = 211, + recvmsg = 212, + readahead = 213, + brk = 214, + munmap = 215, + mremap = 216, + add_key = 217, + request_key = 218, + keyctl = 219, + clone = 220, + execve = 221, + mmap = 222, + fadvise64 = 223, + swapon = 224, + swapoff = 225, + mprotect = 226, + msync = 227, + mlock = 228, + munlock = 229, + mlockall = 230, + munlockall = 231, + mincore = 232, + madvise = 233, + remap_file_pages = 234, + mbind = 235, + get_mempolicy = 236, + set_mempolicy = 237, + migrate_pages = 238, + move_pages = 239, + rt_tgsigqueueinfo = 240, + perf_event_open = 241, + accept4 = 242, + recvmmsg = 243, + arch_specific_syscall = 244, + wait4 = 260, + prlimit64 = 261, + fanotify_init = 262, + fanotify_mark = 263, + clock_adjtime = 266, + syncfs = 267, + setns = 268, + sendmmsg = 269, + process_vm_readv = 270, + process_vm_writev = 271, + kcmp = 272, + finit_module = 273, + sched_setattr = 274, + sched_getattr = 275, + renameat2 = 276, + seccomp = 277, + getrandom = 278, + memfd_create = 279, + bpf = 280, + execveat = 281, + userfaultfd = 282, + membarrier = 283, + mlock2 = 284, + copy_file_range = 285, + preadv2 = 286, + pwritev2 = 287, + pkey_mprotect = 288, + pkey_alloc = 289, + pkey_free = 290, + statx = 291, + io_pgetevents = 292, + rseq = 293, + kexec_file_load = 294, + pidfd_send_signal = 424, + io_uring_setup = 425, + io_uring_enter = 426, + io_uring_register = 427, + open_tree = 428, + move_mount = 429, + fsopen = 430, + fsconfig = 431, + fsmount = 432, + fspick = 433, + pidfd_open = 434, + clone3 = 435, + openat2 = 437, + pidfd_getfd = 438, -pub const SYS_io_setup = 0; -pub const SYS_io_destroy = 1; -pub const SYS_io_submit = 2; -pub const SYS_io_cancel = 3; -pub const SYS_io_getevents = 4; -pub const SYS_setxattr = 5; -pub const SYS_lsetxattr = 6; -pub const SYS_fsetxattr = 7; -pub const SYS_getxattr = 8; -pub const SYS_lgetxattr = 9; -pub const SYS_fgetxattr = 10; -pub const SYS_listxattr = 11; -pub const SYS_llistxattr = 12; -pub const SYS_flistxattr = 13; -pub const SYS_removexattr = 14; -pub const SYS_lremovexattr = 15; -pub const SYS_fremovexattr = 16; -pub const SYS_getcwd = 17; -pub const SYS_lookup_dcookie = 18; -pub const SYS_eventfd2 = 19; -pub const SYS_epoll_create1 = 20; -pub const SYS_epoll_ctl = 21; -pub const SYS_epoll_pwait = 22; -pub const SYS_dup = 23; -pub const SYS_dup3 = 24; -pub const SYS_fcntl = 25; -pub const SYS_inotify_init1 = 26; -pub const SYS_inotify_add_watch = 27; -pub const SYS_inotify_rm_watch = 28; -pub const SYS_ioctl = 29; -pub const SYS_ioprio_set = 30; -pub const SYS_ioprio_get = 31; -pub const SYS_flock = 32; -pub const SYS_mknodat = 33; -pub const SYS_mkdirat = 34; -pub const SYS_unlinkat = 35; -pub const SYS_symlinkat = 36; -pub const SYS_linkat = 37; -pub const SYS_renameat = 38; -pub const SYS_umount2 = 39; -pub const SYS_mount = 40; -pub const SYS_pivot_root = 41; -pub const SYS_nfsservctl = 42; -pub const SYS_statfs = 43; -pub const SYS_fstatfs = 44; -pub const SYS_truncate = 45; -pub const SYS_ftruncate = 46; -pub const SYS_fallocate = 47; -pub const SYS_faccessat = 48; -pub const SYS_chdir = 49; -pub const SYS_fchdir = 50; -pub const SYS_chroot = 51; -pub const SYS_fchmod = 52; -pub const SYS_fchmodat = 53; -pub const SYS_fchownat = 54; -pub const SYS_fchown = 55; -pub const SYS_openat = 56; -pub const SYS_close = 57; -pub const SYS_vhangup = 58; -pub const SYS_pipe2 = 59; -pub const SYS_quotactl = 60; -pub const SYS_getdents64 = 61; -pub const SYS_lseek = 62; -pub const SYS_read = 63; -pub const SYS_write = 64; -pub const SYS_readv = 65; -pub const SYS_writev = 66; -pub const SYS_pread64 = 67; -pub const SYS_pwrite64 = 68; -pub const SYS_preadv = 69; -pub const SYS_pwritev = 70; -pub const SYS_sendfile = 71; -pub const SYS_pselect6 = 72; -pub const SYS_ppoll = 73; -pub const SYS_signalfd4 = 74; -pub const SYS_vmsplice = 75; -pub const SYS_splice = 76; -pub const SYS_tee = 77; -pub const SYS_readlinkat = 78; -pub const SYS_fstatat = 79; -pub const SYS_fstat = 80; -pub const SYS_sync = 81; -pub const SYS_fsync = 82; -pub const SYS_fdatasync = 83; -pub const SYS_sync_file_range2 = 84; -pub const SYS_sync_file_range = 84; -pub const SYS_timerfd_create = 85; -pub const SYS_timerfd_settime = 86; -pub const SYS_timerfd_gettime = 87; -pub const SYS_utimensat = 88; -pub const SYS_acct = 89; -pub const SYS_capget = 90; -pub const SYS_capset = 91; -pub const SYS_personality = 92; -pub const SYS_exit = 93; -pub const SYS_exit_group = 94; -pub const SYS_waitid = 95; -pub const SYS_set_tid_address = 96; -pub const SYS_unshare = 97; -pub const SYS_futex = 98; -pub const SYS_set_robust_list = 99; -pub const SYS_get_robust_list = 100; -pub const SYS_nanosleep = 101; -pub const SYS_getitimer = 102; -pub const SYS_setitimer = 103; -pub const SYS_kexec_load = 104; -pub const SYS_init_module = 105; -pub const SYS_delete_module = 106; -pub const SYS_timer_create = 107; -pub const SYS_timer_gettime = 108; -pub const SYS_timer_getoverrun = 109; -pub const SYS_timer_settime = 110; -pub const SYS_timer_delete = 111; -pub const SYS_clock_settime = 112; -pub const SYS_clock_gettime = 113; -pub const SYS_clock_getres = 114; -pub const SYS_clock_nanosleep = 115; -pub const SYS_syslog = 116; -pub const SYS_ptrace = 117; -pub const SYS_sched_setparam = 118; -pub const SYS_sched_setscheduler = 119; -pub const SYS_sched_getscheduler = 120; -pub const SYS_sched_getparam = 121; -pub const SYS_sched_setaffinity = 122; -pub const SYS_sched_getaffinity = 123; -pub const SYS_sched_yield = 124; -pub const SYS_sched_get_priority_max = 125; -pub const SYS_sched_get_priority_min = 126; -pub const SYS_sched_rr_get_interval = 127; -pub const SYS_restart_syscall = 128; -pub const SYS_kill = 129; -pub const SYS_tkill = 130; -pub const SYS_tgkill = 131; -pub const SYS_sigaltstack = 132; -pub const SYS_rt_sigsuspend = 133; -pub const SYS_rt_sigaction = 134; -pub const SYS_rt_sigprocmask = 135; -pub const SYS_rt_sigpending = 136; -pub const SYS_rt_sigtimedwait = 137; -pub const SYS_rt_sigqueueinfo = 138; -pub const SYS_rt_sigreturn = 139; -pub const SYS_setpriority = 140; -pub const SYS_getpriority = 141; -pub const SYS_reboot = 142; -pub const SYS_setregid = 143; -pub const SYS_setgid = 144; -pub const SYS_setreuid = 145; -pub const SYS_setuid = 146; -pub const SYS_setresuid = 147; -pub const SYS_getresuid = 148; -pub const SYS_setresgid = 149; -pub const SYS_getresgid = 150; -pub const SYS_setfsuid = 151; -pub const SYS_setfsgid = 152; -pub const SYS_times = 153; -pub const SYS_setpgid = 154; -pub const SYS_getpgid = 155; -pub const SYS_getsid = 156; -pub const SYS_setsid = 157; -pub const SYS_getgroups = 158; -pub const SYS_setgroups = 159; -pub const SYS_uname = 160; -pub const SYS_sethostname = 161; -pub const SYS_setdomainname = 162; -pub const SYS_getrlimit = 163; -pub const SYS_setrlimit = 164; -pub const SYS_getrusage = 165; -pub const SYS_umask = 166; -pub const SYS_prctl = 167; -pub const SYS_getcpu = 168; -pub const SYS_gettimeofday = 169; -pub const SYS_settimeofday = 170; -pub const SYS_adjtimex = 171; -pub const SYS_getpid = 172; -pub const SYS_getppid = 173; -pub const SYS_getuid = 174; -pub const SYS_geteuid = 175; -pub const SYS_getgid = 176; -pub const SYS_getegid = 177; -pub const SYS_gettid = 178; -pub const SYS_sysinfo = 179; -pub const SYS_mq_open = 180; -pub const SYS_mq_unlink = 181; -pub const SYS_mq_timedsend = 182; -pub const SYS_mq_timedreceive = 183; -pub const SYS_mq_notify = 184; -pub const SYS_mq_getsetattr = 185; -pub const SYS_msgget = 186; -pub const SYS_msgctl = 187; -pub const SYS_msgrcv = 188; -pub const SYS_msgsnd = 189; -pub const SYS_semget = 190; -pub const SYS_semctl = 191; -pub const SYS_semtimedop = 192; -pub const SYS_semop = 193; -pub const SYS_shmget = 194; -pub const SYS_shmctl = 195; -pub const SYS_shmat = 196; -pub const SYS_shmdt = 197; -pub const SYS_socket = 198; -pub const SYS_socketpair = 199; -pub const SYS_bind = 200; -pub const SYS_listen = 201; -pub const SYS_accept = 202; -pub const SYS_connect = 203; -pub const SYS_getsockname = 204; -pub const SYS_getpeername = 205; -pub const SYS_sendto = 206; -pub const SYS_recvfrom = 207; -pub const SYS_setsockopt = 208; -pub const SYS_getsockopt = 209; -pub const SYS_shutdown = 210; -pub const SYS_sendmsg = 211; -pub const SYS_recvmsg = 212; -pub const SYS_readahead = 213; -pub const SYS_brk = 214; -pub const SYS_munmap = 215; -pub const SYS_mremap = 216; -pub const SYS_add_key = 217; -pub const SYS_request_key = 218; -pub const SYS_keyctl = 219; -pub const SYS_clone = 220; -pub const SYS_execve = 221; -pub const SYS_mmap = 222; -pub const SYS_fadvise64 = 223; -pub const SYS_swapon = 224; -pub const SYS_swapoff = 225; -pub const SYS_mprotect = 226; -pub const SYS_msync = 227; -pub const SYS_mlock = 228; -pub const SYS_munlock = 229; -pub const SYS_mlockall = 230; -pub const SYS_munlockall = 231; -pub const SYS_mincore = 232; -pub const SYS_madvise = 233; -pub const SYS_remap_file_pages = 234; -pub const SYS_mbind = 235; -pub const SYS_get_mempolicy = 236; -pub const SYS_set_mempolicy = 237; -pub const SYS_migrate_pages = 238; -pub const SYS_move_pages = 239; -pub const SYS_rt_tgsigqueueinfo = 240; -pub const SYS_perf_event_open = 241; -pub const SYS_accept4 = 242; -pub const SYS_recvmmsg = 243; -pub const SYS_arch_specific_syscall = 244; -pub const SYS_wait4 = 260; -pub const SYS_prlimit64 = 261; -pub const SYS_fanotify_init = 262; -pub const SYS_fanotify_mark = 263; -pub const SYS_clock_adjtime = 266; -pub const SYS_syncfs = 267; -pub const SYS_setns = 268; -pub const SYS_sendmmsg = 269; -pub const SYS_process_vm_readv = 270; -pub const SYS_process_vm_writev = 271; -pub const SYS_kcmp = 272; -pub const SYS_finit_module = 273; -pub const SYS_sched_setattr = 274; -pub const SYS_sched_getattr = 275; -pub const SYS_renameat2 = 276; -pub const SYS_seccomp = 277; -pub const SYS_getrandom = 278; -pub const SYS_memfd_create = 279; -pub const SYS_bpf = 280; -pub const SYS_execveat = 281; -pub const SYS_userfaultfd = 282; -pub const SYS_membarrier = 283; -pub const SYS_mlock2 = 284; -pub const SYS_copy_file_range = 285; -pub const SYS_preadv2 = 286; -pub const SYS_pwritev2 = 287; -pub const SYS_pkey_mprotect = 288; -pub const SYS_pkey_alloc = 289; -pub const SYS_pkey_free = 290; -pub const SYS_statx = 291; -pub const SYS_io_pgetevents = 292; -pub const SYS_rseq = 293; -pub const SYS_kexec_file_load = 294; -pub const SYS_pidfd_send_signal = 424; -pub const SYS_io_uring_setup = 425; -pub const SYS_io_uring_enter = 426; -pub const SYS_io_uring_register = 427; -pub const SYS_open_tree = 428; -pub const SYS_move_mount = 429; -pub const SYS_fsopen = 430; -pub const SYS_fsconfig = 431; -pub const SYS_fsmount = 432; -pub const SYS_fspick = 433; -pub const SYS_pidfd_open = 434; -pub const SYS_clone3 = 435; -pub const SYS_openat2 = 437; -pub const SYS_pidfd_getfd = 438; + _, +}; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/bits/linux/i386.zig b/lib/std/os/bits/linux/i386.zig index 233340f6a1..f6dfef29bd 100644 --- a/lib/std/os/bits/linux/i386.zig +++ b/lib/std/os/bits/linux/i386.zig @@ -11,431 +11,435 @@ const gid_t = linux.gid_t; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; -pub const SYS_restart_syscall = 0; -pub const SYS_exit = 1; -pub const SYS_fork = 2; -pub const SYS_read = 3; -pub const SYS_write = 4; -pub const SYS_open = 5; -pub const SYS_close = 6; -pub const SYS_waitpid = 7; -pub const SYS_creat = 8; -pub const SYS_link = 9; -pub const SYS_unlink = 10; -pub const SYS_execve = 11; -pub const SYS_chdir = 12; -pub const SYS_time = 13; -pub const SYS_mknod = 14; -pub const SYS_chmod = 15; -pub const SYS_lchown = 16; -pub const SYS_break = 17; -pub const SYS_oldstat = 18; -pub const SYS_lseek = 19; -pub const SYS_getpid = 20; -pub const SYS_mount = 21; -pub const SYS_umount = 22; -pub const SYS_setuid = 23; -pub const SYS_getuid = 24; -pub const SYS_stime = 25; -pub const SYS_ptrace = 26; -pub const SYS_alarm = 27; -pub const SYS_oldfstat = 28; -pub const SYS_pause = 29; -pub const SYS_utime = 30; -pub const SYS_stty = 31; -pub const SYS_gtty = 32; -pub const SYS_access = 33; -pub const SYS_nice = 34; -pub const SYS_ftime = 35; -pub const SYS_sync = 36; -pub const SYS_kill = 37; -pub const SYS_rename = 38; -pub const SYS_mkdir = 39; -pub const SYS_rmdir = 40; -pub const SYS_dup = 41; -pub const SYS_pipe = 42; -pub const SYS_times = 43; -pub const SYS_prof = 44; -pub const SYS_brk = 45; -pub const SYS_setgid = 46; -pub const SYS_getgid = 47; -pub const SYS_signal = 48; -pub const SYS_geteuid = 49; -pub const SYS_getegid = 50; -pub const SYS_acct = 51; -pub const SYS_umount2 = 52; -pub const SYS_lock = 53; -pub const SYS_ioctl = 54; -pub const SYS_fcntl = 55; -pub const SYS_mpx = 56; -pub const SYS_setpgid = 57; -pub const SYS_ulimit = 58; -pub const SYS_oldolduname = 59; -pub const SYS_umask = 60; -pub const SYS_chroot = 61; -pub const SYS_ustat = 62; -pub const SYS_dup2 = 63; -pub const SYS_getppid = 64; -pub const SYS_getpgrp = 65; -pub const SYS_setsid = 66; -pub const SYS_sigaction = 67; -pub const SYS_sgetmask = 68; -pub const SYS_ssetmask = 69; -pub const SYS_setreuid = 70; -pub const SYS_setregid = 71; -pub const SYS_sigsuspend = 72; -pub const SYS_sigpending = 73; -pub const SYS_sethostname = 74; -pub const SYS_setrlimit = 75; -pub const SYS_getrlimit = 76; -pub const SYS_getrusage = 77; -pub const SYS_gettimeofday = 78; -pub const SYS_settimeofday = 79; -pub const SYS_getgroups = 80; -pub const SYS_setgroups = 81; -pub const SYS_select = 82; -pub const SYS_symlink = 83; -pub const SYS_oldlstat = 84; -pub const SYS_readlink = 85; -pub const SYS_uselib = 86; -pub const SYS_swapon = 87; -pub const SYS_reboot = 88; -pub const SYS_readdir = 89; -pub const SYS_mmap = 90; -pub const SYS_munmap = 91; -pub const SYS_truncate = 92; -pub const SYS_ftruncate = 93; -pub const SYS_fchmod = 94; -pub const SYS_fchown = 95; -pub const SYS_getpriority = 96; -pub const SYS_setpriority = 97; -pub const SYS_profil = 98; -pub const SYS_statfs = 99; -pub const SYS_fstatfs = 100; -pub const SYS_ioperm = 101; -pub const SYS_socketcall = 102; -pub const SYS_syslog = 103; -pub const SYS_setitimer = 104; -pub const SYS_getitimer = 105; -pub const SYS_stat = 106; -pub const SYS_lstat = 107; -pub const SYS_fstat = 108; -pub const SYS_olduname = 109; -pub const SYS_iopl = 110; -pub const SYS_vhangup = 111; -pub const SYS_idle = 112; -pub const SYS_vm86old = 113; -pub const SYS_wait4 = 114; -pub const SYS_swapoff = 115; -pub const SYS_sysinfo = 116; -pub const SYS_ipc = 117; -pub const SYS_fsync = 118; -pub const SYS_sigreturn = 119; -pub const SYS_clone = 120; -pub const SYS_setdomainname = 121; -pub const SYS_uname = 122; -pub const SYS_modify_ldt = 123; -pub const SYS_adjtimex = 124; -pub const SYS_mprotect = 125; -pub const SYS_sigprocmask = 126; -pub const SYS_create_module = 127; -pub const SYS_init_module = 128; -pub const SYS_delete_module = 129; -pub const SYS_get_kernel_syms = 130; -pub const SYS_quotactl = 131; -pub const SYS_getpgid = 132; -pub const SYS_fchdir = 133; -pub const SYS_bdflush = 134; -pub const SYS_sysfs = 135; -pub const SYS_personality = 136; -pub const SYS_afs_syscall = 137; -pub const SYS_setfsuid = 138; -pub const SYS_setfsgid = 139; -pub const SYS__llseek = 140; -pub const SYS_getdents = 141; -pub const SYS__newselect = 142; -pub const SYS_flock = 143; -pub const SYS_msync = 144; -pub const SYS_readv = 145; -pub const SYS_writev = 146; -pub const SYS_getsid = 147; -pub const SYS_fdatasync = 148; -pub const SYS__sysctl = 149; -pub const SYS_mlock = 150; -pub const SYS_munlock = 151; -pub const SYS_mlockall = 152; -pub const SYS_munlockall = 153; -pub const SYS_sched_setparam = 154; -pub const SYS_sched_getparam = 155; -pub const SYS_sched_setscheduler = 156; -pub const SYS_sched_getscheduler = 157; -pub const SYS_sched_yield = 158; -pub const SYS_sched_get_priority_max = 159; -pub const SYS_sched_get_priority_min = 160; -pub const SYS_sched_rr_get_interval = 161; -pub const SYS_nanosleep = 162; -pub const SYS_mremap = 163; -pub const SYS_setresuid = 164; -pub const SYS_getresuid = 165; -pub const SYS_vm86 = 166; -pub const SYS_query_module = 167; -pub const SYS_poll = 168; -pub const SYS_nfsservctl = 169; -pub const SYS_setresgid = 170; -pub const SYS_getresgid = 171; -pub const SYS_prctl = 172; -pub const SYS_rt_sigreturn = 173; -pub const SYS_rt_sigaction = 174; -pub const SYS_rt_sigprocmask = 175; -pub const SYS_rt_sigpending = 176; -pub const SYS_rt_sigtimedwait = 177; -pub const SYS_rt_sigqueueinfo = 178; -pub const SYS_rt_sigsuspend = 179; -pub const SYS_pread64 = 180; -pub const SYS_pwrite64 = 181; -pub const SYS_chown = 182; -pub const SYS_getcwd = 183; -pub const SYS_capget = 184; -pub const SYS_capset = 185; -pub const SYS_sigaltstack = 186; -pub const SYS_sendfile = 187; -pub const SYS_getpmsg = 188; -pub const SYS_putpmsg = 189; -pub const SYS_vfork = 190; -pub const SYS_ugetrlimit = 191; -pub const SYS_mmap2 = 192; -pub const SYS_truncate64 = 193; -pub const SYS_ftruncate64 = 194; -pub const SYS_stat64 = 195; -pub const SYS_lstat64 = 196; -pub const SYS_fstat64 = 197; -pub const SYS_lchown32 = 198; -pub const SYS_getuid32 = 199; -pub const SYS_getgid32 = 200; -pub const SYS_geteuid32 = 201; -pub const SYS_getegid32 = 202; -pub const SYS_setreuid32 = 203; -pub const SYS_setregid32 = 204; -pub const SYS_getgroups32 = 205; -pub const SYS_setgroups32 = 206; -pub const SYS_fchown32 = 207; -pub const SYS_setresuid32 = 208; -pub const SYS_getresuid32 = 209; -pub const SYS_setresgid32 = 210; -pub const SYS_getresgid32 = 211; -pub const SYS_chown32 = 212; -pub const SYS_setuid32 = 213; -pub const SYS_setgid32 = 214; -pub const SYS_setfsuid32 = 215; -pub const SYS_setfsgid32 = 216; -pub const SYS_pivot_root = 217; -pub const SYS_mincore = 218; -pub const SYS_madvise = 219; -pub const SYS_getdents64 = 220; -pub const SYS_fcntl64 = 221; -pub const SYS_gettid = 224; -pub const SYS_readahead = 225; -pub const SYS_setxattr = 226; -pub const SYS_lsetxattr = 227; -pub const SYS_fsetxattr = 228; -pub const SYS_getxattr = 229; -pub const SYS_lgetxattr = 230; -pub const SYS_fgetxattr = 231; -pub const SYS_listxattr = 232; -pub const SYS_llistxattr = 233; -pub const SYS_flistxattr = 234; -pub const SYS_removexattr = 235; -pub const SYS_lremovexattr = 236; -pub const SYS_fremovexattr = 237; -pub const SYS_tkill = 238; -pub const SYS_sendfile64 = 239; -pub const SYS_futex = 240; -pub const SYS_sched_setaffinity = 241; -pub const SYS_sched_getaffinity = 242; -pub const SYS_set_thread_area = 243; -pub const SYS_get_thread_area = 244; -pub const SYS_io_setup = 245; -pub const SYS_io_destroy = 246; -pub const SYS_io_getevents = 247; -pub const SYS_io_submit = 248; -pub const SYS_io_cancel = 249; -pub const SYS_fadvise64 = 250; -pub const SYS_exit_group = 252; -pub const SYS_lookup_dcookie = 253; -pub const SYS_epoll_create = 254; -pub const SYS_epoll_ctl = 255; -pub const SYS_epoll_wait = 256; -pub const SYS_remap_file_pages = 257; -pub const SYS_set_tid_address = 258; -pub const SYS_timer_create = 259; -pub const SYS_timer_settime = SYS_timer_create + 1; -pub const SYS_timer_gettime = SYS_timer_create + 2; -pub const SYS_timer_getoverrun = SYS_timer_create + 3; -pub const SYS_timer_delete = SYS_timer_create + 4; -pub const SYS_clock_settime = SYS_timer_create + 5; -pub const SYS_clock_gettime = SYS_timer_create + 6; -pub const SYS_clock_getres = SYS_timer_create + 7; -pub const SYS_clock_nanosleep = SYS_timer_create + 8; -pub const SYS_statfs64 = 268; -pub const SYS_fstatfs64 = 269; -pub const SYS_tgkill = 270; -pub const SYS_utimes = 271; -pub const SYS_fadvise64_64 = 272; -pub const SYS_vserver = 273; -pub const SYS_mbind = 274; -pub const SYS_get_mempolicy = 275; -pub const SYS_set_mempolicy = 276; -pub const SYS_mq_open = 277; -pub const SYS_mq_unlink = SYS_mq_open + 1; -pub const SYS_mq_timedsend = SYS_mq_open + 2; -pub const SYS_mq_timedreceive = SYS_mq_open + 3; -pub const SYS_mq_notify = SYS_mq_open + 4; -pub const SYS_mq_getsetattr = SYS_mq_open + 5; -pub const SYS_kexec_load = 283; -pub const SYS_waitid = 284; -pub const SYS_add_key = 286; -pub const SYS_request_key = 287; -pub const SYS_keyctl = 288; -pub const SYS_ioprio_set = 289; -pub const SYS_ioprio_get = 290; -pub const SYS_inotify_init = 291; -pub const SYS_inotify_add_watch = 292; -pub const SYS_inotify_rm_watch = 293; -pub const SYS_migrate_pages = 294; -pub const SYS_openat = 295; -pub const SYS_mkdirat = 296; -pub const SYS_mknodat = 297; -pub const SYS_fchownat = 298; -pub const SYS_futimesat = 299; -pub const SYS_fstatat64 = 300; -pub const SYS_unlinkat = 301; -pub const SYS_renameat = 302; -pub const SYS_linkat = 303; -pub const SYS_symlinkat = 304; -pub const SYS_readlinkat = 305; -pub const SYS_fchmodat = 306; -pub const SYS_faccessat = 307; -pub const SYS_pselect6 = 308; -pub const SYS_ppoll = 309; -pub const SYS_unshare = 310; -pub const SYS_set_robust_list = 311; -pub const SYS_get_robust_list = 312; -pub const SYS_splice = 313; -pub const SYS_sync_file_range = 314; -pub const SYS_tee = 315; -pub const SYS_vmsplice = 316; -pub const SYS_move_pages = 317; -pub const SYS_getcpu = 318; -pub const SYS_epoll_pwait = 319; -pub const SYS_utimensat = 320; -pub const SYS_signalfd = 321; -pub const SYS_timerfd_create = 322; -pub const SYS_eventfd = 323; -pub const SYS_fallocate = 324; -pub const SYS_timerfd_settime = 325; -pub const SYS_timerfd_gettime = 326; -pub const SYS_signalfd4 = 327; -pub const SYS_eventfd2 = 328; -pub const SYS_epoll_create1 = 329; -pub const SYS_dup3 = 330; -pub const SYS_pipe2 = 331; -pub const SYS_inotify_init1 = 332; -pub const SYS_preadv = 333; -pub const SYS_pwritev = 334; -pub const SYS_rt_tgsigqueueinfo = 335; -pub const SYS_perf_event_open = 336; -pub const SYS_recvmmsg = 337; -pub const SYS_fanotify_init = 338; -pub const SYS_fanotify_mark = 339; -pub const SYS_prlimit64 = 340; -pub const SYS_name_to_handle_at = 341; -pub const SYS_open_by_handle_at = 342; -pub const SYS_clock_adjtime = 343; -pub const SYS_syncfs = 344; -pub const SYS_sendmmsg = 345; -pub const SYS_setns = 346; -pub const SYS_process_vm_readv = 347; -pub const SYS_process_vm_writev = 348; -pub const SYS_kcmp = 349; -pub const SYS_finit_module = 350; -pub const SYS_sched_setattr = 351; -pub const SYS_sched_getattr = 352; -pub const SYS_renameat2 = 353; -pub const SYS_seccomp = 354; -pub const SYS_getrandom = 355; -pub const SYS_memfd_create = 356; -pub const SYS_bpf = 357; -pub const SYS_execveat = 358; -pub const SYS_socket = 359; -pub const SYS_socketpair = 360; -pub const SYS_bind = 361; -pub const SYS_connect = 362; -pub const SYS_listen = 363; -pub const SYS_accept4 = 364; -pub const SYS_getsockopt = 365; -pub const SYS_setsockopt = 366; -pub const SYS_getsockname = 367; -pub const SYS_getpeername = 368; -pub const SYS_sendto = 369; -pub const SYS_sendmsg = 370; -pub const SYS_recvfrom = 371; -pub const SYS_recvmsg = 372; -pub const SYS_shutdown = 373; -pub const SYS_userfaultfd = 374; -pub const SYS_membarrier = 375; -pub const SYS_mlock2 = 376; -pub const SYS_copy_file_range = 377; -pub const SYS_preadv2 = 378; -pub const SYS_pwritev2 = 379; -pub const SYS_pkey_mprotect = 380; -pub const SYS_pkey_alloc = 381; -pub const SYS_pkey_free = 382; -pub const SYS_statx = 383; -pub const SYS_arch_prctl = 384; -pub const SYS_io_pgetevents = 385; -pub const SYS_rseq = 386; -pub const SYS_semget = 393; -pub const SYS_semctl = 394; -pub const SYS_shmget = 395; -pub const SYS_shmctl = 396; -pub const SYS_shmat = 397; -pub const SYS_shmdt = 398; -pub const SYS_msgget = 399; -pub const SYS_msgsnd = 400; -pub const SYS_msgrcv = 401; -pub const SYS_msgctl = 402; -pub const SYS_clock_gettime64 = 403; -pub const SYS_clock_settime64 = 404; -pub const SYS_clock_adjtime64 = 405; -pub const SYS_clock_getres_time64 = 406; -pub const SYS_clock_nanosleep_time64 = 407; -pub const SYS_timer_gettime64 = 408; -pub const SYS_timer_settime64 = 409; -pub const SYS_timerfd_gettime64 = 410; -pub const SYS_timerfd_settime64 = 411; -pub const SYS_utimensat_time64 = 412; -pub const SYS_pselect6_time64 = 413; -pub const SYS_ppoll_time64 = 414; -pub const SYS_io_pgetevents_time64 = 416; -pub const SYS_recvmmsg_time64 = 417; -pub const SYS_mq_timedsend_time64 = 418; -pub const SYS_mq_timedreceive_time64 = 419; -pub const SYS_semtimedop_time64 = 420; -pub const SYS_rt_sigtimedwait_time64 = 421; -pub const SYS_futex_time64 = 422; -pub const SYS_sched_rr_get_interval_time64 = 423; -pub const SYS_pidfd_send_signal = 424; -pub const SYS_io_uring_setup = 425; -pub const SYS_io_uring_enter = 426; -pub const SYS_io_uring_register = 427; -pub const SYS_open_tree = 428; -pub const SYS_move_mount = 429; -pub const SYS_fsopen = 430; -pub const SYS_fsconfig = 431; -pub const SYS_fsmount = 432; -pub const SYS_fspick = 433; -pub const SYS_openat2 = 437; -pub const SYS_pidfd_getfd = 438; +pub const SYS = extern enum(usize) { + restart_syscall = 0, + exit = 1, + fork = 2, + read = 3, + write = 4, + open = 5, + close = 6, + waitpid = 7, + creat = 8, + link = 9, + unlink = 10, + execve = 11, + chdir = 12, + time = 13, + mknod = 14, + chmod = 15, + lchown = 16, + @"break" = 17, + oldstat = 18, + lseek = 19, + getpid = 20, + mount = 21, + umount = 22, + setuid = 23, + getuid = 24, + stime = 25, + ptrace = 26, + alarm = 27, + oldfstat = 28, + pause = 29, + utime = 30, + stty = 31, + gtty = 32, + access = 33, + nice = 34, + ftime = 35, + sync = 36, + kill = 37, + rename = 38, + mkdir = 39, + rmdir = 40, + dup = 41, + pipe = 42, + times = 43, + prof = 44, + brk = 45, + setgid = 46, + getgid = 47, + signal = 48, + geteuid = 49, + getegid = 50, + acct = 51, + umount2 = 52, + lock = 53, + ioctl = 54, + fcntl = 55, + mpx = 56, + setpgid = 57, + ulimit = 58, + oldolduname = 59, + umask = 60, + chroot = 61, + ustat = 62, + dup2 = 63, + getppid = 64, + getpgrp = 65, + setsid = 66, + sigaction = 67, + sgetmask = 68, + ssetmask = 69, + setreuid = 70, + setregid = 71, + sigsuspend = 72, + sigpending = 73, + sethostname = 74, + setrlimit = 75, + getrlimit = 76, + getrusage = 77, + gettimeofday = 78, + settimeofday = 79, + getgroups = 80, + setgroups = 81, + select = 82, + symlink = 83, + oldlstat = 84, + readlink = 85, + uselib = 86, + swapon = 87, + reboot = 88, + readdir = 89, + mmap = 90, + munmap = 91, + truncate = 92, + ftruncate = 93, + fchmod = 94, + fchown = 95, + getpriority = 96, + setpriority = 97, + profil = 98, + statfs = 99, + fstatfs = 100, + ioperm = 101, + socketcall = 102, + syslog = 103, + setitimer = 104, + getitimer = 105, + stat = 106, + lstat = 107, + fstat = 108, + olduname = 109, + iopl = 110, + vhangup = 111, + idle = 112, + vm86old = 113, + wait4 = 114, + swapoff = 115, + sysinfo = 116, + ipc = 117, + fsync = 118, + sigreturn = 119, + clone = 120, + setdomainname = 121, + uname = 122, + modify_ldt = 123, + adjtimex = 124, + mprotect = 125, + sigprocmask = 126, + create_module = 127, + init_module = 128, + delete_module = 129, + get_kernel_syms = 130, + quotactl = 131, + getpgid = 132, + fchdir = 133, + bdflush = 134, + sysfs = 135, + personality = 136, + afs_syscall = 137, + setfsuid = 138, + setfsgid = 139, + _llseek = 140, + getdents = 141, + _newselect = 142, + flock = 143, + msync = 144, + readv = 145, + writev = 146, + getsid = 147, + fdatasync = 148, + _sysctl = 149, + mlock = 150, + munlock = 151, + mlockall = 152, + munlockall = 153, + sched_setparam = 154, + sched_getparam = 155, + sched_setscheduler = 156, + sched_getscheduler = 157, + sched_yield = 158, + sched_get_priority_max = 159, + sched_get_priority_min = 160, + sched_rr_get_interval = 161, + nanosleep = 162, + mremap = 163, + setresuid = 164, + getresuid = 165, + vm86 = 166, + query_module = 167, + poll = 168, + nfsservctl = 169, + setresgid = 170, + getresgid = 171, + prctl = 172, + rt_sigreturn = 173, + rt_sigaction = 174, + rt_sigprocmask = 175, + rt_sigpending = 176, + rt_sigtimedwait = 177, + rt_sigqueueinfo = 178, + rt_sigsuspend = 179, + pread64 = 180, + pwrite64 = 181, + chown = 182, + getcwd = 183, + capget = 184, + capset = 185, + sigaltstack = 186, + sendfile = 187, + getpmsg = 188, + putpmsg = 189, + vfork = 190, + ugetrlimit = 191, + mmap2 = 192, + truncate64 = 193, + ftruncate64 = 194, + stat64 = 195, + lstat64 = 196, + fstat64 = 197, + lchown32 = 198, + getuid32 = 199, + getgid32 = 200, + geteuid32 = 201, + getegid32 = 202, + setreuid32 = 203, + setregid32 = 204, + getgroups32 = 205, + setgroups32 = 206, + fchown32 = 207, + setresuid32 = 208, + getresuid32 = 209, + setresgid32 = 210, + getresgid32 = 211, + chown32 = 212, + setuid32 = 213, + setgid32 = 214, + setfsuid32 = 215, + setfsgid32 = 216, + pivot_root = 217, + mincore = 218, + madvise = 219, + getdents64 = 220, + fcntl64 = 221, + gettid = 224, + readahead = 225, + setxattr = 226, + lsetxattr = 227, + fsetxattr = 228, + getxattr = 229, + lgetxattr = 230, + fgetxattr = 231, + listxattr = 232, + llistxattr = 233, + flistxattr = 234, + removexattr = 235, + lremovexattr = 236, + fremovexattr = 237, + tkill = 238, + sendfile64 = 239, + futex = 240, + sched_setaffinity = 241, + sched_getaffinity = 242, + set_thread_area = 243, + get_thread_area = 244, + io_setup = 245, + io_destroy = 246, + io_getevents = 247, + io_submit = 248, + io_cancel = 249, + fadvise64 = 250, + exit_group = 252, + lookup_dcookie = 253, + epoll_create = 254, + epoll_ctl = 255, + epoll_wait = 256, + remap_file_pages = 257, + set_tid_address = 258, + timer_create = 259, + timer_settime, // SYS_timer_create + 1 + timer_gettime, // SYS_timer_create + 2 + timer_getoverrun, // SYS_timer_create + 3 + timer_delete, // SYS_timer_create + 4 + clock_settime, // SYS_timer_create + 5 + clock_gettime, // SYS_timer_create + 6 + clock_getres, // SYS_timer_create + 7 + clock_nanosleep, // SYS_timer_create + 8 + statfs64 = 268, + fstatfs64 = 269, + tgkill = 270, + utimes = 271, + fadvise64_64 = 272, + vserver = 273, + mbind = 274, + get_mempolicy = 275, + set_mempolicy = 276, + mq_open = 277, + mq_unlink, // SYS_mq_open + 1 + mq_timedsend, // SYS_mq_open + 2 + mq_timedreceive, // SYS_mq_open + 3 + mq_notify, // SYS_mq_open + 4 + mq_getsetattr, // SYS_mq_open + 5 + kexec_load = 283, + waitid = 284, + add_key = 286, + request_key = 287, + keyctl = 288, + ioprio_set = 289, + ioprio_get = 290, + inotify_init = 291, + inotify_add_watch = 292, + inotify_rm_watch = 293, + migrate_pages = 294, + openat = 295, + mkdirat = 296, + mknodat = 297, + fchownat = 298, + futimesat = 299, + fstatat64 = 300, + unlinkat = 301, + renameat = 302, + linkat = 303, + symlinkat = 304, + readlinkat = 305, + fchmodat = 306, + faccessat = 307, + pselect6 = 308, + ppoll = 309, + unshare = 310, + set_robust_list = 311, + get_robust_list = 312, + splice = 313, + sync_file_range = 314, + tee = 315, + vmsplice = 316, + move_pages = 317, + getcpu = 318, + epoll_pwait = 319, + utimensat = 320, + signalfd = 321, + timerfd_create = 322, + eventfd = 323, + fallocate = 324, + timerfd_settime = 325, + timerfd_gettime = 326, + signalfd4 = 327, + eventfd2 = 328, + epoll_create1 = 329, + dup3 = 330, + pipe2 = 331, + inotify_init1 = 332, + preadv = 333, + pwritev = 334, + rt_tgsigqueueinfo = 335, + perf_event_open = 336, + recvmmsg = 337, + fanotify_init = 338, + fanotify_mark = 339, + prlimit64 = 340, + name_to_handle_at = 341, + open_by_handle_at = 342, + clock_adjtime = 343, + syncfs = 344, + sendmmsg = 345, + setns = 346, + process_vm_readv = 347, + process_vm_writev = 348, + kcmp = 349, + finit_module = 350, + sched_setattr = 351, + sched_getattr = 352, + renameat2 = 353, + seccomp = 354, + getrandom = 355, + memfd_create = 356, + bpf = 357, + execveat = 358, + socket = 359, + socketpair = 360, + bind = 361, + connect = 362, + listen = 363, + accept4 = 364, + getsockopt = 365, + setsockopt = 366, + getsockname = 367, + getpeername = 368, + sendto = 369, + sendmsg = 370, + recvfrom = 371, + recvmsg = 372, + shutdown = 373, + userfaultfd = 374, + membarrier = 375, + mlock2 = 376, + copy_file_range = 377, + preadv2 = 378, + pwritev2 = 379, + pkey_mprotect = 380, + pkey_alloc = 381, + pkey_free = 382, + statx = 383, + arch_prctl = 384, + io_pgetevents = 385, + rseq = 386, + semget = 393, + semctl = 394, + shmget = 395, + shmctl = 396, + shmat = 397, + shmdt = 398, + msgget = 399, + msgsnd = 400, + msgrcv = 401, + msgctl = 402, + clock_gettime64 = 403, + clock_settime64 = 404, + clock_adjtime64 = 405, + clock_getres_time64 = 406, + clock_nanosleep_time64 = 407, + timer_gettime64 = 408, + timer_settime64 = 409, + timerfd_gettime64 = 410, + timerfd_settime64 = 411, + utimensat_time64 = 412, + pselect6_time64 = 413, + ppoll_time64 = 414, + io_pgetevents_time64 = 416, + recvmmsg_time64 = 417, + mq_timedsend_time64 = 418, + mq_timedreceive_time64 = 419, + semtimedop_time64 = 420, + rt_sigtimedwait_time64 = 421, + futex_time64 = 422, + sched_rr_get_interval_time64 = 423, + pidfd_send_signal = 424, + io_uring_setup = 425, + io_uring_enter = 426, + io_uring_register = 427, + open_tree = 428, + move_mount = 429, + fsopen = 430, + fsconfig = 431, + fsmount = 432, + fspick = 433, + openat2 = 437, + pidfd_getfd = 438, + + _, +}; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/bits/linux/mipsel.zig b/lib/std/os/bits/linux/mipsel.zig index 4ef7619745..d1f088be40 100644 --- a/lib/std/os/bits/linux/mipsel.zig +++ b/lib/std/os/bits/linux/mipsel.zig @@ -6,377 +6,382 @@ const iovec_const = linux.iovec_const; const uid_t = linux.uid_t; const gid_t = linux.gid_t; -pub const SYS_Linux = 4000; -pub const SYS_syscall = (SYS_Linux + 0); -pub const SYS_exit = (SYS_Linux + 1); -pub const SYS_fork = (SYS_Linux + 2); -pub const SYS_read = (SYS_Linux + 3); -pub const SYS_write = (SYS_Linux + 4); -pub const SYS_open = (SYS_Linux + 5); -pub const SYS_close = (SYS_Linux + 6); -pub const SYS_waitpid = (SYS_Linux + 7); -pub const SYS_creat = (SYS_Linux + 8); -pub const SYS_link = (SYS_Linux + 9); -pub const SYS_unlink = (SYS_Linux + 10); -pub const SYS_execve = (SYS_Linux + 11); -pub const SYS_chdir = (SYS_Linux + 12); -pub const SYS_time = (SYS_Linux + 13); -pub const SYS_mknod = (SYS_Linux + 14); -pub const SYS_chmod = (SYS_Linux + 15); -pub const SYS_lchown = (SYS_Linux + 16); -pub const SYS_break = (SYS_Linux + 17); -pub const SYS_unused18 = (SYS_Linux + 18); -pub const SYS_lseek = (SYS_Linux + 19); -pub const SYS_getpid = (SYS_Linux + 20); -pub const SYS_mount = (SYS_Linux + 21); -pub const SYS_umount = (SYS_Linux + 22); -pub const SYS_setuid = (SYS_Linux + 23); -pub const SYS_getuid = (SYS_Linux + 24); -pub const SYS_stime = (SYS_Linux + 25); -pub const SYS_ptrace = (SYS_Linux + 26); -pub const SYS_alarm = (SYS_Linux + 27); -pub const SYS_unused28 = (SYS_Linux + 28); -pub const SYS_pause = (SYS_Linux + 29); -pub const SYS_utime = (SYS_Linux + 30); -pub const SYS_stty = (SYS_Linux + 31); -pub const SYS_gtty = (SYS_Linux + 32); -pub const SYS_access = (SYS_Linux + 33); -pub const SYS_nice = (SYS_Linux + 34); -pub const SYS_ftime = (SYS_Linux + 35); -pub const SYS_sync = (SYS_Linux + 36); -pub const SYS_kill = (SYS_Linux + 37); -pub const SYS_rename = (SYS_Linux + 38); -pub const SYS_mkdir = (SYS_Linux + 39); -pub const SYS_rmdir = (SYS_Linux + 40); -pub const SYS_dup = (SYS_Linux + 41); -pub const SYS_pipe = (SYS_Linux + 42); -pub const SYS_times = (SYS_Linux + 43); -pub const SYS_prof = (SYS_Linux + 44); -pub const SYS_brk = (SYS_Linux + 45); -pub const SYS_setgid = (SYS_Linux + 46); -pub const SYS_getgid = (SYS_Linux + 47); -pub const SYS_signal = (SYS_Linux + 48); -pub const SYS_geteuid = (SYS_Linux + 49); -pub const SYS_getegid = (SYS_Linux + 50); -pub const SYS_acct = (SYS_Linux + 51); -pub const SYS_umount2 = (SYS_Linux + 52); -pub const SYS_lock = (SYS_Linux + 53); -pub const SYS_ioctl = (SYS_Linux + 54); -pub const SYS_fcntl = (SYS_Linux + 55); -pub const SYS_mpx = (SYS_Linux + 56); -pub const SYS_setpgid = (SYS_Linux + 57); -pub const SYS_ulimit = (SYS_Linux + 58); -pub const SYS_unused59 = (SYS_Linux + 59); -pub const SYS_umask = (SYS_Linux + 60); -pub const SYS_chroot = (SYS_Linux + 61); -pub const SYS_ustat = (SYS_Linux + 62); -pub const SYS_dup2 = (SYS_Linux + 63); -pub const SYS_getppid = (SYS_Linux + 64); -pub const SYS_getpgrp = (SYS_Linux + 65); -pub const SYS_setsid = (SYS_Linux + 66); -pub const SYS_sigaction = (SYS_Linux + 67); -pub const SYS_sgetmask = (SYS_Linux + 68); -pub const SYS_ssetmask = (SYS_Linux + 69); -pub const SYS_setreuid = (SYS_Linux + 70); -pub const SYS_setregid = (SYS_Linux + 71); -pub const SYS_sigsuspend = (SYS_Linux + 72); -pub const SYS_sigpending = (SYS_Linux + 73); -pub const SYS_sethostname = (SYS_Linux + 74); -pub const SYS_setrlimit = (SYS_Linux + 75); -pub const SYS_getrlimit = (SYS_Linux + 76); -pub const SYS_getrusage = (SYS_Linux + 77); -pub const SYS_gettimeofday = (SYS_Linux + 78); -pub const SYS_settimeofday = (SYS_Linux + 79); -pub const SYS_getgroups = (SYS_Linux + 80); -pub const SYS_setgroups = (SYS_Linux + 81); -pub const SYS_reserved82 = (SYS_Linux + 82); -pub const SYS_symlink = (SYS_Linux + 83); -pub const SYS_unused84 = (SYS_Linux + 84); -pub const SYS_readlink = (SYS_Linux + 85); -pub const SYS_uselib = (SYS_Linux + 86); -pub const SYS_swapon = (SYS_Linux + 87); -pub const SYS_reboot = (SYS_Linux + 88); -pub const SYS_readdir = (SYS_Linux + 89); -pub const SYS_mmap = (SYS_Linux + 90); -pub const SYS_munmap = (SYS_Linux + 91); -pub const SYS_truncate = (SYS_Linux + 92); -pub const SYS_ftruncate = (SYS_Linux + 93); -pub const SYS_fchmod = (SYS_Linux + 94); -pub const SYS_fchown = (SYS_Linux + 95); -pub const SYS_getpriority = (SYS_Linux + 96); -pub const SYS_setpriority = (SYS_Linux + 97); -pub const SYS_profil = (SYS_Linux + 98); -pub const SYS_statfs = (SYS_Linux + 99); -pub const SYS_fstatfs = (SYS_Linux + 100); -pub const SYS_ioperm = (SYS_Linux + 101); -pub const SYS_socketcall = (SYS_Linux + 102); -pub const SYS_syslog = (SYS_Linux + 103); -pub const SYS_setitimer = (SYS_Linux + 104); -pub const SYS_getitimer = (SYS_Linux + 105); -pub const SYS_stat = (SYS_Linux + 106); -pub const SYS_lstat = (SYS_Linux + 107); -pub const SYS_fstat = (SYS_Linux + 108); -pub const SYS_unused109 = (SYS_Linux + 109); -pub const SYS_iopl = (SYS_Linux + 110); -pub const SYS_vhangup = (SYS_Linux + 111); -pub const SYS_idle = (SYS_Linux + 112); -pub const SYS_vm86 = (SYS_Linux + 113); -pub const SYS_wait4 = (SYS_Linux + 114); -pub const SYS_swapoff = (SYS_Linux + 115); -pub const SYS_sysinfo = (SYS_Linux + 116); -pub const SYS_ipc = (SYS_Linux + 117); -pub const SYS_fsync = (SYS_Linux + 118); -pub const SYS_sigreturn = (SYS_Linux + 119); -pub const SYS_clone = (SYS_Linux + 120); -pub const SYS_setdomainname = (SYS_Linux + 121); -pub const SYS_uname = (SYS_Linux + 122); -pub const SYS_modify_ldt = (SYS_Linux + 123); -pub const SYS_adjtimex = (SYS_Linux + 124); -pub const SYS_mprotect = (SYS_Linux + 125); -pub const SYS_sigprocmask = (SYS_Linux + 126); -pub const SYS_create_module = (SYS_Linux + 127); -pub const SYS_init_module = (SYS_Linux + 128); -pub const SYS_delete_module = (SYS_Linux + 129); -pub const SYS_get_kernel_syms = (SYS_Linux + 130); -pub const SYS_quotactl = (SYS_Linux + 131); -pub const SYS_getpgid = (SYS_Linux + 132); -pub const SYS_fchdir = (SYS_Linux + 133); -pub const SYS_bdflush = (SYS_Linux + 134); -pub const SYS_sysfs = (SYS_Linux + 135); -pub const SYS_personality = (SYS_Linux + 136); -pub const SYS_afs_syscall = (SYS_Linux + 137); -pub const SYS_setfsuid = (SYS_Linux + 138); -pub const SYS_setfsgid = (SYS_Linux + 139); -pub const SYS__llseek = (SYS_Linux + 140); -pub const SYS_getdents = (SYS_Linux + 141); -pub const SYS__newselect = (SYS_Linux + 142); -pub const SYS_flock = (SYS_Linux + 143); -pub const SYS_msync = (SYS_Linux + 144); -pub const SYS_readv = (SYS_Linux + 145); -pub const SYS_writev = (SYS_Linux + 146); -pub const SYS_cacheflush = (SYS_Linux + 147); -pub const SYS_cachectl = (SYS_Linux + 148); -pub const SYS_sysmips = (SYS_Linux + 149); -pub const SYS_unused150 = (SYS_Linux + 150); -pub const SYS_getsid = (SYS_Linux + 151); -pub const SYS_fdatasync = (SYS_Linux + 152); -pub const SYS__sysctl = (SYS_Linux + 153); -pub const SYS_mlock = (SYS_Linux + 154); -pub const SYS_munlock = (SYS_Linux + 155); -pub const SYS_mlockall = (SYS_Linux + 156); -pub const SYS_munlockall = (SYS_Linux + 157); -pub const SYS_sched_setparam = (SYS_Linux + 158); -pub const SYS_sched_getparam = (SYS_Linux + 159); -pub const SYS_sched_setscheduler = (SYS_Linux + 160); -pub const SYS_sched_getscheduler = (SYS_Linux + 161); -pub const SYS_sched_yield = (SYS_Linux + 162); -pub const SYS_sched_get_priority_max = (SYS_Linux + 163); -pub const SYS_sched_get_priority_min = (SYS_Linux + 164); -pub const SYS_sched_rr_get_interval = (SYS_Linux + 165); -pub const SYS_nanosleep = (SYS_Linux + 166); -pub const SYS_mremap = (SYS_Linux + 167); -pub const SYS_accept = (SYS_Linux + 168); -pub const SYS_bind = (SYS_Linux + 169); -pub const SYS_connect = (SYS_Linux + 170); -pub const SYS_getpeername = (SYS_Linux + 171); -pub const SYS_getsockname = (SYS_Linux + 172); -pub const SYS_getsockopt = (SYS_Linux + 173); -pub const SYS_listen = (SYS_Linux + 174); -pub const SYS_recv = (SYS_Linux + 175); -pub const SYS_recvfrom = (SYS_Linux + 176); -pub const SYS_recvmsg = (SYS_Linux + 177); -pub const SYS_send = (SYS_Linux + 178); -pub const SYS_sendmsg = (SYS_Linux + 179); -pub const SYS_sendto = (SYS_Linux + 180); -pub const SYS_setsockopt = (SYS_Linux + 181); -pub const SYS_shutdown = (SYS_Linux + 182); -pub const SYS_socket = (SYS_Linux + 183); -pub const SYS_socketpair = (SYS_Linux + 184); -pub const SYS_setresuid = (SYS_Linux + 185); -pub const SYS_getresuid = (SYS_Linux + 186); -pub const SYS_query_module = (SYS_Linux + 187); -pub const SYS_poll = (SYS_Linux + 188); -pub const SYS_nfsservctl = (SYS_Linux + 189); -pub const SYS_setresgid = (SYS_Linux + 190); -pub const SYS_getresgid = (SYS_Linux + 191); -pub const SYS_prctl = (SYS_Linux + 192); -pub const SYS_rt_sigreturn = (SYS_Linux + 193); -pub const SYS_rt_sigaction = (SYS_Linux + 194); -pub const SYS_rt_sigprocmask = (SYS_Linux + 195); -pub const SYS_rt_sigpending = (SYS_Linux + 196); -pub const SYS_rt_sigtimedwait = (SYS_Linux + 197); -pub const SYS_rt_sigqueueinfo = (SYS_Linux + 198); -pub const SYS_rt_sigsuspend = (SYS_Linux + 199); -pub const SYS_pread64 = (SYS_Linux + 200); -pub const SYS_pwrite64 = (SYS_Linux + 201); -pub const SYS_chown = (SYS_Linux + 202); -pub const SYS_getcwd = (SYS_Linux + 203); -pub const SYS_capget = (SYS_Linux + 204); -pub const SYS_capset = (SYS_Linux + 205); -pub const SYS_sigaltstack = (SYS_Linux + 206); -pub const SYS_sendfile = (SYS_Linux + 207); -pub const SYS_getpmsg = (SYS_Linux + 208); -pub const SYS_putpmsg = (SYS_Linux + 209); -pub const SYS_mmap2 = (SYS_Linux + 210); -pub const SYS_truncate64 = (SYS_Linux + 211); -pub const SYS_ftruncate64 = (SYS_Linux + 212); -pub const SYS_stat64 = (SYS_Linux + 213); -pub const SYS_lstat64 = (SYS_Linux + 214); -pub const SYS_fstat64 = (SYS_Linux + 215); -pub const SYS_pivot_root = (SYS_Linux + 216); -pub const SYS_mincore = (SYS_Linux + 217); -pub const SYS_madvise = (SYS_Linux + 218); -pub const SYS_getdents64 = (SYS_Linux + 219); -pub const SYS_fcntl64 = (SYS_Linux + 220); -pub const SYS_reserved221 = (SYS_Linux + 221); -pub const SYS_gettid = (SYS_Linux + 222); -pub const SYS_readahead = (SYS_Linux + 223); -pub const SYS_setxattr = (SYS_Linux + 224); -pub const SYS_lsetxattr = (SYS_Linux + 225); -pub const SYS_fsetxattr = (SYS_Linux + 226); -pub const SYS_getxattr = (SYS_Linux + 227); -pub const SYS_lgetxattr = (SYS_Linux + 228); -pub const SYS_fgetxattr = (SYS_Linux + 229); -pub const SYS_listxattr = (SYS_Linux + 230); -pub const SYS_llistxattr = (SYS_Linux + 231); -pub const SYS_flistxattr = (SYS_Linux + 232); -pub const SYS_removexattr = (SYS_Linux + 233); -pub const SYS_lremovexattr = (SYS_Linux + 234); -pub const SYS_fremovexattr = (SYS_Linux + 235); -pub const SYS_tkill = (SYS_Linux + 236); -pub const SYS_sendfile64 = (SYS_Linux + 237); -pub const SYS_futex = (SYS_Linux + 238); -pub const SYS_sched_setaffinity = (SYS_Linux + 239); -pub const SYS_sched_getaffinity = (SYS_Linux + 240); -pub const SYS_io_setup = (SYS_Linux + 241); -pub const SYS_io_destroy = (SYS_Linux + 242); -pub const SYS_io_getevents = (SYS_Linux + 243); -pub const SYS_io_submit = (SYS_Linux + 244); -pub const SYS_io_cancel = (SYS_Linux + 245); -pub const SYS_exit_group = (SYS_Linux + 246); -pub const SYS_lookup_dcookie = (SYS_Linux + 247); -pub const SYS_epoll_create = (SYS_Linux + 248); -pub const SYS_epoll_ctl = (SYS_Linux + 249); -pub const SYS_epoll_wait = (SYS_Linux + 250); -pub const SYS_remap_file_pages = (SYS_Linux + 251); -pub const SYS_set_tid_address = (SYS_Linux + 252); -pub const SYS_restart_syscall = (SYS_Linux + 253); -pub const SYS_fadvise64 = (SYS_Linux + 254); -pub const SYS_statfs64 = (SYS_Linux + 255); -pub const SYS_fstatfs64 = (SYS_Linux + 256); -pub const SYS_timer_create = (SYS_Linux + 257); -pub const SYS_timer_settime = (SYS_Linux + 258); -pub const SYS_timer_gettime = (SYS_Linux + 259); -pub const SYS_timer_getoverrun = (SYS_Linux + 260); -pub const SYS_timer_delete = (SYS_Linux + 261); -pub const SYS_clock_settime = (SYS_Linux + 262); -pub const SYS_clock_gettime = (SYS_Linux + 263); -pub const SYS_clock_getres = (SYS_Linux + 264); -pub const SYS_clock_nanosleep = (SYS_Linux + 265); -pub const SYS_tgkill = (SYS_Linux + 266); -pub const SYS_utimes = (SYS_Linux + 267); -pub const SYS_mbind = (SYS_Linux + 268); -pub const SYS_get_mempolicy = (SYS_Linux + 269); -pub const SYS_set_mempolicy = (SYS_Linux + 270); -pub const SYS_mq_open = (SYS_Linux + 271); -pub const SYS_mq_unlink = (SYS_Linux + 272); -pub const SYS_mq_timedsend = (SYS_Linux + 273); -pub const SYS_mq_timedreceive = (SYS_Linux + 274); -pub const SYS_mq_notify = (SYS_Linux + 275); -pub const SYS_mq_getsetattr = (SYS_Linux + 276); -pub const SYS_vserver = (SYS_Linux + 277); -pub const SYS_waitid = (SYS_Linux + 278); -pub const SYS_add_key = (SYS_Linux + 280); -pub const SYS_request_key = (SYS_Linux + 281); -pub const SYS_keyctl = (SYS_Linux + 282); -pub const SYS_set_thread_area = (SYS_Linux + 283); -pub const SYS_inotify_init = (SYS_Linux + 284); -pub const SYS_inotify_add_watch = (SYS_Linux + 285); -pub const SYS_inotify_rm_watch = (SYS_Linux + 286); -pub const SYS_migrate_pages = (SYS_Linux + 287); -pub const SYS_openat = (SYS_Linux + 288); -pub const SYS_mkdirat = (SYS_Linux + 289); -pub const SYS_mknodat = (SYS_Linux + 290); -pub const SYS_fchownat = (SYS_Linux + 291); -pub const SYS_futimesat = (SYS_Linux + 292); -pub const SYS_fstatat64 = (SYS_Linux + 293); -pub const SYS_unlinkat = (SYS_Linux + 294); -pub const SYS_renameat = (SYS_Linux + 295); -pub const SYS_linkat = (SYS_Linux + 296); -pub const SYS_symlinkat = (SYS_Linux + 297); -pub const SYS_readlinkat = (SYS_Linux + 298); -pub const SYS_fchmodat = (SYS_Linux + 299); -pub const SYS_faccessat = (SYS_Linux + 300); -pub const SYS_pselect6 = (SYS_Linux + 301); -pub const SYS_ppoll = (SYS_Linux + 302); -pub const SYS_unshare = (SYS_Linux + 303); -pub const SYS_splice = (SYS_Linux + 304); -pub const SYS_sync_file_range = (SYS_Linux + 305); -pub const SYS_tee = (SYS_Linux + 306); -pub const SYS_vmsplice = (SYS_Linux + 307); -pub const SYS_move_pages = (SYS_Linux + 308); -pub const SYS_set_robust_list = (SYS_Linux + 309); -pub const SYS_get_robust_list = (SYS_Linux + 310); -pub const SYS_kexec_load = (SYS_Linux + 311); -pub const SYS_getcpu = (SYS_Linux + 312); -pub const SYS_epoll_pwait = (SYS_Linux + 313); -pub const SYS_ioprio_set = (SYS_Linux + 314); -pub const SYS_ioprio_get = (SYS_Linux + 315); -pub const SYS_utimensat = (SYS_Linux + 316); -pub const SYS_signalfd = (SYS_Linux + 317); -pub const SYS_timerfd = (SYS_Linux + 318); -pub const SYS_eventfd = (SYS_Linux + 319); -pub const SYS_fallocate = (SYS_Linux + 320); -pub const SYS_timerfd_create = (SYS_Linux + 321); -pub const SYS_timerfd_gettime = (SYS_Linux + 322); -pub const SYS_timerfd_settime = (SYS_Linux + 323); -pub const SYS_signalfd4 = (SYS_Linux + 324); -pub const SYS_eventfd2 = (SYS_Linux + 325); -pub const SYS_epoll_create1 = (SYS_Linux + 326); -pub const SYS_dup3 = (SYS_Linux + 327); -pub const SYS_pipe2 = (SYS_Linux + 328); -pub const SYS_inotify_init1 = (SYS_Linux + 329); -pub const SYS_preadv = (SYS_Linux + 330); -pub const SYS_pwritev = (SYS_Linux + 331); -pub const SYS_rt_tgsigqueueinfo = (SYS_Linux + 332); -pub const SYS_perf_event_open = (SYS_Linux + 333); -pub const SYS_accept4 = (SYS_Linux + 334); -pub const SYS_recvmmsg = (SYS_Linux + 335); -pub const SYS_fanotify_init = (SYS_Linux + 336); -pub const SYS_fanotify_mark = (SYS_Linux + 337); -pub const SYS_prlimit64 = (SYS_Linux + 338); -pub const SYS_name_to_handle_at = (SYS_Linux + 339); -pub const SYS_open_by_handle_at = (SYS_Linux + 340); -pub const SYS_clock_adjtime = (SYS_Linux + 341); -pub const SYS_syncfs = (SYS_Linux + 342); -pub const SYS_sendmmsg = (SYS_Linux + 343); -pub const SYS_setns = (SYS_Linux + 344); -pub const SYS_process_vm_readv = (SYS_Linux + 345); -pub const SYS_process_vm_writev = (SYS_Linux + 346); -pub const SYS_kcmp = (SYS_Linux + 347); -pub const SYS_finit_module = (SYS_Linux + 348); -pub const SYS_sched_setattr = (SYS_Linux + 349); -pub const SYS_sched_getattr = (SYS_Linux + 350); -pub const SYS_renameat2 = (SYS_Linux + 351); -pub const SYS_seccomp = (SYS_Linux + 352); -pub const SYS_getrandom = (SYS_Linux + 353); -pub const SYS_memfd_create = (SYS_Linux + 354); -pub const SYS_bpf = (SYS_Linux + 355); -pub const SYS_execveat = (SYS_Linux + 356); -pub const SYS_userfaultfd = (SYS_Linux + 357); -pub const SYS_membarrier = (SYS_Linux + 358); -pub const SYS_mlock2 = (SYS_Linux + 359); -pub const SYS_copy_file_range = (SYS_Linux + 360); -pub const SYS_preadv2 = (SYS_Linux + 361); -pub const SYS_pwritev2 = (SYS_Linux + 362); -pub const SYS_pkey_mprotect = (SYS_Linux + 363); -pub const SYS_pkey_alloc = (SYS_Linux + 364); -pub const SYS_pkey_free = (SYS_Linux + 365); -pub const SYS_statx = (SYS_Linux + 366); -pub const SYS_rseq = (SYS_Linux + 367); -pub const SYS_io_pgetevents = (SYS_Linux + 368); -pub const SYS_openat2 = (SYS_Linux + 437); -pub const SYS_pidfd_getfd = (SYS_Linux + 438); +pub const SYS = extern enum(usize) { + pub const Linux = 4000; + + syscall = Linux + 0, + exit = Linux + 1, + fork = Linux + 2, + read = Linux + 3, + write = Linux + 4, + open = Linux + 5, + close = Linux + 6, + waitpid = Linux + 7, + creat = Linux + 8, + link = Linux + 9, + unlink = Linux + 10, + execve = Linux + 11, + chdir = Linux + 12, + time = Linux + 13, + mknod = Linux + 14, + chmod = Linux + 15, + lchown = Linux + 16, + @"break" = Linux + 17, + unused18 = Linux + 18, + lseek = Linux + 19, + getpid = Linux + 20, + mount = Linux + 21, + umount = Linux + 22, + setuid = Linux + 23, + getuid = Linux + 24, + stime = Linux + 25, + ptrace = Linux + 26, + alarm = Linux + 27, + unused28 = Linux + 28, + pause = Linux + 29, + utime = Linux + 30, + stty = Linux + 31, + gtty = Linux + 32, + access = Linux + 33, + nice = Linux + 34, + ftime = Linux + 35, + sync = Linux + 36, + kill = Linux + 37, + rename = Linux + 38, + mkdir = Linux + 39, + rmdir = Linux + 40, + dup = Linux + 41, + pipe = Linux + 42, + times = Linux + 43, + prof = Linux + 44, + brk = Linux + 45, + setgid = Linux + 46, + getgid = Linux + 47, + signal = Linux + 48, + geteuid = Linux + 49, + getegid = Linux + 50, + acct = Linux + 51, + umount2 = Linux + 52, + lock = Linux + 53, + ioctl = Linux + 54, + fcntl = Linux + 55, + mpx = Linux + 56, + setpgid = Linux + 57, + ulimit = Linux + 58, + unused59 = Linux + 59, + umask = Linux + 60, + chroot = Linux + 61, + ustat = Linux + 62, + dup2 = Linux + 63, + getppid = Linux + 64, + getpgrp = Linux + 65, + setsid = Linux + 66, + sigaction = Linux + 67, + sgetmask = Linux + 68, + ssetmask = Linux + 69, + setreuid = Linux + 70, + setregid = Linux + 71, + sigsuspend = Linux + 72, + sigpending = Linux + 73, + sethostname = Linux + 74, + setrlimit = Linux + 75, + getrlimit = Linux + 76, + getrusage = Linux + 77, + gettimeofday = Linux + 78, + settimeofday = Linux + 79, + getgroups = Linux + 80, + setgroups = Linux + 81, + reserved82 = Linux + 82, + symlink = Linux + 83, + unused84 = Linux + 84, + readlink = Linux + 85, + uselib = Linux + 86, + swapon = Linux + 87, + reboot = Linux + 88, + readdir = Linux + 89, + mmap = Linux + 90, + munmap = Linux + 91, + truncate = Linux + 92, + ftruncate = Linux + 93, + fchmod = Linux + 94, + fchown = Linux + 95, + getpriority = Linux + 96, + setpriority = Linux + 97, + profil = Linux + 98, + statfs = Linux + 99, + fstatfs = Linux + 100, + ioperm = Linux + 101, + socketcall = Linux + 102, + syslog = Linux + 103, + setitimer = Linux + 104, + getitimer = Linux + 105, + stat = Linux + 106, + lstat = Linux + 107, + fstat = Linux + 108, + unused109 = Linux + 109, + iopl = Linux + 110, + vhangup = Linux + 111, + idle = Linux + 112, + vm86 = Linux + 113, + wait4 = Linux + 114, + swapoff = Linux + 115, + sysinfo = Linux + 116, + ipc = Linux + 117, + fsync = Linux + 118, + sigreturn = Linux + 119, + clone = Linux + 120, + setdomainname = Linux + 121, + uname = Linux + 122, + modify_ldt = Linux + 123, + adjtimex = Linux + 124, + mprotect = Linux + 125, + sigprocmask = Linux + 126, + create_module = Linux + 127, + init_module = Linux + 128, + delete_module = Linux + 129, + get_kernel_syms = Linux + 130, + quotactl = Linux + 131, + getpgid = Linux + 132, + fchdir = Linux + 133, + bdflush = Linux + 134, + sysfs = Linux + 135, + personality = Linux + 136, + afs_syscall = Linux + 137, + setfsuid = Linux + 138, + setfsgid = Linux + 139, + _llseek = Linux + 140, + getdents = Linux + 141, + _newselect = Linux + 142, + flock = Linux + 143, + msync = Linux + 144, + readv = Linux + 145, + writev = Linux + 146, + cacheflush = Linux + 147, + cachectl = Linux + 148, + sysmips = Linux + 149, + unused150 = Linux + 150, + getsid = Linux + 151, + fdatasync = Linux + 152, + _sysctl = Linux + 153, + mlock = Linux + 154, + munlock = Linux + 155, + mlockall = Linux + 156, + munlockall = Linux + 157, + sched_setparam = Linux + 158, + sched_getparam = Linux + 159, + sched_setscheduler = Linux + 160, + sched_getscheduler = Linux + 161, + sched_yield = Linux + 162, + sched_get_priority_max = Linux + 163, + sched_get_priority_min = Linux + 164, + sched_rr_get_interval = Linux + 165, + nanosleep = Linux + 166, + mremap = Linux + 167, + accept = Linux + 168, + bind = Linux + 169, + connect = Linux + 170, + getpeername = Linux + 171, + getsockname = Linux + 172, + getsockopt = Linux + 173, + listen = Linux + 174, + recv = Linux + 175, + recvfrom = Linux + 176, + recvmsg = Linux + 177, + send = Linux + 178, + sendmsg = Linux + 179, + sendto = Linux + 180, + setsockopt = Linux + 181, + shutdown = Linux + 182, + socket = Linux + 183, + socketpair = Linux + 184, + setresuid = Linux + 185, + getresuid = Linux + 186, + query_module = Linux + 187, + poll = Linux + 188, + nfsservctl = Linux + 189, + setresgid = Linux + 190, + getresgid = Linux + 191, + prctl = Linux + 192, + rt_sigreturn = Linux + 193, + rt_sigaction = Linux + 194, + rt_sigprocmask = Linux + 195, + rt_sigpending = Linux + 196, + rt_sigtimedwait = Linux + 197, + rt_sigqueueinfo = Linux + 198, + rt_sigsuspend = Linux + 199, + pread64 = Linux + 200, + pwrite64 = Linux + 201, + chown = Linux + 202, + getcwd = Linux + 203, + capget = Linux + 204, + capset = Linux + 205, + sigaltstack = Linux + 206, + sendfile = Linux + 207, + getpmsg = Linux + 208, + putpmsg = Linux + 209, + mmap2 = Linux + 210, + truncate64 = Linux + 211, + ftruncate64 = Linux + 212, + stat64 = Linux + 213, + lstat64 = Linux + 214, + fstat64 = Linux + 215, + pivot_root = Linux + 216, + mincore = Linux + 217, + madvise = Linux + 218, + getdents64 = Linux + 219, + fcntl64 = Linux + 220, + reserved221 = Linux + 221, + gettid = Linux + 222, + readahead = Linux + 223, + setxattr = Linux + 224, + lsetxattr = Linux + 225, + fsetxattr = Linux + 226, + getxattr = Linux + 227, + lgetxattr = Linux + 228, + fgetxattr = Linux + 229, + listxattr = Linux + 230, + llistxattr = Linux + 231, + flistxattr = Linux + 232, + removexattr = Linux + 233, + lremovexattr = Linux + 234, + fremovexattr = Linux + 235, + tkill = Linux + 236, + sendfile64 = Linux + 237, + futex = Linux + 238, + sched_setaffinity = Linux + 239, + sched_getaffinity = Linux + 240, + io_setup = Linux + 241, + io_destroy = Linux + 242, + io_getevents = Linux + 243, + io_submit = Linux + 244, + io_cancel = Linux + 245, + exit_group = Linux + 246, + lookup_dcookie = Linux + 247, + epoll_create = Linux + 248, + epoll_ctl = Linux + 249, + epoll_wait = Linux + 250, + remap_file_pages = Linux + 251, + set_tid_address = Linux + 252, + restart_syscall = Linux + 253, + fadvise64 = Linux + 254, + statfs64 = Linux + 255, + fstatfs64 = Linux + 256, + timer_create = Linux + 257, + timer_settime = Linux + 258, + timer_gettime = Linux + 259, + timer_getoverrun = Linux + 260, + timer_delete = Linux + 261, + clock_settime = Linux + 262, + clock_gettime = Linux + 263, + clock_getres = Linux + 264, + clock_nanosleep = Linux + 265, + tgkill = Linux + 266, + utimes = Linux + 267, + mbind = Linux + 268, + get_mempolicy = Linux + 269, + set_mempolicy = Linux + 270, + mq_open = Linux + 271, + mq_unlink = Linux + 272, + mq_timedsend = Linux + 273, + mq_timedreceive = Linux + 274, + mq_notify = Linux + 275, + mq_getsetattr = Linux + 276, + vserver = Linux + 277, + waitid = Linux + 278, + add_key = Linux + 280, + request_key = Linux + 281, + keyctl = Linux + 282, + set_thread_area = Linux + 283, + inotify_init = Linux + 284, + inotify_add_watch = Linux + 285, + inotify_rm_watch = Linux + 286, + migrate_pages = Linux + 287, + openat = Linux + 288, + mkdirat = Linux + 289, + mknodat = Linux + 290, + fchownat = Linux + 291, + futimesat = Linux + 292, + fstatat64 = Linux + 293, + unlinkat = Linux + 294, + renameat = Linux + 295, + linkat = Linux + 296, + symlinkat = Linux + 297, + readlinkat = Linux + 298, + fchmodat = Linux + 299, + faccessat = Linux + 300, + pselect6 = Linux + 301, + ppoll = Linux + 302, + unshare = Linux + 303, + splice = Linux + 304, + sync_file_range = Linux + 305, + tee = Linux + 306, + vmsplice = Linux + 307, + move_pages = Linux + 308, + set_robust_list = Linux + 309, + get_robust_list = Linux + 310, + kexec_load = Linux + 311, + getcpu = Linux + 312, + epoll_pwait = Linux + 313, + ioprio_set = Linux + 314, + ioprio_get = Linux + 315, + utimensat = Linux + 316, + signalfd = Linux + 317, + timerfd = Linux + 318, + eventfd = Linux + 319, + fallocate = Linux + 320, + timerfd_create = Linux + 321, + timerfd_gettime = Linux + 322, + timerfd_settime = Linux + 323, + signalfd4 = Linux + 324, + eventfd2 = Linux + 325, + epoll_create1 = Linux + 326, + dup3 = Linux + 327, + pipe2 = Linux + 328, + inotify_init1 = Linux + 329, + preadv = Linux + 330, + pwritev = Linux + 331, + rt_tgsigqueueinfo = Linux + 332, + perf_event_open = Linux + 333, + accept4 = Linux + 334, + recvmmsg = Linux + 335, + fanotify_init = Linux + 336, + fanotify_mark = Linux + 337, + prlimit64 = Linux + 338, + name_to_handle_at = Linux + 339, + open_by_handle_at = Linux + 340, + clock_adjtime = Linux + 341, + syncfs = Linux + 342, + sendmmsg = Linux + 343, + setns = Linux + 344, + process_vm_readv = Linux + 345, + process_vm_writev = Linux + 346, + kcmp = Linux + 347, + finit_module = Linux + 348, + sched_setattr = Linux + 349, + sched_getattr = Linux + 350, + renameat2 = Linux + 351, + seccomp = Linux + 352, + getrandom = Linux + 353, + memfd_create = Linux + 354, + bpf = Linux + 355, + execveat = Linux + 356, + userfaultfd = Linux + 357, + membarrier = Linux + 358, + mlock2 = Linux + 359, + copy_file_range = Linux + 360, + preadv2 = Linux + 361, + pwritev2 = Linux + 362, + pkey_mprotect = Linux + 363, + pkey_alloc = Linux + 364, + pkey_free = Linux + 365, + statx = Linux + 366, + rseq = Linux + 367, + io_pgetevents = Linux + 368, + openat2 = Linux + 437, + pidfd_getfd = Linux + 438, + + _, +}; pub const O_CREAT = 0o0400; pub const O_EXCL = 0o02000; diff --git a/lib/std/os/bits/linux/riscv64.zig b/lib/std/os/bits/linux/riscv64.zig index 75c67517e4..daeb3a7819 100644 --- a/lib/std/os/bits/linux/riscv64.zig +++ b/lib/std/os/bits/linux/riscv64.zig @@ -3,302 +3,306 @@ const std = @import("../../../std.zig"); const uid_t = std.os.linux.uid_t; const gid_t = std.os.linux.gid_t; -pub const SYS_io_setup = 0; -pub const SYS_io_destroy = 1; -pub const SYS_io_submit = 2; -pub const SYS_io_cancel = 3; -pub const SYS_io_getevents = 4; -pub const SYS_setxattr = 5; -pub const SYS_lsetxattr = 6; -pub const SYS_fsetxattr = 7; -pub const SYS_getxattr = 8; -pub const SYS_lgetxattr = 9; -pub const SYS_fgetxattr = 10; -pub const SYS_listxattr = 11; -pub const SYS_llistxattr = 12; -pub const SYS_flistxattr = 13; -pub const SYS_removexattr = 14; -pub const SYS_lremovexattr = 15; -pub const SYS_fremovexattr = 16; -pub const SYS_getcwd = 17; -pub const SYS_lookup_dcookie = 18; -pub const SYS_eventfd2 = 19; -pub const SYS_epoll_create1 = 20; -pub const SYS_epoll_ctl = 21; -pub const SYS_epoll_pwait = 22; -pub const SYS_dup = 23; -pub const SYS_dup3 = 24; -pub const SYS_fcntl = 25; -pub const SYS_inotify_init1 = 26; -pub const SYS_inotify_add_watch = 27; -pub const SYS_inotify_rm_watch = 28; -pub const SYS_ioctl = 29; -pub const SYS_ioprio_set = 30; -pub const SYS_ioprio_get = 31; -pub const SYS_flock = 32; -pub const SYS_mknodat = 33; -pub const SYS_mkdirat = 34; -pub const SYS_unlinkat = 35; -pub const SYS_symlinkat = 36; -pub const SYS_linkat = 37; -pub const SYS_umount2 = 39; -pub const SYS_mount = 40; -pub const SYS_pivot_root = 41; -pub const SYS_nfsservctl = 42; -pub const SYS_statfs = 43; -pub const SYS_fstatfs = 44; -pub const SYS_truncate = 45; -pub const SYS_ftruncate = 46; -pub const SYS_fallocate = 47; -pub const SYS_faccessat = 48; -pub const SYS_chdir = 49; -pub const SYS_fchdir = 50; -pub const SYS_chroot = 51; -pub const SYS_fchmod = 52; -pub const SYS_fchmodat = 53; -pub const SYS_fchownat = 54; -pub const SYS_fchown = 55; -pub const SYS_openat = 56; -pub const SYS_close = 57; -pub const SYS_vhangup = 58; -pub const SYS_pipe2 = 59; -pub const SYS_quotactl = 60; -pub const SYS_getdents64 = 61; -pub const SYS_lseek = 62; -pub const SYS_read = 63; -pub const SYS_write = 64; -pub const SYS_readv = 65; -pub const SYS_writev = 66; -pub const SYS_pread64 = 67; -pub const SYS_pwrite64 = 68; -pub const SYS_preadv = 69; -pub const SYS_pwritev = 70; -pub const SYS_sendfile = 71; -pub const SYS_pselect6 = 72; -pub const SYS_ppoll = 73; -pub const SYS_signalfd4 = 74; -pub const SYS_vmsplice = 75; -pub const SYS_splice = 76; -pub const SYS_tee = 77; -pub const SYS_readlinkat = 78; -pub const SYS_fstatat = 79; -pub const SYS_fstat = 80; -pub const SYS_sync = 81; -pub const SYS_fsync = 82; -pub const SYS_fdatasync = 83; -pub const SYS_sync_file_range = 84; -pub const SYS_timerfd_create = 85; -pub const SYS_timerfd_settime = 86; -pub const SYS_timerfd_gettime = 87; -pub const SYS_utimensat = 88; -pub const SYS_acct = 89; -pub const SYS_capget = 90; -pub const SYS_capset = 91; -pub const SYS_personality = 92; -pub const SYS_exit = 93; -pub const SYS_exit_group = 94; -pub const SYS_waitid = 95; -pub const SYS_set_tid_address = 96; -pub const SYS_unshare = 97; -pub const SYS_futex = 98; -pub const SYS_set_robust_list = 99; -pub const SYS_get_robust_list = 100; -pub const SYS_nanosleep = 101; -pub const SYS_getitimer = 102; -pub const SYS_setitimer = 103; -pub const SYS_kexec_load = 104; -pub const SYS_init_module = 105; -pub const SYS_delete_module = 106; -pub const SYS_timer_create = 107; -pub const SYS_timer_gettime = 108; -pub const SYS_timer_getoverrun = 109; -pub const SYS_timer_settime = 110; -pub const SYS_timer_delete = 111; -pub const SYS_clock_settime = 112; -pub const SYS_clock_gettime = 113; -pub const SYS_clock_getres = 114; -pub const SYS_clock_nanosleep = 115; -pub const SYS_syslog = 116; -pub const SYS_ptrace = 117; -pub const SYS_sched_setparam = 118; -pub const SYS_sched_setscheduler = 119; -pub const SYS_sched_getscheduler = 120; -pub const SYS_sched_getparam = 121; -pub const SYS_sched_setaffinity = 122; -pub const SYS_sched_getaffinity = 123; -pub const SYS_sched_yield = 124; -pub const SYS_sched_get_priority_max = 125; -pub const SYS_sched_get_priority_min = 126; -pub const SYS_sched_rr_get_interval = 127; -pub const SYS_restart_syscall = 128; -pub const SYS_kill = 129; -pub const SYS_tkill = 130; -pub const SYS_tgkill = 131; -pub const SYS_sigaltstack = 132; -pub const SYS_rt_sigsuspend = 133; -pub const SYS_rt_sigaction = 134; -pub const SYS_rt_sigprocmask = 135; -pub const SYS_rt_sigpending = 136; -pub const SYS_rt_sigtimedwait = 137; -pub const SYS_rt_sigqueueinfo = 138; -pub const SYS_rt_sigreturn = 139; -pub const SYS_setpriority = 140; -pub const SYS_getpriority = 141; -pub const SYS_reboot = 142; -pub const SYS_setregid = 143; -pub const SYS_setgid = 144; -pub const SYS_setreuid = 145; -pub const SYS_setuid = 146; -pub const SYS_setresuid = 147; -pub const SYS_getresuid = 148; -pub const SYS_setresgid = 149; -pub const SYS_getresgid = 150; -pub const SYS_setfsuid = 151; -pub const SYS_setfsgid = 152; -pub const SYS_times = 153; -pub const SYS_setpgid = 154; -pub const SYS_getpgid = 155; -pub const SYS_getsid = 156; -pub const SYS_setsid = 157; -pub const SYS_getgroups = 158; -pub const SYS_setgroups = 159; -pub const SYS_uname = 160; -pub const SYS_sethostname = 161; -pub const SYS_setdomainname = 162; -pub const SYS_getrlimit = 163; -pub const SYS_setrlimit = 164; -pub const SYS_getrusage = 165; -pub const SYS_umask = 166; -pub const SYS_prctl = 167; -pub const SYS_getcpu = 168; -pub const SYS_gettimeofday = 169; -pub const SYS_settimeofday = 170; -pub const SYS_adjtimex = 171; -pub const SYS_getpid = 172; -pub const SYS_getppid = 173; -pub const SYS_getuid = 174; -pub const SYS_geteuid = 175; -pub const SYS_getgid = 176; -pub const SYS_getegid = 177; -pub const SYS_gettid = 178; -pub const SYS_sysinfo = 179; -pub const SYS_mq_open = 180; -pub const SYS_mq_unlink = 181; -pub const SYS_mq_timedsend = 182; -pub const SYS_mq_timedreceive = 183; -pub const SYS_mq_notify = 184; -pub const SYS_mq_getsetattr = 185; -pub const SYS_msgget = 186; -pub const SYS_msgctl = 187; -pub const SYS_msgrcv = 188; -pub const SYS_msgsnd = 189; -pub const SYS_semget = 190; -pub const SYS_semctl = 191; -pub const SYS_semtimedop = 192; -pub const SYS_semop = 193; -pub const SYS_shmget = 194; -pub const SYS_shmctl = 195; -pub const SYS_shmat = 196; -pub const SYS_shmdt = 197; -pub const SYS_socket = 198; -pub const SYS_socketpair = 199; -pub const SYS_bind = 200; -pub const SYS_listen = 201; -pub const SYS_accept = 202; -pub const SYS_connect = 203; -pub const SYS_getsockname = 204; -pub const SYS_getpeername = 205; -pub const SYS_sendto = 206; -pub const SYS_recvfrom = 207; -pub const SYS_setsockopt = 208; -pub const SYS_getsockopt = 209; -pub const SYS_shutdown = 210; -pub const SYS_sendmsg = 211; -pub const SYS_recvmsg = 212; -pub const SYS_readahead = 213; -pub const SYS_brk = 214; -pub const SYS_munmap = 215; -pub const SYS_mremap = 216; -pub const SYS_add_key = 217; -pub const SYS_request_key = 218; -pub const SYS_keyctl = 219; -pub const SYS_clone = 220; -pub const SYS_execve = 221; -pub const SYS_mmap = 222; -pub const SYS_fadvise64 = 223; -pub const SYS_swapon = 224; -pub const SYS_swapoff = 225; -pub const SYS_mprotect = 226; -pub const SYS_msync = 227; -pub const SYS_mlock = 228; -pub const SYS_munlock = 229; -pub const SYS_mlockall = 230; -pub const SYS_munlockall = 231; -pub const SYS_mincore = 232; -pub const SYS_madvise = 233; -pub const SYS_remap_file_pages = 234; -pub const SYS_mbind = 235; -pub const SYS_get_mempolicy = 236; -pub const SYS_set_mempolicy = 237; -pub const SYS_migrate_pages = 238; -pub const SYS_move_pages = 239; -pub const SYS_rt_tgsigqueueinfo = 240; -pub const SYS_perf_event_open = 241; -pub const SYS_accept4 = 242; -pub const SYS_recvmmsg = 243; +pub const SYS = extern enum(usize) { + io_setup = 0, + io_destroy = 1, + io_submit = 2, + io_cancel = 3, + io_getevents = 4, + setxattr = 5, + lsetxattr = 6, + fsetxattr = 7, + getxattr = 8, + lgetxattr = 9, + fgetxattr = 10, + listxattr = 11, + llistxattr = 12, + flistxattr = 13, + removexattr = 14, + lremovexattr = 15, + fremovexattr = 16, + getcwd = 17, + lookup_dcookie = 18, + eventfd2 = 19, + epoll_create1 = 20, + epoll_ctl = 21, + epoll_pwait = 22, + dup = 23, + dup3 = 24, + fcntl = 25, + inotify_init1 = 26, + inotify_add_watch = 27, + inotify_rm_watch = 28, + ioctl = 29, + ioprio_set = 30, + ioprio_get = 31, + flock = 32, + mknodat = 33, + mkdirat = 34, + unlinkat = 35, + symlinkat = 36, + linkat = 37, + umount2 = 39, + mount = 40, + pivot_root = 41, + nfsservctl = 42, + statfs = 43, + fstatfs = 44, + truncate = 45, + ftruncate = 46, + fallocate = 47, + faccessat = 48, + chdir = 49, + fchdir = 50, + chroot = 51, + fchmod = 52, + fchmodat = 53, + fchownat = 54, + fchown = 55, + openat = 56, + close = 57, + vhangup = 58, + pipe2 = 59, + quotactl = 60, + getdents64 = 61, + lseek = 62, + read = 63, + write = 64, + readv = 65, + writev = 66, + pread64 = 67, + pwrite64 = 68, + preadv = 69, + pwritev = 70, + sendfile = 71, + pselect6 = 72, + ppoll = 73, + signalfd4 = 74, + vmsplice = 75, + splice = 76, + tee = 77, + readlinkat = 78, + fstatat = 79, + fstat = 80, + sync = 81, + fsync = 82, + fdatasync = 83, + sync_file_range = 84, + timerfd_create = 85, + timerfd_settime = 86, + timerfd_gettime = 87, + utimensat = 88, + acct = 89, + capget = 90, + capset = 91, + personality = 92, + exit = 93, + exit_group = 94, + waitid = 95, + set_tid_address = 96, + unshare = 97, + futex = 98, + set_robust_list = 99, + get_robust_list = 100, + nanosleep = 101, + getitimer = 102, + setitimer = 103, + kexec_load = 104, + init_module = 105, + delete_module = 106, + timer_create = 107, + timer_gettime = 108, + timer_getoverrun = 109, + timer_settime = 110, + timer_delete = 111, + clock_settime = 112, + clock_gettime = 113, + clock_getres = 114, + clock_nanosleep = 115, + syslog = 116, + ptrace = 117, + sched_setparam = 118, + sched_setscheduler = 119, + sched_getscheduler = 120, + sched_getparam = 121, + sched_setaffinity = 122, + sched_getaffinity = 123, + sched_yield = 124, + sched_get_priority_max = 125, + sched_get_priority_min = 126, + sched_rr_get_interval = 127, + restart_syscall = 128, + kill = 129, + tkill = 130, + tgkill = 131, + sigaltstack = 132, + rt_sigsuspend = 133, + rt_sigaction = 134, + rt_sigprocmask = 135, + rt_sigpending = 136, + rt_sigtimedwait = 137, + rt_sigqueueinfo = 138, + rt_sigreturn = 139, + setpriority = 140, + getpriority = 141, + reboot = 142, + setregid = 143, + setgid = 144, + setreuid = 145, + setuid = 146, + setresuid = 147, + getresuid = 148, + setresgid = 149, + getresgid = 150, + setfsuid = 151, + setfsgid = 152, + times = 153, + setpgid = 154, + getpgid = 155, + getsid = 156, + setsid = 157, + getgroups = 158, + setgroups = 159, + uname = 160, + sethostname = 161, + setdomainname = 162, + getrlimit = 163, + setrlimit = 164, + getrusage = 165, + umask = 166, + prctl = 167, + getcpu = 168, + gettimeofday = 169, + settimeofday = 170, + adjtimex = 171, + getpid = 172, + getppid = 173, + getuid = 174, + geteuid = 175, + getgid = 176, + getegid = 177, + gettid = 178, + sysinfo = 179, + mq_open = 180, + mq_unlink = 181, + mq_timedsend = 182, + mq_timedreceive = 183, + mq_notify = 184, + mq_getsetattr = 185, + msgget = 186, + msgctl = 187, + msgrcv = 188, + msgsnd = 189, + semget = 190, + semctl = 191, + semtimedop = 192, + semop = 193, + shmget = 194, + shmctl = 195, + shmat = 196, + shmdt = 197, + socket = 198, + socketpair = 199, + bind = 200, + listen = 201, + accept = 202, + connect = 203, + getsockname = 204, + getpeername = 205, + sendto = 206, + recvfrom = 207, + setsockopt = 208, + getsockopt = 209, + shutdown = 210, + sendmsg = 211, + recvmsg = 212, + readahead = 213, + brk = 214, + munmap = 215, + mremap = 216, + add_key = 217, + request_key = 218, + keyctl = 219, + clone = 220, + execve = 221, + mmap = 222, + fadvise64 = 223, + swapon = 224, + swapoff = 225, + mprotect = 226, + msync = 227, + mlock = 228, + munlock = 229, + mlockall = 230, + munlockall = 231, + mincore = 232, + madvise = 233, + remap_file_pages = 234, + mbind = 235, + get_mempolicy = 236, + set_mempolicy = 237, + migrate_pages = 238, + move_pages = 239, + rt_tgsigqueueinfo = 240, + perf_event_open = 241, + accept4 = 242, + recvmmsg = 243, -pub const SYS_arch_specific_syscall = 244; -pub const SYS_riscv_flush_icache = SYS_arch_specific_syscall + 15; + pub const arch_specific_syscall = 244; + riscv_flush_icache = arch_specific_syscall + 15, -pub const SYS_wait4 = 260; -pub const SYS_prlimit64 = 261; -pub const SYS_fanotify_init = 262; -pub const SYS_fanotify_mark = 263; -pub const SYS_name_to_handle_at = 264; -pub const SYS_open_by_handle_at = 265; -pub const SYS_clock_adjtime = 266; -pub const SYS_syncfs = 267; -pub const SYS_setns = 268; -pub const SYS_sendmmsg = 269; -pub const SYS_process_vm_readv = 270; -pub const SYS_process_vm_writev = 271; -pub const SYS_kcmp = 272; -pub const SYS_finit_module = 273; -pub const SYS_sched_setattr = 274; -pub const SYS_sched_getattr = 275; -pub const SYS_renameat2 = 276; -pub const SYS_seccomp = 277; -pub const SYS_getrandom = 278; -pub const SYS_memfd_create = 279; -pub const SYS_bpf = 280; -pub const SYS_execveat = 281; -pub const SYS_userfaultfd = 282; -pub const SYS_membarrier = 283; -pub const SYS_mlock2 = 284; -pub const SYS_copy_file_range = 285; -pub const SYS_preadv2 = 286; -pub const SYS_pwritev2 = 287; -pub const SYS_pkey_mprotect = 288; -pub const SYS_pkey_alloc = 289; -pub const SYS_pkey_free = 290; -pub const SYS_statx = 291; -pub const SYS_io_pgetevents = 292; -pub const SYS_rseq = 293; -pub const SYS_kexec_file_load = 294; -pub const SYS_pidfd_send_signal = 424; -pub const SYS_io_uring_setup = 425; -pub const SYS_io_uring_enter = 426; -pub const SYS_io_uring_register = 427; -pub const SYS_open_tree = 428; -pub const SYS_move_mount = 429; -pub const SYS_fsopen = 430; -pub const SYS_fsconfig = 431; -pub const SYS_fsmount = 432; -pub const SYS_fspick = 433; -pub const SYS_pidfd_open = 434; -pub const SYS_clone3 = 435; -pub const SYS_openat2 = 437; -pub const SYS_pidfd_getfd = 438; + wait4 = 260, + prlimit64 = 261, + fanotify_init = 262, + fanotify_mark = 263, + name_to_handle_at = 264, + open_by_handle_at = 265, + clock_adjtime = 266, + syncfs = 267, + setns = 268, + sendmmsg = 269, + process_vm_readv = 270, + process_vm_writev = 271, + kcmp = 272, + finit_module = 273, + sched_setattr = 274, + sched_getattr = 275, + renameat2 = 276, + seccomp = 277, + getrandom = 278, + memfd_create = 279, + bpf = 280, + execveat = 281, + userfaultfd = 282, + membarrier = 283, + mlock2 = 284, + copy_file_range = 285, + preadv2 = 286, + pwritev2 = 287, + pkey_mprotect = 288, + pkey_alloc = 289, + pkey_free = 290, + statx = 291, + io_pgetevents = 292, + rseq = 293, + kexec_file_load = 294, + pidfd_send_signal = 424, + io_uring_setup = 425, + io_uring_enter = 426, + io_uring_register = 427, + open_tree = 428, + move_mount = 429, + fsopen = 430, + fsconfig = 431, + fsmount = 432, + fspick = 433, + pidfd_open = 434, + clone3 = 435, + openat2 = 437, + pidfd_getfd = 438, + + _, +}; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/bits/linux/x86_64.zig b/lib/std/os/bits/linux/x86_64.zig index 96984c7c5a..4fd9922674 100644 --- a/lib/std/os/bits/linux/x86_64.zig +++ b/lib/std/os/bits/linux/x86_64.zig @@ -14,356 +14,360 @@ const iovec_const = linux.iovec_const; pub const mode_t = usize; -pub const SYS_read = 0; -pub const SYS_write = 1; -pub const SYS_open = 2; -pub const SYS_close = 3; -pub const SYS_stat = 4; -pub const SYS_fstat = 5; -pub const SYS_lstat = 6; -pub const SYS_poll = 7; -pub const SYS_lseek = 8; -pub const SYS_mmap = 9; -pub const SYS_mprotect = 10; -pub const SYS_munmap = 11; -pub const SYS_brk = 12; -pub const SYS_rt_sigaction = 13; -pub const SYS_rt_sigprocmask = 14; -pub const SYS_rt_sigreturn = 15; -pub const SYS_ioctl = 16; -pub const SYS_pread = 17; -pub const SYS_pwrite = 18; -pub const SYS_readv = 19; -pub const SYS_writev = 20; -pub const SYS_access = 21; -pub const SYS_pipe = 22; -pub const SYS_select = 23; -pub const SYS_sched_yield = 24; -pub const SYS_mremap = 25; -pub const SYS_msync = 26; -pub const SYS_mincore = 27; -pub const SYS_madvise = 28; -pub const SYS_shmget = 29; -pub const SYS_shmat = 30; -pub const SYS_shmctl = 31; -pub const SYS_dup = 32; -pub const SYS_dup2 = 33; -pub const SYS_pause = 34; -pub const SYS_nanosleep = 35; -pub const SYS_getitimer = 36; -pub const SYS_alarm = 37; -pub const SYS_setitimer = 38; -pub const SYS_getpid = 39; -pub const SYS_sendfile = 40; -pub const SYS_socket = 41; -pub const SYS_connect = 42; -pub const SYS_accept = 43; -pub const SYS_sendto = 44; -pub const SYS_recvfrom = 45; -pub const SYS_sendmsg = 46; -pub const SYS_recvmsg = 47; -pub const SYS_shutdown = 48; -pub const SYS_bind = 49; -pub const SYS_listen = 50; -pub const SYS_getsockname = 51; -pub const SYS_getpeername = 52; -pub const SYS_socketpair = 53; -pub const SYS_setsockopt = 54; -pub const SYS_getsockopt = 55; -pub const SYS_clone = 56; -pub const SYS_fork = 57; -pub const SYS_vfork = 58; -pub const SYS_execve = 59; -pub const SYS_exit = 60; -pub const SYS_wait4 = 61; -pub const SYS_kill = 62; -pub const SYS_uname = 63; -pub const SYS_semget = 64; -pub const SYS_semop = 65; -pub const SYS_semctl = 66; -pub const SYS_shmdt = 67; -pub const SYS_msgget = 68; -pub const SYS_msgsnd = 69; -pub const SYS_msgrcv = 70; -pub const SYS_msgctl = 71; -pub const SYS_fcntl = 72; -pub const SYS_flock = 73; -pub const SYS_fsync = 74; -pub const SYS_fdatasync = 75; -pub const SYS_truncate = 76; -pub const SYS_ftruncate = 77; -pub const SYS_getdents = 78; -pub const SYS_getcwd = 79; -pub const SYS_chdir = 80; -pub const SYS_fchdir = 81; -pub const SYS_rename = 82; -pub const SYS_mkdir = 83; -pub const SYS_rmdir = 84; -pub const SYS_creat = 85; -pub const SYS_link = 86; -pub const SYS_unlink = 87; -pub const SYS_symlink = 88; -pub const SYS_readlink = 89; -pub const SYS_chmod = 90; -pub const SYS_fchmod = 91; -pub const SYS_chown = 92; -pub const SYS_fchown = 93; -pub const SYS_lchown = 94; -pub const SYS_umask = 95; -pub const SYS_gettimeofday = 96; -pub const SYS_getrlimit = 97; -pub const SYS_getrusage = 98; -pub const SYS_sysinfo = 99; -pub const SYS_times = 100; -pub const SYS_ptrace = 101; -pub const SYS_getuid = 102; -pub const SYS_syslog = 103; -pub const SYS_getgid = 104; -pub const SYS_setuid = 105; -pub const SYS_setgid = 106; -pub const SYS_geteuid = 107; -pub const SYS_getegid = 108; -pub const SYS_setpgid = 109; -pub const SYS_getppid = 110; -pub const SYS_getpgrp = 111; -pub const SYS_setsid = 112; -pub const SYS_setreuid = 113; -pub const SYS_setregid = 114; -pub const SYS_getgroups = 115; -pub const SYS_setgroups = 116; -pub const SYS_setresuid = 117; -pub const SYS_getresuid = 118; -pub const SYS_setresgid = 119; -pub const SYS_getresgid = 120; -pub const SYS_getpgid = 121; -pub const SYS_setfsuid = 122; -pub const SYS_setfsgid = 123; -pub const SYS_getsid = 124; -pub const SYS_capget = 125; -pub const SYS_capset = 126; -pub const SYS_rt_sigpending = 127; -pub const SYS_rt_sigtimedwait = 128; -pub const SYS_rt_sigqueueinfo = 129; -pub const SYS_rt_sigsuspend = 130; -pub const SYS_sigaltstack = 131; -pub const SYS_utime = 132; -pub const SYS_mknod = 133; -pub const SYS_uselib = 134; -pub const SYS_personality = 135; -pub const SYS_ustat = 136; -pub const SYS_statfs = 137; -pub const SYS_fstatfs = 138; -pub const SYS_sysfs = 139; -pub const SYS_getpriority = 140; -pub const SYS_setpriority = 141; -pub const SYS_sched_setparam = 142; -pub const SYS_sched_getparam = 143; -pub const SYS_sched_setscheduler = 144; -pub const SYS_sched_getscheduler = 145; -pub const SYS_sched_get_priority_max = 146; -pub const SYS_sched_get_priority_min = 147; -pub const SYS_sched_rr_get_interval = 148; -pub const SYS_mlock = 149; -pub const SYS_munlock = 150; -pub const SYS_mlockall = 151; -pub const SYS_munlockall = 152; -pub const SYS_vhangup = 153; -pub const SYS_modify_ldt = 154; -pub const SYS_pivot_root = 155; -pub const SYS__sysctl = 156; -pub const SYS_prctl = 157; -pub const SYS_arch_prctl = 158; -pub const SYS_adjtimex = 159; -pub const SYS_setrlimit = 160; -pub const SYS_chroot = 161; -pub const SYS_sync = 162; -pub const SYS_acct = 163; -pub const SYS_settimeofday = 164; -pub const SYS_mount = 165; -pub const SYS_umount2 = 166; -pub const SYS_swapon = 167; -pub const SYS_swapoff = 168; -pub const SYS_reboot = 169; -pub const SYS_sethostname = 170; -pub const SYS_setdomainname = 171; -pub const SYS_iopl = 172; -pub const SYS_ioperm = 173; -pub const SYS_create_module = 174; -pub const SYS_init_module = 175; -pub const SYS_delete_module = 176; -pub const SYS_get_kernel_syms = 177; -pub const SYS_query_module = 178; -pub const SYS_quotactl = 179; -pub const SYS_nfsservctl = 180; -pub const SYS_getpmsg = 181; -pub const SYS_putpmsg = 182; -pub const SYS_afs_syscall = 183; -pub const SYS_tuxcall = 184; -pub const SYS_security = 185; -pub const SYS_gettid = 186; -pub const SYS_readahead = 187; -pub const SYS_setxattr = 188; -pub const SYS_lsetxattr = 189; -pub const SYS_fsetxattr = 190; -pub const SYS_getxattr = 191; -pub const SYS_lgetxattr = 192; -pub const SYS_fgetxattr = 193; -pub const SYS_listxattr = 194; -pub const SYS_llistxattr = 195; -pub const SYS_flistxattr = 196; -pub const SYS_removexattr = 197; -pub const SYS_lremovexattr = 198; -pub const SYS_fremovexattr = 199; -pub const SYS_tkill = 200; -pub const SYS_time = 201; -pub const SYS_futex = 202; -pub const SYS_sched_setaffinity = 203; -pub const SYS_sched_getaffinity = 204; -pub const SYS_set_thread_area = 205; -pub const SYS_io_setup = 206; -pub const SYS_io_destroy = 207; -pub const SYS_io_getevents = 208; -pub const SYS_io_submit = 209; -pub const SYS_io_cancel = 210; -pub const SYS_get_thread_area = 211; -pub const SYS_lookup_dcookie = 212; -pub const SYS_epoll_create = 213; -pub const SYS_epoll_ctl_old = 214; -pub const SYS_epoll_wait_old = 215; -pub const SYS_remap_file_pages = 216; -pub const SYS_getdents64 = 217; -pub const SYS_set_tid_address = 218; -pub const SYS_restart_syscall = 219; -pub const SYS_semtimedop = 220; -pub const SYS_fadvise64 = 221; -pub const SYS_timer_create = 222; -pub const SYS_timer_settime = 223; -pub const SYS_timer_gettime = 224; -pub const SYS_timer_getoverrun = 225; -pub const SYS_timer_delete = 226; -pub const SYS_clock_settime = 227; -pub const SYS_clock_gettime = 228; -pub const SYS_clock_getres = 229; -pub const SYS_clock_nanosleep = 230; -pub const SYS_exit_group = 231; -pub const SYS_epoll_wait = 232; -pub const SYS_epoll_ctl = 233; -pub const SYS_tgkill = 234; -pub const SYS_utimes = 235; -pub const SYS_vserver = 236; -pub const SYS_mbind = 237; -pub const SYS_set_mempolicy = 238; -pub const SYS_get_mempolicy = 239; -pub const SYS_mq_open = 240; -pub const SYS_mq_unlink = 241; -pub const SYS_mq_timedsend = 242; -pub const SYS_mq_timedreceive = 243; -pub const SYS_mq_notify = 244; -pub const SYS_mq_getsetattr = 245; -pub const SYS_kexec_load = 246; -pub const SYS_waitid = 247; -pub const SYS_add_key = 248; -pub const SYS_request_key = 249; -pub const SYS_keyctl = 250; -pub const SYS_ioprio_set = 251; -pub const SYS_ioprio_get = 252; -pub const SYS_inotify_init = 253; -pub const SYS_inotify_add_watch = 254; -pub const SYS_inotify_rm_watch = 255; -pub const SYS_migrate_pages = 256; -pub const SYS_openat = 257; -pub const SYS_mkdirat = 258; -pub const SYS_mknodat = 259; -pub const SYS_fchownat = 260; -pub const SYS_futimesat = 261; -pub const SYS_newfstatat = 262; -pub const SYS_fstatat = 262; -pub const SYS_unlinkat = 263; -pub const SYS_renameat = 264; -pub const SYS_linkat = 265; -pub const SYS_symlinkat = 266; -pub const SYS_readlinkat = 267; -pub const SYS_fchmodat = 268; -pub const SYS_faccessat = 269; -pub const SYS_pselect6 = 270; -pub const SYS_ppoll = 271; -pub const SYS_unshare = 272; -pub const SYS_set_robust_list = 273; -pub const SYS_get_robust_list = 274; -pub const SYS_splice = 275; -pub const SYS_tee = 276; -pub const SYS_sync_file_range = 277; -pub const SYS_vmsplice = 278; -pub const SYS_move_pages = 279; -pub const SYS_utimensat = 280; -pub const SYS_epoll_pwait = 281; -pub const SYS_signalfd = 282; -pub const SYS_timerfd_create = 283; -pub const SYS_eventfd = 284; -pub const SYS_fallocate = 285; -pub const SYS_timerfd_settime = 286; -pub const SYS_timerfd_gettime = 287; -pub const SYS_accept4 = 288; -pub const SYS_signalfd4 = 289; -pub const SYS_eventfd2 = 290; -pub const SYS_epoll_create1 = 291; -pub const SYS_dup3 = 292; -pub const SYS_pipe2 = 293; -pub const SYS_inotify_init1 = 294; -pub const SYS_preadv = 295; -pub const SYS_pwritev = 296; -pub const SYS_rt_tgsigqueueinfo = 297; -pub const SYS_perf_event_open = 298; -pub const SYS_recvmmsg = 299; -pub const SYS_fanotify_init = 300; -pub const SYS_fanotify_mark = 301; -pub const SYS_prlimit64 = 302; -pub const SYS_name_to_handle_at = 303; -pub const SYS_open_by_handle_at = 304; -pub const SYS_clock_adjtime = 305; -pub const SYS_syncfs = 306; -pub const SYS_sendmmsg = 307; -pub const SYS_setns = 308; -pub const SYS_getcpu = 309; -pub const SYS_process_vm_readv = 310; -pub const SYS_process_vm_writev = 311; -pub const SYS_kcmp = 312; -pub const SYS_finit_module = 313; -pub const SYS_sched_setattr = 314; -pub const SYS_sched_getattr = 315; -pub const SYS_renameat2 = 316; -pub const SYS_seccomp = 317; -pub const SYS_getrandom = 318; -pub const SYS_memfd_create = 319; -pub const SYS_kexec_file_load = 320; -pub const SYS_bpf = 321; -pub const SYS_execveat = 322; -pub const SYS_userfaultfd = 323; -pub const SYS_membarrier = 324; -pub const SYS_mlock2 = 325; -pub const SYS_copy_file_range = 326; -pub const SYS_preadv2 = 327; -pub const SYS_pwritev2 = 328; -pub const SYS_pkey_mprotect = 329; -pub const SYS_pkey_alloc = 330; -pub const SYS_pkey_free = 331; -pub const SYS_statx = 332; -pub const SYS_io_pgetevents = 333; -pub const SYS_rseq = 334; -pub const SYS_pidfd_send_signal = 424; -pub const SYS_io_uring_setup = 425; -pub const SYS_io_uring_enter = 426; -pub const SYS_io_uring_register = 427; -pub const SYS_open_tree = 428; -pub const SYS_move_mount = 429; -pub const SYS_fsopen = 430; -pub const SYS_fsconfig = 431; -pub const SYS_fsmount = 432; -pub const SYS_fspick = 433; -pub const SYS_pidfd_open = 434; -pub const SYS_clone3 = 435; -pub const SYS_openat2 = 437; -pub const SYS_pidfd_getfd = 438; +pub const SYS = extern enum(usize) { + read = 0, + write = 1, + open = 2, + close = 3, + stat = 4, + fstat = 5, + lstat = 6, + poll = 7, + lseek = 8, + mmap = 9, + mprotect = 10, + munmap = 11, + brk = 12, + rt_sigaction = 13, + rt_sigprocmask = 14, + rt_sigreturn = 15, + ioctl = 16, + pread = 17, + pwrite = 18, + readv = 19, + writev = 20, + access = 21, + pipe = 22, + select = 23, + sched_yield = 24, + mremap = 25, + msync = 26, + mincore = 27, + madvise = 28, + shmget = 29, + shmat = 30, + shmctl = 31, + dup = 32, + dup2 = 33, + pause = 34, + nanosleep = 35, + getitimer = 36, + alarm = 37, + setitimer = 38, + getpid = 39, + sendfile = 40, + socket = 41, + connect = 42, + accept = 43, + sendto = 44, + recvfrom = 45, + sendmsg = 46, + recvmsg = 47, + shutdown = 48, + bind = 49, + listen = 50, + getsockname = 51, + getpeername = 52, + socketpair = 53, + setsockopt = 54, + getsockopt = 55, + clone = 56, + fork = 57, + vfork = 58, + execve = 59, + exit = 60, + wait4 = 61, + kill = 62, + uname = 63, + semget = 64, + semop = 65, + semctl = 66, + shmdt = 67, + msgget = 68, + msgsnd = 69, + msgrcv = 70, + msgctl = 71, + fcntl = 72, + flock = 73, + fsync = 74, + fdatasync = 75, + truncate = 76, + ftruncate = 77, + getdents = 78, + getcwd = 79, + chdir = 80, + fchdir = 81, + rename = 82, + mkdir = 83, + rmdir = 84, + creat = 85, + link = 86, + unlink = 87, + symlink = 88, + readlink = 89, + chmod = 90, + fchmod = 91, + chown = 92, + fchown = 93, + lchown = 94, + umask = 95, + gettimeofday = 96, + getrlimit = 97, + getrusage = 98, + sysinfo = 99, + times = 100, + ptrace = 101, + getuid = 102, + syslog = 103, + getgid = 104, + setuid = 105, + setgid = 106, + geteuid = 107, + getegid = 108, + setpgid = 109, + getppid = 110, + getpgrp = 111, + setsid = 112, + setreuid = 113, + setregid = 114, + getgroups = 115, + setgroups = 116, + setresuid = 117, + getresuid = 118, + setresgid = 119, + getresgid = 120, + getpgid = 121, + setfsuid = 122, + setfsgid = 123, + getsid = 124, + capget = 125, + capset = 126, + rt_sigpending = 127, + rt_sigtimedwait = 128, + rt_sigqueueinfo = 129, + rt_sigsuspend = 130, + sigaltstack = 131, + utime = 132, + mknod = 133, + uselib = 134, + personality = 135, + ustat = 136, + statfs = 137, + fstatfs = 138, + sysfs = 139, + getpriority = 140, + setpriority = 141, + sched_setparam = 142, + sched_getparam = 143, + sched_setscheduler = 144, + sched_getscheduler = 145, + sched_get_priority_max = 146, + sched_get_priority_min = 147, + sched_rr_get_interval = 148, + mlock = 149, + munlock = 150, + mlockall = 151, + munlockall = 152, + vhangup = 153, + modify_ldt = 154, + pivot_root = 155, + _sysctl = 156, + prctl = 157, + arch_prctl = 158, + adjtimex = 159, + setrlimit = 160, + chroot = 161, + sync = 162, + acct = 163, + settimeofday = 164, + mount = 165, + umount2 = 166, + swapon = 167, + swapoff = 168, + reboot = 169, + sethostname = 170, + setdomainname = 171, + iopl = 172, + ioperm = 173, + create_module = 174, + init_module = 175, + delete_module = 176, + get_kernel_syms = 177, + query_module = 178, + quotactl = 179, + nfsservctl = 180, + getpmsg = 181, + putpmsg = 182, + afs_syscall = 183, + tuxcall = 184, + security = 185, + gettid = 186, + readahead = 187, + setxattr = 188, + lsetxattr = 189, + fsetxattr = 190, + getxattr = 191, + lgetxattr = 192, + fgetxattr = 193, + listxattr = 194, + llistxattr = 195, + flistxattr = 196, + removexattr = 197, + lremovexattr = 198, + fremovexattr = 199, + tkill = 200, + time = 201, + futex = 202, + sched_setaffinity = 203, + sched_getaffinity = 204, + set_thread_area = 205, + io_setup = 206, + io_destroy = 207, + io_getevents = 208, + io_submit = 209, + io_cancel = 210, + get_thread_area = 211, + lookup_dcookie = 212, + epoll_create = 213, + epoll_ctl_old = 214, + epoll_wait_old = 215, + remap_file_pages = 216, + getdents64 = 217, + set_tid_address = 218, + restart_syscall = 219, + semtimedop = 220, + fadvise64 = 221, + timer_create = 222, + timer_settime = 223, + timer_gettime = 224, + timer_getoverrun = 225, + timer_delete = 226, + clock_settime = 227, + clock_gettime = 228, + clock_getres = 229, + clock_nanosleep = 230, + exit_group = 231, + epoll_wait = 232, + epoll_ctl = 233, + tgkill = 234, + utimes = 235, + vserver = 236, + mbind = 237, + set_mempolicy = 238, + get_mempolicy = 239, + mq_open = 240, + mq_unlink = 241, + mq_timedsend = 242, + mq_timedreceive = 243, + mq_notify = 244, + mq_getsetattr = 245, + kexec_load = 246, + waitid = 247, + add_key = 248, + request_key = 249, + keyctl = 250, + ioprio_set = 251, + ioprio_get = 252, + inotify_init = 253, + inotify_add_watch = 254, + inotify_rm_watch = 255, + migrate_pages = 256, + openat = 257, + mkdirat = 258, + mknodat = 259, + fchownat = 260, + futimesat = 261, + newfstatat = 262, + fstatat = 262, + unlinkat = 263, + renameat = 264, + linkat = 265, + symlinkat = 266, + readlinkat = 267, + fchmodat = 268, + faccessat = 269, + pselect6 = 270, + ppoll = 271, + unshare = 272, + set_robust_list = 273, + get_robust_list = 274, + splice = 275, + tee = 276, + sync_file_range = 277, + vmsplice = 278, + move_pages = 279, + utimensat = 280, + epoll_pwait = 281, + signalfd = 282, + timerfd_create = 283, + eventfd = 284, + fallocate = 285, + timerfd_settime = 286, + timerfd_gettime = 287, + accept4 = 288, + signalfd4 = 289, + eventfd2 = 290, + epoll_create1 = 291, + dup3 = 292, + pipe2 = 293, + inotify_init1 = 294, + preadv = 295, + pwritev = 296, + rt_tgsigqueueinfo = 297, + perf_event_open = 298, + recvmmsg = 299, + fanotify_init = 300, + fanotify_mark = 301, + prlimit64 = 302, + name_to_handle_at = 303, + open_by_handle_at = 304, + clock_adjtime = 305, + syncfs = 306, + sendmmsg = 307, + setns = 308, + getcpu = 309, + process_vm_readv = 310, + process_vm_writev = 311, + kcmp = 312, + finit_module = 313, + sched_setattr = 314, + sched_getattr = 315, + renameat2 = 316, + seccomp = 317, + getrandom = 318, + memfd_create = 319, + kexec_file_load = 320, + bpf = 321, + execveat = 322, + userfaultfd = 323, + membarrier = 324, + mlock2 = 325, + copy_file_range = 326, + preadv2 = 327, + pwritev2 = 328, + pkey_mprotect = 329, + pkey_alloc = 330, + pkey_free = 331, + statx = 332, + io_pgetevents = 333, + rseq = 334, + pidfd_send_signal = 424, + io_uring_setup = 425, + io_uring_enter = 426, + io_uring_register = 427, + open_tree = 428, + move_mount = 429, + fsopen = 430, + fsconfig = 431, + fsmount = 432, + fspick = 433, + pidfd_open = 434, + clone3 = 435, + openat2 = 437, + pidfd_getfd = 438, + + _, +}; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; diff --git a/lib/std/os/linux.zig b/lib/std/os/linux.zig index 2e1437e6a9..1ed8370274 100644 --- a/lib/std/os/linux.zig +++ b/lib/std/os/linux.zig @@ -53,46 +53,46 @@ pub fn getErrno(r: usize) u12 { } pub fn dup2(old: i32, new: i32) usize { - if (@hasDecl(@This(), "SYS_dup2")) { - return syscall2(SYS_dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new))); + if (@hasField(SYS, "dup2")) { + return syscall2(.dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new))); } else { if (old == new) { if (std.debug.runtime_safety) { - const rc = syscall2(SYS_fcntl, @bitCast(usize, @as(isize, old)), F_GETFD); + const rc = syscall2(.fcntl, @bitCast(usize, @as(isize, old)), F_GETFD); if (@bitCast(isize, rc) < 0) return rc; } return @intCast(usize, old); } else { - return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0); + return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0); } } } pub fn dup3(old: i32, new: i32, flags: u32) usize { - return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags); + return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags); } pub fn chdir(path: [*:0]const u8) usize { - return syscall1(SYS_chdir, @ptrToInt(path)); + return syscall1(.chdir, @ptrToInt(path)); } pub fn fchdir(fd: fd_t) usize { - return syscall1(SYS_fchdir, @bitCast(usize, @as(isize, fd))); + return syscall1(.fchdir, @bitCast(usize, @as(isize, fd))); } pub fn chroot(path: [*:0]const u8) usize { - return syscall1(SYS_chroot, @ptrToInt(path)); + return syscall1(.chroot, @ptrToInt(path)); } pub fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) usize { - return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp)); + return syscall3(.execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp)); } pub fn fork() usize { - if (@hasDecl(@This(), "SYS_fork")) { - return syscall0(SYS_fork); + if (@hasField(SYS, "fork")) { + return syscall0(.fork); } else { - return syscall2(SYS_clone, SIGCHLD, 0); + return syscall2(.clone, SIGCHLD, 0); } } @@ -102,7 +102,7 @@ pub fn fork() usize { /// the compiler is not aware of how vfork affects control flow and you may /// see different results in optimized builds. pub inline fn vfork() usize { - return @call(.{ .modifier = .always_inline }, syscall0, .{SYS_vfork}); + return @call(.{ .modifier = .always_inline }, syscall0, .{.vfork}); } pub fn futimens(fd: i32, times: *const [2]timespec) usize { @@ -110,24 +110,24 @@ pub fn futimens(fd: i32, times: *const [2]timespec) usize { } pub fn utimensat(dirfd: i32, path: ?[*:0]const u8, times: *const [2]timespec, flags: u32) usize { - return syscall4(SYS_utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags); + return syscall4(.utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags); } pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*timespec) usize { - return syscall4(SYS_futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout)); + return syscall4(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout)); } pub fn futex_wake(uaddr: *const i32, futex_op: u32, val: i32) usize { - return syscall3(SYS_futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val)); + return syscall3(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val)); } pub fn getcwd(buf: [*]u8, size: usize) usize { - return syscall2(SYS_getcwd, @ptrToInt(buf), size); + return syscall2(.getcwd, @ptrToInt(buf), size); } pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize { return syscall3( - SYS_getdents, + .getdents, @bitCast(usize, @as(isize, fd)), @ptrToInt(dirp), std.math.min(len, maxInt(c_int)), @@ -136,7 +136,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize { pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize { return syscall3( - SYS_getdents64, + .getdents64, @bitCast(usize, @as(isize, fd)), @ptrToInt(dirp), std.math.min(len, maxInt(c_int)), @@ -144,61 +144,61 @@ pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize { } pub fn inotify_init1(flags: u32) usize { - return syscall1(SYS_inotify_init1, flags); + return syscall1(.inotify_init1, flags); } pub fn inotify_add_watch(fd: i32, pathname: [*:0]const u8, mask: u32) usize { - return syscall3(SYS_inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask); + return syscall3(.inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask); } pub fn inotify_rm_watch(fd: i32, wd: i32) usize { - return syscall2(SYS_inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd))); + return syscall2(.inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd))); } pub fn readlink(noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { - if (@hasDecl(@This(), "SYS_readlink")) { - return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); + if (@hasField(SYS, "readlink")) { + return syscall3(.readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } else { - return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); + return syscall4(.readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } } pub fn readlinkat(dirfd: i32, noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { - return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); + return syscall4(.readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len); } pub fn mkdir(path: [*:0]const u8, mode: u32) usize { - if (@hasDecl(@This(), "SYS_mkdir")) { - return syscall2(SYS_mkdir, @ptrToInt(path), mode); + if (@hasField(SYS, "mkdir")) { + return syscall2(.mkdir, @ptrToInt(path), mode); } else { - return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode); + return syscall3(.mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode); } } pub fn mkdirat(dirfd: i32, path: [*:0]const u8, mode: u32) usize { - return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode); + return syscall3(.mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode); } pub fn mount(special: [*:0]const u8, dir: [*:0]const u8, fstype: [*:0]const u8, flags: u32, data: usize) usize { - return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data); + return syscall5(.mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data); } pub fn umount(special: [*:0]const u8) usize { - return syscall2(SYS_umount2, @ptrToInt(special), 0); + return syscall2(.umount2, @ptrToInt(special), 0); } pub fn umount2(special: [*:0]const u8, flags: u32) usize { - return syscall2(SYS_umount2, @ptrToInt(special), flags); + return syscall2(.umount2, @ptrToInt(special), flags); } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: u64) usize { - if (@hasDecl(@This(), "SYS_mmap2")) { + if (@hasField(SYS, "mmap2")) { // Make sure the offset is also specified in multiples of page size if ((offset & (MMAP2_UNIT - 1)) != 0) return @bitCast(usize, @as(isize, -EINVAL)); return syscall6( - SYS_mmap2, + .mmap2, @ptrToInt(address), length, prot, @@ -208,7 +208,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of ); } else { return syscall6( - SYS_mmap, + .mmap, @ptrToInt(address), length, prot, @@ -220,19 +220,19 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of } pub fn mprotect(address: [*]const u8, length: usize, protection: usize) usize { - return syscall3(SYS_mprotect, @ptrToInt(address), length, protection); + return syscall3(.mprotect, @ptrToInt(address), length, protection); } pub fn munmap(address: [*]const u8, length: usize) usize { - return syscall2(SYS_munmap, @ptrToInt(address), length); + return syscall2(.munmap, @ptrToInt(address), length); } pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize { - if (@hasDecl(@This(), "SYS_poll")) { - return syscall3(SYS_poll, @ptrToInt(fds), n, @bitCast(u32, timeout)); + if (@hasField(SYS, "poll")) { + return syscall3(.poll, @ptrToInt(fds), n, @bitCast(u32, timeout)); } else { return syscall6( - SYS_ppoll, + .ppoll, @ptrToInt(fds), n, @ptrToInt(if (timeout >= 0) @@ -250,12 +250,12 @@ pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize { } pub fn read(fd: i32, buf: [*]u8, count: usize) usize { - return syscall3(SYS_read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count); + return syscall3(.read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count); } pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize { return syscall5( - SYS_preadv, + .preadv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, @@ -266,7 +266,7 @@ pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize { pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: kernel_rwf) usize { return syscall6( - SYS_preadv2, + .preadv2, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, @@ -277,16 +277,16 @@ pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: k } pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize { - return syscall3(SYS_readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count); + return syscall3(.readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count); } pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize { - return syscall3(SYS_writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count); + return syscall3(.writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count); } pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) usize { return syscall5( - SYS_pwritev, + .pwritev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, @@ -297,7 +297,7 @@ pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) us pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, flags: kernel_rwf) usize { return syscall6( - SYS_pwritev2, + .pwritev2, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count, @@ -308,30 +308,30 @@ pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, f } pub fn rmdir(path: [*:0]const u8) usize { - if (@hasDecl(@This(), "SYS_rmdir")) { - return syscall1(SYS_rmdir, @ptrToInt(path)); + if (@hasField(SYS, "rmdir")) { + return syscall1(.rmdir, @ptrToInt(path)); } else { - return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR); + return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR); } } pub fn symlink(existing: [*:0]const u8, new: [*:0]const u8) usize { - if (@hasDecl(@This(), "SYS_symlink")) { - return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new)); + if (@hasField(SYS, "symlink")) { + return syscall2(.symlink, @ptrToInt(existing), @ptrToInt(new)); } else { - return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new)); + return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new)); } } pub fn symlinkat(existing: [*:0]const u8, newfd: i32, newpath: [*:0]const u8) usize { - return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath)); + return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath)); } pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize { - if (@hasDecl(@This(), "SYS_pread64")) { + if (@hasField(SYS, "pread64")) { if (require_aligned_register_pair) { return syscall6( - SYS_pread64, + .pread64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, @@ -341,7 +341,7 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize { ); } else { return syscall5( - SYS_pread64, + .pread64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, @@ -351,7 +351,7 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize { } } else { return syscall4( - SYS_pread, + .pread, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, @@ -361,40 +361,40 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize { } pub fn access(path: [*:0]const u8, mode: u32) usize { - if (@hasDecl(@This(), "SYS_access")) { - return syscall2(SYS_access, @ptrToInt(path), mode); + if (@hasField(SYS, "access")) { + return syscall2(.access, @ptrToInt(path), mode); } else { - return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0); + return syscall4(.faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0); } } pub fn faccessat(dirfd: i32, path: [*:0]const u8, mode: u32, flags: u32) usize { - return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags); + return syscall4(.faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags); } pub fn pipe(fd: *[2]i32) usize { if (comptime builtin.arch.isMIPS()) { return syscall_pipe(fd); - } else if (@hasDecl(@This(), "SYS_pipe")) { - return syscall1(SYS_pipe, @ptrToInt(fd)); + } else if (@hasField(SYS, "pipe")) { + return syscall1(.pipe, @ptrToInt(fd)); } else { - return syscall2(SYS_pipe2, @ptrToInt(fd), 0); + return syscall2(.pipe2, @ptrToInt(fd), 0); } } pub fn pipe2(fd: *[2]i32, flags: u32) usize { - return syscall2(SYS_pipe2, @ptrToInt(fd), flags); + return syscall2(.pipe2, @ptrToInt(fd), flags); } pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { - return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count); + return syscall3(.write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count); } pub fn ftruncate(fd: i32, length: u64) usize { - if (@hasDecl(@This(), "SYS_ftruncate64")) { + if (@hasField(SYS, "ftruncate64")) { if (require_aligned_register_pair) { return syscall4( - SYS_ftruncate64, + .ftruncate64, @bitCast(usize, @as(isize, fd)), 0, @truncate(usize, length), @@ -402,7 +402,7 @@ pub fn ftruncate(fd: i32, length: u64) usize { ); } else { return syscall3( - SYS_ftruncate64, + .ftruncate64, @bitCast(usize, @as(isize, fd)), @truncate(usize, length), @truncate(usize, length >> 32), @@ -410,7 +410,7 @@ pub fn ftruncate(fd: i32, length: u64) usize { } } else { return syscall2( - SYS_ftruncate, + .ftruncate, @bitCast(usize, @as(isize, fd)), @truncate(usize, length), ); @@ -418,10 +418,10 @@ pub fn ftruncate(fd: i32, length: u64) usize { } pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { - if (@hasDecl(@This(), "SYS_pwrite64")) { + if (@hasField(SYS, "pwrite64")) { if (require_aligned_register_pair) { return syscall6( - SYS_pwrite64, + .pwrite64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, @@ -431,7 +431,7 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { ); } else { return syscall5( - SYS_pwrite64, + .pwrite64, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, @@ -441,7 +441,7 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { } } else { return syscall4( - SYS_pwrite, + .pwrite, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, @@ -451,19 +451,19 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { } pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize { - if (@hasDecl(@This(), "SYS_rename")) { - return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new)); - } else if (@hasDecl(@This(), "SYS_renameat")) { - return syscall4(SYS_renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new)); + if (@hasField(SYS, "rename")) { + return syscall2(.rename, @ptrToInt(old), @ptrToInt(new)); + } else if (@hasField(SYS, "renameat")) { + return syscall4(.renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new)); } else { - return syscall5(SYS_renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0); + return syscall5(.renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0); } } pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8) usize { - if (@hasDecl(@This(), "SYS_renameat")) { + if (@hasField(SYS, "renameat")) { return syscall4( - SYS_renameat, + .renameat, @bitCast(usize, @as(isize, oldfd)), @ptrToInt(oldpath), @bitCast(usize, @as(isize, newfd)), @@ -471,7 +471,7 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const ); } else { return syscall5( - SYS_renameat2, + .renameat2, @bitCast(usize, @as(isize, oldfd)), @ptrToInt(oldpath), @bitCast(usize, @as(isize, newfd)), @@ -483,7 +483,7 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]const u8, flags: u32) usize { return syscall5( - SYS_renameat2, + .renameat2, @bitCast(usize, @as(isize, oldfd)), @ptrToInt(oldpath), @bitCast(usize, @as(isize, newfd)), @@ -493,11 +493,11 @@ pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]c } pub fn open(path: [*:0]const u8, flags: u32, perm: usize) usize { - if (@hasDecl(@This(), "SYS_open")) { - return syscall3(SYS_open, @ptrToInt(path), flags, perm); + if (@hasField(SYS, "open")) { + return syscall3(.open, @ptrToInt(path), flags, perm); } else { return syscall4( - SYS_openat, + .openat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), flags, @@ -507,32 +507,32 @@ pub fn open(path: [*:0]const u8, flags: u32, perm: usize) usize { } pub fn create(path: [*:0]const u8, perm: usize) usize { - return syscall2(SYS_creat, @ptrToInt(path), perm); + return syscall2(.creat, @ptrToInt(path), perm); } pub fn openat(dirfd: i32, path: [*:0]const u8, flags: u32, mode: usize) usize { // dirfd could be negative, for example AT_FDCWD is -100 - return syscall4(SYS_openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode); + return syscall4(.openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode); } /// See also `clone` (from the arch-specific include) pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize { - return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls); + return syscall5(.clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls); } /// See also `clone` (from the arch-specific include) pub fn clone2(flags: u32, child_stack_ptr: usize) usize { - return syscall2(SYS_clone, flags, child_stack_ptr); + return syscall2(.clone, flags, child_stack_ptr); } pub fn close(fd: i32) usize { - return syscall1(SYS_close, @bitCast(usize, @as(isize, fd))); + return syscall1(.close, @bitCast(usize, @as(isize, fd))); } /// Can only be called on 32 bit systems. For 64 bit see `lseek`. pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize { return syscall5( - SYS__llseek, + ._llseek, @bitCast(usize, @as(isize, fd)), @truncate(usize, offset >> 32), @truncate(usize, offset), @@ -543,53 +543,53 @@ pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize { /// Can only be called on 64 bit systems. For 32 bit see `llseek`. pub fn lseek(fd: i32, offset: i64, whence: usize) usize { - return syscall3(SYS_lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence); + return syscall3(.lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence); } pub fn exit(status: i32) noreturn { - _ = syscall1(SYS_exit, @bitCast(usize, @as(isize, status))); + _ = syscall1(.exit, @bitCast(usize, @as(isize, status))); unreachable; } pub fn exit_group(status: i32) noreturn { - _ = syscall1(SYS_exit_group, @bitCast(usize, @as(isize, status))); + _ = syscall1(.exit_group, @bitCast(usize, @as(isize, status))); unreachable; } pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize { - return syscall3(SYS_getrandom, @ptrToInt(buf), count, flags); + return syscall3(.getrandom, @ptrToInt(buf), count, flags); } pub fn kill(pid: pid_t, sig: i32) usize { - return syscall2(SYS_kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig))); + return syscall2(.kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig))); } pub fn tkill(tid: pid_t, sig: i32) usize { - return syscall2(SYS_tkill, @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig))); + return syscall2(.tkill, @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig))); } pub fn tgkill(tgid: pid_t, tid: pid_t, sig: i32) usize { - return syscall2(SYS_tgkill, @bitCast(usize, @as(isize, tgid)), @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig))); + return syscall2(.tgkill, @bitCast(usize, @as(isize, tgid)), @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig))); } pub fn unlink(path: [*:0]const u8) usize { - if (@hasDecl(@This(), "SYS_unlink")) { - return syscall1(SYS_unlink, @ptrToInt(path)); + if (@hasField(SYS, "unlink")) { + return syscall1(.unlink, @ptrToInt(path)); } else { - return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0); + return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0); } } pub fn unlinkat(dirfd: i32, path: [*:0]const u8, flags: u32) usize { - return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags); + return syscall3(.unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags); } pub fn waitpid(pid: pid_t, status: *u32, flags: u32) usize { - return syscall4(SYS_wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0); + return syscall4(.wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0); } pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) usize { - return syscall3(SYS_fcntl, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, cmd)), arg); + return syscall3(.fcntl, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, cmd)), arg); } var vdso_clock_gettime = @ptrCast(?*const c_void, init_vdso_clock_gettime); @@ -609,7 +609,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize { } } } - return syscall2(SYS_clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); + return syscall2(.clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); } fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize { @@ -626,86 +626,86 @@ fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize { } pub fn clock_getres(clk_id: i32, tp: *timespec) usize { - return syscall2(SYS_clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); + return syscall2(.clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); } pub fn clock_settime(clk_id: i32, tp: *const timespec) usize { - return syscall2(SYS_clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); + return syscall2(.clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp)); } pub fn gettimeofday(tv: *timeval, tz: *timezone) usize { - return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); + return syscall2(.gettimeofday, @ptrToInt(tv), @ptrToInt(tz)); } pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize { - return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz)); + return syscall2(.settimeofday, @ptrToInt(tv), @ptrToInt(tz)); } pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { - return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem)); + return syscall2(.nanosleep, @ptrToInt(req), @ptrToInt(rem)); } pub fn setuid(uid: u32) usize { - if (@hasDecl(@This(), "SYS_setuid32")) { - return syscall1(SYS_setuid32, uid); + if (@hasField(SYS, "setuid32")) { + return syscall1(.setuid32, uid); } else { - return syscall1(SYS_setuid, uid); + return syscall1(.setuid, uid); } } pub fn setgid(gid: u32) usize { - if (@hasDecl(@This(), "SYS_setgid32")) { - return syscall1(SYS_setgid32, gid); + if (@hasField(SYS, "setgid32")) { + return syscall1(.setgid32, gid); } else { - return syscall1(SYS_setgid, gid); + return syscall1(.setgid, gid); } } pub fn setreuid(ruid: u32, euid: u32) usize { - if (@hasDecl(@This(), "SYS_setreuid32")) { - return syscall2(SYS_setreuid32, ruid, euid); + if (@hasField(SYS, "setreuid32")) { + return syscall2(.setreuid32, ruid, euid); } else { - return syscall2(SYS_setreuid, ruid, euid); + return syscall2(.setreuid, ruid, euid); } } pub fn setregid(rgid: u32, egid: u32) usize { - if (@hasDecl(@This(), "SYS_setregid32")) { - return syscall2(SYS_setregid32, rgid, egid); + if (@hasField(SYS, "setregid32")) { + return syscall2(.setregid32, rgid, egid); } else { - return syscall2(SYS_setregid, rgid, egid); + return syscall2(.setregid, rgid, egid); } } pub fn getuid() u32 { - if (@hasDecl(@This(), "SYS_getuid32")) { - return @as(u32, syscall0(SYS_getuid32)); + if (@hasField(SYS, "getuid32")) { + return @as(u32, syscall0(.getuid32)); } else { - return @as(u32, syscall0(SYS_getuid)); + return @as(u32, syscall0(.getuid)); } } pub fn getgid() u32 { - if (@hasDecl(@This(), "SYS_getgid32")) { - return @as(u32, syscall0(SYS_getgid32)); + if (@hasField(SYS, "getgid32")) { + return @as(u32, syscall0(.getgid32)); } else { - return @as(u32, syscall0(SYS_getgid)); + return @as(u32, syscall0(.getgid)); } } pub fn geteuid() u32 { - if (@hasDecl(@This(), "SYS_geteuid32")) { - return @as(u32, syscall0(SYS_geteuid32)); + if (@hasField(SYS, "geteuid32")) { + return @as(u32, syscall0(.geteuid32)); } else { - return @as(u32, syscall0(SYS_geteuid)); + return @as(u32, syscall0(.geteuid)); } } pub fn getegid() u32 { - if (@hasDecl(@This(), "SYS_getegid32")) { - return @as(u32, syscall0(SYS_getegid32)); + if (@hasField(SYS, "getegid32")) { + return @as(u32, syscall0(.getegid32)); } else { - return @as(u32, syscall0(SYS_getegid)); + return @as(u32, syscall0(.getegid)); } } @@ -718,63 +718,63 @@ pub fn setegid(egid: u32) usize { } pub fn getresuid(ruid: *u32, euid: *u32, suid: *u32) usize { - if (@hasDecl(@This(), "SYS_getresuid32")) { - return syscall3(SYS_getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); + if (@hasField(SYS, "getresuid32")) { + return syscall3(.getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); } else { - return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); + return syscall3(.getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid)); } } pub fn getresgid(rgid: *u32, egid: *u32, sgid: *u32) usize { - if (@hasDecl(@This(), "SYS_getresgid32")) { - return syscall3(SYS_getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); + if (@hasField(SYS, "getresgid32")) { + return syscall3(.getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); } else { - return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); + return syscall3(.getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid)); } } pub fn setresuid(ruid: u32, euid: u32, suid: u32) usize { - if (@hasDecl(@This(), "SYS_setresuid32")) { - return syscall3(SYS_setresuid32, ruid, euid, suid); + if (@hasField(SYS, "setresuid32")) { + return syscall3(.setresuid32, ruid, euid, suid); } else { - return syscall3(SYS_setresuid, ruid, euid, suid); + return syscall3(.setresuid, ruid, euid, suid); } } pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize { - if (@hasDecl(@This(), "SYS_setresgid32")) { - return syscall3(SYS_setresgid32, rgid, egid, sgid); + if (@hasField(SYS, "setresgid32")) { + return syscall3(.setresgid32, rgid, egid, sgid); } else { - return syscall3(SYS_setresgid, rgid, egid, sgid); + return syscall3(.setresgid, rgid, egid, sgid); } } pub fn getgroups(size: usize, list: *u32) usize { - if (@hasDecl(@This(), "SYS_getgroups32")) { - return syscall2(SYS_getgroups32, size, @ptrToInt(list)); + if (@hasField(SYS, "getgroups32")) { + return syscall2(.getgroups32, size, @ptrToInt(list)); } else { - return syscall2(SYS_getgroups, size, @ptrToInt(list)); + return syscall2(.getgroups, size, @ptrToInt(list)); } } pub fn setgroups(size: usize, list: *const u32) usize { - if (@hasDecl(@This(), "SYS_setgroups32")) { - return syscall2(SYS_setgroups32, size, @ptrToInt(list)); + if (@hasField(SYS, "setgroups32")) { + return syscall2(.setgroups32, size, @ptrToInt(list)); } else { - return syscall2(SYS_setgroups, size, @ptrToInt(list)); + return syscall2(.setgroups, size, @ptrToInt(list)); } } pub fn getpid() pid_t { - return @bitCast(pid_t, @truncate(u32, syscall0(SYS_getpid))); + return @bitCast(pid_t, @truncate(u32, syscall0(.getpid))); } pub fn gettid() pid_t { - return @bitCast(pid_t, @truncate(u32, syscall0(SYS_gettid))); + return @bitCast(pid_t, @truncate(u32, syscall0(.gettid))); } pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) usize { - return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8); + return syscall4(.rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8); } pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize { @@ -792,7 +792,7 @@ pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigacti var ksa_old: k_sigaction = undefined; const ksa_mask_size = @sizeOf(@TypeOf(ksa_old.mask)); @memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &act.mask), ksa_mask_size); - const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), ksa_mask_size); + const result = syscall4(.rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), ksa_mask_size); const err = getErrno(result); if (err != 0) { return result; @@ -819,42 +819,42 @@ pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) us if (builtin.arch == .i386) { return socketcall(SC_getsockname, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) }); } - return syscall3(SYS_getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len)); + return syscall3(.getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len)); } pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_getpeername, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) }); } - return syscall3(SYS_getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len)); + return syscall3(.getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len)); } pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_socket, &[3]usize{ domain, socket_type, protocol }); } - return syscall3(SYS_socket, domain, socket_type, protocol); + return syscall3(.socket, domain, socket_type, protocol); } pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_setsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen) }); } - return syscall5(SYS_setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen)); + return syscall5(.setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen)); } pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_getsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen) }); } - return syscall5(SYS_getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); + return syscall5(.getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } pub fn sendmsg(fd: i32, msg: *msghdr_const, flags: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_sendmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags }); } - return syscall3(SYS_sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags); + return syscall3(.sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags); } pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize { @@ -872,7 +872,7 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize // batch-send all messages up to the current message if (next_unsent < i) { const batch_size = i - next_unsent; - const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags); + const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags); if (getErrno(r) != 0) return next_unsent; if (r < batch_size) return next_unsent + r; } @@ -888,68 +888,68 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize } if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG_EOR) const batch_size = kvlen - next_unsent; - const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags); + const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags); if (getErrno(r) != 0) return r; return next_unsent + r; } return kvlen; } - return syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags); + return syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags); } pub fn connect(fd: i32, addr: *const c_void, len: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_connect, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len }); } - return syscall3(SYS_connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len); + return syscall3(.connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len); } pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_recvmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags }); } - return syscall3(SYS_recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags); + return syscall3(.recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags); } pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_recvfrom, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen) }); } - return syscall6(SYS_recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); + return syscall6(.recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } pub fn shutdown(fd: i32, how: i32) usize { if (builtin.arch == .i386) { return socketcall(SC_shutdown, &[2]usize{ @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)) }); } - return syscall2(SYS_shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how))); + return syscall2(.shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how))); } pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_bind, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len) }); } - return syscall3(SYS_bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len)); + return syscall3(.bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len)); } pub fn listen(fd: i32, backlog: u32) usize { if (builtin.arch == .i386) { return socketcall(SC_listen, &[2]usize{ @bitCast(usize, @as(isize, fd)), backlog }); } - return syscall2(SYS_listen, @bitCast(usize, @as(isize, fd)), backlog); + return syscall2(.listen, @bitCast(usize, @as(isize, fd)), backlog); } pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { if (builtin.arch == .i386) { return socketcall(SC_sendto, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen) }); } - return syscall6(SYS_sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen)); + return syscall6(.sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen)); } pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize { - if (@hasDecl(@This(), "SYS_sendfile64")) { + if (@hasField(SYS, "sendfile64")) { return syscall4( - SYS_sendfile64, + .sendfile64, @bitCast(usize, @as(isize, outfd)), @bitCast(usize, @as(isize, infd)), @ptrToInt(offset), @@ -957,7 +957,7 @@ pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize { ); } else { return syscall4( - SYS_sendfile, + .sendfile, @bitCast(usize, @as(isize, outfd)), @bitCast(usize, @as(isize, infd)), @ptrToInt(offset), @@ -970,7 +970,7 @@ pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usiz if (builtin.arch == .i386) { return socketcall(SC_socketpair, &[4]usize{ @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]) }); } - return syscall4(SYS_socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0])); + return syscall4(.socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0])); } pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { @@ -984,45 +984,45 @@ pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: if (builtin.arch == .i386) { return socketcall(SC_accept4, &[4]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags }); } - return syscall4(SYS_accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags); + return syscall4(.accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags); } pub fn fstat(fd: i32, stat_buf: *Stat) usize { - if (@hasDecl(@This(), "SYS_fstat64")) { - return syscall2(SYS_fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf)); + if (@hasField(SYS, "fstat64")) { + return syscall2(.fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf)); } else { - return syscall2(SYS_fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf)); + return syscall2(.fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf)); } } pub fn stat(pathname: [*:0]const u8, statbuf: *Stat) usize { - if (@hasDecl(@This(), "SYS_stat64")) { - return syscall2(SYS_stat64, @ptrToInt(pathname), @ptrToInt(statbuf)); + if (@hasField(SYS, "stat64")) { + return syscall2(.stat64, @ptrToInt(pathname), @ptrToInt(statbuf)); } else { - return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf)); + return syscall2(.stat, @ptrToInt(pathname), @ptrToInt(statbuf)); } } pub fn lstat(pathname: [*:0]const u8, statbuf: *Stat) usize { - if (@hasDecl(@This(), "SYS_lstat64")) { - return syscall2(SYS_lstat64, @ptrToInt(pathname), @ptrToInt(statbuf)); + if (@hasField(SYS, "lstat64")) { + return syscall2(.lstat64, @ptrToInt(pathname), @ptrToInt(statbuf)); } else { - return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf)); + return syscall2(.lstat, @ptrToInt(pathname), @ptrToInt(statbuf)); } } pub fn fstatat(dirfd: i32, path: [*:0]const u8, stat_buf: *Stat, flags: u32) usize { - if (@hasDecl(@This(), "SYS_fstatat64")) { - return syscall4(SYS_fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); + if (@hasField(SYS, "fstatat64")) { + return syscall4(.fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); } else { - return syscall4(SYS_fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); + return syscall4(.fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags); } } pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *Statx) usize { - if (@hasDecl(@This(), "SYS_statx")) { + if (@hasField(SYS, "statx")) { return syscall5( - SYS_statx, + .statx, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, @@ -1034,59 +1034,59 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S } pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize { - return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size); + return syscall3(.listxattr, @ptrToInt(path), @ptrToInt(list), size); } pub fn llistxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize { - return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size); + return syscall3(.llistxattr, @ptrToInt(path), @ptrToInt(list), size); } pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize { - return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size); + return syscall3(.flistxattr, fd, @ptrToInt(list), size); } pub fn getxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize { - return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); + return syscall4(.getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } pub fn lgetxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize { - return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); + return syscall4(.lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size); } pub fn fgetxattr(fd: usize, name: [*:0]const u8, value: [*]u8, size: usize) usize { - return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); + return syscall4(.lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size); } pub fn setxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize { - return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); + return syscall5(.setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn lsetxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize { - return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); + return syscall5(.lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn fsetxattr(fd: usize, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize { - return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); + return syscall5(.fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags); } pub fn removexattr(path: [*:0]const u8, name: [*:0]const u8) usize { - return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name)); + return syscall2(.removexattr, @ptrToInt(path), @ptrToInt(name)); } pub fn lremovexattr(path: [*:0]const u8, name: [*:0]const u8) usize { - return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name)); + return syscall2(.lremovexattr, @ptrToInt(path), @ptrToInt(name)); } pub fn fremovexattr(fd: usize, name: [*:0]const u8) usize { - return syscall2(SYS_fremovexattr, fd, @ptrToInt(name)); + return syscall2(.fremovexattr, fd, @ptrToInt(name)); } pub fn sched_yield() usize { - return syscall0(SYS_sched_yield); + return syscall0(.sched_yield); } pub fn sched_getaffinity(pid: pid_t, size: usize, set: *cpu_set_t) usize { - const rc = syscall3(SYS_sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set)); + const rc = syscall3(.sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set)); if (@bitCast(isize, rc) < 0) return rc; if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc); return 0; @@ -1097,11 +1097,11 @@ pub fn epoll_create() usize { } pub fn epoll_create1(flags: usize) usize { - return syscall1(SYS_epoll_create1, flags); + return syscall1(.epoll_create1, flags); } pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize { - return syscall4(SYS_epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev)); + return syscall4(.epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev)); } pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize { @@ -1110,7 +1110,7 @@ pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*sigset_t) usize { return syscall6( - SYS_epoll_pwait, + .epoll_pwait, @bitCast(usize, @as(isize, epoll_fd)), @ptrToInt(events), @intCast(usize, maxevents), @@ -1121,11 +1121,11 @@ pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeou } pub fn eventfd(count: u32, flags: u32) usize { - return syscall2(SYS_eventfd2, count, flags); + return syscall2(.eventfd2, count, flags); } pub fn timerfd_create(clockid: i32, flags: u32) usize { - return syscall2(SYS_timerfd_create, @bitCast(usize, @as(isize, clockid)), flags); + return syscall2(.timerfd_create, @bitCast(usize, @as(isize, clockid)), flags); } pub const itimerspec = extern struct { @@ -1134,59 +1134,59 @@ pub const itimerspec = extern struct { }; pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize { - return syscall2(SYS_timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value)); + return syscall2(.timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value)); } pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize { - return syscall4(SYS_timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value)); + return syscall4(.timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value)); } pub fn unshare(flags: usize) usize { - return syscall1(SYS_unshare, flags); + return syscall1(.unshare, flags); } pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize { - return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap)); + return syscall2(.capget, @ptrToInt(hdrp), @ptrToInt(datap)); } pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize { - return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap)); + return syscall2(.capset, @ptrToInt(hdrp), @ptrToInt(datap)); } pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize { - return syscall2(SYS_sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss)); + return syscall2(.sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss)); } pub fn uname(uts: *utsname) usize { - return syscall1(SYS_uname, @ptrToInt(uts)); + return syscall1(.uname, @ptrToInt(uts)); } pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize { - return syscall2(SYS_io_uring_setup, entries, @ptrToInt(p)); + return syscall2(.io_uring_setup, entries, @ptrToInt(p)); } pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize { - return syscall6(SYS_io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8); + return syscall6(.io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8); } pub fn io_uring_register(fd: i32, opcode: IORING_REGISTER, arg: ?*const c_void, nr_args: u32) usize { - return syscall4(SYS_io_uring_register, @bitCast(usize, @as(isize, fd)), @enumToInt(opcode), @ptrToInt(arg), nr_args); + return syscall4(.io_uring_register, @bitCast(usize, @as(isize, fd)), @enumToInt(opcode), @ptrToInt(arg), nr_args); } pub fn memfd_create(name: [*:0]const u8, flags: u32) usize { - return syscall2(SYS_memfd_create, @ptrToInt(name), flags); + return syscall2(.memfd_create, @ptrToInt(name), flags); } pub fn getrusage(who: i32, usage: *rusage) usize { - return syscall2(SYS_getrusage, @bitCast(usize, @as(isize, who)), @ptrToInt(usage)); + return syscall2(.getrusage, @bitCast(usize, @as(isize, who)), @ptrToInt(usage)); } pub fn tcgetattr(fd: fd_t, termios_p: *termios) usize { - return syscall3(SYS_ioctl, @bitCast(usize, @as(isize, fd)), TCGETS, @ptrToInt(termios_p)); + return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCGETS, @ptrToInt(termios_p)); } pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usize { - return syscall3(SYS_ioctl, @bitCast(usize, @as(isize, fd)), TCSETS + @enumToInt(optional_action), @ptrToInt(termios_p)); + return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCSETS + @enumToInt(optional_action), @ptrToInt(termios_p)); } test "" { diff --git a/lib/std/os/linux/arm-eabi.zig b/lib/std/os/linux/arm-eabi.zig index 0fbbbc4085..c052aeab4e 100644 --- a/lib/std/os/linux/arm-eabi.zig +++ b/lib/std/os/linux/arm-eabi.zig @@ -1,36 +1,36 @@ usingnamespace @import("../bits.zig"); -pub fn syscall0(number: usize) usize { +pub fn syscall0(number: SYS) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number) + : [number] "{r7}" (@enumToInt(number)) : "memory" ); } -pub fn syscall1(number: usize, arg1: usize) usize { +pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number), + : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1) : "memory" ); } -pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { +pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number), + : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2) : "memory" ); } -pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { +pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number), + : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3) @@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { ); } -pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { +pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number), + : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), @@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz ); } -pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { +pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number), + : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), @@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz } pub fn syscall6( - number: usize, + number: SYS, arg1: usize, arg2: usize, arg3: usize, @@ -74,7 +74,7 @@ pub fn syscall6( ) usize { return asm volatile ("svc #0" : [ret] "={r0}" (-> usize) - : [number] "{r7}" (number), + : [number] "{r7}" (@enumToInt(number)), [arg1] "{r0}" (arg1), [arg2] "{r1}" (arg2), [arg3] "{r2}" (arg3), @@ -91,7 +91,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a pub fn restore() callconv(.Naked) void { return asm volatile ("svc #0" : - : [number] "{r7}" (@as(usize, SYS_sigreturn)) + : [number] "{r7}" (@enumToInt(SYS.sigreturn)) : "memory" ); } @@ -99,7 +99,7 @@ pub fn restore() callconv(.Naked) void { pub fn restore_rt() callconv(.Naked) void { return asm volatile ("svc #0" : - : [number] "{r7}" (@as(usize, SYS_rt_sigreturn)) + : [number] "{r7}" (@enumToInt(SYS.rt_sigreturn)) : "memory" ); } diff --git a/lib/std/os/linux/arm64.zig b/lib/std/os/linux/arm64.zig index f565bea489..52ab3656e0 100644 --- a/lib/std/os/linux/arm64.zig +++ b/lib/std/os/linux/arm64.zig @@ -1,36 +1,36 @@ usingnamespace @import("../bits.zig"); -pub fn syscall0(number: usize) usize { +pub fn syscall0(number: SYS) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number) + : [number] "{x8}" (@enumToInt(number)) : "memory", "cc" ); } -pub fn syscall1(number: usize, arg1: usize) usize { +pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number), + : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1) : "memory", "cc" ); } -pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { +pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number), + : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2) : "memory", "cc" ); } -pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { +pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number), + : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3) @@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { ); } -pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { +pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number), + : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), @@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz ); } -pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { +pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number), + : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), @@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz } pub fn syscall6( - number: usize, + number: SYS, arg1: usize, arg2: usize, arg3: usize, @@ -74,7 +74,7 @@ pub fn syscall6( ) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize) - : [number] "{x8}" (number), + : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), @@ -93,7 +93,7 @@ pub const restore = restore_rt; pub fn restore_rt() callconv(.Naked) void { return asm volatile ("svc #0" : - : [number] "{x8}" (@as(usize, SYS_rt_sigreturn)) + : [number] "{x8}" (@enumToInt(SYS.rt_sigreturn)) : "memory", "cc" ); } diff --git a/lib/std/os/linux/i386.zig b/lib/std/os/linux/i386.zig index ecdf361b63..0342f0754e 100644 --- a/lib/std/os/linux/i386.zig +++ b/lib/std/os/linux/i386.zig @@ -1,36 +1,36 @@ usingnamespace @import("../bits.zig"); -pub fn syscall0(number: usize) usize { +pub fn syscall0(number: SYS) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number) + : [number] "{eax}" (@enumToInt(number)) : "memory" ); } -pub fn syscall1(number: usize, arg1: usize) usize { +pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), + : [number] "{eax}" (@enumToInt(number)), [arg1] "{ebx}" (arg1) : "memory" ); } -pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { +pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), + : [number] "{eax}" (@enumToInt(number)), [arg1] "{ebx}" (arg1), [arg2] "{ecx}" (arg2) : "memory" ); } -pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { +pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), + : [number] "{eax}" (@enumToInt(number)), [arg1] "{ebx}" (arg1), [arg2] "{ecx}" (arg2), [arg3] "{edx}" (arg3) @@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { ); } -pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { +pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), + : [number] "{eax}" (@enumToInt(number)), [arg1] "{ebx}" (arg1), [arg2] "{ecx}" (arg2), [arg3] "{edx}" (arg3), @@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz ); } -pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { +pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), + : [number] "{eax}" (@enumToInt(number)), [arg1] "{ebx}" (arg1), [arg2] "{ecx}" (arg2), [arg3] "{edx}" (arg3), @@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz } pub fn syscall6( - number: usize, + number: SYS, arg1: usize, arg2: usize, arg3: usize, @@ -84,7 +84,7 @@ pub fn syscall6( \\ pop %%ebp \\ add $4, %%esp : [ret] "={eax}" (-> usize) - : [number] "{eax}" (number), + : [number] "{eax}" (@enumToInt(number)), [arg1] "{ebx}" (arg1), [arg2] "{ecx}" (arg2), [arg3] "{edx}" (arg3), @@ -98,7 +98,7 @@ pub fn syscall6( pub fn socketcall(call: usize, args: [*]usize) usize { return asm volatile ("int $0x80" : [ret] "={eax}" (-> usize) - : [number] "{eax}" (@as(usize, SYS_socketcall)), + : [number] "{eax}" (@enumToInt(SYS.socketcall)), [arg1] "{ebx}" (call), [arg2] "{ecx}" (@ptrToInt(args)) : "memory" @@ -111,7 +111,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a pub fn restore() callconv(.Naked) void { return asm volatile ("int $0x80" : - : [number] "{eax}" (@as(usize, SYS_sigreturn)) + : [number] "{eax}" (@enumToInt(SYS.sigreturn)) : "memory" ); } @@ -119,7 +119,7 @@ pub fn restore() callconv(.Naked) void { pub fn restore_rt() callconv(.Naked) void { return asm volatile ("int $0x80" : - : [number] "{eax}" (@as(usize, SYS_rt_sigreturn)) + : [number] "{eax}" (@enumToInt(SYS.rt_sigreturn)) : "memory" ); } diff --git a/lib/std/os/linux/mipsel.zig b/lib/std/os/linux/mipsel.zig index 5193133f6c..87c55db9f6 100644 --- a/lib/std/os/linux/mipsel.zig +++ b/lib/std/os/linux/mipsel.zig @@ -1,13 +1,13 @@ usingnamespace @import("../bits.zig"); -pub fn syscall0(number: usize) usize { +pub fn syscall0(number: SYS) usize { return asm volatile ( \\ syscall \\ blez $7, 1f \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number) + : [number] "{$2}" (@enumToInt(number)) : "memory", "cc", "$7" ); } @@ -26,46 +26,46 @@ pub fn syscall_pipe(fd: *[2]i32) usize { \\ sw $3, 4($4) \\ 2: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (@as(usize, SYS_pipe)) + : [number] "{$2}" (@enumToInt(SYS.pipe)) : "memory", "cc", "$7" ); } -pub fn syscall1(number: usize, arg1: usize) usize { +pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ( \\ syscall \\ blez $7, 1f \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number), + : [number] "{$2}" (@enumToInt(number)), [arg1] "{$4}" (arg1) : "memory", "cc", "$7" ); } -pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { +pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ( \\ syscall \\ blez $7, 1f \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number), + : [number] "{$2}" (@enumToInt(number)), [arg1] "{$4}" (arg1), [arg2] "{$5}" (arg2) : "memory", "cc", "$7" ); } -pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { +pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ( \\ syscall \\ blez $7, 1f \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number), + : [number] "{$2}" (@enumToInt(number)), [arg1] "{$4}" (arg1), [arg2] "{$5}" (arg2), [arg3] "{$6}" (arg3) @@ -73,14 +73,14 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { ); } -pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { +pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ( \\ syscall \\ blez $7, 1f \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number), + : [number] "{$2}" (@enumToInt(number)), [arg1] "{$4}" (arg1), [arg2] "{$5}" (arg2), [arg3] "{$6}" (arg3), @@ -89,7 +89,7 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz ); } -pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { +pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ( \\ .set noat \\ subu $sp, $sp, 24 @@ -100,7 +100,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number), + : [number] "{$2}" (@enumToInt(number)), [arg1] "{$4}" (arg1), [arg2] "{$5}" (arg2), [arg3] "{$6}" (arg3), @@ -111,7 +111,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz } pub fn syscall6( - number: usize, + number: SYS, arg1: usize, arg2: usize, arg3: usize, @@ -130,7 +130,7 @@ pub fn syscall6( \\ subu $2, $0, $2 \\ 1: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (number), + : [number] "{$2}" (@enumToInt(number)), [arg1] "{$4}" (arg1), [arg2] "{$5}" (arg2), [arg3] "{$6}" (arg3), @@ -147,7 +147,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a pub fn restore() callconv(.Naked) void { return asm volatile ("syscall" : - : [number] "{$2}" (@as(usize, SYS_sigreturn)) + : [number] "{$2}" (@enumToInt(SYS.sigreturn)) : "memory", "cc", "$7" ); } @@ -155,7 +155,7 @@ pub fn restore() callconv(.Naked) void { pub fn restore_rt() callconv(.Naked) void { return asm volatile ("syscall" : - : [number] "{$2}" (@as(usize, SYS_rt_sigreturn)) + : [number] "{$2}" (@enumToInt(SYS.rt_sigreturn)) : "memory", "cc", "$7" ); } diff --git a/lib/std/os/linux/riscv64.zig b/lib/std/os/linux/riscv64.zig index 2259dad78e..3832bfbcca 100644 --- a/lib/std/os/linux/riscv64.zig +++ b/lib/std/os/linux/riscv64.zig @@ -1,36 +1,36 @@ usingnamespace @import("../bits.zig"); -pub fn syscall0(number: usize) usize { +pub fn syscall0(number: SYS) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number) + : [number] "{x17}" (@enumToInt(number)) : "memory" ); } -pub fn syscall1(number: usize, arg1: usize) usize { +pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number), + : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1) : "memory" ); } -pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { +pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number), + : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2) : "memory" ); } -pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { +pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number), + : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3) @@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { ); } -pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { +pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number), + : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), @@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz ); } -pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { +pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number), + : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), @@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz } pub fn syscall6( - number: usize, + number: SYS, arg1: usize, arg2: usize, arg3: usize, @@ -74,7 +74,7 @@ pub fn syscall6( ) usize { return asm volatile ("ecall" : [ret] "={x10}" (-> usize) - : [number] "{x17}" (number), + : [number] "{x17}" (@enumToInt(number)), [arg1] "{x10}" (arg1), [arg2] "{x11}" (arg2), [arg3] "{x12}" (arg3), @@ -92,7 +92,7 @@ pub const restore = restore_rt; pub fn restore_rt() callconv(.Naked) void { return asm volatile ("ecall" : - : [number] "{x17}" (@as(usize, SYS_rt_sigreturn)) + : [number] "{x17}" (@enumToInt(SYS.rt_sigreturn)) : "memory" ); } diff --git a/lib/std/os/linux/tls.zig b/lib/std/os/linux/tls.zig index 1c57fd06b9..e7d836eff6 100644 --- a/lib/std/os/linux/tls.zig +++ b/lib/std/os/linux/tls.zig @@ -122,7 +122,7 @@ pub fn setThreadPointer(addr: usize) void { .seg_not_present = 0, .useable = 1, }; - const rc = std.os.linux.syscall1(std.os.linux.SYS_set_thread_area, @ptrToInt(&user_desc)); + const rc = std.os.linux.syscall1(.set_thread_area, @ptrToInt(&user_desc)); assert(rc == 0); const gdt_entry_number = user_desc.entry_number; @@ -135,7 +135,7 @@ pub fn setThreadPointer(addr: usize) void { ); }, .x86_64 => { - const rc = std.os.linux.syscall2(std.os.linux.SYS_arch_prctl, std.os.linux.ARCH_SET_FS, addr); + const rc = std.os.linux.syscall2(.arch_prctl, std.os.linux.ARCH_SET_FS, addr); assert(rc == 0); }, .aarch64 => { @@ -146,7 +146,7 @@ pub fn setThreadPointer(addr: usize) void { ); }, .arm => { - const rc = std.os.linux.syscall1(std.os.linux.SYS_set_tls, addr); + const rc = std.os.linux.syscall1(.set_tls, addr); assert(rc == 0); }, .riscv64 => { @@ -157,7 +157,7 @@ pub fn setThreadPointer(addr: usize) void { ); }, .mipsel => { - const rc = std.os.linux.syscall1(std.os.linux.SYS_set_thread_area, addr); + const rc = std.os.linux.syscall1(.set_thread_area, addr); assert(rc == 0); }, else => @compileError("Unsupported architecture"), diff --git a/lib/std/os/linux/x86_64.zig b/lib/std/os/linux/x86_64.zig index d6067f9b18..b60dcd80e9 100644 --- a/lib/std/os/linux/x86_64.zig +++ b/lib/std/os/linux/x86_64.zig @@ -1,36 +1,36 @@ usingnamespace @import("../bits.zig"); -pub fn syscall0(number: usize) usize { +pub fn syscall0(number: SYS) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number) + : [number] "{rax}" (@enumToInt(number)) : "rcx", "r11", "memory" ); } -pub fn syscall1(number: usize, arg1: usize) usize { +pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number), + : [number] "{rax}" (@enumToInt(number)), [arg1] "{rdi}" (arg1) : "rcx", "r11", "memory" ); } -pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize { +pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number), + : [number] "{rax}" (@enumToInt(number)), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2) : "rcx", "r11", "memory" ); } -pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { +pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number), + : [number] "{rax}" (@enumToInt(number)), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2), [arg3] "{rdx}" (arg3) @@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { ); } -pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { +pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number), + : [number] "{rax}" (@enumToInt(number)), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2), [arg3] "{rdx}" (arg3), @@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz ); } -pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { +pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number), + : [number] "{rax}" (@enumToInt(number)), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2), [arg3] "{rdx}" (arg3), @@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz } pub fn syscall6( - number: usize, + number: SYS, arg1: usize, arg2: usize, arg3: usize, @@ -74,7 +74,7 @@ pub fn syscall6( ) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize) - : [number] "{rax}" (number), + : [number] "{rax}" (@enumToInt(number)), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2), [arg3] "{rdx}" (arg3), @@ -93,7 +93,7 @@ pub const restore = restore_rt; pub fn restore_rt() callconv(.Naked) void { return asm volatile ("syscall" : - : [number] "{rax}" (@as(usize, SYS_rt_sigreturn)) + : [number] "{rax}" (@enumToInt(SYS.rt_sigreturn)) : "rcx", "r11", "memory" ); } diff --git a/lib/std/special/compiler_rt/clear_cache.zig b/lib/std/special/compiler_rt/clear_cache.zig index 984ef7e7ac..1795a6e829 100644 --- a/lib/std/special/compiler_rt/clear_cache.zig +++ b/lib/std/special/compiler_rt/clear_cache.zig @@ -54,7 +54,7 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { // sysarch(ARM_SYNC_ICACHE, &arg); @compileError("TODO: implement for NetBSD/FreeBSD"); } else if (os == .linux) { - const result = std.os.linux.syscall3(std.os.linux.SYS_cacheflush, start, end, 0); + const result = std.os.linux.syscall3(.cacheflush, start, end, 0); std.debug.assert(result == 0); } else { @compileError("no __clear_cache implementation available for this target"); From d57b5205c61d1110745484cbade5fcac51835023 Mon Sep 17 00:00:00 2001 From: Tetralux Date: Tue, 31 Mar 2020 04:32:31 +0000 Subject: [PATCH 40/89] Fix std.fifo.LinearFifo - Fix undeclared variable in 'writeItem' - Clarify docs of `read` regarding bytes vs. items - Normalize 'writeable' to 'writable' (the more common parlance) --- lib/std/fifo.zig | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index 94570e93ef..6866cc3d7a 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -160,7 +160,7 @@ pub fn LinearFifo( return self.readableSliceMut(offset); } - /// Discard first `count` bytes of readable data + /// Discard first `count` items in the fifo pub fn discard(self: *Self, count: usize) void { assert(count <= self.count); { // set old range to undefined. Note: may be wrapped around @@ -199,7 +199,7 @@ pub fn LinearFifo( return c; } - /// Read data from the fifo into `dst`, returns number of bytes copied. + /// Read data from the fifo into `dst`, returns number of items copied. pub fn read(self: *Self, dst: []T) usize { var dst_left = dst; @@ -215,7 +215,7 @@ pub fn LinearFifo( return dst.len - dst_left.len; } - /// Returns number of bytes available in fifo + /// Returns number of items available in fifo pub fn writableLength(self: Self) usize { return self.buf.len - self.count; } @@ -233,9 +233,9 @@ pub fn LinearFifo( } } - /// Returns a writable buffer of at least `size` bytes, allocating memory as needed. + /// Returns a writable buffer of at least `size` items, allocating memory as needed. /// Use `fifo.update` once you've written data to it. - pub fn writeableWithSize(self: *Self, size: usize) ![]T { + pub fn writableWithSize(self: *Self, size: usize) ![]T { try self.ensureUnusedCapacity(size); // try to avoid realigning buffer @@ -247,7 +247,7 @@ pub fn LinearFifo( return slice; } - /// Update the tail location of the buffer (usually follows use of writable/writeableWithSize) + /// Update the tail location of the buffer (usually follows use of writable/writableWithSize) pub fn update(self: *Self, count: usize) void { assert(self.count + count <= self.buf.len); self.count += count; @@ -279,7 +279,7 @@ pub fn LinearFifo( } else { tail %= self.buf.len; } - self.buf[tail] = byte; + self.buf[tail] = item; self.update(1); } @@ -395,7 +395,7 @@ test "LinearFifo(u8, .Dynamic)" { } { - const buf = try fifo.writeableWithSize(12); + const buf = try fifo.writableWithSize(12); testing.expectEqual(@as(usize, 12), buf.len); var i: u8 = 0; while (i < 10) : (i += 1) { @@ -445,6 +445,20 @@ test "LinearFifo" { testing.expectEqual(@as(T, 1), try fifo.readItem()); testing.expectEqual(@as(T, 0), try fifo.readItem()); testing.expectEqual(@as(T, 1), try fifo.readItem()); + testing.expectEqual(@as(usize, 0), fifo.readableLength()); + } + + { + try fifo.writeItem(1); + try fifo.writeItem(1); + try fifo.writeItem(1); + testing.expectEqual(@as(usize, 3), fifo.readableLength()); + } + + { + var readBuf: [3]T = undefined; + const n = fifo.read(&readBuf); + testing.expectEqual(@as(usize, 3), n); // NOTE: It should be the number of items. } } } From e9c49f423d981dc5f4826f284226f312d51b33cc Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Tue, 31 Mar 2020 12:40:28 +0200 Subject: [PATCH 41/89] compiler-rt: More clear_cache implementations --- lib/std/special/compiler_rt.zig | 2 + lib/std/special/compiler_rt/clear_cache.zig | 48 +++++++++++++-------- 2 files changed, 33 insertions(+), 17 deletions(-) diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index 6cdc127137..cf860dfcb0 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -20,6 +20,8 @@ comptime { .aarch64, .aarch64_be, .aarch64_32, + .riscv32, + .riscv64, => @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ .name = "__clear_cache", .linkage = linkage, diff --git a/lib/std/special/compiler_rt/clear_cache.zig b/lib/std/special/compiler_rt/clear_cache.zig index 1795a6e829..1286a5e009 100644 --- a/lib/std/special/compiler_rt/clear_cache.zig +++ b/lib/std/special/compiler_rt/clear_cache.zig @@ -26,6 +26,10 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { .mips, .mipsel, .mips64, .mips64el => true, else => false, }; + const riscv = switch (arch) { + .riscv32, .riscv64 => true, + else => false, + }; const powerpc64 = switch (arch) { .powerpc64, .powerpc64le => true, else => false, @@ -45,28 +49,31 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { @compileError("TODO"); // FlushInstructionCache(GetCurrentProcess(), start, end - start); } else if (arm32 and !apple) { - if (os == .freebsd or os == .netbsd) { - // struct arm_sync_icache_args arg; - // - // arg.addr = (uintptr_t)start; - // arg.len = (uintptr_t)end - (uintptr_t)start; - // - // sysarch(ARM_SYNC_ICACHE, &arg); - @compileError("TODO: implement for NetBSD/FreeBSD"); - } else if (os == .linux) { - const result = std.os.linux.syscall3(.cacheflush, start, end, 0); - std.debug.assert(result == 0); - } else { - @compileError("no __clear_cache implementation available for this target"); + switch (os) { + .freebsd, .netbsd => { + var arg = arm_sync_icache_args{ + .addr = start, + .len = end - start, + }; + const result = sysarch(ARM_SYNC_ICACHE, @ptrToInt(&arg)); + std.debug.assert(result == 0); + }, + .linux => { + const result = std.os.linux.syscall3(.cacheflush, start, end, 0); + std.debug.assert(result == 0); + }, + else => @compileError("TODO"), } } else if (os == .linux and mips) { - @compileError("TODO"); - //const uintptr_t start_int = (uintptr_t)start; - //const uintptr_t end_int = (uintptr_t)end; - //syscall(__NR_cacheflush, start, (end_int - start_int), BCACHE); + const flags = 3; // ICACHE | DCACHE + const result = std.os.linux.syscall3(std.os.linux.SYS_cacheflush, start, end - start, flags); + std.debug.assert(result == 0); } else if (mips and os == .openbsd) { @compileError("TODO"); //cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE); + } else if (os == .linux and riscv) { + const result = std.os.linux.syscall3(std.os.linux.SYS_riscv_flush_icache, start, end - start, 0); + std.debug.assert(result == 0); } else if (arm64 and !apple) { // Get Cache Type Info. // TODO memoize this? @@ -142,3 +149,10 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { // Darwin-only extern fn sys_icache_invalidate(start: usize, len: usize) void; +// BSD-only +const arm_sync_icache_args = extern struct { + addr: usize, // Virtual start address + len: usize, // Region size +}; +const ARM_SYNC_ICACHE = 0; +extern "c" fn sysarch(number: i32, args: usize) i32; From b1eb831aba6eec78f367053200007c867817e811 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Wed, 1 Apr 2020 01:44:14 +1100 Subject: [PATCH 42/89] std: fix mem.span* when an optional pointer is passed --- lib/std/mem.zig | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/std/mem.zig b/lib/std/mem.zig index d4d0a83f46..f54eb03d65 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -559,10 +559,14 @@ test "Span" { /// When there is both a sentinel and an array length or slice length, the /// length value is used instead of the sentinel. pub fn span(ptr: var) Span(@TypeOf(ptr)) { - const Result = Span(@TypeOf(ptr)); - if (@typeInfo(@TypeOf(ptr)) == .Optional and ptr == null) { - return null; + if (@typeInfo(@TypeOf(ptr)) == .Optional) { + if (ptr) |non_null| { + return span(non_null); + } else { + return null; + } } + const Result = Span(@TypeOf(ptr)); const l = len(ptr); if (@typeInfo(Result).Pointer.sentinel) |s| { return ptr[0..l :s]; @@ -576,16 +580,21 @@ test "span" { const ptr = @as([*:3]u16, array[0..2 :3]); testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 })); testing.expect(eql(u16, span(&array), &[_]u16{ 1, 2, 3, 4, 5 })); + testing.expectEqual(@as(?[:0]u16, null), span(@as(?[*:0]u16, null))); } /// Same as `span`, except when there is both a sentinel and an array /// length or slice length, scans the memory for the sentinel value /// rather than using the length. pub fn spanZ(ptr: var) Span(@TypeOf(ptr)) { - const Result = Span(@TypeOf(ptr)); - if (@typeInfo(@TypeOf(ptr)) == .Optional and ptr == null) { - return null; + if (@typeInfo(@TypeOf(ptr)) == .Optional) { + if (ptr) |non_null| { + return spanZ(non_null); + } else { + return null; + } } + const Result = Span(@TypeOf(ptr)); const l = lenZ(ptr); if (@typeInfo(Result).Pointer.sentinel) |s| { return ptr[0..l :s]; @@ -599,6 +608,7 @@ test "spanZ" { const ptr = @as([*:3]u16, array[0..2 :3]); testing.expect(eql(u16, spanZ(ptr), &[_]u16{ 1, 2 })); testing.expect(eql(u16, spanZ(&array), &[_]u16{ 1, 2, 3, 4, 5 })); + testing.expectEqual(@as(?[:0]u16, null), spanZ(@as(?[*:0]u16, null))); } /// Takes a pointer to an array, an array, a sentinel-terminated pointer, From 0e372ccff511a9e286949328037d87af64e31875 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 31 Mar 2020 10:48:48 -0400 Subject: [PATCH 43/89] clean up the duplicate export logic for __clear_cache --- lib/std/special/compiler_rt.zig | 21 ++----------- lib/std/special/compiler_rt/clear_cache.zig | 33 +++++++++++++++------ 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index cf860dfcb0..2a454b19dc 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -17,27 +17,12 @@ comptime { .linkage = linkage, }), - .aarch64, - .aarch64_be, - .aarch64_32, - .riscv32, - .riscv64, - => @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ - .name = "__clear_cache", - .linkage = linkage, - }), - - .arm, .armeb, .thumb, .thumbeb => switch (builtin.os.tag) { - .linux => @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ - .name = "__clear_cache", - .linkage = linkage, - }), - else => {}, - }, - else => {}, } + // __clear_cache manages its own logic about whether to be exported or not. + _ = @import("compiler_rt/clear_cache.zig").clear_cache; + @export(@import("compiler_rt/compareXf2.zig").__lesf2, .{ .name = "__lesf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__ledf2, .{ .name = "__ledf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__letf2", .linkage = linkage }); diff --git a/lib/std/special/compiler_rt/clear_cache.zig b/lib/std/special/compiler_rt/clear_cache.zig index 1286a5e009..8ea688e98a 100644 --- a/lib/std/special/compiler_rt/clear_cache.zig +++ b/lib/std/special/compiler_rt/clear_cache.zig @@ -45,9 +45,11 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { if (x86) { // Intel processors have a unified instruction and data cache // so there is nothing to do + exportIt(); } else if (os == .windows and (arm32 or arm64)) { - @compileError("TODO"); + // TODO // FlushInstructionCache(GetCurrentProcess(), start, end - start); + // exportIt(); } else if (arm32 and !apple) { switch (os) { .freebsd, .netbsd => { @@ -57,23 +59,28 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { }; const result = sysarch(ARM_SYNC_ICACHE, @ptrToInt(&arg)); std.debug.assert(result == 0); + exportIt(); }, .linux => { const result = std.os.linux.syscall3(.cacheflush, start, end, 0); std.debug.assert(result == 0); + exportIt(); }, - else => @compileError("TODO"), + else => {}, } } else if (os == .linux and mips) { const flags = 3; // ICACHE | DCACHE - const result = std.os.linux.syscall3(std.os.linux.SYS_cacheflush, start, end - start, flags); + const result = std.os.linux.syscall3(.cacheflush, start, end - start, flags); std.debug.assert(result == 0); + exportIt(); } else if (mips and os == .openbsd) { - @compileError("TODO"); + // TODO //cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE); + // exportIt(); } else if (os == .linux and riscv) { - const result = std.os.linux.syscall3(std.os.linux.SYS_riscv_flush_icache, start, end - start, 0); + const result = std.os.linux.syscall3(.riscv_flush_icache, start, end - start, 0); std.debug.assert(result == 0); + exportIt(); } else if (arm64 and !apple) { // Get Cache Type Info. // TODO memoize this? @@ -112,8 +119,9 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { } } asm volatile ("isb sy"); + exportIt(); } else if (powerpc64) { - @compileError("TODO"); + // TODO //const size_t line_size = 32; //const size_t len = (uintptr_t)end - (uintptr_t)start; // @@ -128,8 +136,9 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { //for (uintptr_t line = start_line; line < end_line; line += line_size) // __asm__ volatile("icbi 0, %0" : : "r"(line)); //__asm__ volatile("isync"); + // exportIt(); } else if (sparc) { - @compileError("TODO"); + // TODO //const size_t dword_size = 8; //const size_t len = (uintptr_t)end - (uintptr_t)start; // @@ -139,14 +148,20 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { // //for (uintptr_t dword = start_dword; dword < end_dword; dword += dword_size) // __asm__ volatile("flush %0" : : "r"(dword)); + // exportIt(); } else if (apple) { // On Darwin, sys_icache_invalidate() provides this functionality sys_icache_invalidate(start, end - start); - } else { - @compileError("no __clear_cache implementation available for this target"); + exportIt(); } } +const linkage = if (std.builtin.is_test) std.builtin.GlobalLinkage.Internal else std.builtin.GlobalLinkage.Weak; + +inline fn exportIt() void { + @export(clear_cache, .{ .name = "__clear_cache", .linkage = linkage }); +} + // Darwin-only extern fn sys_icache_invalidate(start: usize, len: usize) void; // BSD-only From 3cf302a71d50114c44cedbe0114e513063b93302 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Wed, 1 Apr 2020 01:25:25 +1100 Subject: [PATCH 44/89] Tidy up some mem.spanZ use-sites now that null is accepted --- lib/std/debug.zig | 2 +- lib/std/os.zig | 2 +- src-self-hosted/stage2.zig | 7 +++---- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 35c13809f7..11d808a17d 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -1254,7 +1254,7 @@ pub const DebugInfo = struct { if (context.address >= seg_start and context.address < seg_end) { // Android libc uses NULL instead of an empty string to mark the // main program - context.name = if (info.dlpi_name) |dlpi_name| mem.spanZ(dlpi_name) else ""; + context.name = mem.spanZ(info.dlpi_name) orelse ""; context.base_address = info.dlpi_addr; // Stop the iteration return error.Found; diff --git a/lib/std/os.zig b/lib/std/os.zig index e9e3b449f2..48d82797bd 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -1078,7 +1078,7 @@ pub fn execvpe_expandArg0( mem.set(?[*:0]u8, argv_buf, null); defer { for (argv_buf) |arg| { - const arg_buf = if (arg) |ptr| mem.spanZ(ptr) else break; + const arg_buf = mem.spanZ(arg) orelse break; allocator.free(arg_buf); } allocator.free(argv_buf); diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index fcf9634097..d9b763912c 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -689,12 +689,11 @@ fn stage2CrossTarget( mcpu_oz: ?[*:0]const u8, dynamic_linker_oz: ?[*:0]const u8, ) !CrossTarget { - const zig_triple = if (zig_triple_oz) |zig_triple_z| mem.spanZ(zig_triple_z) else "native"; - const mcpu = if (mcpu_oz) |mcpu_z| mem.spanZ(mcpu_z) else null; - const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.spanZ(dl_z) else null; + const mcpu = mem.spanZ(mcpu_oz); + const dynamic_linker = mem.spanZ(dynamic_linker_oz); var diags: CrossTarget.ParseOptions.Diagnostics = .{}; const target: CrossTarget = CrossTarget.parse(.{ - .arch_os_abi = zig_triple, + .arch_os_abi = mem.spanZ(zig_triple_oz) orelse "native", .cpu_features = mcpu, .dynamic_linker = dynamic_linker, .diagnostics = &diags, From d9d8c4242649b8e93dca675a0151d6f39c1d4817 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 31 Mar 2020 11:17:40 -0400 Subject: [PATCH 45/89] remove unnecessary `inline` works around a bug triggered by previous commit --- lib/std/special/compiler_rt/clear_cache.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/std/special/compiler_rt/clear_cache.zig b/lib/std/special/compiler_rt/clear_cache.zig index 8ea688e98a..6306d5b575 100644 --- a/lib/std/special/compiler_rt/clear_cache.zig +++ b/lib/std/special/compiler_rt/clear_cache.zig @@ -158,7 +158,7 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void { const linkage = if (std.builtin.is_test) std.builtin.GlobalLinkage.Internal else std.builtin.GlobalLinkage.Weak; -inline fn exportIt() void { +fn exportIt() void { @export(clear_cache, .{ .name = "__clear_cache", .linkage = linkage }); } From 9bb76f8ce0b36211e0ff1f502ec46aa5a0142cd0 Mon Sep 17 00:00:00 2001 From: Bodie Solomon Date: Tue, 31 Mar 2020 10:13:31 -0400 Subject: [PATCH 46/89] Use correct compiler flags in MSVC bootstrap builds of Zig https://github.com/ziglang/zig/issues/4877 The CMake build of Zig from C++ uses hand-set compiler flags which are not compatible with the Microsoft C/C++ Optimizing Compiler (cl.exe) used by Visual Studio. This commit attempts to conform them to match the Clang/GCC options under MSVC builds. Note that CL does not have a concept of C99 or "-O3", and may imply other optimizations in "/O2" than are implied by Clang/GCC "-O3". Visual Studio 2019 documentation for cl.exe's optimization options: https://docs.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code?view=vs-2019 Visual Studio 2019 doc for cl.exe's C++ standard options: https://docs.microsoft.com/en-us/cpp/build/reference/std-specify-language-standard-version?view=vs-2019 --- CMakeLists.txt | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9e54f8cf6c..a4864bf0ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -224,7 +224,7 @@ set(EMBEDDED_SOFTFLOAT_SOURCES add_library(embedded_softfloat STATIC ${EMBEDDED_SOFTFLOAT_SOURCES}) if(MSVC) set_target_properties(embedded_softfloat PROPERTIES - COMPILE_FLAGS "-std=c99 /w" + COMPILE_FLAGS "/w /O2" ) else() set_target_properties(embedded_softfloat PROPERTIES @@ -315,7 +315,12 @@ include_directories( ) # These have to go before the -Wno- flags -set(EXE_CFLAGS "-std=c++14") +if(MSVC) + set(EXE_CFLAGS "/std:c++14") +else(MSVC) + set(EXE_CFLAGS "-std=c++14") +endif(MSVC) + if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") if(MSVC) set(EXE_CFLAGS "${EXE_CFLAGS} /w") @@ -333,7 +338,11 @@ else() endif() endif() -set(OPTIMIZED_C_FLAGS "-std=c99 -O3") +if(MSVC) + set(OPTIMIZED_C_FLAGS "/O2") +else(MSVC) + set(OPTIMIZED_C_FLAGS "-std=c99 -O3") +endif(MSVC) set(EXE_LDFLAGS " ") if(MSVC) From c7a37967340da7e21281fca09e82f8fffb3f15d8 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 31 Mar 2020 14:54:13 -0400 Subject: [PATCH 47/89] ci: export master branch version for update-download-page --- ci/srht/update_download_page | 1 + 1 file changed, 1 insertion(+) diff --git a/ci/srht/update_download_page b/ci/srht/update_download_page index 1a721bec80..77436a3772 100755 --- a/ci/srht/update_download_page +++ b/ci/srht/update_download_page @@ -71,6 +71,7 @@ export X86_64_FREEBSD_SHASUM="$(echo "$X86_64_FREEBSD_JSON" | jq .shasum -r)" git clone https://github.com/ziglang/www.ziglang.org --depth 1 cd www.ziglang.org export MASTER_DATE="$(date +%Y-%m-%d)" +export MASTER_VERSION="$VERSION" "../$ZIG" run update-download-page.zig $S3CMD put -P --no-mime-magic --add-header="cache-control: public, max-age=31536000, immutable" "../$SRC_TARBALL" s3://ziglang.org/builds/ From 9e019ed26bf2ab46040099dadaf778dec436bc4a Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Tue, 31 Mar 2020 20:15:09 +0200 Subject: [PATCH 48/89] Fix possible unaligned ptr from `getauxval` This caused SIGILL on armv7a-linux --- src/os.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/os.cpp b/src/os.cpp index a1deb0f611..505063f827 100644 --- a/src/os.cpp +++ b/src/os.cpp @@ -1456,7 +1456,10 @@ static void init_rand() { memcpy(&seed, bytes, sizeof(unsigned)); srand(seed); #elif defined(ZIG_OS_LINUX) - srand(*((unsigned*)getauxval(AT_RANDOM))); + unsigned char *ptr_random = (unsigned char*)getauxval(AT_RANDOM); + unsigned seed; + memcpy(&seed, ptr_random, sizeof(seed)); + srand(seed); #else int fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC); if (fd == -1) { From e3d12471a2554154b507ed675e35530b55259984 Mon Sep 17 00:00:00 2001 From: Michael Dusan Date: Tue, 31 Mar 2020 17:10:01 -0400 Subject: [PATCH 49/89] add compile-error test for #2687 Issue fixed by an unknown commit. closes #2687 --- test/compile_errors.zig | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 6d3506d3a3..361ff8d9a2 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -6806,4 +6806,27 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { , &[_][]const u8{ "tmp.zig:2:27: error: type 'u32' does not support array initialization", }); + + cases.add("issue #2687: coerce from undefined array pointer to slice", + \\export fn foo1() void { + \\ const a: *[1]u8 = undefined; + \\ var b: []u8 = a; + \\} + \\export fn foo2() void { + \\ comptime { + \\ var a: *[1]u8 = undefined; + \\ var b: []u8 = a; + \\ } + \\} + \\export fn foo3() void { + \\ comptime { + \\ const a: *[1]u8 = undefined; + \\ var b: []u8 = a; + \\ } + \\} + , &[_][]const u8{ + "tmp.zig:3:19: error: use of undefined value here causes undefined behavior", + "tmp.zig:8:23: error: use of undefined value here causes undefined behavior", + "tmp.zig:14:23: error: use of undefined value here causes undefined behavior", + }); } From a5af78c376fc41424b81ea83766b38a0a1d17870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Larouche?= Date: Tue, 31 Mar 2020 16:52:16 -0400 Subject: [PATCH 50/89] Fix porting of zlib alder32 with large input --- lib/std/hash/adler.zig | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/lib/std/hash/adler.zig b/lib/std/hash/adler.zig index 3cc3171e49..173a07596c 100644 --- a/lib/std/hash/adler.zig +++ b/lib/std/hash/adler.zig @@ -42,18 +42,23 @@ pub const Adler32 = struct { s2 %= base; } else { - var i: usize = 0; - while (i + nmax <= input.len) : (i += nmax) { - const n = nmax / 16; // note: 16 | nmax + const n = nmax / 16; // note: 16 | nmax + var i: usize = 0; + + while (i + nmax <= input.len) { var rounds: usize = 0; while (rounds < n) : (rounds += 1) { comptime var j: usize = 0; inline while (j < 16) : (j += 1) { - s1 +%= input[i + n * j]; + s1 +%= input[i + j]; s2 +%= s1; } + i += 16; } + + s1 %= base; + s2 %= base; } if (i < input.len) { @@ -89,19 +94,35 @@ pub const Adler32 = struct { }; test "adler32 sanity" { - testing.expect(Adler32.hash("a") == 0x620062); - testing.expect(Adler32.hash("example") == 0xbc002ed); + testing.expectEqual(@as(u32, 0x620062), Adler32.hash("a")); + testing.expectEqual(@as(u32, 0xbc002ed), Adler32.hash("example")); } test "adler32 long" { const long1 = [_]u8{1} ** 1024; - testing.expect(Adler32.hash(long1[0..]) == 0x06780401); + testing.expectEqual(@as(u32, 0x06780401), Adler32.hash(long1[0..])); const long2 = [_]u8{1} ** 1025; - testing.expect(Adler32.hash(long2[0..]) == 0x0a7a0402); + testing.expectEqual(@as(u32, 0x0a7a0402), Adler32.hash(long2[0..])); } test "adler32 very long" { const long = [_]u8{1} ** 5553; - testing.expect(Adler32.hash(long[0..]) == 0x707f15b2); + testing.expectEqual(@as(u32, 0x707f15b2), Adler32.hash(long[0..])); +} + +test "adler32 very long with variation" { + const long = comptime blk: { + @setEvalBranchQuota(7000); + var result: [6000]u8 = undefined; + + var i: usize = 0; + while (i < result.len) : (i += 1) { + result[i] = @truncate(u8, i); + } + + break :blk result; + }; + + testing.expectEqual(@as(u32, 0x5af38d6e), std.hash.Adler32.hash(long[0..])); } From 070ace4b22810116f7816eeccbc1ce600be5b2a2 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Wed, 1 Apr 2020 11:03:36 +0200 Subject: [PATCH 51/89] std: Fix more NetBSD bits Fix some more libc definitions. --- lib/std/c/netbsd.zig | 44 +++++++++--- lib/std/debug.zig | 14 +++- lib/std/os/bits/linux.zig | 4 +- lib/std/os/bits/netbsd.zig | 142 ++++++++++++++++++++++++++++++------- 4 files changed, 161 insertions(+), 43 deletions(-) diff --git a/lib/std/c/netbsd.zig b/lib/std/c/netbsd.zig index fd70220603..a286c181a6 100644 --- a/lib/std/c/netbsd.zig +++ b/lib/std/c/netbsd.zig @@ -10,36 +10,58 @@ pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int; pub extern "c" fn __fstat50(fd: fd_t, buf: *Stat) c_int; +pub extern "c" fn __stat50(path: [*:0]const u8, buf: *Stat) c_int; pub extern "c" fn __clock_gettime50(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn __clock_getres50(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn __getdents30(fd: c_int, buf_ptr: [*]u8, nbytes: usize) c_int; pub extern "c" fn __sigaltstack14(ss: ?*stack_t, old_ss: ?*stack_t) c_int; +pub extern "c" fn __nanosleep50(rqtp: *const timespec, rmtp: ?*timespec) c_int; +pub extern "c" fn __sigaction14(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; +pub extern "c" fn __sigprocmask14(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; +pub extern "c" fn __socket30(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; +pub extern "c" fn __gettimeofday50(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; +pub extern "c" fn __getrusage50(who: c_int, usage: *rusage) c_int; +// instead of sched_yield +pub extern "c" fn __libc_thr_yield() c_int; pub const pthread_mutex_t = extern struct { - ptm_magic: c_uint = 0x33330003, - ptm_errorcheck: padded_spin_t = 0, - ptm_unused: padded_spin_t = 0, + ptm_magic: u32 = 0x33330003, + ptm_errorcheck: padded_pthread_spin_t = 0, + ptm_ceiling: padded_pthread_spin_t = 0, ptm_owner: usize = 0, ptm_waiters: ?*u8 = null, - ptm_recursed: c_uint = 0, + ptm_recursed: u32 = 0, ptm_spare2: ?*c_void = null, }; + pub const pthread_cond_t = extern struct { - ptc_magic: c_uint = 0x55550005, + ptc_magic: u32 = 0x55550005, ptc_lock: pthread_spin_t = 0, ptc_waiters_first: ?*u8 = null, ptc_waiters_last: ?*u8 = null, ptc_mutex: ?*pthread_mutex_t = null, ptc_private: ?*c_void = null, }; -const pthread_spin_t = if (builtin.arch == .arm or .arch == .powerpc) c_int else u8; -const padded_spin_t = switch (builtin.arch) { - .sparc, .sparcel, .sparcv9, .i386, .x86_64, .le64 => u32, - else => spin_t, + +const pthread_spin_t = switch (builtin.arch) { + .aarch64, .aarch64_be, .aarch64_32 => u8, + .mips, .mipsel, .mips64, .mips64el => u32, + .powerpc, .powerpc64, .powerpc64le => i32, + .i386, .x86_64 => u8, + .arm, .armeb, .thumb, .thumbeb => i32, + .sparc, .sparcel, .sparcv9 => u8, + .riscv32, .riscv64 => u32, + else => @compileError("undefined pthread_spin_t for this arch"), +}; + +const padded_pthread_spin_t = switch (builtin.arch) { + .i386, .x86_64 => u32, + .sparc, .sparcel, .sparcv9 => u32, + else => pthread_spin_t, }; pub const pthread_attr_t = extern struct { pta_magic: u32, - pta_flags: c_int, - pta_private: *c_void, + pta_flags: i32, + pta_private: ?*c_void, }; diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 11d808a17d..9e14d132a8 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -1666,7 +1666,11 @@ fn getDebugInfoAllocator() *mem.Allocator { } /// Whether or not the current target can print useful debug information when a segfault occurs. -pub const have_segfault_handling_support = builtin.os.tag == .linux or builtin.os.tag == .windows; +pub const have_segfault_handling_support = switch (builtin.os.tag) { + .linux, .netbsd => true, + .windows => true, + else => false, +}; pub const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler")) root.enable_segfault_handler else @@ -1718,13 +1722,17 @@ fn resetSegfaultHandler() void { os.sigaction(os.SIGBUS, &act, null); } -fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *const c_void) callconv(.C) noreturn { +fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) noreturn { // Reset to the default handler so that if a segfault happens in this handler it will crash // the process. Also when this handler returns, the original instruction will be repeated // and the resulting segfault will crash the process rather than continually dump stack traces. resetSegfaultHandler(); - const addr = @ptrToInt(info.fields.sigfault.addr); + const addr = switch (builtin.os.tag) { + .linux => @ptrToInt(info.fields.sigfault.addr), + .netbsd => @ptrToInt(info.info.reason.fault.addr), + else => unreachable, + }; switch (sig) { os.SIGSEGV => std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr}), os.SIGILL => std.debug.warn("Illegal instruction at address 0x{x}\n", .{addr}), diff --git a/lib/std/os/bits/linux.zig b/lib/std/os/bits/linux.zig index 3a2040b440..2d5f07209a 100644 --- a/lib/std/os/bits/linux.zig +++ b/lib/std/os/bits/linux.zig @@ -813,13 +813,13 @@ pub const app_mask: sigset_t = [2]u32{ 0xfffffffc, 0x7fffffff } ++ [_]u32{0xffff pub const k_sigaction = if (is_mips) extern struct { flags: usize, - sigaction: ?extern fn (i32, *siginfo_t, *c_void) void, + sigaction: ?extern fn (i32, *siginfo_t, ?*c_void) void, mask: [4]u32, restorer: extern fn () void, } else extern struct { - sigaction: ?extern fn (i32, *siginfo_t, *c_void) void, + sigaction: ?extern fn (i32, *siginfo_t, ?*c_void) void, flags: usize, restorer: extern fn () void, mask: [2]u32, diff --git a/lib/std/os/bits/netbsd.zig b/lib/std/os/bits/netbsd.zig index a26fdee2a9..21f75a0414 100644 --- a/lib/std/os/bits/netbsd.zig +++ b/lib/std/os/bits/netbsd.zig @@ -1,12 +1,22 @@ const std = @import("../../std.zig"); +const builtin = std.builtin; const maxInt = std.math.maxInt; +pub const blkcnt_t = i64; +pub const blksize_t = i32; +pub const clock_t = u32; +pub const dev_t = u64; pub const fd_t = i32; -pub const pid_t = i32; -pub const mode_t = u32; +pub const gid_t = u32; pub const ino_t = u64; +pub const mode_t = u32; +pub const nlink_t = u32; pub const off_t = i64; +pub const pid_t = i32; pub const socklen_t = u32; +pub const time_t = i64; +pub const uid_t = u32; +pub const lwpid_t = i32; /// Renamed from `kevent` to `Kevent` to avoid conflict with function name. pub const Kevent = extern struct { @@ -137,23 +147,20 @@ pub const msghdr_const = extern struct { /// in C, macros are used to hide the differences. Here we use /// methods to accomplish this. pub const Stat = extern struct { - dev: u64, - mode: u32, + dev: dev_t, + mode: mode_t, ino: ino_t, - nlink: usize, - - uid: u32, - gid: u32, - rdev: u64, - + nlink: nlink_t, + uid: uid_t, + gid: gid_t, + rdev: dev_t, atim: timespec, mtim: timespec, ctim: timespec, birthtim: timespec, - size: off_t, - blocks: i64, - blksize: isize, + blocks: blkcnt_t, + blksize: blksize_t, flags: u32, gen: u32, __spare: [2]u32, @@ -176,12 +183,14 @@ pub const timespec = extern struct { tv_nsec: isize, }; +pub const MAXNAMLEN = 511; + pub const dirent = extern struct { - d_fileno: u64, + d_fileno: ino_t, d_reclen: u16, d_namlen: u16, d_type: u8, - d_name: [512]u8, + d_name: [MAXNAMLEN:0]u8, pub fn reclen(self: dirent) u16 { return self.d_reclen; @@ -685,23 +694,74 @@ pub const winsize = extern struct { const NSIG = 32; -pub const SIG_ERR = @intToPtr(extern fn (i32) void, maxInt(usize)); -pub const SIG_DFL = @intToPtr(extern fn (i32) void, 0); -pub const SIG_IGN = @intToPtr(extern fn (i32) void, 1); +pub const SIG_ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize)); +pub const SIG_DFL = @intToPtr(?Sigaction.sigaction_fn, 0); +pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1); /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = extern struct { + pub const sigaction_fn = fn (i32, *siginfo_t, ?*c_void) callconv(.C) void; /// signal handler - __sigaction_u: extern union { - __sa_handler: extern fn (i32) void, - __sa_sigaction: extern fn (i32, *__siginfo, usize) void, - }, - - /// see signal options - sa_flags: u32, - + sigaction: ?sigaction_fn, /// signal mask to apply - sa_mask: sigset_t, + mask: sigset_t, + /// signal options + flags: u32, +}; + +pub const sigval_t = extern union { + int: i32, + ptr: ?*c_void, +}; + +pub const siginfo_t = extern union { + pad: [128]u8, + info: _ksiginfo, +}; + +pub const _ksiginfo = extern struct { + signo: i32, + code: i32, + errno: i32, + // 64bit architectures insert 4bytes of padding here, this is done by + // correctly aligning the reason field + reason: extern union { + rt: extern struct { + pid: pid_t, + uid: uid_t, + value: sigval_t, + }, + child: extern struct { + pid: pid_t, + uid: uid_t, + status: i32, + utime: clock_t, + stime: clock_t, + }, + fault: extern struct { + addr: ?*c_void, + trap: i32, + trap2: i32, + trap3: i32, + }, + poll: extern struct { + band: i32, + fd: i32, + }, + syscall: extern struct { + sysnum: i32, + retval: [2]i32, + @"error": i32, + args: [8]u64, + }, + ptrace_state: extern struct { + pe_report_event: i32, + option: extern union { + pe_other_pid: pid_t, + pe_lwp: lwpid_t, + }, + }, + } align(@sizeOf(usize)), }; pub const _SIG_WORDS = 4; @@ -724,6 +784,34 @@ pub const sigset_t = extern struct { __bits: [_SIG_WORDS]u32, }; +pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** _SIG_WORDS }; + +// XXX x86_64 specific +pub const mcontext_t = extern struct { + gregs: [26]u64, + mc_tlsbase: u64, + fpregs: [512]u8 align(8), +}; + +pub const REG_RBP = 12; +pub const REG_RIP = 21; +pub const REG_RSP = 24; + +pub const ucontext_t = extern struct { + flags: u32, + link: ?*ucontext_t, + sigmask: sigset_t, + stack: stack_t, + mcontext: mcontext_t, + __pad: [switch (builtin.arch) { + .i386 => 4, + .mips, .mipsel, .mips64, .mips64el => 14, + .arm, .armeb, .thumb, .thumbeb => 1, + .sparc, .sparcel, .sparcv9 => if (@sizeOf(usize) == 4) 43 else 8, + else => 0, + }]u32, +}; + pub const EPERM = 1; // Operation not permitted pub const ENOENT = 2; // No such file or directory pub const ESRCH = 3; // No such process From 4209ab90a8a9922bcc407e12b0e58b827a179a91 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Wed, 1 Apr 2020 10:00:37 +0000 Subject: [PATCH 52/89] std: Use the versioned libc symbols if needed Many symbols on NetBSD and some on OSX require the definition of an alias. --- lib/std/c.zig | 57 ++++++++++++++++++++++++++++++++++---------- lib/std/c/netbsd.zig | 2 +- lib/std/os.zig | 30 ++++------------------- 3 files changed, 50 insertions(+), 39 deletions(-) diff --git a/lib/std/c.zig b/lib/std/c.zig index 303fa58fae..1261974d65 100644 --- a/lib/std/c.zig +++ b/lib/std/c.zig @@ -73,7 +73,6 @@ pub extern "c" fn abort() noreturn; pub extern "c" fn exit(code: c_int) noreturn; pub extern "c" fn isatty(fd: fd_t) c_int; pub extern "c" fn close(fd: fd_t) c_int; -pub extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int; pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int; pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t; pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int; @@ -86,7 +85,6 @@ pub extern "c" fn pread(fd: fd_t, buf: [*]u8, nbyte: usize, offset: u64) isize; pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: u64) isize; pub extern "c" fn writev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint) isize; pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: u64) isize; -pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int; pub extern "c" fn write(fd: fd_t, buf: [*]const u8, nbyte: usize) isize; pub extern "c" fn pwrite(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: u64) isize; pub extern "c" fn mmap(addr: ?*align(page_size) c_void, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: u64) *c_void; @@ -114,15 +112,10 @@ pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int; pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize; pub extern "c" fn readlinkat(dirfd: fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize; pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8; -pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; -pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; -pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; -pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int; pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int; pub extern "c" fn rmdir(path: [*:0]const u8) c_int; pub extern "c" fn getenv(name: [*:0]const u8) ?[*:0]u8; -pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int; pub extern "c" fn sysctl(name: [*]const c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int; pub extern "c" fn sysctlbyname(name: [*:0]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int; pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*usize) c_int; @@ -133,7 +126,6 @@ pub extern "c" fn uname(buf: *utsname) c_int; pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int; pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int; -pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; pub extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]fd_t) c_int; pub extern "c" fn listen(sockfd: fd_t, backlog: c_uint) c_int; pub extern "c" fn getsockname(sockfd: fd_t, noalias addr: *sockaddr, noalias addrlen: *socklen_t) c_int; @@ -161,12 +153,55 @@ pub extern fn recvfrom( noalias addrlen: ?*socklen_t, ) isize; +pub usingnamespace switch (builtin.os.tag) { + .netbsd => struct { + pub const clock_getres = __clock_getres50; + pub const clock_gettime = __clock_gettime50; + pub const fstat = __fstat50; + pub const getdents = __getdents30; + pub const getrusage = __getrusage50; + pub const gettimeofday = __gettimeofday50; + pub const nanosleep = __nanosleep50; + pub const sched_yield = __libc_thr_yield; + pub const sigaction = __sigaction14; + pub const sigaltstack = __sigaltstack14; + pub const sigprocmask = __sigprocmask14; + pub const stat = __stat50; + }, + .macosx, .ios, .watchos, .tvos => struct { + // XXX: close -> close$NOCANCEL + // XXX: getdirentries -> _getdirentries64 + pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; + pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; + pub const fstat = @"fstat$INODE64"; + pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int; + pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; + pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; + pub extern "c" fn sched_yield() c_int; + pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; + pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; + pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; + pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int; + }, + else => struct { + pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; + pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; + pub extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int; + pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int; + pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; + pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; + pub extern "c" fn sched_yield() c_int; + pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int; + pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; + pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; + pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int; + }, +}; + pub extern "c" fn kill(pid: pid_t, sig: c_int) c_int; pub extern "c" fn getdirentries(fd: fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize; pub extern "c" fn setgid(ruid: c_uint, euid: c_uint) c_int; pub extern "c" fn setuid(uid: c_uint) c_int; -pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; -pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?*c_void; pub extern "c" fn malloc(usize) ?*c_void; @@ -229,8 +264,6 @@ pub extern "c" fn dn_expand( length: c_int, ) c_int; -pub extern "c" fn sched_yield() c_int; - pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{}; pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int; pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int; diff --git a/lib/std/c/netbsd.zig b/lib/std/c/netbsd.zig index a286c181a6..f3c34b5cad 100644 --- a/lib/std/c/netbsd.zig +++ b/lib/std/c/netbsd.zig @@ -21,7 +21,7 @@ pub extern "c" fn __sigprocmask14(how: c_int, noalias set: ?*const sigset_t, noa pub extern "c" fn __socket30(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; pub extern "c" fn __gettimeofday50(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; pub extern "c" fn __getrusage50(who: c_int, usage: *rusage) c_int; -// instead of sched_yield +// libc aliases this as sched_yield pub extern "c" fn __libc_thr_yield() c_int; pub const pthread_mutex_t = extern struct { diff --git a/lib/std/os.zig b/lib/std/os.zig index 48d82797bd..467badca95 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -2553,14 +2553,7 @@ pub const FStatError = error{ pub fn fstat(fd: fd_t) FStatError!Stat { var stat: Stat = undefined; - const symbol_name = if (comptime std.Target.current.isDarwin()) - "fstat$INODE64" - else if (std.Target.current.os.tag == .netbsd) - "__fstat50" - else - "fstat"; - - switch (errno(@field(system, symbol_name)(fd, &stat))) { + switch (errno(system.fstat(fd, &stat))) { 0 => return stat, EINVAL => unreachable, EBADF => unreachable, // Always a race condition. @@ -3427,12 +3420,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void { return; } - const symbol_name = if (std.Target.current.os.tag == .netbsd) - "__clock_gettime50" - else - "clock_gettime"; - - switch (errno(@field(system, symbol_name)(clk_id, tp))) { + switch (errno(system.clock_gettime(clk_id, tp))) { 0 => return, EFAULT => unreachable, EINVAL => return error.UnsupportedClock, @@ -3454,12 +3442,7 @@ pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void { return; } - const symbol_name = if (std.Target.current.os.tag == .netbsd) - "__clock_getres50" - else - "clock_getres"; - - switch (errno(@field(system, symbol_name)(clk_id, res))) { + switch (errno(system.clock_getres(clk_id, res))) { 0 => return, EFAULT => unreachable, EINVAL => return error.UnsupportedClock, @@ -3525,12 +3508,7 @@ pub const SigaltstackError = error{ } || UnexpectedError; pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void { - const symbol_name = if (std.Target.current.os.tag == .netbsd) - "__sigaltstack14" - else - "sigaltstack"; - - switch (errno(@field(system, symbol_name)(ss, old_ss))) { + switch (errno(system.sigaltstack(ss, old_ss))) { 0 => return, EFAULT => unreachable, EINVAL => unreachable, From 318abaad02060a68070aa03fe86f04a7a52c51db Mon Sep 17 00:00:00 2001 From: Vincent Rischmann Date: Wed, 1 Apr 2020 12:24:09 +0200 Subject: [PATCH 53/89] io: test all files under std/io --- lib/std/io.zig | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/lib/std/io.zig b/lib/std/io.zig index 69cc4a923a..b498f2a299 100644 --- a/lib/std/io.zig +++ b/lib/std/io.zig @@ -141,6 +141,20 @@ test "null_out_stream" { } test "" { + _ = @import("io/bit_in_stream.zig"); + _ = @import("io/bit_out_stream.zig"); + _ = @import("io/buffered_atomic_file.zig"); + _ = @import("io/buffered_in_stream.zig"); + _ = @import("io/buffered_out_stream.zig"); + _ = @import("io/c_out_stream.zig"); + _ = @import("io/counting_out_stream.zig"); + _ = @import("io/fixed_buffer_stream.zig"); + _ = @import("io/in_stream.zig"); + _ = @import("io/out_stream.zig"); + _ = @import("io/peek_stream.zig"); + _ = @import("io/seekable_stream.zig"); + _ = @import("io/serialization.zig"); + _ = @import("io/stream_source.zig"); _ = @import("io/test.zig"); } From eddf491bf4babc0d3a2d6ea065c91d9a744ea090 Mon Sep 17 00:00:00 2001 From: Vincent Rischmann Date: Wed, 1 Apr 2020 12:26:49 +0200 Subject: [PATCH 54/89] io: fix PeekStream compilation --- lib/std/io/peek_stream.zig | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/std/io/peek_stream.zig b/lib/std/io/peek_stream.zig index 5ee30ce273..3362efe419 100644 --- a/lib/std/io/peek_stream.zig +++ b/lib/std/io/peek_stream.zig @@ -24,7 +24,7 @@ pub fn PeekStream( .Static => struct { pub fn init(base: InStreamType) Self { return .{ - .base = base, + .unbuffered_in_stream = base, .fifo = FifoType.init(), }; } @@ -32,7 +32,7 @@ pub fn PeekStream( .Slice => struct { pub fn init(base: InStreamType, buf: []u8) Self { return .{ - .base = base, + .unbuffered_in_stream = base, .fifo = FifoType.init(buf), }; } @@ -40,7 +40,7 @@ pub fn PeekStream( .Dynamic => struct { pub fn init(base: InStreamType, allocator: *mem.Allocator) Self { return .{ - .base = base, + .unbuffered_in_stream = base, .fifo = FifoType.init(allocator), }; } @@ -61,7 +61,7 @@ pub fn PeekStream( if (dest_index == dest.len) return dest_index; // ask the backing stream for more - dest_index += try self.base.read(dest[dest_index..]); + dest_index += try self.unbuffered_in_stream.read(dest[dest_index..]); return dest_index; } From f46121b8fc1df6d97bd96116166366ed4dcc5a8c Mon Sep 17 00:00:00 2001 From: Vincent Rischmann Date: Wed, 1 Apr 2020 12:37:02 +0200 Subject: [PATCH 55/89] io: fix serialization compilation and tests --- lib/std/io/serialization.zig | 99 ++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 49 deletions(-) diff --git a/lib/std/io/serialization.zig b/lib/std/io/serialization.zig index da04c63661..6ce18b780c 100644 --- a/lib/std/io/serialization.zig +++ b/lib/std/io/serialization.zig @@ -5,6 +5,7 @@ const assert = std.debug.assert; const math = std.math; const meta = std.meta; const trait = meta.trait; +const testing = std.testing; pub const Packing = enum { /// Pack data to byte alignment @@ -273,7 +274,7 @@ pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, co if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self); if (comptime trait.isPacked(T) and packing != .Bit) { - var packed_serializer = Serializer(endian, .Bit, Error).init(self.out_stream); + var packed_serializer = Serializer(endian, .Bit, OutStreamType).init(self.out_stream); try packed_serializer.serialize(value); try packed_serializer.flush(); return; @@ -364,28 +365,28 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi var data_mem: [total_bytes]u8 = undefined; var out = io.fixedBufferStream(&data_mem); - var serializer = serializer(endian, packing, out.outStream()); + var _serializer = serializer(endian, packing, out.outStream()); var in = io.fixedBufferStream(&data_mem); - var deserializer = Deserializer(endian, packing, in.inStream()); + var _deserializer = deserializer(endian, packing, in.inStream()); comptime var i = 0; inline while (i <= max_test_bitsize) : (i += 1) { const U = std.meta.IntType(false, i); const S = std.meta.IntType(true, i); - try serializer.serializeInt(@as(U, i)); - if (i != 0) try serializer.serializeInt(@as(S, -1)) else try serializer.serialize(@as(S, 0)); + try _serializer.serializeInt(@as(U, i)); + if (i != 0) try _serializer.serializeInt(@as(S, -1)) else try _serializer.serialize(@as(S, 0)); } - try serializer.flush(); + try _serializer.flush(); i = 0; inline while (i <= max_test_bitsize) : (i += 1) { const U = std.meta.IntType(false, i); const S = std.meta.IntType(true, i); - const x = try deserializer.deserializeInt(U); - const y = try deserializer.deserializeInt(S); - expect(x == @as(U, i)); - if (i != 0) expect(y == @as(S, -1)) else expect(y == 0); + const x = try _deserializer.deserializeInt(U); + const y = try _deserializer.deserializeInt(S); + testing.expect(x == @as(U, i)); + if (i != 0) testing.expect(y == @as(S, -1)) else testing.expect(y == 0); } const u8_bit_count = comptime meta.bitCount(u8); @@ -395,7 +396,7 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0); const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte; - expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes); + testing.expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes); //Verify that empty error set works with serializer. //deserializer is covered by FixedBufferStream @@ -421,35 +422,35 @@ fn testIntSerializerDeserializerInfNaN( var data_mem: [mem_size]u8 = undefined; var out = io.fixedBufferStream(&data_mem); - var serializer = serializer(endian, packing, out.outStream()); + var _serializer = serializer(endian, packing, out.outStream()); var in = io.fixedBufferStream(&data_mem); - var deserializer = deserializer(endian, packing, in.inStream()); + var _deserializer = deserializer(endian, packing, in.inStream()); //@TODO: isInf/isNan not currently implemented for f128. - try serializer.serialize(std.math.nan(f16)); - try serializer.serialize(std.math.inf(f16)); - try serializer.serialize(std.math.nan(f32)); - try serializer.serialize(std.math.inf(f32)); - try serializer.serialize(std.math.nan(f64)); - try serializer.serialize(std.math.inf(f64)); + try _serializer.serialize(std.math.nan(f16)); + try _serializer.serialize(std.math.inf(f16)); + try _serializer.serialize(std.math.nan(f32)); + try _serializer.serialize(std.math.inf(f32)); + try _serializer.serialize(std.math.nan(f64)); + try _serializer.serialize(std.math.inf(f64)); //try serializer.serialize(std.math.nan(f128)); //try serializer.serialize(std.math.inf(f128)); - const nan_check_f16 = try deserializer.deserialize(f16); - const inf_check_f16 = try deserializer.deserialize(f16); - const nan_check_f32 = try deserializer.deserialize(f32); - deserializer.alignToByte(); - const inf_check_f32 = try deserializer.deserialize(f32); - const nan_check_f64 = try deserializer.deserialize(f64); - const inf_check_f64 = try deserializer.deserialize(f64); + const nan_check_f16 = try _deserializer.deserialize(f16); + const inf_check_f16 = try _deserializer.deserialize(f16); + const nan_check_f32 = try _deserializer.deserialize(f32); + _deserializer.alignToByte(); + const inf_check_f32 = try _deserializer.deserialize(f32); + const nan_check_f64 = try _deserializer.deserialize(f64); + const inf_check_f64 = try _deserializer.deserialize(f64); //const nan_check_f128 = try deserializer.deserialize(f128); //const inf_check_f128 = try deserializer.deserialize(f128); - expect(std.math.isNan(nan_check_f16)); - expect(std.math.isInf(inf_check_f16)); - expect(std.math.isNan(nan_check_f32)); - expect(std.math.isInf(inf_check_f32)); - expect(std.math.isNan(nan_check_f64)); - expect(std.math.isInf(inf_check_f64)); + testing.expect(std.math.isNan(nan_check_f16)); + testing.expect(std.math.isInf(inf_check_f16)); + testing.expect(std.math.isNan(nan_check_f32)); + testing.expect(std.math.isInf(inf_check_f32)); + testing.expect(std.math.isNan(nan_check_f64)); + testing.expect(std.math.isInf(inf_check_f64)); //expect(std.math.isNan(nan_check_f128)); //expect(std.math.isInf(inf_check_f128)); } @@ -461,8 +462,8 @@ test "Serializer/Deserializer Int: Inf/NaN" { try testIntSerializerDeserializerInfNaN(.Little, .Bit); } -fn testAlternateSerializer(self: var, serializer: var) !void { - try serializer.serialize(self.f_f16); +fn testAlternateSerializer(self: var, _serializer: var) !void { + try _serializer.serialize(self.f_f16); } fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void { @@ -502,8 +503,8 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: f_f16: f16, f_unused_u32: u32, - pub fn deserialize(self: *@This(), deserializer: var) !void { - try deserializer.deserializeInto(&self.f_f16); + pub fn deserialize(self: *@This(), _deserializer: var) !void { + try _deserializer.deserializeInto(&self.f_f16); self.f_unused_u32 = 47; } @@ -550,15 +551,15 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: var data_mem: [@sizeOf(MyStruct)]u8 = undefined; var out = io.fixedBufferStream(&data_mem); - var serializer = serializer(endian, packing, out.outStream()); + var _serializer = serializer(endian, packing, out.outStream()); var in = io.fixedBufferStream(&data_mem); - var deserializer = deserializer(endian, packing, in.inStream()); + var _deserializer = deserializer(endian, packing, in.inStream()); - try serializer.serialize(my_inst); + try _serializer.serialize(my_inst); - const my_copy = try deserializer.deserialize(MyStruct); - expect(meta.eql(my_copy, my_inst)); + const my_copy = try _deserializer.deserialize(MyStruct); + testing.expect(meta.eql(my_copy, my_inst)); } test "Serializer/Deserializer generic" { @@ -584,18 +585,18 @@ fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !v }; var data_mem: [4]u8 = undefined; - var out = io.fixedBufferStream.init(&data_mem); - var serializer = serializer(endian, packing, out.outStream()); + var out = io.fixedBufferStream(&data_mem); + var _serializer = serializer(endian, packing, out.outStream()); var in = io.fixedBufferStream(&data_mem); - var deserializer = deserializer(endian, packing, in.inStream()); + var _deserializer = deserializer(endian, packing, in.inStream()); - try serializer.serialize(@as(u14, 3)); - expectError(error.InvalidEnumTag, deserializer.deserialize(A)); + try _serializer.serialize(@as(u14, 3)); + testing.expectError(error.InvalidEnumTag, _deserializer.deserialize(A)); out.pos = 0; - try serializer.serialize(@as(u14, 3)); - try serializer.serialize(@as(u14, 88)); - expectError(error.InvalidEnumTag, deserializer.deserialize(C)); + try _serializer.serialize(@as(u14, 3)); + try _serializer.serialize(@as(u14, 88)); + testing.expectError(error.InvalidEnumTag, _deserializer.deserialize(C)); } test "Deserializer bad data" { From 5047cd3d782c51474216eda92ea457315bc4f8b5 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Wed, 1 Apr 2020 12:46:16 +0200 Subject: [PATCH 56/89] Workaround for #4789 --- lib/std/os/bits/linux.zig | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/std/os/bits/linux.zig b/lib/std/os/bits/linux.zig index 2d5f07209a..4bc3357ce5 100644 --- a/lib/std/os/bits/linux.zig +++ b/lib/std/os/bits/linux.zig @@ -827,15 +827,17 @@ else /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = extern struct { - sigaction: ?extern fn (i32, *siginfo_t, *c_void) void, + pub const sigaction_fn = fn (i32, *siginfo_t, ?*c_void) callconv(.C) void; + sigaction: ?sigaction_fn, mask: sigset_t, flags: u32, restorer: ?extern fn () void = null, }; -pub const SIG_ERR = @intToPtr(extern fn (i32, *siginfo_t, *c_void) void, maxInt(usize)); -pub const SIG_DFL = @intToPtr(?extern fn (i32, *siginfo_t, *c_void) void, 0); -pub const SIG_IGN = @intToPtr(extern fn (i32, *siginfo_t, *c_void) void, 1); +pub const SIG_ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize)); +pub const SIG_DFL = @intToPtr(?Sigaction.sigaction_fn, 0); +pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1); + pub const empty_sigset = [_]u32{0} ** sigset_t.len; pub const in_port_t = u16; From 748b2c72a34265e57f6fb2987ab705563f17abe2 Mon Sep 17 00:00:00 2001 From: Vincent Rischmann Date: Wed, 1 Apr 2020 13:13:47 +0200 Subject: [PATCH 57/89] io: fix COutStream test --- lib/std/io/c_out_stream.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/std/io/c_out_stream.zig b/lib/std/io/c_out_stream.zig index 3b5e44bf75..b8c9a51528 100644 --- a/lib/std/io/c_out_stream.zig +++ b/lib/std/io/c_out_stream.zig @@ -36,9 +36,9 @@ test "" { const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile; defer { _ = std.c.fclose(out_file); - fs.cwd().deleteFileZ(filename) catch {}; + std.fs.cwd().deleteFileZ(filename) catch {}; } - const out_stream = &io.COutStream.init(out_file).stream; + const out_stream = &cOutStream(out_file); try out_stream.print("hi: {}\n", .{@as(i32, 123)}); } From d23f9a164eede57135ca141b11c9a9803ed52fc6 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 1 Apr 2020 10:21:17 -0400 Subject: [PATCH 58/89] Remove unneeeded address-of operator --- lib/std/io/c_out_stream.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/std/io/c_out_stream.zig b/lib/std/io/c_out_stream.zig index b8c9a51528..119b7f9d29 100644 --- a/lib/std/io/c_out_stream.zig +++ b/lib/std/io/c_out_stream.zig @@ -39,6 +39,6 @@ test "" { std.fs.cwd().deleteFileZ(filename) catch {}; } - const out_stream = &cOutStream(out_file); + const out_stream = cOutStream(out_file); try out_stream.print("hi: {}\n", .{@as(i32, 123)}); } From 0ee2462a3116020013f8c55e830182df0fa369f2 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sun, 1 Mar 2020 19:13:26 +1100 Subject: [PATCH 59/89] std: add std.ArrayList(u8).outStream() --- lib/std/array_list.zig | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index cbbec0b4f3..87bf3c51df 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -189,6 +189,22 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type { self.len += items.len; } + pub usingnamespace if (T == u8) + struct { + /// Same as `append` except it returns the number of bytes written, which is always the same + /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. + fn appendWrite(self: *Self, m: []const u8) !usize { + try self.appendSlice(m); + return m.len; + } + + pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) { + return .{ .context = self }; + } + } + else + struct {}; + /// Append a value to the list `n` times. Allocates more memory /// as necessary. pub fn appendNTimes(self: *Self, value: T, n: usize) !void { @@ -479,3 +495,14 @@ test "std.ArrayList: ArrayList(T) of struct T" { try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(testing.allocator) }); testing.expect(root.sub_items.items[0].integer == 42); } + +test "std.ArrayList(u8) implements outStream" { + var buffer = ArrayList(u8).init(std.testing.allocator); + defer buffer.deinit(); + + const x: i32 = 42; + const y: i32 = 1234; + try buffer.outStream().print("x: {}\ny: {}\n", .{ x, y }); + + testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.span()); +} From bb5383cf00b3a518f9101f1503681aff510cdcbb Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sat, 7 Mar 2020 15:25:48 +1100 Subject: [PATCH 60/89] std: don't return sentinel slices from cross_target functions --- lib/std/target.zig | 8 ++++---- lib/std/zig/cross_target.zig | 18 ++++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/std/target.zig b/lib/std/target.zig index 8e1b9f8736..3f18791eb9 100644 --- a/lib/std/target.zig +++ b/lib/std/target.zig @@ -967,15 +967,15 @@ pub const Target = struct { pub const stack_align = 16; - pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 { + pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 { return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator); } - pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![:0]u8 { - return std.fmt.allocPrint0(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) }); + pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 { + return std.fmt.allocPrint(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) }); } - pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 { + pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 { return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi); } diff --git a/lib/std/zig/cross_target.zig b/lib/std/zig/cross_target.zig index bea69b3978..9099519274 100644 --- a/lib/std/zig/cross_target.zig +++ b/lib/std/zig/cross_target.zig @@ -495,16 +495,18 @@ pub const CrossTarget = struct { return self.isNativeCpu() and self.isNativeOs() and self.abi == null; } - pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![:0]u8 { + pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![]u8 { if (self.isNative()) { - return mem.dupeZ(allocator, u8, "native"); + return mem.dupe(allocator, u8, "native"); } const arch_name = if (self.cpu_arch) |arch| @tagName(arch) else "native"; const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native"; - var result = try std.Buffer.allocPrint(allocator, "{}-{}", .{ arch_name, os_name }); - defer result.deinit(); + var result = std.ArrayList(u8).init(allocator); + errdefer result.deinit(); + + try result.outStream().print("{}-{}", .{ arch_name, os_name }); // The zig target syntax does not allow specifying a max os version with no min, so // if either are present, we need the min. @@ -532,13 +534,13 @@ pub const CrossTarget = struct { return result.toOwnedSlice(); } - pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 { + pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![]u8 { // TODO is there anything else worthy of the description that is not // already captured in the triple? return self.zigTriple(allocator); } - pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 { + pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![]u8 { return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi()); } @@ -549,7 +551,7 @@ pub const CrossTarget = struct { pub const VcpkgLinkage = std.builtin.LinkMode; /// Returned slice must be freed by the caller. - pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![:0]u8 { + pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![]u8 { const arch = switch (self.getCpuArch()) { .i386 => "x86", .x86_64 => "x64", @@ -580,7 +582,7 @@ pub const CrossTarget = struct { .Dynamic => "", }; - return std.fmt.allocPrint0(allocator, "{}-{}{}", .{ arch, os, static_suffix }); + return std.fmt.allocPrint(allocator, "{}-{}{}", .{ arch, os, static_suffix }); } pub const Executor = union(enum) { From ecbc235403eb424a40e111a8789ae3a32fd14edd Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sat, 7 Mar 2020 15:35:06 +1100 Subject: [PATCH 61/89] std: use std.ArrayList(u8) instead of std.Buffer in std/build.zig --- lib/std/build.zig | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/lib/std/build.zig b/lib/std/build.zig index 858f6bd6f0..626638647e 100644 --- a/lib/std/build.zig +++ b/lib/std/build.zig @@ -1139,7 +1139,7 @@ pub const LibExeObjStep = struct { out_lib_filename: []const u8, out_pdb_filename: []const u8, packages: ArrayList(Pkg), - build_options_contents: std.Buffer, + build_options_contents: std.ArrayList(u8), system_linker_hack: bool = false, object_src: []const u8, @@ -1274,7 +1274,7 @@ pub const LibExeObjStep = struct { .lib_paths = ArrayList([]const u8).init(builder.allocator), .framework_dirs = ArrayList([]const u8).init(builder.allocator), .object_src = undefined, - .build_options_contents = std.Buffer.initSize(builder.allocator, 0) catch unreachable, + .build_options_contents = std.ArrayList(u8).init(builder.allocator), .c_std = Builder.CStd.C99, .override_lib_dir = null, .main_pkg_path = null, @@ -1847,7 +1847,7 @@ pub const LibExeObjStep = struct { } } - if (self.build_options_contents.len() > 0) { + if (self.build_options_contents.len > 0) { const build_options_file = try fs.path.join( builder.allocator, &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) }, @@ -1960,22 +1960,23 @@ pub const LibExeObjStep = struct { try zig_args.append(cross.cpu.model.name); } } else { - var mcpu_buffer = try std.Buffer.init(builder.allocator, "-mcpu="); - try mcpu_buffer.append(cross.cpu.model.name); + var mcpu_buffer = std.ArrayList(u8).init(builder.allocator); + errdefer mcpu_buffer.deinit(); + + try mcpu_buffer.outStream().print("-mcpu={}", .{cross.cpu.model.name}); for (all_features) |feature, i_usize| { const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize); const in_cpu_set = populated_cpu_features.isEnabled(i); const in_actual_set = cross.cpu.features.isEnabled(i); if (in_cpu_set and !in_actual_set) { - try mcpu_buffer.appendByte('-'); - try mcpu_buffer.append(feature.name); + try mcpu_buffer.outStream().print("-{}", .{feature.name}); } else if (!in_cpu_set and in_actual_set) { - try mcpu_buffer.appendByte('+'); - try mcpu_buffer.append(feature.name); + try mcpu_buffer.outStream().print("+{}", .{feature.name}); } } - try zig_args.append(mcpu_buffer.span()); + + try zig_args.append(mcpu_buffer.toOwnedSlice()); } if (self.target.dynamic_linker.get()) |dynamic_linker| { From 37e6a64690a257b4f5a9e3f234deb8b72e74ca54 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sat, 7 Mar 2020 15:42:10 +1100 Subject: [PATCH 62/89] std: use Buffer.outStream in std/child_process.zig --- lib/std/child_process.zig | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig index 3013133b11..8e341a07b8 100644 --- a/lib/std/child_process.zig +++ b/lib/std/child_process.zig @@ -758,37 +758,36 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1 /// Caller must dealloc. /// Guarantees a null byte at result[result.len]. -fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![]u8 { +fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 { var buf = try Buffer.initSize(allocator, 0); defer buf.deinit(); - - var buf_stream = buf.outStream(); + const buf_stream = buf.outStream(); for (argv) |arg, arg_i| { - if (arg_i != 0) try buf.appendByte(' '); + if (arg_i != 0) try buf_stream.writeByte(' '); if (mem.indexOfAny(u8, arg, " \t\n\"") == null) { - try buf.append(arg); + try buf_stream.writeAll(arg); continue; } - try buf.appendByte('"'); + try buf_stream.writeByte('"'); var backslash_count: usize = 0; for (arg) |byte| { switch (byte) { '\\' => backslash_count += 1, '"' => { try buf_stream.writeByteNTimes('\\', backslash_count * 2 + 1); - try buf.appendByte('"'); + try buf_stream.writeByte('"'); backslash_count = 0; }, else => { try buf_stream.writeByteNTimes('\\', backslash_count); - try buf.appendByte(byte); + try buf_stream.writeByte(byte); backslash_count = 0; }, } } try buf_stream.writeByteNTimes('\\', backslash_count * 2); - try buf.appendByte('"'); + try buf_stream.writeByte('"'); } return buf.toOwnedSlice(); From 3fb030e78a04ff5eebd4e01769099b799912b9fd Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sat, 7 Mar 2020 15:45:29 +1100 Subject: [PATCH 63/89] std: use std.ArrayList(u8) instead of std.Buffer in src-self-hosted/translate_c.zig --- src-self-hosted/translate_c.zig | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index f8eec3578f..62318a40aa 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -209,7 +209,7 @@ const Scope = struct { pub const Context = struct { tree: *ast.Tree, - source_buffer: *std.Buffer, + source_buffer: *std.ArrayList(u8), err: Error, source_manager: *ZigClangSourceManager, decl_table: DeclTable, @@ -296,7 +296,8 @@ pub fn translate( .eof_token = undefined, }; - var source_buffer = try std.Buffer.initSize(arena, 0); + var source_buffer = std.ArrayList(u8).init(arena); + errdefer source_buffer.deinit(); var context = Context{ .tree = tree, @@ -4309,7 +4310,7 @@ fn makeRestorePoint(c: *Context) RestorePoint { return RestorePoint{ .c = c, .token_index = c.tree.tokens.len, - .src_buf_index = c.source_buffer.len(), + .src_buf_index = c.source_buffer.len, }; } @@ -4771,11 +4772,11 @@ fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenInd fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex { assert(token_id != .Invalid); - const start_index = c.source_buffer.len(); + const start_index = c.source_buffer.len; errdefer c.source_buffer.shrink(start_index); try c.source_buffer.outStream().print(format, args); - const end_index = c.source_buffer.len(); + const end_index = c.source_buffer.len; const token_index = c.tree.tokens.len; const new_token = try c.tree.tokens.addOne(); errdefer c.tree.tokens.shrink(token_index); @@ -4785,7 +4786,7 @@ fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, .start = start_index, .end = end_index, }; - try c.source_buffer.appendByte(' '); + try c.source_buffer.append(' '); return token_index; } From e535057364d33819001e55d34d104916cfab1b91 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Sun, 8 Mar 2020 18:16:10 +1100 Subject: [PATCH 64/89] std: use std.ArrayList(u8).OutStream instead of std.Buffer.OutStream --- doc/docgen.zig | 8 ++++---- lib/std/zig/parser_test.zig | 2 +- src-self-hosted/errmsg.zig | 4 ++-- src-self-hosted/stage2.zig | 5 +++-- src-self-hosted/type.zig | 4 ++-- 5 files changed, 12 insertions(+), 11 deletions(-) diff --git a/doc/docgen.zig b/doc/docgen.zig index be62cab076..9e4c8173c0 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -321,7 +321,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { var last_action = Action.Open; var last_columns: ?u8 = null; - var toc_buf = try std.Buffer.initSize(allocator, 0); + var toc_buf = std.ArrayList(u8).init(allocator); defer toc_buf.deinit(); var toc = toc_buf.outStream(); @@ -607,7 +607,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc { } fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 { - var buf = try std.Buffer.initSize(allocator, 0); + var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); const out = buf.outStream(); @@ -626,7 +626,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 { } fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 { - var buf = try std.Buffer.initSize(allocator, 0); + var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); const out = buf.outStream(); @@ -672,7 +672,7 @@ test "term color" { } fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 { - var buf = try std.Buffer.initSize(allocator, 0); + var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); var out = buf.outStream(); diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index 136e323fe6..91921786a2 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -2953,7 +2953,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b return error.ParseError; } - var buffer = try std.Buffer.initSize(allocator, 0); + var buffer = std.ArrayList(u8).init(allocator); errdefer buffer.deinit(); anything_changed.* = try std.zig.render(allocator, buffer.outStream(), tree); diff --git a/src-self-hosted/errmsg.zig b/src-self-hosted/errmsg.zig index 606c8c4b3a..5775c1df83 100644 --- a/src-self-hosted/errmsg.zig +++ b/src-self-hosted/errmsg.zig @@ -158,7 +158,7 @@ pub const Msg = struct { parse_error: *const ast.Error, ) !*Msg { const loc_token = parse_error.loc(); - var text_buf = try std.Buffer.initSize(comp.gpa(), 0); + var text_buf = std.ArrayList(u8).init(comp.gpa()); defer text_buf.deinit(); const realpath_copy = try mem.dupe(comp.gpa(), u8, tree_scope.root().realpath); @@ -197,7 +197,7 @@ pub const Msg = struct { realpath: []const u8, ) !*Msg { const loc_token = parse_error.loc(); - var text_buf = try std.Buffer.initSize(allocator, 0); + var text_buf = std.ArrayList(u8).init(allocator); defer text_buf.deinit(); const realpath_copy = try mem.dupe(allocator, u8, realpath); diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index d9b763912c..92eb04539a 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -411,10 +411,11 @@ fn printErrMsgToFile( const start_loc = tree.tokenLocationPtr(0, first_token); const end_loc = tree.tokenLocationPtr(first_token.end, last_token); - var text_buf = try std.Buffer.initSize(allocator, 0); + var text_buf = std.ArrayList(u8).init(allocator); + defer text_buf.deinit(); const out_stream = &text_buf.outStream(); try parse_error.render(&tree.tokens, out_stream); - const text = text_buf.toOwnedSlice(); + const text = text_buf.span(); const stream = &file.outStream(); try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text }); diff --git a/src-self-hosted/type.zig b/src-self-hosted/type.zig index 70ed754cea..6adad9fa67 100644 --- a/src-self-hosted/type.zig +++ b/src-self-hosted/type.zig @@ -387,10 +387,10 @@ pub const Type = struct { }; errdefer comp.gpa().destroy(self); - var name_buf = try std.Buffer.initSize(comp.gpa(), 0); + var name_buf = std.ArrayList(u8).init(comp.gpa()); defer name_buf.deinit(); - const name_stream = &std.io.BufferOutStream.init(&name_buf).stream; + const name_stream = name_buf.outStream(); switch (key.data) { .Generic => |generic| { From 7eb938c9096db54fe6e99148824252904c79c227 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Fri, 13 Mar 2020 00:52:28 +1100 Subject: [PATCH 65/89] Use length field as passed in stage2 libc_installation instead of relying on zero termination --- src-self-hosted/libc_installation.zig | 95 +++++++++++++++++---------- src-self-hosted/stage2.zig | 20 +++--- src/cache_hash.cpp | 8 ++- src/cache_hash.hpp | 1 + src/codegen.cpp | 27 ++++---- src/link.cpp | 26 ++++++-- 6 files changed, 112 insertions(+), 65 deletions(-) diff --git a/src-self-hosted/libc_installation.zig b/src-self-hosted/libc_installation.zig index 9aa7b39c9b..f802cbd606 100644 --- a/src-self-hosted/libc_installation.zig +++ b/src-self-hosted/libc_installation.zig @@ -14,11 +14,11 @@ usingnamespace @import("windows_sdk.zig"); /// See the render function implementation for documentation of the fields. pub const LibCInstallation = struct { - include_dir: ?[:0]const u8 = null, - sys_include_dir: ?[:0]const u8 = null, - crt_dir: ?[:0]const u8 = null, - msvc_lib_dir: ?[:0]const u8 = null, - kernel32_lib_dir: ?[:0]const u8 = null, + include_dir: ?[]const u8 = null, + sys_include_dir: ?[]const u8 = null, + crt_dir: ?[]const u8 = null, + msvc_lib_dir: ?[]const u8 = null, + kernel32_lib_dir: ?[]const u8 = null, pub const FindError = error{ OutOfMemory, @@ -327,15 +327,20 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - var result_buf = try std.Buffer.initSize(allocator, 0); - defer result_buf.deinit(); - for (searches) |search| { - result_buf.shrink(0); - const stream = result_buf.outStream(); - try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version }); + const dir_path = try fs.path.join( + allocator, + &[_][]const u8{ + search.path, + "Include", + search.version, + "ucrt", + }, + ); + var found = false; + defer if (!found) allocator.free(dir_path); - var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -350,7 +355,8 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - self.include_dir = result_buf.toOwnedSlice(); + found = true; + self.include_dir = dir_path; return; } @@ -367,9 +373,6 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - var result_buf = try std.Buffer.initSize(allocator, 0); - defer result_buf.deinit(); - const arch_sub_dir = switch (builtin.arch) { .i386 => "x86", .x86_64 => "x64", @@ -378,11 +381,20 @@ pub const LibCInstallation = struct { }; for (searches) |search| { - result_buf.shrink(0); - const stream = result_buf.outStream(); - try stream.print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir }); + const dir_path = try fs.path.join( + allocator, + &[_][]const u8{ + search.path, + "Lib", + search.version, + "ucrt", + arch_sub_dir, + }, + ); + var found = false; + defer if (!found) allocator.free(dir_path); - var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -397,7 +409,8 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - self.crt_dir = result_buf.toOwnedSlice(); + found = true; + self.crt_dir = dir_path; return; } return error.LibCRuntimeNotFound; @@ -421,10 +434,6 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - - var result_buf = try std.Buffer.initSize(allocator, 0); - defer result_buf.deinit(); - const arch_sub_dir = switch (builtin.arch) { .i386 => "x86", .x86_64 => "x64", @@ -433,11 +442,20 @@ pub const LibCInstallation = struct { }; for (searches) |search| { - result_buf.shrink(0); - const stream = result_buf.outStream(); - try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir }); + const dir_path = try fs.path.join( + allocator, + &[_][]const u8{ + search.path, + "Lib", + search.version, + "um", + arch_sub_dir, + }, + ); + var found = false; + defer if (!found) allocator.free(dir_path); - var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -452,7 +470,8 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - self.kernel32_lib_dir = result_buf.toOwnedSlice(); + found = true; + self.kernel32_lib_dir = dir_path; return; } return error.LibCKernel32LibNotFound; @@ -470,12 +489,16 @@ pub const LibCInstallation = struct { const up1 = fs.path.dirname(msvc_lib_dir) orelse return error.LibCStdLibHeaderNotFound; const up2 = fs.path.dirname(up1) orelse return error.LibCStdLibHeaderNotFound; - var result_buf = try std.Buffer.init(allocator, up2); - defer result_buf.deinit(); + const dir_path = try fs.path.join( + allocator, + &[_][]const u8{ + up2, + "include", + }, + ); + errdefer allocator.free(dir_path); - try result_buf.append("\\include"); - - var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -490,7 +513,7 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - self.sys_include_dir = result_buf.toOwnedSlice(); + self.sys_include_dir = dir_path; } fn findNativeMsvcLibDir( diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 92eb04539a..771765bee6 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -741,15 +741,15 @@ fn stage2TargetParse( // ABI warning const Stage2LibCInstallation = extern struct { - include_dir: [*:0]const u8, + include_dir: [*]const u8, include_dir_len: usize, - sys_include_dir: [*:0]const u8, + sys_include_dir: [*]const u8, sys_include_dir_len: usize, - crt_dir: [*:0]const u8, + crt_dir: [*]const u8, crt_dir_len: usize, - msvc_lib_dir: [*:0]const u8, + msvc_lib_dir: [*]const u8, msvc_lib_dir_len: usize, - kernel32_lib_dir: [*:0]const u8, + kernel32_lib_dir: [*]const u8, kernel32_lib_dir_len: usize, fn initFromStage2(self: *Stage2LibCInstallation, libc: LibCInstallation) void { @@ -793,19 +793,19 @@ const Stage2LibCInstallation = extern struct { fn toStage2(self: Stage2LibCInstallation) LibCInstallation { var libc: LibCInstallation = .{}; if (self.include_dir_len != 0) { - libc.include_dir = self.include_dir[0..self.include_dir_len :0]; + libc.include_dir = self.include_dir[0..self.include_dir_len]; } if (self.sys_include_dir_len != 0) { - libc.sys_include_dir = self.sys_include_dir[0..self.sys_include_dir_len :0]; + libc.sys_include_dir = self.sys_include_dir[0..self.sys_include_dir_len]; } if (self.crt_dir_len != 0) { - libc.crt_dir = self.crt_dir[0..self.crt_dir_len :0]; + libc.crt_dir = self.crt_dir[0..self.crt_dir_len]; } if (self.msvc_lib_dir_len != 0) { - libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len :0]; + libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len]; } if (self.kernel32_lib_dir_len != 0) { - libc.kernel32_lib_dir = self.kernel32_lib_dir[0..self.kernel32_lib_dir_len :0]; + libc.kernel32_lib_dir = self.kernel32_lib_dir[0..self.kernel32_lib_dir_len]; } return libc; } diff --git a/src/cache_hash.cpp b/src/cache_hash.cpp index 3cff34ea5c..c12d8f29ef 100644 --- a/src/cache_hash.cpp +++ b/src/cache_hash.cpp @@ -27,11 +27,17 @@ void cache_init(CacheHash *ch, Buf *manifest_dir) { void cache_mem(CacheHash *ch, const char *ptr, size_t len) { assert(ch->manifest_file_path == nullptr); assert(ptr != nullptr); - // + 1 to include the null byte blake2b_update(&ch->blake, ptr, len); } +void cache_slice(CacheHash *ch, Slice slice) { + // mix the length into the hash so that two juxtaposed cached slices can't collide + cache_usize(ch, slice.len); + cache_mem(ch, slice.ptr, slice.len); +} + void cache_str(CacheHash *ch, const char *ptr) { + // + 1 to include the null byte cache_mem(ch, ptr, strlen(ptr) + 1); } diff --git a/src/cache_hash.hpp b/src/cache_hash.hpp index 9e4c41b1e0..ba2434076a 100644 --- a/src/cache_hash.hpp +++ b/src/cache_hash.hpp @@ -36,6 +36,7 @@ void cache_init(CacheHash *ch, Buf *manifest_dir); // Next, use the hash population functions to add the initial parameters. void cache_mem(CacheHash *ch, const char *ptr, size_t len); +void cache_slice(CacheHash *ch, Slice slice); void cache_str(CacheHash *ch, const char *ptr); void cache_int(CacheHash *ch, int x); void cache_bool(CacheHash *ch, bool x); diff --git a/src/codegen.cpp b/src/codegen.cpp index d36e398bf7..2c2bf7c36b 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -9123,21 +9123,26 @@ static void detect_libc(CodeGen *g) { g->libc_include_dir_len = 0; g->libc_include_dir_list = heap::c_allocator.allocate(dir_count); - g->libc_include_dir_list[g->libc_include_dir_len] = g->libc->include_dir; + g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem(g->libc->include_dir, g->libc->include_dir_len)); g->libc_include_dir_len += 1; if (want_sys_dir) { - g->libc_include_dir_list[g->libc_include_dir_len] = g->libc->sys_include_dir; + g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem(g->libc->sys_include_dir, g->libc->sys_include_dir_len)); g->libc_include_dir_len += 1; } if (want_um_and_shared_dirs != 0) { - g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_sprintf( - "%s" OS_SEP ".." OS_SEP "um", g->libc->include_dir)); + Buf *include_dir_parent = buf_alloc(); + os_path_join(buf_create_from_mem(g->libc->include_dir, g->libc->include_dir_len), buf_create_from_str(".."), include_dir_parent); + + Buf *buff1 = buf_alloc(); + os_path_join(include_dir_parent, buf_create_from_str("um"), buff1); + g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buff1); g->libc_include_dir_len += 1; - g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_sprintf( - "%s" OS_SEP ".." OS_SEP "shared", g->libc->include_dir)); + Buf *buff2 = buf_alloc(); + os_path_join(include_dir_parent, buf_create_from_str("shared"), buff2); + g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buff2); g->libc_include_dir_len += 1; } assert(g->libc_include_dir_len == dir_count); @@ -10546,11 +10551,11 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) { cache_list_of_str(ch, g->lib_dirs.items, g->lib_dirs.length); cache_list_of_str(ch, g->framework_dirs.items, g->framework_dirs.length); if (g->libc) { - cache_str(ch, g->libc->include_dir); - cache_str(ch, g->libc->sys_include_dir); - cache_str(ch, g->libc->crt_dir); - cache_str(ch, g->libc->msvc_lib_dir); - cache_str(ch, g->libc->kernel32_lib_dir); + cache_slice(ch, Slice{g->libc->include_dir, g->libc->include_dir_len}); + cache_slice(ch, Slice{g->libc->sys_include_dir, g->libc->sys_include_dir_len}); + cache_slice(ch, Slice{g->libc->crt_dir, g->libc->crt_dir_len}); + cache_slice(ch, Slice{g->libc->msvc_lib_dir, g->libc->msvc_lib_dir_len}); + cache_slice(ch, Slice{g->libc->kernel32_lib_dir, g->libc->kernel32_lib_dir_len}); } cache_buf_opt(ch, g->version_script_path); cache_buf_opt(ch, g->override_soname); diff --git a/src/link.cpp b/src/link.cpp index 0d7a8a410b..49bbb7c1a5 100644 --- a/src/link.cpp +++ b/src/link.cpp @@ -1595,7 +1595,7 @@ static const char *get_libc_crt_file(CodeGen *parent, const char *file, Stage2Pr } else { assert(parent->libc != nullptr); Buf *out_buf = buf_alloc(); - os_path_join(buf_create_from_str(parent->libc->crt_dir), buf_create_from_str(file), out_buf); + os_path_join(buf_create_from_mem(parent->libc->crt_dir, parent->libc->crt_dir_len), buf_create_from_str(file), out_buf); return buf_ptr(out_buf); } } @@ -1860,7 +1860,7 @@ static void construct_linker_job_elf(LinkJob *lj) { if (g->libc_link_lib != nullptr) { if (g->libc != nullptr) { lj->args.append("-L"); - lj->args.append(g->libc->crt_dir); + lj->args.append(buf_ptr(buf_create_from_mem(g->libc->crt_dir, g->libc->crt_dir_len))); } if (g->have_dynamic_link && (is_dyn_lib || g->out_type == OutTypeExe)) { @@ -2381,14 +2381,26 @@ static void construct_linker_job_coff(LinkJob *lj) { lj->args.append(buf_ptr(buf_sprintf("-OUT:%s", buf_ptr(&g->bin_file_output_path)))); if (g->libc_link_lib != nullptr && g->libc != nullptr) { - lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->crt_dir))); + Buf *buff0 = buf_create_from_str("-LIBPATH:"); + buf_append_mem(buff0, g->libc->crt_dir, g->libc->crt_dir_len); + lj->args.append(buf_ptr(buff0)); if (target_abi_is_gnu(g->zig_target->abi)) { - lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->sys_include_dir))); - lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->include_dir))); + Buf *buff1 = buf_create_from_str("-LIBPATH:"); + buf_append_mem(buff1, g->libc->sys_include_dir, g->libc->sys_include_dir_len); + lj->args.append(buf_ptr(buff1)); + + Buf *buff2 = buf_create_from_str("-LIBPATH:"); + buf_append_mem(buff2, g->libc->include_dir, g->libc->include_dir_len); + lj->args.append(buf_ptr(buff2)); } else { - lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->msvc_lib_dir))); - lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->kernel32_lib_dir))); + Buf *buff1 = buf_create_from_str("-LIBPATH:"); + buf_append_mem(buff1, g->libc->msvc_lib_dir, g->libc->msvc_lib_dir_len); + lj->args.append(buf_ptr(buff1)); + + Buf *buff2 = buf_create_from_str("-LIBPATH:"); + buf_append_mem(buff2, g->libc->kernel32_lib_dir, g->libc->kernel32_lib_dir_len); + lj->args.append(buf_ptr(buff2)); } } From 553f0e0546e0ceecf2ff735443d9a2c2f282b8db Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 1 Apr 2020 11:56:39 -0400 Subject: [PATCH 66/89] fixups and revert a few things --- lib/std/array_list.zig | 34 ++++++------ lib/std/build.zig | 1 - lib/std/child_process.zig | 1 - lib/std/zig/cross_target.zig | 2 +- src-self-hosted/libc_installation.zig | 77 +++++++++------------------ src-self-hosted/stage2.zig | 4 +- src-self-hosted/translate_c.zig | 1 - src/codegen.cpp | 9 ++-- src/link.cpp | 3 +- 9 files changed, 52 insertions(+), 80 deletions(-) diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index 87bf3c51df..523d1c810f 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -189,32 +189,30 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type { self.len += items.len; } - pub usingnamespace if (T == u8) - struct { - /// Same as `append` except it returns the number of bytes written, which is always the same - /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. - fn appendWrite(self: *Self, m: []const u8) !usize { - try self.appendSlice(m); - return m.len; - } + /// Same as `append` except it returns the number of bytes written, which is always the same + /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. + /// This function may be called only when `T` is `u8`. + fn appendWrite(self: *Self, m: []const u8) !usize { + try self.appendSlice(m); + return m.len; + } - pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) { - return .{ .context = self }; - } - } - else - struct {}; + /// Initializes an OutStream which will append to the list. + /// This function may be called only when `T` is `u8`. + pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) { + return .{ .context = self }; + } - /// Append a value to the list `n` times. Allocates more memory - /// as necessary. + /// Append a value to the list `n` times. + /// Allocates more memory as necessary. pub fn appendNTimes(self: *Self, value: T, n: usize) !void { const old_len = self.len; try self.resize(self.len + n); mem.set(T, self.items[old_len..self.len], value); } - /// Adjust the list's length to `new_len`. Doesn't initialize - /// added items if any. + /// Adjust the list's length to `new_len`. + /// Does not initialize added items if any. pub fn resize(self: *Self, new_len: usize) !void { try self.ensureCapacity(new_len); self.len = new_len; diff --git a/lib/std/build.zig b/lib/std/build.zig index 626638647e..ccd0ebaf8a 100644 --- a/lib/std/build.zig +++ b/lib/std/build.zig @@ -1961,7 +1961,6 @@ pub const LibExeObjStep = struct { } } else { var mcpu_buffer = std.ArrayList(u8).init(builder.allocator); - errdefer mcpu_buffer.deinit(); try mcpu_buffer.outStream().print("-mcpu={}", .{cross.cpu.model.name}); diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig index 8e341a07b8..0c24af2d85 100644 --- a/lib/std/child_process.zig +++ b/lib/std/child_process.zig @@ -757,7 +757,6 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1 } /// Caller must dealloc. -/// Guarantees a null byte at result[result.len]. fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 { var buf = try Buffer.initSize(allocator, 0); defer buf.deinit(); diff --git a/lib/std/zig/cross_target.zig b/lib/std/zig/cross_target.zig index 9099519274..4d19ecee8c 100644 --- a/lib/std/zig/cross_target.zig +++ b/lib/std/zig/cross_target.zig @@ -504,7 +504,7 @@ pub const CrossTarget = struct { const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native"; var result = std.ArrayList(u8).init(allocator); - errdefer result.deinit(); + defer result.deinit(); try result.outStream().print("{}-{}", .{ arch_name, os_name }); diff --git a/src-self-hosted/libc_installation.zig b/src-self-hosted/libc_installation.zig index f802cbd606..11708e2a31 100644 --- a/src-self-hosted/libc_installation.zig +++ b/src-self-hosted/libc_installation.zig @@ -327,20 +327,14 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - for (searches) |search| { - const dir_path = try fs.path.join( - allocator, - &[_][]const u8{ - search.path, - "Include", - search.version, - "ucrt", - }, - ); - var found = false; - defer if (!found) allocator.free(dir_path); + var result_buf = std.ArrayList([]const u8).init(allocator); + defer result_buf.deinit(); - var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { + for (searches) |search| { + result_buf.shrink(0); + try result_buf.outStream().print("{}\\Include\\{}\\ucrt", .{ search.path, search.version }); + + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -355,8 +349,7 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - found = true; - self.include_dir = dir_path; + self.include_dir = result_buf.toOwnedSlice(); return; } @@ -373,6 +366,9 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); + var result_buf = try std.ArrayList([]const u8).init(allocator); + defer result_buf.deinit(); + const arch_sub_dir = switch (builtin.arch) { .i386 => "x86", .x86_64 => "x64", @@ -381,20 +377,10 @@ pub const LibCInstallation = struct { }; for (searches) |search| { - const dir_path = try fs.path.join( - allocator, - &[_][]const u8{ - search.path, - "Lib", - search.version, - "ucrt", - arch_sub_dir, - }, - ); - var found = false; - defer if (!found) allocator.free(dir_path); + result_buf.shrink(0); + try result_buf.outStream().print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir }); - var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -409,8 +395,7 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - found = true; - self.crt_dir = dir_path; + self.crt_dir = result_buf.toOwnedSlice(); return; } return error.LibCRuntimeNotFound; @@ -434,6 +419,10 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); + + var result_buf = try std.ArrayList([]const u8).init(allocator); + defer result_buf.deinit(); + const arch_sub_dir = switch (builtin.arch) { .i386 => "x86", .x86_64 => "x64", @@ -442,20 +431,11 @@ pub const LibCInstallation = struct { }; for (searches) |search| { - const dir_path = try fs.path.join( - allocator, - &[_][]const u8{ - search.path, - "Lib", - search.version, - "um", - arch_sub_dir, - }, - ); - var found = false; - defer if (!found) allocator.free(dir_path); + result_buf.shrink(0); + const stream = result_buf.outStream(); + try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir }); - var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { + var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir, error.NoDevice, @@ -470,8 +450,7 @@ pub const LibCInstallation = struct { else => return error.FileSystem, }; - found = true; - self.kernel32_lib_dir = dir_path; + self.kernel32_lib_dir = result_buf.toOwnedSlice(); return; } return error.LibCKernel32LibNotFound; @@ -489,13 +468,7 @@ pub const LibCInstallation = struct { const up1 = fs.path.dirname(msvc_lib_dir) orelse return error.LibCStdLibHeaderNotFound; const up2 = fs.path.dirname(up1) orelse return error.LibCStdLibHeaderNotFound; - const dir_path = try fs.path.join( - allocator, - &[_][]const u8{ - up2, - "include", - }, - ); + const dir_path = try fs.path.join(allocator, &[_][]const u8{ up2, "include" }); errdefer allocator.free(dir_path); var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) { diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 771765bee6..02213464e6 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -413,11 +413,11 @@ fn printErrMsgToFile( var text_buf = std.ArrayList(u8).init(allocator); defer text_buf.deinit(); - const out_stream = &text_buf.outStream(); + const out_stream = text_buf.outStream(); try parse_error.render(&tree.tokens, out_stream); const text = text_buf.span(); - const stream = &file.outStream(); + const stream = file.outStream(); try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text }); if (!color_on) return; diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index 62318a40aa..854037ec57 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -297,7 +297,6 @@ pub fn translate( }; var source_buffer = std.ArrayList(u8).init(arena); - errdefer source_buffer.deinit(); var context = Context{ .tree = tree, diff --git a/src/codegen.cpp b/src/codegen.cpp index 2c2bf7c36b..24e77e8689 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -9123,17 +9123,20 @@ static void detect_libc(CodeGen *g) { g->libc_include_dir_len = 0; g->libc_include_dir_list = heap::c_allocator.allocate(dir_count); - g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem(g->libc->include_dir, g->libc->include_dir_len)); + g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem( + g->libc->include_dir, g->libc->include_dir_len)); g->libc_include_dir_len += 1; if (want_sys_dir) { - g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem(g->libc->sys_include_dir, g->libc->sys_include_dir_len)); + g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem( + g->libc->sys_include_dir, g->libc->sys_include_dir_len)); g->libc_include_dir_len += 1; } if (want_um_and_shared_dirs != 0) { Buf *include_dir_parent = buf_alloc(); - os_path_join(buf_create_from_mem(g->libc->include_dir, g->libc->include_dir_len), buf_create_from_str(".."), include_dir_parent); + os_path_join(buf_create_from_mem(g->libc->include_dir, g->libc->include_dir_len), + buf_create_from_str(".."), include_dir_parent); Buf *buff1 = buf_alloc(); os_path_join(include_dir_parent, buf_create_from_str("um"), buff1); diff --git a/src/link.cpp b/src/link.cpp index 49bbb7c1a5..fba572de98 100644 --- a/src/link.cpp +++ b/src/link.cpp @@ -1595,7 +1595,8 @@ static const char *get_libc_crt_file(CodeGen *parent, const char *file, Stage2Pr } else { assert(parent->libc != nullptr); Buf *out_buf = buf_alloc(); - os_path_join(buf_create_from_mem(parent->libc->crt_dir, parent->libc->crt_dir_len), buf_create_from_str(file), out_buf); + os_path_join(buf_create_from_mem(parent->libc->crt_dir, parent->libc->crt_dir_len), + buf_create_from_str(file), out_buf); return buf_ptr(out_buf); } } From 2e806682f451efd26bef0486ddd980ab60de0fa1 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 1 Apr 2020 12:44:45 -0400 Subject: [PATCH 67/89] (breaking) std.Buffer => std.ArrayListSentineled(u8, 0) This new name (and the fact that it is a function returning a type) will make it more clear which use cases are better suited for ArrayList and which are better suited for ArrayListSentineled. Also for consistency with ArrayList, * `append` => `appendSlice` * `appendByte` => `append` Thanks daurnimator for pointing out the confusion of std.Buffer. --- lib/std/array_list_sentineled.zig | 224 +++++++++++++++++++++++ lib/std/buffer.zig | 218 ---------------------- lib/std/child_process.zig | 4 +- lib/std/fs.zig | 13 +- lib/std/io/in_stream.zig | 1 - lib/std/net.zig | 20 +- lib/std/std.zig | 2 +- src-self-hosted/codegen.zig | 4 +- src-self-hosted/compilation.zig | 16 +- src-self-hosted/dep_tokenizer.zig | 82 ++++----- src-self-hosted/link.zig | 8 +- src-self-hosted/package.zig | 10 +- src-self-hosted/stage2.zig | 34 ++-- src-self-hosted/translate_c.zig | 2 +- src-self-hosted/util.zig | 14 +- src-self-hosted/value.zig | 14 +- test/standalone/brace_expansion/main.zig | 32 ++-- test/tests.zig | 19 +- 18 files changed, 362 insertions(+), 355 deletions(-) create mode 100644 lib/std/array_list_sentineled.zig delete mode 100644 lib/std/buffer.zig diff --git a/lib/std/array_list_sentineled.zig b/lib/std/array_list_sentineled.zig new file mode 100644 index 0000000000..ee262b0322 --- /dev/null +++ b/lib/std/array_list_sentineled.zig @@ -0,0 +1,224 @@ +const std = @import("std.zig"); +const debug = std.debug; +const mem = std.mem; +const Allocator = mem.Allocator; +const assert = debug.assert; +const testing = std.testing; +const ArrayList = std.ArrayList; + +/// A contiguous, growable list of items in memory, with a sentinel after them. +/// The sentinel is maintained when appending, resizing, etc. +/// If you do not need a sentinel, consider using `ArrayList` instead. +pub fn ArrayListSentineled(comptime T: type, comptime sentinel: T) type { + return struct { + list: ArrayList(T), + + const Self = @This(); + + /// Must deinitialize with deinit. + pub fn init(allocator: *Allocator, m: []const T) !Self { + var self = try initSize(allocator, m.len); + mem.copy(T, self.list.items, m); + return self; + } + + /// Initialize memory to size bytes of undefined values. + /// Must deinitialize with deinit. + pub fn initSize(allocator: *Allocator, size: usize) !Self { + var self = initNull(allocator); + try self.resize(size); + return self; + } + + /// Initialize with capacity to hold at least num bytes. + /// Must deinitialize with deinit. + pub fn initCapacity(allocator: *Allocator, num: usize) !Self { + var self = Self{ .list = try ArrayList(T).initCapacity(allocator, num + 1) }; + self.list.appendAssumeCapacity(sentinel); + return self; + } + + /// Must deinitialize with deinit. + /// None of the other operations are valid until you do one of these: + /// * `replaceContents` + /// * `resize` + pub fn initNull(allocator: *Allocator) Self { + return Self{ .list = ArrayList(T).init(allocator) }; + } + + /// Must deinitialize with deinit. + pub fn initFromBuffer(buffer: Self) !Self { + return Self.init(buffer.list.allocator, buffer.span()); + } + + /// Takes ownership of the passed in slice. The slice must have been + /// allocated with `allocator`. + /// Must deinitialize with deinit. + pub fn fromOwnedSlice(allocator: *Allocator, slice: []T) !Self { + var self = Self{ .list = ArrayList(T).fromOwnedSlice(allocator, slice) }; + try self.list.append(sentinel); + return self; + } + + /// The caller owns the returned memory. The list becomes null and is safe to `deinit`. + pub fn toOwnedSlice(self: *Self) [:sentinel]T { + const allocator = self.list.allocator; + const result = self.list.toOwnedSlice(); + self.* = initNull(allocator); + return result[0 .. result.len - 1 :sentinel]; + } + + /// Only works when `T` is `u8`. + pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Self { + const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) { + error.Overflow => return error.OutOfMemory, + }; + var self = try Self.initSize(allocator, size); + assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size); + return self; + } + + pub fn deinit(self: *Self) void { + self.list.deinit(); + } + + pub fn span(self: var) @TypeOf(self.list.items[0 .. self.list.len - 1 :sentinel]) { + return self.list.span()[0..self.len() :sentinel]; + } + + pub fn shrink(self: *Self, new_len: usize) void { + assert(new_len <= self.len()); + self.list.shrink(new_len + 1); + self.list.items[self.len()] = sentinel; + } + + pub fn resize(self: *Self, new_len: usize) !void { + try self.list.resize(new_len + 1); + self.list.items[self.len()] = sentinel; + } + + pub fn isNull(self: Self) bool { + return self.list.len == 0; + } + + pub fn len(self: Self) usize { + return self.list.len - 1; + } + + pub fn capacity(self: Self) usize { + return if (self.list.items.len > 0) + self.list.items.len - 1 + else + 0; + } + + pub fn appendSlice(self: *Self, m: []const T) !void { + const old_len = self.len(); + try self.resize(old_len + m.len); + mem.copy(T, self.list.span()[old_len..], m); + } + + pub fn append(self: *Self, byte: T) !void { + const old_len = self.len(); + try self.resize(old_len + 1); + self.list.span()[old_len] = byte; + } + + pub fn eql(self: Self, m: []const T) bool { + return mem.eql(T, self.span(), m); + } + + pub fn startsWith(self: Self, m: []const T) bool { + if (self.len() < m.len) return false; + return mem.eql(T, self.list.items[0..m.len], m); + } + + pub fn endsWith(self: Self, m: []const T) bool { + const l = self.len(); + if (l < m.len) return false; + const start = l - m.len; + return mem.eql(T, self.list.items[start..l], m); + } + + pub fn replaceContents(self: *Self, m: []const T) !void { + try self.resize(m.len); + mem.copy(T, self.list.span(), m); + } + + /// Initializes an OutStream which will append to the list. + /// This function may be called only when `T` is `u8`. + pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) { + return .{ .context = self }; + } + + /// Same as `append` except it returns the number of bytes written, which is always the same + /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. + /// This function may be called only when `T` is `u8`. + pub fn appendWrite(self: *Self, m: []const u8) !usize { + try self.appendSlice(m); + return m.len; + } + }; +} + +test "simple" { + var buf = try ArrayListSentineled(u8, 0).init(testing.allocator, ""); + defer buf.deinit(); + + testing.expect(buf.len() == 0); + try buf.appendSlice("hello"); + try buf.appendSlice(" "); + try buf.appendSlice("world"); + testing.expect(buf.eql("hello world")); + testing.expect(mem.eql(u8, mem.spanZ(buf.span().ptr), buf.span())); + + var buf2 = try ArrayListSentineled(u8, 0).initFromBuffer(buf); + defer buf2.deinit(); + testing.expect(buf.eql(buf2.span())); + + testing.expect(buf.startsWith("hell")); + testing.expect(buf.endsWith("orld")); + + try buf2.resize(4); + testing.expect(buf.startsWith(buf2.span())); +} + +test "initSize" { + var buf = try ArrayListSentineled(u8, 0).initSize(testing.allocator, 3); + defer buf.deinit(); + testing.expect(buf.len() == 3); + try buf.appendSlice("hello"); + testing.expect(mem.eql(u8, buf.span()[3..], "hello")); +} + +test "initCapacity" { + var buf = try ArrayListSentineled(u8, 0).initCapacity(testing.allocator, 10); + defer buf.deinit(); + testing.expect(buf.len() == 0); + testing.expect(buf.capacity() >= 10); + const old_cap = buf.capacity(); + try buf.appendSlice("hello"); + testing.expect(buf.len() == 5); + testing.expect(buf.capacity() == old_cap); + testing.expect(mem.eql(u8, buf.span(), "hello")); +} + +test "print" { + var buf = try ArrayListSentineled(u8, 0).init(testing.allocator, ""); + defer buf.deinit(); + + try buf.outStream().print("Hello {} the {}", .{ 2, "world" }); + testing.expect(buf.eql("Hello 2 the world")); +} + +test "outStream" { + var buffer = try ArrayListSentineled(u8, 0).initSize(testing.allocator, 0); + defer buffer.deinit(); + const buf_stream = buffer.outStream(); + + const x: i32 = 42; + const y: i32 = 1234; + try buf_stream.print("x: {}\ny: {}\n", .{ x, y }); + + testing.expect(mem.eql(u8, buffer.span(), "x: 42\ny: 1234\n")); +} diff --git a/lib/std/buffer.zig b/lib/std/buffer.zig deleted file mode 100644 index 7971820770..0000000000 --- a/lib/std/buffer.zig +++ /dev/null @@ -1,218 +0,0 @@ -const std = @import("std.zig"); -const debug = std.debug; -const mem = std.mem; -const Allocator = mem.Allocator; -const assert = debug.assert; -const testing = std.testing; -const ArrayList = std.ArrayList; - -/// A buffer that allocates memory and maintains a null byte at the end. -pub const Buffer = struct { - list: ArrayList(u8), - - /// Must deinitialize with deinit. - pub fn init(allocator: *Allocator, m: []const u8) !Buffer { - var self = try initSize(allocator, m.len); - mem.copy(u8, self.list.items, m); - return self; - } - - /// Initialize memory to size bytes of undefined values. - /// Must deinitialize with deinit. - pub fn initSize(allocator: *Allocator, size: usize) !Buffer { - var self = initNull(allocator); - try self.resize(size); - return self; - } - - /// Initialize with capacity to hold at least num bytes. - /// Must deinitialize with deinit. - pub fn initCapacity(allocator: *Allocator, num: usize) !Buffer { - var self = Buffer{ .list = try ArrayList(u8).initCapacity(allocator, num + 1) }; - self.list.appendAssumeCapacity(0); - return self; - } - - /// Must deinitialize with deinit. - /// None of the other operations are valid until you do one of these: - /// * ::replaceContents - /// * ::resize - pub fn initNull(allocator: *Allocator) Buffer { - return Buffer{ .list = ArrayList(u8).init(allocator) }; - } - - /// Must deinitialize with deinit. - pub fn initFromBuffer(buffer: Buffer) !Buffer { - return Buffer.init(buffer.list.allocator, buffer.span()); - } - - /// Buffer takes ownership of the passed in slice. The slice must have been - /// allocated with `allocator`. - /// Must deinitialize with deinit. - pub fn fromOwnedSlice(allocator: *Allocator, slice: []u8) !Buffer { - var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) }; - try self.list.append(0); - return self; - } - - /// The caller owns the returned memory. The Buffer becomes null and - /// is safe to `deinit`. - pub fn toOwnedSlice(self: *Buffer) [:0]u8 { - const allocator = self.list.allocator; - const result = self.list.toOwnedSlice(); - self.* = initNull(allocator); - return result[0 .. result.len - 1 :0]; - } - - pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer { - const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) { - error.Overflow => return error.OutOfMemory, - }; - var self = try Buffer.initSize(allocator, size); - assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size); - return self; - } - - pub fn deinit(self: *Buffer) void { - self.list.deinit(); - } - - pub fn span(self: var) @TypeOf(self.list.items[0 .. self.list.len - 1 :0]) { - return self.list.span()[0..self.len() :0]; - } - - pub const toSlice = @compileError("deprecated; use span()"); - pub const toSliceConst = @compileError("deprecated; use span()"); - - pub fn shrink(self: *Buffer, new_len: usize) void { - assert(new_len <= self.len()); - self.list.shrink(new_len + 1); - self.list.items[self.len()] = 0; - } - - pub fn resize(self: *Buffer, new_len: usize) !void { - try self.list.resize(new_len + 1); - self.list.items[self.len()] = 0; - } - - pub fn isNull(self: Buffer) bool { - return self.list.len == 0; - } - - pub fn len(self: Buffer) usize { - return self.list.len - 1; - } - - pub fn capacity(self: Buffer) usize { - return if (self.list.items.len > 0) - self.list.items.len - 1 - else - 0; - } - - pub fn append(self: *Buffer, m: []const u8) !void { - const old_len = self.len(); - try self.resize(old_len + m.len); - mem.copy(u8, self.list.span()[old_len..], m); - } - - pub fn appendByte(self: *Buffer, byte: u8) !void { - const old_len = self.len(); - try self.resize(old_len + 1); - self.list.span()[old_len] = byte; - } - - pub fn eql(self: Buffer, m: []const u8) bool { - return mem.eql(u8, self.span(), m); - } - - pub fn startsWith(self: Buffer, m: []const u8) bool { - if (self.len() < m.len) return false; - return mem.eql(u8, self.list.items[0..m.len], m); - } - - pub fn endsWith(self: Buffer, m: []const u8) bool { - const l = self.len(); - if (l < m.len) return false; - const start = l - m.len; - return mem.eql(u8, self.list.items[start..l], m); - } - - pub fn replaceContents(self: *Buffer, m: []const u8) !void { - try self.resize(m.len); - mem.copy(u8, self.list.span(), m); - } - - pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) { - return .{ .context = self }; - } - - /// Same as `append` except it returns the number of bytes written, which is always the same - /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. - pub fn appendWrite(self: *Buffer, m: []const u8) !usize { - try self.append(m); - return m.len; - } -}; - -test "simple Buffer" { - var buf = try Buffer.init(testing.allocator, ""); - defer buf.deinit(); - - testing.expect(buf.len() == 0); - try buf.append("hello"); - try buf.append(" "); - try buf.append("world"); - testing.expect(buf.eql("hello world")); - testing.expect(mem.eql(u8, mem.spanZ(buf.span().ptr), buf.span())); - - var buf2 = try Buffer.initFromBuffer(buf); - defer buf2.deinit(); - testing.expect(buf.eql(buf2.span())); - - testing.expect(buf.startsWith("hell")); - testing.expect(buf.endsWith("orld")); - - try buf2.resize(4); - testing.expect(buf.startsWith(buf2.span())); -} - -test "Buffer.initSize" { - var buf = try Buffer.initSize(testing.allocator, 3); - defer buf.deinit(); - testing.expect(buf.len() == 3); - try buf.append("hello"); - testing.expect(mem.eql(u8, buf.span()[3..], "hello")); -} - -test "Buffer.initCapacity" { - var buf = try Buffer.initCapacity(testing.allocator, 10); - defer buf.deinit(); - testing.expect(buf.len() == 0); - testing.expect(buf.capacity() >= 10); - const old_cap = buf.capacity(); - try buf.append("hello"); - testing.expect(buf.len() == 5); - testing.expect(buf.capacity() == old_cap); - testing.expect(mem.eql(u8, buf.span(), "hello")); -} - -test "Buffer.print" { - var buf = try Buffer.init(testing.allocator, ""); - defer buf.deinit(); - - try buf.outStream().print("Hello {} the {}", .{ 2, "world" }); - testing.expect(buf.eql("Hello 2 the world")); -} - -test "Buffer.outStream" { - var buffer = try Buffer.initSize(testing.allocator, 0); - defer buffer.deinit(); - const buf_stream = buffer.outStream(); - - const x: i32 = 42; - const y: i32 = 1234; - try buf_stream.print("x: {}\ny: {}\n", .{ x, y }); - - testing.expect(mem.eql(u8, buffer.span(), "x: 42\ny: 1234\n")); -} diff --git a/lib/std/child_process.zig b/lib/std/child_process.zig index 0c24af2d85..e1c489bf05 100644 --- a/lib/std/child_process.zig +++ b/lib/std/child_process.zig @@ -10,7 +10,7 @@ const windows = os.windows; const mem = std.mem; const debug = std.debug; const BufMap = std.BufMap; -const Buffer = std.Buffer; +const ArrayListSentineled = std.ArrayListSentineled; const builtin = @import("builtin"); const Os = builtin.Os; const TailQueue = std.TailQueue; @@ -758,7 +758,7 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1 /// Caller must dealloc. fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 { - var buf = try Buffer.initSize(allocator, 0); + var buf = try ArrayListSentineled(u8, 0).initSize(allocator, 0); defer buf.deinit(); const buf_stream = buf.outStream(); diff --git a/lib/std/fs.zig b/lib/std/fs.zig index 95f1b08bd9..0eeb1758f2 100644 --- a/lib/std/fs.zig +++ b/lib/std/fs.zig @@ -1416,13 +1416,14 @@ pub const readLinkC = @compileError("deprecated; use Dir.readLinkZ or readLinkAb pub const Walker = struct { stack: std.ArrayList(StackItem), - name_buffer: std.Buffer, + name_buffer: std.ArrayList(u8), pub const Entry = struct { /// The containing directory. This can be used to operate directly on `basename` /// rather than `path`, avoiding `error.NameTooLong` for deeply nested paths. /// The directory remains open until `next` or `deinit` is called. dir: Dir, + /// TODO make this null terminated for API convenience basename: []const u8, path: []const u8, @@ -1445,8 +1446,8 @@ pub const Walker = struct { const dirname_len = top.dirname_len; if (try top.dir_it.next()) |base| { self.name_buffer.shrink(dirname_len); - try self.name_buffer.appendByte(path.sep); - try self.name_buffer.append(base.name); + try self.name_buffer.append(path.sep); + try self.name_buffer.appendSlice(base.name); if (base.kind == .Directory) { var new_dir = top.dir_it.dir.openDir(base.name, .{ .iterate = true }) catch |err| switch (err) { error.NameTooLong => unreachable, // no path sep in base.name @@ -1456,7 +1457,7 @@ pub const Walker = struct { errdefer new_dir.close(); try self.stack.append(StackItem{ .dir_it = new_dir.iterate(), - .dirname_len = self.name_buffer.len(), + .dirname_len = self.name_buffer.len, }); } } @@ -1489,9 +1490,11 @@ pub fn walkPath(allocator: *Allocator, dir_path: []const u8) !Walker { var dir = try cwd().openDir(dir_path, .{ .iterate = true }); errdefer dir.close(); - var name_buffer = try std.Buffer.init(allocator, dir_path); + var name_buffer = std.ArrayList(u8).init(allocator); errdefer name_buffer.deinit(); + try name_buffer.appendSlice(dir_path); + var walker = Walker{ .stack = std.ArrayList(Walker.StackItem).init(allocator), .name_buffer = name_buffer, diff --git a/lib/std/io/in_stream.zig b/lib/std/io/in_stream.zig index 045b0daae0..340995198f 100644 --- a/lib/std/io/in_stream.zig +++ b/lib/std/io/in_stream.zig @@ -3,7 +3,6 @@ const builtin = std.builtin; const math = std.math; const assert = std.debug.assert; const mem = std.mem; -const Buffer = std.Buffer; const testing = std.testing; pub fn InStream( diff --git a/lib/std/net.zig b/lib/std/net.zig index 5b39b8cbd4..0f7118c331 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -504,7 +504,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !* var lookup_addrs = std.ArrayList(LookupAddr).init(allocator); defer lookup_addrs.deinit(); - var canon = std.Buffer.initNull(arena); + var canon = std.ArrayListSentineled(u8, 0).initNull(arena); defer canon.deinit(); try linuxLookupName(&lookup_addrs, &canon, name, family, flags, port); @@ -539,7 +539,7 @@ const DAS_ORDER_SHIFT = 0; fn linuxLookupName( addrs: *std.ArrayList(LookupAddr), - canon: *std.Buffer, + canon: *std.ArrayListSentineled(u8, 0), opt_name: ?[]const u8, family: os.sa_family_t, flags: u32, @@ -798,7 +798,7 @@ fn linuxLookupNameFromNull( fn linuxLookupNameFromHosts( addrs: *std.ArrayList(LookupAddr), - canon: *std.Buffer, + canon: *std.ArrayListSentineled(u8, 0), name: []const u8, family: os.sa_family_t, port: u16, @@ -868,7 +868,7 @@ pub fn isValidHostName(hostname: []const u8) bool { fn linuxLookupNameFromDnsSearch( addrs: *std.ArrayList(LookupAddr), - canon: *std.Buffer, + canon: *std.ArrayListSentineled(u8, 0), name: []const u8, family: os.sa_family_t, port: u16, @@ -901,12 +901,12 @@ fn linuxLookupNameFromDnsSearch( // the full requested name to name_from_dns. try canon.resize(canon_name.len); mem.copy(u8, canon.span(), canon_name); - try canon.appendByte('.'); + try canon.append('.'); var tok_it = mem.tokenize(search, " \t"); while (tok_it.next()) |tok| { canon.shrink(canon_name.len + 1); - try canon.append(tok); + try canon.appendSlice(tok); try linuxLookupNameFromDns(addrs, canon, canon.span(), family, rc, port); if (addrs.len != 0) return; } @@ -917,13 +917,13 @@ fn linuxLookupNameFromDnsSearch( const dpc_ctx = struct { addrs: *std.ArrayList(LookupAddr), - canon: *std.Buffer, + canon: *std.ArrayListSentineled(u8, 0), port: u16, }; fn linuxLookupNameFromDns( addrs: *std.ArrayList(LookupAddr), - canon: *std.Buffer, + canon: *std.ArrayListSentineled(u8, 0), name: []const u8, family: os.sa_family_t, rc: ResolvConf, @@ -978,7 +978,7 @@ const ResolvConf = struct { attempts: u32, ndots: u32, timeout: u32, - search: std.Buffer, + search: std.ArrayListSentineled(u8, 0), ns: std.ArrayList(LookupAddr), fn deinit(rc: *ResolvConf) void { @@ -993,7 +993,7 @@ const ResolvConf = struct { fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void { rc.* = ResolvConf{ .ns = std.ArrayList(LookupAddr).init(allocator), - .search = std.Buffer.initNull(allocator), + .search = std.ArrayListSentineled(u8, 0).initNull(allocator), .ndots = 1, .timeout = 5, .attempts = 2, diff --git a/lib/std/std.zig b/lib/std/std.zig index 9277370ca6..4ea8e7170b 100644 --- a/lib/std/std.zig +++ b/lib/std/std.zig @@ -1,10 +1,10 @@ pub const AlignedArrayList = @import("array_list.zig").AlignedArrayList; pub const ArrayList = @import("array_list.zig").ArrayList; +pub const ArrayListSentineled = @import("array_list_sentineled.zig").ArrayListSentineled; pub const AutoHashMap = @import("hash_map.zig").AutoHashMap; pub const BloomFilter = @import("bloom_filter.zig").BloomFilter; pub const BufMap = @import("buf_map.zig").BufMap; pub const BufSet = @import("buf_set.zig").BufSet; -pub const Buffer = @import("buffer.zig").Buffer; pub const ChildProcess = @import("child_process.zig").ChildProcess; pub const DynLib = @import("dynamic_library.zig").DynLib; pub const HashMap = @import("hash_map.zig").HashMap; diff --git a/src-self-hosted/codegen.zig b/src-self-hosted/codegen.zig index e10d66d1f6..585ba6c51a 100644 --- a/src-self-hosted/codegen.zig +++ b/src-self-hosted/codegen.zig @@ -45,7 +45,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) // Don't use ZIG_VERSION_STRING here. LLVM misparses it when it includes // the git revision. - const producer = try std.Buffer.allocPrint(&code.arena.allocator, "zig {}.{}.{}", .{ + const producer = try std.fmt.allocPrintZ(&code.arena.allocator, "zig {}.{}.{}", .{ @as(u32, c.ZIG_VERSION_MAJOR), @as(u32, c.ZIG_VERSION_MINOR), @as(u32, c.ZIG_VERSION_PATCH), @@ -62,7 +62,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code) dibuilder, DW.LANG_C99, compile_unit_file, - producer.span(), + producer, is_optimized, flags, runtime_version, diff --git a/src-self-hosted/compilation.zig b/src-self-hosted/compilation.zig index 5e2b9ad899..8f9fe9ebc2 100644 --- a/src-self-hosted/compilation.zig +++ b/src-self-hosted/compilation.zig @@ -2,7 +2,7 @@ const std = @import("std"); const io = std.io; const mem = std.mem; const Allocator = mem.Allocator; -const Buffer = std.Buffer; +const ArrayListSentineled = std.ArrayListSentineled; const llvm = @import("llvm.zig"); const c = @import("c.zig"); const builtin = std.builtin; @@ -123,8 +123,8 @@ pub const LlvmHandle = struct { pub const Compilation = struct { zig_compiler: *ZigCompiler, - name: Buffer, - llvm_triple: Buffer, + name: ArrayListSentineled(u8, 0), + llvm_triple: ArrayListSentineled(u8, 0), root_src_path: ?[]const u8, target: std.Target, llvm_target: *llvm.Target, @@ -444,7 +444,7 @@ pub const Compilation = struct { comp.arena_allocator.deinit(); } - comp.name = try Buffer.init(comp.arena(), name); + comp.name = try ArrayListSentineled(u8, 0).init(comp.arena(), name); comp.llvm_triple = try util.getLLVMTriple(comp.arena(), target); comp.llvm_target = try util.llvmTargetFromTriple(comp.llvm_triple); comp.zig_std_dir = try fs.path.join(comp.arena(), &[_][]const u8{ zig_lib_dir, "std" }); @@ -1151,7 +1151,7 @@ pub const Compilation = struct { /// If the temporary directory for this compilation has not been created, it creates it. /// Then it creates a random file name in that dir and returns it. - pub fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !Buffer { + pub fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !ArrayListSentineled(u8, 0) { const tmp_dir = try self.getTmpDir(); const file_prefix = self.getRandomFileName(); @@ -1161,7 +1161,7 @@ pub const Compilation = struct { const full_path = try fs.path.join(self.gpa(), &[_][]const u8{ tmp_dir, file_name[0..] }); errdefer self.gpa().free(full_path); - return Buffer.fromOwnedSlice(self.gpa(), full_path); + return ArrayListSentineled(u8, 0).fromOwnedSlice(self.gpa(), full_path); } /// If the temporary directory for this Compilation has not been created, creates it. @@ -1279,7 +1279,7 @@ fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void { const fn_type = try analyzeFnType(comp, tree_scope, fn_decl.base.parent_scope, fn_decl.fn_proto); defer fn_type.base.base.deref(comp); - var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name); + var symbol_name = try std.ArrayListSentineled(u8, 0).init(comp.gpa(), fn_decl.base.name); var symbol_name_consumed = false; errdefer if (!symbol_name_consumed) symbol_name.deinit(); @@ -1426,7 +1426,7 @@ fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void { ); defer fn_type.base.base.deref(comp); - var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name); + var symbol_name = try std.ArrayListSentineled(u8, 0).init(comp.gpa(), fn_decl.base.name); var symbol_name_consumed = false; defer if (!symbol_name_consumed) symbol_name.deinit(); diff --git a/src-self-hosted/dep_tokenizer.zig b/src-self-hosted/dep_tokenizer.zig index 6eba0c759c..cad12834a7 100644 --- a/src-self-hosted/dep_tokenizer.zig +++ b/src-self-hosted/dep_tokenizer.zig @@ -33,7 +33,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - self.state = State{ .target = try std.Buffer.initSize(&self.arena.allocator, 0) }; + self.state = State{ .target = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0) }; }, }, .target => |*target| switch (char) { @@ -53,7 +53,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - try target.appendByte(char); + try target.append(char); break; // advance }, }, @@ -62,24 +62,24 @@ pub const Tokenizer = struct { return self.errorIllegalChar(self.index, char, "bad target escape", .{}); }, ' ', '#', '\\' => { - try target.appendByte(char); + try target.append(char); self.state = State{ .target = target.* }; break; // advance }, '$' => { - try target.append(self.bytes[self.index - 1 .. self.index]); + try target.appendSlice(self.bytes[self.index - 1 .. self.index]); self.state = State{ .target_dollar_sign = target.* }; break; // advance }, else => { - try target.append(self.bytes[self.index - 1 .. self.index + 1]); + try target.appendSlice(self.bytes[self.index - 1 .. self.index + 1]); self.state = State{ .target = target.* }; break; // advance }, }, .target_dollar_sign => |*target| switch (char) { '$' => { - try target.appendByte(char); + try target.append(char); self.state = State{ .target = target.* }; break; // advance }, @@ -125,7 +125,7 @@ pub const Tokenizer = struct { continue; }, else => { - try target.append(self.bytes[self.index - 2 .. self.index + 1]); + try target.appendSlice(self.bytes[self.index - 2 .. self.index + 1]); self.state = State{ .target = target.* }; break; }, @@ -144,11 +144,11 @@ pub const Tokenizer = struct { break; // advance }, '"' => { - self.state = State{ .prereq_quote = try std.Buffer.initSize(&self.arena.allocator, 0) }; + self.state = State{ .prereq_quote = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0) }; break; // advance }, else => { - self.state = State{ .prereq = try std.Buffer.initSize(&self.arena.allocator, 0) }; + self.state = State{ .prereq = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0) }; }, }, .rhs_continuation => switch (char) { @@ -181,7 +181,7 @@ pub const Tokenizer = struct { return Token{ .id = .prereq, .bytes = bytes }; }, else => { - try prereq.appendByte(char); + try prereq.append(char); break; // advance }, }, @@ -201,7 +201,7 @@ pub const Tokenizer = struct { break; // advance }, else => { - try prereq.appendByte(char); + try prereq.append(char); break; // advance }, }, @@ -218,7 +218,7 @@ pub const Tokenizer = struct { }, else => { // not continuation - try prereq.append(self.bytes[self.index - 1 .. self.index + 1]); + try prereq.appendSlice(self.bytes[self.index - 1 .. self.index + 1]); self.state = State{ .prereq = prereq.* }; break; // advance }, @@ -300,25 +300,25 @@ pub const Tokenizer = struct { } fn errorf(self: *Tokenizer, comptime fmt: []const u8, args: var) Error { - self.error_text = (try std.Buffer.allocPrint(&self.arena.allocator, fmt, args)).span(); + self.error_text = try std.fmt.allocPrintZ(&self.arena.allocator, fmt, args); return Error.InvalidInput; } fn errorPosition(self: *Tokenizer, position: usize, bytes: []const u8, comptime fmt: []const u8, args: var) Error { - var buffer = try std.Buffer.initSize(&self.arena.allocator, 0); + var buffer = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0); try buffer.outStream().print(fmt, args); - try buffer.append(" '"); - var out = makeOutput(std.Buffer.append, &buffer); + try buffer.appendSlice(" '"); + var out = makeOutput(std.ArrayListSentineled(u8, 0).appendSlice, &buffer); try printCharValues(&out, bytes); - try buffer.append("'"); + try buffer.appendSlice("'"); try buffer.outStream().print(" at position {}", .{position - (bytes.len - 1)}); self.error_text = buffer.span(); return Error.InvalidInput; } fn errorIllegalChar(self: *Tokenizer, position: usize, char: u8, comptime fmt: []const u8, args: var) Error { - var buffer = try std.Buffer.initSize(&self.arena.allocator, 0); - try buffer.append("illegal char "); + var buffer = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0); + try buffer.appendSlice("illegal char "); try printUnderstandableChar(&buffer, char); try buffer.outStream().print(" at position {}", .{position}); if (fmt.len != 0) try buffer.outStream().print(": " ++ fmt, args); @@ -333,18 +333,18 @@ pub const Tokenizer = struct { const State = union(enum) { lhs: void, - target: std.Buffer, - target_reverse_solidus: std.Buffer, - target_dollar_sign: std.Buffer, - target_colon: std.Buffer, - target_colon_reverse_solidus: std.Buffer, + target: std.ArrayListSentineled(u8, 0), + target_reverse_solidus: std.ArrayListSentineled(u8, 0), + target_dollar_sign: std.ArrayListSentineled(u8, 0), + target_colon: std.ArrayListSentineled(u8, 0), + target_colon_reverse_solidus: std.ArrayListSentineled(u8, 0), rhs: void, rhs_continuation: void, rhs_continuation_linefeed: void, - prereq_quote: std.Buffer, - prereq: std.Buffer, - prereq_continuation: std.Buffer, - prereq_continuation_linefeed: std.Buffer, + prereq_quote: std.ArrayListSentineled(u8, 0), + prereq: std.ArrayListSentineled(u8, 0), + prereq_continuation: std.ArrayListSentineled(u8, 0), + prereq_continuation_linefeed: std.ArrayListSentineled(u8, 0), }; const Token = struct { @@ -841,28 +841,28 @@ fn depTokenizer(input: []const u8, expect: []const u8) !void { defer arena_allocator.deinit(); var it = Tokenizer.init(arena, input); - var buffer = try std.Buffer.initSize(arena, 0); + var buffer = try std.ArrayListSentineled(u8, 0).initSize(arena, 0); var i: usize = 0; while (true) { const r = it.next() catch |err| { switch (err) { Tokenizer.Error.InvalidInput => { - if (i != 0) try buffer.append("\n"); - try buffer.append("ERROR: "); - try buffer.append(it.error_text); + if (i != 0) try buffer.appendSlice("\n"); + try buffer.appendSlice("ERROR: "); + try buffer.appendSlice(it.error_text); }, else => return err, } break; }; const token = r orelse break; - if (i != 0) try buffer.append("\n"); - try buffer.append(@tagName(token.id)); - try buffer.append(" = {"); + if (i != 0) try buffer.appendSlice("\n"); + try buffer.appendSlice(@tagName(token.id)); + try buffer.appendSlice(" = {"); for (token.bytes) |b| { - try buffer.appendByte(printable_char_tab[b]); + try buffer.append(printable_char_tab[b]); } - try buffer.append("}"); + try buffer.appendSlice("}"); i += 1; } const got: []const u8 = buffer.span(); @@ -995,13 +995,13 @@ fn printCharValues(out: var, bytes: []const u8) !void { } } -fn printUnderstandableChar(buffer: *std.Buffer, char: u8) !void { +fn printUnderstandableChar(buffer: *std.ArrayListSentineled(u8, 0), char: u8) !void { if (!std.ascii.isPrint(char) or char == ' ') { try buffer.outStream().print("\\x{X:2}", .{char}); } else { - try buffer.append("'"); - try buffer.appendByte(printable_char_tab[char]); - try buffer.append("'"); + try buffer.appendSlice("'"); + try buffer.append(printable_char_tab[char]); + try buffer.appendSlice("'"); } } diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index ee2ef53d22..013a6248cc 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -15,10 +15,10 @@ const Context = struct { link_in_crt: bool, link_err: error{OutOfMemory}!void, - link_msg: std.Buffer, + link_msg: std.ArrayListSentineled(u8, 0), libc: *LibCInstallation, - out_file_path: std.Buffer, + out_file_path: std.ArrayListSentineled(u8, 0), }; pub fn link(comp: *Compilation) !void { @@ -34,9 +34,9 @@ pub fn link(comp: *Compilation) !void { }; defer ctx.arena.deinit(); ctx.args = std.ArrayList([*:0]const u8).init(&ctx.arena.allocator); - ctx.link_msg = std.Buffer.initNull(&ctx.arena.allocator); + ctx.link_msg = std.ArrayListSentineled(u8, 0).initNull(&ctx.arena.allocator); - ctx.out_file_path = try std.Buffer.init(&ctx.arena.allocator, comp.name.span()); + ctx.out_file_path = try std.ArrayListSentineled(u8, 0).init(&ctx.arena.allocator, comp.name.span()); switch (comp.kind) { .Exe => { try ctx.out_file_path.append(comp.target.exeFileExt()); diff --git a/src-self-hosted/package.zig b/src-self-hosted/package.zig index c8d46c7719..3111555878 100644 --- a/src-self-hosted/package.zig +++ b/src-self-hosted/package.zig @@ -1,11 +1,11 @@ const std = @import("std"); const mem = std.mem; const assert = std.debug.assert; -const Buffer = std.Buffer; +const ArrayListSentineled = std.ArrayListSentineled; pub const Package = struct { - root_src_dir: Buffer, - root_src_path: Buffer, + root_src_dir: ArrayListSentineled(u8, 0), + root_src_path: ArrayListSentineled(u8, 0), /// relative to root_src_dir table: Table, @@ -17,8 +17,8 @@ pub const Package = struct { pub fn create(allocator: *mem.Allocator, root_src_dir: []const u8, root_src_path: []const u8) !*Package { const ptr = try allocator.create(Package); ptr.* = Package{ - .root_src_dir = try Buffer.init(allocator, root_src_dir), - .root_src_path = try Buffer.init(allocator, root_src_path), + .root_src_dir = try ArrayListSentineled(u8, 0).init(allocator, root_src_dir), + .root_src_path = try ArrayListSentineled(u8, 0).init(allocator, root_src_path), .table = Table.init(allocator), }; return ptr; diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 02213464e6..8dd2ee876d 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -8,7 +8,7 @@ const fs = std.fs; const process = std.process; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; -const Buffer = std.Buffer; +const ArrayListSentineled = std.ArrayListSentineled; const Target = std.Target; const CrossTarget = std.zig.CrossTarget; const self_hosted_main = @import("main.zig"); @@ -449,7 +449,7 @@ export fn stage2_DepTokenizer_deinit(self: *stage2_DepTokenizer) void { export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextResult { const otoken = self.handle.next() catch { - const textz = std.Buffer.init(&self.handle.arena.allocator, self.handle.error_text) catch @panic("failed to create .d tokenizer error text"); + const textz = std.ArrayListSentineled(u8, 0).init(&self.handle.arena.allocator, self.handle.error_text) catch @panic("failed to create .d tokenizer error text"); return stage2_DepNextResult{ .type_id = .error_, .textz = textz.span().ptr, @@ -461,7 +461,7 @@ export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextRes .textz = undefined, }; }; - const textz = std.Buffer.init(&self.handle.arena.allocator, token.bytes) catch @panic("failed to create .d tokenizer token text"); + const textz = std.ArrayListSentineled(u8, 0).init(&self.handle.arena.allocator, token.bytes) catch @panic("failed to create .d tokenizer token text"); return stage2_DepNextResult{ .type_id = switch (token.id) { .target => .target, @@ -924,14 +924,14 @@ const Stage2Target = extern struct { var dynamic_linker: ?[*:0]u8 = null; const target = try crossTargetToTarget(cross_target, &dynamic_linker); - var cache_hash = try std.Buffer.allocPrint(allocator, "{}\n{}\n", .{ + var cache_hash = try std.ArrayListSentineled(u8, 0).allocPrint(allocator, "{}\n{}\n", .{ target.cpu.model.name, target.cpu.features.asBytes(), }); defer cache_hash.deinit(); const generic_arch_name = target.cpu.arch.genericName(); - var cpu_builtin_str_buffer = try std.Buffer.allocPrint(allocator, + var cpu_builtin_str_buffer = try std.ArrayListSentineled(u8, 0).allocPrint(allocator, \\Cpu{{ \\ .arch = .{}, \\ .model = &Target.{}.cpu.{}, @@ -946,7 +946,7 @@ const Stage2Target = extern struct { }); defer cpu_builtin_str_buffer.deinit(); - var llvm_features_buffer = try std.Buffer.initSize(allocator, 0); + var llvm_features_buffer = try std.ArrayListSentineled(u8, 0).initSize(allocator, 0); defer llvm_features_buffer.deinit(); // Unfortunately we have to do the work twice, because Clang does not support @@ -961,17 +961,17 @@ const Stage2Target = extern struct { if (feature.llvm_name) |llvm_name| { const plus_or_minus = "-+"[@boolToInt(is_enabled)]; - try llvm_features_buffer.appendByte(plus_or_minus); - try llvm_features_buffer.append(llvm_name); - try llvm_features_buffer.append(","); + try llvm_features_buffer.append(plus_or_minus); + try llvm_features_buffer.appendSlice(llvm_name); + try llvm_features_buffer.appendSlice(","); } if (is_enabled) { // TODO some kind of "zig identifier escape" function rather than // unconditionally using @"" syntax - try cpu_builtin_str_buffer.append(" .@\""); - try cpu_builtin_str_buffer.append(feature.name); - try cpu_builtin_str_buffer.append("\",\n"); + try cpu_builtin_str_buffer.appendSlice(" .@\""); + try cpu_builtin_str_buffer.appendSlice(feature.name); + try cpu_builtin_str_buffer.appendSlice("\",\n"); } } @@ -990,7 +990,7 @@ const Stage2Target = extern struct { }, } - try cpu_builtin_str_buffer.append( + try cpu_builtin_str_buffer.appendSlice( \\ }), \\}; \\ @@ -999,7 +999,7 @@ const Stage2Target = extern struct { assert(mem.endsWith(u8, llvm_features_buffer.span(), ",")); llvm_features_buffer.shrink(llvm_features_buffer.len() - 1); - var os_builtin_str_buffer = try std.Buffer.allocPrint(allocator, + var os_builtin_str_buffer = try std.ArrayListSentineled(u8, 0).allocPrint(allocator, \\Os{{ \\ .tag = .{}, \\ .version_range = .{{ @@ -1042,7 +1042,7 @@ const Stage2Target = extern struct { .emscripten, .uefi, .other, - => try os_builtin_str_buffer.append(" .none = {} }\n"), + => try os_builtin_str_buffer.appendSlice(" .none = {} }\n"), .freebsd, .macosx, @@ -1118,9 +1118,9 @@ const Stage2Target = extern struct { @tagName(target.os.version_range.windows.max), }), } - try os_builtin_str_buffer.append("};\n"); + try os_builtin_str_buffer.appendSlice("};\n"); - try cache_hash.append( + try cache_hash.appendSlice( os_builtin_str_buffer.span()[os_builtin_str_ver_start_index..os_builtin_str_buffer.len()], ); diff --git a/src-self-hosted/translate_c.zig b/src-self-hosted/translate_c.zig index 854037ec57..6ba7fc8ca1 100644 --- a/src-self-hosted/translate_c.zig +++ b/src-self-hosted/translate_c.zig @@ -275,7 +275,7 @@ pub fn translate( const tree = try tree_arena.allocator.create(ast.Tree); tree.* = ast.Tree{ - .source = undefined, // need to use Buffer.toOwnedSlice later + .source = undefined, // need to use toOwnedSlice later .root_node = undefined, .arena_allocator = tree_arena, .tokens = undefined, // can't reference the allocator yet diff --git a/src-self-hosted/util.zig b/src-self-hosted/util.zig index 4699b453ef..6585fd7c6f 100644 --- a/src-self-hosted/util.zig +++ b/src-self-hosted/util.zig @@ -16,11 +16,11 @@ pub fn getDarwinArchString(self: Target) [:0]const u8 { } } -pub fn llvmTargetFromTriple(triple: std.Buffer) !*llvm.Target { +pub fn llvmTargetFromTriple(triple: [:0]const u8) !*llvm.Target { var result: *llvm.Target = undefined; var err_msg: [*:0]u8 = undefined; - if (llvm.GetTargetFromTriple(triple.span(), &result, &err_msg) != 0) { - std.debug.warn("triple: {s} error: {s}\n", .{ triple.span(), err_msg }); + if (llvm.GetTargetFromTriple(triple, &result, &err_msg) != 0) { + std.debug.warn("triple: {s} error: {s}\n", .{ triple, err_msg }); return error.UnsupportedTarget; } return result; @@ -34,14 +34,14 @@ pub fn initializeAllTargets() void { llvm.InitializeAllAsmParsers(); } -pub fn getLLVMTriple(allocator: *std.mem.Allocator, target: std.Target) !std.Buffer { - var result = try std.Buffer.initSize(allocator, 0); - errdefer result.deinit(); +pub fn getLLVMTriple(allocator: *std.mem.Allocator, target: std.Target) ![:0]u8 { + var result = try std.ArrayListSentineled(u8, 0).initSize(allocator, 0); + defer result.deinit(); try result.outStream().print( "{}-unknown-{}-{}", .{ @tagName(target.cpu.arch), @tagName(target.os.tag), @tagName(target.abi) }, ); - return result; + return result.toOwnedSlice(); } diff --git a/src-self-hosted/value.zig b/src-self-hosted/value.zig index c2d91eecab..c35289e238 100644 --- a/src-self-hosted/value.zig +++ b/src-self-hosted/value.zig @@ -3,7 +3,7 @@ const Scope = @import("scope.zig").Scope; const Compilation = @import("compilation.zig").Compilation; const ObjectFile = @import("codegen.zig").ObjectFile; const llvm = @import("llvm.zig"); -const Buffer = std.Buffer; +const ArrayListSentineled = std.ArrayListSentineled; const assert = std.debug.assert; /// Values are ref-counted, heap-allocated, and copy-on-write @@ -131,9 +131,9 @@ pub const Value = struct { /// The main external name that is used in the .o file. /// TODO https://github.com/ziglang/zig/issues/265 - symbol_name: Buffer, + symbol_name: ArrayListSentineled(u8, 0), - pub fn create(comp: *Compilation, fn_type: *Type.Fn, symbol_name: Buffer) !*FnProto { + pub fn create(comp: *Compilation, fn_type: *Type.Fn, symbol_name: ArrayListSentineled(u8, 0)) !*FnProto { const self = try comp.gpa().create(FnProto); self.* = FnProto{ .base = Value{ @@ -171,7 +171,7 @@ pub const Value = struct { /// The main external name that is used in the .o file. /// TODO https://github.com/ziglang/zig/issues/265 - symbol_name: Buffer, + symbol_name: ArrayListSentineled(u8, 0), /// parent should be the top level decls or container decls fndef_scope: *Scope.FnDef, @@ -183,13 +183,13 @@ pub const Value = struct { block_scope: ?*Scope.Block, /// Path to the object file that contains this function - containing_object: Buffer, + containing_object: ArrayListSentineled(u8, 0), link_set_node: *std.TailQueue(?*Value.Fn).Node, /// Creates a Fn value with 1 ref /// Takes ownership of symbol_name - pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: Buffer) !*Fn { + pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: ArrayListSentineled(u8, 0)) !*Fn { const link_set_node = try comp.gpa().create(Compilation.FnLinkSet.Node); link_set_node.* = Compilation.FnLinkSet.Node{ .data = null, @@ -209,7 +209,7 @@ pub const Value = struct { .child_scope = &fndef_scope.base, .block_scope = null, .symbol_name = symbol_name, - .containing_object = Buffer.initNull(comp.gpa()), + .containing_object = ArrayListSentineled(u8, 0).initNull(comp.gpa()), .link_set_node = link_set_node, }; fn_type.base.base.ref(); diff --git a/test/standalone/brace_expansion/main.zig b/test/standalone/brace_expansion/main.zig index 603eeb43e1..411f2bfaf6 100644 --- a/test/standalone/brace_expansion/main.zig +++ b/test/standalone/brace_expansion/main.zig @@ -4,7 +4,7 @@ const mem = std.mem; const debug = std.debug; const assert = debug.assert; const testing = std.testing; -const Buffer = std.Buffer; +const ArrayListSentineled = std.ArrayListSentineled; const ArrayList = std.ArrayList; const maxInt = std.math.maxInt; @@ -111,7 +111,7 @@ fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node { } } -fn expandString(input: []const u8, output: *Buffer) !void { +fn expandString(input: []const u8, output: *ArrayListSentineled(u8, 0)) !void { const tokens = try tokenize(input); if (tokens.len == 1) { return output.resize(0); @@ -125,7 +125,7 @@ fn expandString(input: []const u8, output: *Buffer) !void { else => return error.InvalidInput, } - var result_list = ArrayList(Buffer).init(global_allocator); + var result_list = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); defer result_list.deinit(); try expandNode(root, &result_list); @@ -133,41 +133,41 @@ fn expandString(input: []const u8, output: *Buffer) !void { try output.resize(0); for (result_list.span()) |buf, i| { if (i != 0) { - try output.appendByte(' '); + try output.append(' '); } - try output.append(buf.span()); + try output.appendSlice(buf.span()); } } const ExpandNodeError = error{OutOfMemory}; -fn expandNode(node: Node, output: *ArrayList(Buffer)) ExpandNodeError!void { +fn expandNode(node: Node, output: *ArrayList(ArrayListSentineled(u8, 0))) ExpandNodeError!void { assert(output.len == 0); switch (node) { Node.Scalar => |scalar| { - try output.append(try Buffer.init(global_allocator, scalar)); + try output.append(try ArrayListSentineled(u8, 0).init(global_allocator, scalar)); }, Node.Combine => |pair| { const a_node = pair[0]; const b_node = pair[1]; - var child_list_a = ArrayList(Buffer).init(global_allocator); + var child_list_a = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); try expandNode(a_node, &child_list_a); - var child_list_b = ArrayList(Buffer).init(global_allocator); + var child_list_b = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); try expandNode(b_node, &child_list_b); for (child_list_a.span()) |buf_a| { for (child_list_b.span()) |buf_b| { - var combined_buf = try Buffer.initFromBuffer(buf_a); - try combined_buf.append(buf_b.span()); + var combined_buf = try ArrayListSentineled(u8, 0).initFromBuffer(buf_a); + try combined_buf.appendSlice(buf_b.span()); try output.append(combined_buf); } } }, Node.List => |list| { for (list.span()) |child_node| { - var child_list = ArrayList(Buffer).init(global_allocator); + var child_list = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); try expandNode(child_node, &child_list); for (child_list.span()) |buf| { @@ -187,13 +187,13 @@ pub fn main() !void { global_allocator = &arena.allocator; - var stdin_buf = try Buffer.initSize(global_allocator, 0); + var stdin_buf = try ArrayListSentineled(u8, 0).initSize(global_allocator, 0); defer stdin_buf.deinit(); var stdin_adapter = stdin_file.inStream(); try stdin_adapter.stream.readAllBuffer(&stdin_buf, maxInt(usize)); - var result_buf = try Buffer.initSize(global_allocator, 0); + var result_buf = try ArrayListSentineled(u8, 0).initSize(global_allocator, 0); defer result_buf.deinit(); try expandString(stdin_buf.span(), &result_buf); @@ -218,7 +218,7 @@ test "invalid inputs" { } fn expectError(test_input: []const u8, expected_err: anyerror) void { - var output_buf = Buffer.initSize(global_allocator, 0) catch unreachable; + var output_buf = ArrayListSentineled(u8, 0).initSize(global_allocator, 0) catch unreachable; defer output_buf.deinit(); testing.expectError(expected_err, expandString(test_input, &output_buf)); @@ -251,7 +251,7 @@ test "valid inputs" { } fn expectExpansion(test_input: []const u8, expected_result: []const u8) void { - var result = Buffer.initSize(global_allocator, 0) catch unreachable; + var result = ArrayListSentineled(u8, 0).initSize(global_allocator, 0) catch unreachable; defer result.deinit(); expandString(test_input, &result) catch unreachable; diff --git a/test/tests.zig b/test/tests.zig index 28459d84c1..7f3e55ec7a 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -4,7 +4,6 @@ const debug = std.debug; const warn = debug.warn; const build = std.build; const CrossTarget = std.zig.CrossTarget; -const Buffer = std.Buffer; const io = std.io; const fs = std.fs; const mem = std.mem; @@ -640,7 +639,7 @@ pub const StackTracesContext = struct { // - replace address with symbolic string // - skip empty lines const got: []const u8 = got_result: { - var buf = try Buffer.initSize(b.allocator, 0); + var buf = ArrayList(u8).init(b.allocator); defer buf.deinit(); if (stderr.len != 0 and stderr[stderr.len - 1] == '\n') stderr = stderr[0 .. stderr.len - 1]; var it = mem.separate(stderr, "\n"); @@ -652,21 +651,21 @@ pub const StackTracesContext = struct { var pos: usize = if (std.Target.current.os.tag == .windows) 2 else 0; for (delims) |delim, i| { marks[i] = mem.indexOfPos(u8, line, pos, delim) orelse { - try buf.append(line); - try buf.append("\n"); + try buf.appendSlice(line); + try buf.appendSlice("\n"); continue :process_lines; }; pos = marks[i] + delim.len; } pos = mem.lastIndexOfScalar(u8, line[0..marks[0]], fs.path.sep) orelse { - try buf.append(line); - try buf.append("\n"); + try buf.appendSlice(line); + try buf.appendSlice("\n"); continue :process_lines; }; - try buf.append(line[pos + 1 .. marks[2] + delims[2].len]); - try buf.append(" [address]"); - try buf.append(line[marks[3]..]); - try buf.append("\n"); + try buf.appendSlice(line[pos + 1 .. marks[2] + delims[2].len]); + try buf.appendSlice(" [address]"); + try buf.appendSlice(line[marks[3]..]); + try buf.appendSlice("\n"); } break :got_result buf.toOwnedSlice(); }; From d9cf779b47573f750f9e6ffb6373bfcb75b1632e Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Wed, 1 Apr 2020 20:38:32 +0200 Subject: [PATCH 68/89] Fix some nullptr dereferences on arm-linux-musleabhif --- src/ir.cpp | 6 ++++-- test/compile_errors.zig | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index b9a14d0fe1..215dac5946 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -18982,7 +18982,7 @@ static IrInstGen *ir_analyze_async_call(IrAnalyze *ira, IrInst* source_instr, Zi if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) { return result_loc; } - result_loc = ir_implicit_cast2(ira, &call_result_loc->source_instruction->base, result_loc, + result_loc = ir_implicit_cast2(ira, source_instr, result_loc, get_pointer_to_type(ira->codegen, frame_type, false)); if (type_is_invalid(result_loc->value->type)) return ira->codegen->invalid_inst_gen; @@ -19967,14 +19967,16 @@ static IrInstGen *ir_analyze_call_extra(IrAnalyze *ira, IrInst* source_instr, return ira->codegen->invalid_inst_gen; IrInstGen *stack = nullptr; + IrInst *stack_src = nullptr; if (stack_is_non_null) { stack = ir_analyze_optional_value_payload_value(ira, source_instr, opt_stack, false); if (type_is_invalid(stack->value->type)) return ira->codegen->invalid_inst_gen; + stack_src = &stack->base; } return ir_analyze_fn_call(ira, source_instr, fn, fn_type, fn_ref, first_arg_ptr, first_arg_ptr_src, - modifier, stack, &stack->base, false, args_ptr, args_len, nullptr, result_loc); + modifier, stack, stack_src, false, args_ptr, args_len, nullptr, result_loc); } static IrInstGen *ir_analyze_instruction_call_extra(IrAnalyze *ira, IrInstSrcCallExtra *instruction) { diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 361ff8d9a2..1f003ba73a 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1188,7 +1188,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ suspend; \\} , &[_][]const u8{ - "tmp.zig:3:5: error: expected type '*@Frame(bar)', found '*@Frame(foo)'", + "tmp.zig:3:13: error: expected type '*@Frame(bar)', found '*@Frame(foo)'", }); cases.add("@Frame() of generic function", From ae6965a4e73cd5aad04e1c6831f48e7f0ecafc04 Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Wed, 1 Apr 2020 20:40:13 +0200 Subject: [PATCH 69/89] Fix undefined behavior when shift amount is 64 --- src/bigint.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bigint.cpp b/src/bigint.cpp index 644e25837e..dd04363e82 100644 --- a/src/bigint.cpp +++ b/src/bigint.cpp @@ -1430,7 +1430,7 @@ void bigint_shr(BigInt *dest, const BigInt *op1, const BigInt *op2) { uint64_t digit = op1_digits[op_digit_index]; size_t dest_digit_index = op_digit_index - digit_shift_count; digits[dest_digit_index] = carry | (digit >> leftover_shift_count); - carry = digit << (64 - leftover_shift_count); + carry = (leftover_shift_count != 0) ? (digit << (64 - leftover_shift_count)) : 0; if (dest_digit_index == 0) { break; } op_digit_index -= 1; From d33766e6c7289b79256b2e50d0dc2344729ff710 Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Wed, 1 Apr 2020 20:42:43 +0200 Subject: [PATCH 70/89] Make sure that ZigTypeVector and ZigTypeArray have the same memory layout Throughout the stage1 code it is assumed that these have the same layout, but that was not the case. This caused an issue on 32-bit hardware. --- src/all_types.hpp | 8 +++++++- src/analyze.cpp | 1 + src/codegen.cpp | 2 +- src/ir.cpp | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/all_types.hpp b/src/all_types.hpp index f51a9c0572..c0d728124b 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -1324,6 +1324,7 @@ struct ZigTypeFloat { size_t bit_count; }; +// Needs to have the same memory layout as ZigTypeVector struct ZigTypeArray { ZigType *child_type; uint64_t len; @@ -1512,12 +1513,17 @@ struct ZigTypeBoundFn { ZigType *fn_type; }; +// Needs to have the same memory layout as ZigTypeArray struct ZigTypeVector { // The type must be a pointer, integer, bool, or float ZigType *elem_type; - uint32_t len; + uint64_t len; + size_t padding; }; +// A lot of code is relying on ZigTypeArray and ZigTypeVector having the same layout/size +static_assert(sizeof(ZigTypeVector) == sizeof(ZigTypeArray), "Size of ZigTypeVector and ZigTypeArray do not match!"); + enum ZigTypeId { ZigTypeIdInvalid, ZigTypeIdMetaType, diff --git a/src/analyze.cpp b/src/analyze.cpp index df7bcdf9de..45983e5d38 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -5156,6 +5156,7 @@ ZigType *get_vector_type(CodeGen *g, uint32_t len, ZigType *elem_type) { } entry->data.vector.len = len; entry->data.vector.elem_type = elem_type; + entry->data.vector.padding = 0; buf_resize(&entry->name, 0); buf_appendf(&entry->name, "@Vector(%u, %s)", len, buf_ptr(&elem_type->name)); diff --git a/src/codegen.cpp b/src/codegen.cpp index d36e398bf7..088b3779a9 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -714,7 +714,7 @@ static LLVMValueRef get_arithmetic_overflow_fn(CodeGen *g, ZigType *operand_type }; if (operand_type->id == ZigTypeIdVector) { - sprintf(fn_name, "llvm.%s.with.overflow.v%" PRIu32 "i%" PRIu32, signed_str, + sprintf(fn_name, "llvm.%s.with.overflow.v%" PRIu64 "i%" PRIu32, signed_str, operand_type->data.vector.len, int_type->data.integral.bit_count); LLVMTypeRef return_elem_types[] = { diff --git a/src/ir.cpp b/src/ir.cpp index 215dac5946..41c4a3b58c 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -15953,7 +15953,7 @@ static IrInstGen *ir_analyze_bin_op_cmp_numeric(IrAnalyze *ira, IrInst *source_i if (op1->value->type->id == ZigTypeIdVector && op2->value->type->id == ZigTypeIdVector) { if (op1->value->type->data.vector.len != op2->value->type->data.vector.len) { ir_add_error(ira, source_instr, - buf_sprintf("vector length mismatch: %" PRIu32 " and %" PRIu32, + buf_sprintf("vector length mismatch: %" PRIu64 " and %" PRIu64, op1->value->type->data.vector.len, op2->value->type->data.vector.len)); return ira->codegen->invalid_inst_gen; } From c211b8f91df3ff7545a8cc3e93b58372eeccfe69 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 1 Apr 2020 15:02:31 -0400 Subject: [PATCH 71/89] fix regressions from previous commit --- src-self-hosted/libc_installation.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src-self-hosted/libc_installation.zig b/src-self-hosted/libc_installation.zig index 11708e2a31..60124d30e5 100644 --- a/src-self-hosted/libc_installation.zig +++ b/src-self-hosted/libc_installation.zig @@ -327,7 +327,7 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - var result_buf = std.ArrayList([]const u8).init(allocator); + var result_buf = std.ArrayList(u8).init(allocator); defer result_buf.deinit(); for (searches) |search| { @@ -366,7 +366,7 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - var result_buf = try std.ArrayList([]const u8).init(allocator); + var result_buf = std.ArrayList(u8).init(allocator); defer result_buf.deinit(); const arch_sub_dir = switch (builtin.arch) { @@ -420,7 +420,7 @@ pub const LibCInstallation = struct { var search_buf: [2]Search = undefined; const searches = fillSearch(&search_buf, sdk); - var result_buf = try std.ArrayList([]const u8).init(allocator); + var result_buf = std.ArrayList(u8).init(allocator); defer result_buf.deinit(); const arch_sub_dir = switch (builtin.arch) { From 212e2354b8ab631995b0c25f7cf1d9a3e01fac57 Mon Sep 17 00:00:00 2001 From: Michael Dusan Date: Wed, 1 Apr 2020 12:47:50 -0400 Subject: [PATCH 72/89] stage1: make C++ switch fallthrough an error Make fallthrough an error when compiler supports it. This requires a new macro that is defined with such compilers to be used as a statement, at all fallthrough sites: switch (...) { case 0: ... ZIG_FALLTHROUGH; case 1: ... break; default: ... break; } If we ever move to C++17 as minimal requirement, then the macro can be replaced with `[[fallthrough]];` at statement sites. --- CMakeLists.txt | 2 +- src/analyze.cpp | 2 ++ src/codegen.cpp | 3 ++- src/dump_analysis.cpp | 4 ++-- src/ir.cpp | 2 ++ src/target.cpp | 5 +++++ src/tokenizer.cpp | 7 ++++--- src/util_base.hpp | 10 ++++++++++ 8 files changed, 28 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a4864bf0ba..7349fa01c4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -325,7 +325,7 @@ if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") if(MSVC) set(EXE_CFLAGS "${EXE_CFLAGS} /w") else() - set(EXE_CFLAGS "${EXE_CFLAGS} -Werror -Wall") + set(EXE_CFLAGS "${EXE_CFLAGS} -Werror -Wall -Werror=implicit-fallthrough") endif() endif() diff --git a/src/analyze.cpp b/src/analyze.cpp index 45983e5d38..9cc1ad2472 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -363,6 +363,7 @@ bool type_is_resolved(ZigType *type_entry, ResolveStatus status) { case ResolveStatusLLVMFull: return type_entry->llvm_type != nullptr; } + zig_unreachable(); case ZigTypeIdOpaque: return status < ResolveStatusSizeKnown; case ZigTypeIdPointer: @@ -381,6 +382,7 @@ bool type_is_resolved(ZigType *type_entry, ResolveStatus status) { case ResolveStatusLLVMFull: return type_entry->llvm_type != nullptr; } + zig_unreachable(); case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: diff --git a/src/codegen.cpp b/src/codegen.cpp index 616e6360e0..1bc80c8dc7 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -3954,8 +3954,9 @@ static void render_async_var_decls(CodeGen *g, Scope *scope) { if (var->did_the_decl_codegen) { render_decl_var(g, var); } - // fallthrough } + ZIG_FALLTHROUGH; + case ScopeIdDecls: case ScopeIdBlock: case ScopeIdDefer: diff --git a/src/dump_analysis.cpp b/src/dump_analysis.cpp index c31438b658..3522dcf6f4 100644 --- a/src/dump_analysis.cpp +++ b/src/dump_analysis.cpp @@ -80,7 +80,7 @@ static void jw_array_elem(JsonWriter *jw) { zig_unreachable(); case JsonWriterStateArray: fprintf(jw->f, ","); - // fallthrough + ZIG_FALLTHROUGH; case JsonWriterStateArrayStart: jw->state[jw->state_index] = JsonWriterStateArray; jw_push_state(jw, JsonWriterStateValue); @@ -134,7 +134,7 @@ static void jw_object_field(JsonWriter *jw, const char *name) { zig_unreachable(); case JsonWriterStateObject: fprintf(jw->f, ","); - // fallthrough + ZIG_FALLTHROUGH; case JsonWriterStateObjectStart: jw->state[jw->state_index] = JsonWriterStateObject; jw_push_state(jw, JsonWriterStateValue); diff --git a/src/ir.cpp b/src/ir.cpp index 41c4a3b58c..a30d467194 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -19949,6 +19949,7 @@ static IrInstGen *ir_analyze_call_extra(IrAnalyze *ira, IrInst* source_instr, buf_sprintf("the specified modifier requires a comptime-known function")); return ira->codegen->invalid_inst_gen; } + ZIG_FALLTHROUGH; default: break; } @@ -28169,6 +28170,7 @@ static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ZigValue *val) return; } } + zig_unreachable(); case ZigTypeIdOptional: zig_panic("TODO buf_write_value_bytes maybe type"); case ZigTypeIdFn: diff --git a/src/target.cpp b/src/target.cpp index 4430adfe5a..da19f76f45 100644 --- a/src/target.cpp +++ b/src/target.cpp @@ -624,6 +624,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { case CIntTypeCount: zig_unreachable(); } + zig_unreachable(); default: switch (id) { case CIntTypeShort: @@ -642,6 +643,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { zig_unreachable(); } } + zig_unreachable(); case OsLinux: case OsMacOSX: case OsFreeBSD: @@ -666,6 +668,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { case CIntTypeCount: zig_unreachable(); } + zig_unreachable(); case OsUefi: case OsWindows: switch (id) { @@ -683,6 +686,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { case CIntTypeCount: zig_unreachable(); } + zig_unreachable(); case OsIOS: switch (id) { case CIntTypeShort: @@ -699,6 +703,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) { case CIntTypeCount: zig_unreachable(); } + zig_unreachable(); case OsAnanas: case OsCloudABI: case OsKFreeBSD: diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index b4e9d910d9..11432ecac1 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -840,6 +840,7 @@ void tokenize(Buf *buf, Tokenization *out) { t.state = TokenizeStateStart; continue; } + break; case TokenizeStateSawSlash: switch (c) { case '/': @@ -1209,7 +1210,7 @@ void tokenize(Buf *buf, Tokenization *out) { t.is_trailing_underscore = false; t.state = TokenizeStateNumber; } - // fall through + ZIG_FALLTHROUGH; case TokenizeStateNumber: { if (c == '_') { @@ -1291,7 +1292,7 @@ void tokenize(Buf *buf, Tokenization *out) { t.is_trailing_underscore = false; t.state = TokenizeStateFloatFraction; } - // fall through + ZIG_FALLTHROUGH; case TokenizeStateFloatFraction: { if (c == '_') { @@ -1350,7 +1351,7 @@ void tokenize(Buf *buf, Tokenization *out) { t.is_trailing_underscore = false; t.state = TokenizeStateFloatExponentNumber; } - // fall through + ZIG_FALLTHROUGH; case TokenizeStateFloatExponentNumber: { if (c == '_') { diff --git a/src/util_base.hpp b/src/util_base.hpp index f6cea45c20..1c665bf931 100644 --- a/src/util_base.hpp +++ b/src/util_base.hpp @@ -64,4 +64,14 @@ static inline void zig_assert(bool ok, const char *file, int line, const char *f #undef assert #define assert(ok) zig_assert(ok, __FILE__, __LINE__, __func__) +#if defined(_MSC_VER) +#define ZIG_FALLTHROUGH +#elif defined(__clang__) +#define ZIG_FALLTHROUGH [[clang::fallthrough]] +#elif defined(__GNUC__) +#define ZIG_FALLTHROUGH __attribute__((fallthrough)) +#else +#define ZIG_FALLTHROUGH +#endif + #endif From 6695fa4f326e807256b9afc6321e63a90b08e1ba Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Wed, 1 Apr 2020 18:30:40 +0200 Subject: [PATCH 73/89] ir: Fix comparison of ?T values The code assumed that every ?T had a pointer child type T, add some more checks to make sure the type is effectively a pointer. Closes #4789 --- src/ir.cpp | 6 ++---- test/compile_errors.zig | 13 +++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index a30d467194..5b86922be3 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -11454,10 +11454,8 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, ZigType *wanted bool actual_allows_zero = ptr_allows_addr_zero(actual_type); bool wanted_is_c_ptr = wanted_type->id == ZigTypeIdPointer && wanted_type->data.pointer.ptr_len == PtrLenC; bool actual_is_c_ptr = actual_type->id == ZigTypeIdPointer && actual_type->data.pointer.ptr_len == PtrLenC; - bool wanted_opt_or_ptr = wanted_ptr_type != nullptr && - (wanted_type->id == ZigTypeIdPointer || wanted_type->id == ZigTypeIdOptional); - bool actual_opt_or_ptr = actual_ptr_type != nullptr && - (actual_type->id == ZigTypeIdPointer || actual_type->id == ZigTypeIdOptional); + bool wanted_opt_or_ptr = wanted_ptr_type != nullptr && wanted_ptr_type->id == ZigTypeIdPointer; + bool actual_opt_or_ptr = actual_ptr_type != nullptr && actual_ptr_type->id == ZigTypeIdPointer; if (wanted_opt_or_ptr && actual_opt_or_ptr) { bool ok_null_term_ptrs = wanted_ptr_type->data.pointer.sentinel == nullptr || diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 1f003ba73a..0155ad3fa8 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -2,6 +2,19 @@ const tests = @import("tests.zig"); const std = @import("std"); pub fn addCases(cases: *tests.CompileErrorContext) void { + cases.addTest("cast between ?T where T is not a pointer", + \\pub const fnty1 = ?fn (i8) void; + \\pub const fnty2 = ?fn (u64) void; + \\export fn entry() void { + \\ var a: fnty1 = undefined; + \\ var b: fnty2 = undefined; + \\ a = b; + \\} + , &[_][]const u8{ + "tmp.zig:6:9: error: expected type '?fn(i8) void', found '?fn(u64) void'", + "tmp.zig:6:9: note: optional type child 'fn(u64) void' cannot cast into optional type child 'fn(i8) void'", + }); + cases.addTest("unused variable error on errdefer", \\fn foo() !void { \\ errdefer |a| unreachable; From 783f73c7e3590f05825d66f1f0ccb108be74b5c4 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 1 Apr 2020 16:01:06 -0400 Subject: [PATCH 74/89] zig cc properly handles -S flag and .ll, .bc extensions --- src-self-hosted/clang_options_data.zig | 10 ++-- src-self-hosted/stage2.zig | 2 +- src/all_types.hpp | 10 ++++ src/analyze.hpp | 8 +-- src/buffer.hpp | 5 +- src/codegen.cpp | 82 ++++++++++++-------------- src/compiler.cpp | 22 +++++++ src/compiler.hpp | 6 +- src/ir.cpp | 2 +- src/main.cpp | 46 ++++++++------- src/stage2.h | 2 +- src/util.hpp | 9 +++ tools/update_clang_options.zig | 8 +-- 13 files changed, 122 insertions(+), 90 deletions(-) diff --git a/src-self-hosted/clang_options_data.zig b/src-self-hosted/clang_options_data.zig index d8bd020431..6dec814938 100644 --- a/src-self-hosted/clang_options_data.zig +++ b/src-self-hosted/clang_options_data.zig @@ -7,7 +7,7 @@ flagpd1("CC"), .{ .name = "E", .syntax = .flag, - .zig_equivalent = .preprocess, + .zig_equivalent = .pp_or_asm, .pd1 = true, .pd2 = false, .psl = false, @@ -53,7 +53,7 @@ flagpd1("Qy"), .{ .name = "S", .syntax = .flag, - .zig_equivalent = .driver_punt, + .zig_equivalent = .pp_or_asm, .pd1 = true, .pd2 = false, .psl = false, @@ -154,7 +154,7 @@ sepd1("Zlinker-input"), .{ .name = "E", .syntax = .flag, - .zig_equivalent = .preprocess, + .zig_equivalent = .pp_or_asm, .pd1 = true, .pd2 = false, .psl = true, @@ -1442,7 +1442,7 @@ sepd1("Zlinker-input"), .{ .name = "assemble", .syntax = .flag, - .zig_equivalent = .driver_punt, + .zig_equivalent = .pp_or_asm, .pd1 = false, .pd2 = true, .psl = false, @@ -1770,7 +1770,7 @@ sepd1("Zlinker-input"), .{ .name = "preprocess", .syntax = .flag, - .zig_equivalent = .preprocess, + .zig_equivalent = .pp_or_asm, .pd1 = false, .pd2 = true, .psl = false, diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 8dd2ee876d..56f608c280 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -1280,7 +1280,7 @@ pub const ClangArgIterator = extern struct { shared, rdynamic, wl, - preprocess, + pp_or_asm, optimize, debug, sanitize, diff --git a/src/all_types.hpp b/src/all_types.hpp index c0d728124b..efb2cd1f0f 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -54,6 +54,16 @@ struct ResultLocCast; struct ResultLocReturn; struct IrExecutableGen; +enum FileExt { + FileExtUnknown, + FileExtAsm, + FileExtC, + FileExtCpp, + FileExtHeader, + FileExtLLVMIr, + FileExtLLVMBitCode, +}; + enum PtrLen { PtrLenUnknown, PtrLenSingle, diff --git a/src/analyze.hpp b/src/analyze.hpp index ee069427bd..ae010c87e1 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -257,14 +257,8 @@ Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose LLVMTypeRef get_llvm_type(CodeGen *g, ZigType *type); ZigLLVMDIType *get_llvm_di_type(CodeGen *g, ZigType *type); -enum CSourceKind { - CSourceKindAsm, - CSourceKindC, - CSourceKindCpp, -}; - void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_path, bool translate_c, - CSourceKind source_kind); + FileExt source_kind); void src_assert(bool ok, AstNode *source_node); bool is_container(ZigType *type_entry); diff --git a/src/buffer.hpp b/src/buffer.hpp index 82bcb56611..8876316589 100644 --- a/src/buffer.hpp +++ b/src/buffer.hpp @@ -178,10 +178,7 @@ static inline bool buf_starts_with_str(Buf *buf, const char *str) { } static inline bool buf_ends_with_mem(Buf *buf, const char *mem, size_t mem_len) { - if (buf_len(buf) < mem_len) { - return false; - } - return memcmp(buf_ptr(buf) + buf_len(buf) - mem_len, mem, mem_len) == 0; + return mem_ends_with_mem(buf_ptr(buf), buf_len(buf), mem, mem_len); } static inline bool buf_ends_with_str(Buf *buf, const char *str) { diff --git a/src/codegen.cpp b/src/codegen.cpp index 1bc80c8dc7..5ead5f7d73 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -9170,20 +9170,13 @@ static void detect_libc(CodeGen *g) { // does not add the "cc" arg void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_path, - bool translate_c, CSourceKind source_kind) + bool translate_c, FileExt source_kind) { if (translate_c) { args.append("-x"); args.append("c"); } - if (source_kind != CSourceKindAsm && out_dep_path != nullptr) { - args.append("-MD"); - args.append("-MV"); - args.append("-MF"); - args.append(out_dep_path); - } - args.append("-nostdinc"); args.append("-fno-spell-checking"); @@ -9191,14 +9184,7 @@ void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_pa args.append("-ffunction-sections"); } - if (translate_c) { - if (source_kind != CSourceKindAsm) { - // this gives us access to preprocessing entities, presumably at - // the cost of performance - args.append("-Xclang"); - args.append("-detailed-preprocessing-record"); - } - } else { + if (!translate_c) { switch (g->err_color) { case ErrColorAuto: break; @@ -9232,24 +9218,25 @@ void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_pa args.append("-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS"); } - // According to Rich Felker libc headers are supposed to go before C language headers. - // However as noted by @dimenus, appending libc headers before c_headers breaks intrinsics - // and other compiler specific items. - args.append("-isystem"); - args.append(buf_ptr(g->zig_c_headers_dir)); - - for (size_t i = 0; i < g->libc_include_dir_len; i += 1) { - const char *include_dir = g->libc_include_dir_list[i]; - args.append("-isystem"); - args.append(include_dir); - } - args.append("-target"); args.append(buf_ptr(&g->llvm_triple_str)); switch (source_kind) { - case CSourceKindC: - case CSourceKindCpp: + case FileExtC: + case FileExtCpp: + case FileExtHeader: + // According to Rich Felker libc headers are supposed to go before C language headers. + // However as noted by @dimenus, appending libc headers before c_headers breaks intrinsics + // and other compiler specific items. + args.append("-isystem"); + args.append(buf_ptr(g->zig_c_headers_dir)); + + for (size_t i = 0; i < g->libc_include_dir_len; i += 1) { + const char *include_dir = g->libc_include_dir_list[i]; + args.append("-isystem"); + args.append(include_dir); + } + if (g->zig_target->llvm_cpu_name != nullptr) { args.append("-Xclang"); args.append("-target-cpu"); @@ -9262,8 +9249,23 @@ void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_pa args.append("-Xclang"); args.append(g->zig_target->llvm_cpu_features); } + if (translate_c) { + // this gives us access to preprocessing entities, presumably at + // the cost of performance + args.append("-Xclang"); + args.append("-detailed-preprocessing-record"); + } + if (out_dep_path != nullptr) { + args.append("-MD"); + args.append("-MV"); + args.append("-MF"); + args.append(out_dep_path); + } break; - case CSourceKindAsm: + case FileExtAsm: + case FileExtLLVMIr: + case FileExtLLVMBitCode: + case FileExtUnknown: break; } for (size_t i = 0; i < g->zig_target->llvm_cpu_features_asm_len; i += 1) { @@ -9413,7 +9415,7 @@ void codegen_translate_c(CodeGen *g, Buf *full_path) { } ZigList clang_argv = {0}; - add_cc_args(g, clang_argv, out_dep_path_cstr, true, CSourceKindC); + add_cc_args(g, clang_argv, out_dep_path_cstr, true, FileExtC); clang_argv.append(buf_ptr(full_path)); @@ -9751,15 +9753,6 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) { Buf *c_source_basename = buf_alloc(); os_path_split(c_source_file, nullptr, c_source_basename); - CSourceKind c_source_kind; - if (buf_ends_with_str(c_source_basename, ".s") || - buf_ends_with_str(c_source_basename, ".S")) - { - c_source_kind = CSourceKindAsm; - } else { - c_source_kind = CSourceKindC; - } - Stage2ProgressNode *child_prog_node = stage2_progress_start(g->sub_progress_node, buf_ptr(c_source_basename), buf_len(c_source_basename), 0); @@ -9825,14 +9818,13 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) { args.append(buf_ptr(self_exe_path)); args.append("clang"); - if (c_file->preprocessor_only_basename != nullptr) { - args.append("-E"); - } else { + if (c_file->preprocessor_only_basename == nullptr) { args.append("-c"); } Buf *out_dep_path = buf_sprintf("%s.d", buf_ptr(out_obj_path)); - add_cc_args(g, args, buf_ptr(out_dep_path), false, c_source_kind); + FileExt ext = classify_file_ext(buf_ptr(c_source_basename), buf_len(c_source_basename)); + add_cc_args(g, args, buf_ptr(out_dep_path), false, ext); args.append("-o"); args.append(buf_ptr(out_obj_path)); diff --git a/src/compiler.cpp b/src/compiler.cpp index cddecc2025..8294fc7871 100644 --- a/src/compiler.cpp +++ b/src/compiler.cpp @@ -164,3 +164,25 @@ Buf *get_global_cache_dir(void) { buf_deinit(&app_data_dir); return &saved_global_cache_dir; } + +FileExt classify_file_ext(const char *filename_ptr, size_t filename_len) { + if (mem_ends_with_str(filename_ptr, filename_len, ".c")) { + return FileExtC; + } else if (mem_ends_with_str(filename_ptr, filename_len, ".C") || + mem_ends_with_str(filename_ptr, filename_len, ".cc") || + mem_ends_with_str(filename_ptr, filename_len, ".cpp") || + mem_ends_with_str(filename_ptr, filename_len, ".cxx")) + { + return FileExtCpp; + } else if (mem_ends_with_str(filename_ptr, filename_len, ".ll")) { + return FileExtLLVMIr; + } else if (mem_ends_with_str(filename_ptr, filename_len, ".bc")) { + return FileExtLLVMBitCode; + } else if (mem_ends_with_str(filename_ptr, filename_len, ".s") || + mem_ends_with_str(filename_ptr, filename_len, ".S")) + { + return FileExtAsm; + } + // TODO look for .so, .so.X, .so.X.Y, .so.X.Y.Z + return FileExtUnknown; +} diff --git a/src/compiler.hpp b/src/compiler.hpp index 47841af5dc..ae2e6e9c5e 100644 --- a/src/compiler.hpp +++ b/src/compiler.hpp @@ -8,8 +8,7 @@ #ifndef ZIG_COMPILER_HPP #define ZIG_COMPILER_HPP -#include "buffer.hpp" -#include "error.hpp" +#include "all_types.hpp" Error get_compiler_id(Buf **result); @@ -19,4 +18,7 @@ Buf *get_zig_std_dir(Buf *zig_lib_dir); Buf *get_global_cache_dir(void); + +FileExt classify_file_ext(const char *filename_ptr, size_t filename_len); + #endif diff --git a/src/ir.cpp b/src/ir.cpp index 5b86922be3..2f9e3638f8 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -25171,7 +25171,7 @@ static IrInstGen *ir_analyze_instruction_c_import(IrAnalyze *ira, IrInstSrcCImpo ZigList clang_argv = {0}; - add_cc_args(ira->codegen, clang_argv, buf_ptr(tmp_dep_file), true, CSourceKindC); + add_cc_args(ira->codegen, clang_argv, buf_ptr(tmp_dep_file), true, FileExtC); clang_argv.append(buf_ptr(&tmp_c_file_path)); diff --git a/src/main.cpp b/src/main.cpp index c95a512210..e9babe562d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -455,7 +455,7 @@ static int main0(int argc, char **argv) { const char *mcpu = nullptr; CodeModel code_model = CodeModelDefault; const char *override_soname = nullptr; - bool only_preprocess = false; + bool only_pp_or_asm = false; bool ensure_libc_on_non_freestanding = false; bool ensure_libcpp_on_non_freestanding = false; @@ -615,20 +615,22 @@ static int main0(int argc, char **argv) { } break; case Stage2ClangArgPositional: { - Buf *arg_buf = buf_create_from_str(it.only_arg); - if (buf_ends_with_str(arg_buf, ".c") || - buf_ends_with_str(arg_buf, ".C") || - buf_ends_with_str(arg_buf, ".cc") || - buf_ends_with_str(arg_buf, ".cpp") || - buf_ends_with_str(arg_buf, ".cxx") || - buf_ends_with_str(arg_buf, ".s") || - buf_ends_with_str(arg_buf, ".S")) - { - CFile *c_file = heap::c_allocator.create(); - c_file->source_path = it.only_arg; - c_source_files.append(c_file); - } else { - objects.append(it.only_arg); + FileExt file_ext = classify_file_ext(it.only_arg, strlen(it.only_arg)); + switch (file_ext) { + case FileExtAsm: + case FileExtC: + case FileExtCpp: + case FileExtLLVMIr: + case FileExtLLVMBitCode: + case FileExtHeader: { + CFile *c_file = heap::c_allocator.create(); + c_file->source_path = it.only_arg; + c_source_files.append(c_file); + break; + } + case FileExtUnknown: + objects.append(it.only_arg); + break; } break; } @@ -674,8 +676,12 @@ static int main0(int argc, char **argv) { } break; } - case Stage2ClangArgPreprocess: - only_preprocess = true; + case Stage2ClangArgPreprocessOrAsm: + // this handles both -E and -S + only_pp_or_asm = true; + for (size_t i = 0; i < it.other_args_len; i += 1) { + clang_argv.append(it.other_args_ptr[i]); + } break; case Stage2ClangArgOptimize: // alright what release mode do they want? @@ -799,7 +805,7 @@ static int main0(int argc, char **argv) { build_mode = BuildModeSafeRelease; } - if (only_preprocess) { + if (only_pp_or_asm) { cmd = CmdBuild; out_type = OutTypeObj; emit_bin = false; @@ -1597,7 +1603,7 @@ static int main0(int argc, char **argv) { #endif Buf *dest_path = buf_create_from_str(emit_bin_override_path); Buf *source_path; - if (only_preprocess) { + if (only_pp_or_asm) { source_path = buf_alloc(); Buf *pp_only_basename = buf_create_from_str( c_source_files.at(0)->preprocessor_only_basename); @@ -1611,7 +1617,7 @@ static int main0(int argc, char **argv) { buf_ptr(dest_path), err_str(err)); return main_exit(root_progress_node, EXIT_FAILURE); } - } else if (only_preprocess) { + } else if (only_pp_or_asm) { #if defined(ZIG_OS_WINDOWS) buf_replace(g->c_artifact_dir, '/', '\\'); #endif diff --git a/src/stage2.h b/src/stage2.h index 54355ea735..49e0dcc28c 100644 --- a/src/stage2.h +++ b/src/stage2.h @@ -339,7 +339,7 @@ enum Stage2ClangArg { Stage2ClangArgShared, Stage2ClangArgRDynamic, Stage2ClangArgWL, - Stage2ClangArgPreprocess, + Stage2ClangArgPreprocessOrAsm, Stage2ClangArgOptimize, Stage2ClangArgDebug, Stage2ClangArgSanitize, diff --git a/src/util.hpp b/src/util.hpp index a119606245..bd1a5b1e4c 100644 --- a/src/util.hpp +++ b/src/util.hpp @@ -100,6 +100,15 @@ static inline bool is_power_of_2(uint64_t x) { return x != 0 && ((x & (~x + 1)) == x); } +static inline bool mem_ends_with_mem(const char *mem, size_t mem_len, const char *end, size_t end_len) { + if (mem_len < end_len) return false; + return memcmp(mem + mem_len - end_len, end, end_len) == 0; +} + +static inline bool mem_ends_with_str(const char *mem, size_t mem_len, const char *str) { + return mem_ends_with_mem(mem, mem_len, str, strlen(str)); +} + static inline uint64_t round_to_next_power_of_2(uint64_t x) { --x; x |= x >> 1; diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index f5b483e667..d2ad8cad33 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -96,19 +96,19 @@ const known_options = [_]KnownOpt{ }, .{ .name = "E", - .ident = "preprocess", + .ident = "pp_or_asm", }, .{ .name = "preprocess", - .ident = "preprocess", + .ident = "pp_or_asm", }, .{ .name = "S", - .ident = "driver_punt", + .ident = "pp_or_asm", }, .{ .name = "assemble", - .ident = "driver_punt", + .ident = "pp_or_asm", }, .{ .name = "O1", From 2b6dfdd3d403fb33e226aa2566eacfad4b251379 Mon Sep 17 00:00:00 2001 From: Rejean Loyer Date: Wed, 1 Apr 2020 05:22:19 -0400 Subject: [PATCH 75/89] zig cc: add support for -L linker arguments --- src-self-hosted/clang_options_data.zig | 13 ++++++++++--- src-self-hosted/stage2.zig | 1 + src/main.cpp | 3 +++ src/stage2.h | 1 + tools/update_clang_options.zig | 8 ++++++++ 5 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src-self-hosted/clang_options_data.zig b/src-self-hosted/clang_options_data.zig index 6dec814938..533451b5e0 100644 --- a/src-self-hosted/clang_options_data.zig +++ b/src-self-hosted/clang_options_data.zig @@ -1658,7 +1658,7 @@ sepd1("Zlinker-input"), .{ .name = "library-directory", .syntax = .separate, - .zig_equivalent = .other, + .zig_equivalent = .linker_input_l, .pd1 = false, .pd2 = true, .psl = false, @@ -4534,7 +4534,7 @@ joinpd1("target-sdk-version="), .{ .name = "library-directory=", .syntax = .joined, - .zig_equivalent = .other, + .zig_equivalent = .linker_input_l, .pd1 = false, .pd2 = true, .psl = false, @@ -5632,7 +5632,14 @@ jspd1("F"), jspd1("G"), jspd1("I"), jspd1("J"), -jspd1("L"), +.{ + .name = "L", + .syntax = .joined_or_separate, + .zig_equivalent = .linker_input_l, + .pd1 = true, + .pd2 = false, + .psl = false, +}, .{ .name = "O", .syntax = .joined, diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 56f608c280..d4503a3a52 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -1288,6 +1288,7 @@ pub const ClangArgIterator = extern struct { verbose_cmds, for_linker, linker_input_z, + linker_input_l, }; const Args = struct { diff --git a/src/main.cpp b/src/main.cpp index e9babe562d..3bfb154405 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -735,6 +735,9 @@ static int main0(int argc, char **argv) { linker_args.append(buf_create_from_str("-z")); linker_args.append(buf_create_from_str(it.only_arg)); break; + case Stage2ClangArgLinkerInputL: + lib_dirs.append(it.only_arg); + break; } } // Parse linker args diff --git a/src/stage2.h b/src/stage2.h index 49e0dcc28c..449635f2ff 100644 --- a/src/stage2.h +++ b/src/stage2.h @@ -347,6 +347,7 @@ enum Stage2ClangArg { Stage2ClangArgVerboseCmds, Stage2ClangArgForLinker, Stage2ClangArgLinkerInputZ, + Stage2ClangArgLinkerInputL, }; // ABI warning diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index d2ad8cad33..24e8223520 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -174,6 +174,14 @@ const known_options = [_]KnownOpt{ .name = "###", .ident = "verbose_cmds", }, + .{ + .name = "L", + .ident = "linker_input_l", + }, + .{ + .name = "library-directory", + .ident = "linker_input_l", + }, }; const blacklisted_options = [_][]const u8{}; From eefb0a36c060fab2d9d2bf2a258f0fd5e8126fe8 Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Wed, 1 Apr 2020 22:46:02 +0200 Subject: [PATCH 76/89] Fix CrossTarget.parse test on platforms where abi != gnu Closes #4902 --- lib/std/zig/cross_target.zig | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/std/zig/cross_target.zig b/lib/std/zig/cross_target.zig index 4d19ecee8c..76aff2ae51 100644 --- a/lib/std/zig/cross_target.zig +++ b/lib/std/zig/cross_target.zig @@ -765,7 +765,15 @@ test "CrossTarget.parse" { const text = try cross_target.zigTriple(std.testing.allocator); defer std.testing.allocator.free(text); - std.testing.expectEqualSlices(u8, "native-native-gnu.2.1.1", text); + + var buf: [256]u8 = undefined; + const triple = std.fmt.bufPrint( + buf[0..], + "native-native-{}.2.1.1", + .{@tagName(std.Target.current.abi)}, + ) catch unreachable; + + std.testing.expectEqualSlices(u8, triple, text); } { const cross_target = try CrossTarget.parse(.{ From 4848b28ec84edb719e780f164eac366ab2e83f22 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 1 Apr 2020 18:05:06 -0400 Subject: [PATCH 77/89] zig cc: detect -mcpu, -march, -mtune However these are all treated like zig's -mcpu parameter. See #4784 --- src-self-hosted/clang_options_data.zig | 33 +++++++++++++++++++++----- src-self-hosted/stage2.zig | 3 ++- src/main.cpp | 5 +++- src/stage2.h | 3 ++- tools/update_clang_options.zig | 16 +++++++++++-- 5 files changed, 49 insertions(+), 11 deletions(-) diff --git a/src-self-hosted/clang_options_data.zig b/src-self-hosted/clang_options_data.zig index 533451b5e0..f24039ba32 100644 --- a/src-self-hosted/clang_options_data.zig +++ b/src-self-hosted/clang_options_data.zig @@ -1658,7 +1658,7 @@ sepd1("Zlinker-input"), .{ .name = "library-directory", .syntax = .separate, - .zig_equivalent = .linker_input_l, + .zig_equivalent = .lib_dir, .pd1 = false, .pd2 = true, .psl = false, @@ -4534,7 +4534,7 @@ joinpd1("target-sdk-version="), .{ .name = "library-directory=", .syntax = .joined, - .zig_equivalent = .linker_input_l, + .zig_equivalent = .lib_dir, .pd1 = false, .pd2 = true, .psl = false, @@ -5254,8 +5254,22 @@ joinpd1("fixit="), joinpd1("gstabs"), joinpd1("gxcoff"), jspd1("iquote"), -joinpd1("march="), -joinpd1("mtune="), +.{ + .name = "march=", + .syntax = .joined, + .zig_equivalent = .mcpu, + .pd1 = true, + .pd2 = false, + .psl = false, +}, +.{ + .name = "mtune=", + .syntax = .joined, + .zig_equivalent = .mcpu, + .pd1 = true, + .pd2 = false, + .psl = false, +}, .{ .name = "rtlib=", .syntax = .joined, @@ -5320,7 +5334,14 @@ joinpd1("gcoff"), joinpd1("mabi="), joinpd1("mabs="), joinpd1("masm="), -joinpd1("mcpu="), +.{ + .name = "mcpu=", + .syntax = .joined, + .zig_equivalent = .mcpu, + .pd1 = true, + .pd2 = false, + .psl = false, +}, joinpd1("mfpu="), joinpd1("mhvx="), joinpd1("mmcu="), @@ -5635,7 +5656,7 @@ jspd1("J"), .{ .name = "L", .syntax = .joined_or_separate, - .zig_equivalent = .linker_input_l, + .zig_equivalent = .lib_dir, .pd1 = true, .pd2 = false, .psl = false, diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index d4503a3a52..798fb552c0 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -1288,7 +1288,8 @@ pub const ClangArgIterator = extern struct { verbose_cmds, for_linker, linker_input_z, - linker_input_l, + lib_dir, + mcpu, }; const Args = struct { diff --git a/src/main.cpp b/src/main.cpp index 3bfb154405..206b733325 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -735,9 +735,12 @@ static int main0(int argc, char **argv) { linker_args.append(buf_create_from_str("-z")); linker_args.append(buf_create_from_str(it.only_arg)); break; - case Stage2ClangArgLinkerInputL: + case Stage2ClangArgLibDir: lib_dirs.append(it.only_arg); break; + case Stage2ClangArgMCpu: + mcpu = it.only_arg; + break; } } // Parse linker args diff --git a/src/stage2.h b/src/stage2.h index 449635f2ff..8bb269dd23 100644 --- a/src/stage2.h +++ b/src/stage2.h @@ -347,7 +347,8 @@ enum Stage2ClangArg { Stage2ClangArgVerboseCmds, Stage2ClangArgForLinker, Stage2ClangArgLinkerInputZ, - Stage2ClangArgLinkerInputL, + Stage2ClangArgLibDir, + Stage2ClangArgMCpu, }; // ABI warning diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index 24e8223520..b85d708470 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -176,11 +176,23 @@ const known_options = [_]KnownOpt{ }, .{ .name = "L", - .ident = "linker_input_l", + .ident = "lib_dir", }, .{ .name = "library-directory", - .ident = "linker_input_l", + .ident = "lib_dir", + }, + .{ + .name = "mcpu", + .ident = "mcpu", + }, + .{ + .name = "march", + .ident = "mcpu", + }, + .{ + .name = "mtune", + .ident = "mcpu", }, }; From f6d384450fd7a9c6da236928ef84629bfbfbb781 Mon Sep 17 00:00:00 2001 From: Michael Dusan Date: Wed, 1 Apr 2020 11:02:38 -0400 Subject: [PATCH 78/89] add compile-error test: bitcast Issue fixed by an unknown commit. closes #3818 --- test/compile_errors.zig | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 0155ad3fa8..e54f6591b5 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -6842,4 +6842,19 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { "tmp.zig:8:23: error: use of undefined value here causes undefined behavior", "tmp.zig:14:23: error: use of undefined value here causes undefined behavior", }); + + cases.add("issue #3818: bitcast from parray/slice to u16", + \\export fn foo1() void { + \\ var bytes = [_]u8{1, 2}; + \\ const word: u16 = @bitCast(u16, bytes[0..]); + \\} + \\export fn foo2() void { + \\ var bytes: []u8 = &[_]u8{1, 2}; + \\ const word: u16 = @bitCast(u16, bytes); + \\} + , &[_][]const u8{ + "tmp.zig:3:42: error: unable to @bitCast from pointer type '*[2]u8'", + "tmp.zig:7:32: error: destination type 'u16' has size 2 but source type '[]u8' has size 16", + "tmp.zig:7:37: note: referenced here", + }); } From 2a031c8825832fa70299c3fb772d8230de723c22 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Thu, 2 Apr 2020 20:55:59 +1100 Subject: [PATCH 79/89] std: LinearFifo matches ArrayList in always having outStream method --- lib/std/fifo.zig | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index 6866cc3d7a..c97b0542b0 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -291,24 +291,16 @@ pub fn LinearFifo( return self.writeAssumeCapacity(src); } - pub usingnamespace if (T == u8) - struct { - const OutStream = std.io.OutStream(*Self, Error, appendWrite); - const Error = error{OutOfMemory}; + /// Same as `write` except it returns the number of bytes written, which is always the same + /// as `bytes.len`. The purpose of this function existing is to match `std.io.OutStream` API. + fn appendWrite(self: *Self, bytes: []const u8) error{OutOfMemory}!usize { + try self.write(bytes); + return bytes.len; + } - /// Same as `write` except it returns the number of bytes written, which is always the same - /// as `bytes.len`. The purpose of this function existing is to match `std.io.OutStream` API. - pub fn appendWrite(fifo: *Self, bytes: []const u8) Error!usize { - try fifo.write(bytes); - return bytes.len; - } - - pub fn outStream(self: *Self) OutStream { - return .{ .context = self }; - } - } - else - struct {}; + pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) { + return .{ .context = self }; + } /// Make `count` items available before the current read location fn rewind(self: *Self, count: usize) void { From 34524a179227d1492229f52b93c61405455c47e8 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Thu, 2 Apr 2020 21:14:15 +1100 Subject: [PATCH 80/89] std: add LinearFifo().inStream --- lib/std/fifo.zig | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index c97b0542b0..6bbec57072 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -215,6 +215,16 @@ pub fn LinearFifo( return dst.len - dst_left.len; } + /// Same as `read` except it returns an error union + /// The purpose of this function existing is to match `std.io.InStream` API. + fn readFn(self: *Self, dest: []u8) error{}!usize { + return self.read(dest); + } + + pub fn inStream(self: *Self) std.io.InStream(*Self, error{}, readFn) { + return .{ .context = self }; + } + /// Returns number of items available in fifo pub fn writableLength(self: Self) usize { return self.buf.len - self.count; @@ -414,6 +424,15 @@ test "LinearFifo(u8, .Dynamic)" { testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]); testing.expectEqual(@as(usize, 0), fifo.readableLength()); } + + { + try fifo.outStream().writeAll("This is a test"); + var result: [30]u8 = undefined; + testing.expectEqualSlices(u8, "This", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?); + testing.expectEqualSlices(u8, "is", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?); + testing.expectEqualSlices(u8, "a", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?); + testing.expectEqualSlices(u8, "test", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?); + } } test "LinearFifo" { From deef063bbfd415c031f7281908805bf6f3920fdb Mon Sep 17 00:00:00 2001 From: Michael Dusan Date: Wed, 1 Apr 2020 22:47:22 -0400 Subject: [PATCH 81/89] use static-qemu linux-x86_64 tarball - no longer install qemu via apt-get - wget hosted tarball, extract and prepend to path --- ci/azure/linux_script | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ci/azure/linux_script b/ci/azure/linux_script index c34d8d324f..d3a0d40b53 100755 --- a/ci/azure/linux_script +++ b/ci/azure/linux_script @@ -12,7 +12,11 @@ sudo apt-get update -q sudo apt-get remove -y llvm-* sudo rm -rf /usr/local/* -sudo apt-get install -y libxml2-dev libclang-10-dev llvm-10 llvm-10-dev liblld-10-dev cmake s3cmd gcc-7 g++-7 qemu +sudo apt-get install -y libxml2-dev libclang-10-dev llvm-10 llvm-10-dev liblld-10-dev cmake s3cmd gcc-7 g++-7 + +wget https://ziglang.org/deps/qemu-5.0.0-rc1-x86_64-alpinelinux.tar.xz +tar xf qemu-5.0.0-rc1-x86_64-alpinelinux.tar.xz +PATH=$PWD/qemu-5.0.0-rc1/bin:$PATH # Make the `zig version` number consistent. # This will affect the cmake command below. From ba1a8b64c44b9b99e9f0002555b9b4a35092e8f6 Mon Sep 17 00:00:00 2001 From: Ilmari Autio Date: Mon, 2 Mar 2020 23:15:36 +0200 Subject: [PATCH 82/89] make std.os.getenvW case insensitive partially addresses #4603 Fixing std.process.getEnvMap is NOT included in this commit. --- lib/std/os.zig | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/std/os.zig b/lib/std/os.zig index 467badca95..07d4c19a89 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -21,6 +21,7 @@ const assert = std.debug.assert; const math = std.math; const mem = std.mem; const elf = std.elf; +const unicode = std.unicode; const dl = @import("dynamic_library.zig"); const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES; @@ -1206,6 +1207,19 @@ pub fn getenvZ(key: [*:0]const u8) ?[]const u8 { return getenv(mem.spanZ(key)); } +fn utf16LeAsciiEqlIgnoreCase(a: []const u16, b: []const u16) bool { + if (a.len != b.len) return false; + var a_it = unicode.Utf16LeIterator.init(a); + var b_it = unicode.Utf16LeIterator.init(b); + while (a_it.nextCodepoint() catch return false) |a_codepoint| { + const b_codepoint = (b_it.nextCodepoint() catch return false) orelse return false; + const upper_a = if (a_codepoint >= 97 and a_codepoint <= 122) a_codepoint & 0b11011111 else a_codepoint; + const upper_b = if (b_codepoint >= 97 and b_codepoint <= 122) b_codepoint & 0b11011111 else b_codepoint; + if (upper_a != upper_b) return false; + } + return true; +} + /// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name. /// See also `getenv`. pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 { @@ -1227,7 +1241,7 @@ pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 { while (ptr[i] != 0) : (i += 1) {} const this_value = ptr[value_start..i :0]; - if (mem.eql(u16, key_slice, this_key)) return this_value; + if (utf16LeAsciiEqlIgnoreCase(key_slice, this_key)) return this_value; i += 1; // skip over null byte } From 8bf7cffe29b520cda094756309bca1d354af0d6b Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 2 Apr 2020 15:04:42 -0400 Subject: [PATCH 83/89] slight modification of the semantics of std.os.getenvW Now, this function first attempts a case-sensitive lookup. If no match is found, and `key` is ASCII, then it attempts a second case-insensitive lookup. It is not planned to support full Unicode case-insensitivity on Windows, and in fact relying on non-ASCII case-insensitive environment variables is fundamentally problematic. --- lib/std/os.zig | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/lib/std/os.zig b/lib/std/os.zig index 07d4c19a89..bb206b289f 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -21,7 +21,6 @@ const assert = std.debug.assert; const math = std.math; const mem = std.mem; const elf = std.elf; -const unicode = std.unicode; const dl = @import("dynamic_library.zig"); const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES; @@ -1207,27 +1206,17 @@ pub fn getenvZ(key: [*:0]const u8) ?[]const u8 { return getenv(mem.spanZ(key)); } -fn utf16LeAsciiEqlIgnoreCase(a: []const u16, b: []const u16) bool { - if (a.len != b.len) return false; - var a_it = unicode.Utf16LeIterator.init(a); - var b_it = unicode.Utf16LeIterator.init(b); - while (a_it.nextCodepoint() catch return false) |a_codepoint| { - const b_codepoint = (b_it.nextCodepoint() catch return false) orelse return false; - const upper_a = if (a_codepoint >= 97 and a_codepoint <= 122) a_codepoint & 0b11011111 else a_codepoint; - const upper_b = if (b_codepoint >= 97 and b_codepoint <= 122) b_codepoint & 0b11011111 else b_codepoint; - if (upper_a != upper_b) return false; - } - return true; -} - /// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name. /// See also `getenv`. +/// This function first attempts a case-sensitive lookup. If no match is found, and `key` +/// is ASCII, then it attempts a second case-insensitive lookup. pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 { if (builtin.os.tag != .windows) { @compileError("std.os.getenvW is a Windows-only API"); } const key_slice = mem.spanZ(key); const ptr = windows.peb().ProcessParameters.Environment; + var ascii_match: ?[:0]const u16 = null; var i: usize = 0; while (ptr[i] != 0) { const key_start = i; @@ -1241,11 +1230,22 @@ pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 { while (ptr[i] != 0) : (i += 1) {} const this_value = ptr[value_start..i :0]; - if (utf16LeAsciiEqlIgnoreCase(key_slice, this_key)) return this_value; + if (mem.eql(u16, key_slice, this_key)) return this_value; + + ascii_check: { + if (ascii_match != null) break :ascii_check; + if (key_slice.len != this_key.len) break :ascii_check; + for (key_slice) |a_c, key_index| { + const a = math.cast(u8, a_c) catch break :ascii_check; + const b = math.cast(u8, this_key[key_index]) catch break :ascii_check; + if (std.ascii.toLower(a) != std.ascii.toLower(b)) break :ascii_check; + } + ascii_match = this_value; + } i += 1; // skip over null byte } - return null; + return ascii_match; } pub const GetCwdError = error{ From e4edc6d118e0e0cd3510bbe89ca4a292436bb82f Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 2 Apr 2020 15:47:27 -0400 Subject: [PATCH 84/89] zig cc: respect -MF -MV -MD options Zig disables its caching and forwards these args when any are provided. see #4784 --- src-self-hosted/clang_options_data.zig | 29 ++++++++++++++++++--- src-self-hosted/stage2.zig | 1 + src/all_types.hpp | 3 ++- src/codegen.cpp | 35 ++++++++++++++------------ src/main.cpp | 8 ++++++ src/stage2.h | 1 + tools/update_clang_options.zig | 12 +++++++++ 7 files changed, 68 insertions(+), 21 deletions(-) diff --git a/src-self-hosted/clang_options_data.zig b/src-self-hosted/clang_options_data.zig index f24039ba32..c7113afa4d 100644 --- a/src-self-hosted/clang_options_data.zig +++ b/src-self-hosted/clang_options_data.zig @@ -26,12 +26,26 @@ flagpd1("H"), }, flagpd1("I-"), flagpd1("M"), -flagpd1("MD"), +.{ + .name = "MD", + .syntax = .flag, + .zig_equivalent = .dep_file, + .pd1 = true, + .pd2 = false, + .psl = false, +}, flagpd1("MG"), flagpd1("MM"), flagpd1("MMD"), flagpd1("MP"), -flagpd1("MV"), +.{ + .name = "MV", + .syntax = .flag, + .zig_equivalent = .dep_file, + .pd1 = true, + .pd2 = false, + .psl = false, +}, flagpd1("Mach"), flagpd1("O0"), flagpd1("O4"), @@ -490,7 +504,7 @@ sepd1("Zlinker-input"), .{ .name = "MD", .syntax = .flag, - .zig_equivalent = .other, + .zig_equivalent = .dep_file, .pd1 = true, .pd2 = false, .psl = true, @@ -5434,7 +5448,14 @@ joinpd1("mtp="), joinpd1("gz="), joinpd1("A-"), joinpd1("G="), -jspd1("MF"), +.{ + .name = "MF", + .syntax = .joined_or_separate, + .zig_equivalent = .dep_file, + .pd1 = true, + .pd2 = false, + .psl = false, +}, jspd1("MJ"), jspd1("MQ"), jspd1("MT"), diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 798fb552c0..9f829b0152 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -1290,6 +1290,7 @@ pub const ClangArgIterator = extern struct { linker_input_z, lib_dir, mcpu, + dep_file, }; const Args = struct { diff --git a/src/all_types.hpp b/src/all_types.hpp index efb2cd1f0f..483a098474 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -2230,6 +2230,7 @@ struct CodeGen { bool reported_bad_link_libc_error; bool is_dynamic; // shared library rather than static library. dynamic musl rather than static musl. bool need_frame_size_prefix_data; + bool disable_c_depfile; //////////////////////////// Participates in Input Parameter Cache Hash /////// Note: there is a separate cache hash for builtin.zig, when adding fields, @@ -2258,6 +2259,7 @@ struct CodeGen { const ZigTarget *zig_target; TargetSubsystem subsystem; // careful using this directly; see detect_subsystem ValgrindSupport valgrind_support; + CodeModel code_model; bool strip_debug_symbols; bool is_test_build; bool is_single_threaded; @@ -2278,7 +2280,6 @@ struct CodeGen { bool emit_asm; bool emit_llvm_ir; bool test_is_evented; - CodeModel code_model; Buf *root_out_name; Buf *test_filter; diff --git a/src/codegen.cpp b/src/codegen.cpp index 5ead5f7d73..c02b79e97d 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -9803,7 +9803,7 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) { exit(1); } } - bool is_cache_miss = (buf_len(&digest) == 0); + bool is_cache_miss = g->disable_c_depfile || (buf_len(&digest) == 0); if (is_cache_miss) { // we can't know the digest until we do the C compiler invocation, so we // need a tmp filename. @@ -9822,9 +9822,10 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) { args.append("-c"); } - Buf *out_dep_path = buf_sprintf("%s.d", buf_ptr(out_obj_path)); + Buf *out_dep_path = g->disable_c_depfile ? nullptr : buf_sprintf("%s.d", buf_ptr(out_obj_path)); + const char *out_dep_path_cstr = (out_dep_path == nullptr) ? nullptr : buf_ptr(out_dep_path); FileExt ext = classify_file_ext(buf_ptr(c_source_basename), buf_len(c_source_basename)); - add_cc_args(g, args, buf_ptr(out_dep_path), false, ext); + add_cc_args(g, args, out_dep_path_cstr, false, ext); args.append("-o"); args.append(buf_ptr(out_obj_path)); @@ -9845,23 +9846,25 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) { exit(1); } - // add the files depended on to the cache system - if ((err = cache_add_dep_file(cache_hash, out_dep_path, true))) { - // Don't treat the absence of the .d file as a fatal error, the - // compiler may not produce one eg. when compiling .s files + if (out_dep_path != nullptr) { + // add the files depended on to the cache system + if ((err = cache_add_dep_file(cache_hash, out_dep_path, true))) { + // Don't treat the absence of the .d file as a fatal error, the + // compiler may not produce one eg. when compiling .s files + if (err != ErrorFileNotFound) { + fprintf(stderr, "Failed to add C source dependencies to cache: %s\n", err_str(err)); + exit(1); + } + } if (err != ErrorFileNotFound) { - fprintf(stderr, "Failed to add C source dependencies to cache: %s\n", err_str(err)); + os_delete_file(out_dep_path); + } + + if ((err = cache_final(cache_hash, &digest))) { + fprintf(stderr, "Unable to finalize cache hash: %s\n", err_str(err)); exit(1); } } - if (err != ErrorFileNotFound) { - os_delete_file(out_dep_path); - } - - if ((err = cache_final(cache_hash, &digest))) { - fprintf(stderr, "Unable to finalize cache hash: %s\n", err_str(err)); - exit(1); - } artifact_dir = buf_alloc(); os_path_join(o_dir, &digest, artifact_dir); if ((err = os_make_path(artifact_dir))) { diff --git a/src/main.cpp b/src/main.cpp index 206b733325..5436145bc3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -458,6 +458,7 @@ static int main0(int argc, char **argv) { bool only_pp_or_asm = false; bool ensure_libc_on_non_freestanding = false; bool ensure_libcpp_on_non_freestanding = false; + bool disable_c_depfile = false; ZigList llvm_argv = {0}; llvm_argv.append("zig (LLVM option parsing)"); @@ -741,6 +742,12 @@ static int main0(int argc, char **argv) { case Stage2ClangArgMCpu: mcpu = it.only_arg; break; + case Stage2ClangArgDepFile: + disable_c_depfile = true; + for (size_t i = 0; i < it.other_args_len; i += 1) { + clang_argv.append(it.other_args_ptr[i]); + } + break; } } // Parse linker args @@ -1520,6 +1527,7 @@ static int main0(int argc, char **argv) { g->system_linker_hack = system_linker_hack; g->function_sections = function_sections; g->code_model = code_model; + g->disable_c_depfile = disable_c_depfile; if (override_soname) { g->override_soname = buf_create_from_str(override_soname); diff --git a/src/stage2.h b/src/stage2.h index 8bb269dd23..c2a7bdc2f5 100644 --- a/src/stage2.h +++ b/src/stage2.h @@ -349,6 +349,7 @@ enum Stage2ClangArg { Stage2ClangArgLinkerInputZ, Stage2ClangArgLibDir, Stage2ClangArgMCpu, + Stage2ClangArgDepFile, }; // ABI warning diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index b85d708470..d6192c93cf 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -194,6 +194,18 @@ const known_options = [_]KnownOpt{ .name = "mtune", .ident = "mcpu", }, + .{ + .name = "MD", + .ident = "dep_file", + }, + .{ + .name = "MV", + .ident = "dep_file", + }, + .{ + .name = "MF", + .ident = "dep_file", + }, }; const blacklisted_options = [_][]const u8{}; From c4b3c84b3f64ad3c24c2b6ad36616e10c3cf98f3 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 2 Apr 2020 15:59:48 -0400 Subject: [PATCH 85/89] zig cc: support -F and -framework --- src-self-hosted/clang_options_data.zig | 20 +++++++++++++++++--- src-self-hosted/stage2.zig | 2 ++ src/main.cpp | 6 ++++++ src/stage2.h | 2 ++ tools/update_clang_options.zig | 8 ++++++++ 5 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src-self-hosted/clang_options_data.zig b/src-self-hosted/clang_options_data.zig index c7113afa4d..0b3a3b9416 100644 --- a/src-self-hosted/clang_options_data.zig +++ b/src-self-hosted/clang_options_data.zig @@ -2989,7 +2989,14 @@ sepd1("fprofile-remapping-file"), flagpd1("fprofile-sample-accurate"), flagpd1("fprofile-sample-use"), flagpd1("fprofile-use"), -sepd1("framework"), +.{ + .name = "framework", + .syntax = .separate, + .zig_equivalent = .framework, + .pd1 = true, + .pd2 = false, + .psl = false, +}, flagpd1("freciprocal-math"), flagpd1("frecord-command-line"), flagpd1("ffree-form"), @@ -5670,7 +5677,14 @@ jspd1("MT"), jspd1("A"), jspd1("B"), jspd1("D"), -jspd1("F"), +.{ + .name = "F", + .syntax = .joined_or_separate, + .zig_equivalent = .framework_dir, + .pd1 = true, + .pd2 = false, + .psl = false, +}, jspd1("G"), jspd1("I"), jspd1("J"), @@ -5715,7 +5729,7 @@ joinpd1("Z"), .{ .name = "F", .syntax = .joined_or_separate, - .zig_equivalent = .other, + .zig_equivalent = .framework_dir, .pd1 = true, .pd2 = false, .psl = true, diff --git a/src-self-hosted/stage2.zig b/src-self-hosted/stage2.zig index 9f829b0152..43e0a8ffca 100644 --- a/src-self-hosted/stage2.zig +++ b/src-self-hosted/stage2.zig @@ -1291,6 +1291,8 @@ pub const ClangArgIterator = extern struct { lib_dir, mcpu, dep_file, + framework_dir, + framework, }; const Args = struct { diff --git a/src/main.cpp b/src/main.cpp index 5436145bc3..d46947628a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -748,6 +748,12 @@ static int main0(int argc, char **argv) { clang_argv.append(it.other_args_ptr[i]); } break; + case Stage2ClangArgFrameworkDir: + framework_dirs.append(it.only_arg); + break; + case Stage2ClangArgFramework: + frameworks.append(it.only_arg); + break; } } // Parse linker args diff --git a/src/stage2.h b/src/stage2.h index c2a7bdc2f5..02b33419f6 100644 --- a/src/stage2.h +++ b/src/stage2.h @@ -350,6 +350,8 @@ enum Stage2ClangArg { Stage2ClangArgLibDir, Stage2ClangArgMCpu, Stage2ClangArgDepFile, + Stage2ClangArgFrameworkDir, + Stage2ClangArgFramework, }; // ABI warning diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index d6192c93cf..dd46f72d4c 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -206,6 +206,14 @@ const known_options = [_]KnownOpt{ .name = "MF", .ident = "dep_file", }, + .{ + .name = "F", + .ident = "framework_dir", + }, + .{ + .name = "framework", + .ident = "framework", + }, }; const blacklisted_options = [_][]const u8{}; From c1778bd41f1fd340662920909fdd9992ac55133e Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 2 Apr 2020 16:59:08 -0400 Subject: [PATCH 86/89] zig cc: support --version-script linker arg See #4784 --- src/main.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index d46947628a..278f684181 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -815,6 +815,13 @@ static int main0(int argc, char **argv) { buf_eql_str(arg, "-export-dynamic")) { rdynamic = true; + } else if (buf_eql_str(arg, "--version-script")) { + i += 1; + if (i >= linker_args.length) { + fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg)); + return EXIT_FAILURE; + } + version_script = linker_args.at(i); } else { fprintf(stderr, "warning: unsupported linker arg: %s\n", buf_ptr(arg)); } From 5314641e117f3b3d9cef2db527af532ddf18ccfc Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 2 Apr 2020 17:29:22 -0400 Subject: [PATCH 87/89] zig cc: support more linker args --- src/all_types.hpp | 11 +++++++ src/codegen.cpp | 5 +++ src/link.cpp | 80 ++++++++++++++++++++++++++++++++++++++++++----- src/main.cpp | 35 +++++++++++++++++++++ 4 files changed, 124 insertions(+), 7 deletions(-) diff --git a/src/all_types.hpp b/src/all_types.hpp index 483a098474..9b22279b91 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -2015,6 +2015,12 @@ enum WantCSanitize { WantCSanitizeEnabled, }; +enum OptionalBool { + OptionalBoolNull, + OptionalBoolFalse, + OptionalBoolTrue, +}; + struct CFile { ZigList args; const char *source_path; @@ -2260,6 +2266,8 @@ struct CodeGen { TargetSubsystem subsystem; // careful using this directly; see detect_subsystem ValgrindSupport valgrind_support; CodeModel code_model; + OptionalBool linker_gc_sections; + OptionalBool linker_allow_shlib_undefined; bool strip_debug_symbols; bool is_test_build; bool is_single_threaded; @@ -2280,6 +2288,8 @@ struct CodeGen { bool emit_asm; bool emit_llvm_ir; bool test_is_evented; + bool linker_z_nodelete; + bool linker_z_defs; Buf *root_out_name; Buf *test_filter; @@ -2288,6 +2298,7 @@ struct CodeGen { Buf *zig_std_dir; Buf *version_script_path; Buf *override_soname; + Buf *linker_optimization; const char **llvm_argv; size_t llvm_argv_len; diff --git a/src/codegen.cpp b/src/codegen.cpp index c02b79e97d..c9e67dcac5 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -10558,6 +10558,11 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) { } cache_buf_opt(ch, g->version_script_path); cache_buf_opt(ch, g->override_soname); + cache_buf_opt(ch, g->linker_optimization); + cache_int(ch, g->linker_gc_sections); + cache_int(ch, g->linker_allow_shlib_undefined); + cache_bool(ch, g->linker_z_nodelete); + cache_bool(ch, g->linker_z_defs); // gen_c_objects appends objects to g->link_objects which we want to include in the hash gen_c_objects(g); diff --git a/src/link.cpp b/src/link.cpp index fba572de98..e26a7ea436 100644 --- a/src/link.cpp +++ b/src/link.cpp @@ -1769,8 +1769,17 @@ static void construct_linker_job_elf(LinkJob *lj) { lj->args.append(g->linker_script); } - if (g->out_type != OutTypeObj) { - lj->args.append("--gc-sections"); + switch (g->linker_gc_sections) { + case OptionalBoolNull: + if (g->out_type != OutTypeObj) { + lj->args.append("--gc-sections"); + } + break; + case OptionalBoolTrue: + lj->args.append("--gc-sections"); + break; + case OptionalBoolFalse: + break; } if (g->link_eh_frame_hdr) { @@ -1781,6 +1790,19 @@ static void construct_linker_job_elf(LinkJob *lj) { lj->args.append("--export-dynamic"); } + if (g->linker_optimization != nullptr) { + lj->args.append(buf_ptr(g->linker_optimization)); + } + + if (g->linker_z_nodelete) { + lj->args.append("-z"); + lj->args.append("nodelete"); + } + if (g->linker_z_defs) { + lj->args.append("-z"); + lj->args.append("defs"); + } + lj->args.append("-m"); lj->args.append(getLDMOption(g->zig_target)); @@ -1971,8 +1993,17 @@ static void construct_linker_job_elf(LinkJob *lj) { } } - if (!g->zig_target->is_native_os) { - lj->args.append("--allow-shlib-undefined"); + switch (g->linker_allow_shlib_undefined) { + case OptionalBoolNull: + if (!g->zig_target->is_native_os) { + lj->args.append("--allow-shlib-undefined"); + } + break; + case OptionalBoolFalse: + break; + case OptionalBoolTrue: + lj->args.append("--allow-shlib-undefined"); + break; } } @@ -2536,10 +2567,34 @@ static void construct_linker_job_macho(LinkJob *lj) { //lj->args.append("-error-limit=0"); lj->args.append("-demangle"); + switch (g->linker_gc_sections) { + case OptionalBoolNull: + // TODO why do we not follow the same logic of elf here? + break; + case OptionalBoolTrue: + lj->args.append("--gc-sections"); + break; + case OptionalBoolFalse: + break; + } + if (g->linker_rdynamic) { lj->args.append("-export_dynamic"); } + if (g->linker_optimization != nullptr) { + lj->args.append(buf_ptr(g->linker_optimization)); + } + + if (g->linker_z_nodelete) { + lj->args.append("-z"); + lj->args.append("nodelete"); + } + if (g->linker_z_defs) { + lj->args.append("-z"); + lj->args.append("defs"); + } + bool is_lib = g->out_type == OutTypeLib; bool is_dyn_lib = g->is_dynamic && is_lib; if (is_lib && !g->is_dynamic) { @@ -2654,9 +2709,20 @@ static void construct_linker_job_macho(LinkJob *lj) { // and change between versions. // so we always link against libSystem lj->args.append("-lSystem"); - } else { - lj->args.append("-undefined"); - lj->args.append("dynamic_lookup"); + } + switch (g->linker_allow_shlib_undefined) { + case OptionalBoolNull: + if (!g->zig_target->is_native_os) { + lj->args.append("-undefined"); + lj->args.append("dynamic_lookup"); + } + break; + case OptionalBoolFalse: + break; + case OptionalBoolTrue: + lj->args.append("-undefined"); + lj->args.append("dynamic_lookup"); + break; } for (size_t i = 0; i < g->framework_dirs.length; i += 1) { diff --git a/src/main.cpp b/src/main.cpp index 278f684181..cd45d40e5f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -459,6 +459,11 @@ static int main0(int argc, char **argv) { bool ensure_libc_on_non_freestanding = false; bool ensure_libcpp_on_non_freestanding = false; bool disable_c_depfile = false; + Buf *linker_optimization = nullptr; + OptionalBool linker_gc_sections = OptionalBoolNull; + OptionalBool linker_allow_shlib_undefined = OptionalBoolNull; + bool linker_z_nodelete = false; + bool linker_z_defs = false; ZigList llvm_argv = {0}; llvm_argv.append("zig (LLVM option parsing)"); @@ -822,6 +827,30 @@ static int main0(int argc, char **argv) { return EXIT_FAILURE; } version_script = linker_args.at(i); + } else if (buf_starts_with_str(arg, "-O")) { + linker_optimization = arg; + } else if (buf_eql_str(arg, "--gc-sections")) { + linker_gc_sections = OptionalBoolTrue; + } else if (buf_eql_str(arg, "--no-gc-sections")) { + linker_gc_sections = OptionalBoolFalse; + } else if (buf_eql_str(arg, "--allow-shlib-undefined")) { + linker_allow_shlib_undefined = OptionalBoolTrue; + } else if (buf_eql_str(arg, "--no-allow-shlib-undefined")) { + linker_allow_shlib_undefined = OptionalBoolFalse; + } else if (buf_eql_str(arg, "-z")) { + i += 1; + if (i >= linker_args.length) { + fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg)); + return EXIT_FAILURE; + } + Buf *z_arg = linker_args.at(i); + if (buf_eql_str(z_arg, "nodelete")) { + linker_z_nodelete = true; + } else if (buf_eql_str(z_arg, "defs")) { + linker_z_defs = true; + } else { + fprintf(stderr, "warning: unsupported linker arg: -z %s\n", buf_ptr(z_arg)); + } } else { fprintf(stderr, "warning: unsupported linker arg: %s\n", buf_ptr(arg)); } @@ -1542,6 +1571,12 @@ static int main0(int argc, char **argv) { g->code_model = code_model; g->disable_c_depfile = disable_c_depfile; + g->linker_optimization = linker_optimization; + g->linker_gc_sections = linker_gc_sections; + g->linker_allow_shlib_undefined = linker_allow_shlib_undefined; + g->linker_z_nodelete = linker_z_nodelete; + g->linker_z_defs = linker_z_defs; + if (override_soname) { g->override_soname = buf_create_from_str(override_soname); } From b5526d0b3bb0329ed9ba614d45a1b711b118c315 Mon Sep 17 00:00:00 2001 From: Timon Kruiper Date: Thu, 2 Apr 2020 21:32:38 +0200 Subject: [PATCH 88/89] Fix multiplication overflow in `hash_const_val` In some cases the compiler was actually emitting an 64 bit signed multiplication, instead of a 32 bit unsigned one. --- src/analyze.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/analyze.cpp b/src/analyze.cpp index 9cc1ad2472..e627eaf91b 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -5361,7 +5361,7 @@ static uint32_t hash_const_val(ZigValue *const_val) { return result; } case ZigTypeIdEnumLiteral: - return buf_hash(const_val->data.x_enum_literal) * 2691276464; + return buf_hash(const_val->data.x_enum_literal) * (uint32_t)2691276464; case ZigTypeIdEnum: { uint32_t result = 31643936; @@ -5429,12 +5429,12 @@ static uint32_t hash_const_val(ZigValue *const_val) { return 2709806591; case ZigTypeIdOptional: if (get_src_ptr_type(const_val->type) != nullptr) { - return hash_const_val_ptr(const_val) * 1992916303; + return hash_const_val_ptr(const_val) * (uint32_t)1992916303; } else if (const_val->type->data.maybe.child_type->id == ZigTypeIdErrorSet) { - return hash_const_val_error_set(const_val) * 3147031929; + return hash_const_val_error_set(const_val) * (uint32_t)3147031929; } else { if (const_val->data.x_optional) { - return hash_const_val(const_val->data.x_optional) * 1992916303; + return hash_const_val(const_val->data.x_optional) * (uint32_t)1992916303; } else { return 4016830364; } From e7f555ca550cc73288adbdf4ec8d0e4abbc7a987 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 2 Apr 2020 19:07:31 -0400 Subject: [PATCH 89/89] stage1: fix build for i386-linux --- src/zig_clang.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/zig_clang.h b/src/zig_clang.h index 0e0582a08a..f938d8b56e 100644 --- a/src/zig_clang.h +++ b/src/zig_clang.h @@ -52,6 +52,8 @@ struct ZigClangAPValue { // experimentally-derived size of clang::APValue::DataType #if defined(_WIN32) && defined(_MSC_VER) char Data[52]; +#elif defined(__i386__) + char Data[48]; #else char Data[68]; #endif