authorgravatar for alex_naskos@hotmail.comAlexandros Naskos <alex_naskos@hotmail.com> 2020-03-02 00:55:19+02:00
committergravatar for alex_naskos@hotmail.comAlexandros Naskos <alex_naskos@hotmail.com> 2020-03-02 00:55:19+02:00
logb838122cc0bfef2d986c6addc688a35318777034
tree2ed5ef3aab4f9fa1f7f0bac2ad28690c3966ddcc
parent78e4daaa03613da5d1398f7c3bcbfda24086b051
parent00be934569d25e3b041091ff63a4cf6c456d1403

Merge branch 'master' of https://github.com/ziglang/zig into tuple_concat


134 files changed, 4069 insertions(+), 2290 deletions(-)

build.zig+1-1
...@@ -298,7 +298,7 @@ fn configureStage2(b: *Builder, exe: var, ctx: Context) !void {...@@ -298,7 +298,7 @@ fn configureStage2(b: *Builder, exe: var, ctx: Context) !void {
298 }298 }
299 dependOnLib(b, exe, ctx.llvm);299 dependOnLib(b, exe, ctx.llvm);
300300
301 if (exe.target.getOs() == .linux) {301 if (exe.target.getOsTag() == .linux) {
302 try addCxxKnownPath(b, ctx, exe, "libstdc++.a",302 try addCxxKnownPath(b, ctx, exe, "libstdc++.a",
303 \\Unable to determine path to libstdc++.a303 \\Unable to determine path to libstdc++.a
304 \\On Fedora, install libstdc++-static and try again.304 \\On Fedora, install libstdc++-static and try again.
doc/docgen.zig+42-41
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");
2const std = @import("std");1const std = @import("std");
2const builtin = std.builtin;
3const io = std.io;3const io = std.io;
4const fs = std.fs;4const fs = std.fs;
5const process = std.process;5const process = std.process;
...@@ -10,8 +10,8 @@ const testing = std.testing;...@@ -10,8 +10,8 @@ const testing = std.testing;
1010
11const max_doc_file_size = 10 * 1024 * 1024;11const max_doc_file_size = 10 * 1024 * 1024;
1212
13const exe_ext = @as(std.build.Target, std.build.Target.Native).exeFileExt();13const exe_ext = @as(std.zig.CrossTarget, .{}).exeFileExt();
14const obj_ext = @as(std.build.Target, std.build.Target.Native).oFileExt();14const obj_ext = @as(std.zig.CrossTarget, .{}).oFileExt();
15const tmp_dir_name = "docgen_tmp";15const tmp_dir_name = "docgen_tmp";
16const test_out_path = tmp_dir_name ++ fs.path.sep_str ++ "test" ++ exe_ext;16const test_out_path = tmp_dir_name ++ fs.path.sep_str ++ "test" ++ exe_ext;
1717
...@@ -521,7 +521,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -521,7 +521,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
521 return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {}", .{code_kind_str});521 return parseError(tokenizer, code_kind_tok, "unrecognized code kind: {}", .{code_kind_str});
522 }522 }
523523
524 var mode = builtin.Mode.Debug;524 var mode: builtin.Mode = .Debug;
525 var link_objects = std.ArrayList([]const u8).init(allocator);525 var link_objects = std.ArrayList([]const u8).init(allocator);
526 defer link_objects.deinit();526 defer link_objects.deinit();
527 var target_str: ?[]const u8 = null;527 var target_str: ?[]const u8 = null;
...@@ -533,9 +533,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -533,9 +533,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
533 const end_code_tag = try eatToken(tokenizer, Token.Id.TagContent);533 const end_code_tag = try eatToken(tokenizer, Token.Id.TagContent);
534 const end_tag_name = tokenizer.buffer[end_code_tag.start..end_code_tag.end];534 const end_tag_name = tokenizer.buffer[end_code_tag.start..end_code_tag.end];
535 if (mem.eql(u8, end_tag_name, "code_release_fast")) {535 if (mem.eql(u8, end_tag_name, "code_release_fast")) {
536 mode = builtin.Mode.ReleaseFast;536 mode = .ReleaseFast;
537 } else if (mem.eql(u8, end_tag_name, "code_release_safe")) {537 } else if (mem.eql(u8, end_tag_name, "code_release_safe")) {
538 mode = builtin.Mode.ReleaseSafe;538 mode = .ReleaseSafe;
539 } else if (mem.eql(u8, end_tag_name, "code_link_object")) {539 } else if (mem.eql(u8, end_tag_name, "code_link_object")) {
540 _ = try eatToken(tokenizer, Token.Id.Separator);540 _ = try eatToken(tokenizer, Token.Id.Separator);
541 const obj_tok = try eatToken(tokenizer, Token.Id.TagContent);541 const obj_tok = try eatToken(tokenizer, Token.Id.TagContent);
...@@ -1001,30 +1001,30 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1001,30 +1001,30 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
10011001
1002 for (toc.nodes) |node| {1002 for (toc.nodes) |node| {
1003 switch (node) {1003 switch (node) {
1004 Node.Content => |data| {1004 .Content => |data| {
1005 try out.write(data);1005 try out.write(data);
1006 },1006 },
1007 Node.Link => |info| {1007 .Link => |info| {
1008 if (!toc.urls.contains(info.url)) {1008 if (!toc.urls.contains(info.url)) {
1009 return parseError(tokenizer, info.token, "url not found: {}", .{info.url});1009 return parseError(tokenizer, info.token, "url not found: {}", .{info.url});
1010 }1010 }
1011 try out.print("<a href=\"#{}\">{}</a>", .{ info.url, info.name });1011 try out.print("<a href=\"#{}\">{}</a>", .{ info.url, info.name });
1012 },1012 },
1013 Node.Nav => {1013 .Nav => {
1014 try out.write(toc.toc);1014 try out.write(toc.toc);
1015 },1015 },
1016 Node.Builtin => |tok| {1016 .Builtin => |tok| {
1017 try out.write("<pre>");1017 try out.write("<pre>");
1018 try tokenizeAndPrintRaw(tokenizer, out, tok, builtin_code);1018 try tokenizeAndPrintRaw(tokenizer, out, tok, builtin_code);
1019 try out.write("</pre>");1019 try out.write("</pre>");
1020 },1020 },
1021 Node.HeaderOpen => |info| {1021 .HeaderOpen => |info| {
1022 try out.print(1022 try out.print(
1023 "<h{} id=\"{}\"><a href=\"#toc-{}\">{}</a> <a class=\"hdr\" href=\"#{}\">§</a></h{}>\n",1023 "<h{} id=\"{}\"><a href=\"#toc-{}\">{}</a> <a class=\"hdr\" href=\"#{}\">§</a></h{}>\n",
1024 .{ info.n, info.url, info.url, info.name, info.url, info.n },1024 .{ info.n, info.url, info.url, info.name, info.url, info.n },
1025 );1025 );
1026 },1026 },
1027 Node.SeeAlso => |items| {1027 .SeeAlso => |items| {
1028 try out.write("<p>See also:</p><ul>\n");1028 try out.write("<p>See also:</p><ul>\n");
1029 for (items) |item| {1029 for (items) |item| {
1030 const url = try urlize(allocator, item.name);1030 const url = try urlize(allocator, item.name);
...@@ -1035,10 +1035,10 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1035,10 +1035,10 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1035 }1035 }
1036 try out.write("</ul>\n");1036 try out.write("</ul>\n");
1037 },1037 },
1038 Node.Syntax => |content_tok| {1038 .Syntax => |content_tok| {
1039 try tokenizeAndPrint(tokenizer, out, content_tok);1039 try tokenizeAndPrint(tokenizer, out, content_tok);
1040 },1040 },
1041 Node.Code => |code| {1041 .Code => |code| {
1042 code_progress_index += 1;1042 code_progress_index += 1;
1043 warn("docgen example code {}/{}...", .{ code_progress_index, tokenizer.code_node_count });1043 warn("docgen example code {}/{}...", .{ code_progress_index, tokenizer.code_node_count });
10441044
...@@ -1075,16 +1075,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1075,16 +1075,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1075 });1075 });
1076 try out.print("<pre><code class=\"shell\">$ zig build-exe {}.zig", .{code.name});1076 try out.print("<pre><code class=\"shell\">$ zig build-exe {}.zig", .{code.name});
1077 switch (code.mode) {1077 switch (code.mode) {
1078 builtin.Mode.Debug => {},1078 .Debug => {},
1079 builtin.Mode.ReleaseSafe => {1079 .ReleaseSafe => {
1080 try build_args.append("--release-safe");1080 try build_args.append("--release-safe");
1081 try out.print(" --release-safe", .{});1081 try out.print(" --release-safe", .{});
1082 },1082 },
1083 builtin.Mode.ReleaseFast => {1083 .ReleaseFast => {
1084 try build_args.append("--release-fast");1084 try build_args.append("--release-fast");
1085 try out.print(" --release-fast", .{});1085 try out.print(" --release-fast", .{});
1086 },1086 },
1087 builtin.Mode.ReleaseSmall => {1087 .ReleaseSmall => {
1088 try build_args.append("--release-small");1088 try build_args.append("--release-small");
1089 try out.print(" --release-small", .{});1089 try out.print(" --release-small", .{});
1090 },1090 },
...@@ -1142,13 +1142,14 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1142,13 +1142,14 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1142 try out.print("\n{}</code></pre>\n", .{colored_stderr});1142 try out.print("\n{}</code></pre>\n", .{colored_stderr});
1143 break :code_block;1143 break :code_block;
1144 }1144 }
1145 const exec_result = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{});1145 const exec_result = exec(allocator, &env_map, build_args.toSliceConst()) catch
1146 return parseError(tokenizer, code.source_token, "example failed to compile", .{});
11461147
1147 if (code.target_str) |triple| {1148 if (code.target_str) |triple| {
1148 if (mem.startsWith(u8, triple, "wasm32") or1149 if (mem.startsWith(u8, triple, "wasm32") or
1149 mem.startsWith(u8, triple, "riscv64-linux") or1150 mem.startsWith(u8, triple, "riscv64-linux") or
1150 mem.startsWith(u8, triple, "x86_64-linux") and1151 (mem.startsWith(u8, triple, "x86_64-linux") and
1151 (builtin.os != .linux or builtin.arch != .x86_64))1152 std.Target.current.os.tag != .linux or std.Target.current.cpu.arch != .x86_64))
1152 {1153 {
1153 // skip execution1154 // skip execution
1154 try out.print("</code></pre>\n", .{});1155 try out.print("</code></pre>\n", .{});
...@@ -1207,16 +1208,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1207,16 +1208,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1207 });1208 });
1208 try out.print("<pre><code class=\"shell\">$ zig test {}.zig", .{code.name});1209 try out.print("<pre><code class=\"shell\">$ zig test {}.zig", .{code.name});
1209 switch (code.mode) {1210 switch (code.mode) {
1210 builtin.Mode.Debug => {},1211 .Debug => {},
1211 builtin.Mode.ReleaseSafe => {1212 .ReleaseSafe => {
1212 try test_args.append("--release-safe");1213 try test_args.append("--release-safe");
1213 try out.print(" --release-safe", .{});1214 try out.print(" --release-safe", .{});
1214 },1215 },
1215 builtin.Mode.ReleaseFast => {1216 .ReleaseFast => {
1216 try test_args.append("--release-fast");1217 try test_args.append("--release-fast");
1217 try out.print(" --release-fast", .{});1218 try out.print(" --release-fast", .{});
1218 },1219 },
1219 builtin.Mode.ReleaseSmall => {1220 .ReleaseSmall => {
1220 try test_args.append("--release-small");1221 try test_args.append("--release-small");
1221 try out.print(" --release-small", .{});1222 try out.print(" --release-small", .{});
1222 },1223 },
...@@ -1249,16 +1250,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1249,16 +1250,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1249 });1250 });
1250 try out.print("<pre><code class=\"shell\">$ zig test {}.zig", .{code.name});1251 try out.print("<pre><code class=\"shell\">$ zig test {}.zig", .{code.name});
1251 switch (code.mode) {1252 switch (code.mode) {
1252 builtin.Mode.Debug => {},1253 .Debug => {},
1253 builtin.Mode.ReleaseSafe => {1254 .ReleaseSafe => {
1254 try test_args.append("--release-safe");1255 try test_args.append("--release-safe");
1255 try out.print(" --release-safe", .{});1256 try out.print(" --release-safe", .{});
1256 },1257 },
1257 builtin.Mode.ReleaseFast => {1258 .ReleaseFast => {
1258 try test_args.append("--release-fast");1259 try test_args.append("--release-fast");
1259 try out.print(" --release-fast", .{});1260 try out.print(" --release-fast", .{});
1260 },1261 },
1261 builtin.Mode.ReleaseSmall => {1262 .ReleaseSmall => {
1262 try test_args.append("--release-small");1263 try test_args.append("--release-small");
1263 try out.print(" --release-small", .{});1264 try out.print(" --release-small", .{});
1264 },1265 },
...@@ -1306,16 +1307,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1306,16 +1307,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1306 });1307 });
1307 var mode_arg: []const u8 = "";1308 var mode_arg: []const u8 = "";
1308 switch (code.mode) {1309 switch (code.mode) {
1309 builtin.Mode.Debug => {},1310 .Debug => {},
1310 builtin.Mode.ReleaseSafe => {1311 .ReleaseSafe => {
1311 try test_args.append("--release-safe");1312 try test_args.append("--release-safe");
1312 mode_arg = " --release-safe";1313 mode_arg = " --release-safe";
1313 },1314 },
1314 builtin.Mode.ReleaseFast => {1315 .ReleaseFast => {
1315 try test_args.append("--release-fast");1316 try test_args.append("--release-fast");
1316 mode_arg = " --release-fast";1317 mode_arg = " --release-fast";
1317 },1318 },
1318 builtin.Mode.ReleaseSmall => {1319 .ReleaseSmall => {
1319 try test_args.append("--release-small");1320 try test_args.append("--release-small");
1320 mode_arg = " --release-small";1321 mode_arg = " --release-small";
1321 },1322 },
...@@ -1386,20 +1387,20 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1386,20 +1387,20 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1386 }1387 }
13871388
1388 switch (code.mode) {1389 switch (code.mode) {
1389 builtin.Mode.Debug => {},1390 .Debug => {},
1390 builtin.Mode.ReleaseSafe => {1391 .ReleaseSafe => {
1391 try build_args.append("--release-safe");1392 try build_args.append("--release-safe");
1392 if (!code.is_inline) {1393 if (!code.is_inline) {
1393 try out.print(" --release-safe", .{});1394 try out.print(" --release-safe", .{});
1394 }1395 }
1395 },1396 },
1396 builtin.Mode.ReleaseFast => {1397 .ReleaseFast => {
1397 try build_args.append("--release-fast");1398 try build_args.append("--release-fast");
1398 if (!code.is_inline) {1399 if (!code.is_inline) {
1399 try out.print(" --release-fast", .{});1400 try out.print(" --release-fast", .{});
1400 }1401 }
1401 },1402 },
1402 builtin.Mode.ReleaseSmall => {1403 .ReleaseSmall => {
1403 try build_args.append("--release-small");1404 try build_args.append("--release-small");
1404 if (!code.is_inline) {1405 if (!code.is_inline) {
1405 try out.print(" --release-small", .{});1406 try out.print(" --release-small", .{});
...@@ -1461,16 +1462,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1461,16 +1462,16 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1461 });1462 });
1462 try out.print("<pre><code class=\"shell\">$ zig build-lib {}.zig", .{code.name});1463 try out.print("<pre><code class=\"shell\">$ zig build-lib {}.zig", .{code.name});
1463 switch (code.mode) {1464 switch (code.mode) {
1464 builtin.Mode.Debug => {},1465 .Debug => {},
1465 builtin.Mode.ReleaseSafe => {1466 .ReleaseSafe => {
1466 try test_args.append("--release-safe");1467 try test_args.append("--release-safe");
1467 try out.print(" --release-safe", .{});1468 try out.print(" --release-safe", .{});
1468 },1469 },
1469 builtin.Mode.ReleaseFast => {1470 .ReleaseFast => {
1470 try test_args.append("--release-fast");1471 try test_args.append("--release-fast");
1471 try out.print(" --release-fast", .{});1472 try out.print(" --release-fast", .{});
1472 },1473 },
1473 builtin.Mode.ReleaseSmall => {1474 .ReleaseSmall => {
1474 try test_args.append("--release-small");1475 try test_args.append("--release-small");
1475 try out.print(" --release-small", .{});1476 try out.print(" --release-small", .{});
1476 },1477 },
doc/langref.html.in+15-15
...@@ -965,7 +965,8 @@ const nan = std.math.nan(f128);...@@ -965,7 +965,8 @@ const nan = std.math.nan(f128);
965 but you can switch to {#syntax#}Optimized{#endsyntax#} mode on a per-block basis:</p>965 but you can switch to {#syntax#}Optimized{#endsyntax#} mode on a per-block basis:</p>
966 {#code_begin|obj|foo#}966 {#code_begin|obj|foo#}
967 {#code_release_fast#}967 {#code_release_fast#}
968const builtin = @import("builtin");968const std = @import("std");
969const builtin = std.builtin;
969const big = @as(f64, 1 << 40);970const big = @as(f64, 1 << 40);
970971
971export fn foo_strict(x: f64) f64 {972export fn foo_strict(x: f64) f64 {
...@@ -2063,15 +2064,15 @@ test "pointer child type" {...@@ -2063,15 +2064,15 @@ test "pointer child type" {
2063 alignment of the underlying type, it can be omitted from the type:2064 alignment of the underlying type, it can be omitted from the type:
2064 </p>2065 </p>
2065 {#code_begin|test#}2066 {#code_begin|test#}
2066const assert = @import("std").debug.assert;2067const std = @import("std");
2067const builtin = @import("builtin");2068const assert = std.debug.assert;
20682069
2069test "variable alignment" {2070test "variable alignment" {
2070 var x: i32 = 1234;2071 var x: i32 = 1234;
2071 const align_of_i32 = @alignOf(@TypeOf(x));2072 const align_of_i32 = @alignOf(@TypeOf(x));
2072 assert(@TypeOf(&x) == *i32);2073 assert(@TypeOf(&x) == *i32);
2073 assert(*i32 == *align(align_of_i32) i32);2074 assert(*i32 == *align(align_of_i32) i32);
2074 if (builtin.arch == builtin.Arch.x86_64) {2075 if (std.Target.current.cpu.arch == .x86_64) {
2075 assert((*i32).alignment == 4);2076 assert((*i32).alignment == 4);
2076 }2077 }
2077}2078}
...@@ -2474,7 +2475,7 @@ test "default struct initialization fields" {...@@ -2474,7 +2475,7 @@ test "default struct initialization fields" {
2474 </p>2475 </p>
2475 {#code_begin|test#}2476 {#code_begin|test#}
2476const std = @import("std");2477const std = @import("std");
2477const builtin = @import("builtin");2478const builtin = std.builtin;
2478const assert = std.debug.assert;2479const assert = std.debug.assert;
24792480
2480const Full = packed struct {2481const Full = packed struct {
...@@ -3204,8 +3205,8 @@ test "separate scopes" {...@@ -3204,8 +3205,8 @@ test "separate scopes" {
32043205
3205 {#header_open|switch#}3206 {#header_open|switch#}
3206 {#code_begin|test|switch#}3207 {#code_begin|test|switch#}
3207const assert = @import("std").debug.assert;3208const std = @import("std");
3208const builtin = @import("builtin");3209const assert = std.debug.assert;
32093210
3210test "switch simple" {3211test "switch simple" {
3211 const a: u64 = 10;3212 const a: u64 = 10;
...@@ -3249,16 +3250,16 @@ test "switch simple" {...@@ -3249,16 +3250,16 @@ test "switch simple" {
3249}3250}
32503251
3251// Switch expressions can be used outside a function:3252// Switch expressions can be used outside a function:
3252const os_msg = switch (builtin.os) {3253const os_msg = switch (std.Target.current.os.tag) {
3253 builtin.Os.linux => "we found a linux user",3254 .linux => "we found a linux user",
3254 else => "not a linux user",3255 else => "not a linux user",
3255};3256};
32563257
3257// Inside a function, switch statements implicitly are compile-time3258// Inside a function, switch statements implicitly are compile-time
3258// evaluated if the target expression is compile-time known.3259// evaluated if the target expression is compile-time known.
3259test "switch inside function" {3260test "switch inside function" {
3260 switch (builtin.os) {3261 switch (std.Target.current.os.tag) {
3261 builtin.Os.fuchsia => {3262 .fuchsia => {
3262 // On an OS other than fuchsia, block is not even analyzed,3263 // On an OS other than fuchsia, block is not even analyzed,
3263 // so this compile error is not triggered.3264 // so this compile error is not triggered.
3264 // On fuchsia this compile error would be triggered.3265 // On fuchsia this compile error would be triggered.
...@@ -7364,8 +7365,6 @@ test "main" {...@@ -7364,8 +7365,6 @@ test "main" {
7364 the {#syntax#}export{#endsyntax#} keyword used on a function:7365 the {#syntax#}export{#endsyntax#} keyword used on a function:
7365 </p>7366 </p>
7366 {#code_begin|obj#}7367 {#code_begin|obj#}
7367const builtin = @import("builtin");
7368
7369comptime {7368comptime {
7370 @export(internalName, .{ .name = "foo", .linkage = .Strong });7369 @export(internalName, .{ .name = "foo", .linkage = .Strong });
7371}7370}
...@@ -9397,7 +9396,7 @@ const separator = if (builtin.os == builtin.Os.windows) '\\' else '/';...@@ -9397,7 +9396,7 @@ const separator = if (builtin.os == builtin.Os.windows) '\\' else '/';
9397 </p>9396 </p>
9398 {#code_begin|test|detect_test#}9397 {#code_begin|test|detect_test#}
9399const std = @import("std");9398const std = @import("std");
9400const builtin = @import("builtin");9399const builtin = std.builtin;
9401const assert = std.debug.assert;9400const assert = std.debug.assert;
94029401
9403test "builtin.is_test" {9402test "builtin.is_test" {
...@@ -9715,7 +9714,8 @@ WebAssembly.instantiate(typedArray, {...@@ -9715,7 +9714,8 @@ WebAssembly.instantiate(typedArray, {
9715 <pre><code>$ node test.js9714 <pre><code>$ node test.js
9716The result is 3</code></pre>9715The result is 3</code></pre>
9717 {#header_open|WASI#}9716 {#header_open|WASI#}
9718 <p>Zig's support for WebAssembly System Interface (WASI) is under active development. Example of using the standard library and reading command line arguments:</p>9717 <p>Zig's support for WebAssembly System Interface (WASI) is under active development.
9718 Example of using the standard library and reading command line arguments:</p>
9719 {#code_begin|exe|wasi#}9719 {#code_begin|exe|wasi#}
9720 {#target_wasi#}9720 {#target_wasi#}
9721const std = @import("std");9721const std = @import("std");
lib/std/build.zig+137-110
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const std = @import("std.zig");1const std = @import("std.zig");
2const builtin = @import("builtin");2const builtin = std.builtin;
3const io = std.io;3const io = std.io;
4const fs = std.fs;4const fs = std.fs;
5const mem = std.mem;5const mem = std.mem;
...@@ -15,6 +15,7 @@ const BufSet = std.BufSet;...@@ -15,6 +15,7 @@ const BufSet = std.BufSet;
15const BufMap = std.BufMap;15const BufMap = std.BufMap;
16const fmt_lib = std.fmt;16const fmt_lib = std.fmt;
17const File = std.fs.File;17const File = std.fs.File;
18const CrossTarget = std.zig.CrossTarget;
1819
19pub const FmtStep = @import("build/fmt.zig").FmtStep;20pub const FmtStep = @import("build/fmt.zig").FmtStep;
20pub const TranslateCStep = @import("build/translate_c.zig").TranslateCStep;21pub const TranslateCStep = @import("build/translate_c.zig").TranslateCStep;
...@@ -521,24 +522,91 @@ pub const Builder = struct {...@@ -521,24 +522,91 @@ pub const Builder = struct {
521 return mode;522 return mode;
522 }523 }
523524
524 /// Exposes standard `zig build` options for choosing a target. Pass `null` to support all targets.525 pub const StandardTargetOptionsArgs = struct {
525 pub fn standardTargetOptions(self: *Builder, supported_targets: ?[]const Target) Target {526 whitelist: ?[]const CrossTarget = null,
526 if (supported_targets) |target_list| {527
527 // TODO detect multiple args and emit an error message528 default_target: CrossTarget = CrossTarget{},
528 // there's probably a better way to collect the target529 };
529 for (target_list) |targ| {530
530 const targ_str = targ.zigTriple(self.allocator) catch unreachable;531 /// Exposes standard `zig build` options for choosing a target.
531 const targ_desc = targ.allocDescription(self.allocator) catch unreachable;532 pub fn standardTargetOptions(self: *Builder, args: StandardTargetOptionsArgs) CrossTarget {
532 const this_targ_opt = self.option(bool, targ_str, targ_desc) orelse false;533 const triple = self.option(
533 if (this_targ_opt) {534 []const u8,
534 return targ;535 "target",
536 "The CPU architecture, OS, and ABI to build for.",
537 ) orelse return args.default_target;
538
539 // TODO add cpu and features as part of the target triple
540
541 var diags: CrossTarget.ParseOptions.Diagnostics = .{};
542 const selected_target = CrossTarget.parse(.{
543 .arch_os_abi = triple,
544 .diagnostics = &diags,
545 }) catch |err| switch (err) {
546 error.UnknownCpuModel => {
547 std.debug.warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{
548 diags.cpu_name.?,
549 @tagName(diags.arch.?),
550 });
551 for (diags.arch.?.allCpuModels()) |cpu| {
552 std.debug.warn(" {}\n", .{cpu.name});
553 }
554 process.exit(1);
555 },
556 error.UnknownCpuFeature => {
557 std.debug.warn(
558 \\Unknown CPU feature: '{}'
559 \\Available CPU features for architecture '{}':
560 \\
561 , .{
562 diags.unknown_feature_name,
563 @tagName(diags.arch.?),
564 });
565 for (diags.arch.?.allFeaturesList()) |feature| {
566 std.debug.warn(" {}: {}\n", .{ feature.name, feature.description });
567 }
568 process.exit(1);
569 },
570 error.UnknownOperatingSystem => {
571 std.debug.warn(
572 \\Unknown OS: '{}'
573 \\Available operating systems:
574 \\
575 , .{diags.os_name});
576 inline for (std.meta.fields(std.Target.Os.Tag)) |field| {
577 std.debug.warn(" {}\n", .{field.name});
578 }
579 process.exit(1);
580 },
581 else => |e| {
582 std.debug.warn("Unable to parse target '{}': {}\n", .{ triple, @errorName(e) });
583 process.exit(1);
584 },
585 };
586
587 const selected_canonicalized_triple = selected_target.zigTriple(self.allocator) catch unreachable;
588
589 if (args.whitelist) |list| whitelist_check: {
590 // Make sure it's a match of one of the list.
591 for (list) |t| {
592 const t_triple = t.zigTriple(self.allocator) catch unreachable;
593 if (mem.eql(u8, t_triple, selected_canonicalized_triple)) {
594 break :whitelist_check;
535 }595 }
536 }596 }
537 return Target.Native;597 std.debug.warn("Chosen target '{}' does not match one of the supported targets:\n", .{
538 } else {598 selected_canonicalized_triple,
539 const target_str = self.option([]const u8, "target", "the target to build for") orelse return Target.Native;599 });
540 return Target.parse(.{ .arch_os_abi = target_str }) catch unreachable; // TODO better error message for bad target600 for (list) |t| {
601 const t_triple = t.zigTriple(self.allocator) catch unreachable;
602 std.debug.warn(" {}\n", .{t_triple});
603 }
604 // TODO instead of process exit, return error and have a zig build flag implemented by
605 // the build runner that turns process exits into error return traces
606 process.exit(1);
541 }607 }
608
609 return selected_target;
542 }610 }
543611
544 pub fn addUserInputOption(self: *Builder, name: []const u8, value: []const u8) !bool {612 pub fn addUserInputOption(self: *Builder, name: []const u8, value: []const u8) !bool {
...@@ -796,7 +864,7 @@ pub const Builder = struct {...@@ -796,7 +864,7 @@ pub const Builder = struct {
796864
797 pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {865 pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {
798 // TODO report error for ambiguous situations866 // TODO report error for ambiguous situations
799 const exe_extension = (Target{ .Native = {} }).exeFileExt();867 const exe_extension = @as(CrossTarget, .{}).exeFileExt();
800 for (self.search_prefixes.toSliceConst()) |search_prefix| {868 for (self.search_prefixes.toSliceConst()) |search_prefix| {
801 for (names) |name| {869 for (names) |name| {
802 if (fs.path.isAbsolute(name)) {870 if (fs.path.isAbsolute(name)) {
...@@ -971,21 +1039,19 @@ pub const Builder = struct {...@@ -971,21 +1039,19 @@ pub const Builder = struct {
971};1039};
9721040
973test "builder.findProgram compiles" {1041test "builder.findProgram compiles" {
974 // TODO: uncomment and fix the leak1042 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
975 // const builder = try Builder.create(std.testing.allocator, "zig", "zig-cache", "zig-cache");1043 defer arena.deinit();
976 const builder = try Builder.create(std.heap.page_allocator, "zig", "zig-cache", "zig-cache");1044
1045 const builder = try Builder.create(&arena.allocator, "zig", "zig-cache", "zig-cache");
977 defer builder.destroy();1046 defer builder.destroy();
978 _ = builder.findProgram(&[_][]const u8{}, &[_][]const u8{}) catch null;1047 _ = builder.findProgram(&[_][]const u8{}, &[_][]const u8{}) catch null;
979}1048}
9801049
981/// Deprecated. Use `builtin.Version`.1050/// Deprecated. Use `std.builtin.Version`.
982pub const Version = builtin.Version;1051pub const Version = builtin.Version;
9831052
984/// Deprecated. Use `std.Target.Cross`.1053/// Deprecated. Use `std.zig.CrossTarget`.
985pub const CrossTarget = std.Target.Cross;1054pub const Target = std.zig.CrossTarget;
986
987/// Deprecated. Use `std.Target`.
988pub const Target = std.Target;
9891055
990pub const Pkg = struct {1056pub const Pkg = struct {
991 name: []const u8,1057 name: []const u8,
...@@ -1038,7 +1104,7 @@ pub const LibExeObjStep = struct {...@@ -1038,7 +1104,7 @@ pub const LibExeObjStep = struct {
1038 step: Step,1104 step: Step,
1039 builder: *Builder,1105 builder: *Builder,
1040 name: []const u8,1106 name: []const u8,
1041 target: Target,1107 target: CrossTarget = CrossTarget{},
1042 linker_script: ?[]const u8 = null,1108 linker_script: ?[]const u8 = null,
1043 version_script: ?[]const u8 = null,1109 version_script: ?[]const u8 = null,
1044 out_filename: []const u8,1110 out_filename: []const u8,
...@@ -1076,7 +1142,7 @@ pub const LibExeObjStep = struct {...@@ -1076,7 +1142,7 @@ pub const LibExeObjStep = struct {
1076 out_pdb_filename: []const u8,1142 out_pdb_filename: []const u8,
1077 packages: ArrayList(Pkg),1143 packages: ArrayList(Pkg),
1078 build_options_contents: std.Buffer,1144 build_options_contents: std.Buffer,
1079 system_linker_hack: bool,1145 system_linker_hack: bool = false,
10801146
1081 object_src: []const u8,1147 object_src: []const u8,
10821148
...@@ -1091,7 +1157,6 @@ pub const LibExeObjStep = struct {...@@ -1091,7 +1157,6 @@ pub const LibExeObjStep = struct {
1091 install_step: ?*InstallArtifactStep,1157 install_step: ?*InstallArtifactStep,
10921158
1093 libc_file: ?[]const u8 = null,1159 libc_file: ?[]const u8 = null,
1094 target_glibc: ?Version = null,
10951160
1096 valgrind_support: ?bool = null,1161 valgrind_support: ?bool = null,
10971162
...@@ -1112,8 +1177,6 @@ pub const LibExeObjStep = struct {...@@ -1112,8 +1177,6 @@ pub const LibExeObjStep = struct {
1112 /// that contains the path `aarch64-linux-gnu/lib/ld-linux-aarch64.so.1`.1177 /// that contains the path `aarch64-linux-gnu/lib/ld-linux-aarch64.so.1`.
1113 glibc_multi_install_dir: ?[]const u8 = null,1178 glibc_multi_install_dir: ?[]const u8 = null,
11141179
1115 dynamic_linker: ?[]const u8 = null,
1116
1117 /// Position Independent Code1180 /// Position Independent Code
1118 force_pic: ?bool = null,1181 force_pic: ?bool = null,
11191182
...@@ -1191,7 +1254,6 @@ pub const LibExeObjStep = struct {...@@ -1191,7 +1254,6 @@ pub const LibExeObjStep = struct {
1191 .kind = kind,1254 .kind = kind,
1192 .root_src = root_src,1255 .root_src = root_src,
1193 .name = name,1256 .name = name,
1194 .target = Target.Native,
1195 .frameworks = BufSet.init(builder.allocator),1257 .frameworks = BufSet.init(builder.allocator),
1196 .step = Step.init(name, builder.allocator, make),1258 .step = Step.init(name, builder.allocator, make),
1197 .version = ver,1259 .version = ver,
...@@ -1210,7 +1272,6 @@ pub const LibExeObjStep = struct {...@@ -1210,7 +1272,6 @@ pub const LibExeObjStep = struct {
1210 .object_src = undefined,1272 .object_src = undefined,
1211 .build_options_contents = std.Buffer.initSize(builder.allocator, 0) catch unreachable,1273 .build_options_contents = std.Buffer.initSize(builder.allocator, 0) catch unreachable,
1212 .c_std = Builder.CStd.C99,1274 .c_std = Builder.CStd.C99,
1213 .system_linker_hack = false,
1214 .override_lib_dir = null,1275 .override_lib_dir = null,
1215 .main_pkg_path = null,1276 .main_pkg_path = null,
1216 .exec_cmd_args = null,1277 .exec_cmd_args = null,
...@@ -1282,36 +1343,11 @@ pub const LibExeObjStep = struct {...@@ -1282,36 +1343,11 @@ pub const LibExeObjStep = struct {
1282 }1343 }
1283 }1344 }
12841345
1285 /// Deprecated. Use `setTheTarget`.1346 pub fn setTarget(self: *LibExeObjStep, target: CrossTarget) void {
1286 pub fn setTarget(
1287 self: *LibExeObjStep,
1288 target_arch: builtin.Arch,
1289 target_os: builtin.Os,
1290 target_abi: builtin.Abi,
1291 ) void {
1292 return self.setTheTarget(Target{
1293 .Cross = CrossTarget{
1294 .arch = target_arch,
1295 .os = target_os,
1296 .abi = target_abi,
1297 .cpu_features = target_arch.getBaselineCpuFeatures(),
1298 },
1299 });
1300 }
1301
1302 pub fn setTheTarget(self: *LibExeObjStep, target: Target) void {
1303 self.target = target;1347 self.target = target;
1304 self.computeOutFileNames();1348 self.computeOutFileNames();
1305 }1349 }
13061350
1307 pub fn setTargetGLibC(self: *LibExeObjStep, major: u32, minor: u32, patch: u32) void {
1308 self.target_glibc = Version{
1309 .major = major,
1310 .minor = minor,
1311 .patch = patch,
1312 };
1313 }
1314
1315 pub fn setOutputDir(self: *LibExeObjStep, dir: []const u8) void {1351 pub fn setOutputDir(self: *LibExeObjStep, dir: []const u8) void {
1316 self.output_dir = self.builder.dupePath(dir);1352 self.output_dir = self.builder.dupePath(dir);
1317 }1353 }
...@@ -1692,7 +1728,7 @@ pub const LibExeObjStep = struct {...@@ -1692,7 +1728,7 @@ pub const LibExeObjStep = struct {
1692 .NotFound => return error.VcpkgNotFound,1728 .NotFound => return error.VcpkgNotFound,
1693 .Found => |root| {1729 .Found => |root| {
1694 const allocator = self.builder.allocator;1730 const allocator = self.builder.allocator;
1695 const triplet = try Target.vcpkgTriplet(allocator, self.target, linkage);1731 const triplet = try self.target.vcpkgTriplet(allocator, linkage);
1696 defer self.builder.allocator.free(triplet);1732 defer self.builder.allocator.free(triplet);
16971733
1698 const include_path = try fs.path.join(allocator, &[_][]const u8{ root, "installed", triplet, "include" });1734 const include_path = try fs.path.join(allocator, &[_][]const u8{ root, "installed", triplet, "include" });
...@@ -1862,10 +1898,10 @@ pub const LibExeObjStep = struct {...@@ -1862,10 +1898,10 @@ pub const LibExeObjStep = struct {
1862 }1898 }
18631899
1864 switch (self.build_mode) {1900 switch (self.build_mode) {
1865 builtin.Mode.Debug => {},1901 .Debug => {},
1866 builtin.Mode.ReleaseSafe => zig_args.append("--release-safe") catch unreachable,1902 .ReleaseSafe => zig_args.append("--release-safe") catch unreachable,
1867 builtin.Mode.ReleaseFast => zig_args.append("--release-fast") catch unreachable,1903 .ReleaseFast => zig_args.append("--release-fast") catch unreachable,
1868 builtin.Mode.ReleaseSmall => zig_args.append("--release-small") catch unreachable,1904 .ReleaseSmall => zig_args.append("--release-small") catch unreachable,
1869 }1905 }
18701906
1871 try zig_args.append("--cache-dir");1907 try zig_args.append("--cache-dir");
...@@ -1905,47 +1941,46 @@ pub const LibExeObjStep = struct {...@@ -1905,47 +1941,46 @@ pub const LibExeObjStep = struct {
1905 try zig_args.append(@tagName(self.code_model));1941 try zig_args.append(@tagName(self.code_model));
1906 }1942 }
19071943
1908 switch (self.target) {1944 if (!self.target.isNative()) {
1909 .Native => {},1945 try zig_args.append("-target");
1910 .Cross => |cross| {1946 try zig_args.append(try self.target.zigTriple(builder.allocator));
1911 try zig_args.append("-target");
1912 try zig_args.append(self.target.zigTriple(builder.allocator) catch unreachable);
19131947
1914 const all_features = self.target.getArch().allFeaturesList();1948 // TODO this logic can disappear if cpu model + features becomes part of the target triple
1915 var populated_cpu_features = cross.cpu.model.features;1949 const cross = self.target.toTarget();
1916 populated_cpu_features.populateDependencies(all_features);1950 const all_features = cross.cpu.arch.allFeaturesList();
1951 var populated_cpu_features = cross.cpu.model.features;
1952 populated_cpu_features.populateDependencies(all_features);
19171953
1918 if (populated_cpu_features.eql(cross.cpu.features)) {1954 if (populated_cpu_features.eql(cross.cpu.features)) {
1919 // The CPU name alone is sufficient.1955 // The CPU name alone is sufficient.
1920 // If it is the baseline CPU, no command line args are required.1956 // If it is the baseline CPU, no command line args are required.
1921 if (cross.cpu.model != Target.Cpu.baseline(self.target.getArch()).model) {1957 if (cross.cpu.model != std.Target.Cpu.baseline(cross.cpu.arch).model) {
1922 try zig_args.append("-mcpu");1958 try zig_args.append("-mcpu");
1923 try zig_args.append(cross.cpu.model.name);1959 try zig_args.append(cross.cpu.model.name);
1924 }1960 }
1925 } else {1961 } else {
1926 var mcpu_buffer = try std.Buffer.init(builder.allocator, "-mcpu=");1962 var mcpu_buffer = try std.Buffer.init(builder.allocator, "-mcpu=");
1927 try mcpu_buffer.append(cross.cpu.model.name);1963 try mcpu_buffer.append(cross.cpu.model.name);
19281964
1929 for (all_features) |feature, i_usize| {1965 for (all_features) |feature, i_usize| {
1930 const i = @intCast(Target.Cpu.Feature.Set.Index, i_usize);1966 const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize);
1931 const in_cpu_set = populated_cpu_features.isEnabled(i);1967 const in_cpu_set = populated_cpu_features.isEnabled(i);
1932 const in_actual_set = cross.cpu.features.isEnabled(i);1968 const in_actual_set = cross.cpu.features.isEnabled(i);
1933 if (in_cpu_set and !in_actual_set) {1969 if (in_cpu_set and !in_actual_set) {
1934 try mcpu_buffer.appendByte('-');1970 try mcpu_buffer.appendByte('-');
1935 try mcpu_buffer.append(feature.name);1971 try mcpu_buffer.append(feature.name);
1936 } else if (!in_cpu_set and in_actual_set) {1972 } else if (!in_cpu_set and in_actual_set) {
1937 try mcpu_buffer.appendByte('+');1973 try mcpu_buffer.appendByte('+');
1938 try mcpu_buffer.append(feature.name);1974 try mcpu_buffer.append(feature.name);
1939 }
1940 }1975 }
1941 try zig_args.append(mcpu_buffer.toSliceConst());
1942 }1976 }
1943 },1977 try zig_args.append(mcpu_buffer.toSliceConst());
1944 }1978 }
19451979
1946 if (self.target_glibc) |ver| {1980 if (self.target.dynamic_linker.get()) |dynamic_linker| {
1947 try zig_args.append("-target-glibc");1981 try zig_args.append("--dynamic-linker");
1948 try zig_args.append(builder.fmt("{}.{}.{}", .{ ver.major, ver.minor, ver.patch }));1982 try zig_args.append(dynamic_linker);
1983 }
1949 }1984 }
19501985
1951 if (self.linker_script) |linker_script| {1986 if (self.linker_script) |linker_script| {
...@@ -1953,11 +1988,6 @@ pub const LibExeObjStep = struct {...@@ -1953,11 +1988,6 @@ pub const LibExeObjStep = struct {
1953 zig_args.append(builder.pathFromRoot(linker_script)) catch unreachable;1988 zig_args.append(builder.pathFromRoot(linker_script)) catch unreachable;
1954 }1989 }
19551990
1956 if (self.dynamic_linker) |dynamic_linker| {
1957 try zig_args.append("--dynamic-linker");
1958 try zig_args.append(dynamic_linker);
1959 }
1960
1961 if (self.version_script) |version_script| {1991 if (self.version_script) |version_script| {
1962 try zig_args.append("--version-script");1992 try zig_args.append("--version-script");
1963 try zig_args.append(builder.pathFromRoot(version_script));1993 try zig_args.append(builder.pathFromRoot(version_script));
...@@ -1975,7 +2005,7 @@ pub const LibExeObjStep = struct {...@@ -1975,7 +2005,7 @@ pub const LibExeObjStep = struct {
1975 } else switch (self.target.getExternalExecutor()) {2005 } else switch (self.target.getExternalExecutor()) {
1976 .native, .unavailable => {},2006 .native, .unavailable => {},
1977 .qemu => |bin_name| if (self.enable_qemu) qemu: {2007 .qemu => |bin_name| if (self.enable_qemu) qemu: {
1978 const need_cross_glibc = self.target.isGnu() and self.target.isLinux() and self.is_linking_libc;2008 const need_cross_glibc = self.target.isGnuLibC() and self.is_linking_libc;
1979 const glibc_dir_arg = if (need_cross_glibc)2009 const glibc_dir_arg = if (need_cross_glibc)
1980 self.glibc_multi_install_dir orelse break :qemu2010 self.glibc_multi_install_dir orelse break :qemu
1981 else2011 else
...@@ -2420,10 +2450,7 @@ const VcpkgRootStatus = enum {...@@ -2420,10 +2450,7 @@ const VcpkgRootStatus = enum {
2420 Found,2450 Found,
2421};2451};
24222452
2423pub const VcpkgLinkage = enum {2453pub const VcpkgLinkage = std.builtin.LinkMode;
2424 Static,
2425 Dynamic,
2426};
24272454
2428pub const InstallDir = enum {2455pub const InstallDir = enum {
2429 Prefix,2456 Prefix,
lib/std/build/run.zig+1-1
...@@ -82,7 +82,7 @@ pub const RunStep = struct {...@@ -82,7 +82,7 @@ pub const RunStep = struct {
8282
83 var key: []const u8 = undefined;83 var key: []const u8 = undefined;
84 var prev_path: ?[]const u8 = undefined;84 var prev_path: ?[]const u8 = undefined;
85 if (builtin.os == .windows) {85 if (builtin.os.tag == .windows) {
86 key = "Path";86 key = "Path";
87 prev_path = env_map.get(key);87 prev_path = env_map.get(key);
88 if (prev_path == null) {88 if (prev_path == null) {
lib/std/build/translate_c.zig+6-8
...@@ -7,6 +7,7 @@ const LibExeObjStep = build.LibExeObjStep;...@@ -7,6 +7,7 @@ const LibExeObjStep = build.LibExeObjStep;
7const CheckFileStep = build.CheckFileStep;7const CheckFileStep = build.CheckFileStep;
8const fs = std.fs;8const fs = std.fs;
9const mem = std.mem;9const mem = std.mem;
10const CrossTarget = std.zig.CrossTarget;
1011
11pub const TranslateCStep = struct {12pub const TranslateCStep = struct {
12 step: Step,13 step: Step,
...@@ -14,7 +15,7 @@ pub const TranslateCStep = struct {...@@ -14,7 +15,7 @@ pub const TranslateCStep = struct {
14 source: build.FileSource,15 source: build.FileSource,
15 output_dir: ?[]const u8,16 output_dir: ?[]const u8,
16 out_basename: []const u8,17 out_basename: []const u8,
17 target: std.Target = .Native,18 target: CrossTarget = CrossTarget{},
1819
19 pub fn create(builder: *Builder, source: build.FileSource) *TranslateCStep {20 pub fn create(builder: *Builder, source: build.FileSource) *TranslateCStep {
20 const self = builder.allocator.create(TranslateCStep) catch unreachable;21 const self = builder.allocator.create(TranslateCStep) catch unreachable;
...@@ -39,7 +40,7 @@ pub const TranslateCStep = struct {...@@ -39,7 +40,7 @@ pub const TranslateCStep = struct {
39 ) catch unreachable;40 ) catch unreachable;
40 }41 }
4142
42 pub fn setTarget(self: *TranslateCStep, target: std.Target) void {43 pub fn setTarget(self: *TranslateCStep, target: CrossTarget) void {
43 self.target = target;44 self.target = target;
44 }45 }
4546
...@@ -63,12 +64,9 @@ pub const TranslateCStep = struct {...@@ -63,12 +64,9 @@ pub const TranslateCStep = struct {
63 try argv_list.append("--cache");64 try argv_list.append("--cache");
64 try argv_list.append("on");65 try argv_list.append("on");
6566
66 switch (self.target) {67 if (!self.target.isNative()) {
67 .Native => {},68 try argv_list.append("-target");
68 .Cross => {69 try argv_list.append(try self.target.zigTriple(self.builder.allocator));
69 try argv_list.append("-target");
70 try argv_list.append(try self.target.zigTriple(self.builder.allocator));
71 },
72 }70 }
7371
74 try argv_list.append(self.source.getPath(self.builder));72 try argv_list.append(self.source.getPath(self.builder));
lib/std/builtin.zig+57-2
...@@ -185,6 +185,7 @@ pub const TypeInfo = union(enum) {...@@ -185,6 +185,7 @@ pub const TypeInfo = union(enum) {
185 child: type,185 child: type,
186 is_allowzero: bool,186 is_allowzero: bool,
187187
188 /// This field is an optional type.
188 /// The type of the sentinel is the element type of the pointer, which is189 /// The type of the sentinel is the element type of the pointer, which is
189 /// the value of the `child` field in this struct. However there is no way190 /// the value of the `child` field in this struct. However there is no way
190 /// to refer to that type here, so we use `var`.191 /// to refer to that type here, so we use `var`.
...@@ -206,6 +207,7 @@ pub const TypeInfo = union(enum) {...@@ -206,6 +207,7 @@ pub const TypeInfo = union(enum) {
206 len: comptime_int,207 len: comptime_int,
207 child: type,208 child: type,
208209
210 /// This field is an optional type.
209 /// The type of the sentinel is the element type of the array, which is211 /// The type of the sentinel is the element type of the array, which is
210 /// the value of the `child` field in this struct. However there is no way212 /// the value of the `child` field in this struct. However there is no way
211 /// to refer to that type here, so we use `var`.213 /// to refer to that type here, so we use `var`.
...@@ -398,7 +400,60 @@ pub const LinkMode = enum {...@@ -398,7 +400,60 @@ pub const LinkMode = enum {
398pub const Version = struct {400pub const Version = struct {
399 major: u32,401 major: u32,
400 minor: u32,402 minor: u32,
401 patch: u32,403 patch: u32 = 0,
404
405 pub const Range = struct {
406 min: Version,
407 max: Version,
408
409 pub fn includesVersion(self: LinuxVersionRange, ver: Version) bool {
410 if (self.min.compare(ver) == .gt) return false;
411 if (self.max.compare(ver) == .lt) return false;
412 return true;
413 }
414 };
415
416 pub fn order(lhs: Version, rhs: Version) std.math.Order {
417 if (lhs.major < rhs.major) return .lt;
418 if (lhs.major > rhs.major) return .gt;
419 if (lhs.minor < rhs.minor) return .lt;
420 if (lhs.minor > rhs.minor) return .gt;
421 if (lhs.patch < rhs.patch) return .lt;
422 if (lhs.patch > rhs.patch) return .gt;
423 return .eq;
424 }
425
426 pub fn parse(text: []const u8) !Version {
427 var it = std.mem.separate(text, ".");
428 return Version{
429 .major = try std.fmt.parseInt(u32, it.next() orelse return error.InvalidVersion, 10),
430 .minor = try std.fmt.parseInt(u32, it.next() orelse "0", 10),
431 .patch = try std.fmt.parseInt(u32, it.next() orelse "0", 10),
432 };
433 }
434
435 pub fn format(
436 self: Version,
437 comptime fmt: []const u8,
438 options: std.fmt.FormatOptions,
439 context: var,
440 comptime Error: type,
441 comptime output: fn (@TypeOf(context), []const u8) Error!void,
442 ) Error!void {
443 if (fmt.len == 0) {
444 if (self.patch == 0) {
445 if (self.minor == 0) {
446 return std.fmt.format(context, Error, output, "{}", .{self.major});
447 } else {
448 return std.fmt.format(context, Error, output, "{}.{}", .{ self.major, self.minor });
449 }
450 } else {
451 return std.fmt.format(context, Error, output, "{}.{}.{}", .{ self.major, self.minor, self.patch });
452 }
453 } else {
454 @compileError("Unknown format string: '" ++ fmt ++ "'");
455 }
456 }
402};457};
403458
404/// This data structure is used by the Zig language code generation and459/// This data structure is used by the Zig language code generation and
...@@ -474,7 +529,7 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn...@@ -474,7 +529,7 @@ pub fn default_panic(msg: []const u8, error_return_trace: ?*StackTrace) noreturn
474 root.os.panic(msg, error_return_trace);529 root.os.panic(msg, error_return_trace);
475 unreachable;530 unreachable;
476 }531 }
477 switch (os) {532 switch (os.tag) {
478 .freestanding => {533 .freestanding => {
479 while (true) {534 while (true) {
480 @breakpoint();535 @breakpoint();
lib/std/c.zig+14-13
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");
2const std = @import("std");1const std = @import("std");
2const builtin = std.builtin;
3const page_size = std.mem.page_size;3const page_size = std.mem.page_size;
44
5pub const tokenizer = @import("c/tokenizer.zig");5pub const tokenizer = @import("c/tokenizer.zig");
...@@ -10,7 +10,7 @@ pub const ast = @import("c/ast.zig");...@@ -10,7 +10,7 @@ pub const ast = @import("c/ast.zig");
1010
11pub usingnamespace @import("os/bits.zig");11pub usingnamespace @import("os/bits.zig");
1212
13pub usingnamespace switch (builtin.os) {13pub usingnamespace switch (std.Target.current.os.tag) {
14 .linux => @import("c/linux.zig"),14 .linux => @import("c/linux.zig"),
15 .windows => @import("c/windows.zig"),15 .windows => @import("c/windows.zig"),
16 .macosx, .ios, .tvos, .watchos => @import("c/darwin.zig"),16 .macosx, .ios, .tvos, .watchos => @import("c/darwin.zig"),
...@@ -46,17 +46,16 @@ pub fn versionCheck(glibc_version: builtin.Version) type {...@@ -46,17 +46,16 @@ pub fn versionCheck(glibc_version: builtin.Version) type {
46 return struct {46 return struct {
47 pub const ok = blk: {47 pub const ok = blk: {
48 if (!builtin.link_libc) break :blk false;48 if (!builtin.link_libc) break :blk false;
49 switch (builtin.abi) {49 if (std.Target.current.abi.isMusl()) break :blk true;
50 .musl, .musleabi, .musleabihf => break :blk true,50 if (std.Target.current.isGnuLibC()) {
51 .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => {51 const ver = std.Target.current.os.version_range.linux.glibc;
52 const ver = builtin.glibc_version orelse break :blk false;52 const order = ver.order(glibc_version);
53 if (ver.major < glibc_version.major) break :blk false;53 break :blk switch (order) {
54 if (ver.major > glibc_version.major) break :blk true;54 .gt, .eq => true,
55 if (ver.minor < glibc_version.minor) break :blk false;55 .lt => false,
56 if (ver.minor > glibc_version.minor) break :blk true;56 };
57 break :blk ver.patch >= glibc_version.patch;57 } else {
58 },58 break :blk false;
59 else => break :blk false,
60 }59 }
61 };60 };
62 };61 };
...@@ -109,6 +108,7 @@ pub extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8...@@ -109,6 +108,7 @@ pub extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8
109pub extern "c" fn dup(fd: fd_t) c_int;108pub extern "c" fn dup(fd: fd_t) c_int;
110pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int;109pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int;
111pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;110pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
111pub extern "c" fn readlinkat(dirfd: fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
112pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;112pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
113pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;113pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
114pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;114pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
...@@ -125,6 +125,7 @@ pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*u...@@ -125,6 +125,7 @@ pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*u
125pub extern "c" fn tcgetattr(fd: fd_t, termios_p: *termios) c_int;125pub extern "c" fn tcgetattr(fd: fd_t, termios_p: *termios) c_int;
126pub extern "c" fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) c_int;126pub extern "c" fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) c_int;
127pub extern "c" fn fcntl(fd: fd_t, cmd: c_int, ...) c_int;127pub extern "c" fn fcntl(fd: fd_t, cmd: c_int, ...) c_int;
128pub extern "c" fn uname(buf: *utsname) c_int;
128129
129pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int;130pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int;
130pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int;131pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int;
lib/std/c/linux.zig+1-1
...@@ -94,7 +94,7 @@ pub const pthread_cond_t = extern struct {...@@ -94,7 +94,7 @@ pub const pthread_cond_t = extern struct {
94 size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,94 size: [__SIZEOF_PTHREAD_COND_T]u8 align(@alignOf(usize)) = [_]u8{0} ** __SIZEOF_PTHREAD_COND_T,
95};95};
96const __SIZEOF_PTHREAD_COND_T = 48;96const __SIZEOF_PTHREAD_COND_T = 48;
97const __SIZEOF_PTHREAD_MUTEX_T = if (builtin.os == .fuchsia) 40 else switch (builtin.abi) {97const __SIZEOF_PTHREAD_MUTEX_T = if (builtin.os.tag == .fuchsia) 40 else switch (builtin.abi) {
98 .musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,98 .musl, .musleabi, .musleabihf => if (@sizeOf(usize) == 8) 40 else 24,
99 .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (builtin.arch) {99 .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => switch (builtin.arch) {
100 .aarch64 => 48,100 .aarch64 => 48,
lib/std/child_process.zig+13-13
...@@ -17,9 +17,9 @@ const TailQueue = std.TailQueue;...@@ -17,9 +17,9 @@ const TailQueue = std.TailQueue;
17const maxInt = std.math.maxInt;17const maxInt = std.math.maxInt;
1818
19pub const ChildProcess = struct {19pub const ChildProcess = struct {
20 pid: if (builtin.os == .windows) void else i32,20 pid: if (builtin.os.tag == .windows) void else i32,
21 handle: if (builtin.os == .windows) windows.HANDLE else void,21 handle: if (builtin.os.tag == .windows) windows.HANDLE else void,
22 thread_handle: if (builtin.os == .windows) windows.HANDLE else void,22 thread_handle: if (builtin.os.tag == .windows) windows.HANDLE else void,
2323
24 allocator: *mem.Allocator,24 allocator: *mem.Allocator,
2525
...@@ -39,15 +39,15 @@ pub const ChildProcess = struct {...@@ -39,15 +39,15 @@ pub const ChildProcess = struct {
39 stderr_behavior: StdIo,39 stderr_behavior: StdIo,
4040
41 /// Set to change the user id when spawning the child process.41 /// Set to change the user id when spawning the child process.
42 uid: if (builtin.os == .windows) void else ?u32,42 uid: if (builtin.os.tag == .windows) void else ?u32,
4343
44 /// Set to change the group id when spawning the child process.44 /// Set to change the group id when spawning the child process.
45 gid: if (builtin.os == .windows) void else ?u32,45 gid: if (builtin.os.tag == .windows) void else ?u32,
4646
47 /// Set to change the current working directory when spawning the child process.47 /// Set to change the current working directory when spawning the child process.
48 cwd: ?[]const u8,48 cwd: ?[]const u8,
4949
50 err_pipe: if (builtin.os == .windows) void else [2]os.fd_t,50 err_pipe: if (builtin.os.tag == .windows) void else [2]os.fd_t,
5151
52 expand_arg0: Arg0Expand,52 expand_arg0: Arg0Expand,
5353
...@@ -96,8 +96,8 @@ pub const ChildProcess = struct {...@@ -96,8 +96,8 @@ pub const ChildProcess = struct {
96 .term = null,96 .term = null,
97 .env_map = null,97 .env_map = null,
98 .cwd = null,98 .cwd = null,
99 .uid = if (builtin.os == .windows) {} else null,99 .uid = if (builtin.os.tag == .windows) {} else null,
100 .gid = if (builtin.os == .windows) {} else null,100 .gid = if (builtin.os.tag == .windows) {} else null,
101 .stdin = null,101 .stdin = null,
102 .stdout = null,102 .stdout = null,
103 .stderr = null,103 .stderr = null,
...@@ -118,7 +118,7 @@ pub const ChildProcess = struct {...@@ -118,7 +118,7 @@ pub const ChildProcess = struct {
118118
119 /// On success must call `kill` or `wait`.119 /// On success must call `kill` or `wait`.
120 pub fn spawn(self: *ChildProcess) SpawnError!void {120 pub fn spawn(self: *ChildProcess) SpawnError!void {
121 if (builtin.os == .windows) {121 if (builtin.os.tag == .windows) {
122 return self.spawnWindows();122 return self.spawnWindows();
123 } else {123 } else {
124 return self.spawnPosix();124 return self.spawnPosix();
...@@ -132,7 +132,7 @@ pub const ChildProcess = struct {...@@ -132,7 +132,7 @@ pub const ChildProcess = struct {
132132
133 /// Forcibly terminates child process and then cleans up all resources.133 /// Forcibly terminates child process and then cleans up all resources.
134 pub fn kill(self: *ChildProcess) !Term {134 pub fn kill(self: *ChildProcess) !Term {
135 if (builtin.os == .windows) {135 if (builtin.os.tag == .windows) {
136 return self.killWindows(1);136 return self.killWindows(1);
137 } else {137 } else {
138 return self.killPosix();138 return self.killPosix();
...@@ -162,7 +162,7 @@ pub const ChildProcess = struct {...@@ -162,7 +162,7 @@ pub const ChildProcess = struct {
162162
163 /// Blocks until child process terminates and then cleans up all resources.163 /// Blocks until child process terminates and then cleans up all resources.
164 pub fn wait(self: *ChildProcess) !Term {164 pub fn wait(self: *ChildProcess) !Term {
165 if (builtin.os == .windows) {165 if (builtin.os.tag == .windows) {
166 return self.waitWindows();166 return self.waitWindows();
167 } else {167 } else {
168 return self.waitPosix();168 return self.waitPosix();
...@@ -307,7 +307,7 @@ pub const ChildProcess = struct {...@@ -307,7 +307,7 @@ pub const ChildProcess = struct {
307 fn cleanupAfterWait(self: *ChildProcess, status: u32) !Term {307 fn cleanupAfterWait(self: *ChildProcess, status: u32) !Term {
308 defer destroyPipe(self.err_pipe);308 defer destroyPipe(self.err_pipe);
309309
310 if (builtin.os == .linux) {310 if (builtin.os.tag == .linux) {
311 var fd = [1]std.os.pollfd{std.os.pollfd{311 var fd = [1]std.os.pollfd{std.os.pollfd{
312 .fd = self.err_pipe[0],312 .fd = self.err_pipe[0],
313 .events = std.os.POLLIN,313 .events = std.os.POLLIN,
...@@ -402,7 +402,7 @@ pub const ChildProcess = struct {...@@ -402,7 +402,7 @@ pub const ChildProcess = struct {
402 // This pipe is used to communicate errors between the time of fork402 // This pipe is used to communicate errors between the time of fork
403 // and execve from the child process to the parent process.403 // and execve from the child process to the parent process.
404 const err_pipe = blk: {404 const err_pipe = blk: {
405 if (builtin.os == .linux) {405 if (builtin.os.tag == .linux) {
406 const fd = try os.eventfd(0, 0);406 const fd = try os.eventfd(0, 0);
407 // There's no distinction between the readable and the writeable407 // There's no distinction between the readable and the writeable
408 // end with eventfd408 // end with eventfd
lib/std/crypto/benchmark.zig+1-1
...@@ -120,7 +120,7 @@ fn usage() void {...@@ -120,7 +120,7 @@ fn usage() void {
120}120}
121121
122fn mode(comptime x: comptime_int) comptime_int {122fn mode(comptime x: comptime_int) comptime_int {
123 return if (builtin.mode == builtin.Mode.Debug) x / 64 else x;123 return if (builtin.mode == .Debug) x / 64 else x;
124}124}
125125
126// TODO(#1358): Replace with builtin formatted padding when available.126// TODO(#1358): Replace with builtin formatted padding when available.
lib/std/cstr.zig+3-3
...@@ -4,8 +4,8 @@ const debug = std.debug;...@@ -4,8 +4,8 @@ const debug = std.debug;
4const mem = std.mem;4const mem = std.mem;
5const testing = std.testing;5const testing = std.testing;
66
7pub const line_sep = switch (builtin.os) {7pub const line_sep = switch (builtin.os.tag) {
8 builtin.Os.windows => "\r\n",8 .windows => "\r\n",
9 else => "\n",9 else => "\n",
10};10};
1111
...@@ -28,7 +28,7 @@ test "cstr fns" {...@@ -28,7 +28,7 @@ test "cstr fns" {
2828
29fn testCStrFnsImpl() void {29fn testCStrFnsImpl() void {
30 testing.expect(cmp("aoeu", "aoez") == -1);30 testing.expect(cmp("aoeu", "aoez") == -1);
31 testing.expect(mem.len(u8, "123456789") == 9);31 testing.expect(mem.len("123456789") == 9);
32}32}
3333
34/// Returns a mutable, null-terminated slice with the same length as `slice`.34/// Returns a mutable, null-terminated slice with the same length as `slice`.
lib/std/debug.zig+12-12
...@@ -1,4 +1,5 @@...@@ -1,4 +1,5 @@
1const std = @import("std.zig");1const std = @import("std.zig");
2const builtin = std.builtin;
2const math = std.math;3const math = std.math;
3const mem = std.mem;4const mem = std.mem;
4const io = std.io;5const io = std.io;
...@@ -11,7 +12,6 @@ const macho = std.macho;...@@ -11,7 +12,6 @@ const macho = std.macho;
11const coff = std.coff;12const coff = std.coff;
12const pdb = std.pdb;13const pdb = std.pdb;
13const ArrayList = std.ArrayList;14const ArrayList = std.ArrayList;
14const builtin = @import("builtin");
15const root = @import("root");15const root = @import("root");
16const maxInt = std.math.maxInt;16const maxInt = std.math.maxInt;
17const File = std.fs.File;17const File = std.fs.File;
...@@ -101,7 +101,7 @@ pub fn detectTTYConfig() TTY.Config {...@@ -101,7 +101,7 @@ pub fn detectTTYConfig() TTY.Config {
101 } else |_| {101 } else |_| {
102 if (stderr_file.supportsAnsiEscapeCodes()) {102 if (stderr_file.supportsAnsiEscapeCodes()) {
103 return .escape_codes;103 return .escape_codes;
104 } else if (builtin.os == .windows and stderr_file.isTty()) {104 } else if (builtin.os.tag == .windows and stderr_file.isTty()) {
105 return .windows_api;105 return .windows_api;
106 } else {106 } else {
107 return .no_color;107 return .no_color;
...@@ -155,7 +155,7 @@ pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void {...@@ -155,7 +155,7 @@ pub fn dumpStackTraceFromBase(bp: usize, ip: usize) void {
155/// chopping off the irrelevant frames and shifting so that the returned addresses pointer155/// chopping off the irrelevant frames and shifting so that the returned addresses pointer
156/// equals the passed in addresses pointer.156/// equals the passed in addresses pointer.
157pub fn captureStackTrace(first_address: ?usize, stack_trace: *builtin.StackTrace) void {157pub fn captureStackTrace(first_address: ?usize, stack_trace: *builtin.StackTrace) void {
158 if (builtin.os == .windows) {158 if (builtin.os.tag == .windows) {
159 const addrs = stack_trace.instruction_addresses;159 const addrs = stack_trace.instruction_addresses;
160 const u32_addrs_len = @intCast(u32, addrs.len);160 const u32_addrs_len = @intCast(u32, addrs.len);
161 const first_addr = first_address orelse {161 const first_addr = first_address orelse {
...@@ -231,7 +231,7 @@ pub fn assert(ok: bool) void {...@@ -231,7 +231,7 @@ pub fn assert(ok: bool) void {
231pub fn panic(comptime format: []const u8, args: var) noreturn {231pub fn panic(comptime format: []const u8, args: var) noreturn {
232 @setCold(true);232 @setCold(true);
233 // TODO: remove conditional once wasi / LLVM defines __builtin_return_address233 // TODO: remove conditional once wasi / LLVM defines __builtin_return_address
234 const first_trace_addr = if (builtin.os == .wasi) null else @returnAddress();234 const first_trace_addr = if (builtin.os.tag == .wasi) null else @returnAddress();
235 panicExtra(null, first_trace_addr, format, args);235 panicExtra(null, first_trace_addr, format, args);
236}236}
237237
...@@ -361,7 +361,7 @@ pub fn writeCurrentStackTrace(...@@ -361,7 +361,7 @@ pub fn writeCurrentStackTrace(
361 tty_config: TTY.Config,361 tty_config: TTY.Config,
362 start_addr: ?usize,362 start_addr: ?usize,
363) !void {363) !void {
364 if (builtin.os == .windows) {364 if (builtin.os.tag == .windows) {
365 return writeCurrentStackTraceWindows(out_stream, debug_info, tty_config, start_addr);365 return writeCurrentStackTraceWindows(out_stream, debug_info, tty_config, start_addr);
366 }366 }
367 var it = StackIterator.init(start_addr, null);367 var it = StackIterator.init(start_addr, null);
...@@ -418,7 +418,7 @@ pub const TTY = struct {...@@ -418,7 +418,7 @@ pub const TTY = struct {
418 .Dim => noasync out_stream.write(DIM) catch return,418 .Dim => noasync out_stream.write(DIM) catch return,
419 .Reset => noasync out_stream.write(RESET) catch return,419 .Reset => noasync out_stream.write(RESET) catch return,
420 },420 },
421 .windows_api => if (builtin.os == .windows) {421 .windows_api => if (builtin.os.tag == .windows) {
422 const S = struct {422 const S = struct {
423 var attrs: windows.WORD = undefined;423 var attrs: windows.WORD = undefined;
424 var init_attrs = false;424 var init_attrs = false;
...@@ -617,7 +617,7 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {...@@ -617,7 +617,7 @@ pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {
617 if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {617 if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {
618 return noasync root.os.debug.openSelfDebugInfo(allocator);618 return noasync root.os.debug.openSelfDebugInfo(allocator);
619 }619 }
620 switch (builtin.os) {620 switch (builtin.os.tag) {
621 .linux,621 .linux,
622 .freebsd,622 .freebsd,
623 .macosx,623 .macosx,
...@@ -1019,7 +1019,7 @@ pub const DebugInfo = struct {...@@ -1019,7 +1019,7 @@ pub const DebugInfo = struct {
1019 pub fn getModuleForAddress(self: *DebugInfo, address: usize) !*ModuleDebugInfo {1019 pub fn getModuleForAddress(self: *DebugInfo, address: usize) !*ModuleDebugInfo {
1020 if (comptime std.Target.current.isDarwin())1020 if (comptime std.Target.current.isDarwin())
1021 return self.lookupModuleDyld(address)1021 return self.lookupModuleDyld(address)
1022 else if (builtin.os == .windows)1022 else if (builtin.os.tag == .windows)
1023 return self.lookupModuleWin32(address)1023 return self.lookupModuleWin32(address)
1024 else1024 else
1025 return self.lookupModuleDl(address);1025 return self.lookupModuleDl(address);
...@@ -1242,7 +1242,7 @@ const SymbolInfo = struct {...@@ -1242,7 +1242,7 @@ const SymbolInfo = struct {
1242 }1242 }
1243};1243};
12441244
1245pub const ModuleDebugInfo = switch (builtin.os) {1245pub const ModuleDebugInfo = switch (builtin.os.tag) {
1246 .macosx, .ios, .watchos, .tvos => struct {1246 .macosx, .ios, .watchos, .tvos => struct {
1247 base_address: usize,1247 base_address: usize,
1248 mapped_memory: []const u8,1248 mapped_memory: []const u8,
...@@ -1602,7 +1602,7 @@ fn getDebugInfoAllocator() *mem.Allocator {...@@ -1602,7 +1602,7 @@ fn getDebugInfoAllocator() *mem.Allocator {
1602}1602}
16031603
1604/// Whether or not the current target can print useful debug information when a segfault occurs.1604/// Whether or not the current target can print useful debug information when a segfault occurs.
1605pub const have_segfault_handling_support = builtin.os == .linux or builtin.os == .windows;1605pub const have_segfault_handling_support = builtin.os.tag == .linux or builtin.os.tag == .windows;
1606pub const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler"))1606pub const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler"))
1607 root.enable_segfault_handler1607 root.enable_segfault_handler
1608else1608else
...@@ -1621,7 +1621,7 @@ pub fn attachSegfaultHandler() void {...@@ -1621,7 +1621,7 @@ pub fn attachSegfaultHandler() void {
1621 if (!have_segfault_handling_support) {1621 if (!have_segfault_handling_support) {
1622 @compileError("segfault handler not supported for this target");1622 @compileError("segfault handler not supported for this target");
1623 }1623 }
1624 if (builtin.os == .windows) {1624 if (builtin.os.tag == .windows) {
1625 windows_segfault_handle = windows.kernel32.AddVectoredExceptionHandler(0, handleSegfaultWindows);1625 windows_segfault_handle = windows.kernel32.AddVectoredExceptionHandler(0, handleSegfaultWindows);
1626 return;1626 return;
1627 }1627 }
...@@ -1637,7 +1637,7 @@ pub fn attachSegfaultHandler() void {...@@ -1637,7 +1637,7 @@ pub fn attachSegfaultHandler() void {
1637}1637}
16381638
1639fn resetSegfaultHandler() void {1639fn resetSegfaultHandler() void {
1640 if (builtin.os == .windows) {1640 if (builtin.os.tag == .windows) {
1641 if (windows_segfault_handle) |handle| {1641 if (windows_segfault_handle) |handle| {
1642 assert(windows.kernel32.RemoveVectoredExceptionHandler(handle) != 0);1642 assert(windows.kernel32.RemoveVectoredExceptionHandler(handle) != 0);
1643 windows_segfault_handle = null;1643 windows_segfault_handle = null;
lib/std/dynamic_library.zig+4-4
...@@ -11,7 +11,7 @@ const system = std.os.system;...@@ -11,7 +11,7 @@ const system = std.os.system;
11const maxInt = std.math.maxInt;11const maxInt = std.math.maxInt;
12const max = std.math.max;12const max = std.math.max;
1313
14pub const DynLib = switch (builtin.os) {14pub const DynLib = switch (builtin.os.tag) {
15 .linux => if (builtin.link_libc) DlDynlib else ElfDynLib,15 .linux => if (builtin.link_libc) DlDynlib else ElfDynLib,
16 .windows => WindowsDynLib,16 .windows => WindowsDynLib,
17 .macosx, .tvos, .watchos, .ios, .freebsd => DlDynlib,17 .macosx, .tvos, .watchos, .ios, .freebsd => DlDynlib,
...@@ -82,12 +82,12 @@ pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator {...@@ -82,12 +82,12 @@ pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator {
82 for (dyn_table) |*dyn| {82 for (dyn_table) |*dyn| {
83 switch (dyn.d_tag) {83 switch (dyn.d_tag) {
84 elf.DT_DEBUG => {84 elf.DT_DEBUG => {
85 const r_debug = @intToPtr(*RDebug, dyn.d_un.d_ptr);85 const r_debug = @intToPtr(*RDebug, dyn.d_val);
86 if (r_debug.r_version != 1) return error.InvalidExe;86 if (r_debug.r_version != 1) return error.InvalidExe;
87 break :init r_debug.r_map;87 break :init r_debug.r_map;
88 },88 },
89 elf.DT_PLTGOT => {89 elf.DT_PLTGOT => {
90 const got_table = @intToPtr([*]usize, dyn.d_un.d_ptr);90 const got_table = @intToPtr([*]usize, dyn.d_val);
91 // The address to the link_map structure is stored in the91 // The address to the link_map structure is stored in the
92 // second slot92 // second slot
93 break :init @intToPtr(?*LinkMap, got_table[1]);93 break :init @intToPtr(?*LinkMap, got_table[1]);
...@@ -390,7 +390,7 @@ pub const DlDynlib = struct {...@@ -390,7 +390,7 @@ pub const DlDynlib = struct {
390};390};
391391
392test "dynamic_library" {392test "dynamic_library" {
393 const libname = switch (builtin.os) {393 const libname = switch (builtin.os.tag) {
394 .linux, .freebsd => "invalid_so.so",394 .linux, .freebsd => "invalid_so.so",
395 .windows => "invalid_dll.dll",395 .windows => "invalid_dll.dll",
396 .macosx, .tvos, .watchos, .ios => "invalid_dylib.dylib",396 .macosx, .tvos, .watchos, .ios => "invalid_dylib.dylib",
lib/std/elf.zig+19-20
...@@ -349,16 +349,6 @@ pub const Elf = struct {...@@ -349,16 +349,6 @@ pub const Elf = struct {
349 program_headers: []ProgramHeader,349 program_headers: []ProgramHeader,
350 allocator: *mem.Allocator,350 allocator: *mem.Allocator,
351351
352 /// Call close when done.
353 pub fn openPath(allocator: *mem.Allocator, path: []const u8) !Elf {
354 @compileError("TODO implement");
355 }
356
357 /// Call close when done.
358 pub fn openFile(allocator: *mem.Allocator, file: File) !Elf {
359 @compileError("TODO implement");
360 }
361
362 pub fn openStream(352 pub fn openStream(
363 allocator: *mem.Allocator,353 allocator: *mem.Allocator,
364 seekable_stream: *io.SeekableStream(anyerror, anyerror),354 seekable_stream: *io.SeekableStream(anyerror, anyerror),
...@@ -380,8 +370,8 @@ pub const Elf = struct {...@@ -380,8 +370,8 @@ pub const Elf = struct {
380 };370 };
381371
382 elf.endian = switch (try in.readByte()) {372 elf.endian = switch (try in.readByte()) {
383 1 => builtin.Endian.Little,373 1 => .Little,
384 2 => builtin.Endian.Big,374 2 => .Big,
385 else => return error.InvalidFormat,375 else => return error.InvalidFormat,
386 };376 };
387377
...@@ -554,6 +544,21 @@ pub const Elf = struct {...@@ -554,6 +544,21 @@ pub const Elf = struct {
554};544};
555545
556pub const EI_NIDENT = 16;546pub const EI_NIDENT = 16;
547
548pub const EI_CLASS = 4;
549pub const ELFCLASSNONE = 0;
550pub const ELFCLASS32 = 1;
551pub const ELFCLASS64 = 2;
552pub const ELFCLASSNUM = 3;
553
554pub const EI_DATA = 5;
555pub const ELFDATANONE = 0;
556pub const ELFDATA2LSB = 1;
557pub const ELFDATA2MSB = 2;
558pub const ELFDATANUM = 3;
559
560pub const EI_VERSION = 6;
561
557pub const Elf32_Half = u16;562pub const Elf32_Half = u16;
558pub const Elf64_Half = u16;563pub const Elf64_Half = u16;
559pub const Elf32_Word = u32;564pub const Elf32_Word = u32;
...@@ -703,17 +708,11 @@ pub const Elf64_Rela = extern struct {...@@ -703,17 +708,11 @@ pub const Elf64_Rela = extern struct {
703};708};
704pub const Elf32_Dyn = extern struct {709pub const Elf32_Dyn = extern struct {
705 d_tag: Elf32_Sword,710 d_tag: Elf32_Sword,
706 d_un: extern union {711 d_val: Elf32_Addr,
707 d_val: Elf32_Word,
708 d_ptr: Elf32_Addr,
709 },
710};712};
711pub const Elf64_Dyn = extern struct {713pub const Elf64_Dyn = extern struct {
712 d_tag: Elf64_Sxword,714 d_tag: Elf64_Sxword,
713 d_un: extern union {715 d_val: Elf64_Addr,
714 d_val: Elf64_Xword,
715 d_ptr: Elf64_Addr,
716 },
717};716};
718pub const Elf32_Verdef = extern struct {717pub const Elf32_Verdef = extern struct {
719 vd_version: Elf32_Half,718 vd_version: Elf32_Half,
lib/std/event/channel.zig+1-1
...@@ -273,7 +273,7 @@ test "std.event.Channel" {...@@ -273,7 +273,7 @@ test "std.event.Channel" {
273 if (builtin.single_threaded) return error.SkipZigTest;273 if (builtin.single_threaded) return error.SkipZigTest;
274274
275 // https://github.com/ziglang/zig/issues/3251275 // https://github.com/ziglang/zig/issues/3251
276 if (builtin.os == .freebsd) return error.SkipZigTest;276 if (builtin.os.tag == .freebsd) return error.SkipZigTest;
277277
278 var channel: Channel(i32) = undefined;278 var channel: Channel(i32) = undefined;
279 channel.init(&[0]i32{});279 channel.init(&[0]i32{});
lib/std/event/future.zig+1-1
...@@ -86,7 +86,7 @@ test "std.event.Future" {...@@ -86,7 +86,7 @@ test "std.event.Future" {
86 // https://github.com/ziglang/zig/issues/190886 // https://github.com/ziglang/zig/issues/1908
87 if (builtin.single_threaded) return error.SkipZigTest;87 if (builtin.single_threaded) return error.SkipZigTest;
88 // https://github.com/ziglang/zig/issues/325188 // https://github.com/ziglang/zig/issues/3251
89 if (builtin.os == .freebsd) return error.SkipZigTest;89 if (builtin.os.tag == .freebsd) return error.SkipZigTest;
90 // TODO provide a way to run tests in evented I/O mode90 // TODO provide a way to run tests in evented I/O mode
91 if (!std.io.is_async) return error.SkipZigTest;91 if (!std.io.is_async) return error.SkipZigTest;
9292
lib/std/event/lock.zig+1-1
...@@ -123,7 +123,7 @@ test "std.event.Lock" {...@@ -123,7 +123,7 @@ test "std.event.Lock" {
123 if (builtin.single_threaded) return error.SkipZigTest;123 if (builtin.single_threaded) return error.SkipZigTest;
124124
125 // TODO https://github.com/ziglang/zig/issues/3251125 // TODO https://github.com/ziglang/zig/issues/3251
126 if (builtin.os == .freebsd) return error.SkipZigTest;126 if (builtin.os.tag == .freebsd) return error.SkipZigTest;
127127
128 var lock = Lock.init();128 var lock = Lock.init();
129 defer lock.deinit();129 defer lock.deinit();
lib/std/event/loop.zig+13-13
...@@ -34,7 +34,7 @@ pub const Loop = struct {...@@ -34,7 +34,7 @@ pub const Loop = struct {
34 handle: anyframe,34 handle: anyframe,
35 overlapped: Overlapped,35 overlapped: Overlapped,
3636
37 pub const overlapped_init = switch (builtin.os) {37 pub const overlapped_init = switch (builtin.os.tag) {
38 .windows => windows.OVERLAPPED{38 .windows => windows.OVERLAPPED{
39 .Internal = 0,39 .Internal = 0,
40 .InternalHigh = 0,40 .InternalHigh = 0,
...@@ -52,7 +52,7 @@ pub const Loop = struct {...@@ -52,7 +52,7 @@ pub const Loop = struct {
52 EventFd,52 EventFd,
53 };53 };
5454
55 pub const EventFd = switch (builtin.os) {55 pub const EventFd = switch (builtin.os.tag) {
56 .macosx, .freebsd, .netbsd, .dragonfly => KEventFd,56 .macosx, .freebsd, .netbsd, .dragonfly => KEventFd,
57 .linux => struct {57 .linux => struct {
58 base: ResumeNode,58 base: ResumeNode,
...@@ -71,7 +71,7 @@ pub const Loop = struct {...@@ -71,7 +71,7 @@ pub const Loop = struct {
71 kevent: os.Kevent,71 kevent: os.Kevent,
72 };72 };
7373
74 pub const Basic = switch (builtin.os) {74 pub const Basic = switch (builtin.os.tag) {
75 .macosx, .freebsd, .netbsd, .dragonfly => KEventBasic,75 .macosx, .freebsd, .netbsd, .dragonfly => KEventBasic,
76 .linux => struct {76 .linux => struct {
77 base: ResumeNode,77 base: ResumeNode,
...@@ -173,7 +173,7 @@ pub const Loop = struct {...@@ -173,7 +173,7 @@ pub const Loop = struct {
173 const wakeup_bytes = [_]u8{0x1} ** 8;173 const wakeup_bytes = [_]u8{0x1} ** 8;
174174
175 fn initOsData(self: *Loop, extra_thread_count: usize) InitOsDataError!void {175 fn initOsData(self: *Loop, extra_thread_count: usize) InitOsDataError!void {
176 switch (builtin.os) {176 switch (builtin.os.tag) {
177 .linux => {177 .linux => {
178 self.os_data.fs_queue = std.atomic.Queue(Request).init();178 self.os_data.fs_queue = std.atomic.Queue(Request).init();
179 self.os_data.fs_queue_item = 0;179 self.os_data.fs_queue_item = 0;
...@@ -404,7 +404,7 @@ pub const Loop = struct {...@@ -404,7 +404,7 @@ pub const Loop = struct {
404 }404 }
405405
406 fn deinitOsData(self: *Loop) void {406 fn deinitOsData(self: *Loop) void {
407 switch (builtin.os) {407 switch (builtin.os.tag) {
408 .linux => {408 .linux => {
409 noasync os.close(self.os_data.final_eventfd);409 noasync os.close(self.os_data.final_eventfd);
410 while (self.available_eventfd_resume_nodes.pop()) |node| noasync os.close(node.data.eventfd);410 while (self.available_eventfd_resume_nodes.pop()) |node| noasync os.close(node.data.eventfd);
...@@ -568,7 +568,7 @@ pub const Loop = struct {...@@ -568,7 +568,7 @@ pub const Loop = struct {
568 };568 };
569 const eventfd_node = &resume_stack_node.data;569 const eventfd_node = &resume_stack_node.data;
570 eventfd_node.base.handle = next_tick_node.data;570 eventfd_node.base.handle = next_tick_node.data;
571 switch (builtin.os) {571 switch (builtin.os.tag) {
572 .macosx, .freebsd, .netbsd, .dragonfly => {572 .macosx, .freebsd, .netbsd, .dragonfly => {
573 const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.kevent);573 const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.kevent);
574 const empty_kevs = &[0]os.Kevent{};574 const empty_kevs = &[0]os.Kevent{};
...@@ -628,7 +628,7 @@ pub const Loop = struct {...@@ -628,7 +628,7 @@ pub const Loop = struct {
628628
629 self.workerRun();629 self.workerRun();
630630
631 switch (builtin.os) {631 switch (builtin.os.tag) {
632 .linux,632 .linux,
633 .macosx,633 .macosx,
634 .freebsd,634 .freebsd,
...@@ -678,7 +678,7 @@ pub const Loop = struct {...@@ -678,7 +678,7 @@ pub const Loop = struct {
678 const prev = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst);678 const prev = @atomicRmw(usize, &self.pending_event_count, AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst);
679 if (prev == 1) {679 if (prev == 1) {
680 // cause all the threads to stop680 // cause all the threads to stop
681 switch (builtin.os) {681 switch (builtin.os.tag) {
682 .linux => {682 .linux => {
683 self.posixFsRequest(&self.os_data.fs_end_request);683 self.posixFsRequest(&self.os_data.fs_end_request);
684 // writing 8 bytes to an eventfd cannot fail684 // writing 8 bytes to an eventfd cannot fail
...@@ -902,7 +902,7 @@ pub const Loop = struct {...@@ -902,7 +902,7 @@ pub const Loop = struct {
902 self.finishOneEvent();902 self.finishOneEvent();
903 }903 }
904904
905 switch (builtin.os) {905 switch (builtin.os.tag) {
906 .linux => {906 .linux => {
907 // only process 1 event so we don't steal from other threads907 // only process 1 event so we don't steal from other threads
908 var events: [1]os.linux.epoll_event = undefined;908 var events: [1]os.linux.epoll_event = undefined;
...@@ -989,7 +989,7 @@ pub const Loop = struct {...@@ -989,7 +989,7 @@ pub const Loop = struct {
989 fn posixFsRequest(self: *Loop, request_node: *Request.Node) void {989 fn posixFsRequest(self: *Loop, request_node: *Request.Node) void {
990 self.beginOneEvent(); // finished in posixFsRun after processing the msg990 self.beginOneEvent(); // finished in posixFsRun after processing the msg
991 self.os_data.fs_queue.put(request_node);991 self.os_data.fs_queue.put(request_node);
992 switch (builtin.os) {992 switch (builtin.os.tag) {
993 .macosx, .freebsd, .netbsd, .dragonfly => {993 .macosx, .freebsd, .netbsd, .dragonfly => {
994 const fs_kevs = @as(*const [1]os.Kevent, &self.os_data.fs_kevent_wake);994 const fs_kevs = @as(*const [1]os.Kevent, &self.os_data.fs_kevent_wake);
995 const empty_kevs = &[0]os.Kevent{};995 const empty_kevs = &[0]os.Kevent{};
...@@ -1018,7 +1018,7 @@ pub const Loop = struct {...@@ -1018,7 +1018,7 @@ pub const Loop = struct {
1018 // https://github.com/ziglang/zig/issues/31571018 // https://github.com/ziglang/zig/issues/3157
1019 fn posixFsRun(self: *Loop) void {1019 fn posixFsRun(self: *Loop) void {
1020 while (true) {1020 while (true) {
1021 if (builtin.os == .linux) {1021 if (builtin.os.tag == .linux) {
1022 @atomicStore(i32, &self.os_data.fs_queue_item, 0, .SeqCst);1022 @atomicStore(i32, &self.os_data.fs_queue_item, 0, .SeqCst);
1023 }1023 }
1024 while (self.os_data.fs_queue.get()) |node| {1024 while (self.os_data.fs_queue.get()) |node| {
...@@ -1053,7 +1053,7 @@ pub const Loop = struct {...@@ -1053,7 +1053,7 @@ pub const Loop = struct {
1053 }1053 }
1054 self.finishOneEvent();1054 self.finishOneEvent();
1055 }1055 }
1056 switch (builtin.os) {1056 switch (builtin.os.tag) {
1057 .linux => {1057 .linux => {
1058 const rc = os.linux.futex_wait(&self.os_data.fs_queue_item, os.linux.FUTEX_WAIT, 0, null);1058 const rc = os.linux.futex_wait(&self.os_data.fs_queue_item, os.linux.FUTEX_WAIT, 0, null);
1059 switch (os.linux.getErrno(rc)) {1059 switch (os.linux.getErrno(rc)) {
...@@ -1071,7 +1071,7 @@ pub const Loop = struct {...@@ -1071,7 +1071,7 @@ pub const Loop = struct {
1071 }1071 }
1072 }1072 }
10731073
1074 const OsData = switch (builtin.os) {1074 const OsData = switch (builtin.os.tag) {
1075 .linux => LinuxOsData,1075 .linux => LinuxOsData,
1076 .macosx, .freebsd, .netbsd, .dragonfly => KEventData,1076 .macosx, .freebsd, .netbsd, .dragonfly => KEventData,
1077 .windows => struct {1077 .windows => struct {
lib/std/fmt.zig+4-2
...@@ -441,10 +441,12 @@ pub fn formatType(...@@ -441,10 +441,12 @@ pub fn formatType(
441 else => return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }),441 else => return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }),
442 },442 },
443 .Many, .C => {443 .Many, .C => {
444 if (ptr_info.sentinel) |sentinel| {
445 return formatType(mem.span(value), fmt, options, context, Errors, output, max_depth);
446 }
444 if (ptr_info.child == u8) {447 if (ptr_info.child == u8) {
445 if (fmt.len > 0 and fmt[0] == 's') {448 if (fmt.len > 0 and fmt[0] == 's') {
446 const len = mem.len(u8, value);449 return formatText(mem.span(value), fmt, options, context, Errors, output);
447 return formatText(value[0..len], fmt, options, context, Errors, output);
448 }450 }
449 }451 }
450 return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });452 return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
lib/std/fmt/parse_float.zig+1-1
...@@ -382,7 +382,7 @@ pub fn parseFloat(comptime T: type, s: []const u8) !T {...@@ -382,7 +382,7 @@ pub fn parseFloat(comptime T: type, s: []const u8) !T {
382}382}
383383
384test "fmt.parseFloat" {384test "fmt.parseFloat" {
385 if (std.Target.current.isWindows()) {385 if (std.Target.current.os.tag == .windows) {
386 // TODO https://github.com/ziglang/zig/issues/508386 // TODO https://github.com/ziglang/zig/issues/508
387 return error.SkipZigTest;387 return error.SkipZigTest;
388 }388 }
lib/std/fs.zig+23-23
...@@ -29,7 +29,7 @@ pub const Watch = @import("fs/watch.zig").Watch;...@@ -29,7 +29,7 @@ pub const Watch = @import("fs/watch.zig").Watch;
29/// All file system operations which return a path are guaranteed to29/// All file system operations which return a path are guaranteed to
30/// fit into a UTF-8 encoded array of this length.30/// fit into a UTF-8 encoded array of this length.
31/// The byte count includes room for a null sentinel byte.31/// The byte count includes room for a null sentinel byte.
32pub const MAX_PATH_BYTES = switch (builtin.os) {32pub const MAX_PATH_BYTES = switch (builtin.os.tag) {
33 .linux, .macosx, .ios, .freebsd, .netbsd, .dragonfly => os.PATH_MAX,33 .linux, .macosx, .ios, .freebsd, .netbsd, .dragonfly => os.PATH_MAX,
34 // Each UTF-16LE character may be expanded to 3 UTF-8 bytes.34 // Each UTF-16LE character may be expanded to 3 UTF-8 bytes.
35 // If it would require 4 UTF-8 bytes, then there would be a surrogate35 // If it would require 4 UTF-8 bytes, then there would be a surrogate
...@@ -47,7 +47,7 @@ pub const base64_encoder = base64.Base64Encoder.init(...@@ -47,7 +47,7 @@ pub const base64_encoder = base64.Base64Encoder.init(
4747
48/// Whether or not async file system syscalls need a dedicated thread because the operating48/// Whether or not async file system syscalls need a dedicated thread because the operating
49/// system does not support non-blocking I/O on the file system.49/// system does not support non-blocking I/O on the file system.
50pub const need_async_thread = std.io.is_async and switch (builtin.os) {50pub const need_async_thread = std.io.is_async and switch (builtin.os.tag) {
51 .windows, .other => false,51 .windows, .other => false,
52 else => true,52 else => true,
53};53};
...@@ -270,7 +270,7 @@ pub const AtomicFile = struct {...@@ -270,7 +270,7 @@ pub const AtomicFile = struct {
270 assert(!self.finished);270 assert(!self.finished);
271 self.file.close();271 self.file.close();
272 self.finished = true;272 self.finished = true;
273 if (builtin.os == .windows) {273 if (builtin.os.tag == .windows) {
274 const dest_path_w = try os.windows.sliceToPrefixedFileW(self.dest_path);274 const dest_path_w = try os.windows.sliceToPrefixedFileW(self.dest_path);
275 const tmp_path_w = try os.windows.cStrToPrefixedFileW(@ptrCast([*:0]u8, &self.tmp_path_buf));275 const tmp_path_w = try os.windows.cStrToPrefixedFileW(@ptrCast([*:0]u8, &self.tmp_path_buf));
276 return os.renameW(&tmp_path_w, &dest_path_w);276 return os.renameW(&tmp_path_w, &dest_path_w);
...@@ -394,7 +394,7 @@ pub const Dir = struct {...@@ -394,7 +394,7 @@ pub const Dir = struct {
394394
395 const IteratorError = error{AccessDenied} || os.UnexpectedError;395 const IteratorError = error{AccessDenied} || os.UnexpectedError;
396396
397 pub const Iterator = switch (builtin.os) {397 pub const Iterator = switch (builtin.os.tag) {
398 .macosx, .ios, .freebsd, .netbsd, .dragonfly => struct {398 .macosx, .ios, .freebsd, .netbsd, .dragonfly => struct {
399 dir: Dir,399 dir: Dir,
400 seek: i64,400 seek: i64,
...@@ -409,7 +409,7 @@ pub const Dir = struct {...@@ -409,7 +409,7 @@ pub const Dir = struct {
409 /// Memory such as file names referenced in this returned entry becomes invalid409 /// Memory such as file names referenced in this returned entry becomes invalid
410 /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized.410 /// with subsequent calls to `next`, as well as when this `Dir` is deinitialized.
411 pub fn next(self: *Self) Error!?Entry {411 pub fn next(self: *Self) Error!?Entry {
412 switch (builtin.os) {412 switch (builtin.os.tag) {
413 .macosx, .ios => return self.nextDarwin(),413 .macosx, .ios => return self.nextDarwin(),
414 .freebsd, .netbsd, .dragonfly => return self.nextBsd(),414 .freebsd, .netbsd, .dragonfly => return self.nextBsd(),
415 else => @compileError("unimplemented"),415 else => @compileError("unimplemented"),
...@@ -644,7 +644,7 @@ pub const Dir = struct {...@@ -644,7 +644,7 @@ pub const Dir = struct {
644 };644 };
645645
646 pub fn iterate(self: Dir) Iterator {646 pub fn iterate(self: Dir) Iterator {
647 switch (builtin.os) {647 switch (builtin.os.tag) {
648 .macosx, .ios, .freebsd, .netbsd, .dragonfly => return Iterator{648 .macosx, .ios, .freebsd, .netbsd, .dragonfly => return Iterator{
649 .dir = self,649 .dir = self,
650 .seek = 0,650 .seek = 0,
...@@ -710,7 +710,7 @@ pub const Dir = struct {...@@ -710,7 +710,7 @@ pub const Dir = struct {
710 /// Asserts that the path parameter has no null bytes.710 /// Asserts that the path parameter has no null bytes.
711 pub fn openFile(self: Dir, sub_path: []const u8, flags: File.OpenFlags) File.OpenError!File {711 pub fn openFile(self: Dir, sub_path: []const u8, flags: File.OpenFlags) File.OpenError!File {
712 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);712 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);
713 if (builtin.os == .windows) {713 if (builtin.os.tag == .windows) {
714 const path_w = try os.windows.sliceToPrefixedFileW(sub_path);714 const path_w = try os.windows.sliceToPrefixedFileW(sub_path);
715 return self.openFileW(&path_w, flags);715 return self.openFileW(&path_w, flags);
716 }716 }
...@@ -720,7 +720,7 @@ pub const Dir = struct {...@@ -720,7 +720,7 @@ pub const Dir = struct {
720720
721 /// Same as `openFile` but the path parameter is null-terminated.721 /// Same as `openFile` but the path parameter is null-terminated.
722 pub fn openFileC(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File {722 pub fn openFileC(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File {
723 if (builtin.os == .windows) {723 if (builtin.os.tag == .windows) {
724 const path_w = try os.windows.cStrToPrefixedFileW(sub_path);724 const path_w = try os.windows.cStrToPrefixedFileW(sub_path);
725 return self.openFileW(&path_w, flags);725 return self.openFileW(&path_w, flags);
726 }726 }
...@@ -760,7 +760,7 @@ pub const Dir = struct {...@@ -760,7 +760,7 @@ pub const Dir = struct {
760 /// Asserts that the path parameter has no null bytes.760 /// Asserts that the path parameter has no null bytes.
761 pub fn createFile(self: Dir, sub_path: []const u8, flags: File.CreateFlags) File.OpenError!File {761 pub fn createFile(self: Dir, sub_path: []const u8, flags: File.CreateFlags) File.OpenError!File {
762 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);762 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);
763 if (builtin.os == .windows) {763 if (builtin.os.tag == .windows) {
764 const path_w = try os.windows.sliceToPrefixedFileW(sub_path);764 const path_w = try os.windows.sliceToPrefixedFileW(sub_path);
765 return self.createFileW(&path_w, flags);765 return self.createFileW(&path_w, flags);
766 }766 }
...@@ -770,7 +770,7 @@ pub const Dir = struct {...@@ -770,7 +770,7 @@ pub const Dir = struct {
770770
771 /// Same as `createFile` but the path parameter is null-terminated.771 /// Same as `createFile` but the path parameter is null-terminated.
772 pub fn createFileC(self: Dir, sub_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File {772 pub fn createFileC(self: Dir, sub_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File {
773 if (builtin.os == .windows) {773 if (builtin.os.tag == .windows) {
774 const path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);774 const path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);
775 return self.createFileW(&path_w, flags);775 return self.createFileW(&path_w, flags);
776 }776 }
...@@ -901,7 +901,7 @@ pub const Dir = struct {...@@ -901,7 +901,7 @@ pub const Dir = struct {
901 /// Asserts that the path parameter has no null bytes.901 /// Asserts that the path parameter has no null bytes.
902 pub fn openDirTraverse(self: Dir, sub_path: []const u8) OpenError!Dir {902 pub fn openDirTraverse(self: Dir, sub_path: []const u8) OpenError!Dir {
903 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);903 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);
904 if (builtin.os == .windows) {904 if (builtin.os.tag == .windows) {
905 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);905 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);
906 return self.openDirTraverseW(&sub_path_w);906 return self.openDirTraverseW(&sub_path_w);
907 }907 }
...@@ -919,7 +919,7 @@ pub const Dir = struct {...@@ -919,7 +919,7 @@ pub const Dir = struct {
919 /// Asserts that the path parameter has no null bytes.919 /// Asserts that the path parameter has no null bytes.
920 pub fn openDirList(self: Dir, sub_path: []const u8) OpenError!Dir {920 pub fn openDirList(self: Dir, sub_path: []const u8) OpenError!Dir {
921 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);921 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);
922 if (builtin.os == .windows) {922 if (builtin.os.tag == .windows) {
923 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);923 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);
924 return self.openDirListW(&sub_path_w);924 return self.openDirListW(&sub_path_w);
925 }925 }
...@@ -930,7 +930,7 @@ pub const Dir = struct {...@@ -930,7 +930,7 @@ pub const Dir = struct {
930930
931 /// Same as `openDirTraverse` except the parameter is null-terminated.931 /// Same as `openDirTraverse` except the parameter is null-terminated.
932 pub fn openDirTraverseC(self: Dir, sub_path_c: [*:0]const u8) OpenError!Dir {932 pub fn openDirTraverseC(self: Dir, sub_path_c: [*:0]const u8) OpenError!Dir {
933 if (builtin.os == .windows) {933 if (builtin.os.tag == .windows) {
934 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);934 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);
935 return self.openDirTraverseW(&sub_path_w);935 return self.openDirTraverseW(&sub_path_w);
936 } else {936 } else {
...@@ -941,7 +941,7 @@ pub const Dir = struct {...@@ -941,7 +941,7 @@ pub const Dir = struct {
941941
942 /// Same as `openDirList` except the parameter is null-terminated.942 /// Same as `openDirList` except the parameter is null-terminated.
943 pub fn openDirListC(self: Dir, sub_path_c: [*:0]const u8) OpenError!Dir {943 pub fn openDirListC(self: Dir, sub_path_c: [*:0]const u8) OpenError!Dir {
944 if (builtin.os == .windows) {944 if (builtin.os.tag == .windows) {
945 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);945 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);
946 return self.openDirListW(&sub_path_w);946 return self.openDirListW(&sub_path_w);
947 } else {947 } else {
...@@ -1083,7 +1083,7 @@ pub const Dir = struct {...@@ -1083,7 +1083,7 @@ pub const Dir = struct {
1083 /// Asserts that the path parameter has no null bytes.1083 /// Asserts that the path parameter has no null bytes.
1084 pub fn deleteDir(self: Dir, sub_path: []const u8) DeleteDirError!void {1084 pub fn deleteDir(self: Dir, sub_path: []const u8) DeleteDirError!void {
1085 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);1085 if (std.debug.runtime_safety) for (sub_path) |byte| assert(byte != 0);
1086 if (builtin.os == .windows) {1086 if (builtin.os.tag == .windows) {
1087 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);1087 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);
1088 return self.deleteDirW(&sub_path_w);1088 return self.deleteDirW(&sub_path_w);
1089 }1089 }
...@@ -1340,7 +1340,7 @@ pub const Dir = struct {...@@ -1340,7 +1340,7 @@ pub const Dir = struct {
1340 /// For example, instead of testing if a file exists and then opening it, just1340 /// For example, instead of testing if a file exists and then opening it, just
1341 /// open it and handle the error for file not found.1341 /// open it and handle the error for file not found.
1342 pub fn access(self: Dir, sub_path: []const u8, flags: File.OpenFlags) AccessError!void {1342 pub fn access(self: Dir, sub_path: []const u8, flags: File.OpenFlags) AccessError!void {
1343 if (builtin.os == .windows) {1343 if (builtin.os.tag == .windows) {
1344 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);1344 const sub_path_w = try os.windows.sliceToPrefixedFileW(sub_path);
1345 return self.accessW(&sub_path_w, flags);1345 return self.accessW(&sub_path_w, flags);
1346 }1346 }
...@@ -1350,7 +1350,7 @@ pub const Dir = struct {...@@ -1350,7 +1350,7 @@ pub const Dir = struct {
13501350
1351 /// Same as `access` except the path parameter is null-terminated.1351 /// Same as `access` except the path parameter is null-terminated.
1352 pub fn accessZ(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) AccessError!void {1352 pub fn accessZ(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) AccessError!void {
1353 if (builtin.os == .windows) {1353 if (builtin.os.tag == .windows) {
1354 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path);1354 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path);
1355 return self.accessW(&sub_path_w, flags);1355 return self.accessW(&sub_path_w, flags);
1356 }1356 }
...@@ -1381,7 +1381,7 @@ pub const Dir = struct {...@@ -1381,7 +1381,7 @@ pub const Dir = struct {
1381/// Closing the returned `Dir` is checked illegal behavior. Iterating over the result is illegal behavior.1381/// Closing the returned `Dir` is checked illegal behavior. Iterating over the result is illegal behavior.
1382/// On POSIX targets, this function is comptime-callable.1382/// On POSIX targets, this function is comptime-callable.
1383pub fn cwd() Dir {1383pub fn cwd() Dir {
1384 if (builtin.os == .windows) {1384 if (builtin.os.tag == .windows) {
1385 return Dir{ .fd = os.windows.peb().ProcessParameters.CurrentDirectory.Handle };1385 return Dir{ .fd = os.windows.peb().ProcessParameters.CurrentDirectory.Handle };
1386 } else {1386 } else {
1387 return Dir{ .fd = os.AT_FDCWD };1387 return Dir{ .fd = os.AT_FDCWD };
...@@ -1560,10 +1560,10 @@ pub fn readLinkC(pathname_c: [*]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {...@@ -1560,10 +1560,10 @@ pub fn readLinkC(pathname_c: [*]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
1560pub const OpenSelfExeError = os.OpenError || os.windows.CreateFileError || SelfExePathError;1560pub const OpenSelfExeError = os.OpenError || os.windows.CreateFileError || SelfExePathError;
15611561
1562pub fn openSelfExe() OpenSelfExeError!File {1562pub fn openSelfExe() OpenSelfExeError!File {
1563 if (builtin.os == .linux) {1563 if (builtin.os.tag == .linux) {
1564 return openFileAbsoluteC("/proc/self/exe", .{});1564 return openFileAbsoluteC("/proc/self/exe", .{});
1565 }1565 }
1566 if (builtin.os == .windows) {1566 if (builtin.os.tag == .windows) {
1567 const wide_slice = selfExePathW();1567 const wide_slice = selfExePathW();
1568 const prefixed_path_w = try os.windows.wToPrefixedFileW(wide_slice);1568 const prefixed_path_w = try os.windows.wToPrefixedFileW(wide_slice);
1569 return cwd().openReadW(&prefixed_path_w);1569 return cwd().openReadW(&prefixed_path_w);
...@@ -1575,7 +1575,7 @@ pub fn openSelfExe() OpenSelfExeError!File {...@@ -1575,7 +1575,7 @@ pub fn openSelfExe() OpenSelfExeError!File {
1575}1575}
15761576
1577test "openSelfExe" {1577test "openSelfExe" {
1578 switch (builtin.os) {1578 switch (builtin.os.tag) {
1579 .linux, .macosx, .ios, .windows, .freebsd, .dragonfly => (try openSelfExe()).close(),1579 .linux, .macosx, .ios, .windows, .freebsd, .dragonfly => (try openSelfExe()).close(),
1580 else => return error.SkipZigTest, // Unsupported OS.1580 else => return error.SkipZigTest, // Unsupported OS.
1581 }1581 }
...@@ -1600,7 +1600,7 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {...@@ -1600,7 +1600,7 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {
1600 if (rc != 0) return error.NameTooLong;1600 if (rc != 0) return error.NameTooLong;
1601 return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer));1601 return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer));
1602 }1602 }
1603 switch (builtin.os) {1603 switch (builtin.os.tag) {
1604 .linux => return os.readlinkC("/proc/self/exe", out_buffer),1604 .linux => return os.readlinkC("/proc/self/exe", out_buffer),
1605 .freebsd, .dragonfly => {1605 .freebsd, .dragonfly => {
1606 var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC, os.KERN_PROC_PATHNAME, -1 };1606 var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC, os.KERN_PROC_PATHNAME, -1 };
...@@ -1642,7 +1642,7 @@ pub fn selfExeDirPathAlloc(allocator: *Allocator) ![]u8 {...@@ -1642,7 +1642,7 @@ pub fn selfExeDirPathAlloc(allocator: *Allocator) ![]u8 {
1642/// Get the directory path that contains the current executable.1642/// Get the directory path that contains the current executable.
1643/// Returned value is a slice of out_buffer.1643/// Returned value is a slice of out_buffer.
1644pub fn selfExeDirPath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]const u8 {1644pub fn selfExeDirPath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]const u8 {
1645 if (builtin.os == .linux) {1645 if (builtin.os.tag == .linux) {
1646 // If the currently executing binary has been deleted,1646 // If the currently executing binary has been deleted,
1647 // the file path looks something like `/a/b/c/exe (deleted)`1647 // the file path looks something like `/a/b/c/exe (deleted)`
1648 // This path cannot be opened, but it's valid for determining the directory1648 // This path cannot be opened, but it's valid for determining the directory
lib/std/fs/file.zig+6-6
...@@ -29,7 +29,7 @@ pub const File = struct {...@@ -29,7 +29,7 @@ pub const File = struct {
2929
30 pub const Mode = os.mode_t;30 pub const Mode = os.mode_t;
3131
32 pub const default_mode = switch (builtin.os) {32 pub const default_mode = switch (builtin.os.tag) {
33 .windows => 0,33 .windows => 0,
34 else => 0o666,34 else => 0o666,
35 };35 };
...@@ -83,7 +83,7 @@ pub const File = struct {...@@ -83,7 +83,7 @@ pub const File = struct {
8383
84 /// Test whether ANSI escape codes will be treated as such.84 /// Test whether ANSI escape codes will be treated as such.
85 pub fn supportsAnsiEscapeCodes(self: File) bool {85 pub fn supportsAnsiEscapeCodes(self: File) bool {
86 if (builtin.os == .windows) {86 if (builtin.os.tag == .windows) {
87 return os.isCygwinPty(self.handle);87 return os.isCygwinPty(self.handle);
88 }88 }
89 if (self.isTty()) {89 if (self.isTty()) {
...@@ -128,7 +128,7 @@ pub const File = struct {...@@ -128,7 +128,7 @@ pub const File = struct {
128128
129 /// TODO: integrate with async I/O129 /// TODO: integrate with async I/O
130 pub fn getEndPos(self: File) GetPosError!u64 {130 pub fn getEndPos(self: File) GetPosError!u64 {
131 if (builtin.os == .windows) {131 if (builtin.os.tag == .windows) {
132 return windows.GetFileSizeEx(self.handle);132 return windows.GetFileSizeEx(self.handle);
133 }133 }
134 return (try self.stat()).size;134 return (try self.stat()).size;
...@@ -138,7 +138,7 @@ pub const File = struct {...@@ -138,7 +138,7 @@ pub const File = struct {
138138
139 /// TODO: integrate with async I/O139 /// TODO: integrate with async I/O
140 pub fn mode(self: File) ModeError!Mode {140 pub fn mode(self: File) ModeError!Mode {
141 if (builtin.os == .windows) {141 if (builtin.os.tag == .windows) {
142 return {};142 return {};
143 }143 }
144 return (try self.stat()).mode;144 return (try self.stat()).mode;
...@@ -162,7 +162,7 @@ pub const File = struct {...@@ -162,7 +162,7 @@ pub const File = struct {
162162
163 /// TODO: integrate with async I/O163 /// TODO: integrate with async I/O
164 pub fn stat(self: File) StatError!Stat {164 pub fn stat(self: File) StatError!Stat {
165 if (builtin.os == .windows) {165 if (builtin.os.tag == .windows) {
166 var io_status_block: windows.IO_STATUS_BLOCK = undefined;166 var io_status_block: windows.IO_STATUS_BLOCK = undefined;
167 var info: windows.FILE_ALL_INFORMATION = undefined;167 var info: windows.FILE_ALL_INFORMATION = undefined;
168 const rc = windows.ntdll.NtQueryInformationFile(self.handle, &io_status_block, &info, @sizeOf(windows.FILE_ALL_INFORMATION), .FileAllInformation);168 const rc = windows.ntdll.NtQueryInformationFile(self.handle, &io_status_block, &info, @sizeOf(windows.FILE_ALL_INFORMATION), .FileAllInformation);
...@@ -209,7 +209,7 @@ pub const File = struct {...@@ -209,7 +209,7 @@ pub const File = struct {
209 /// last modification timestamp in nanoseconds209 /// last modification timestamp in nanoseconds
210 mtime: i64,210 mtime: i64,
211 ) UpdateTimesError!void {211 ) UpdateTimesError!void {
212 if (builtin.os == .windows) {212 if (builtin.os.tag == .windows) {
213 const atime_ft = windows.nanoSecondsToFileTime(atime);213 const atime_ft = windows.nanoSecondsToFileTime(atime);
214 const mtime_ft = windows.nanoSecondsToFileTime(mtime);214 const mtime_ft = windows.nanoSecondsToFileTime(mtime);
215 return windows.SetFileTime(self.handle, null, &atime_ft, &mtime_ft);215 return windows.SetFileTime(self.handle, null, &atime_ft, &mtime_ft);
lib/std/fs/get_app_data_dir.zig+1-1
...@@ -13,7 +13,7 @@ pub const GetAppDataDirError = error{...@@ -13,7 +13,7 @@ pub const GetAppDataDirError = error{
13/// Caller owns returned memory.13/// Caller owns returned memory.
14/// TODO determine if we can remove the allocator requirement14/// TODO determine if we can remove the allocator requirement
15pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataDirError![]u8 {15pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataDirError![]u8 {
16 switch (builtin.os) {16 switch (builtin.os.tag) {
17 .windows => {17 .windows => {
18 var dir_path_ptr: [*:0]u16 = undefined;18 var dir_path_ptr: [*:0]u16 = undefined;
19 switch (os.windows.shell32.SHGetKnownFolderPath(19 switch (os.windows.shell32.SHGetKnownFolderPath(
lib/std/fs/path.zig+19-19
...@@ -13,18 +13,18 @@ const process = std.process;...@@ -13,18 +13,18 @@ const process = std.process;
1313
14pub const sep_windows = '\\';14pub const sep_windows = '\\';
15pub const sep_posix = '/';15pub const sep_posix = '/';
16pub const sep = if (builtin.os == .windows) sep_windows else sep_posix;16pub const sep = if (builtin.os.tag == .windows) sep_windows else sep_posix;
1717
18pub const sep_str_windows = "\\";18pub const sep_str_windows = "\\";
19pub const sep_str_posix = "/";19pub const sep_str_posix = "/";
20pub const sep_str = if (builtin.os == .windows) sep_str_windows else sep_str_posix;20pub const sep_str = if (builtin.os.tag == .windows) sep_str_windows else sep_str_posix;
2121
22pub const delimiter_windows = ';';22pub const delimiter_windows = ';';
23pub const delimiter_posix = ':';23pub const delimiter_posix = ':';
24pub const delimiter = if (builtin.os == .windows) delimiter_windows else delimiter_posix;24pub const delimiter = if (builtin.os.tag == .windows) delimiter_windows else delimiter_posix;
2525
26pub fn isSep(byte: u8) bool {26pub fn isSep(byte: u8) bool {
27 if (builtin.os == .windows) {27 if (builtin.os.tag == .windows) {
28 return byte == '/' or byte == '\\';28 return byte == '/' or byte == '\\';
29 } else {29 } else {
30 return byte == '/';30 return byte == '/';
...@@ -74,7 +74,7 @@ fn joinSep(allocator: *Allocator, separator: u8, paths: []const []const u8) ![]u...@@ -74,7 +74,7 @@ fn joinSep(allocator: *Allocator, separator: u8, paths: []const []const u8) ![]u
74 return buf;74 return buf;
75}75}
7676
77pub const join = if (builtin.os == .windows) joinWindows else joinPosix;77pub const join = if (builtin.os.tag == .windows) joinWindows else joinPosix;
7878
79/// Naively combines a series of paths with the native path seperator.79/// Naively combines a series of paths with the native path seperator.
80/// Allocates memory for the result, which must be freed by the caller.80/// Allocates memory for the result, which must be freed by the caller.
...@@ -129,7 +129,7 @@ test "join" {...@@ -129,7 +129,7 @@ test "join" {
129}129}
130130
131pub fn isAbsoluteC(path_c: [*:0]const u8) bool {131pub fn isAbsoluteC(path_c: [*:0]const u8) bool {
132 if (builtin.os == .windows) {132 if (builtin.os.tag == .windows) {
133 return isAbsoluteWindowsC(path_c);133 return isAbsoluteWindowsC(path_c);
134 } else {134 } else {
135 return isAbsolutePosixC(path_c);135 return isAbsolutePosixC(path_c);
...@@ -137,7 +137,7 @@ pub fn isAbsoluteC(path_c: [*:0]const u8) bool {...@@ -137,7 +137,7 @@ pub fn isAbsoluteC(path_c: [*:0]const u8) bool {
137}137}
138138
139pub fn isAbsolute(path: []const u8) bool {139pub fn isAbsolute(path: []const u8) bool {
140 if (builtin.os == .windows) {140 if (builtin.os.tag == .windows) {
141 return isAbsoluteWindows(path);141 return isAbsoluteWindows(path);
142 } else {142 } else {
143 return isAbsolutePosix(path);143 return isAbsolutePosix(path);
...@@ -318,7 +318,7 @@ test "windowsParsePath" {...@@ -318,7 +318,7 @@ test "windowsParsePath" {
318}318}
319319
320pub fn diskDesignator(path: []const u8) []const u8 {320pub fn diskDesignator(path: []const u8) []const u8 {
321 if (builtin.os == .windows) {321 if (builtin.os.tag == .windows) {
322 return diskDesignatorWindows(path);322 return diskDesignatorWindows(path);
323 } else {323 } else {
324 return "";324 return "";
...@@ -383,7 +383,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {...@@ -383,7 +383,7 @@ fn asciiEqlIgnoreCase(s1: []const u8, s2: []const u8) bool {
383383
384/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.384/// On Windows, this calls `resolveWindows` and on POSIX it calls `resolvePosix`.
385pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {385pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
386 if (builtin.os == .windows) {386 if (builtin.os.tag == .windows) {
387 return resolveWindows(allocator, paths);387 return resolveWindows(allocator, paths);
388 } else {388 } else {
389 return resolvePosix(allocator, paths);389 return resolvePosix(allocator, paths);
...@@ -400,7 +400,7 @@ pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {...@@ -400,7 +400,7 @@ pub fn resolve(allocator: *Allocator, paths: []const []const u8) ![]u8 {
400/// Without performing actual syscalls, resolving `..` could be incorrect.400/// Without performing actual syscalls, resolving `..` could be incorrect.
401pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {401pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
402 if (paths.len == 0) {402 if (paths.len == 0) {
403 assert(builtin.os == .windows); // resolveWindows called on non windows can't use getCwd403 assert(builtin.os.tag == .windows); // resolveWindows called on non windows can't use getCwd
404 return process.getCwdAlloc(allocator);404 return process.getCwdAlloc(allocator);
405 }405 }
406406
...@@ -495,7 +495,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {...@@ -495,7 +495,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
495 result_disk_designator = result[0..result_index];495 result_disk_designator = result[0..result_index];
496 },496 },
497 WindowsPath.Kind.None => {497 WindowsPath.Kind.None => {
498 assert(builtin.os == .windows); // resolveWindows called on non windows can't use getCwd498 assert(builtin.os.tag == .windows); // resolveWindows called on non windows can't use getCwd
499 const cwd = try process.getCwdAlloc(allocator);499 const cwd = try process.getCwdAlloc(allocator);
500 defer allocator.free(cwd);500 defer allocator.free(cwd);
501 const parsed_cwd = windowsParsePath(cwd);501 const parsed_cwd = windowsParsePath(cwd);
...@@ -510,7 +510,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {...@@ -510,7 +510,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
510 },510 },
511 }511 }
512 } else {512 } else {
513 assert(builtin.os == .windows); // resolveWindows called on non windows can't use getCwd513 assert(builtin.os.tag == .windows); // resolveWindows called on non windows can't use getCwd
514 // TODO call get cwd for the result_disk_designator instead of the global one514 // TODO call get cwd for the result_disk_designator instead of the global one
515 const cwd = try process.getCwdAlloc(allocator);515 const cwd = try process.getCwdAlloc(allocator);
516 defer allocator.free(cwd);516 defer allocator.free(cwd);
...@@ -581,7 +581,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {...@@ -581,7 +581,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 {
581/// Without performing actual syscalls, resolving `..` could be incorrect.581/// Without performing actual syscalls, resolving `..` could be incorrect.
582pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {582pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
583 if (paths.len == 0) {583 if (paths.len == 0) {
584 assert(builtin.os != .windows); // resolvePosix called on windows can't use getCwd584 assert(builtin.os.tag != .windows); // resolvePosix called on windows can't use getCwd
585 return process.getCwdAlloc(allocator);585 return process.getCwdAlloc(allocator);
586 }586 }
587587
...@@ -603,7 +603,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {...@@ -603,7 +603,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
603 if (have_abs) {603 if (have_abs) {
604 result = try allocator.alloc(u8, max_size);604 result = try allocator.alloc(u8, max_size);
605 } else {605 } else {
606 assert(builtin.os != .windows); // resolvePosix called on windows can't use getCwd606 assert(builtin.os.tag != .windows); // resolvePosix called on windows can't use getCwd
607 const cwd = try process.getCwdAlloc(allocator);607 const cwd = try process.getCwdAlloc(allocator);
608 defer allocator.free(cwd);608 defer allocator.free(cwd);
609 result = try allocator.alloc(u8, max_size + cwd.len + 1);609 result = try allocator.alloc(u8, max_size + cwd.len + 1);
...@@ -645,7 +645,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {...@@ -645,7 +645,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 {
645test "resolve" {645test "resolve" {
646 const cwd = try process.getCwdAlloc(testing.allocator);646 const cwd = try process.getCwdAlloc(testing.allocator);
647 defer testing.allocator.free(cwd);647 defer testing.allocator.free(cwd);
648 if (builtin.os == .windows) {648 if (builtin.os.tag == .windows) {
649 if (windowsParsePath(cwd).kind == WindowsPath.Kind.Drive) {649 if (windowsParsePath(cwd).kind == WindowsPath.Kind.Drive) {
650 cwd[0] = asciiUpper(cwd[0]);650 cwd[0] = asciiUpper(cwd[0]);
651 }651 }
...@@ -661,7 +661,7 @@ test "resolveWindows" {...@@ -661,7 +661,7 @@ test "resolveWindows" {
661 // TODO https://github.com/ziglang/zig/issues/3288661 // TODO https://github.com/ziglang/zig/issues/3288
662 return error.SkipZigTest;662 return error.SkipZigTest;
663 }663 }
664 if (builtin.os == .windows) {664 if (builtin.os.tag == .windows) {
665 const cwd = try process.getCwdAlloc(testing.allocator);665 const cwd = try process.getCwdAlloc(testing.allocator);
666 defer testing.allocator.free(cwd);666 defer testing.allocator.free(cwd);
667 const parsed_cwd = windowsParsePath(cwd);667 const parsed_cwd = windowsParsePath(cwd);
...@@ -732,7 +732,7 @@ fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void {...@@ -732,7 +732,7 @@ fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void {
732/// If the path is a file in the current directory (no directory component)732/// If the path is a file in the current directory (no directory component)
733/// then returns null733/// then returns null
734pub fn dirname(path: []const u8) ?[]const u8 {734pub fn dirname(path: []const u8) ?[]const u8 {
735 if (builtin.os == .windows) {735 if (builtin.os.tag == .windows) {
736 return dirnameWindows(path);736 return dirnameWindows(path);
737 } else {737 } else {
738 return dirnamePosix(path);738 return dirnamePosix(path);
...@@ -864,7 +864,7 @@ fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) void {...@@ -864,7 +864,7 @@ fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) void {
864}864}
865865
866pub fn basename(path: []const u8) []const u8 {866pub fn basename(path: []const u8) []const u8 {
867 if (builtin.os == .windows) {867 if (builtin.os.tag == .windows) {
868 return basenameWindows(path);868 return basenameWindows(path);
869 } else {869 } else {
870 return basenamePosix(path);870 return basenamePosix(path);
...@@ -980,7 +980,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) void {...@@ -980,7 +980,7 @@ fn testBasenameWindows(input: []const u8, expected_output: []const u8) void {
980/// string is returned.980/// string is returned.
981/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.981/// On Windows this canonicalizes the drive to a capital letter and paths to `\\`.
982pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {982pub fn relative(allocator: *Allocator, from: []const u8, to: []const u8) ![]u8 {
983 if (builtin.os == .windows) {983 if (builtin.os.tag == .windows) {
984 return relativeWindows(allocator, from, to);984 return relativeWindows(allocator, from, to);
985 } else {985 } else {
986 return relativePosix(allocator, from, to);986 return relativePosix(allocator, from, to);
lib/std/fs/watch.zig+4-4
...@@ -42,7 +42,7 @@ pub fn Watch(comptime V: type) type {...@@ -42,7 +42,7 @@ pub fn Watch(comptime V: type) type {
42 os_data: OsData,42 os_data: OsData,
43 allocator: *Allocator,43 allocator: *Allocator,
4444
45 const OsData = switch (builtin.os) {45 const OsData = switch (builtin.os.tag) {
46 // TODO https://github.com/ziglang/zig/issues/377846 // TODO https://github.com/ziglang/zig/issues/3778
47 .macosx, .freebsd, .netbsd, .dragonfly => KqOsData,47 .macosx, .freebsd, .netbsd, .dragonfly => KqOsData,
48 .linux => LinuxOsData,48 .linux => LinuxOsData,
...@@ -121,7 +121,7 @@ pub fn Watch(comptime V: type) type {...@@ -121,7 +121,7 @@ pub fn Watch(comptime V: type) type {
121 const self = try allocator.create(Self);121 const self = try allocator.create(Self);
122 errdefer allocator.destroy(self);122 errdefer allocator.destroy(self);
123123
124 switch (builtin.os) {124 switch (builtin.os.tag) {
125 .linux => {125 .linux => {
126 const inotify_fd = try os.inotify_init1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC);126 const inotify_fd = try os.inotify_init1(os.linux.IN_NONBLOCK | os.linux.IN_CLOEXEC);
127 errdefer os.close(inotify_fd);127 errdefer os.close(inotify_fd);
...@@ -172,7 +172,7 @@ pub fn Watch(comptime V: type) type {...@@ -172,7 +172,7 @@ pub fn Watch(comptime V: type) type {
172172
173 /// All addFile calls and removeFile calls must have completed.173 /// All addFile calls and removeFile calls must have completed.
174 pub fn deinit(self: *Self) void {174 pub fn deinit(self: *Self) void {
175 switch (builtin.os) {175 switch (builtin.os.tag) {
176 .macosx, .freebsd, .netbsd, .dragonfly => {176 .macosx, .freebsd, .netbsd, .dragonfly => {
177 // TODO we need to cancel the frames before destroying the lock177 // TODO we need to cancel the frames before destroying the lock
178 self.os_data.table_lock.deinit();178 self.os_data.table_lock.deinit();
...@@ -223,7 +223,7 @@ pub fn Watch(comptime V: type) type {...@@ -223,7 +223,7 @@ pub fn Watch(comptime V: type) type {
223 }223 }
224224
225 pub fn addFile(self: *Self, file_path: []const u8, value: V) !?V {225 pub fn addFile(self: *Self, file_path: []const u8, value: V) !?V {
226 switch (builtin.os) {226 switch (builtin.os.tag) {
227 .macosx, .freebsd, .netbsd, .dragonfly => return addFileKEvent(self, file_path, value),227 .macosx, .freebsd, .netbsd, .dragonfly => return addFileKEvent(self, file_path, value),
228 .linux => return addFileLinux(self, file_path, value),228 .linux => return addFileLinux(self, file_path, value),
229 .windows => return addFileWindows(self, file_path, value),229 .windows => return addFileWindows(self, file_path, value),
lib/std/hash/auto_hash.zig+3-5
...@@ -25,13 +25,13 @@ pub fn hashPointer(hasher: var, key: var, comptime strat: HashStrategy) void {...@@ -25,13 +25,13 @@ pub fn hashPointer(hasher: var, key: var, comptime strat: HashStrategy) void {
25 const info = @typeInfo(@TypeOf(key));25 const info = @typeInfo(@TypeOf(key));
2626
27 switch (info.Pointer.size) {27 switch (info.Pointer.size) {
28 builtin.TypeInfo.Pointer.Size.One => switch (strat) {28 .One => switch (strat) {
29 .Shallow => hash(hasher, @ptrToInt(key), .Shallow),29 .Shallow => hash(hasher, @ptrToInt(key), .Shallow),
30 .Deep => hash(hasher, key.*, .Shallow),30 .Deep => hash(hasher, key.*, .Shallow),
31 .DeepRecursive => hash(hasher, key.*, .DeepRecursive),31 .DeepRecursive => hash(hasher, key.*, .DeepRecursive),
32 },32 },
3333
34 builtin.TypeInfo.Pointer.Size.Slice => switch (strat) {34 .Slice => switch (strat) {
35 .Shallow => {35 .Shallow => {
36 hashPointer(hasher, key.ptr, .Shallow);36 hashPointer(hasher, key.ptr, .Shallow);
37 hash(hasher, key.len, .Shallow);37 hash(hasher, key.len, .Shallow);
...@@ -40,9 +40,7 @@ pub fn hashPointer(hasher: var, key: var, comptime strat: HashStrategy) void {...@@ -40,9 +40,7 @@ pub fn hashPointer(hasher: var, key: var, comptime strat: HashStrategy) void {
40 .DeepRecursive => hashArray(hasher, key, .DeepRecursive),40 .DeepRecursive => hashArray(hasher, key, .DeepRecursive),
41 },41 },
4242
43 builtin.TypeInfo.Pointer.Size.Many,43 .Many, .C, => switch (strat) {
44 builtin.TypeInfo.Pointer.Size.C,
45 => switch (strat) {
46 .Shallow => hash(hasher, @ptrToInt(key), .Shallow),44 .Shallow => hash(hasher, @ptrToInt(key), .Shallow),
47 else => @compileError(45 else => @compileError(
48 \\ unknown-length pointers and C pointers cannot be hashed deeply.46 \\ unknown-length pointers and C pointers cannot be hashed deeply.
lib/std/hash/benchmark.zig+1-1
...@@ -168,7 +168,7 @@ fn usage() void {...@@ -168,7 +168,7 @@ fn usage() void {
168}168}
169169
170fn mode(comptime x: comptime_int) comptime_int {170fn mode(comptime x: comptime_int) comptime_int {
171 return if (builtin.mode == builtin.Mode.Debug) x / 64 else x;171 return if (builtin.mode == .Debug) x / 64 else x;
172}172}
173173
174pub fn main() !void {174pub fn main() !void {
lib/std/hash/cityhash.zig+4-4
...@@ -11,7 +11,7 @@ pub const CityHash32 = struct {...@@ -11,7 +11,7 @@ pub const CityHash32 = struct {
11 fn fetch32(ptr: [*]const u8) u32 {11 fn fetch32(ptr: [*]const u8) u32 {
12 var v: u32 = undefined;12 var v: u32 = undefined;
13 @memcpy(@ptrCast([*]u8, &v), ptr, 4);13 @memcpy(@ptrCast([*]u8, &v), ptr, 4);
14 if (builtin.endian == builtin.Endian.Big)14 if (builtin.endian == .Big)
15 return @byteSwap(u32, v);15 return @byteSwap(u32, v);
16 return v;16 return v;
17 }17 }
...@@ -174,7 +174,7 @@ pub const CityHash64 = struct {...@@ -174,7 +174,7 @@ pub const CityHash64 = struct {
174 fn fetch32(ptr: [*]const u8) u32 {174 fn fetch32(ptr: [*]const u8) u32 {
175 var v: u32 = undefined;175 var v: u32 = undefined;
176 @memcpy(@ptrCast([*]u8, &v), ptr, 4);176 @memcpy(@ptrCast([*]u8, &v), ptr, 4);
177 if (builtin.endian == builtin.Endian.Big)177 if (builtin.endian == .Big)
178 return @byteSwap(u32, v);178 return @byteSwap(u32, v);
179 return v;179 return v;
180 }180 }
...@@ -182,7 +182,7 @@ pub const CityHash64 = struct {...@@ -182,7 +182,7 @@ pub const CityHash64 = struct {
182 fn fetch64(ptr: [*]const u8) u64 {182 fn fetch64(ptr: [*]const u8) u64 {
183 var v: u64 = undefined;183 var v: u64 = undefined;
184 @memcpy(@ptrCast([*]u8, &v), ptr, 8);184 @memcpy(@ptrCast([*]u8, &v), ptr, 8);
185 if (builtin.endian == builtin.Endian.Big)185 if (builtin.endian == .Big)
186 return @byteSwap(u64, v);186 return @byteSwap(u64, v);
187 return v;187 return v;
188 }188 }
...@@ -369,7 +369,7 @@ fn SMHasherTest(comptime hash_fn: var, comptime hashbits: u32) u32 {...@@ -369,7 +369,7 @@ fn SMHasherTest(comptime hash_fn: var, comptime hashbits: u32) u32 {
369 key[i] = @intCast(u8, i);369 key[i] = @intCast(u8, i);
370370
371 var h = hash_fn(key[0..i], 256 - i);371 var h = hash_fn(key[0..i], 256 - i);
372 if (builtin.endian == builtin.Endian.Big)372 if (builtin.endian == .Big)
373 h = @byteSwap(@TypeOf(h), h);373 h = @byteSwap(@TypeOf(h), h);
374 @memcpy(@ptrCast([*]u8, &hashes[i * hashbytes]), @ptrCast([*]u8, &h), hashbytes);374 @memcpy(@ptrCast([*]u8, &hashes[i * hashbytes]), @ptrCast([*]u8, &h), hashbytes);
375 }375 }
lib/std/hash/murmur.zig+8-8
...@@ -17,7 +17,7 @@ pub const Murmur2_32 = struct {...@@ -17,7 +17,7 @@ pub const Murmur2_32 = struct {
17 var h1: u32 = seed ^ len;17 var h1: u32 = seed ^ len;
18 for (@ptrCast([*]align(1) const u32, str.ptr)[0..(len >> 2)]) |v| {18 for (@ptrCast([*]align(1) const u32, str.ptr)[0..(len >> 2)]) |v| {
19 var k1: u32 = v;19 var k1: u32 = v;
20 if (builtin.endian == builtin.Endian.Big)20 if (builtin.endian == .Big)
21 k1 = @byteSwap(u32, k1);21 k1 = @byteSwap(u32, k1);
22 k1 *%= m;22 k1 *%= m;
23 k1 ^= k1 >> 24;23 k1 ^= k1 >> 24;
...@@ -102,7 +102,7 @@ pub const Murmur2_64 = struct {...@@ -102,7 +102,7 @@ pub const Murmur2_64 = struct {
102 var h1: u64 = seed ^ (len *% m);102 var h1: u64 = seed ^ (len *% m);
103 for (@ptrCast([*]align(1) const u64, str.ptr)[0..@intCast(usize, len >> 3)]) |v| {103 for (@ptrCast([*]align(1) const u64, str.ptr)[0..@intCast(usize, len >> 3)]) |v| {
104 var k1: u64 = v;104 var k1: u64 = v;
105 if (builtin.endian == builtin.Endian.Big)105 if (builtin.endian == .Big)
106 k1 = @byteSwap(u64, k1);106 k1 = @byteSwap(u64, k1);
107 k1 *%= m;107 k1 *%= m;
108 k1 ^= k1 >> 47;108 k1 ^= k1 >> 47;
...@@ -115,7 +115,7 @@ pub const Murmur2_64 = struct {...@@ -115,7 +115,7 @@ pub const Murmur2_64 = struct {
115 if (rest > 0) {115 if (rest > 0) {
116 var k1: u64 = 0;116 var k1: u64 = 0;
117 @memcpy(@ptrCast([*]u8, &k1), @ptrCast([*]const u8, &str[@intCast(usize, offset)]), @intCast(usize, rest));117 @memcpy(@ptrCast([*]u8, &k1), @ptrCast([*]const u8, &str[@intCast(usize, offset)]), @intCast(usize, rest));
118 if (builtin.endian == builtin.Endian.Big)118 if (builtin.endian == .Big)
119 k1 = @byteSwap(u64, k1);119 k1 = @byteSwap(u64, k1);
120 h1 ^= k1;120 h1 ^= k1;
121 h1 *%= m;121 h1 *%= m;
...@@ -182,7 +182,7 @@ pub const Murmur3_32 = struct {...@@ -182,7 +182,7 @@ pub const Murmur3_32 = struct {
182 var h1: u32 = seed;182 var h1: u32 = seed;
183 for (@ptrCast([*]align(1) const u32, str.ptr)[0..(len >> 2)]) |v| {183 for (@ptrCast([*]align(1) const u32, str.ptr)[0..(len >> 2)]) |v| {
184 var k1: u32 = v;184 var k1: u32 = v;
185 if (builtin.endian == builtin.Endian.Big)185 if (builtin.endian == .Big)
186 k1 = @byteSwap(u32, k1);186 k1 = @byteSwap(u32, k1);
187 k1 *%= c1;187 k1 *%= c1;
188 k1 = rotl32(k1, 15);188 k1 = rotl32(k1, 15);
...@@ -294,7 +294,7 @@ fn SMHasherTest(comptime hash_fn: var, comptime hashbits: u32) u32 {...@@ -294,7 +294,7 @@ fn SMHasherTest(comptime hash_fn: var, comptime hashbits: u32) u32 {
294 key[i] = @truncate(u8, i);294 key[i] = @truncate(u8, i);
295295
296 var h = hash_fn(key[0..i], 256 - i);296 var h = hash_fn(key[0..i], 256 - i);
297 if (builtin.endian == builtin.Endian.Big)297 if (builtin.endian == .Big)
298 h = @byteSwap(@TypeOf(h), h);298 h = @byteSwap(@TypeOf(h), h);
299 @memcpy(@ptrCast([*]u8, &hashes[i * hashbytes]), @ptrCast([*]u8, &h), hashbytes);299 @memcpy(@ptrCast([*]u8, &hashes[i * hashbytes]), @ptrCast([*]u8, &h), hashbytes);
300 }300 }
...@@ -308,7 +308,7 @@ test "murmur2_32" {...@@ -308,7 +308,7 @@ test "murmur2_32" {
308 var v1: u64 = 0x1234567812345678;308 var v1: u64 = 0x1234567812345678;
309 var v0le: u32 = v0;309 var v0le: u32 = v0;
310 var v1le: u64 = v1;310 var v1le: u64 = v1;
311 if (builtin.endian == builtin.Endian.Big) {311 if (builtin.endian == .Big) {
312 v0le = @byteSwap(u32, v0le);312 v0le = @byteSwap(u32, v0le);
313 v1le = @byteSwap(u64, v1le);313 v1le = @byteSwap(u64, v1le);
314 }314 }
...@@ -322,7 +322,7 @@ test "murmur2_64" {...@@ -322,7 +322,7 @@ test "murmur2_64" {
322 var v1: u64 = 0x1234567812345678;322 var v1: u64 = 0x1234567812345678;
323 var v0le: u32 = v0;323 var v0le: u32 = v0;
324 var v1le: u64 = v1;324 var v1le: u64 = v1;
325 if (builtin.endian == builtin.Endian.Big) {325 if (builtin.endian == .Big) {
326 v0le = @byteSwap(u32, v0le);326 v0le = @byteSwap(u32, v0le);
327 v1le = @byteSwap(u64, v1le);327 v1le = @byteSwap(u64, v1le);
328 }328 }
...@@ -336,7 +336,7 @@ test "murmur3_32" {...@@ -336,7 +336,7 @@ test "murmur3_32" {
336 var v1: u64 = 0x1234567812345678;336 var v1: u64 = 0x1234567812345678;
337 var v0le: u32 = v0;337 var v0le: u32 = v0;
338 var v1le: u64 = v1;338 var v1le: u64 = v1;
339 if (builtin.endian == builtin.Endian.Big) {339 if (builtin.endian == .Big) {
340 v0le = @byteSwap(u32, v0le);340 v0le = @byteSwap(u32, v0le);
341 v1le = @byteSwap(u64, v1le);341 v1le = @byteSwap(u64, v1le);
342 }342 }
lib/std/hash_map.zig+1-1
...@@ -10,7 +10,7 @@ const Wyhash = std.hash.Wyhash;...@@ -10,7 +10,7 @@ const Wyhash = std.hash.Wyhash;
10const Allocator = mem.Allocator;10const Allocator = mem.Allocator;
11const builtin = @import("builtin");11const builtin = @import("builtin");
1212
13const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast;13const want_modification_safety = builtin.mode != .ReleaseFast;
14const debug_u32 = if (want_modification_safety) u32 else void;14const debug_u32 = if (want_modification_safety) u32 else void;
1515
16pub fn AutoHashMap(comptime K: type, comptime V: type) type {16pub fn AutoHashMap(comptime K: type, comptime V: type) type {
lib/std/heap.zig+7-7
...@@ -36,7 +36,7 @@ fn cShrink(self: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new...@@ -36,7 +36,7 @@ fn cShrink(self: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new
36/// Thread-safe and lock-free.36/// Thread-safe and lock-free.
37pub const page_allocator = if (std.Target.current.isWasm())37pub const page_allocator = if (std.Target.current.isWasm())
38 &wasm_page_allocator_state38 &wasm_page_allocator_state
39else if (std.Target.current.getOs() == .freestanding)39else if (std.Target.current.os.tag == .freestanding)
40 root.os.heap.page_allocator40 root.os.heap.page_allocator
41else41else
42 &page_allocator_state;42 &page_allocator_state;
...@@ -57,7 +57,7 @@ const PageAllocator = struct {...@@ -57,7 +57,7 @@ const PageAllocator = struct {
57 fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 {57 fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 {
58 if (n == 0) return &[0]u8{};58 if (n == 0) return &[0]u8{};
5959
60 if (builtin.os == .windows) {60 if (builtin.os.tag == .windows) {
61 const w = os.windows;61 const w = os.windows;
6262
63 // Although officially it's at least aligned to page boundary,63 // Although officially it's at least aligned to page boundary,
...@@ -143,7 +143,7 @@ const PageAllocator = struct {...@@ -143,7 +143,7 @@ const PageAllocator = struct {
143143
144 fn shrink(allocator: *Allocator, old_mem_unaligned: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {144 fn shrink(allocator: *Allocator, old_mem_unaligned: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
145 const old_mem = @alignCast(mem.page_size, old_mem_unaligned);145 const old_mem = @alignCast(mem.page_size, old_mem_unaligned);
146 if (builtin.os == .windows) {146 if (builtin.os.tag == .windows) {
147 const w = os.windows;147 const w = os.windows;
148 if (new_size == 0) {148 if (new_size == 0) {
149 // From the docs:149 // From the docs:
...@@ -183,7 +183,7 @@ const PageAllocator = struct {...@@ -183,7 +183,7 @@ const PageAllocator = struct {
183183
184 fn realloc(allocator: *Allocator, old_mem_unaligned: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {184 fn realloc(allocator: *Allocator, old_mem_unaligned: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
185 const old_mem = @alignCast(mem.page_size, old_mem_unaligned);185 const old_mem = @alignCast(mem.page_size, old_mem_unaligned);
186 if (builtin.os == .windows) {186 if (builtin.os.tag == .windows) {
187 if (old_mem.len == 0) {187 if (old_mem.len == 0) {
188 return alloc(allocator, new_size, new_align);188 return alloc(allocator, new_size, new_align);
189 }189 }
...@@ -412,7 +412,7 @@ const WasmPageAllocator = struct {...@@ -412,7 +412,7 @@ const WasmPageAllocator = struct {
412 }412 }
413};413};
414414
415pub const HeapAllocator = switch (builtin.os) {415pub const HeapAllocator = switch (builtin.os.tag) {
416 .windows => struct {416 .windows => struct {
417 allocator: Allocator,417 allocator: Allocator,
418 heap_handle: ?HeapHandle,418 heap_handle: ?HeapHandle,
...@@ -855,7 +855,7 @@ test "PageAllocator" {...@@ -855,7 +855,7 @@ test "PageAllocator" {
855 try testAllocatorAlignedShrink(allocator);855 try testAllocatorAlignedShrink(allocator);
856 }856 }
857857
858 if (builtin.os == .windows) {858 if (builtin.os.tag == .windows) {
859 // Trying really large alignment. As mentionned in the implementation,859 // Trying really large alignment. As mentionned in the implementation,
860 // VirtualAlloc returns 64K aligned addresses. We want to make sure860 // VirtualAlloc returns 64K aligned addresses. We want to make sure
861 // PageAllocator works beyond that, as it's not tested by861 // PageAllocator works beyond that, as it's not tested by
...@@ -868,7 +868,7 @@ test "PageAllocator" {...@@ -868,7 +868,7 @@ test "PageAllocator" {
868}868}
869869
870test "HeapAllocator" {870test "HeapAllocator" {
871 if (builtin.os == .windows) {871 if (builtin.os.tag == .windows) {
872 var heap_allocator = HeapAllocator.init();872 var heap_allocator = HeapAllocator.init();
873 defer heap_allocator.deinit();873 defer heap_allocator.deinit();
874874
lib/std/io.zig+17-17
...@@ -35,7 +35,7 @@ else...@@ -35,7 +35,7 @@ else
35pub const is_async = mode != .blocking;35pub const is_async = mode != .blocking;
3636
37fn getStdOutHandle() os.fd_t {37fn getStdOutHandle() os.fd_t {
38 if (builtin.os == .windows) {38 if (builtin.os.tag == .windows) {
39 return os.windows.peb().ProcessParameters.hStdOutput;39 return os.windows.peb().ProcessParameters.hStdOutput;
40 }40 }
4141
...@@ -54,7 +54,7 @@ pub fn getStdOut() File {...@@ -54,7 +54,7 @@ pub fn getStdOut() File {
54}54}
5555
56fn getStdErrHandle() os.fd_t {56fn getStdErrHandle() os.fd_t {
57 if (builtin.os == .windows) {57 if (builtin.os.tag == .windows) {
58 return os.windows.peb().ProcessParameters.hStdError;58 return os.windows.peb().ProcessParameters.hStdError;
59 }59 }
6060
...@@ -74,7 +74,7 @@ pub fn getStdErr() File {...@@ -74,7 +74,7 @@ pub fn getStdErr() File {
74}74}
7575
76fn getStdInHandle() os.fd_t {76fn getStdInHandle() os.fd_t {
77 if (builtin.os == .windows) {77 if (builtin.os.tag == .windows) {
78 return os.windows.peb().ProcessParameters.hStdInput;78 return os.windows.peb().ProcessParameters.hStdInput;
79 }79 }
8080
...@@ -348,11 +348,11 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {...@@ -348,11 +348,11 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
348 const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;348 const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;
349 const shift = u7_bit_count - n;349 const shift = u7_bit_count - n;
350 switch (endian) {350 switch (endian) {
351 builtin.Endian.Big => {351 .Big => {
352 out_buffer = @as(Buf, self.bit_buffer >> shift);352 out_buffer = @as(Buf, self.bit_buffer >> shift);
353 self.bit_buffer <<= n;353 self.bit_buffer <<= n;
354 },354 },
355 builtin.Endian.Little => {355 .Little => {
356 const value = (self.bit_buffer << shift) >> shift;356 const value = (self.bit_buffer << shift) >> shift;
357 out_buffer = @as(Buf, value);357 out_buffer = @as(Buf, value);
358 self.bit_buffer >>= n;358 self.bit_buffer >>= n;
...@@ -376,7 +376,7 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {...@@ -376,7 +376,7 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
376 };376 };
377377
378 switch (endian) {378 switch (endian) {
379 builtin.Endian.Big => {379 .Big => {
380 if (n >= u8_bit_count) {380 if (n >= u8_bit_count) {
381 out_buffer <<= @intCast(u3, u8_bit_count - 1);381 out_buffer <<= @intCast(u3, u8_bit_count - 1);
382 out_buffer <<= 1;382 out_buffer <<= 1;
...@@ -392,7 +392,7 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {...@@ -392,7 +392,7 @@ pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
392 self.bit_buffer = @truncate(u7, next_byte << @intCast(u3, n - 1));392 self.bit_buffer = @truncate(u7, next_byte << @intCast(u3, n - 1));
393 self.bit_count = shift;393 self.bit_count = shift;
394 },394 },
395 builtin.Endian.Little => {395 .Little => {
396 if (n >= u8_bit_count) {396 if (n >= u8_bit_count) {
397 out_buffer |= @as(Buf, next_byte) << @intCast(BufShift, out_bits.*);397 out_buffer |= @as(Buf, next_byte) << @intCast(BufShift, out_bits.*);
398 out_bits.* += u8_bit_count;398 out_bits.* += u8_bit_count;
...@@ -666,8 +666,8 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {...@@ -666,8 +666,8 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {
666666
667 const high_byte_shift = @intCast(BufShift, buf_bit_count - u8_bit_count);667 const high_byte_shift = @intCast(BufShift, buf_bit_count - u8_bit_count);
668 var in_buffer = switch (endian) {668 var in_buffer = switch (endian) {
669 builtin.Endian.Big => buf_value << @intCast(BufShift, buf_bit_count - bits),669 .Big => buf_value << @intCast(BufShift, buf_bit_count - bits),
670 builtin.Endian.Little => buf_value,670 .Little => buf_value,
671 };671 };
672 var in_bits = bits;672 var in_bits = bits;
673673
...@@ -675,13 +675,13 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {...@@ -675,13 +675,13 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {
675 const bits_remaining = u8_bit_count - self.bit_count;675 const bits_remaining = u8_bit_count - self.bit_count;
676 const n = @intCast(u3, if (bits_remaining > bits) bits else bits_remaining);676 const n = @intCast(u3, if (bits_remaining > bits) bits else bits_remaining);
677 switch (endian) {677 switch (endian) {
678 builtin.Endian.Big => {678 .Big => {
679 const shift = @intCast(BufShift, high_byte_shift + self.bit_count);679 const shift = @intCast(BufShift, high_byte_shift + self.bit_count);
680 const v = @intCast(u8, in_buffer >> shift);680 const v = @intCast(u8, in_buffer >> shift);
681 self.bit_buffer |= v;681 self.bit_buffer |= v;
682 in_buffer <<= n;682 in_buffer <<= n;
683 },683 },
684 builtin.Endian.Little => {684 .Little => {
685 const v = @truncate(u8, in_buffer) << @intCast(u3, self.bit_count);685 const v = @truncate(u8, in_buffer) << @intCast(u3, self.bit_count);
686 self.bit_buffer |= v;686 self.bit_buffer |= v;
687 in_buffer >>= n;687 in_buffer >>= n;
...@@ -701,13 +701,13 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {...@@ -701,13 +701,13 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {
701 //copy bytes until we can't fill one anymore, then leave the rest in bit_buffer701 //copy bytes until we can't fill one anymore, then leave the rest in bit_buffer
702 while (in_bits >= u8_bit_count) {702 while (in_bits >= u8_bit_count) {
703 switch (endian) {703 switch (endian) {
704 builtin.Endian.Big => {704 .Big => {
705 const v = @intCast(u8, in_buffer >> high_byte_shift);705 const v = @intCast(u8, in_buffer >> high_byte_shift);
706 try self.out_stream.writeByte(v);706 try self.out_stream.writeByte(v);
707 in_buffer <<= @intCast(u3, u8_bit_count - 1);707 in_buffer <<= @intCast(u3, u8_bit_count - 1);
708 in_buffer <<= 1;708 in_buffer <<= 1;
709 },709 },
710 builtin.Endian.Little => {710 .Little => {
711 const v = @truncate(u8, in_buffer);711 const v = @truncate(u8, in_buffer);
712 try self.out_stream.writeByte(v);712 try self.out_stream.writeByte(v);
713 in_buffer >>= @intCast(u3, u8_bit_count - 1);713 in_buffer >>= @intCast(u3, u8_bit_count - 1);
...@@ -720,8 +720,8 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {...@@ -720,8 +720,8 @@ pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {
720 if (in_bits > 0) {720 if (in_bits > 0) {
721 self.bit_count = @intCast(u4, in_bits);721 self.bit_count = @intCast(u4, in_bits);
722 self.bit_buffer = switch (endian) {722 self.bit_buffer = switch (endian) {
723 builtin.Endian.Big => @truncate(u8, in_buffer >> high_byte_shift),723 .Big => @truncate(u8, in_buffer >> high_byte_shift),
724 builtin.Endian.Little => @truncate(u8, in_buffer),724 .Little => @truncate(u8, in_buffer),
725 };725 };
726 }726 }
727 }727 }
...@@ -858,10 +858,10 @@ pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing,...@@ -858,10 +858,10 @@ pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing,
858 var result = @as(U, 0);858 var result = @as(U, 0);
859 for (buffer) |byte, i| {859 for (buffer) |byte, i| {
860 switch (endian) {860 switch (endian) {
861 builtin.Endian.Big => {861 .Big => {
862 result = (result << u8_bit_count) | byte;862 result = (result << u8_bit_count) | byte;
863 },863 },
864 builtin.Endian.Little => {864 .Little => {
865 result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);865 result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);
866 },866 },
867 }867 }
lib/std/io/test.zig+1-1
...@@ -544,7 +544,7 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing:...@@ -544,7 +544,7 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing:
544}544}
545545
546test "Serializer/Deserializer generic" {546test "Serializer/Deserializer generic" {
547 if (std.Target.current.isWindows()) {547 if (std.Target.current.os.tag == .windows) {
548 // TODO https://github.com/ziglang/zig/issues/508548 // TODO https://github.com/ziglang/zig/issues/508
549 return error.SkipZigTest;549 return error.SkipZigTest;
550 }550 }
lib/std/math/fabs.zig+1-1
...@@ -95,7 +95,7 @@ test "math.fabs64.special" {...@@ -95,7 +95,7 @@ test "math.fabs64.special" {
95}95}
9696
97test "math.fabs128.special" {97test "math.fabs128.special" {
98 if (std.Target.current.isWindows()) {98 if (std.Target.current.os.tag == .windows) {
99 // TODO https://github.com/ziglang/zig/issues/50899 // TODO https://github.com/ziglang/zig/issues/508
100 return error.SkipZigTest;100 return error.SkipZigTest;
101 }101 }
lib/std/math/isinf.zig+3-3
...@@ -74,7 +74,7 @@ pub fn isNegativeInf(x: var) bool {...@@ -74,7 +74,7 @@ pub fn isNegativeInf(x: var) bool {
74}74}
7575
76test "math.isInf" {76test "math.isInf" {
77 if (std.Target.current.isWindows()) {77 if (std.Target.current.os.tag == .windows) {
78 // TODO https://github.com/ziglang/zig/issues/50878 // TODO https://github.com/ziglang/zig/issues/508
79 return error.SkipZigTest;79 return error.SkipZigTest;
80 }80 }
...@@ -97,7 +97,7 @@ test "math.isInf" {...@@ -97,7 +97,7 @@ test "math.isInf" {
97}97}
9898
99test "math.isPositiveInf" {99test "math.isPositiveInf" {
100 if (std.Target.current.isWindows()) {100 if (std.Target.current.os.tag == .windows) {
101 // TODO https://github.com/ziglang/zig/issues/508101 // TODO https://github.com/ziglang/zig/issues/508
102 return error.SkipZigTest;102 return error.SkipZigTest;
103 }103 }
...@@ -120,7 +120,7 @@ test "math.isPositiveInf" {...@@ -120,7 +120,7 @@ test "math.isPositiveInf" {
120}120}
121121
122test "math.isNegativeInf" {122test "math.isNegativeInf" {
123 if (std.Target.current.isWindows()) {123 if (std.Target.current.os.tag == .windows) {
124 // TODO https://github.com/ziglang/zig/issues/508124 // TODO https://github.com/ziglang/zig/issues/508
125 return error.SkipZigTest;125 return error.SkipZigTest;
126 }126 }
lib/std/math/isnan.zig+1-1
...@@ -16,7 +16,7 @@ pub fn isSignalNan(x: var) bool {...@@ -16,7 +16,7 @@ pub fn isSignalNan(x: var) bool {
16}16}
1717
18test "math.isNan" {18test "math.isNan" {
19 if (std.Target.current.isWindows()) {19 if (std.Target.current.os.tag == .windows) {
20 // TODO https://github.com/ziglang/zig/issues/50820 // TODO https://github.com/ziglang/zig/issues/508
21 return error.SkipZigTest;21 return error.SkipZigTest;
22 }22 }
lib/std/math/pow.zig+1-1
...@@ -32,7 +32,7 @@ const expect = std.testing.expect;...@@ -32,7 +32,7 @@ const expect = std.testing.expect;
32/// - pow(-inf, y) = pow(-0, -y)32/// - pow(-inf, y) = pow(-0, -y)
33/// - pow(x, y) = nan for finite x < 0 and finite non-integer y33/// - pow(x, y) = nan for finite x < 0 and finite non-integer y
34pub fn pow(comptime T: type, x: T, y: T) T {34pub fn pow(comptime T: type, x: T, y: T) T {
35 if (@typeInfo(T) == builtin.TypeId.Int) {35 if (@typeInfo(T) == .Int) {
36 return math.powi(T, x, y) catch unreachable;36 return math.powi(T, x, y) catch unreachable;
37 }37 }
3838
lib/std/math/powi.zig+1-1
...@@ -25,7 +25,7 @@ pub fn powi(comptime T: type, x: T, y: T) (error{...@@ -25,7 +25,7 @@ pub fn powi(comptime T: type, x: T, y: T) (error{
25}!T) {25}!T) {
26 const info = @typeInfo(T);26 const info = @typeInfo(T);
2727
28 comptime assert(@typeInfo(T) == builtin.TypeId.Int);28 comptime assert(@typeInfo(T) == .Int);
2929
30 // powi(x, +-0) = 1 for any x30 // powi(x, +-0) = 1 for any x
31 if (y == 0 or y == -0) {31 if (y == 0 or y == -0) {
lib/std/mem.zig+174-60
...@@ -333,8 +333,20 @@ pub fn zeroes(comptime T: type) T {...@@ -333,8 +333,20 @@ pub fn zeroes(comptime T: type) T {
333 }333 }
334 return array;334 return array;
335 },335 },
336 .Vector, .ErrorUnion, .ErrorSet, .Union, .Fn, .BoundFn, .Type, .NoReturn, .Undefined, .Opaque, .Frame, .AnyFrame, => {336 .Vector,
337 @compileError("Can't set a "++ @typeName(T) ++" to zero.");337 .ErrorUnion,
338 .ErrorSet,
339 .Union,
340 .Fn,
341 .BoundFn,
342 .Type,
343 .NoReturn,
344 .Undefined,
345 .Opaque,
346 .Frame,
347 .AnyFrame,
348 => {
349 @compileError("Can't set a " ++ @typeName(T) ++ " to zero.");
338 },350 },
339 }351 }
340}352}
...@@ -470,18 +482,115 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {...@@ -470,18 +482,115 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
470 return true;482 return true;
471}483}
472484
473pub fn len(comptime T: type, ptr: [*:0]const T) usize {485/// Deprecated. Use `span`.
474 var count: usize = 0;
475 while (ptr[count] != 0) : (count += 1) {}
476 return count;
477}
478
479pub fn toSliceConst(comptime T: type, ptr: [*:0]const T) [:0]const T {486pub fn toSliceConst(comptime T: type, ptr: [*:0]const T) [:0]const T {
480 return ptr[0..len(T, ptr) :0];487 return ptr[0..len(ptr) :0];
481}488}
482489
490/// Deprecated. Use `span`.
483pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {491pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {
484 return ptr[0..len(T, ptr) :0];492 return ptr[0..len(ptr) :0];
493}
494
495/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and
496/// returns a slice. If there is a sentinel on the input type, there will be a
497/// sentinel on the output type. The constness of the output type matches
498/// the constness of the input type. `[*c]` pointers are assumed to be 0-terminated,
499/// and assumed to not allow null.
500pub fn Span(comptime T: type) type {
501 var ptr_info = @typeInfo(T).Pointer;
502 switch (ptr_info.size) {
503 .One => switch (@typeInfo(ptr_info.child)) {
504 .Array => |info| {
505 ptr_info.child = info.child;
506 ptr_info.sentinel = info.sentinel;
507 },
508 else => @compileError("invalid type given to std.mem.Span"),
509 },
510 .C => {
511 ptr_info.sentinel = 0;
512 ptr_info.is_allowzero = false;
513 },
514 .Many, .Slice => {},
515 }
516 ptr_info.size = .Slice;
517 return @Type(std.builtin.TypeInfo{ .Pointer = ptr_info });
518}
519
520test "Span" {
521 testing.expect(Span(*[5]u16) == []u16);
522 testing.expect(Span(*const [5]u16) == []const u16);
523 testing.expect(Span([]u16) == []u16);
524 testing.expect(Span([]const u8) == []const u8);
525 testing.expect(Span([:1]u16) == [:1]u16);
526 testing.expect(Span([:1]const u8) == [:1]const u8);
527 testing.expect(Span([*:1]u16) == [:1]u16);
528 testing.expect(Span([*:1]const u8) == [:1]const u8);
529 testing.expect(Span([*c]u16) == [:0]u16);
530 testing.expect(Span([*c]const u8) == [:0]const u8);
531}
532
533/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and
534/// returns a slice. If there is a sentinel on the input type, there will be a
535/// sentinel on the output type. The constness of the output type matches
536/// the constness of the input type.
537pub fn span(ptr: var) Span(@TypeOf(ptr)) {
538 const Result = Span(@TypeOf(ptr));
539 const l = len(ptr);
540 if (@typeInfo(Result).Pointer.sentinel) |s| {
541 return ptr[0..l :s];
542 } else {
543 return ptr[0..l];
544 }
545}
546
547test "span" {
548 var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
549 const ptr = array[0..2 :3].ptr;
550 testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));
551 testing.expect(eql(u16, span(&array), &[_]u16{ 1, 2, 3, 4, 5 }));
552}
553
554/// Takes a pointer to an array, an array, a sentinel-terminated pointer,
555/// or a slice, and returns the length.
556pub fn len(ptr: var) usize {
557 return switch (@typeInfo(@TypeOf(ptr))) {
558 .Array => |info| info.len,
559 .Pointer => |info| switch (info.size) {
560 .One => switch (@typeInfo(info.child)) {
561 .Array => |x| x.len,
562 else => @compileError("invalid type given to std.mem.length"),
563 },
564 .Many => if (info.sentinel) |sentinel|
565 indexOfSentinel(info.child, sentinel, ptr)
566 else
567 @compileError("length of pointer with no sentinel"),
568 .C => indexOfSentinel(info.child, 0, ptr),
569 .Slice => ptr.len,
570 },
571 else => @compileError("invalid type given to std.mem.length"),
572 };
573}
574
575test "len" {
576 testing.expect(len("aoeu") == 4);
577
578 {
579 var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
580 testing.expect(len(&array) == 5);
581 testing.expect(len(array[0..3]) == 3);
582 array[2] = 0;
583 const ptr = array[0..2 :0].ptr;
584 testing.expect(len(ptr) == 2);
585 }
586}
587
588pub fn indexOfSentinel(comptime Elem: type, comptime sentinel: Elem, ptr: [*:sentinel]const Elem) usize {
589 var i: usize = 0;
590 while (ptr[i] != sentinel) {
591 i += 1;
592 }
593 return i;
485}594}
486595
487/// Returns true if all elements in a slice are equal to the scalar value provided596/// Returns true if all elements in a slice are equal to the scalar value provided
...@@ -637,12 +746,12 @@ test "mem.indexOf" {...@@ -637,12 +746,12 @@ test "mem.indexOf" {
637pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: builtin.Endian) ReturnType {746pub fn readVarInt(comptime ReturnType: type, bytes: []const u8, endian: builtin.Endian) ReturnType {
638 var result: ReturnType = 0;747 var result: ReturnType = 0;
639 switch (endian) {748 switch (endian) {
640 builtin.Endian.Big => {749 .Big => {
641 for (bytes) |b| {750 for (bytes) |b| {
642 result = (result << 8) | b;751 result = (result << 8) | b;
643 }752 }
644 },753 },
645 builtin.Endian.Little => {754 .Little => {
646 const ShiftType = math.Log2Int(ReturnType);755 const ShiftType = math.Log2Int(ReturnType);
647 for (bytes) |b, index| {756 for (bytes) |b, index| {
648 result = result | (@as(ReturnType, b) << @intCast(ShiftType, index * 8));757 result = result | (@as(ReturnType, b) << @intCast(ShiftType, index * 8));
...@@ -670,13 +779,13 @@ pub fn readIntForeign(comptime T: type, bytes: *const [@divExact(T.bit_count, 8)...@@ -670,13 +779,13 @@ pub fn readIntForeign(comptime T: type, bytes: *const [@divExact(T.bit_count, 8)
670}779}
671780
672pub const readIntLittle = switch (builtin.endian) {781pub const readIntLittle = switch (builtin.endian) {
673 builtin.Endian.Little => readIntNative,782 .Little => readIntNative,
674 builtin.Endian.Big => readIntForeign,783 .Big => readIntForeign,
675};784};
676785
677pub const readIntBig = switch (builtin.endian) {786pub const readIntBig = switch (builtin.endian) {
678 builtin.Endian.Little => readIntForeign,787 .Little => readIntForeign,
679 builtin.Endian.Big => readIntNative,788 .Big => readIntNative,
680};789};
681790
682/// Asserts that bytes.len >= T.bit_count / 8. Reads the integer starting from index 0791/// Asserts that bytes.len >= T.bit_count / 8. Reads the integer starting from index 0
...@@ -700,13 +809,13 @@ pub fn readIntSliceForeign(comptime T: type, bytes: []const u8) T {...@@ -700,13 +809,13 @@ pub fn readIntSliceForeign(comptime T: type, bytes: []const u8) T {
700}809}
701810
702pub const readIntSliceLittle = switch (builtin.endian) {811pub const readIntSliceLittle = switch (builtin.endian) {
703 builtin.Endian.Little => readIntSliceNative,812 .Little => readIntSliceNative,
704 builtin.Endian.Big => readIntSliceForeign,813 .Big => readIntSliceForeign,
705};814};
706815
707pub const readIntSliceBig = switch (builtin.endian) {816pub const readIntSliceBig = switch (builtin.endian) {
708 builtin.Endian.Little => readIntSliceForeign,817 .Little => readIntSliceForeign,
709 builtin.Endian.Big => readIntSliceNative,818 .Big => readIntSliceNative,
710};819};
711820
712/// Reads an integer from memory with bit count specified by T.821/// Reads an integer from memory with bit count specified by T.
...@@ -783,13 +892,13 @@ pub fn writeIntForeign(comptime T: type, buf: *[@divExact(T.bit_count, 8)]u8, va...@@ -783,13 +892,13 @@ pub fn writeIntForeign(comptime T: type, buf: *[@divExact(T.bit_count, 8)]u8, va
783}892}
784893
785pub const writeIntLittle = switch (builtin.endian) {894pub const writeIntLittle = switch (builtin.endian) {
786 builtin.Endian.Little => writeIntNative,895 .Little => writeIntNative,
787 builtin.Endian.Big => writeIntForeign,896 .Big => writeIntForeign,
788};897};
789898
790pub const writeIntBig = switch (builtin.endian) {899pub const writeIntBig = switch (builtin.endian) {
791 builtin.Endian.Little => writeIntForeign,900 .Little => writeIntForeign,
792 builtin.Endian.Big => writeIntNative,901 .Big => writeIntNative,
793};902};
794903
795/// Writes an integer to memory, storing it in twos-complement.904/// Writes an integer to memory, storing it in twos-complement.
...@@ -841,13 +950,13 @@ pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {...@@ -841,13 +950,13 @@ pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {
841}950}
842951
843pub const writeIntSliceNative = switch (builtin.endian) {952pub const writeIntSliceNative = switch (builtin.endian) {
844 builtin.Endian.Little => writeIntSliceLittle,953 .Little => writeIntSliceLittle,
845 builtin.Endian.Big => writeIntSliceBig,954 .Big => writeIntSliceBig,
846};955};
847956
848pub const writeIntSliceForeign = switch (builtin.endian) {957pub const writeIntSliceForeign = switch (builtin.endian) {
849 builtin.Endian.Little => writeIntSliceBig,958 .Little => writeIntSliceBig,
850 builtin.Endian.Big => writeIntSliceLittle,959 .Big => writeIntSliceLittle,
851};960};
852961
853/// Writes a twos-complement integer to memory, with the specified endianness.962/// Writes a twos-complement integer to memory, with the specified endianness.
...@@ -858,10 +967,10 @@ pub const writeIntSliceForeign = switch (builtin.endian) {...@@ -858,10 +967,10 @@ pub const writeIntSliceForeign = switch (builtin.endian) {
858/// use writeInt instead.967/// use writeInt instead.
859pub fn writeIntSlice(comptime T: type, buffer: []u8, value: T, endian: builtin.Endian) void {968pub fn writeIntSlice(comptime T: type, buffer: []u8, value: T, endian: builtin.Endian) void {
860 comptime assert(T.bit_count % 8 == 0);969 comptime assert(T.bit_count % 8 == 0);
861 switch (endian) {970 return switch (endian) {
862 builtin.Endian.Little => return writeIntSliceLittle(T, buffer, value),971 .Little => writeIntSliceLittle(T, buffer, value),
863 builtin.Endian.Big => return writeIntSliceBig(T, buffer, value),972 .Big => writeIntSliceBig(T, buffer, value),
864 }973 };
865}974}
866975
867test "writeIntBig and writeIntLittle" {976test "writeIntBig and writeIntLittle" {
...@@ -1397,54 +1506,54 @@ test "rotate" {...@@ -1397,54 +1506,54 @@ test "rotate" {
1397/// Converts a little-endian integer to host endianness.1506/// Converts a little-endian integer to host endianness.
1398pub fn littleToNative(comptime T: type, x: T) T {1507pub fn littleToNative(comptime T: type, x: T) T {
1399 return switch (builtin.endian) {1508 return switch (builtin.endian) {
1400 builtin.Endian.Little => x,1509 .Little => x,
1401 builtin.Endian.Big => @byteSwap(T, x),1510 .Big => @byteSwap(T, x),
1402 };1511 };
1403}1512}
14041513
1405/// Converts a big-endian integer to host endianness.1514/// Converts a big-endian integer to host endianness.
1406pub fn bigToNative(comptime T: type, x: T) T {1515pub fn bigToNative(comptime T: type, x: T) T {
1407 return switch (builtin.endian) {1516 return switch (builtin.endian) {
1408 builtin.Endian.Little => @byteSwap(T, x),1517 .Little => @byteSwap(T, x),
1409 builtin.Endian.Big => x,1518 .Big => x,
1410 };1519 };
1411}1520}
14121521
1413/// Converts an integer from specified endianness to host endianness.1522/// Converts an integer from specified endianness to host endianness.
1414pub fn toNative(comptime T: type, x: T, endianness_of_x: builtin.Endian) T {1523pub fn toNative(comptime T: type, x: T, endianness_of_x: builtin.Endian) T {
1415 return switch (endianness_of_x) {1524 return switch (endianness_of_x) {
1416 builtin.Endian.Little => littleToNative(T, x),1525 .Little => littleToNative(T, x),
1417 builtin.Endian.Big => bigToNative(T, x),1526 .Big => bigToNative(T, x),
1418 };1527 };
1419}1528}
14201529
1421/// Converts an integer which has host endianness to the desired endianness.1530/// Converts an integer which has host endianness to the desired endianness.
1422pub fn nativeTo(comptime T: type, x: T, desired_endianness: builtin.Endian) T {1531pub fn nativeTo(comptime T: type, x: T, desired_endianness: builtin.Endian) T {
1423 return switch (desired_endianness) {1532 return switch (desired_endianness) {
1424 builtin.Endian.Little => nativeToLittle(T, x),1533 .Little => nativeToLittle(T, x),
1425 builtin.Endian.Big => nativeToBig(T, x),1534 .Big => nativeToBig(T, x),
1426 };1535 };
1427}1536}
14281537
1429/// Converts an integer which has host endianness to little endian.1538/// Converts an integer which has host endianness to little endian.
1430pub fn nativeToLittle(comptime T: type, x: T) T {1539pub fn nativeToLittle(comptime T: type, x: T) T {
1431 return switch (builtin.endian) {1540 return switch (builtin.endian) {
1432 builtin.Endian.Little => x,1541 .Little => x,
1433 builtin.Endian.Big => @byteSwap(T, x),1542 .Big => @byteSwap(T, x),
1434 };1543 };
1435}1544}
14361545
1437/// Converts an integer which has host endianness to big endian.1546/// Converts an integer which has host endianness to big endian.
1438pub fn nativeToBig(comptime T: type, x: T) T {1547pub fn nativeToBig(comptime T: type, x: T) T {
1439 return switch (builtin.endian) {1548 return switch (builtin.endian) {
1440 builtin.Endian.Little => @byteSwap(T, x),1549 .Little => @byteSwap(T, x),
1441 builtin.Endian.Big => x,1550 .Big => x,
1442 };1551 };
1443}1552}
14441553
1445fn AsBytesReturnType(comptime P: type) type {1554fn AsBytesReturnType(comptime P: type) type {
1446 if (comptime !trait.isSingleItemPtr(P))1555 if (comptime !trait.isSingleItemPtr(P))
1447 @compileError("expected single item " ++ "pointer, passed " ++ @typeName(P));1556 @compileError("expected single item pointer, passed " ++ @typeName(P));
14481557
1449 const size = @as(usize, @sizeOf(meta.Child(P)));1558 const size = @as(usize, @sizeOf(meta.Child(P)));
1450 const alignment = comptime meta.alignment(P);1559 const alignment = comptime meta.alignment(P);
...@@ -1469,8 +1578,8 @@ pub fn asBytes(ptr: var) AsBytesReturnType(@TypeOf(ptr)) {...@@ -1469,8 +1578,8 @@ pub fn asBytes(ptr: var) AsBytesReturnType(@TypeOf(ptr)) {
1469test "asBytes" {1578test "asBytes" {
1470 const deadbeef = @as(u32, 0xDEADBEEF);1579 const deadbeef = @as(u32, 0xDEADBEEF);
1471 const deadbeef_bytes = switch (builtin.endian) {1580 const deadbeef_bytes = switch (builtin.endian) {
1472 builtin.Endian.Big => "\xDE\xAD\xBE\xEF",1581 .Big => "\xDE\xAD\xBE\xEF",
1473 builtin.Endian.Little => "\xEF\xBE\xAD\xDE",1582 .Little => "\xEF\xBE\xAD\xDE",
1474 };1583 };
14751584
1476 testing.expect(eql(u8, asBytes(&deadbeef), deadbeef_bytes));1585 testing.expect(eql(u8, asBytes(&deadbeef), deadbeef_bytes));
...@@ -1508,21 +1617,21 @@ pub fn toBytes(value: var) [@sizeOf(@TypeOf(value))]u8 {...@@ -1508,21 +1617,21 @@ pub fn toBytes(value: var) [@sizeOf(@TypeOf(value))]u8 {
1508test "toBytes" {1617test "toBytes" {
1509 var my_bytes = toBytes(@as(u32, 0x12345678));1618 var my_bytes = toBytes(@as(u32, 0x12345678));
1510 switch (builtin.endian) {1619 switch (builtin.endian) {
1511 builtin.Endian.Big => testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")),1620 .Big => testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")),
1512 builtin.Endian.Little => testing.expect(eql(u8, &my_bytes, "\x78\x56\x34\x12")),1621 .Little => testing.expect(eql(u8, &my_bytes, "\x78\x56\x34\x12")),
1513 }1622 }
15141623
1515 my_bytes[0] = '\x99';1624 my_bytes[0] = '\x99';
1516 switch (builtin.endian) {1625 switch (builtin.endian) {
1517 builtin.Endian.Big => testing.expect(eql(u8, &my_bytes, "\x99\x34\x56\x78")),1626 .Big => testing.expect(eql(u8, &my_bytes, "\x99\x34\x56\x78")),
1518 builtin.Endian.Little => testing.expect(eql(u8, &my_bytes, "\x99\x56\x34\x12")),1627 .Little => testing.expect(eql(u8, &my_bytes, "\x99\x56\x34\x12")),
1519 }1628 }
1520}1629}
15211630
1522fn BytesAsValueReturnType(comptime T: type, comptime B: type) type {1631fn BytesAsValueReturnType(comptime T: type, comptime B: type) type {
1523 const size = @as(usize, @sizeOf(T));1632 const size = @as(usize, @sizeOf(T));
15241633
1525 if (comptime !trait.is(builtin.TypeId.Pointer)(B) or1634 if (comptime !trait.is(.Pointer)(B) or
1526 (meta.Child(B) != [size]u8 and meta.Child(B) != [size:0]u8))1635 (meta.Child(B) != [size]u8 and meta.Child(B) != [size:0]u8))
1527 {1636 {
1528 @compileError("expected *[N]u8 " ++ ", passed " ++ @typeName(B));1637 @compileError("expected *[N]u8 " ++ ", passed " ++ @typeName(B));
...@@ -1542,15 +1651,15 @@ pub fn bytesAsValue(comptime T: type, bytes: var) BytesAsValueReturnType(T, @Typ...@@ -1542,15 +1651,15 @@ pub fn bytesAsValue(comptime T: type, bytes: var) BytesAsValueReturnType(T, @Typ
1542test "bytesAsValue" {1651test "bytesAsValue" {
1543 const deadbeef = @as(u32, 0xDEADBEEF);1652 const deadbeef = @as(u32, 0xDEADBEEF);
1544 const deadbeef_bytes = switch (builtin.endian) {1653 const deadbeef_bytes = switch (builtin.endian) {
1545 builtin.Endian.Big => "\xDE\xAD\xBE\xEF",1654 .Big => "\xDE\xAD\xBE\xEF",
1546 builtin.Endian.Little => "\xEF\xBE\xAD\xDE",1655 .Little => "\xEF\xBE\xAD\xDE",
1547 };1656 };
15481657
1549 testing.expect(deadbeef == bytesAsValue(u32, deadbeef_bytes).*);1658 testing.expect(deadbeef == bytesAsValue(u32, deadbeef_bytes).*);
15501659
1551 var codeface_bytes: [4]u8 = switch (builtin.endian) {1660 var codeface_bytes: [4]u8 = switch (builtin.endian) {
1552 builtin.Endian.Big => "\xC0\xDE\xFA\xCE",1661 .Big => "\xC0\xDE\xFA\xCE",
1553 builtin.Endian.Little => "\xCE\xFA\xDE\xC0",1662 .Little => "\xCE\xFA\xDE\xC0",
1554 }.*;1663 }.*;
1555 var codeface = bytesAsValue(u32, &codeface_bytes);1664 var codeface = bytesAsValue(u32, &codeface_bytes);
1556 testing.expect(codeface.* == 0xC0DEFACE);1665 testing.expect(codeface.* == 0xC0DEFACE);
...@@ -1583,8 +1692,8 @@ pub fn bytesToValue(comptime T: type, bytes: var) T {...@@ -1583,8 +1692,8 @@ pub fn bytesToValue(comptime T: type, bytes: var) T {
1583}1692}
1584test "bytesToValue" {1693test "bytesToValue" {
1585 const deadbeef_bytes = switch (builtin.endian) {1694 const deadbeef_bytes = switch (builtin.endian) {
1586 builtin.Endian.Big => "\xDE\xAD\xBE\xEF",1695 .Big => "\xDE\xAD\xBE\xEF",
1587 builtin.Endian.Little => "\xEF\xBE\xAD\xDE",1696 .Little => "\xEF\xBE\xAD\xDE",
1588 };1697 };
15891698
1590 const deadbeef = bytesToValue(u32, deadbeef_bytes);1699 const deadbeef = bytesToValue(u32, deadbeef_bytes);
...@@ -1753,8 +1862,13 @@ fn SubArrayPtrReturnType(comptime T: type, comptime length: usize) type {...@@ -1753,8 +1862,13 @@ fn SubArrayPtrReturnType(comptime T: type, comptime length: usize) type {
1753 return *[length]meta.Child(meta.Child(T));1862 return *[length]meta.Child(meta.Child(T));
1754}1863}
17551864
1756///Given a pointer to an array, returns a pointer to a portion of that array, preserving constness.1865/// Given a pointer to an array, returns a pointer to a portion of that array, preserving constness.
1757pub fn subArrayPtr(ptr: var, comptime start: usize, comptime length: usize) SubArrayPtrReturnType(@TypeOf(ptr), length) {1866/// TODO this will be obsoleted by https://github.com/ziglang/zig/issues/863
1867pub fn subArrayPtr(
1868 ptr: var,
1869 comptime start: usize,
1870 comptime length: usize,
1871) SubArrayPtrReturnType(@TypeOf(ptr), length) {
1758 assert(start + length <= ptr.*.len);1872 assert(start + length <= ptr.*.len);
17591873
1760 const ReturnType = SubArrayPtrReturnType(@TypeOf(ptr), length);1874 const ReturnType = SubArrayPtrReturnType(@TypeOf(ptr), length);
lib/std/meta.zig+26
...@@ -115,6 +115,32 @@ test "std.meta.Child" {...@@ -115,6 +115,32 @@ test "std.meta.Child" {
115 testing.expect(Child(?u8) == u8);115 testing.expect(Child(?u8) == u8);
116}116}
117117
118/// Given a type with a sentinel e.g. `[:0]u8`, returns the sentinel
119pub fn Sentinel(comptime T: type) Child(T) {
120 // comptime asserts that ptr has a sentinel
121 switch (@typeInfo(T)) {
122 .Array => |arrayInfo| {
123 return comptime arrayInfo.sentinel.?;
124 },
125 .Pointer => |ptrInfo| {
126 switch (ptrInfo.size) {
127 .Many, .Slice => {
128 return comptime ptrInfo.sentinel.?;
129 },
130 else => {},
131 }
132 },
133 else => {},
134 }
135 @compileError("not a sentinel type, found '" ++ @typeName(T) ++ "'");
136}
137
138test "std.meta.Sentinel" {
139 testing.expectEqual(@as(u8, 0), Sentinel([:0]u8));
140 testing.expectEqual(@as(u8, 0), Sentinel([*:0]u8));
141 testing.expectEqual(@as(u8, 0), Sentinel([5:0]u8));
142}
143
118pub fn containerLayout(comptime T: type) TypeInfo.ContainerLayout {144pub fn containerLayout(comptime T: type) TypeInfo.ContainerLayout {
119 return switch (@typeInfo(T)) {145 return switch (@typeInfo(T)) {
120 .Struct => |info| info.layout,146 .Struct => |info| info.layout,
lib/std/mutex.zig+2-2
...@@ -73,7 +73,7 @@ pub const Mutex = if (builtin.single_threaded)...@@ -73,7 +73,7 @@ pub const Mutex = if (builtin.single_threaded)
73 return self.tryAcquire() orelse @panic("deadlock detected");73 return self.tryAcquire() orelse @panic("deadlock detected");
74 }74 }
75 }75 }
76else if (builtin.os == .windows)76else if (builtin.os.tag == .windows)
77// https://locklessinc.com/articles/keyed_events/77// https://locklessinc.com/articles/keyed_events/
78 extern union {78 extern union {
79 locked: u8,79 locked: u8,
...@@ -161,7 +161,7 @@ else if (builtin.os == .windows)...@@ -161,7 +161,7 @@ else if (builtin.os == .windows)
161 }161 }
162 };162 };
163 }163 }
164else if (builtin.link_libc or builtin.os == .linux)164else if (builtin.link_libc or builtin.os.tag == .linux)
165// stack-based version of https://github.com/Amanieu/parking_lot/blob/master/core/src/word_lock.rs165// stack-based version of https://github.com/Amanieu/parking_lot/blob/master/core/src/word_lock.rs
166 struct {166 struct {
167 state: usize,167 state: usize,
lib/std/net.zig+2-2
...@@ -352,7 +352,7 @@ pub const Address = extern union {...@@ -352,7 +352,7 @@ pub const Address = extern union {
352 unreachable;352 unreachable;
353 }353 }
354354
355 const path_len = std.mem.len(u8, @ptrCast([*:0]const u8, &self.un.path));355 const path_len = std.mem.len(@ptrCast([*:0]const u8, &self.un.path));
356 return @intCast(os.socklen_t, @sizeOf(os.sockaddr_un) - self.un.path.len + path_len);356 return @intCast(os.socklen_t, @sizeOf(os.sockaddr_un) - self.un.path.len + path_len);
357 },357 },
358 else => unreachable,358 else => unreachable,
...@@ -501,7 +501,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*...@@ -501,7 +501,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
501501
502 return result;502 return result;
503 }503 }
504 if (builtin.os == .linux) {504 if (builtin.os.tag == .linux) {
505 const flags = std.c.AI_NUMERICSERV;505 const flags = std.c.AI_NUMERICSERV;
506 const family = os.AF_UNSPEC;506 const family = os.AF_UNSPEC;
507 var lookup_addrs = std.ArrayList(LookupAddr).init(allocator);507 var lookup_addrs = std.ArrayList(LookupAddr).init(allocator);
lib/std/net/test.zig+2-2
...@@ -63,7 +63,7 @@ test "parse and render IPv4 addresses" {...@@ -63,7 +63,7 @@ test "parse and render IPv4 addresses" {
63}63}
6464
65test "resolve DNS" {65test "resolve DNS" {
66 if (std.builtin.os == .windows) {66 if (std.builtin.os.tag == .windows) {
67 // DNS resolution not implemented on Windows yet.67 // DNS resolution not implemented on Windows yet.
68 return error.SkipZigTest;68 return error.SkipZigTest;
69 }69 }
...@@ -81,7 +81,7 @@ test "resolve DNS" {...@@ -81,7 +81,7 @@ test "resolve DNS" {
81test "listen on a port, send bytes, receive bytes" {81test "listen on a port, send bytes, receive bytes" {
82 if (!std.io.is_async) return error.SkipZigTest;82 if (!std.io.is_async) return error.SkipZigTest;
8383
84 if (std.builtin.os != .linux) {84 if (std.builtin.os.tag != .linux) {
85 // TODO build abstractions for other operating systems85 // TODO build abstractions for other operating systems
86 return error.SkipZigTest;86 return error.SkipZigTest;
87 }87 }
lib/std/os.zig+87-82
...@@ -56,7 +56,7 @@ pub const system = if (@hasDecl(root, "os") and root.os != @This())...@@ -56,7 +56,7 @@ pub const system = if (@hasDecl(root, "os") and root.os != @This())
56 root.os.system56 root.os.system
57else if (builtin.link_libc)57else if (builtin.link_libc)
58 std.c58 std.c
59else switch (builtin.os) {59else switch (builtin.os.tag) {
60 .macosx, .ios, .watchos, .tvos => darwin,60 .macosx, .ios, .watchos, .tvos => darwin,
61 .freebsd => freebsd,61 .freebsd => freebsd,
62 .linux => linux,62 .linux => linux,
...@@ -93,10 +93,10 @@ pub const errno = system.getErrno;...@@ -93,10 +93,10 @@ pub const errno = system.getErrno;
93/// must call `fsync` before `close`.93/// must call `fsync` before `close`.
94/// Note: The Zig standard library does not support POSIX thread cancellation.94/// Note: The Zig standard library does not support POSIX thread cancellation.
95pub fn close(fd: fd_t) void {95pub fn close(fd: fd_t) void {
96 if (builtin.os == .windows) {96 if (builtin.os.tag == .windows) {
97 return windows.CloseHandle(fd);97 return windows.CloseHandle(fd);
98 }98 }
99 if (builtin.os == .wasi) {99 if (builtin.os.tag == .wasi) {
100 _ = wasi.fd_close(fd);100 _ = wasi.fd_close(fd);
101 }101 }
102 if (comptime std.Target.current.isDarwin()) {102 if (comptime std.Target.current.isDarwin()) {
...@@ -121,12 +121,12 @@ pub const GetRandomError = OpenError;...@@ -121,12 +121,12 @@ pub const GetRandomError = OpenError;
121/// appropriate OS-specific library call. Otherwise it uses the zig standard121/// appropriate OS-specific library call. Otherwise it uses the zig standard
122/// library implementation.122/// library implementation.
123pub fn getrandom(buffer: []u8) GetRandomError!void {123pub fn getrandom(buffer: []u8) GetRandomError!void {
124 if (builtin.os == .windows) {124 if (builtin.os.tag == .windows) {
125 return windows.RtlGenRandom(buffer);125 return windows.RtlGenRandom(buffer);
126 }126 }
127 if (builtin.os == .linux or builtin.os == .freebsd) {127 if (builtin.os.tag == .linux or builtin.os.tag == .freebsd) {
128 var buf = buffer;128 var buf = buffer;
129 const use_c = builtin.os != .linux or129 const use_c = builtin.os.tag != .linux or
130 std.c.versionCheck(builtin.Version{ .major = 2, .minor = 25, .patch = 0 }).ok;130 std.c.versionCheck(builtin.Version{ .major = 2, .minor = 25, .patch = 0 }).ok;
131131
132 while (buf.len != 0) {132 while (buf.len != 0) {
...@@ -153,7 +153,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {...@@ -153,7 +153,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {
153 }153 }
154 return;154 return;
155 }155 }
156 if (builtin.os == .wasi) {156 if (builtin.os.tag == .wasi) {
157 switch (wasi.random_get(buffer.ptr, buffer.len)) {157 switch (wasi.random_get(buffer.ptr, buffer.len)) {
158 0 => return,158 0 => return,
159 else => |err| return unexpectedErrno(err),159 else => |err| return unexpectedErrno(err),
...@@ -188,13 +188,13 @@ pub fn abort() noreturn {...@@ -188,13 +188,13 @@ pub fn abort() noreturn {
188 // MSVCRT abort() sometimes opens a popup window which is undesirable, so188 // MSVCRT abort() sometimes opens a popup window which is undesirable, so
189 // even when linking libc on Windows we use our own abort implementation.189 // even when linking libc on Windows we use our own abort implementation.
190 // See https://github.com/ziglang/zig/issues/2071 for more details.190 // See https://github.com/ziglang/zig/issues/2071 for more details.
191 if (builtin.os == .windows) {191 if (builtin.os.tag == .windows) {
192 if (builtin.mode == .Debug) {192 if (builtin.mode == .Debug) {
193 @breakpoint();193 @breakpoint();
194 }194 }
195 windows.kernel32.ExitProcess(3);195 windows.kernel32.ExitProcess(3);
196 }196 }
197 if (!builtin.link_libc and builtin.os == .linux) {197 if (!builtin.link_libc and builtin.os.tag == .linux) {
198 raise(SIGABRT) catch {};198 raise(SIGABRT) catch {};
199199
200 // TODO the rest of the implementation of abort() from musl libc here200 // TODO the rest of the implementation of abort() from musl libc here
...@@ -202,10 +202,10 @@ pub fn abort() noreturn {...@@ -202,10 +202,10 @@ pub fn abort() noreturn {
202 raise(SIGKILL) catch {};202 raise(SIGKILL) catch {};
203 exit(127);203 exit(127);
204 }204 }
205 if (builtin.os == .uefi) {205 if (builtin.os.tag == .uefi) {
206 exit(0); // TODO choose appropriate exit code206 exit(0); // TODO choose appropriate exit code
207 }207 }
208 if (builtin.os == .wasi) {208 if (builtin.os.tag == .wasi) {
209 @breakpoint();209 @breakpoint();
210 exit(1);210 exit(1);
211 }211 }
...@@ -223,7 +223,7 @@ pub fn raise(sig: u8) RaiseError!void {...@@ -223,7 +223,7 @@ pub fn raise(sig: u8) RaiseError!void {
223 }223 }
224 }224 }
225225
226 if (builtin.os == .linux) {226 if (builtin.os.tag == .linux) {
227 var set: linux.sigset_t = undefined;227 var set: linux.sigset_t = undefined;
228 // block application signals228 // block application signals
229 _ = linux.sigprocmask(SIG_BLOCK, &linux.app_mask, &set);229 _ = linux.sigprocmask(SIG_BLOCK, &linux.app_mask, &set);
...@@ -260,16 +260,16 @@ pub fn exit(status: u8) noreturn {...@@ -260,16 +260,16 @@ pub fn exit(status: u8) noreturn {
260 if (builtin.link_libc) {260 if (builtin.link_libc) {
261 system.exit(status);261 system.exit(status);
262 }262 }
263 if (builtin.os == .windows) {263 if (builtin.os.tag == .windows) {
264 windows.kernel32.ExitProcess(status);264 windows.kernel32.ExitProcess(status);
265 }265 }
266 if (builtin.os == .wasi) {266 if (builtin.os.tag == .wasi) {
267 wasi.proc_exit(status);267 wasi.proc_exit(status);
268 }268 }
269 if (builtin.os == .linux and !builtin.single_threaded) {269 if (builtin.os.tag == .linux and !builtin.single_threaded) {
270 linux.exit_group(status);270 linux.exit_group(status);
271 }271 }
272 if (builtin.os == .uefi) {272 if (builtin.os.tag == .uefi) {
273 // exit() is only avaliable if exitBootServices() has not been called yet.273 // exit() is only avaliable if exitBootServices() has not been called yet.
274 // This call to exit should not fail, so we don't care about its return value.274 // This call to exit should not fail, so we don't care about its return value.
275 if (uefi.system_table.boot_services) |bs| {275 if (uefi.system_table.boot_services) |bs| {
...@@ -299,11 +299,11 @@ pub const ReadError = error{...@@ -299,11 +299,11 @@ pub const ReadError = error{
299/// If the application has a global event loop enabled, EAGAIN is handled299/// If the application has a global event loop enabled, EAGAIN is handled
300/// via the event loop. Otherwise EAGAIN results in error.WouldBlock.300/// via the event loop. Otherwise EAGAIN results in error.WouldBlock.
301pub fn read(fd: fd_t, buf: []u8) ReadError!usize {301pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
302 if (builtin.os == .windows) {302 if (builtin.os.tag == .windows) {
303 return windows.ReadFile(fd, buf, null);303 return windows.ReadFile(fd, buf, null);
304 }304 }
305305
306 if (builtin.os == .wasi and !builtin.link_libc) {306 if (builtin.os.tag == .wasi and !builtin.link_libc) {
307 const iovs = [1]iovec{iovec{307 const iovs = [1]iovec{iovec{
308 .iov_base = buf.ptr,308 .iov_base = buf.ptr,
309 .iov_len = buf.len,309 .iov_len = buf.len,
...@@ -352,7 +352,7 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {...@@ -352,7 +352,7 @@ pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
352/// * Windows352/// * Windows
353/// On these systems, the read races with concurrent writes to the same file descriptor.353/// On these systems, the read races with concurrent writes to the same file descriptor.
354pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {354pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
355 if (builtin.os == .windows) {355 if (builtin.os.tag == .windows) {
356 // TODO batch these into parallel requests356 // TODO batch these into parallel requests
357 var off: usize = 0;357 var off: usize = 0;
358 var iov_i: usize = 0;358 var iov_i: usize = 0;
...@@ -406,7 +406,7 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {...@@ -406,7 +406,7 @@ pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
406/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are406/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
407/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.407/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
408pub fn pread(fd: fd_t, buf: []u8, offset: u64) ReadError!usize {408pub fn pread(fd: fd_t, buf: []u8, offset: u64) ReadError!usize {
409 if (builtin.os == .windows) {409 if (builtin.os.tag == .windows) {
410 return windows.ReadFile(fd, buf, offset);410 return windows.ReadFile(fd, buf, offset);
411 }411 }
412412
...@@ -493,7 +493,7 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) ReadError!usize {...@@ -493,7 +493,7 @@ pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) ReadError!usize {
493 }493 }
494 }494 }
495495
496 if (builtin.os == .windows) {496 if (builtin.os.tag == .windows) {
497 // TODO batch these into parallel requests497 // TODO batch these into parallel requests
498 var off: usize = 0;498 var off: usize = 0;
499 var iov_i: usize = 0;499 var iov_i: usize = 0;
...@@ -557,11 +557,11 @@ pub const WriteError = error{...@@ -557,11 +557,11 @@ pub const WriteError = error{
557/// If the application has a global event loop enabled, EAGAIN is handled557/// If the application has a global event loop enabled, EAGAIN is handled
558/// via the event loop. Otherwise EAGAIN results in error.WouldBlock.558/// via the event loop. Otherwise EAGAIN results in error.WouldBlock.
559pub fn write(fd: fd_t, bytes: []const u8) WriteError!void {559pub fn write(fd: fd_t, bytes: []const u8) WriteError!void {
560 if (builtin.os == .windows) {560 if (builtin.os.tag == .windows) {
561 return windows.WriteFile(fd, bytes, null);561 return windows.WriteFile(fd, bytes, null);
562 }562 }
563563
564 if (builtin.os == .wasi and !builtin.link_libc) {564 if (builtin.os.tag == .wasi and !builtin.link_libc) {
565 const ciovs = [1]iovec_const{iovec_const{565 const ciovs = [1]iovec_const{iovec_const{
566 .iov_base = bytes.ptr,566 .iov_base = bytes.ptr,
567 .iov_len = bytes.len,567 .iov_len = bytes.len,
...@@ -650,7 +650,7 @@ pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!void {...@@ -650,7 +650,7 @@ pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!void {
650/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are650/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
651/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.651/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
652pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) WriteError!void {652pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) WriteError!void {
653 if (comptime std.Target.current.isWindows()) {653 if (std.Target.current.os.tag == .windows) {
654 return windows.WriteFile(fd, bytes, offset);654 return windows.WriteFile(fd, bytes, offset);
655 }655 }
656656
...@@ -739,7 +739,7 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) WriteError!void...@@ -739,7 +739,7 @@ pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) WriteError!void
739 }739 }
740 }740 }
741741
742 if (comptime std.Target.current.isWindows()) {742 if (std.Target.current.os.tag == .windows) {
743 var off = offset;743 var off = offset;
744 for (iov) |item| {744 for (iov) |item| {
745 try pwrite(fd, item.iov_base[0..item.iov_len], off);745 try pwrite(fd, item.iov_base[0..item.iov_len], off);
...@@ -1095,7 +1095,7 @@ pub fn createNullDelimitedEnvMap(allocator: *mem.Allocator, env_map: *const std....@@ -1095,7 +1095,7 @@ pub fn createNullDelimitedEnvMap(allocator: *mem.Allocator, env_map: *const std.
10951095
1096pub fn freeNullDelimitedEnvMap(allocator: *mem.Allocator, envp_buf: []?[*:0]u8) void {1096pub fn freeNullDelimitedEnvMap(allocator: *mem.Allocator, envp_buf: []?[*:0]u8) void {
1097 for (envp_buf) |env| {1097 for (envp_buf) |env| {
1098 const env_buf = if (env) |ptr| ptr[0 .. mem.len(u8, ptr) + 1] else break;1098 const env_buf = if (env) |ptr| ptr[0 .. mem.len(ptr) + 1] else break;
1099 allocator.free(env_buf);1099 allocator.free(env_buf);
1100 }1100 }
1101 allocator.free(envp_buf);1101 allocator.free(envp_buf);
...@@ -1129,7 +1129,7 @@ pub fn getenv(key: []const u8) ?[]const u8 {...@@ -1129,7 +1129,7 @@ pub fn getenv(key: []const u8) ?[]const u8 {
1129 }1129 }
1130 return null;1130 return null;
1131 }1131 }
1132 if (builtin.os == .windows) {1132 if (builtin.os.tag == .windows) {
1133 @compileError("std.os.getenv 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.");1133 @compileError("std.os.getenv 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.");
1134 }1134 }
1135 // TODO see https://github.com/ziglang/zig/issues/45241135 // TODO see https://github.com/ziglang/zig/issues/4524
...@@ -1158,7 +1158,7 @@ pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {...@@ -1158,7 +1158,7 @@ pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
1158 const value = system.getenv(key) orelse return null;1158 const value = system.getenv(key) orelse return null;
1159 return mem.toSliceConst(u8, value);1159 return mem.toSliceConst(u8, value);
1160 }1160 }
1161 if (builtin.os == .windows) {1161 if (builtin.os.tag == .windows) {
1162 @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.");1162 @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.");
1163 }1163 }
1164 return getenv(mem.toSliceConst(u8, key));1164 return getenv(mem.toSliceConst(u8, key));
...@@ -1167,7 +1167,7 @@ pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {...@@ -1167,7 +1167,7 @@ pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
1167/// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name.1167/// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name.
1168/// See also `getenv`.1168/// See also `getenv`.
1169pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {1169pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {
1170 if (builtin.os != .windows) {1170 if (builtin.os.tag != .windows) {
1171 @compileError("std.os.getenvW is a Windows-only API");1171 @compileError("std.os.getenvW is a Windows-only API");
1172 }1172 }
1173 const key_slice = mem.toSliceConst(u16, key);1173 const key_slice = mem.toSliceConst(u16, key);
...@@ -1199,7 +1199,7 @@ pub const GetCwdError = error{...@@ -1199,7 +1199,7 @@ pub const GetCwdError = error{
11991199
1200/// The result is a slice of out_buffer, indexed from 0.1200/// The result is a slice of out_buffer, indexed from 0.
1201pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {1201pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
1202 if (builtin.os == .windows) {1202 if (builtin.os.tag == .windows) {
1203 return windows.GetCurrentDirectory(out_buffer);1203 return windows.GetCurrentDirectory(out_buffer);
1204 }1204 }
12051205
...@@ -1240,7 +1240,7 @@ pub const SymLinkError = error{...@@ -1240,7 +1240,7 @@ pub const SymLinkError = error{
1240/// If `sym_link_path` exists, it will not be overwritten.1240/// If `sym_link_path` exists, it will not be overwritten.
1241/// See also `symlinkC` and `symlinkW`.1241/// See also `symlinkC` and `symlinkW`.
1242pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!void {1242pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!void {
1243 if (builtin.os == .windows) {1243 if (builtin.os.tag == .windows) {
1244 const target_path_w = try windows.sliceToPrefixedFileW(target_path);1244 const target_path_w = try windows.sliceToPrefixedFileW(target_path);
1245 const sym_link_path_w = try windows.sliceToPrefixedFileW(sym_link_path);1245 const sym_link_path_w = try windows.sliceToPrefixedFileW(sym_link_path);
1246 return windows.CreateSymbolicLinkW(&sym_link_path_w, &target_path_w, 0);1246 return windows.CreateSymbolicLinkW(&sym_link_path_w, &target_path_w, 0);
...@@ -1254,7 +1254,7 @@ pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!...@@ -1254,7 +1254,7 @@ pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!
1254/// This is the same as `symlink` except the parameters are null-terminated pointers.1254/// This is the same as `symlink` except the parameters are null-terminated pointers.
1255/// See also `symlink`.1255/// See also `symlink`.
1256pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void {1256pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void {
1257 if (builtin.os == .windows) {1257 if (builtin.os.tag == .windows) {
1258 const target_path_w = try windows.cStrToPrefixedFileW(target_path);1258 const target_path_w = try windows.cStrToPrefixedFileW(target_path);
1259 const sym_link_path_w = try windows.cStrToPrefixedFileW(sym_link_path);1259 const sym_link_path_w = try windows.cStrToPrefixedFileW(sym_link_path);
1260 return windows.CreateSymbolicLinkW(&sym_link_path_w, &target_path_w, 0);1260 return windows.CreateSymbolicLinkW(&sym_link_path_w, &target_path_w, 0);
...@@ -1329,7 +1329,7 @@ pub const UnlinkError = error{...@@ -1329,7 +1329,7 @@ pub const UnlinkError = error{
1329/// Delete a name and possibly the file it refers to.1329/// Delete a name and possibly the file it refers to.
1330/// See also `unlinkC`.1330/// See also `unlinkC`.
1331pub fn unlink(file_path: []const u8) UnlinkError!void {1331pub fn unlink(file_path: []const u8) UnlinkError!void {
1332 if (builtin.os == .windows) {1332 if (builtin.os.tag == .windows) {
1333 const file_path_w = try windows.sliceToPrefixedFileW(file_path);1333 const file_path_w = try windows.sliceToPrefixedFileW(file_path);
1334 return windows.DeleteFileW(&file_path_w);1334 return windows.DeleteFileW(&file_path_w);
1335 } else {1335 } else {
...@@ -1340,7 +1340,7 @@ pub fn unlink(file_path: []const u8) UnlinkError!void {...@@ -1340,7 +1340,7 @@ pub fn unlink(file_path: []const u8) UnlinkError!void {
13401340
1341/// Same as `unlink` except the parameter is a null terminated UTF8-encoded string.1341/// Same as `unlink` except the parameter is a null terminated UTF8-encoded string.
1342pub fn unlinkC(file_path: [*:0]const u8) UnlinkError!void {1342pub fn unlinkC(file_path: [*:0]const u8) UnlinkError!void {
1343 if (builtin.os == .windows) {1343 if (builtin.os.tag == .windows) {
1344 const file_path_w = try windows.cStrToPrefixedFileW(file_path);1344 const file_path_w = try windows.cStrToPrefixedFileW(file_path);
1345 return windows.DeleteFileW(&file_path_w);1345 return windows.DeleteFileW(&file_path_w);
1346 }1346 }
...@@ -1372,7 +1372,7 @@ pub const UnlinkatError = UnlinkError || error{...@@ -1372,7 +1372,7 @@ pub const UnlinkatError = UnlinkError || error{
1372/// Asserts that the path parameter has no null bytes.1372/// Asserts that the path parameter has no null bytes.
1373pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!void {1373pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!void {
1374 if (std.debug.runtime_safety) for (file_path) |byte| assert(byte != 0);1374 if (std.debug.runtime_safety) for (file_path) |byte| assert(byte != 0);
1375 if (builtin.os == .windows) {1375 if (builtin.os.tag == .windows) {
1376 const file_path_w = try windows.sliceToPrefixedFileW(file_path);1376 const file_path_w = try windows.sliceToPrefixedFileW(file_path);
1377 return unlinkatW(dirfd, &file_path_w, flags);1377 return unlinkatW(dirfd, &file_path_w, flags);
1378 }1378 }
...@@ -1382,7 +1382,7 @@ pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!vo...@@ -1382,7 +1382,7 @@ pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!vo
13821382
1383/// Same as `unlinkat` but `file_path` is a null-terminated string.1383/// Same as `unlinkat` but `file_path` is a null-terminated string.
1384pub fn unlinkatC(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void {1384pub fn unlinkatC(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void {
1385 if (builtin.os == .windows) {1385 if (builtin.os.tag == .windows) {
1386 const file_path_w = try windows.cStrToPrefixedFileW(file_path_c);1386 const file_path_w = try windows.cStrToPrefixedFileW(file_path_c);
1387 return unlinkatW(dirfd, &file_path_w, flags);1387 return unlinkatW(dirfd, &file_path_w, flags);
1388 }1388 }
...@@ -1493,7 +1493,7 @@ const RenameError = error{...@@ -1493,7 +1493,7 @@ const RenameError = error{
14931493
1494/// Change the name or location of a file.1494/// Change the name or location of a file.
1495pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {1495pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {
1496 if (builtin.os == .windows) {1496 if (builtin.os.tag == .windows) {
1497 const old_path_w = try windows.sliceToPrefixedFileW(old_path);1497 const old_path_w = try windows.sliceToPrefixedFileW(old_path);
1498 const new_path_w = try windows.sliceToPrefixedFileW(new_path);1498 const new_path_w = try windows.sliceToPrefixedFileW(new_path);
1499 return renameW(&old_path_w, &new_path_w);1499 return renameW(&old_path_w, &new_path_w);
...@@ -1506,7 +1506,7 @@ pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {...@@ -1506,7 +1506,7 @@ pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {
15061506
1507/// Same as `rename` except the parameters are null-terminated byte arrays.1507/// Same as `rename` except the parameters are null-terminated byte arrays.
1508pub fn renameC(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void {1508pub fn renameC(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void {
1509 if (builtin.os == .windows) {1509 if (builtin.os.tag == .windows) {
1510 const old_path_w = try windows.cStrToPrefixedFileW(old_path);1510 const old_path_w = try windows.cStrToPrefixedFileW(old_path);
1511 const new_path_w = try windows.cStrToPrefixedFileW(new_path);1511 const new_path_w = try windows.cStrToPrefixedFileW(new_path);
1512 return renameW(&old_path_w, &new_path_w);1512 return renameW(&old_path_w, &new_path_w);
...@@ -1561,7 +1561,7 @@ pub const MakeDirError = error{...@@ -1561,7 +1561,7 @@ pub const MakeDirError = error{
1561/// Create a directory.1561/// Create a directory.
1562/// `mode` is ignored on Windows.1562/// `mode` is ignored on Windows.
1563pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {1563pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {
1564 if (builtin.os == .windows) {1564 if (builtin.os.tag == .windows) {
1565 const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);1565 const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
1566 return windows.CreateDirectoryW(&dir_path_w, null);1566 return windows.CreateDirectoryW(&dir_path_w, null);
1567 } else {1567 } else {
...@@ -1572,7 +1572,7 @@ pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {...@@ -1572,7 +1572,7 @@ pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {
15721572
1573/// Same as `mkdir` but the parameter is a null-terminated UTF8-encoded string.1573/// Same as `mkdir` but the parameter is a null-terminated UTF8-encoded string.
1574pub fn mkdirC(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {1574pub fn mkdirC(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
1575 if (builtin.os == .windows) {1575 if (builtin.os.tag == .windows) {
1576 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);1576 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
1577 return windows.CreateDirectoryW(&dir_path_w, null);1577 return windows.CreateDirectoryW(&dir_path_w, null);
1578 }1578 }
...@@ -1611,7 +1611,7 @@ pub const DeleteDirError = error{...@@ -1611,7 +1611,7 @@ pub const DeleteDirError = error{
16111611
1612/// Deletes an empty directory.1612/// Deletes an empty directory.
1613pub fn rmdir(dir_path: []const u8) DeleteDirError!void {1613pub fn rmdir(dir_path: []const u8) DeleteDirError!void {
1614 if (builtin.os == .windows) {1614 if (builtin.os.tag == .windows) {
1615 const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);1615 const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
1616 return windows.RemoveDirectoryW(&dir_path_w);1616 return windows.RemoveDirectoryW(&dir_path_w);
1617 } else {1617 } else {
...@@ -1622,7 +1622,7 @@ pub fn rmdir(dir_path: []const u8) DeleteDirError!void {...@@ -1622,7 +1622,7 @@ pub fn rmdir(dir_path: []const u8) DeleteDirError!void {
16221622
1623/// Same as `rmdir` except the parameter is null-terminated.1623/// Same as `rmdir` except the parameter is null-terminated.
1624pub fn rmdirC(dir_path: [*:0]const u8) DeleteDirError!void {1624pub fn rmdirC(dir_path: [*:0]const u8) DeleteDirError!void {
1625 if (builtin.os == .windows) {1625 if (builtin.os.tag == .windows) {
1626 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);1626 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
1627 return windows.RemoveDirectoryW(&dir_path_w);1627 return windows.RemoveDirectoryW(&dir_path_w);
1628 }1628 }
...@@ -1658,7 +1658,7 @@ pub const ChangeCurDirError = error{...@@ -1658,7 +1658,7 @@ pub const ChangeCurDirError = error{
1658/// Changes the current working directory of the calling process.1658/// Changes the current working directory of the calling process.
1659/// `dir_path` is recommended to be a UTF-8 encoded string.1659/// `dir_path` is recommended to be a UTF-8 encoded string.
1660pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {1660pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {
1661 if (builtin.os == .windows) {1661 if (builtin.os.tag == .windows) {
1662 const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);1662 const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
1663 @compileError("TODO implement chdir for Windows");1663 @compileError("TODO implement chdir for Windows");
1664 } else {1664 } else {
...@@ -1669,7 +1669,7 @@ pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {...@@ -1669,7 +1669,7 @@ pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {
16691669
1670/// Same as `chdir` except the parameter is null-terminated.1670/// Same as `chdir` except the parameter is null-terminated.
1671pub fn chdirC(dir_path: [*:0]const u8) ChangeCurDirError!void {1671pub fn chdirC(dir_path: [*:0]const u8) ChangeCurDirError!void {
1672 if (builtin.os == .windows) {1672 if (builtin.os.tag == .windows) {
1673 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);1673 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
1674 @compileError("TODO implement chdir for Windows");1674 @compileError("TODO implement chdir for Windows");
1675 }1675 }
...@@ -1700,7 +1700,7 @@ pub const ReadLinkError = error{...@@ -1700,7 +1700,7 @@ pub const ReadLinkError = error{
1700/// Read value of a symbolic link.1700/// Read value of a symbolic link.
1701/// The return value is a slice of `out_buffer` from index 0.1701/// The return value is a slice of `out_buffer` from index 0.
1702pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {1702pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
1703 if (builtin.os == .windows) {1703 if (builtin.os.tag == .windows) {
1704 const file_path_w = try windows.sliceToPrefixedFileW(file_path);1704 const file_path_w = try windows.sliceToPrefixedFileW(file_path);
1705 @compileError("TODO implement readlink for Windows");1705 @compileError("TODO implement readlink for Windows");
1706 } else {1706 } else {
...@@ -1711,7 +1711,7 @@ pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {...@@ -1711,7 +1711,7 @@ pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
17111711
1712/// Same as `readlink` except `file_path` is null-terminated.1712/// Same as `readlink` except `file_path` is null-terminated.
1713pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {1713pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
1714 if (builtin.os == .windows) {1714 if (builtin.os.tag == .windows) {
1715 const file_path_w = try windows.cStrToPrefixedFileW(file_path);1715 const file_path_w = try windows.cStrToPrefixedFileW(file_path);
1716 @compileError("TODO implement readlink for Windows");1716 @compileError("TODO implement readlink for Windows");
1717 }1717 }
...@@ -1732,7 +1732,7 @@ pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8...@@ -1732,7 +1732,7 @@ pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8
1732}1732}
17331733
1734pub fn readlinkatC(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {1734pub fn readlinkatC(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
1735 if (builtin.os == .windows) {1735 if (builtin.os.tag == .windows) {
1736 const file_path_w = try windows.cStrToPrefixedFileW(file_path);1736 const file_path_w = try windows.cStrToPrefixedFileW(file_path);
1737 @compileError("TODO implement readlink for Windows");1737 @compileError("TODO implement readlink for Windows");
1738 }1738 }
...@@ -1800,7 +1800,7 @@ pub fn setregid(rgid: u32, egid: u32) SetIdError!void {...@@ -1800,7 +1800,7 @@ pub fn setregid(rgid: u32, egid: u32) SetIdError!void {
18001800
1801/// Test whether a file descriptor refers to a terminal.1801/// Test whether a file descriptor refers to a terminal.
1802pub fn isatty(handle: fd_t) bool {1802pub fn isatty(handle: fd_t) bool {
1803 if (builtin.os == .windows) {1803 if (builtin.os.tag == .windows) {
1804 if (isCygwinPty(handle))1804 if (isCygwinPty(handle))
1805 return true;1805 return true;
18061806
...@@ -1810,7 +1810,7 @@ pub fn isatty(handle: fd_t) bool {...@@ -1810,7 +1810,7 @@ pub fn isatty(handle: fd_t) bool {
1810 if (builtin.link_libc) {1810 if (builtin.link_libc) {
1811 return system.isatty(handle) != 0;1811 return system.isatty(handle) != 0;
1812 }1812 }
1813 if (builtin.os == .wasi) {1813 if (builtin.os.tag == .wasi) {
1814 var statbuf: fdstat_t = undefined;1814 var statbuf: fdstat_t = undefined;
1815 const err = system.fd_fdstat_get(handle, &statbuf);1815 const err = system.fd_fdstat_get(handle, &statbuf);
1816 if (err != 0) {1816 if (err != 0) {
...@@ -1828,7 +1828,7 @@ pub fn isatty(handle: fd_t) bool {...@@ -1828,7 +1828,7 @@ pub fn isatty(handle: fd_t) bool {
18281828
1829 return true;1829 return true;
1830 }1830 }
1831 if (builtin.os == .linux) {1831 if (builtin.os.tag == .linux) {
1832 var wsz: linux.winsize = undefined;1832 var wsz: linux.winsize = undefined;
1833 return linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;1833 return linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
1834 }1834 }
...@@ -1836,7 +1836,7 @@ pub fn isatty(handle: fd_t) bool {...@@ -1836,7 +1836,7 @@ pub fn isatty(handle: fd_t) bool {
1836}1836}
18371837
1838pub fn isCygwinPty(handle: fd_t) bool {1838pub fn isCygwinPty(handle: fd_t) bool {
1839 if (builtin.os != .windows) return false;1839 if (builtin.os.tag != .windows) return false;
18401840
1841 const size = @sizeOf(windows.FILE_NAME_INFO);1841 const size = @sizeOf(windows.FILE_NAME_INFO);
1842 var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = [_]u8{0} ** (size + windows.MAX_PATH);1842 var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = [_]u8{0} ** (size + windows.MAX_PATH);
...@@ -2589,7 +2589,7 @@ pub const AccessError = error{...@@ -2589,7 +2589,7 @@ pub const AccessError = error{
2589/// check user's permissions for a file2589/// check user's permissions for a file
2590/// TODO currently this assumes `mode` is `F_OK` on Windows.2590/// TODO currently this assumes `mode` is `F_OK` on Windows.
2591pub fn access(path: []const u8, mode: u32) AccessError!void {2591pub fn access(path: []const u8, mode: u32) AccessError!void {
2592 if (builtin.os == .windows) {2592 if (builtin.os.tag == .windows) {
2593 const path_w = try windows.sliceToPrefixedFileW(path);2593 const path_w = try windows.sliceToPrefixedFileW(path);
2594 _ = try windows.GetFileAttributesW(&path_w);2594 _ = try windows.GetFileAttributesW(&path_w);
2595 return;2595 return;
...@@ -2603,7 +2603,7 @@ pub const accessC = accessZ;...@@ -2603,7 +2603,7 @@ pub const accessC = accessZ;
26032603
2604/// Same as `access` except `path` is null-terminated.2604/// Same as `access` except `path` is null-terminated.
2605pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {2605pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {
2606 if (builtin.os == .windows) {2606 if (builtin.os.tag == .windows) {
2607 const path_w = try windows.cStrToPrefixedFileW(path);2607 const path_w = try windows.cStrToPrefixedFileW(path);
2608 _ = try windows.GetFileAttributesW(&path_w);2608 _ = try windows.GetFileAttributesW(&path_w);
2609 return;2609 return;
...@@ -2644,7 +2644,7 @@ pub fn accessW(path: [*:0]const u16, mode: u32) windows.GetFileAttributesError!v...@@ -2644,7 +2644,7 @@ pub fn accessW(path: [*:0]const u16, mode: u32) windows.GetFileAttributesError!v
2644/// Check user's permissions for a file, based on an open directory handle.2644/// Check user's permissions for a file, based on an open directory handle.
2645/// TODO currently this ignores `mode` and `flags` on Windows.2645/// TODO currently this ignores `mode` and `flags` on Windows.
2646pub fn faccessat(dirfd: fd_t, path: []const u8, mode: u32, flags: u32) AccessError!void {2646pub fn faccessat(dirfd: fd_t, path: []const u8, mode: u32, flags: u32) AccessError!void {
2647 if (builtin.os == .windows) {2647 if (builtin.os.tag == .windows) {
2648 const path_w = try windows.sliceToPrefixedFileW(path);2648 const path_w = try windows.sliceToPrefixedFileW(path);
2649 return faccessatW(dirfd, &path_w, mode, flags);2649 return faccessatW(dirfd, &path_w, mode, flags);
2650 }2650 }
...@@ -2654,7 +2654,7 @@ pub fn faccessat(dirfd: fd_t, path: []const u8, mode: u32, flags: u32) AccessErr...@@ -2654,7 +2654,7 @@ pub fn faccessat(dirfd: fd_t, path: []const u8, mode: u32, flags: u32) AccessErr
26542654
2655/// Same as `faccessat` except the path parameter is null-terminated.2655/// Same as `faccessat` except the path parameter is null-terminated.
2656pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) AccessError!void {2656pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) AccessError!void {
2657 if (builtin.os == .windows) {2657 if (builtin.os.tag == .windows) {
2658 const path_w = try windows.cStrToPrefixedFileW(path);2658 const path_w = try windows.cStrToPrefixedFileW(path);
2659 return faccessatW(dirfd, &path_w, mode, flags);2659 return faccessatW(dirfd, &path_w, mode, flags);
2660 }2660 }
...@@ -2764,6 +2764,7 @@ pub const SysCtlError = error{...@@ -2764,6 +2764,7 @@ pub const SysCtlError = error{
2764 PermissionDenied,2764 PermissionDenied,
2765 SystemResources,2765 SystemResources,
2766 NameTooLong,2766 NameTooLong,
2767 UnknownName,
2767} || UnexpectedError;2768} || UnexpectedError;
27682769
2769pub fn sysctl(2770pub fn sysctl(
...@@ -2779,6 +2780,7 @@ pub fn sysctl(...@@ -2779,6 +2780,7 @@ pub fn sysctl(
2779 EFAULT => unreachable,2780 EFAULT => unreachable,
2780 EPERM => return error.PermissionDenied,2781 EPERM => return error.PermissionDenied,
2781 ENOMEM => return error.SystemResources,2782 ENOMEM => return error.SystemResources,
2783 ENOENT => return error.UnknownName,
2782 else => |err| return unexpectedErrno(err),2784 else => |err| return unexpectedErrno(err),
2783 }2785 }
2784}2786}
...@@ -2795,6 +2797,7 @@ pub fn sysctlbynameC(...@@ -2795,6 +2797,7 @@ pub fn sysctlbynameC(
2795 EFAULT => unreachable,2797 EFAULT => unreachable,
2796 EPERM => return error.PermissionDenied,2798 EPERM => return error.PermissionDenied,
2797 ENOMEM => return error.SystemResources,2799 ENOMEM => return error.SystemResources,
2800 ENOENT => return error.UnknownName,
2798 else => |err| return unexpectedErrno(err),2801 else => |err| return unexpectedErrno(err),
2799 }2802 }
2800}2803}
...@@ -2811,7 +2814,7 @@ pub const SeekError = error{Unseekable} || UnexpectedError;...@@ -2811,7 +2814,7 @@ pub const SeekError = error{Unseekable} || UnexpectedError;
28112814
2812/// Repositions read/write file offset relative to the beginning.2815/// Repositions read/write file offset relative to the beginning.
2813pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {2816pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
2814 if (builtin.os == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {2817 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
2815 var result: u64 = undefined;2818 var result: u64 = undefined;
2816 switch (errno(system.llseek(fd, offset, &result, SEEK_SET))) {2819 switch (errno(system.llseek(fd, offset, &result, SEEK_SET))) {
2817 0 => return,2820 0 => return,
...@@ -2823,7 +2826,7 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {...@@ -2823,7 +2826,7 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
2823 else => |err| return unexpectedErrno(err),2826 else => |err| return unexpectedErrno(err),
2824 }2827 }
2825 }2828 }
2826 if (builtin.os == .windows) {2829 if (builtin.os.tag == .windows) {
2827 return windows.SetFilePointerEx_BEGIN(fd, offset);2830 return windows.SetFilePointerEx_BEGIN(fd, offset);
2828 }2831 }
2829 const ipos = @bitCast(i64, offset); // the OS treats this as unsigned2832 const ipos = @bitCast(i64, offset); // the OS treats this as unsigned
...@@ -2840,7 +2843,7 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {...@@ -2840,7 +2843,7 @@ pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
28402843
2841/// Repositions read/write file offset relative to the current offset.2844/// Repositions read/write file offset relative to the current offset.
2842pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {2845pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
2843 if (builtin.os == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {2846 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
2844 var result: u64 = undefined;2847 var result: u64 = undefined;
2845 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_CUR))) {2848 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_CUR))) {
2846 0 => return,2849 0 => return,
...@@ -2852,7 +2855,7 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {...@@ -2852,7 +2855,7 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
2852 else => |err| return unexpectedErrno(err),2855 else => |err| return unexpectedErrno(err),
2853 }2856 }
2854 }2857 }
2855 if (builtin.os == .windows) {2858 if (builtin.os.tag == .windows) {
2856 return windows.SetFilePointerEx_CURRENT(fd, offset);2859 return windows.SetFilePointerEx_CURRENT(fd, offset);
2857 }2860 }
2858 switch (errno(system.lseek(fd, offset, SEEK_CUR))) {2861 switch (errno(system.lseek(fd, offset, SEEK_CUR))) {
...@@ -2868,7 +2871,7 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {...@@ -2868,7 +2871,7 @@ pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
28682871
2869/// Repositions read/write file offset relative to the end.2872/// Repositions read/write file offset relative to the end.
2870pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {2873pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
2871 if (builtin.os == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {2874 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
2872 var result: u64 = undefined;2875 var result: u64 = undefined;
2873 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_END))) {2876 switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_END))) {
2874 0 => return,2877 0 => return,
...@@ -2880,7 +2883,7 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {...@@ -2880,7 +2883,7 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
2880 else => |err| return unexpectedErrno(err),2883 else => |err| return unexpectedErrno(err),
2881 }2884 }
2882 }2885 }
2883 if (builtin.os == .windows) {2886 if (builtin.os.tag == .windows) {
2884 return windows.SetFilePointerEx_END(fd, offset);2887 return windows.SetFilePointerEx_END(fd, offset);
2885 }2888 }
2886 switch (errno(system.lseek(fd, offset, SEEK_END))) {2889 switch (errno(system.lseek(fd, offset, SEEK_END))) {
...@@ -2896,7 +2899,7 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {...@@ -2896,7 +2899,7 @@ pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
28962899
2897/// Returns the read/write file offset relative to the beginning.2900/// Returns the read/write file offset relative to the beginning.
2898pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {2901pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
2899 if (builtin.os == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {2902 if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
2900 var result: u64 = undefined;2903 var result: u64 = undefined;
2901 switch (errno(system.llseek(fd, 0, &result, SEEK_CUR))) {2904 switch (errno(system.llseek(fd, 0, &result, SEEK_CUR))) {
2902 0 => return result,2905 0 => return result,
...@@ -2908,7 +2911,7 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {...@@ -2908,7 +2911,7 @@ pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
2908 else => |err| return unexpectedErrno(err),2911 else => |err| return unexpectedErrno(err),
2909 }2912 }
2910 }2913 }
2911 if (builtin.os == .windows) {2914 if (builtin.os.tag == .windows) {
2912 return windows.SetFilePointerEx_CURRENT_get(fd);2915 return windows.SetFilePointerEx_CURRENT_get(fd);
2913 }2916 }
2914 const rc = system.lseek(fd, 0, SEEK_CUR);2917 const rc = system.lseek(fd, 0, SEEK_CUR);
...@@ -2957,7 +2960,7 @@ pub const RealPathError = error{...@@ -2957,7 +2960,7 @@ pub const RealPathError = error{
2957/// The return value is a slice of `out_buffer`, but not necessarily from the beginning.2960/// The return value is a slice of `out_buffer`, but not necessarily from the beginning.
2958/// See also `realpathC` and `realpathW`.2961/// See also `realpathC` and `realpathW`.
2959pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {2962pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
2960 if (builtin.os == .windows) {2963 if (builtin.os.tag == .windows) {
2961 const pathname_w = try windows.sliceToPrefixedFileW(pathname);2964 const pathname_w = try windows.sliceToPrefixedFileW(pathname);
2962 return realpathW(&pathname_w, out_buffer);2965 return realpathW(&pathname_w, out_buffer);
2963 }2966 }
...@@ -2967,11 +2970,11 @@ pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathE...@@ -2967,11 +2970,11 @@ pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathE
29672970
2968/// Same as `realpath` except `pathname` is null-terminated.2971/// Same as `realpath` except `pathname` is null-terminated.
2969pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {2972pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
2970 if (builtin.os == .windows) {2973 if (builtin.os.tag == .windows) {
2971 const pathname_w = try windows.cStrToPrefixedFileW(pathname);2974 const pathname_w = try windows.cStrToPrefixedFileW(pathname);
2972 return realpathW(&pathname_w, out_buffer);2975 return realpathW(&pathname_w, out_buffer);
2973 }2976 }
2974 if (builtin.os == .linux and !builtin.link_libc) {2977 if (builtin.os.tag == .linux and !builtin.link_libc) {
2975 const fd = try openC(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0);2978 const fd = try openC(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0);
2976 defer close(fd);2979 defer close(fd);
29772980
...@@ -3121,7 +3124,7 @@ pub fn dl_iterate_phdr(...@@ -3121,7 +3124,7 @@ pub fn dl_iterate_phdr(
3121pub const ClockGetTimeError = error{UnsupportedClock} || UnexpectedError;3124pub const ClockGetTimeError = error{UnsupportedClock} || UnexpectedError;
31223125
3123pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {3126pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
3124 if (comptime std.Target.current.getOs() == .wasi) {3127 if (std.Target.current.os.tag == .wasi) {
3125 var ts: timestamp_t = undefined;3128 var ts: timestamp_t = undefined;
3126 switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {3129 switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {
3127 0 => {3130 0 => {
...@@ -3144,7 +3147,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {...@@ -3144,7 +3147,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
3144}3147}
31453148
3146pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {3149pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
3147 if (comptime std.Target.current.getOs() == .wasi) {3150 if (std.Target.current.os.tag == .wasi) {
3148 var ts: timestamp_t = undefined;3151 var ts: timestamp_t = undefined;
3149 switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {3152 switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {
3150 0 => res.* = .{3153 0 => res.* = .{
...@@ -3222,7 +3225,7 @@ pub const SigaltstackError = error{...@@ -3222,7 +3225,7 @@ pub const SigaltstackError = error{
3222} || UnexpectedError;3225} || UnexpectedError;
32233226
3224pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {3227pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
3225 if (builtin.os == .windows or builtin.os == .uefi or builtin.os == .wasi)3228 if (builtin.os.tag == .windows or builtin.os.tag == .uefi or builtin.os.tag == .wasi)
3226 @compileError("std.os.sigaltstack not available for this target");3229 @compileError("std.os.sigaltstack not available for this target");
32273230
3228 switch (errno(system.sigaltstack(ss, old_ss))) {3231 switch (errno(system.sigaltstack(ss, old_ss))) {
...@@ -3294,23 +3297,25 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {...@@ -3294,23 +3297,25 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
3294 else => |err| return unexpectedErrno(err),3297 else => |err| return unexpectedErrno(err),
3295 }3298 }
3296 }3299 }
3297 if (builtin.os == .linux) {3300 if (builtin.os.tag == .linux) {
3298 var uts: utsname = undefined;3301 const uts = uname();
3299 switch (errno(system.uname(&uts))) {3302 const hostname = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &uts.nodename));
3300 0 => {3303 mem.copy(u8, name_buffer, hostname);
3301 const hostname = mem.toSlice(u8, @ptrCast([*:0]u8, &uts.nodename));3304 return name_buffer[0..hostname.len];
3302 mem.copy(u8, name_buffer, hostname);
3303 return name_buffer[0..hostname.len];
3304 },
3305 EFAULT => unreachable,
3306 EPERM => return error.PermissionDenied,
3307 else => |err| return unexpectedErrno(err),
3308 }
3309 }3305 }
33103306
3311 @compileError("TODO implement gethostname for this OS");3307 @compileError("TODO implement gethostname for this OS");
3312}3308}
33133309
3310pub fn uname() utsname {
3311 var uts: utsname = undefined;
3312 switch (errno(system.uname(&uts))) {
3313 0 => return uts,
3314 EFAULT => unreachable,
3315 else => unreachable,
3316 }
3317}
3318
3314pub fn res_mkquery(3319pub fn res_mkquery(
3315 op: u4,3320 op: u4,
3316 dname: []const u8,3321 dname: []const u8,
...@@ -3611,7 +3616,7 @@ pub const SchedYieldError = error{...@@ -3611,7 +3616,7 @@ pub const SchedYieldError = error{
3611};3616};
36123617
3613pub fn sched_yield() SchedYieldError!void {3618pub fn sched_yield() SchedYieldError!void {
3614 if (builtin.os == .windows) {3619 if (builtin.os.tag == .windows) {
3615 // The return value has to do with how many other threads there are; it is not3620 // The return value has to do with how many other threads there are; it is not
3616 // an error condition on Windows.3621 // an error condition on Windows.
3617 _ = windows.kernel32.SwitchToThread();3622 _ = windows.kernel32.SwitchToThread();
lib/std/os/bits.zig+2-2
...@@ -3,10 +3,10 @@...@@ -3,10 +3,10 @@
3//! Root source files can define `os.bits` and these will additionally be added3//! Root source files can define `os.bits` and these will additionally be added
4//! to the namespace.4//! to the namespace.
55
6const builtin = @import("builtin");6const std = @import("std");
7const root = @import("root");7const root = @import("root");
88
9pub usingnamespace switch (builtin.os) {9pub usingnamespace switch (std.Target.current.os.tag) {
10 .macosx, .ios, .tvos, .watchos => @import("bits/darwin.zig"),10 .macosx, .ios, .tvos, .watchos => @import("bits/darwin.zig"),
11 .dragonfly => @import("bits/dragonfly.zig"),11 .dragonfly => @import("bits/dragonfly.zig"),
12 .freebsd => @import("bits/freebsd.zig"),12 .freebsd => @import("bits/freebsd.zig"),
lib/std/os/linux.zig+1-1
...@@ -1070,7 +1070,7 @@ pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usi...@@ -1070,7 +1070,7 @@ pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usi
1070}1070}
10711071
1072test "" {1072test "" {
1073 if (builtin.os == .linux) {1073 if (builtin.os.tag == .linux) {
1074 _ = @import("linux/test.zig");1074 _ = @import("linux/test.zig");
1075 }1075 }
1076}1076}
lib/std/os/test.zig+8-8
...@@ -53,7 +53,7 @@ test "std.Thread.getCurrentId" {...@@ -53,7 +53,7 @@ test "std.Thread.getCurrentId" {
53 thread.wait();53 thread.wait();
54 if (Thread.use_pthreads) {54 if (Thread.use_pthreads) {
55 expect(thread_current_id == thread_id);55 expect(thread_current_id == thread_id);
56 } else if (builtin.os == .windows) {56 } else if (builtin.os.tag == .windows) {
57 expect(Thread.getCurrentId() != thread_current_id);57 expect(Thread.getCurrentId() != thread_current_id);
58 } else {58 } else {
59 // If the thread completes very quickly, then thread_id can be 0. See the59 // If the thread completes very quickly, then thread_id can be 0. See the
...@@ -151,7 +151,7 @@ test "realpath" {...@@ -151,7 +151,7 @@ test "realpath" {
151}151}
152152
153test "sigaltstack" {153test "sigaltstack" {
154 if (builtin.os == .windows or builtin.os == .wasi) return error.SkipZigTest;154 if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
155155
156 var st: os.stack_t = undefined;156 var st: os.stack_t = undefined;
157 try os.sigaltstack(null, &st);157 try os.sigaltstack(null, &st);
...@@ -204,7 +204,7 @@ fn iter_fn(info: *dl_phdr_info, size: usize, counter: *usize) IterFnError!void {...@@ -204,7 +204,7 @@ fn iter_fn(info: *dl_phdr_info, size: usize, counter: *usize) IterFnError!void {
204}204}
205205
206test "dl_iterate_phdr" {206test "dl_iterate_phdr" {
207 if (builtin.os == .windows or builtin.os == .wasi or builtin.os == .macosx)207 if (builtin.os.tag == .windows or builtin.os.tag == .wasi or builtin.os.tag == .macosx)
208 return error.SkipZigTest;208 return error.SkipZigTest;
209209
210 var counter: usize = 0;210 var counter: usize = 0;
...@@ -213,7 +213,7 @@ test "dl_iterate_phdr" {...@@ -213,7 +213,7 @@ test "dl_iterate_phdr" {
213}213}
214214
215test "gethostname" {215test "gethostname" {
216 if (builtin.os == .windows)216 if (builtin.os.tag == .windows)
217 return error.SkipZigTest;217 return error.SkipZigTest;
218218
219 var buf: [os.HOST_NAME_MAX]u8 = undefined;219 var buf: [os.HOST_NAME_MAX]u8 = undefined;
...@@ -222,7 +222,7 @@ test "gethostname" {...@@ -222,7 +222,7 @@ test "gethostname" {
222}222}
223223
224test "pipe" {224test "pipe" {
225 if (builtin.os == .windows)225 if (builtin.os.tag == .windows)
226 return error.SkipZigTest;226 return error.SkipZigTest;
227227
228 var fds = try os.pipe();228 var fds = try os.pipe();
...@@ -241,7 +241,7 @@ test "argsAlloc" {...@@ -241,7 +241,7 @@ test "argsAlloc" {
241241
242test "memfd_create" {242test "memfd_create" {
243 // memfd_create is linux specific.243 // memfd_create is linux specific.
244 if (builtin.os != .linux) return error.SkipZigTest;244 if (builtin.os.tag != .linux) return error.SkipZigTest;
245 const fd = std.os.memfd_create("test", 0) catch |err| switch (err) {245 const fd = std.os.memfd_create("test", 0) catch |err| switch (err) {
246 // Related: https://github.com/ziglang/zig/issues/4019246 // Related: https://github.com/ziglang/zig/issues/4019
247 error.SystemOutdated => return error.SkipZigTest,247 error.SystemOutdated => return error.SkipZigTest,
...@@ -258,7 +258,7 @@ test "memfd_create" {...@@ -258,7 +258,7 @@ test "memfd_create" {
258}258}
259259
260test "mmap" {260test "mmap" {
261 if (builtin.os == .windows)261 if (builtin.os.tag == .windows)
262 return error.SkipZigTest;262 return error.SkipZigTest;
263263
264 // Simple mmap() call with non page-aligned size264 // Simple mmap() call with non page-aligned size
...@@ -353,7 +353,7 @@ test "mmap" {...@@ -353,7 +353,7 @@ test "mmap" {
353}353}
354354
355test "getenv" {355test "getenv" {
356 if (builtin.os == .windows) {356 if (builtin.os.tag == .windows) {
357 expect(os.getenvW(&[_:0]u16{ 'B', 'O', 'G', 'U', 'S', 0x11, 0x22, 0x33, 0x44, 0x55 }) == null);357 expect(os.getenvW(&[_:0]u16{ 'B', 'O', 'G', 'U', 'S', 0x11, 0x22, 0x33, 0x44, 0x55 }) == null);
358 } else {358 } else {
359 expect(os.getenvZ("BOGUSDOESNOTEXISTENVVAR") == null);359 expect(os.getenvZ("BOGUSDOESNOTEXISTENVVAR") == null);
lib/std/os/windows/bits.zig+201-16
...@@ -23,6 +23,7 @@ pub const BOOL = c_int;...@@ -23,6 +23,7 @@ pub const BOOL = c_int;
23pub const BOOLEAN = BYTE;23pub const BOOLEAN = BYTE;
24pub const BYTE = u8;24pub const BYTE = u8;
25pub const CHAR = u8;25pub const CHAR = u8;
26pub const UCHAR = u8;
26pub const FLOAT = f32;27pub const FLOAT = f32;
27pub const HANDLE = *c_void;28pub const HANDLE = *c_void;
28pub const HCRYPTPROV = ULONG_PTR;29pub const HCRYPTPROV = ULONG_PTR;
...@@ -54,6 +55,7 @@ pub const WORD = u16;...@@ -54,6 +55,7 @@ pub const WORD = u16;
54pub const DWORD = u32;55pub const DWORD = u32;
55pub const DWORD64 = u64;56pub const DWORD64 = u64;
56pub const LARGE_INTEGER = i64;57pub const LARGE_INTEGER = i64;
58pub const ULARGE_INTEGER = u64;
57pub const USHORT = u16;59pub const USHORT = u16;
58pub const SHORT = i16;60pub const SHORT = i16;
59pub const ULONG = u32;61pub const ULONG = u32;
...@@ -1145,32 +1147,202 @@ pub const UNICODE_STRING = extern struct {...@@ -1145,32 +1147,202 @@ pub const UNICODE_STRING = extern struct {
1145 Buffer: [*]WCHAR,1147 Buffer: [*]WCHAR,
1146};1148};
11471149
1150const ACTIVATION_CONTEXT_DATA = @OpaqueType();
1151const ASSEMBLY_STORAGE_MAP = @OpaqueType();
1152const FLS_CALLBACK_INFO = @OpaqueType();
1153const RTL_BITMAP = @OpaqueType();
1154pub const PRTL_BITMAP = *RTL_BITMAP;
1155const KAFFINITY = usize;
1156
1157/// Process Environment Block
1158/// Microsoft documentation of this is incomplete, the fields here are taken from various resources including:
1159/// - https://github.com/wine-mirror/wine/blob/1aff1e6a370ee8c0213a0fd4b220d121da8527aa/include/winternl.h#L269
1160/// - https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb/index.htm
1148pub const PEB = extern struct {1161pub const PEB = extern struct {
1149 Reserved1: [2]BYTE,1162 // Versions: All
1150 BeingDebugged: BYTE,1163 InheritedAddressSpace: BOOLEAN,
1151 Reserved2: [1]BYTE,1164
1152 Reserved3: [2]PVOID,1165 // Versions: 3.51+
1166 ReadImageFileExecOptions: BOOLEAN,
1167 BeingDebugged: BOOLEAN,
1168
1169 // Versions: 5.2+ (previously was padding)
1170 BitField: UCHAR,
1171
1172 // Versions: all
1173 Mutant: HANDLE,
1174 ImageBaseAddress: HMODULE,
1153 Ldr: *PEB_LDR_DATA,1175 Ldr: *PEB_LDR_DATA,
1154 ProcessParameters: *RTL_USER_PROCESS_PARAMETERS,1176 ProcessParameters: *RTL_USER_PROCESS_PARAMETERS,
1155 Reserved4: [3]PVOID,1177 SubSystemData: PVOID,
1178 ProcessHeap: HANDLE,
1179
1180 // Versions: 5.1+
1181 FastPebLock: *RTL_CRITICAL_SECTION,
1182
1183 // Versions: 5.2+
1156 AtlThunkSListPtr: PVOID,1184 AtlThunkSListPtr: PVOID,
1157 Reserved5: PVOID,1185 IFEOKey: PVOID,
1158 Reserved6: ULONG,1186
1159 Reserved7: PVOID,1187 // Versions: 6.0+
1160 Reserved8: ULONG,1188
1189 /// https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb/crossprocessflags.htm
1190 CrossProcessFlags: ULONG,
1191
1192 // Versions: 6.0+
1193 union1: extern union {
1194 KernelCallbackTable: PVOID,
1195 UserSharedInfoPtr: PVOID,
1196 },
1197
1198 // Versions: 5.1+
1199 SystemReserved: ULONG,
1200
1201 // Versions: 5.1, (not 5.2, not 6.0), 6.1+
1161 AtlThunkSListPtr32: ULONG,1202 AtlThunkSListPtr32: ULONG,
1162 Reserved9: [45]PVOID,1203
1163 Reserved10: [96]BYTE,1204 // Versions: 6.1+
1164 PostProcessInitRoutine: PPS_POST_PROCESS_INIT_ROUTINE,1205 ApiSetMap: PVOID,
1165 Reserved11: [128]BYTE,1206
1166 Reserved12: [1]PVOID,1207 // Versions: all
1208 TlsExpansionCounter: ULONG,
1209 // note: there is padding here on 64 bit
1210 TlsBitmap: PRTL_BITMAP,
1211 TlsBitmapBits: [2]ULONG,
1212 ReadOnlySharedMemoryBase: PVOID,
1213
1214 // Versions: 1703+
1215 SharedData: PVOID,
1216
1217 // Versions: all
1218 ReadOnlyStaticServerData: *PVOID,
1219 AnsiCodePageData: PVOID,
1220 OemCodePageData: PVOID,
1221 UnicodeCaseTableData: PVOID,
1222
1223 // Versions: 3.51+
1224 NumberOfProcessors: ULONG,
1225 NtGlobalFlag: ULONG,
1226
1227 // Versions: all
1228 CriticalSectionTimeout: LARGE_INTEGER,
1229
1230 // End of Original PEB size
1231
1232 // Fields appended in 3.51:
1233 HeapSegmentReserve: ULONG_PTR,
1234 HeapSegmentCommit: ULONG_PTR,
1235 HeapDeCommitTotalFreeThreshold: ULONG_PTR,
1236 HeapDeCommitFreeBlockThreshold: ULONG_PTR,
1237 NumberOfHeaps: ULONG,
1238 MaximumNumberOfHeaps: ULONG,
1239 ProcessHeaps: *PVOID,
1240
1241 // Fields appended in 4.0:
1242 GdiSharedHandleTable: PVOID,
1243 ProcessStarterHelper: PVOID,
1244 GdiDCAttributeList: ULONG,
1245 // note: there is padding here on 64 bit
1246 LoaderLock: *RTL_CRITICAL_SECTION,
1247 OSMajorVersion: ULONG,
1248 OSMinorVersion: ULONG,
1249 OSBuildNumber: USHORT,
1250 OSCSDVersion: USHORT,
1251 OSPlatformId: ULONG,
1252 ImageSubSystem: ULONG,
1253 ImageSubSystemMajorVersion: ULONG,
1254 ImageSubSystemMinorVersion: ULONG,
1255 // note: there is padding here on 64 bit
1256 ActiveProcessAffinityMask: KAFFINITY,
1257 GdiHandleBuffer: [switch (@sizeOf(usize)) {
1258 4 => 0x22,
1259 8 => 0x3C,
1260 else => unreachable,
1261 }]ULONG,
1262
1263 // Fields appended in 5.0 (Windows 2000):
1264 PostProcessInitRoutine: PVOID,
1265 TlsExpansionBitmap: PRTL_BITMAP,
1266 TlsExpansionBitmapBits: [32]ULONG,
1167 SessionId: ULONG,1267 SessionId: ULONG,
1268 // note: there is padding here on 64 bit
1269 // Versions: 5.1+
1270 AppCompatFlags: ULARGE_INTEGER,
1271 AppCompatFlagsUser: ULARGE_INTEGER,
1272 ShimData: PVOID,
1273 // Versions: 5.0+
1274 AppCompatInfo: PVOID,
1275 CSDVersion: UNICODE_STRING,
1276
1277 // Fields appended in 5.1 (Windows XP):
1278 ActivationContextData: *const ACTIVATION_CONTEXT_DATA,
1279 ProcessAssemblyStorageMap: *ASSEMBLY_STORAGE_MAP,
1280 SystemDefaultActivationData: *const ACTIVATION_CONTEXT_DATA,
1281 SystemAssemblyStorageMap: *ASSEMBLY_STORAGE_MAP,
1282 MinimumStackCommit: ULONG_PTR,
1283
1284 // Fields appended in 5.2 (Windows Server 2003):
1285 FlsCallback: *FLS_CALLBACK_INFO,
1286 FlsListHead: LIST_ENTRY,
1287 FlsBitmap: PRTL_BITMAP,
1288 FlsBitmapBits: [4]ULONG,
1289 FlsHighIndex: ULONG,
1290
1291 // Fields appended in 6.0 (Windows Vista):
1292 WerRegistrationData: PVOID,
1293 WerShipAssertPtr: PVOID,
1294
1295 // Fields appended in 6.1 (Windows 7):
1296 pUnused: PVOID, // previously pContextData
1297 pImageHeaderHash: PVOID,
1298
1299 /// TODO: https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb/tracingflags.htm
1300 TracingFlags: ULONG,
1301
1302 // Fields appended in 6.2 (Windows 8):
1303 CsrServerReadOnlySharedMemoryBase: ULONGLONG,
1304
1305 // Fields appended in 1511:
1306 TppWorkerpListLock: ULONG,
1307 TppWorkerpList: LIST_ENTRY,
1308 WaitOnAddressHashTable: [0x80]PVOID,
1309
1310 // Fields appended in 1709:
1311 TelemetryCoverageHeader: PVOID,
1312 CloudFileFlags: ULONG,
1168};1313};
11691314
1315/// The `PEB_LDR_DATA` structure is the main record of what modules are loaded in a process.
1316/// It is essentially the head of three double-linked lists of `LDR_DATA_TABLE_ENTRY` structures which each represent one loaded module.
1317///
1318/// Microsoft documentation of this is incomplete, the fields here are taken from various resources including:
1319/// - https://www.geoffchappell.com/studies/windows/win32/ntdll/structs/peb_ldr_data.htm
1170pub const PEB_LDR_DATA = extern struct {1320pub const PEB_LDR_DATA = extern struct {
1171 Reserved1: [8]BYTE,1321 // Versions: 3.51 and higher
1172 Reserved2: [3]PVOID,1322 /// The size in bytes of the structure
1323 Length: ULONG,
1324
1325 /// TRUE if the structure is prepared.
1326 Initialized: BOOLEAN,
1327
1328 SsHandle: PVOID,
1329 InLoadOrderModuleList: LIST_ENTRY,
1173 InMemoryOrderModuleList: LIST_ENTRY,1330 InMemoryOrderModuleList: LIST_ENTRY,
1331 InInitializationOrderModuleList: LIST_ENTRY,
1332
1333 // Versions: 5.1 and higher
1334
1335 /// No known use of this field is known in Windows 8 and higher.
1336 EntryInProgress: PVOID,
1337
1338 // Versions: 6.0 from Windows Vista SP1, and higher
1339 ShutdownInProgress: BOOLEAN,
1340
1341 /// Though ShutdownThreadId is declared as a HANDLE,
1342 /// it is indeed the thread ID as suggested by its name.
1343 /// It is picked up from the UniqueThread member of the CLIENT_ID in the
1344 /// TEB of the thread that asks to terminate the process.
1345 ShutdownThreadId: HANDLE,
1174};1346};
11751347
1176pub const RTL_USER_PROCESS_PARAMETERS = extern struct {1348pub const RTL_USER_PROCESS_PARAMETERS = extern struct {
...@@ -1321,3 +1493,16 @@ pub const PSAPI_WS_WATCH_INFORMATION_EX = extern struct {...@@ -1321,3 +1493,16 @@ pub const PSAPI_WS_WATCH_INFORMATION_EX = extern struct {
1321 Flags: ULONG_PTR,1493 Flags: ULONG_PTR,
1322};1494};
1323pub const PPSAPI_WS_WATCH_INFORMATION_EX = *PSAPI_WS_WATCH_INFORMATION_EX;1495pub const PPSAPI_WS_WATCH_INFORMATION_EX = *PSAPI_WS_WATCH_INFORMATION_EX;
1496
1497pub const OSVERSIONINFOW = extern struct {
1498 dwOSVersionInfoSize: ULONG,
1499 dwMajorVersion: ULONG,
1500 dwMinorVersion: ULONG,
1501 dwBuildNumber: ULONG,
1502 dwPlatformId: ULONG,
1503 szCSDVersion: [128]WCHAR,
1504};
1505pub const POSVERSIONINFOW = *OSVERSIONINFOW;
1506pub const LPOSVERSIONINFOW = *OSVERSIONINFOW;
1507pub const RTL_OSVERSIONINFOW = OSVERSIONINFOW;
1508pub const PRTL_OSVERSIONINFOW = *RTL_OSVERSIONINFOW;
lib/std/os/windows/ntdll.zig+9-1
...@@ -1,6 +1,14 @@...@@ -1,6 +1,14 @@
1usingnamespace @import("bits.zig");1usingnamespace @import("bits.zig");
22
3pub extern "NtDll" fn RtlCaptureStackBackTrace(FramesToSkip: DWORD, FramesToCapture: DWORD, BackTrace: **c_void, BackTraceHash: ?*DWORD) callconv(.Stdcall) WORD;3pub extern "NtDll" fn RtlGetVersion(
4 lpVersionInformation: PRTL_OSVERSIONINFOW,
5) callconv(.Stdcall) NTSTATUS;
6pub extern "NtDll" fn RtlCaptureStackBackTrace(
7 FramesToSkip: DWORD,
8 FramesToCapture: DWORD,
9 BackTrace: **c_void,
10 BackTraceHash: ?*DWORD,
11) callconv(.Stdcall) WORD;
4pub extern "NtDll" fn NtQueryInformationFile(12pub extern "NtDll" fn NtQueryInformationFile(
5 FileHandle: HANDLE,13 FileHandle: HANDLE,
6 IoStatusBlock: *IO_STATUS_BLOCK,14 IoStatusBlock: *IO_STATUS_BLOCK,
lib/std/packed_int_array.zig+2-2
...@@ -593,7 +593,7 @@ test "PackedInt(Array/Slice)Endian" {...@@ -593,7 +593,7 @@ test "PackedInt(Array/Slice)Endian" {
593// after this one is not mapped and will cause a segfault if we593// after this one is not mapped and will cause a segfault if we
594// don't account for the bounds.594// don't account for the bounds.
595test "PackedIntArray at end of available memory" {595test "PackedIntArray at end of available memory" {
596 switch (builtin.os) {596 switch (builtin.os.tag) {
597 .linux, .macosx, .ios, .freebsd, .netbsd, .windows => {},597 .linux, .macosx, .ios, .freebsd, .netbsd, .windows => {},
598 else => return,598 else => return,
599 }599 }
...@@ -612,7 +612,7 @@ test "PackedIntArray at end of available memory" {...@@ -612,7 +612,7 @@ test "PackedIntArray at end of available memory" {
612}612}
613613
614test "PackedIntSlice at end of available memory" {614test "PackedIntSlice at end of available memory" {
615 switch (builtin.os) {615 switch (builtin.os.tag) {
616 .linux, .macosx, .ios, .freebsd, .netbsd, .windows => {},616 .linux, .macosx, .ios, .freebsd, .netbsd, .windows => {},
617 else => return,617 else => return,
618 }618 }
lib/std/process.zig+15-11
...@@ -36,7 +36,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {...@@ -36,7 +36,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
36 var result = BufMap.init(allocator);36 var result = BufMap.init(allocator);
37 errdefer result.deinit();37 errdefer result.deinit();
3838
39 if (builtin.os == .windows) {39 if (builtin.os.tag == .windows) {
40 const ptr = os.windows.peb().ProcessParameters.Environment;40 const ptr = os.windows.peb().ProcessParameters.Environment;
4141
42 var i: usize = 0;42 var i: usize = 0;
...@@ -61,7 +61,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {...@@ -61,7 +61,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
61 try result.setMove(key, value);61 try result.setMove(key, value);
62 }62 }
63 return result;63 return result;
64 } else if (builtin.os == .wasi) {64 } else if (builtin.os.tag == .wasi) {
65 var environ_count: usize = undefined;65 var environ_count: usize = undefined;
66 var environ_buf_size: usize = undefined;66 var environ_buf_size: usize = undefined;
6767
...@@ -137,7 +137,7 @@ pub const GetEnvVarOwnedError = error{...@@ -137,7 +137,7 @@ pub const GetEnvVarOwnedError = error{
137137
138/// Caller must free returned memory.138/// Caller must free returned memory.
139pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) GetEnvVarOwnedError![]u8 {139pub fn getEnvVarOwned(allocator: *mem.Allocator, key: []const u8) GetEnvVarOwnedError![]u8 {
140 if (builtin.os == .windows) {140 if (builtin.os.tag == .windows) {
141 const result_w = blk: {141 const result_w = blk: {
142 const key_w = try std.unicode.utf8ToUtf16LeWithNull(allocator, key);142 const key_w = try std.unicode.utf8ToUtf16LeWithNull(allocator, key);
143 defer allocator.free(key_w);143 defer allocator.free(key_w);
...@@ -338,12 +338,12 @@ pub const ArgIteratorWindows = struct {...@@ -338,12 +338,12 @@ pub const ArgIteratorWindows = struct {
338};338};
339339
340pub const ArgIterator = struct {340pub const ArgIterator = struct {
341 const InnerType = if (builtin.os == .windows) ArgIteratorWindows else ArgIteratorPosix;341 const InnerType = if (builtin.os.tag == .windows) ArgIteratorWindows else ArgIteratorPosix;
342342
343 inner: InnerType,343 inner: InnerType,
344344
345 pub fn init() ArgIterator {345 pub fn init() ArgIterator {
346 if (builtin.os == .wasi) {346 if (builtin.os.tag == .wasi) {
347 // TODO: Figure out a compatible interface accomodating WASI347 // TODO: Figure out a compatible interface accomodating WASI
348 @compileError("ArgIterator is not yet supported in WASI. Use argsAlloc and argsFree instead.");348 @compileError("ArgIterator is not yet supported in WASI. Use argsAlloc and argsFree instead.");
349 }349 }
...@@ -355,7 +355,7 @@ pub const ArgIterator = struct {...@@ -355,7 +355,7 @@ pub const ArgIterator = struct {
355355
356 /// You must free the returned memory when done.356 /// You must free the returned memory when done.
357 pub fn next(self: *ArgIterator, allocator: *Allocator) ?(NextError![]u8) {357 pub fn next(self: *ArgIterator, allocator: *Allocator) ?(NextError![]u8) {
358 if (builtin.os == .windows) {358 if (builtin.os.tag == .windows) {
359 return self.inner.next(allocator);359 return self.inner.next(allocator);
360 } else {360 } else {
361 return mem.dupe(allocator, u8, self.inner.next() orelse return null);361 return mem.dupe(allocator, u8, self.inner.next() orelse return null);
...@@ -380,7 +380,7 @@ pub fn args() ArgIterator {...@@ -380,7 +380,7 @@ pub fn args() ArgIterator {
380380
381/// Caller must call argsFree on result.381/// Caller must call argsFree on result.
382pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {382pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {
383 if (builtin.os == .wasi) {383 if (builtin.os.tag == .wasi) {
384 var count: usize = undefined;384 var count: usize = undefined;
385 var buf_size: usize = undefined;385 var buf_size: usize = undefined;
386386
...@@ -445,7 +445,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {...@@ -445,7 +445,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {
445}445}
446446
447pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const []u8) void {447pub fn argsFree(allocator: *mem.Allocator, args_alloc: []const []u8) void {
448 if (builtin.os == .wasi) {448 if (builtin.os.tag == .wasi) {
449 const last_item = args_alloc[args_alloc.len - 1];449 const last_item = args_alloc[args_alloc.len - 1];
450 const last_byte_addr = @ptrToInt(last_item.ptr) + last_item.len + 1; // null terminated450 const last_byte_addr = @ptrToInt(last_item.ptr) + last_item.len + 1; // null terminated
451 const first_item_ptr = args_alloc[0].ptr;451 const first_item_ptr = args_alloc[0].ptr;
...@@ -498,7 +498,7 @@ pub const UserInfo = struct {...@@ -498,7 +498,7 @@ pub const UserInfo = struct {
498498
499/// POSIX function which gets a uid from username.499/// POSIX function which gets a uid from username.
500pub fn getUserInfo(name: []const u8) !UserInfo {500pub fn getUserInfo(name: []const u8) !UserInfo {
501 return switch (builtin.os) {501 return switch (builtin.os.tag) {
502 .linux, .macosx, .watchos, .tvos, .ios, .freebsd, .netbsd => posixGetUserInfo(name),502 .linux, .macosx, .watchos, .tvos, .ios, .freebsd, .netbsd => posixGetUserInfo(name),
503 else => @compileError("Unsupported OS"),503 else => @compileError("Unsupported OS"),
504 };504 };
...@@ -591,7 +591,7 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo {...@@ -591,7 +591,7 @@ pub fn posixGetUserInfo(name: []const u8) !UserInfo {
591}591}
592592
593pub fn getBaseAddress() usize {593pub fn getBaseAddress() usize {
594 switch (builtin.os) {594 switch (builtin.os.tag) {
595 .linux => {595 .linux => {
596 const base = os.system.getauxval(std.elf.AT_BASE);596 const base = os.system.getauxval(std.elf.AT_BASE);
597 if (base != 0) {597 if (base != 0) {
...@@ -609,13 +609,17 @@ pub fn getBaseAddress() usize {...@@ -609,13 +609,17 @@ pub fn getBaseAddress() usize {
609}609}
610610
611/// Caller owns the result value and each inner slice.611/// Caller owns the result value and each inner slice.
612/// TODO Remove the `Allocator` requirement from this API, which will remove the `Allocator`
613/// requirement from `std.zig.system.NativeTargetInfo.detect`. Most likely this will require
614/// introducing a new, lower-level function which takes a callback function, and then this
615/// function which takes an allocator can exist on top of it.
612pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]u8 {616pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]u8 {
613 switch (builtin.link_mode) {617 switch (builtin.link_mode) {
614 .Static => return &[_][:0]u8{},618 .Static => return &[_][:0]u8{},
615 .Dynamic => {},619 .Dynamic => {},
616 }620 }
617 const List = std.ArrayList([:0]u8);621 const List = std.ArrayList([:0]u8);
618 switch (builtin.os) {622 switch (builtin.os.tag) {
619 .linux,623 .linux,
620 .freebsd,624 .freebsd,
621 .netbsd,625 .netbsd,
lib/std/reset_event.zig+3-3
...@@ -16,7 +16,7 @@ pub const ResetEvent = struct {...@@ -16,7 +16,7 @@ pub const ResetEvent = struct {
1616
17 pub const OsEvent = if (builtin.single_threaded)17 pub const OsEvent = if (builtin.single_threaded)
18 DebugEvent18 DebugEvent
19 else if (builtin.link_libc and builtin.os != .windows and builtin.os != .linux)19 else if (builtin.link_libc and builtin.os.tag != .windows and builtin.os.tag != .linux)
20 PosixEvent20 PosixEvent
21 else21 else
22 AtomicEvent;22 AtomicEvent;
...@@ -106,7 +106,7 @@ const PosixEvent = struct {...@@ -106,7 +106,7 @@ const PosixEvent = struct {
106 fn deinit(self: *PosixEvent) void {106 fn deinit(self: *PosixEvent) void {
107 // on dragonfly, *destroy() functions can return EINVAL107 // on dragonfly, *destroy() functions can return EINVAL
108 // for statically initialized pthread structures108 // for statically initialized pthread structures
109 const err = if (builtin.os == .dragonfly) os.EINVAL else 0;109 const err = if (builtin.os.tag == .dragonfly) os.EINVAL else 0;
110110
111 const retm = c.pthread_mutex_destroy(&self.mutex);111 const retm = c.pthread_mutex_destroy(&self.mutex);
112 assert(retm == 0 or retm == err);112 assert(retm == 0 or retm == err);
...@@ -215,7 +215,7 @@ const AtomicEvent = struct {...@@ -215,7 +215,7 @@ const AtomicEvent = struct {
215 }215 }
216 }216 }
217217
218 pub const Futex = switch (builtin.os) {218 pub const Futex = switch (builtin.os.tag) {
219 .windows => WindowsFutex,219 .windows => WindowsFutex,
220 .linux => LinuxFutex,220 .linux => LinuxFutex,
221 else => SpinFutex,221 else => SpinFutex,
lib/std/special/c.zig+5-5
...@@ -17,7 +17,7 @@ const is_msvc = switch (builtin.abi) {...@@ -17,7 +17,7 @@ const is_msvc = switch (builtin.abi) {
17 .msvc => true,17 .msvc => true,
18 else => false,18 else => false,
19};19};
20const is_freestanding = switch (builtin.os) {20const is_freestanding = switch (builtin.os.tag) {
21 .freestanding => true,21 .freestanding => true,
22 else => false,22 else => false,
23};23};
...@@ -47,7 +47,7 @@ fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) callconv(.C) c_int {...@@ -47,7 +47,7 @@ fn strcmp(s1: [*:0]const u8, s2: [*:0]const u8) callconv(.C) c_int {
47}47}
4848
49fn strlen(s: [*:0]const u8) callconv(.C) usize {49fn strlen(s: [*:0]const u8) callconv(.C) usize {
50 return std.mem.len(u8, s);50 return std.mem.len(s);
51}51}
5252
53fn strncmp(_l: [*:0]const u8, _r: [*:0]const u8, _n: usize) callconv(.C) c_int {53fn strncmp(_l: [*:0]const u8, _r: [*:0]const u8, _n: usize) callconv(.C) c_int {
...@@ -81,7 +81,7 @@ pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn...@@ -81,7 +81,7 @@ pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn
81 @setCold(true);81 @setCold(true);
82 std.debug.panic("{}", .{msg});82 std.debug.panic("{}", .{msg});
83 }83 }
84 if (builtin.os != .freestanding and builtin.os != .other) {84 if (builtin.os.tag != .freestanding and builtin.os.tag != .other) {
85 std.os.abort();85 std.os.abort();
86 }86 }
87 while (true) {}87 while (true) {}
...@@ -178,11 +178,11 @@ test "test_bcmp" {...@@ -178,11 +178,11 @@ test "test_bcmp" {
178comptime {178comptime {
179 if (builtin.mode != builtin.Mode.ReleaseFast and179 if (builtin.mode != builtin.Mode.ReleaseFast and
180 builtin.mode != builtin.Mode.ReleaseSmall and180 builtin.mode != builtin.Mode.ReleaseSmall and
181 builtin.os != builtin.Os.windows)181 builtin.os.tag != .windows)
182 {182 {
183 @export(__stack_chk_fail, .{ .name = "__stack_chk_fail" });183 @export(__stack_chk_fail, .{ .name = "__stack_chk_fail" });
184 }184 }
185 if (builtin.os == builtin.Os.linux) {185 if (builtin.os.tag == .linux) {
186 @export(clone, .{ .name = "clone" });186 @export(clone, .{ .name = "clone" });
187 }187 }
188}188}
lib/std/special/compiler_rt.zig+8-10
...@@ -1,11 +1,9 @@...@@ -1,11 +1,9 @@
1const builtin = @import("builtin");1const std = @import("std");
2const builtin = std.builtin;
2const is_test = builtin.is_test;3const is_test = builtin.is_test;
34
4const is_gnu = switch (builtin.abi) {5const is_gnu = std.Target.current.abi.isGnu();
5 .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => true,6const is_mingw = builtin.os.tag == .windows and is_gnu;
6 else => false,
7};
8const is_mingw = builtin.os == .windows and is_gnu;
97
10comptime {8comptime {
11 const linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak;9 const linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak;
...@@ -180,7 +178,7 @@ comptime {...@@ -180,7 +178,7 @@ comptime {
180 @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr4", .linkage = linkage });178 @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr4", .linkage = linkage });
181 @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr8", .linkage = linkage });179 @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr8", .linkage = linkage });
182180
183 if (builtin.os == .linux) {181 if (builtin.os.tag == .linux) {
184 @export(@import("compiler_rt/arm.zig").__aeabi_read_tp, .{ .name = "__aeabi_read_tp", .linkage = linkage });182 @export(@import("compiler_rt/arm.zig").__aeabi_read_tp, .{ .name = "__aeabi_read_tp", .linkage = linkage });
185 }183 }
186184
...@@ -250,7 +248,7 @@ comptime {...@@ -250,7 +248,7 @@ comptime {
250 @export(@import("compiler_rt/aullrem.zig")._aullrem, .{ .name = "\x01__aullrem", .linkage = strong_linkage });248 @export(@import("compiler_rt/aullrem.zig")._aullrem, .{ .name = "\x01__aullrem", .linkage = strong_linkage });
251 }249 }
252250
253 if (builtin.os == .windows) {251 if (builtin.os.tag == .windows) {
254 // Default stack-probe functions emitted by LLVM252 // Default stack-probe functions emitted by LLVM
255 if (is_mingw) {253 if (is_mingw) {
256 @export(@import("compiler_rt/stack_probe.zig")._chkstk, .{ .name = "_alloca", .linkage = strong_linkage });254 @export(@import("compiler_rt/stack_probe.zig")._chkstk, .{ .name = "_alloca", .linkage = strong_linkage });
...@@ -288,7 +286,7 @@ comptime {...@@ -288,7 +286,7 @@ comptime {
288 else => {},286 else => {},
289 }287 }
290 } else {288 } else {
291 if (builtin.glibc_version != null) {289 if (std.Target.current.isGnuLibC() and builtin.link_libc) {
292 @export(__stack_chk_guard, .{ .name = "__stack_chk_guard", .linkage = linkage });290 @export(__stack_chk_guard, .{ .name = "__stack_chk_guard", .linkage = linkage });
293 }291 }
294 @export(@import("compiler_rt/divti3.zig").__divti3, .{ .name = "__divti3", .linkage = linkage });292 @export(@import("compiler_rt/divti3.zig").__divti3, .{ .name = "__divti3", .linkage = linkage });
...@@ -307,7 +305,7 @@ comptime {...@@ -307,7 +305,7 @@ comptime {
307pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {305pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {
308 @setCold(true);306 @setCold(true);
309 if (is_test) {307 if (is_test) {
310 @import("std").debug.panic("{}", .{msg});308 std.debug.panic("{}", .{msg});
311 } else {309 } else {
312 unreachable;310 unreachable;
313 }311 }
lib/std/special/compiler_rt/addXf3_test.zig+2-2
...@@ -31,7 +31,7 @@ fn test__addtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void {...@@ -31,7 +31,7 @@ fn test__addtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void {
31}31}
3232
33test "addtf3" {33test "addtf3" {
34 if (@import("std").Target.current.isWindows()) {34 if (@import("std").Target.current.os.tag == .windows) {
35 // TODO https://github.com/ziglang/zig/issues/50835 // TODO https://github.com/ziglang/zig/issues/508
36 return error.SkipZigTest;36 return error.SkipZigTest;
37 }37 }
...@@ -75,7 +75,7 @@ fn test__subtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void {...@@ -75,7 +75,7 @@ fn test__subtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) void {
75}75}
7676
77test "subtf3" {77test "subtf3" {
78 if (@import("std").Target.current.isWindows()) {78 if (@import("std").Target.current.os.tag == .windows) {
79 // TODO https://github.com/ziglang/zig/issues/50879 // TODO https://github.com/ziglang/zig/issues/508
80 return error.SkipZigTest;80 return error.SkipZigTest;
81 }81 }
lib/std/special/compiler_rt/ashlti3.zig+1-1
...@@ -24,7 +24,7 @@ const twords = extern union {...@@ -24,7 +24,7 @@ const twords = extern union {
24 all: i128,24 all: i128,
25 s: S,25 s: S,
2626
27 const S = if (builtin.endian == builtin.Endian.Little)27 const S = if (builtin.endian == .Little)
28 struct {28 struct {
29 low: u64,29 low: u64,
30 high: u64,30 high: u64,
lib/std/special/compiler_rt/ashrti3.zig+1-1
...@@ -25,7 +25,7 @@ const twords = extern union {...@@ -25,7 +25,7 @@ const twords = extern union {
25 all: i128,25 all: i128,
26 s: S,26 s: S,
2727
28 const S = if (builtin.endian == builtin.Endian.Little)28 const S = if (builtin.endian == .Little)
29 struct {29 struct {
30 low: i64,30 low: i64,
31 high: i64,31 high: i64,
lib/std/special/compiler_rt/extendXfYf2_test.zig+1-1
...@@ -90,7 +90,7 @@ test "extendhfsf2" {...@@ -90,7 +90,7 @@ test "extendhfsf2" {
90 test__extendhfsf2(0x7f00, 0x7fe00000); // sNaN90 test__extendhfsf2(0x7f00, 0x7fe00000); // sNaN
91 // On x86 the NaN becomes quiet because the return is pushed on the x8791 // On x86 the NaN becomes quiet because the return is pushed on the x87
92 // stack due to ABI requirements92 // stack due to ABI requirements
93 if (builtin.arch != .i386 and builtin.os == .windows)93 if (builtin.arch != .i386 and builtin.os.tag == .windows)
94 test__extendhfsf2(0x7c01, 0x7f802000); // sNaN94 test__extendhfsf2(0x7c01, 0x7f802000); // sNaN
9595
96 test__extendhfsf2(0, 0); // 096 test__extendhfsf2(0, 0); // 0
lib/std/special/compiler_rt/fixtfdi_test.zig+1-1
...@@ -11,7 +11,7 @@ fn test__fixtfdi(a: f128, expected: i64) void {...@@ -11,7 +11,7 @@ fn test__fixtfdi(a: f128, expected: i64) void {
11}11}
1212
13test "fixtfdi" {13test "fixtfdi" {
14 if (@import("std").Target.current.isWindows()) {14 if (@import("std").Target.current.os.tag == .windows) {
15 // TODO https://github.com/ziglang/zig/issues/50815 // TODO https://github.com/ziglang/zig/issues/508
16 return error.SkipZigTest;16 return error.SkipZigTest;
17 }17 }
lib/std/special/compiler_rt/fixtfsi_test.zig+1-1
...@@ -11,7 +11,7 @@ fn test__fixtfsi(a: f128, expected: i32) void {...@@ -11,7 +11,7 @@ fn test__fixtfsi(a: f128, expected: i32) void {
11}11}
1212
13test "fixtfsi" {13test "fixtfsi" {
14 if (@import("std").Target.current.isWindows()) {14 if (@import("std").Target.current.os.tag == .windows) {
15 // TODO https://github.com/ziglang/zig/issues/50815 // TODO https://github.com/ziglang/zig/issues/508
16 return error.SkipZigTest;16 return error.SkipZigTest;
17 }17 }
lib/std/special/compiler_rt/fixtfti_test.zig+1-1
...@@ -11,7 +11,7 @@ fn test__fixtfti(a: f128, expected: i128) void {...@@ -11,7 +11,7 @@ fn test__fixtfti(a: f128, expected: i128) void {
11}11}
1212
13test "fixtfti" {13test "fixtfti" {
14 if (@import("std").Target.current.isWindows()) {14 if (@import("std").Target.current.os.tag == .windows) {
15 // TODO https://github.com/ziglang/zig/issues/50815 // TODO https://github.com/ziglang/zig/issues/508
16 return error.SkipZigTest;16 return error.SkipZigTest;
17 }17 }
lib/std/special/compiler_rt/fixunstfdi_test.zig+1-1
...@@ -7,7 +7,7 @@ fn test__fixunstfdi(a: f128, expected: u64) void {...@@ -7,7 +7,7 @@ fn test__fixunstfdi(a: f128, expected: u64) void {
7}7}
88
9test "fixunstfdi" {9test "fixunstfdi" {
10 if (@import("std").Target.current.isWindows()) {10 if (@import("std").Target.current.os.tag == .windows) {
11 // TODO https://github.com/ziglang/zig/issues/50811 // TODO https://github.com/ziglang/zig/issues/508
12 return error.SkipZigTest;12 return error.SkipZigTest;
13 }13 }
lib/std/special/compiler_rt/fixunstfsi_test.zig+1-1
...@@ -9,7 +9,7 @@ fn test__fixunstfsi(a: f128, expected: u32) void {...@@ -9,7 +9,7 @@ fn test__fixunstfsi(a: f128, expected: u32) void {
9const inf128 = @bitCast(f128, @as(u128, 0x7fff0000000000000000000000000000));9const inf128 = @bitCast(f128, @as(u128, 0x7fff0000000000000000000000000000));
1010
11test "fixunstfsi" {11test "fixunstfsi" {
12 if (@import("std").Target.current.isWindows()) {12 if (@import("std").Target.current.os.tag == .windows) {
13 // TODO https://github.com/ziglang/zig/issues/50813 // TODO https://github.com/ziglang/zig/issues/508
14 return error.SkipZigTest;14 return error.SkipZigTest;
15 }15 }
lib/std/special/compiler_rt/fixunstfti_test.zig+1-1
...@@ -9,7 +9,7 @@ fn test__fixunstfti(a: f128, expected: u128) void {...@@ -9,7 +9,7 @@ fn test__fixunstfti(a: f128, expected: u128) void {
9const inf128 = @bitCast(f128, @as(u128, 0x7fff0000000000000000000000000000));9const inf128 = @bitCast(f128, @as(u128, 0x7fff0000000000000000000000000000));
1010
11test "fixunstfti" {11test "fixunstfti" {
12 if (@import("std").Target.current.isWindows()) {12 if (@import("std").Target.current.os.tag == .windows) {
13 // TODO https://github.com/ziglang/zig/issues/50813 // TODO https://github.com/ziglang/zig/issues/508
14 return error.SkipZigTest;14 return error.SkipZigTest;
15 }15 }
lib/std/special/compiler_rt/floattitf_test.zig+1-1
...@@ -7,7 +7,7 @@ fn test__floattitf(a: i128, expected: f128) void {...@@ -7,7 +7,7 @@ fn test__floattitf(a: i128, expected: f128) void {
7}7}
88
9test "floattitf" {9test "floattitf" {
10 if (@import("std").Target.current.isWindows()) {10 if (@import("std").Target.current.os.tag == .windows) {
11 // TODO https://github.com/ziglang/zig/issues/50811 // TODO https://github.com/ziglang/zig/issues/508
12 return error.SkipZigTest;12 return error.SkipZigTest;
13 }13 }
lib/std/special/compiler_rt/floatuntitf_test.zig+1-1
...@@ -7,7 +7,7 @@ fn test__floatuntitf(a: u128, expected: f128) void {...@@ -7,7 +7,7 @@ fn test__floatuntitf(a: u128, expected: f128) void {
7}7}
88
9test "floatuntitf" {9test "floatuntitf" {
10 if (@import("std").Target.current.isWindows()) {10 if (@import("std").Target.current.os.tag == .windows) {
11 // TODO https://github.com/ziglang/zig/issues/50811 // TODO https://github.com/ziglang/zig/issues/508
12 return error.SkipZigTest;12 return error.SkipZigTest;
13 }13 }
lib/std/special/compiler_rt/lshrti3.zig+1-1
...@@ -24,7 +24,7 @@ const twords = extern union {...@@ -24,7 +24,7 @@ const twords = extern union {
24 all: i128,24 all: i128,
25 s: S,25 s: S,
2626
27 const S = if (builtin.endian == builtin.Endian.Little)27 const S = if (builtin.endian == .Little)
28 struct {28 struct {
29 low: u64,29 low: u64,
30 high: u64,30 high: u64,
lib/std/special/compiler_rt/mulXf3_test.zig+1-1
...@@ -44,7 +44,7 @@ fn makeNaN128(rand: u64) f128 {...@@ -44,7 +44,7 @@ fn makeNaN128(rand: u64) f128 {
44 return float_result;44 return float_result;
45}45}
46test "multf3" {46test "multf3" {
47 if (@import("std").Target.current.isWindows()) {47 if (@import("std").Target.current.os.tag == .windows) {
48 // TODO https://github.com/ziglang/zig/issues/50848 // TODO https://github.com/ziglang/zig/issues/508
49 return error.SkipZigTest;49 return error.SkipZigTest;
50 }50 }
lib/std/special/compiler_rt/multi3.zig+1-1
...@@ -45,7 +45,7 @@ const twords = extern union {...@@ -45,7 +45,7 @@ const twords = extern union {
45 all: i128,45 all: i128,
46 s: S,46 s: S,
4747
48 const S = if (builtin.endian == builtin.Endian.Little)48 const S = if (builtin.endian == .Little)
49 struct {49 struct {
50 low: u64,50 low: u64,
51 high: u64,51 high: u64,
lib/std/special/compiler_rt/truncXfYf2.zig+6-6
...@@ -1,23 +1,23 @@...@@ -1,23 +1,23 @@
1const std = @import("std");1const std = @import("std");
22
3pub fn __truncsfhf2(a: f32) callconv(.C) u16 {3pub fn __truncsfhf2(a: f32) callconv(.C) u16 {
4 return @bitCast(u16, truncXfYf2(f16, f32, a));4 return @bitCast(u16, @call(.{ .modifier = .always_inline }, truncXfYf2, .{ f16, f32, a }));
5}5}
66
7pub fn __truncdfhf2(a: f64) callconv(.C) u16 {7pub fn __truncdfhf2(a: f64) callconv(.C) u16 {
8 return @bitCast(u16, truncXfYf2(f16, f64, a));8 return @bitCast(u16, @call(.{ .modifier = .always_inline }, truncXfYf2, .{ f16, f64, a }));
9}9}
1010
11pub fn __trunctfsf2(a: f128) callconv(.C) f32 {11pub fn __trunctfsf2(a: f128) callconv(.C) f32 {
12 return truncXfYf2(f32, f128, a);12 return @call(.{ .modifier = .always_inline }, truncXfYf2, .{ f32, f128, a });
13}13}
1414
15pub fn __trunctfdf2(a: f128) callconv(.C) f64 {15pub fn __trunctfdf2(a: f128) callconv(.C) f64 {
16 return truncXfYf2(f64, f128, a);16 return @call(.{ .modifier = .always_inline }, truncXfYf2, .{ f64, f128, a });
17}17}
1818
19pub fn __truncdfsf2(a: f64) callconv(.C) f32 {19pub fn __truncdfsf2(a: f64) callconv(.C) f32 {
20 return truncXfYf2(f32, f64, a);20 return @call(.{ .modifier = .always_inline }, truncXfYf2, .{ f32, f64, a });
21}21}
2222
23pub fn __aeabi_d2f(a: f64) callconv(.AAPCS) f32 {23pub fn __aeabi_d2f(a: f64) callconv(.AAPCS) f32 {
...@@ -35,7 +35,7 @@ pub fn __aeabi_f2h(a: f32) callconv(.AAPCS) u16 {...@@ -35,7 +35,7 @@ pub fn __aeabi_f2h(a: f32) callconv(.AAPCS) u16 {
35 return @call(.{ .modifier = .always_inline }, __truncsfhf2, .{a});35 return @call(.{ .modifier = .always_inline }, __truncsfhf2, .{a});
36}36}
3737
38inline fn truncXfYf2(comptime dst_t: type, comptime src_t: type, a: src_t) dst_t {38fn truncXfYf2(comptime dst_t: type, comptime src_t: type, a: src_t) dst_t {
39 const src_rep_t = std.meta.IntType(false, @typeInfo(src_t).Float.bits);39 const src_rep_t = std.meta.IntType(false, @typeInfo(src_t).Float.bits);
40 const dst_rep_t = std.meta.IntType(false, @typeInfo(dst_t).Float.bits);40 const dst_rep_t = std.meta.IntType(false, @typeInfo(dst_t).Float.bits);
41 const srcSigBits = std.math.floatMantissaBits(src_t);41 const srcSigBits = std.math.floatMantissaBits(src_t);
lib/std/special/compiler_rt/truncXfYf2_test.zig+2-2
...@@ -151,7 +151,7 @@ fn test__trunctfsf2(a: f128, expected: u32) void {...@@ -151,7 +151,7 @@ fn test__trunctfsf2(a: f128, expected: u32) void {
151}151}
152152
153test "trunctfsf2" {153test "trunctfsf2" {
154 if (@import("std").Target.current.isWindows()) {154 if (@import("std").Target.current.os.tag == .windows) {
155 // TODO https://github.com/ziglang/zig/issues/508155 // TODO https://github.com/ziglang/zig/issues/508
156 return error.SkipZigTest;156 return error.SkipZigTest;
157 }157 }
...@@ -190,7 +190,7 @@ fn test__trunctfdf2(a: f128, expected: u64) void {...@@ -190,7 +190,7 @@ fn test__trunctfdf2(a: f128, expected: u64) void {
190}190}
191191
192test "trunctfdf2" {192test "trunctfdf2" {
193 if (@import("std").Target.current.isWindows()) {193 if (@import("std").Target.current.os.tag == .windows) {
194 // TODO https://github.com/ziglang/zig/issues/508194 // TODO https://github.com/ziglang/zig/issues/508
195 return error.SkipZigTest;195 return error.SkipZigTest;
196 }196 }
lib/std/special/compiler_rt/udivmod.zig+2-2
...@@ -2,8 +2,8 @@ const builtin = @import("builtin");...@@ -2,8 +2,8 @@ const builtin = @import("builtin");
2const is_test = builtin.is_test;2const is_test = builtin.is_test;
33
4const low = switch (builtin.endian) {4const low = switch (builtin.endian) {
5 builtin.Endian.Big => 1,5 .Big => 1,
6 builtin.Endian.Little => 0,6 .Little => 0,
7};7};
8const high = 1 - low;8const high = 1 - low;
99
lib/std/special/init-exe/build.zig+10
...@@ -1,8 +1,18 @@...@@ -1,8 +1,18 @@
1const Builder = @import("std").build.Builder;1const Builder = @import("std").build.Builder;
22
3pub fn build(b: *Builder) void {3pub fn build(b: *Builder) void {
4 // Standard target options allows the person running `zig build` to choose
5 // what target to build for. Here we do not override the defaults, which
6 // means any target is allowed, and the default is native. Other options
7 // for restricting supported target set are available.
8 const target = b.standardTargetOptions(.{});
9
10 // Standard release options allow the person running `zig build` to select
11 // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
4 const mode = b.standardReleaseOptions();12 const mode = b.standardReleaseOptions();
13
5 const exe = b.addExecutable("$", "src/main.zig");14 const exe = b.addExecutable("$", "src/main.zig");
15 exe.setTarget(target);
6 exe.setBuildMode(mode);16 exe.setBuildMode(mode);
7 exe.install();17 exe.install();
818
lib/std/special/init-exe/src/main.zig+1-1
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const std = @import("std");1const std = @import("std");
22
3pub fn main() anyerror!void {3pub fn main() anyerror!void {
4 std.debug.warn("All your base are belong to us.\n", .{});4 std.debug.warn("All your codebase are belong to us.\n", .{});
5}5}
lib/std/spinlock.zig+1-1
...@@ -46,7 +46,7 @@ pub const SpinLock = struct {...@@ -46,7 +46,7 @@ pub const SpinLock = struct {
46 // and yielding for 380-410 iterations was found to be46 // and yielding for 380-410 iterations was found to be
47 // a nice sweet spot. Posix systems on the other hand,47 // a nice sweet spot. Posix systems on the other hand,
48 // especially linux, perform better by yielding the thread.48 // especially linux, perform better by yielding the thread.
49 switch (builtin.os) {49 switch (builtin.os.tag) {
50 .windows => loopHint(400),50 .windows => loopHint(400),
51 else => std.os.sched_yield() catch loopHint(1),51 else => std.os.sched_yield() catch loopHint(1),
52 }52 }
lib/std/start.zig+8-8
...@@ -12,7 +12,7 @@ const start_sym_name = if (builtin.arch.isMIPS()) "__start" else "_start";...@@ -12,7 +12,7 @@ const start_sym_name = if (builtin.arch.isMIPS()) "__start" else "_start";
1212
13comptime {13comptime {
14 if (builtin.output_mode == .Lib and builtin.link_mode == .Dynamic) {14 if (builtin.output_mode == .Lib and builtin.link_mode == .Dynamic) {
15 if (builtin.os == .windows and !@hasDecl(root, "_DllMainCRTStartup")) {15 if (builtin.os.tag == .windows and !@hasDecl(root, "_DllMainCRTStartup")) {
16 @export(_DllMainCRTStartup, .{ .name = "_DllMainCRTStartup" });16 @export(_DllMainCRTStartup, .{ .name = "_DllMainCRTStartup" });
17 }17 }
18 } else if (builtin.output_mode == .Exe or @hasDecl(root, "main")) {18 } else if (builtin.output_mode == .Exe or @hasDecl(root, "main")) {
...@@ -20,17 +20,17 @@ comptime {...@@ -20,17 +20,17 @@ comptime {
20 if (@typeInfo(@TypeOf(root.main)).Fn.calling_convention != .C) {20 if (@typeInfo(@TypeOf(root.main)).Fn.calling_convention != .C) {
21 @export(main, .{ .name = "main", .linkage = .Weak });21 @export(main, .{ .name = "main", .linkage = .Weak });
22 }22 }
23 } else if (builtin.os == .windows) {23 } else if (builtin.os.tag == .windows) {
24 if (!@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and24 if (!@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and
25 !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup"))25 !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup"))
26 {26 {
27 @export(WinMainCRTStartup, .{ .name = "WinMainCRTStartup" });27 @export(WinMainCRTStartup, .{ .name = "WinMainCRTStartup" });
28 }28 }
29 } else if (builtin.os == .uefi) {29 } else if (builtin.os.tag == .uefi) {
30 if (!@hasDecl(root, "EfiMain")) @export(EfiMain, .{ .name = "EfiMain" });30 if (!@hasDecl(root, "EfiMain")) @export(EfiMain, .{ .name = "EfiMain" });
31 } else if (builtin.arch.isWasm() and builtin.os == .freestanding) {31 } else if (builtin.arch.isWasm() and builtin.os.tag == .freestanding) {
32 if (!@hasDecl(root, start_sym_name)) @export(wasm_freestanding_start, .{ .name = start_sym_name });32 if (!@hasDecl(root, start_sym_name)) @export(wasm_freestanding_start, .{ .name = start_sym_name });
33 } else if (builtin.os != .other and builtin.os != .freestanding) {33 } else if (builtin.os.tag != .other and builtin.os.tag != .freestanding) {
34 if (!@hasDecl(root, start_sym_name)) @export(_start, .{ .name = start_sym_name });34 if (!@hasDecl(root, start_sym_name)) @export(_start, .{ .name = start_sym_name });
35 }35 }
36 }36 }
...@@ -78,7 +78,7 @@ fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv...@@ -78,7 +78,7 @@ fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv
78}78}
7979
80fn _start() callconv(.Naked) noreturn {80fn _start() callconv(.Naked) noreturn {
81 if (builtin.os == builtin.Os.wasi) {81 if (builtin.os.tag == .wasi) {
82 // This is marked inline because for some reason LLVM in release mode fails to inline it,82 // This is marked inline because for some reason LLVM in release mode fails to inline it,
83 // and we want fewer call frames in stack traces.83 // and we want fewer call frames in stack traces.
84 std.os.wasi.proc_exit(@call(.{ .modifier = .always_inline }, callMain, .{}));84 std.os.wasi.proc_exit(@call(.{ .modifier = .always_inline }, callMain, .{}));
...@@ -133,7 +133,7 @@ fn WinMainCRTStartup() callconv(.Stdcall) noreturn {...@@ -133,7 +133,7 @@ fn WinMainCRTStartup() callconv(.Stdcall) noreturn {
133133
134// TODO https://github.com/ziglang/zig/issues/265134// TODO https://github.com/ziglang/zig/issues/265
135fn posixCallMainAndExit() noreturn {135fn posixCallMainAndExit() noreturn {
136 if (builtin.os == builtin.Os.freebsd) {136 if (builtin.os.tag == .freebsd) {
137 @setAlignStack(16);137 @setAlignStack(16);
138 }138 }
139 const argc = starting_stack_ptr[0];139 const argc = starting_stack_ptr[0];
...@@ -144,7 +144,7 @@ fn posixCallMainAndExit() noreturn {...@@ -144,7 +144,7 @@ fn posixCallMainAndExit() noreturn {
144 while (envp_optional[envp_count]) |_| : (envp_count += 1) {}144 while (envp_optional[envp_count]) |_| : (envp_count += 1) {}
145 const envp = @ptrCast([*][*:0]u8, envp_optional)[0..envp_count];145 const envp = @ptrCast([*][*:0]u8, envp_optional)[0..envp_count];
146146
147 if (builtin.os == .linux) {147 if (builtin.os.tag == .linux) {
148 // Find the beginning of the auxiliary vector148 // Find the beginning of the auxiliary vector
149 const auxv = @ptrCast([*]std.elf.Auxv, @alignCast(@alignOf(usize), envp.ptr + envp_count + 1));149 const auxv = @ptrCast([*]std.elf.Auxv, @alignCast(@alignOf(usize), envp.ptr + envp_count + 1));
150 std.os.linux.elf_aux_maybe = auxv;150 std.os.linux.elf_aux_maybe = auxv;
lib/std/target.zig+602-619
...@@ -1,61 +1,291 @@...@@ -1,61 +1,291 @@
1const std = @import("std.zig");1const std = @import("std.zig");
2const mem = std.mem;2const mem = std.mem;
3const builtin = std.builtin;3const builtin = std.builtin;
4const Version = std.builtin.Version;
45
5/// TODO Nearly all the functions in this namespace would be6/// TODO Nearly all the functions in this namespace would be
6/// better off if https://github.com/ziglang/zig/issues/4257/// better off if https://github.com/ziglang/zig/issues/425
7/// was solved.8/// was solved.
8pub const Target = union(enum) {9pub const Target = struct {
9 Native: void,10 cpu: Cpu,
10 Cross: Cross,11 os: Os,
1112 abi: Abi,
12 pub const Os = enum {13
13 freestanding,14 pub const Os = struct {
14 ananas,15 tag: Tag,
15 cloudabi,16 version_range: VersionRange,
16 dragonfly,17
17 freebsd,18 pub const Tag = enum {
18 fuchsia,19 freestanding,
19 ios,20 ananas,
20 kfreebsd,21 cloudabi,
21 linux,22 dragonfly,
22 lv2,23 freebsd,
23 macosx,24 fuchsia,
24 netbsd,25 ios,
25 openbsd,26 kfreebsd,
26 solaris,27 linux,
27 windows,28 lv2,
28 haiku,29 macosx,
29 minix,30 netbsd,
30 rtems,31 openbsd,
31 nacl,32 solaris,
32 cnk,33 windows,
33 aix,34 haiku,
34 cuda,35 minix,
35 nvcl,36 rtems,
36 amdhsa,37 nacl,
37 ps4,38 cnk,
38 elfiamcu,39 aix,
39 tvos,40 cuda,
40 watchos,41 nvcl,
41 mesa3d,42 amdhsa,
42 contiki,43 ps4,
43 amdpal,44 elfiamcu,
44 hermit,45 tvos,
45 hurd,46 watchos,
46 wasi,47 mesa3d,
47 emscripten,48 contiki,
48 uefi,49 amdpal,
49 other,50 hermit,
5051 hurd,
51 pub fn parse(text: []const u8) !Os {52 wasi,
52 const info = @typeInfo(Os);53 emscripten,
53 inline for (info.Enum.fields) |field| {54 uefi,
54 if (mem.eql(u8, text, field.name)) {55 other,
55 return @field(Os, field.name);56
57 pub fn isDarwin(tag: Tag) bool {
58 return switch (tag) {
59 .ios, .macosx, .watchos, .tvos => true,
60 else => false,
61 };
62 }
63
64 pub fn dynamicLibSuffix(tag: Tag) [:0]const u8 {
65 if (tag.isDarwin()) {
66 return ".dylib";
67 }
68 switch (tag) {
69 .windows => return ".dll",
70 else => return ".so",
71 }
72 }
73 };
74
75 /// Based on NTDDI version constants from
76 /// https://docs.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt
77 pub const WindowsVersion = enum(u32) {
78 nt4 = 0x04000000,
79 win2k = 0x05000000,
80 xp = 0x05010000,
81 ws2003 = 0x05020000,
82 vista = 0x06000000,
83 win7 = 0x06010000,
84 win8 = 0x06020000,
85 win8_1 = 0x06030000,
86 win10 = 0x0A000000,
87 win10_th2 = 0x0A000001,
88 win10_rs1 = 0x0A000002,
89 win10_rs2 = 0x0A000003,
90 win10_rs3 = 0x0A000004,
91 win10_rs4 = 0x0A000005,
92 win10_rs5 = 0x0A000006,
93 win10_19h1 = 0x0A000007,
94 _,
95
96 pub const Range = struct {
97 min: WindowsVersion,
98 max: WindowsVersion,
99
100 pub fn includesVersion(self: Range, ver: WindowsVersion) bool {
101 return @enumToInt(ver) >= @enumToInt(self.min) and @enumToInt(ver) <= @enumToInt(self.max);
56 }102 }
103 };
104 };
105
106 pub const LinuxVersionRange = struct {
107 range: Version.Range,
108 glibc: Version,
109
110 pub fn includesVersion(self: LinuxVersionRange, ver: Version) bool {
111 return self.range.includesVersion(ver);
57 }112 }
58 return error.UnknownOperatingSystem;113 };
114
115 /// The version ranges here represent the minimum OS version to be supported
116 /// and the maximum OS version to be supported. The default values represent
117 /// the range that the Zig Standard Library bases its abstractions on.
118 ///
119 /// The minimum version of the range is the main setting to tweak for a target.
120 /// Usually, the maximum target OS version will remain the default, which is
121 /// the latest released version of the OS.
122 ///
123 /// To test at compile time if the target is guaranteed to support a given OS feature,
124 /// one should check that the minimum version of the range is greater than or equal to
125 /// the version the feature was introduced in.
126 ///
127 /// To test at compile time if the target certainly will not support a given OS feature,
128 /// one should check that the maximum version of the range is less than the version the
129 /// feature was introduced in.
130 ///
131 /// If neither of these cases apply, a runtime check should be used to determine if the
132 /// target supports a given OS feature.
133 ///
134 /// Binaries built with a given maximum version will continue to function on newer operating system
135 /// versions. However, such a binary may not take full advantage of the newer operating system APIs.
136 pub const VersionRange = union {
137 none: void,
138 semver: Version.Range,
139 linux: LinuxVersionRange,
140 windows: WindowsVersion.Range,
141
142 /// The default `VersionRange` represents the range that the Zig Standard Library
143 /// bases its abstractions on.
144 pub fn default(tag: Tag) VersionRange {
145 switch (tag) {
146 .freestanding,
147 .ananas,
148 .cloudabi,
149 .dragonfly,
150 .fuchsia,
151 .kfreebsd,
152 .lv2,
153 .solaris,
154 .haiku,
155 .minix,
156 .rtems,
157 .nacl,
158 .cnk,
159 .aix,
160 .cuda,
161 .nvcl,
162 .amdhsa,
163 .ps4,
164 .elfiamcu,
165 .mesa3d,
166 .contiki,
167 .amdpal,
168 .hermit,
169 .hurd,
170 .wasi,
171 .emscripten,
172 .uefi,
173 .other,
174 => return .{ .none = {} },
175
176 .freebsd => return .{
177 .semver = Version.Range{
178 .min = .{ .major = 12, .minor = 0 },
179 .max = .{ .major = 12, .minor = 1 },
180 },
181 },
182 .macosx => return .{
183 .semver = .{
184 .min = .{ .major = 10, .minor = 13 },
185 .max = .{ .major = 10, .minor = 15, .patch = 3 },
186 },
187 },
188 .ios => return .{
189 .semver = .{
190 .min = .{ .major = 12, .minor = 0 },
191 .max = .{ .major = 13, .minor = 4, .patch = 0 },
192 },
193 },
194 .watchos => return .{
195 .semver = .{
196 .min = .{ .major = 6, .minor = 0 },
197 .max = .{ .major = 6, .minor = 2, .patch = 0 },
198 },
199 },
200 .tvos => return .{
201 .semver = .{
202 .min = .{ .major = 13, .minor = 0 },
203 .max = .{ .major = 13, .minor = 4, .patch = 0 },
204 },
205 },
206 .netbsd => return .{
207 .semver = .{
208 .min = .{ .major = 8, .minor = 0 },
209 .max = .{ .major = 9, .minor = 0 },
210 },
211 },
212 .openbsd => return .{
213 .semver = .{
214 .min = .{ .major = 6, .minor = 6 },
215 .max = .{ .major = 6, .minor = 6 },
216 },
217 },
218
219 .linux => return .{
220 .linux = .{
221 .range = .{
222 .min = .{ .major = 3, .minor = 16 },
223 .max = .{ .major = 5, .minor = 5, .patch = 5 },
224 },
225 .glibc = .{ .major = 2, .minor = 17 },
226 },
227 },
228
229 .windows => return .{
230 .windows = .{
231 .min = .win8_1,
232 .max = .win10_19h1,
233 },
234 },
235 }
236 }
237 };
238
239 pub fn defaultVersionRange(tag: Tag) Os {
240 return .{
241 .tag = tag,
242 .version_range = VersionRange.default(tag),
243 };
244 }
245
246 pub fn requiresLibC(os: Os) bool {
247 return switch (os.tag) {
248 .freebsd,
249 .netbsd,
250 .macosx,
251 .ios,
252 .tvos,
253 .watchos,
254 .dragonfly,
255 .openbsd,
256 => true,
257
258 .linux,
259 .windows,
260 .freestanding,
261 .ananas,
262 .cloudabi,
263 .fuchsia,
264 .kfreebsd,
265 .lv2,
266 .solaris,
267 .haiku,
268 .minix,
269 .rtems,
270 .nacl,
271 .cnk,
272 .aix,
273 .cuda,
274 .nvcl,
275 .amdhsa,
276 .ps4,
277 .elfiamcu,
278 .mesa3d,
279 .contiki,
280 .amdpal,
281 .hermit,
282 .hurd,
283 .wasi,
284 .emscripten,
285 .uefi,
286 .other,
287 => false,
288 };
59 }289 }
60 };290 };
61291
...@@ -100,11 +330,10 @@ pub const Target = union(enum) {...@@ -100,11 +330,10 @@ pub const Target = union(enum) {
100 macabi,330 macabi,
101331
102 pub fn default(arch: Cpu.Arch, target_os: Os) Abi {332 pub fn default(arch: Cpu.Arch, target_os: Os) Abi {
103 switch (arch) {333 if (arch.isWasm()) {
104 .wasm32, .wasm64 => return .musl,334 return .musl;
105 else => {},
106 }335 }
107 switch (target_os) {336 switch (target_os.tag) {
108 .freestanding,337 .freestanding,
109 .ananas,338 .ananas,
110 .cloudabi,339 .cloudabi,
...@@ -149,14 +378,25 @@ pub const Target = union(enum) {...@@ -149,14 +378,25 @@ pub const Target = union(enum) {
149 }378 }
150 }379 }
151380
152 pub fn parse(text: []const u8) !Abi {381 pub fn isGnu(abi: Abi) bool {
153 const info = @typeInfo(Abi);382 return switch (abi) {
154 inline for (info.Enum.fields) |field| {383 .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => true,
155 if (mem.eql(u8, text, field.name)) {384 else => false,
156 return @field(Abi, field.name);385 };
157 }386 }
158 }387
159 return error.UnknownApplicationBinaryInterface;388 pub fn isMusl(abi: Abi) bool {
389 return switch (abi) {
390 .musl, .musleabi, .musleabihf => true,
391 else => false,
392 };
393 }
394
395 pub fn oFileExt(abi: Abi) [:0]const u8 {
396 return switch (abi) {
397 .msvc => ".obj",
398 else => ".o",
399 };
160 }400 }
161 };401 };
162402
...@@ -179,12 +419,6 @@ pub const Target = union(enum) {...@@ -179,12 +419,6 @@ pub const Target = union(enum) {
179 EfiRuntimeDriver,419 EfiRuntimeDriver,
180 };420 };
181421
182 pub const Cross = struct {
183 cpu: Cpu,
184 os: Os,
185 abi: Abi,
186 };
187
188 pub const Cpu = struct {422 pub const Cpu = struct {
189 /// Architecture423 /// Architecture
190 arch: Arch,424 arch: Arch,
...@@ -230,6 +464,12 @@ pub const Target = union(enum) {...@@ -230,6 +464,12 @@ pub const Target = union(enum) {
230 return Set{ .ints = [1]usize{0} ** usize_count };464 return Set{ .ints = [1]usize{0} ** usize_count };
231 }465 }
232466
467 pub fn isEmpty(set: Set) bool {
468 return for (set.ints) |x| {
469 if (x != 0) break false;
470 } else true;
471 }
472
233 pub fn isEnabled(set: Set, arch_feature_index: Index) bool {473 pub fn isEnabled(set: Set, arch_feature_index: Index) bool {
234 const usize_index = arch_feature_index / @bitSizeOf(usize);474 const usize_index = arch_feature_index / @bitSizeOf(usize);
235 const bit_index = @intCast(ShiftInt, arch_feature_index % @bitSizeOf(usize));475 const bit_index = @intCast(ShiftInt, arch_feature_index % @bitSizeOf(usize));
...@@ -256,6 +496,15 @@ pub const Target = union(enum) {...@@ -256,6 +496,15 @@ pub const Target = union(enum) {
256 set.ints[usize_index] &= ~(@as(usize, 1) << bit_index);496 set.ints[usize_index] &= ~(@as(usize, 1) << bit_index);
257 }497 }
258498
499 /// Removes the specified feature but not its dependents.
500 pub fn removeFeatureSet(set: *Set, other_set: Set) void {
501 // TODO should be able to use binary not on @Vector type.
502 // https://github.com/ziglang/zig/issues/903
503 for (set.ints) |*int, i| {
504 int.* &= ~other_set.ints[i];
505 }
506 }
507
259 pub fn populateDependencies(set: *Set, all_features_list: []const Cpu.Feature) void {508 pub fn populateDependencies(set: *Set, all_features_list: []const Cpu.Feature) void {
260 @setEvalBranchQuota(1000000);509 @setEvalBranchQuota(1000000);
261510
...@@ -393,7 +642,7 @@ pub const Target = union(enum) {...@@ -393,7 +642,7 @@ pub const Target = union(enum) {
393 return cpu;642 return cpu;
394 }643 }
395 }644 }
396 return error.UnknownCpu;645 return error.UnknownCpuModel;
397 }646 }
398647
399 pub fn toElfMachine(arch: Arch) std.elf.EM {648 pub fn toElfMachine(arch: Arch) std.elf.EM {
...@@ -509,6 +758,66 @@ pub const Target = union(enum) {...@@ -509,6 +758,66 @@ pub const Target = union(enum) {
509 };758 };
510 }759 }
511760
761 pub fn ptrBitWidth(arch: Arch) u32 {
762 switch (arch) {
763 .avr,
764 .msp430,
765 => return 16,
766
767 .arc,
768 .arm,
769 .armeb,
770 .hexagon,
771 .le32,
772 .mips,
773 .mipsel,
774 .powerpc,
775 .r600,
776 .riscv32,
777 .sparc,
778 .sparcel,
779 .tce,
780 .tcele,
781 .thumb,
782 .thumbeb,
783 .i386,
784 .xcore,
785 .nvptx,
786 .amdil,
787 .hsail,
788 .spir,
789 .kalimba,
790 .shave,
791 .lanai,
792 .wasm32,
793 .renderscript32,
794 .aarch64_32,
795 => return 32,
796
797 .aarch64,
798 .aarch64_be,
799 .mips64,
800 .mips64el,
801 .powerpc64,
802 .powerpc64le,
803 .riscv64,
804 .x86_64,
805 .nvptx64,
806 .le64,
807 .amdil64,
808 .hsail64,
809 .spir64,
810 .wasm64,
811 .renderscript64,
812 .amdgcn,
813 .bpfel,
814 .bpfeb,
815 .sparcv9,
816 .s390x,
817 => return 64,
818 }
819 }
820
512 /// Returns a name that matches the lib/std/target/* directory name.821 /// Returns a name that matches the lib/std/target/* directory name.
513 pub fn genericName(arch: Arch) []const u8 {822 pub fn genericName(arch: Arch) []const u8 {
514 return switch (arch) {823 return switch (arch) {
...@@ -576,16 +885,6 @@ pub const Target = union(enum) {...@@ -576,16 +885,6 @@ pub const Target = union(enum) {
576 else => &[0]*const Model{},885 else => &[0]*const Model{},
577 };886 };
578 }887 }
579
580 pub fn parse(text: []const u8) !Arch {
581 const info = @typeInfo(Arch);
582 inline for (info.Enum.fields) |field| {
583 if (mem.eql(u8, text, field.name)) {
584 return @as(Arch, @field(Arch, field.name));
585 }
586 }
587 return error.UnknownArchitecture;
588 }
589 };888 };
590889
591 pub const Model = struct {890 pub const Model = struct {
...@@ -602,524 +901,172 @@ pub const Target = union(enum) {...@@ -602,524 +901,172 @@ pub const Target = union(enum) {
602 .features = features,901 .features = features,
603 };902 };
604 }903 }
904
905 pub fn baseline(arch: Arch) *const Model {
906 const S = struct {
907 const generic_model = Model{
908 .name = "generic",
909 .llvm_name = null,
910 .features = Cpu.Feature.Set.empty,
911 };
912 };
913 return switch (arch) {
914 .arm, .armeb, .thumb, .thumbeb => &arm.cpu.baseline,
915 .aarch64, .aarch64_be, .aarch64_32 => &aarch64.cpu.generic,
916 .avr => &avr.cpu.avr1,
917 .bpfel, .bpfeb => &bpf.cpu.generic,
918 .hexagon => &hexagon.cpu.generic,
919 .mips, .mipsel => &mips.cpu.mips32,
920 .mips64, .mips64el => &mips.cpu.mips64,
921 .msp430 => &msp430.cpu.generic,
922 .powerpc, .powerpc64, .powerpc64le => &powerpc.cpu.generic,
923 .amdgcn => &amdgpu.cpu.generic,
924 .riscv32 => &riscv.cpu.baseline_rv32,
925 .riscv64 => &riscv.cpu.baseline_rv64,
926 .sparc, .sparcv9, .sparcel => &sparc.cpu.generic,
927 .s390x => &systemz.cpu.generic,
928 .i386 => &x86.cpu.pentium4,
929 .x86_64 => &x86.cpu.x86_64,
930 .nvptx, .nvptx64 => &nvptx.cpu.sm_20,
931 .wasm32, .wasm64 => &wasm.cpu.generic,
932
933 else => &S.generic_model,
934 };
935 }
605 };936 };
606937
607 /// The "default" set of CPU features for cross-compiling. A conservative set938 /// The "default" set of CPU features for cross-compiling. A conservative set
608 /// of features that is expected to be supported on most available hardware.939 /// of features that is expected to be supported on most available hardware.
609 pub fn baseline(arch: Arch) Cpu {940 pub fn baseline(arch: Arch) Cpu {
610 const S = struct {941 return Model.baseline(arch).toCpu(arch);
611 const generic_model = Model{
612 .name = "generic",
613 .llvm_name = null,
614 .features = Cpu.Feature.Set.empty,
615 };
616 };
617 const model = switch (arch) {
618 .arm, .armeb, .thumb, .thumbeb => &arm.cpu.baseline,
619 .aarch64, .aarch64_be, .aarch64_32 => &aarch64.cpu.generic,
620 .avr => &avr.cpu.avr1,
621 .bpfel, .bpfeb => &bpf.cpu.generic,
622 .hexagon => &hexagon.cpu.generic,
623 .mips, .mipsel => &mips.cpu.mips32,
624 .mips64, .mips64el => &mips.cpu.mips64,
625 .msp430 => &msp430.cpu.generic,
626 .powerpc, .powerpc64, .powerpc64le => &powerpc.cpu.generic,
627 .amdgcn => &amdgpu.cpu.generic,
628 .riscv32 => &riscv.cpu.baseline_rv32,
629 .riscv64 => &riscv.cpu.baseline_rv64,
630 .sparc, .sparcv9, .sparcel => &sparc.cpu.generic,
631 .s390x => &systemz.cpu.generic,
632 .i386 => &x86.cpu.pentium4,
633 .x86_64 => &x86.cpu.x86_64,
634 .nvptx, .nvptx64 => &nvptx.cpu.sm_20,
635 .wasm32, .wasm64 => &wasm.cpu.generic,
636
637 else => &S.generic_model,
638 };
639 return model.toCpu(arch);
640 }942 }
641 };943 };
642944
643 pub const current = Target{945 pub const current = Target{
644 .Cross = Cross{946 .cpu = builtin.cpu,
645 .cpu = builtin.cpu,947 .os = builtin.os,
646 .os = builtin.os,948 .abi = builtin.abi,
647 .abi = builtin.abi,
648 },
649 };949 };
650950
651 pub const stack_align = 16;951 pub const stack_align = 16;
652952
653 pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 {953 pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 {
654 return std.fmt.allocPrint(allocator, "{}-{}-{}", .{954 return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator);
655 @tagName(self.getArch()),
656 @tagName(self.getOs()),
657 @tagName(self.getAbi()),
658 });
659 }
660
661 /// Returned slice must be freed by the caller.
662 pub fn vcpkgTriplet(allocator: *mem.Allocator, target: Target, linkage: std.build.VcpkgLinkage) ![]const u8 {
663 const arch = switch (target.getArch()) {
664 .i386 => "x86",
665 .x86_64 => "x64",
666
667 .arm,
668 .armeb,
669 .thumb,
670 .thumbeb,
671 .aarch64_32,
672 => "arm",
673
674 .aarch64,
675 .aarch64_be,
676 => "arm64",
677
678 else => return error.VcpkgNoSuchArchitecture,
679 };
680
681 const os = switch (target.getOs()) {
682 .windows => "windows",
683 .linux => "linux",
684 .macosx => "macos",
685 else => return error.VcpkgNoSuchOs,
686 };
687
688 if (linkage == .Static) {
689 return try mem.join(allocator, "-", &[_][]const u8{ arch, os, "static" });
690 } else {
691 return try mem.join(allocator, "-", &[_][]const u8{ arch, os });
692 }
693 }955 }
694956
695 pub fn allocDescription(self: Target, allocator: *mem.Allocator) ![]u8 {957 pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![:0]u8 {
696 // TODO is there anything else worthy of the description that is not958 return std.fmt.allocPrint0(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });
697 // already captured in the triple?
698 return self.zigTriple(allocator);
699 }959 }
700960
701 pub fn zigTripleNoSubArch(self: Target, allocator: *mem.Allocator) ![]u8 {961 pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 {
702 return std.fmt.allocPrint(allocator, "{}-{}-{}", .{962 return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi);
703 @tagName(self.getArch()),
704 @tagName(self.getOs()),
705 @tagName(self.getAbi()),
706 });
707 }963 }
708964
709 pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 {965 pub fn oFileExt(self: Target) [:0]const u8 {
710 return std.fmt.allocPrint(allocator, "{}-{}-{}", .{966 return self.abi.oFileExt();
711 @tagName(self.getArch()),
712 @tagName(self.getOs()),
713 @tagName(self.getAbi()),
714 });
715 }967 }
716968
717 pub const ParseOptions = struct {969 pub fn exeFileExtSimple(cpu_arch: Cpu.Arch, os_tag: Os.Tag) [:0]const u8 {
718 /// This is sometimes called a "triple". It looks roughly like this:970 switch (os_tag) {
719 /// riscv64-linux-gnu971 .windows => return ".exe",
720 /// The fields are, respectively:972 .uefi => return ".efi",
721 /// * CPU Architecture973 else => if (cpu_arch.isWasm()) {
722 /// * Operating System974 return ".wasm";
723 /// * C ABI (optional)975 } else {
724 arch_os_abi: []const u8,976 return "";
725977 },
726 /// Looks like "name+a+b-c-d+e", where "name" is a CPU Model name, "a", "b", and "e"
727 /// are examples of CPU features to add to the set, and "c" and "d" are examples of CPU features
728 /// to remove from the set.
729 cpu_features: []const u8 = "baseline",
730
731 /// If this is provided, the function will populate some information about parsing failures,
732 /// so that user-friendly error messages can be delivered.
733 diagnostics: ?*Diagnostics = null,
734
735 pub const Diagnostics = struct {
736 /// If the architecture was determined, this will be populated.
737 arch: ?Cpu.Arch = null,
738
739 /// If the OS was determined, this will be populated.
740 os: ?Os = null,
741
742 /// If the ABI was determined, this will be populated.
743 abi: ?Abi = null,
744
745 /// If the CPU name was determined, this will be populated.
746 cpu_name: ?[]const u8 = null,
747
748 /// If error.UnknownCpuFeature is returned, this will be populated.
749 unknown_feature_name: ?[]const u8 = null,
750 };
751 };
752
753 pub fn parse(args: ParseOptions) !Target {
754 var dummy_diags: ParseOptions.Diagnostics = undefined;
755 var diags = args.diagnostics orelse &dummy_diags;
756
757 var it = mem.separate(args.arch_os_abi, "-");
758 const arch_name = it.next() orelse return error.MissingArchitecture;
759 const arch = try Cpu.Arch.parse(arch_name);
760 diags.arch = arch;
761
762 const os_name = it.next() orelse return error.MissingOperatingSystem;
763 const os = try Os.parse(os_name);
764 diags.os = os;
765
766 const abi_name = it.next();
767 const abi = if (abi_name) |n| try Abi.parse(n) else Abi.default(arch, os);
768 diags.abi = abi;
769
770 if (it.next() != null) return error.UnexpectedExtraField;
771
772 const all_features = arch.allFeaturesList();
773 var index: usize = 0;
774 while (index < args.cpu_features.len and
775 args.cpu_features[index] != '+' and
776 args.cpu_features[index] != '-')
777 {
778 index += 1;
779 }978 }
780 const cpu_name = args.cpu_features[0..index];
781 diags.cpu_name = cpu_name;
782
783 const cpu: Cpu = if (mem.eql(u8, cpu_name, "baseline")) Cpu.baseline(arch) else blk: {
784 const cpu_model = try arch.parseCpuModel(cpu_name);
785
786 var set = cpu_model.features;
787 while (index < args.cpu_features.len) {
788 const op = args.cpu_features[index];
789 index += 1;
790 const start = index;
791 while (index < args.cpu_features.len and
792 args.cpu_features[index] != '+' and
793 args.cpu_features[index] != '-')
794 {
795 index += 1;
796 }
797 const feature_name = args.cpu_features[start..index];
798 for (all_features) |feature, feat_index_usize| {
799 const feat_index = @intCast(Cpu.Feature.Set.Index, feat_index_usize);
800 if (mem.eql(u8, feature_name, feature.name)) {
801 switch (op) {
802 '+' => set.addFeature(feat_index),
803 '-' => set.removeFeature(feat_index),
804 else => unreachable,
805 }
806 break;
807 }
808 } else {
809 diags.unknown_feature_name = feature_name;
810 return error.UnknownCpuFeature;
811 }
812 }
813 set.populateDependencies(all_features);
814 break :blk .{
815 .arch = arch,
816 .model = cpu_model,
817 .features = set,
818 };
819 };
820 var cross = Cross{
821 .cpu = cpu,
822 .os = os,
823 .abi = abi,
824 };
825 return Target{ .Cross = cross };
826 }979 }
827980
828 pub fn oFileExt(self: Target) []const u8 {981 pub fn exeFileExt(self: Target) [:0]const u8 {
829 return switch (self.getAbi()) {982 return exeFileExtSimple(self.cpu.arch, self.os.tag);
830 .msvc => ".obj",
831 else => ".o",
832 };
833 }983 }
834984
835 pub fn exeFileExt(self: Target) []const u8 {985 pub fn staticLibSuffix_cpu_arch_abi(cpu_arch: Cpu.Arch, abi: Abi) [:0]const u8 {
836 if (self.isWindows()) {986 if (cpu_arch.isWasm()) {
837 return ".exe";
838 } else if (self.isUefi()) {
839 return ".efi";
840 } else if (self.isWasm()) {
841 return ".wasm";987 return ".wasm";
842 } else {
843 return "";
844 }988 }
845 }989 switch (abi) {
846
847 pub fn staticLibSuffix(self: Target) []const u8 {
848 if (self.isWasm()) {
849 return ".wasm";
850 }
851 switch (self.getAbi()) {
852 .msvc => return ".lib",990 .msvc => return ".lib",
853 else => return ".a",991 else => return ".a",
854 }992 }
855 }993 }
856994
857 pub fn dynamicLibSuffix(self: Target) []const u8 {995 pub fn staticLibSuffix(self: Target) [:0]const u8 {
858 if (self.isDarwin()) {996 return staticLibSuffix_cpu_arch_abi(self.cpu.arch, self.abi);
859 return ".dylib";
860 }
861 switch (self.getOs()) {
862 .windows => return ".dll",
863 else => return ".so",
864 }
865 }997 }
866998
867 pub fn libPrefix(self: Target) []const u8 {999 pub fn dynamicLibSuffix(self: Target) [:0]const u8 {
868 if (self.isWasm()) {1000 return self.os.tag.dynamicLibSuffix();
1001 }
1002
1003 pub fn libPrefix_cpu_arch_abi(cpu_arch: Cpu.Arch, abi: Abi) [:0]const u8 {
1004 if (cpu_arch.isWasm()) {
869 return "";1005 return "";
870 }1006 }
871 switch (self.getAbi()) {1007 switch (abi) {
872 .msvc => return "",1008 .msvc => return "",
873 else => return "lib",1009 else => return "lib",
874 }1010 }
875 }1011 }
8761012
877 pub fn getOs(self: Target) Os {1013 pub fn libPrefix(self: Target) [:0]const u8 {
878 return switch (self) {1014 return libPrefix_cpu_arch_abi(self.cpu.arch, self.abi);
879 .Native => builtin.os,
880 .Cross => |t| t.os,
881 };
882 }1015 }
8831016
884 pub fn getCpu(self: Target) Cpu {1017 pub fn getObjectFormatSimple(os_tag: Os.Tag, cpu_arch: Cpu.Arch) ObjectFormat {
885 return switch (self) {1018 if (os_tag == .windows or os_tag == .uefi) {
886 .Native => builtin.cpu,1019 return .coff;
887 .Cross => |cross| cross.cpu,1020 } else if (os_tag.isDarwin()) {
888 };1021 return .macho;
889 }1022 }
8901023 if (cpu_arch.isWasm()) {
891 pub fn getArch(self: Target) Cpu.Arch {1024 return .wasm;
892 return self.getCpu().arch;
893 }
894
895 pub fn getAbi(self: Target) Abi {
896 switch (self) {
897 .Native => return builtin.abi,
898 .Cross => |t| return t.abi,
899 }1025 }
1026 return .elf;
900 }1027 }
9011028
902 pub fn getObjectFormat(self: Target) ObjectFormat {1029 pub fn getObjectFormat(self: Target) ObjectFormat {
903 switch (self) {1030 return getObjectFormatSimple(self.os.tag, self.cpu.arch);
904 .Native => return @import("builtin").object_format,
905 .Cross => blk: {
906 if (self.isWindows() or self.isUefi()) {
907 return .coff;
908 } else if (self.isDarwin()) {
909 return .macho;
910 }
911 if (self.isWasm()) {
912 return .wasm;
913 }
914 return .elf;
915 },
916 }
917 }1031 }
9181032
919 pub fn isMinGW(self: Target) bool {1033 pub fn isMinGW(self: Target) bool {
920 return self.isWindows() and self.isGnu();1034 return self.os.tag == .windows and self.isGnu();
921 }1035 }
9221036
923 pub fn isGnu(self: Target) bool {1037 pub fn isGnu(self: Target) bool {
924 return switch (self.getAbi()) {1038 return self.abi.isGnu();
925 .gnu, .gnuabin32, .gnuabi64, .gnueabi, .gnueabihf, .gnux32 => true,
926 else => false,
927 };
928 }1039 }
9291040
930 pub fn isMusl(self: Target) bool {1041 pub fn isMusl(self: Target) bool {
931 return switch (self.getAbi()) {1042 return self.abi.isMusl();
932 .musl, .musleabi, .musleabihf => true,
933 else => false,
934 };
935 }
936
937 pub fn isDarwin(self: Target) bool {
938 return switch (self.getOs()) {
939 .ios, .macosx, .watchos, .tvos => true,
940 else => false,
941 };
942 }
943
944 pub fn isWindows(self: Target) bool {
945 return switch (self.getOs()) {
946 .windows => true,
947 else => false,
948 };
949 }
950
951 pub fn isLinux(self: Target) bool {
952 return switch (self.getOs()) {
953 .linux => true,
954 else => false,
955 };
956 }1043 }
9571044
958 pub fn isAndroid(self: Target) bool {1045 pub fn isAndroid(self: Target) bool {
959 return switch (self.getAbi()) {1046 return switch (self.abi) {
960 .android => true,1047 .android => true,
961 else => false,1048 else => false,
962 };1049 };
963 }1050 }
9641051
965 pub fn isDragonFlyBSD(self: Target) bool {
966 return switch (self.getOs()) {
967 .dragonfly => true,
968 else => false,
969 };
970 }
971
972 pub fn isUefi(self: Target) bool {
973 return switch (self.getOs()) {
974 .uefi => true,
975 else => false,
976 };
977 }
978
979 pub fn isWasm(self: Target) bool {1052 pub fn isWasm(self: Target) bool {
980 return switch (self.getArch()) {1053 return self.cpu.arch.isWasm();
981 .wasm32, .wasm64 => true,
982 else => false,
983 };
984 }
985
986 pub fn isFreeBSD(self: Target) bool {
987 return switch (self.getOs()) {
988 .freebsd => true,
989 else => false,
990 };
991 }1054 }
9921055
993 pub fn isNetBSD(self: Target) bool {1056 pub fn isDarwin(self: Target) bool {
994 return switch (self.getOs()) {1057 return self.os.tag.isDarwin();
995 .netbsd => true,
996 else => false,
997 };
998 }1058 }
9991059
1000 pub fn wantSharedLibSymLinks(self: Target) bool {1060 pub fn isGnuLibC_os_tag_abi(os_tag: Os.Tag, abi: Abi) bool {
1001 return !self.isWindows();1061 return os_tag == .linux and abi.isGnu();
1002 }1062 }
10031063
1004 pub fn osRequiresLibC(self: Target) bool {1064 pub fn isGnuLibC(self: Target) bool {
1005 return self.isDarwin() or self.isFreeBSD() or self.isNetBSD();1065 return isGnuLibC_os_tag_abi(self.os.tag, self.abi);
1006 }
1007
1008 pub fn getArchPtrBitWidth(self: Target) u32 {
1009 switch (self.getArch()) {
1010 .avr,
1011 .msp430,
1012 => return 16,
1013
1014 .arc,
1015 .arm,
1016 .armeb,
1017 .hexagon,
1018 .le32,
1019 .mips,
1020 .mipsel,
1021 .powerpc,
1022 .r600,
1023 .riscv32,
1024 .sparc,
1025 .sparcel,
1026 .tce,
1027 .tcele,
1028 .thumb,
1029 .thumbeb,
1030 .i386,
1031 .xcore,
1032 .nvptx,
1033 .amdil,
1034 .hsail,
1035 .spir,
1036 .kalimba,
1037 .shave,
1038 .lanai,
1039 .wasm32,
1040 .renderscript32,
1041 .aarch64_32,
1042 => return 32,
1043
1044 .aarch64,
1045 .aarch64_be,
1046 .mips64,
1047 .mips64el,
1048 .powerpc64,
1049 .powerpc64le,
1050 .riscv64,
1051 .x86_64,
1052 .nvptx64,
1053 .le64,
1054 .amdil64,
1055 .hsail64,
1056 .spir64,
1057 .wasm64,
1058 .renderscript64,
1059 .amdgcn,
1060 .bpfel,
1061 .bpfeb,
1062 .sparcv9,
1063 .s390x,
1064 => return 64,
1065 }
1066 }1066 }
10671067
1068 pub fn supportsNewStackCall(self: Target) bool {1068 pub fn supportsNewStackCall(self: Target) bool {
1069 return !self.isWasm();1069 return !self.cpu.arch.isWasm();
1070 }
1071
1072 pub const Executor = union(enum) {
1073 native,
1074 qemu: []const u8,
1075 wine: []const u8,
1076 wasmtime: []const u8,
1077 unavailable,
1078 };
1079
1080 pub fn getExternalExecutor(self: Target) Executor {
1081 if (@as(@TagType(Target), self) == .Native) return .native;
1082
1083 // If the target OS matches the host OS, we can use QEMU to emulate a foreign architecture.
1084 if (self.getOs() == builtin.os) {
1085 return switch (self.getArch()) {
1086 .aarch64 => Executor{ .qemu = "qemu-aarch64" },
1087 .aarch64_be => Executor{ .qemu = "qemu-aarch64_be" },
1088 .arm => Executor{ .qemu = "qemu-arm" },
1089 .armeb => Executor{ .qemu = "qemu-armeb" },
1090 .i386 => Executor{ .qemu = "qemu-i386" },
1091 .mips => Executor{ .qemu = "qemu-mips" },
1092 .mipsel => Executor{ .qemu = "qemu-mipsel" },
1093 .mips64 => Executor{ .qemu = "qemu-mips64" },
1094 .mips64el => Executor{ .qemu = "qemu-mips64el" },
1095 .powerpc => Executor{ .qemu = "qemu-ppc" },
1096 .powerpc64 => Executor{ .qemu = "qemu-ppc64" },
1097 .powerpc64le => Executor{ .qemu = "qemu-ppc64le" },
1098 .riscv32 => Executor{ .qemu = "qemu-riscv32" },
1099 .riscv64 => Executor{ .qemu = "qemu-riscv64" },
1100 .s390x => Executor{ .qemu = "qemu-s390x" },
1101 .sparc => Executor{ .qemu = "qemu-sparc" },
1102 .x86_64 => Executor{ .qemu = "qemu-x86_64" },
1103 else => return .unavailable,
1104 };
1105 }
1106
1107 if (self.isWindows()) {
1108 switch (self.getArchPtrBitWidth()) {
1109 32 => return Executor{ .wine = "wine" },
1110 64 => return Executor{ .wine = "wine64" },
1111 else => return .unavailable,
1112 }
1113 }
1114
1115 if (self.getOs() == .wasi) {
1116 switch (self.getArchPtrBitWidth()) {
1117 32 => return Executor{ .wasmtime = "wasmtime" },
1118 else => return .unavailable,
1119 }
1120 }
1121
1122 return .unavailable;
1123 }1070 }
11241071
1125 pub const FloatAbi = enum {1072 pub const FloatAbi = enum {
...@@ -1129,7 +1076,7 @@ pub const Target = union(enum) {...@@ -1129,7 +1076,7 @@ pub const Target = union(enum) {
1129 };1076 };
11301077
1131 pub fn getFloatAbi(self: Target) FloatAbi {1078 pub fn getFloatAbi(self: Target) FloatAbi {
1132 return switch (self.getAbi()) {1079 return switch (self.abi) {
1133 .gnueabihf,1080 .gnueabihf,
1134 .eabihf,1081 .eabihf,
1135 .musleabihf,1082 .musleabihf,
...@@ -1139,13 +1086,10 @@ pub const Target = union(enum) {...@@ -1139,13 +1086,10 @@ pub const Target = union(enum) {
1139 }1086 }
11401087
1141 pub fn hasDynamicLinker(self: Target) bool {1088 pub fn hasDynamicLinker(self: Target) bool {
1142 switch (self.getArch()) {1089 if (self.cpu.arch.isWasm()) {
1143 .wasm32,1090 return false;
1144 .wasm64,
1145 => return false,
1146 else => {},
1147 }1091 }
1148 switch (self.getOs()) {1092 switch (self.os.tag) {
1149 .freestanding,1093 .freestanding,
1150 .ios,1094 .ios,
1151 .tvos,1095 .tvos,
...@@ -1160,65 +1104,93 @@ pub const Target = union(enum) {...@@ -1160,65 +1104,93 @@ pub const Target = union(enum) {
1160 }1104 }
1161 }1105 }
11621106
1163 /// Caller owns returned memory.1107 pub const DynamicLinker = struct {
1164 pub fn getStandardDynamicLinkerPath(1108 /// Contains the memory used to store the dynamic linker path. This field should
1165 self: Target,1109 /// not be used directly. See `get` and `set`. This field exists so that this API requires no allocator.
1166 allocator: *mem.Allocator,1110 buffer: [255]u8 = undefined,
1167 ) error{1111
1168 OutOfMemory,1112 /// Used to construct the dynamic linker path. This field should not be used
1169 UnknownDynamicLinkerPath,1113 /// directly. See `get` and `set`.
1170 TargetHasNoDynamicLinker,1114 max_byte: ?u8 = null,
1171 }![:0]u8 {1115
1172 const a = allocator;1116 /// Asserts that the length is less than or equal to 255 bytes.
1173 if (self.isAndroid()) {1117 pub fn init(dl_or_null: ?[]const u8) DynamicLinker {
1174 return mem.dupeZ(a, u8, if (self.getArchPtrBitWidth() == 64)1118 var result: DynamicLinker = undefined;
1175 "/system/bin/linker64"1119 result.set(dl_or_null);
1176 else1120 return result;
1177 "/system/bin/linker");
1178 }1121 }
11791122
1180 if (self.isMusl()) {1123 /// The returned memory has the same lifetime as the `DynamicLinker`.
1181 var result = try std.Buffer.init(allocator, "/lib/ld-musl-");1124 pub fn get(self: *const DynamicLinker) ?[]const u8 {
1182 defer result.deinit();1125 const m: usize = self.max_byte orelse return null;
11831126 return self.buffer[0 .. m + 1];
1184 var is_arm = false;1127 }
1185 switch (self.getArch()) {1128
1186 .arm, .thumb => {1129 /// Asserts that the length is less than or equal to 255 bytes.
1187 try result.append("arm");1130 pub fn set(self: *DynamicLinker, dl_or_null: ?[]const u8) void {
1188 is_arm = true;1131 if (dl_or_null) |dl| {
1189 },1132 mem.copy(u8, &self.buffer, dl);
1190 .armeb, .thumbeb => {1133 self.max_byte = @intCast(u8, dl.len - 1);
1191 try result.append("armeb");1134 } else {
1192 is_arm = true;1135 self.max_byte = null;
1193 },1136 }
1194 else => |arch| try result.append(@tagName(arch)),1137 }
1138 };
1139
1140 pub fn standardDynamicLinkerPath(self: Target) DynamicLinker {
1141 var result: DynamicLinker = .{};
1142 const S = struct {
1143 fn print(r: *DynamicLinker, comptime fmt: []const u8, args: var) DynamicLinker {
1144 r.max_byte = @intCast(u8, (std.fmt.bufPrint(&r.buffer, fmt, args) catch unreachable).len - 1);
1145 return r.*;
1195 }1146 }
1196 if (is_arm and self.getFloatAbi() == .hard) {1147 fn copy(r: *DynamicLinker, s: []const u8) DynamicLinker {
1197 try result.append("hf");1148 mem.copy(u8, &r.buffer, s);
1149 r.max_byte = @intCast(u8, s.len - 1);
1150 return r.*;
1198 }1151 }
1199 try result.append(".so.1");1152 };
1200 return result.toOwnedSlice();1153 const print = S.print;
1154 const copy = S.copy;
1155
1156 if (self.isAndroid()) {
1157 const suffix = if (self.cpu.arch.ptrBitWidth() == 64) "64" else "";
1158 return print(&result, "/system/bin/linker{}", .{suffix});
1201 }1159 }
12021160
1203 switch (self.getOs()) {1161 if (self.isMusl()) {
1204 .freebsd => return mem.dupeZ(a, u8, "/libexec/ld-elf.so.1"),1162 const is_arm = switch (self.cpu.arch) {
1205 .netbsd => return mem.dupeZ(a, u8, "/libexec/ld.elf_so"),1163 .arm, .armeb, .thumb, .thumbeb => true,
1206 .dragonfly => return mem.dupeZ(a, u8, "/libexec/ld-elf.so.2"),1164 else => false,
1207 .linux => switch (self.getArch()) {1165 };
1166 const arch_part = switch (self.cpu.arch) {
1167 .arm, .thumb => "arm",
1168 .armeb, .thumbeb => "armeb",
1169 else => |arch| @tagName(arch),
1170 };
1171 const arch_suffix = if (is_arm and self.getFloatAbi() == .hard) "hf" else "";
1172 return print(&result, "/lib/ld-musl-{}{}.so.1", .{ arch_part, arch_suffix });
1173 }
1174
1175 switch (self.os.tag) {
1176 .freebsd => return copy(&result, "/libexec/ld-elf.so.1"),
1177 .netbsd => return copy(&result, "/libexec/ld.elf_so"),
1178 .dragonfly => return copy(&result, "/libexec/ld-elf.so.2"),
1179 .linux => switch (self.cpu.arch) {
1208 .i386,1180 .i386,
1209 .sparc,1181 .sparc,
1210 .sparcel,1182 .sparcel,
1211 => return mem.dupeZ(a, u8, "/lib/ld-linux.so.2"),1183 => return copy(&result, "/lib/ld-linux.so.2"),
12121184
1213 .aarch64 => return mem.dupeZ(a, u8, "/lib/ld-linux-aarch64.so.1"),1185 .aarch64 => return copy(&result, "/lib/ld-linux-aarch64.so.1"),
1214 .aarch64_be => return mem.dupeZ(a, u8, "/lib/ld-linux-aarch64_be.so.1"),1186 .aarch64_be => return copy(&result, "/lib/ld-linux-aarch64_be.so.1"),
1215 .aarch64_32 => return mem.dupeZ(a, u8, "/lib/ld-linux-aarch64_32.so.1"),1187 .aarch64_32 => return copy(&result, "/lib/ld-linux-aarch64_32.so.1"),
12161188
1217 .arm,1189 .arm,
1218 .armeb,1190 .armeb,
1219 .thumb,1191 .thumb,
1220 .thumbeb,1192 .thumbeb,
1221 => return mem.dupeZ(a, u8, switch (self.getFloatAbi()) {1193 => return copy(&result, switch (self.getFloatAbi()) {
1222 .hard => "/lib/ld-linux-armhf.so.3",1194 .hard => "/lib/ld-linux-armhf.so.3",
1223 else => "/lib/ld-linux.so.3",1195 else => "/lib/ld-linux.so.3",
1224 }),1196 }),
...@@ -1227,28 +1199,43 @@ pub const Target = union(enum) {...@@ -1227,28 +1199,43 @@ pub const Target = union(enum) {
1227 .mipsel,1199 .mipsel,
1228 .mips64,1200 .mips64,
1229 .mips64el,1201 .mips64el,
1230 => return error.UnknownDynamicLinkerPath,1202 => {
1203 const lib_suffix = switch (self.abi) {
1204 .gnuabin32, .gnux32 => "32",
1205 .gnuabi64 => "64",
1206 else => "",
1207 };
1208 const is_nan_2008 = mips.featureSetHas(self.cpu.features, .nan2008);
1209 const loader = if (is_nan_2008) "ld-linux-mipsn8.so.1" else "ld.so.1";
1210 return print(&result, "/lib{}/{}", .{ lib_suffix, loader });
1211 },
12311212
1232 .powerpc => return mem.dupeZ(a, u8, "/lib/ld.so.1"),1213 .powerpc => return copy(&result, "/lib/ld.so.1"),
1233 .powerpc64, .powerpc64le => return mem.dupeZ(a, u8, "/lib64/ld64.so.2"),1214 .powerpc64, .powerpc64le => return copy(&result, "/lib64/ld64.so.2"),
1234 .s390x => return mem.dupeZ(a, u8, "/lib64/ld64.so.1"),1215 .s390x => return copy(&result, "/lib64/ld64.so.1"),
1235 .sparcv9 => return mem.dupeZ(a, u8, "/lib64/ld-linux.so.2"),1216 .sparcv9 => return copy(&result, "/lib64/ld-linux.so.2"),
1236 .x86_64 => return mem.dupeZ(a, u8, switch (self.getAbi()) {1217 .x86_64 => return copy(&result, switch (self.abi) {
1237 .gnux32 => "/libx32/ld-linux-x32.so.2",1218 .gnux32 => "/libx32/ld-linux-x32.so.2",
1238 else => "/lib64/ld-linux-x86-64.so.2",1219 else => "/lib64/ld-linux-x86-64.so.2",
1239 }),1220 }),
12401221
1241 .riscv32 => return mem.dupeZ(a, u8, "/lib/ld-linux-riscv32-ilp32.so.1"),1222 .riscv32 => return copy(&result, "/lib/ld-linux-riscv32-ilp32.so.1"),
1242 .riscv64 => return mem.dupeZ(a, u8, "/lib/ld-linux-riscv64-lp64.so.1"),1223 .riscv64 => return copy(&result, "/lib/ld-linux-riscv64-lp64.so.1"),
12431224
1225 // Architectures in this list have been verified as not having a standard
1226 // dynamic linker path.
1244 .wasm32,1227 .wasm32,
1245 .wasm64,1228 .wasm64,
1246 => return error.TargetHasNoDynamicLinker,1229 .bpfel,
1230 .bpfeb,
1231 .nvptx,
1232 .nvptx64,
1233 => return result,
12471234
1235 // TODO go over each item in this list and either move it to the above list, or
1236 // implement the standard dynamic linker path code for it.
1248 .arc,1237 .arc,
1249 .avr,1238 .avr,
1250 .bpfel,
1251 .bpfeb,
1252 .hexagon,1239 .hexagon,
1253 .msp430,1240 .msp430,
1254 .r600,1241 .r600,
...@@ -1256,8 +1243,6 @@ pub const Target = union(enum) {...@@ -1256,8 +1243,6 @@ pub const Target = union(enum) {
1256 .tce,1243 .tce,
1257 .tcele,1244 .tcele,
1258 .xcore,1245 .xcore,
1259 .nvptx,
1260 .nvptx64,
1261 .le32,1246 .le32,
1262 .le64,1247 .le64,
1263 .amdil,1248 .amdil,
...@@ -1271,9 +1256,11 @@ pub const Target = union(enum) {...@@ -1271,9 +1256,11 @@ pub const Target = union(enum) {
1271 .lanai,1256 .lanai,
1272 .renderscript32,1257 .renderscript32,
1273 .renderscript64,1258 .renderscript64,
1274 => return error.UnknownDynamicLinkerPath,1259 => return result,
1275 },1260 },
12761261
1262 // Operating systems in this list have been verified as not having a standard
1263 // dynamic linker path.
1277 .freestanding,1264 .freestanding,
1278 .ios,1265 .ios,
1279 .tvos,1266 .tvos,
...@@ -1282,40 +1269,36 @@ pub const Target = union(enum) {...@@ -1282,40 +1269,36 @@ pub const Target = union(enum) {
1282 .uefi,1269 .uefi,
1283 .windows,1270 .windows,
1284 .emscripten,1271 .emscripten,
1272 .wasi,
1285 .other,1273 .other,
1286 => return error.TargetHasNoDynamicLinker,1274 => return result,
12871275
1288 else => return error.UnknownDynamicLinkerPath,1276 // TODO go over each item in this list and either move it to the above list, or
1277 // implement the standard dynamic linker path code for it.
1278 .ananas,
1279 .cloudabi,
1280 .fuchsia,
1281 .kfreebsd,
1282 .lv2,
1283 .openbsd,
1284 .solaris,
1285 .haiku,
1286 .minix,
1287 .rtems,
1288 .nacl,
1289 .cnk,
1290 .aix,
1291 .cuda,
1292 .nvcl,
1293 .amdhsa,
1294 .ps4,
1295 .elfiamcu,
1296 .mesa3d,
1297 .contiki,
1298 .amdpal,
1299 .hermit,
1300 .hurd,
1301 => return result,
1289 }1302 }
1290 }1303 }
1291};1304};
1292
1293test "Target.parse" {
1294 {
1295 const target = (try Target.parse(.{
1296 .arch_os_abi = "x86_64-linux-gnu",
1297 .cpu_features = "x86_64-sse-sse2-avx-cx8",
1298 })).Cross;
1299
1300 std.testing.expect(target.os == .linux);
1301 std.testing.expect(target.abi == .gnu);
1302 std.testing.expect(target.cpu.arch == .x86_64);
1303 std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .sse));
1304 std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .avx));
1305 std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .cx8));
1306 std.testing.expect(Target.x86.featureSetHas(target.cpu.features, .cmov));
1307 std.testing.expect(Target.x86.featureSetHas(target.cpu.features, .fxsr));
1308 }
1309 {
1310 const target = (try Target.parse(.{
1311 .arch_os_abi = "arm-linux-musleabihf",
1312 .cpu_features = "generic+v8a",
1313 })).Cross;
1314
1315 std.testing.expect(target.os == .linux);
1316 std.testing.expect(target.abi == .musleabihf);
1317 std.testing.expect(target.cpu.arch == .arm);
1318 std.testing.expect(target.cpu.model == &Target.arm.cpu.generic);
1319 std.testing.expect(Target.arm.featureSetHas(target.cpu.features, .v8a));
1320 }
1321}
lib/std/testing.zig+2-8
...@@ -1,5 +1,3 @@...@@ -1,5 +1,3 @@
1const builtin = @import("builtin");
2const TypeId = builtin.TypeId;
3const std = @import("std.zig");1const std = @import("std.zig");
42
5pub const LeakCountAllocator = @import("testing/leak_count_allocator.zig").LeakCountAllocator;3pub const LeakCountAllocator = @import("testing/leak_count_allocator.zig").LeakCountAllocator;
...@@ -65,16 +63,12 @@ pub fn expectEqual(expected: var, actual: @TypeOf(expected)) void {...@@ -65,16 +63,12 @@ pub fn expectEqual(expected: var, actual: @TypeOf(expected)) void {
6563
66 .Pointer => |pointer| {64 .Pointer => |pointer| {
67 switch (pointer.size) {65 switch (pointer.size) {
68 builtin.TypeInfo.Pointer.Size.One,66 .One, .Many, .C => {
69 builtin.TypeInfo.Pointer.Size.Many,
70 builtin.TypeInfo.Pointer.Size.C,
71 => {
72 if (actual != expected) {67 if (actual != expected) {
73 std.debug.panic("expected {*}, found {*}", .{ expected, actual });68 std.debug.panic("expected {*}, found {*}", .{ expected, actual });
74 }69 }
75 },70 },
7671 .Slice => {
77 builtin.TypeInfo.Pointer.Size.Slice => {
78 if (actual.ptr != expected.ptr) {72 if (actual.ptr != expected.ptr) {
79 std.debug.panic("expected slice ptr {}, found {}", .{ expected.ptr, actual.ptr });73 std.debug.panic("expected slice ptr {}, found {}", .{ expected.ptr, actual.ptr });
80 }74 }
lib/std/thread.zig+15-18
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");
2const std = @import("std.zig");1const std = @import("std.zig");
2const builtin = std.builtin;
3const os = std.os;3const os = std.os;
4const mem = std.mem;4const mem = std.mem;
5const windows = std.os.windows;5const windows = std.os.windows;
...@@ -9,14 +9,14 @@ const assert = std.debug.assert;...@@ -9,14 +9,14 @@ const assert = std.debug.assert;
9pub const Thread = struct {9pub const Thread = struct {
10 data: Data,10 data: Data,
1111
12 pub const use_pthreads = builtin.os != .windows and builtin.link_libc;12 pub const use_pthreads = std.Target.current.os.tag != .windows and builtin.link_libc;
1313
14 /// Represents a kernel thread handle.14 /// Represents a kernel thread handle.
15 /// May be an integer or a pointer depending on the platform.15 /// May be an integer or a pointer depending on the platform.
16 /// On Linux and POSIX, this is the same as Id.16 /// On Linux and POSIX, this is the same as Id.
17 pub const Handle = if (use_pthreads)17 pub const Handle = if (use_pthreads)
18 c.pthread_t18 c.pthread_t
19 else switch (builtin.os) {19 else switch (std.Target.current.os.tag) {
20 .linux => i32,20 .linux => i32,
21 .windows => windows.HANDLE,21 .windows => windows.HANDLE,
22 else => void,22 else => void,
...@@ -25,7 +25,7 @@ pub const Thread = struct {...@@ -25,7 +25,7 @@ pub const Thread = struct {
25 /// Represents a unique ID per thread.25 /// Represents a unique ID per thread.
26 /// May be an integer or pointer depending on the platform.26 /// May be an integer or pointer depending on the platform.
27 /// On Linux and POSIX, this is the same as Handle.27 /// On Linux and POSIX, this is the same as Handle.
28 pub const Id = switch (builtin.os) {28 pub const Id = switch (std.Target.current.os.tag) {
29 .windows => windows.DWORD,29 .windows => windows.DWORD,
30 else => Handle,30 else => Handle,
31 };31 };
...@@ -35,7 +35,7 @@ pub const Thread = struct {...@@ -35,7 +35,7 @@ pub const Thread = struct {
35 handle: Thread.Handle,35 handle: Thread.Handle,
36 memory: []align(mem.page_size) u8,36 memory: []align(mem.page_size) u8,
37 }37 }
38 else switch (builtin.os) {38 else switch (std.Target.current.os.tag) {
39 .linux => struct {39 .linux => struct {
40 handle: Thread.Handle,40 handle: Thread.Handle,
41 memory: []align(mem.page_size) u8,41 memory: []align(mem.page_size) u8,
...@@ -55,7 +55,7 @@ pub const Thread = struct {...@@ -55,7 +55,7 @@ pub const Thread = struct {
55 if (use_pthreads) {55 if (use_pthreads) {
56 return c.pthread_self();56 return c.pthread_self();
57 } else57 } else
58 return switch (builtin.os) {58 return switch (std.Target.current.os.tag) {
59 .linux => os.linux.gettid(),59 .linux => os.linux.gettid(),
60 .windows => windows.kernel32.GetCurrentThreadId(),60 .windows => windows.kernel32.GetCurrentThreadId(),
61 else => @compileError("Unsupported OS"),61 else => @compileError("Unsupported OS"),
...@@ -83,7 +83,7 @@ pub const Thread = struct {...@@ -83,7 +83,7 @@ pub const Thread = struct {
83 else => unreachable,83 else => unreachable,
84 }84 }
85 os.munmap(self.data.memory);85 os.munmap(self.data.memory);
86 } else switch (builtin.os) {86 } else switch (std.Target.current.os.tag) {
87 .linux => {87 .linux => {
88 while (true) {88 while (true) {
89 const pid_value = @atomicLoad(i32, &self.data.handle, .SeqCst);89 const pid_value = @atomicLoad(i32, &self.data.handle, .SeqCst);
...@@ -150,7 +150,7 @@ pub const Thread = struct {...@@ -150,7 +150,7 @@ pub const Thread = struct {
150 const Context = @TypeOf(context);150 const Context = @TypeOf(context);
151 comptime assert(@typeInfo(@TypeOf(startFn)).Fn.args[0].arg_type.? == Context);151 comptime assert(@typeInfo(@TypeOf(startFn)).Fn.args[0].arg_type.? == Context);
152152
153 if (builtin.os == builtin.Os.windows) {153 if (std.Target.current.os.tag == .windows) {
154 const WinThread = struct {154 const WinThread = struct {
155 const OuterContext = struct {155 const OuterContext = struct {
156 thread: Thread,156 thread: Thread,
...@@ -309,16 +309,16 @@ pub const Thread = struct {...@@ -309,16 +309,16 @@ pub const Thread = struct {
309 os.EINVAL => unreachable,309 os.EINVAL => unreachable,
310 else => return os.unexpectedErrno(@intCast(usize, err)),310 else => return os.unexpectedErrno(@intCast(usize, err)),
311 }311 }
312 } else if (builtin.os == .linux) {312 } else if (std.Target.current.os.tag == .linux) {
313 var flags: u32 = os.CLONE_VM | os.CLONE_FS | os.CLONE_FILES | os.CLONE_SIGHAND |313 var flags: u32 = os.CLONE_VM | os.CLONE_FS | os.CLONE_FILES | os.CLONE_SIGHAND |
314 os.CLONE_THREAD | os.CLONE_SYSVSEM | os.CLONE_PARENT_SETTID | os.CLONE_CHILD_CLEARTID |314 os.CLONE_THREAD | os.CLONE_SYSVSEM | os.CLONE_PARENT_SETTID | os.CLONE_CHILD_CLEARTID |
315 os.CLONE_DETACHED;315 os.CLONE_DETACHED;
316 var newtls: usize = undefined;316 var newtls: usize = undefined;
317 // This structure is only needed when targeting i386317 // This structure is only needed when targeting i386
318 var user_desc: if (builtin.arch == .i386) os.linux.user_desc else void = undefined;318 var user_desc: if (std.Target.current.cpu.arch == .i386) os.linux.user_desc else void = undefined;
319319
320 if (os.linux.tls.tls_image) |tls_img| {320 if (os.linux.tls.tls_image) |tls_img| {
321 if (builtin.arch == .i386) {321 if (std.Target.current.cpu.arch == .i386) {
322 user_desc = os.linux.user_desc{322 user_desc = os.linux.user_desc{
323 .entry_number = tls_img.gdt_entry_number,323 .entry_number = tls_img.gdt_entry_number,
324 .base_addr = os.linux.tls.copyTLS(mmap_addr + tls_start_offset),324 .base_addr = os.linux.tls.copyTLS(mmap_addr + tls_start_offset),
...@@ -362,27 +362,24 @@ pub const Thread = struct {...@@ -362,27 +362,24 @@ pub const Thread = struct {
362 }362 }
363363
364 pub const CpuCountError = error{364 pub const CpuCountError = error{
365 OutOfMemory,
366 PermissionDenied,365 PermissionDenied,
367 SystemResources,366 SystemResources,
368 Unexpected,367 Unexpected,
369 };368 };
370369
371 pub fn cpuCount() CpuCountError!usize {370 pub fn cpuCount() CpuCountError!usize {
372 if (builtin.os == .linux) {371 if (std.Target.current.os.tag == .linux) {
373 const cpu_set = try os.sched_getaffinity(0);372 const cpu_set = try os.sched_getaffinity(0);
374 return @as(usize, os.CPU_COUNT(cpu_set)); // TODO should not need this usize cast373 return @as(usize, os.CPU_COUNT(cpu_set)); // TODO should not need this usize cast
375 }374 }
376 if (builtin.os == .windows) {375 if (std.Target.current.os.tag == .windows) {
377 var system_info: windows.SYSTEM_INFO = undefined;376 return os.windows.peb().NumberOfProcessors;
378 windows.kernel32.GetSystemInfo(&system_info);
379 return @intCast(usize, system_info.dwNumberOfProcessors);
380 }377 }
381 var count: c_int = undefined;378 var count: c_int = undefined;
382 var count_len: usize = @sizeOf(c_int);379 var count_len: usize = @sizeOf(c_int);
383 const name = if (comptime std.Target.current.isDarwin()) "hw.logicalcpu" else "hw.ncpu";380 const name = if (comptime std.Target.current.isDarwin()) "hw.logicalcpu" else "hw.ncpu";
384 os.sysctlbynameC(name, &count, &count_len, null, 0) catch |err| switch (err) {381 os.sysctlbynameC(name, &count, &count_len, null, 0) catch |err| switch (err) {
385 error.NameTooLong => unreachable,382 error.NameTooLong, error.UnknownName => unreachable,
386 else => |e| return e,383 else => |e| return e,
387 };384 };
388 return @intCast(usize, count);385 return @intCast(usize, count);
lib/std/time.zig+10-8
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");
2const std = @import("std.zig");1const std = @import("std.zig");
2const builtin = std.builtin;
3const assert = std.debug.assert;3const assert = std.debug.assert;
4const testing = std.testing;4const testing = std.testing;
5const os = std.os;5const os = std.os;
...@@ -7,10 +7,12 @@ const math = std.math;...@@ -7,10 +7,12 @@ const math = std.math;
77
8pub const epoch = @import("time/epoch.zig");8pub const epoch = @import("time/epoch.zig");
99
10const is_windows = std.Target.current.os.tag == .windows;
11
10/// Spurious wakeups are possible and no precision of timing is guaranteed.12/// Spurious wakeups are possible and no precision of timing is guaranteed.
11/// TODO integrate with evented I/O13/// TODO integrate with evented I/O
12pub fn sleep(nanoseconds: u64) void {14pub fn sleep(nanoseconds: u64) void {
13 if (builtin.os == .windows) {15 if (is_windows) {
14 const ns_per_ms = ns_per_s / ms_per_s;16 const ns_per_ms = ns_per_s / ms_per_s;
15 const big_ms_from_ns = nanoseconds / ns_per_ms;17 const big_ms_from_ns = nanoseconds / ns_per_ms;
16 const ms = math.cast(os.windows.DWORD, big_ms_from_ns) catch math.maxInt(os.windows.DWORD);18 const ms = math.cast(os.windows.DWORD, big_ms_from_ns) catch math.maxInt(os.windows.DWORD);
...@@ -31,7 +33,7 @@ pub fn timestamp() u64 {...@@ -31,7 +33,7 @@ pub fn timestamp() u64 {
31/// Get the posix timestamp, UTC, in milliseconds33/// Get the posix timestamp, UTC, in milliseconds
32/// TODO audit this function. is it possible to return an error?34/// TODO audit this function. is it possible to return an error?
33pub fn milliTimestamp() u64 {35pub fn milliTimestamp() u64 {
34 if (builtin.os == .windows) {36 if (is_windows) {
35 //FileTime has a granularity of 100 nanoseconds37 //FileTime has a granularity of 100 nanoseconds
36 // and uses the NTFS/Windows epoch38 // and uses the NTFS/Windows epoch
37 var ft: os.windows.FILETIME = undefined;39 var ft: os.windows.FILETIME = undefined;
...@@ -42,7 +44,7 @@ pub fn milliTimestamp() u64 {...@@ -42,7 +44,7 @@ pub fn milliTimestamp() u64 {
42 const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;44 const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
43 return @divFloor(ft64, hns_per_ms) - -epoch_adj;45 return @divFloor(ft64, hns_per_ms) - -epoch_adj;
44 }46 }
45 if (builtin.os == .wasi and !builtin.link_libc) {47 if (builtin.os.tag == .wasi and !builtin.link_libc) {
46 var ns: os.wasi.timestamp_t = undefined;48 var ns: os.wasi.timestamp_t = undefined;
4749
48 // TODO: Verify that precision is ignored50 // TODO: Verify that precision is ignored
...@@ -102,7 +104,7 @@ pub const Timer = struct {...@@ -102,7 +104,7 @@ pub const Timer = struct {
102 ///if we used resolution's value when performing the104 ///if we used resolution's value when performing the
103 /// performance counter calc on windows/darwin, it would105 /// performance counter calc on windows/darwin, it would
104 /// be less precise106 /// be less precise
105 frequency: switch (builtin.os) {107 frequency: switch (builtin.os.tag) {
106 .windows => u64,108 .windows => u64,
107 .macosx, .ios, .tvos, .watchos => os.darwin.mach_timebase_info_data,109 .macosx, .ios, .tvos, .watchos => os.darwin.mach_timebase_info_data,
108 else => void,110 else => void,
...@@ -127,7 +129,7 @@ pub const Timer = struct {...@@ -127,7 +129,7 @@ pub const Timer = struct {
127 pub fn start() Error!Timer {129 pub fn start() Error!Timer {
128 var self: Timer = undefined;130 var self: Timer = undefined;
129131
130 if (builtin.os == .windows) {132 if (is_windows) {
131 self.frequency = os.windows.QueryPerformanceFrequency();133 self.frequency = os.windows.QueryPerformanceFrequency();
132 self.resolution = @divFloor(ns_per_s, self.frequency);134 self.resolution = @divFloor(ns_per_s, self.frequency);
133 self.start_time = os.windows.QueryPerformanceCounter();135 self.start_time = os.windows.QueryPerformanceCounter();
...@@ -172,7 +174,7 @@ pub const Timer = struct {...@@ -172,7 +174,7 @@ pub const Timer = struct {
172 }174 }
173175
174 fn clockNative() u64 {176 fn clockNative() u64 {
175 if (builtin.os == .windows) {177 if (is_windows) {
176 return os.windows.QueryPerformanceCounter();178 return os.windows.QueryPerformanceCounter();
177 }179 }
178 if (comptime std.Target.current.isDarwin()) {180 if (comptime std.Target.current.isDarwin()) {
...@@ -184,7 +186,7 @@ pub const Timer = struct {...@@ -184,7 +186,7 @@ pub const Timer = struct {
184 }186 }
185187
186 fn nativeDurationToNanos(self: Timer, duration: u64) u64 {188 fn nativeDurationToNanos(self: Timer, duration: u64) u64 {
187 if (builtin.os == .windows) {189 if (is_windows) {
188 return @divFloor(duration * ns_per_s, self.frequency);190 return @divFloor(duration * ns_per_s, self.frequency);
189 }191 }
190 if (comptime std.Target.current.isDarwin()) {192 if (comptime std.Target.current.isDarwin()) {
lib/std/valgrind.zig+2-2
...@@ -8,7 +8,7 @@ pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3:...@@ -8,7 +8,7 @@ pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3:
8 }8 }
99
10 switch (builtin.arch) {10 switch (builtin.arch) {
11 builtin.Arch.i386 => {11 .i386 => {
12 return asm volatile (12 return asm volatile (
13 \\ roll $3, %%edi ; roll $13, %%edi13 \\ roll $3, %%edi ; roll $13, %%edi
14 \\ roll $29, %%edi ; roll $19, %%edi14 \\ roll $29, %%edi ; roll $19, %%edi
...@@ -19,7 +19,7 @@ pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3:...@@ -19,7 +19,7 @@ pub fn doClientRequest(default: usize, request: usize, a1: usize, a2: usize, a3:
19 : "cc", "memory"19 : "cc", "memory"
20 );20 );
21 },21 },
22 builtin.Arch.x86_64 => {22 .x86_64 => {
23 return asm volatile (23 return asm volatile (
24 \\ rolq $3, %%rdi ; rolq $13, %%rdi24 \\ rolq $3, %%rdi ; rolq $13, %%rdi
25 \\ rolq $61, %%rdi ; rolq $51, %%rdi25 \\ rolq $61, %%rdi ; rolq $51, %%rdi
lib/std/zig.zig+3-6
...@@ -6,11 +6,8 @@ pub const parseStringLiteral = @import("zig/parse_string_literal.zig").parseStri...@@ -6,11 +6,8 @@ pub const parseStringLiteral = @import("zig/parse_string_literal.zig").parseStri
6pub const render = @import("zig/render.zig").render;6pub const render = @import("zig/render.zig").render;
7pub const ast = @import("zig/ast.zig");7pub const ast = @import("zig/ast.zig");
8pub const system = @import("zig/system.zig");8pub const system = @import("zig/system.zig");
9pub const CrossTarget = @import("zig/cross_target.zig").CrossTarget;
910
10test "std.zig tests" {11test "" {
11 _ = @import("zig/ast.zig");12 @import("std").meta.refAllDecls(@This());
12 _ = @import("zig/parse.zig");
13 _ = @import("zig/render.zig");
14 _ = @import("zig/tokenizer.zig");
15 _ = @import("zig/parse_string_literal.zig");
16}13}
lib/std/zig/cross_target.zig created+839
...@@ -0,0 +1,839 @@
1const std = @import("../std.zig");
2const assert = std.debug.assert;
3const Target = std.Target;
4const mem = std.mem;
5
6/// Contains all the same data as `Target`, additionally introducing the concept of "the native target".
7/// The purpose of this abstraction is to provide meaningful and unsurprising defaults.
8/// This struct does reference any resources and it is copyable.
9pub const CrossTarget = struct {
10 /// `null` means native.
11 cpu_arch: ?Target.Cpu.Arch = null,
12
13 cpu_model: CpuModel = CpuModel.determined_by_cpu_arch,
14
15 /// Sparse set of CPU features to add to the set from `cpu_model`.
16 cpu_features_add: Target.Cpu.Feature.Set = Target.Cpu.Feature.Set.empty,
17
18 /// Sparse set of CPU features to remove from the set from `cpu_model`.
19 cpu_features_sub: Target.Cpu.Feature.Set = Target.Cpu.Feature.Set.empty,
20
21 /// `null` means native.
22 os_tag: ?Target.Os.Tag = null,
23
24 /// `null` means the default version range for `os_tag`. If `os_tag` is `null` (native)
25 /// then `null` for this field means native.
26 os_version_min: ?OsVersion = null,
27
28 /// When cross compiling, `null` means default (latest known OS version).
29 /// When `os_tag` is native, `null` means equal to the native OS version.
30 os_version_max: ?OsVersion = null,
31
32 /// `null` means default when cross compiling, or native when os_tag is native.
33 /// If `isGnuLibC()` is `false`, this must be `null` and is ignored.
34 glibc_version: ?SemVer = null,
35
36 /// `null` means the native C ABI, if `os_tag` is native, otherwise it means the default C ABI.
37 abi: ?Target.Abi = null,
38
39 /// When `os_tag` is `null`, then `null` means native. Otherwise it means the standard path
40 /// based on the `os_tag`.
41 dynamic_linker: DynamicLinker = DynamicLinker{},
42
43 pub const CpuModel = union(enum) {
44 /// Always native
45 native,
46
47 /// Always baseline
48 baseline,
49
50 /// If CPU Architecture is native, then the CPU model will be native. Otherwise,
51 /// it will be baseline.
52 determined_by_cpu_arch,
53
54 explicit: *const Target.Cpu.Model,
55 };
56
57 pub const OsVersion = union(enum) {
58 none: void,
59 semver: SemVer,
60 windows: Target.Os.WindowsVersion,
61 };
62
63 pub const SemVer = std.builtin.Version;
64
65 pub const DynamicLinker = Target.DynamicLinker;
66
67 pub fn fromTarget(target: Target) CrossTarget {
68 var result: CrossTarget = .{
69 .cpu_arch = target.cpu.arch,
70 .cpu_model = .{ .explicit = target.cpu.model },
71 .os_tag = target.os.tag,
72 .os_version_min = undefined,
73 .os_version_max = undefined,
74 .abi = target.abi,
75 .glibc_version = if (target.isGnuLibC())
76 target.os.version_range.linux.glibc
77 else
78 null,
79 };
80 result.updateOsVersionRange(target.os);
81
82 const all_features = target.cpu.arch.allFeaturesList();
83 var cpu_model_set = target.cpu.model.features;
84 cpu_model_set.populateDependencies(all_features);
85 {
86 // The "add" set is the full set with the CPU Model set removed.
87 const add_set = &result.cpu_features_add;
88 add_set.* = target.cpu.features;
89 add_set.removeFeatureSet(cpu_model_set);
90 }
91 {
92 // The "sub" set is the features that are on in CPU Model set and off in the full set.
93 const sub_set = &result.cpu_features_sub;
94 sub_set.* = cpu_model_set;
95 sub_set.removeFeatureSet(target.cpu.features);
96 }
97 return result;
98 }
99
100 fn updateOsVersionRange(self: *CrossTarget, os: Target.Os) void {
101 switch (os.tag) {
102 .freestanding,
103 .ananas,
104 .cloudabi,
105 .dragonfly,
106 .fuchsia,
107 .kfreebsd,
108 .lv2,
109 .solaris,
110 .haiku,
111 .minix,
112 .rtems,
113 .nacl,
114 .cnk,
115 .aix,
116 .cuda,
117 .nvcl,
118 .amdhsa,
119 .ps4,
120 .elfiamcu,
121 .mesa3d,
122 .contiki,
123 .amdpal,
124 .hermit,
125 .hurd,
126 .wasi,
127 .emscripten,
128 .uefi,
129 .other,
130 => {
131 self.os_version_min = .{ .none = {} };
132 self.os_version_max = .{ .none = {} };
133 },
134
135 .freebsd,
136 .macosx,
137 .ios,
138 .netbsd,
139 .openbsd,
140 .tvos,
141 .watchos,
142 => {
143 self.os_version_min = .{ .semver = os.version_range.semver.min };
144 self.os_version_max = .{ .semver = os.version_range.semver.max };
145 },
146
147 .linux => {
148 self.os_version_min = .{ .semver = os.version_range.linux.range.min };
149 self.os_version_max = .{ .semver = os.version_range.linux.range.max };
150 },
151
152 .windows => {
153 self.os_version_min = .{ .windows = os.version_range.windows.min };
154 self.os_version_max = .{ .windows = os.version_range.windows.max };
155 },
156 }
157 }
158
159 /// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
160 pub fn toTarget(self: CrossTarget) Target {
161 return .{
162 .cpu = self.getCpu(),
163 .os = self.getOs(),
164 .abi = self.getAbi(),
165 };
166 }
167
168 pub const ParseOptions = struct {
169 /// This is sometimes called a "triple". It looks roughly like this:
170 /// riscv64-linux-musl
171 /// The fields are, respectively:
172 /// * CPU Architecture
173 /// * Operating System (and optional version range)
174 /// * C ABI (optional, with optional glibc version)
175 /// The string "native" can be used for CPU architecture as well as Operating System.
176 /// If the CPU Architecture is specified as "native", then the Operating System and C ABI may be omitted.
177 arch_os_abi: []const u8 = "native",
178
179 /// Looks like "name+a+b-c-d+e", where "name" is a CPU Model name, "a", "b", and "e"
180 /// are examples of CPU features to add to the set, and "c" and "d" are examples of CPU features
181 /// to remove from the set.
182 /// The following special strings are recognized for CPU Model name:
183 /// * "baseline" - The "default" set of CPU features for cross-compiling. A conservative set
184 /// of features that is expected to be supported on most available hardware.
185 /// * "native" - The native CPU model is to be detected when compiling.
186 /// If this field is not provided (`null`), then the value will depend on the
187 /// parsed CPU Architecture. If native, then this will be "native". Otherwise, it will be "baseline".
188 cpu_features: ?[]const u8 = null,
189
190 /// Absolute path to dynamic linker, to override the default, which is either a natively
191 /// detected path, or a standard path.
192 dynamic_linker: ?[]const u8 = null,
193
194 /// If this is provided, the function will populate some information about parsing failures,
195 /// so that user-friendly error messages can be delivered.
196 diagnostics: ?*Diagnostics = null,
197
198 pub const Diagnostics = struct {
199 /// If the architecture was determined, this will be populated.
200 arch: ?Target.Cpu.Arch = null,
201
202 /// If the OS name was determined, this will be populated.
203 os_name: ?[]const u8 = null,
204
205 /// If the OS tag was determined, this will be populated.
206 os_tag: ?Target.Os.Tag = null,
207
208 /// If the ABI was determined, this will be populated.
209 abi: ?Target.Abi = null,
210
211 /// If the CPU name was determined, this will be populated.
212 cpu_name: ?[]const u8 = null,
213
214 /// If error.UnknownCpuFeature is returned, this will be populated.
215 unknown_feature_name: ?[]const u8 = null,
216 };
217 };
218
219 pub fn parse(args: ParseOptions) !CrossTarget {
220 var dummy_diags: ParseOptions.Diagnostics = undefined;
221 const diags = args.diagnostics orelse &dummy_diags;
222
223 var result: CrossTarget = .{
224 .dynamic_linker = DynamicLinker.init(args.dynamic_linker),
225 };
226
227 var it = mem.separate(args.arch_os_abi, "-");
228 const arch_name = it.next().?;
229 const arch_is_native = mem.eql(u8, arch_name, "native");
230 if (!arch_is_native) {
231 result.cpu_arch = std.meta.stringToEnum(Target.Cpu.Arch, arch_name) orelse
232 return error.UnknownArchitecture;
233 }
234 const arch = result.getCpuArch();
235 diags.arch = arch;
236
237 if (it.next()) |os_text| {
238 try parseOs(&result, diags, os_text);
239 } else if (!arch_is_native) {
240 return error.MissingOperatingSystem;
241 }
242
243 const opt_abi_text = it.next();
244 if (opt_abi_text) |abi_text| {
245 var abi_it = mem.separate(abi_text, ".");
246 const abi = std.meta.stringToEnum(Target.Abi, abi_it.next().?) orelse
247 return error.UnknownApplicationBinaryInterface;
248 result.abi = abi;
249 diags.abi = abi;
250
251 const abi_ver_text = abi_it.rest();
252 if (abi_it.next() != null) {
253 if (result.isGnuLibC()) {
254 result.glibc_version = SemVer.parse(abi_ver_text) catch |err| switch (err) {
255 error.Overflow => return error.InvalidAbiVersion,
256 error.InvalidCharacter => return error.InvalidAbiVersion,
257 error.InvalidVersion => return error.InvalidAbiVersion,
258 };
259 } else {
260 return error.InvalidAbiVersion;
261 }
262 }
263 }
264
265 if (it.next() != null) return error.UnexpectedExtraField;
266
267 if (args.cpu_features) |cpu_features| {
268 const all_features = arch.allFeaturesList();
269 var index: usize = 0;
270 while (index < cpu_features.len and
271 cpu_features[index] != '+' and
272 cpu_features[index] != '-')
273 {
274 index += 1;
275 }
276 const cpu_name = cpu_features[0..index];
277 diags.cpu_name = cpu_name;
278
279 const add_set = &result.cpu_features_add;
280 const sub_set = &result.cpu_features_sub;
281 if (mem.eql(u8, cpu_name, "native")) {
282 result.cpu_model = .native;
283 } else if (mem.eql(u8, cpu_name, "baseline")) {
284 result.cpu_model = .baseline;
285 } else {
286 result.cpu_model = .{ .explicit = try arch.parseCpuModel(cpu_name) };
287 }
288
289 while (index < cpu_features.len) {
290 const op = cpu_features[index];
291 const set = switch (op) {
292 '+' => add_set,
293 '-' => sub_set,
294 else => unreachable,
295 };
296 index += 1;
297 const start = index;
298 while (index < cpu_features.len and
299 cpu_features[index] != '+' and
300 cpu_features[index] != '-')
301 {
302 index += 1;
303 }
304 const feature_name = cpu_features[start..index];
305 for (all_features) |feature, feat_index_usize| {
306 const feat_index = @intCast(Target.Cpu.Feature.Set.Index, feat_index_usize);
307 if (mem.eql(u8, feature_name, feature.name)) {
308 set.addFeature(feat_index);
309 break;
310 }
311 } else {
312 diags.unknown_feature_name = feature_name;
313 return error.UnknownCpuFeature;
314 }
315 }
316 }
317
318 return result;
319 }
320
321 /// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
322 pub fn getCpu(self: CrossTarget) Target.Cpu {
323 switch (self.cpu_model) {
324 .native => {
325 // This works when doing `zig build` because Zig generates a build executable using
326 // native CPU model & features. However this will not be accurate otherwise, and
327 // will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
328 return Target.current.cpu;
329 },
330 .baseline => {
331 var adjusted_baseline = Target.Cpu.baseline(self.getCpuArch());
332 self.updateCpuFeatures(&adjusted_baseline.features);
333 return adjusted_baseline;
334 },
335 .determined_by_cpu_arch => if (self.cpu_arch == null) {
336 // This works when doing `zig build` because Zig generates a build executable using
337 // native CPU model & features. However this will not be accurate otherwise, and
338 // will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
339 return Target.current.cpu;
340 } else {
341 var adjusted_baseline = Target.Cpu.baseline(self.getCpuArch());
342 self.updateCpuFeatures(&adjusted_baseline.features);
343 return adjusted_baseline;
344 },
345 .explicit => |model| {
346 var adjusted_model = model.toCpu(self.getCpuArch());
347 self.updateCpuFeatures(&adjusted_model.features);
348 return adjusted_model;
349 },
350 }
351 }
352
353 pub fn getCpuArch(self: CrossTarget) Target.Cpu.Arch {
354 return self.cpu_arch orelse Target.current.cpu.arch;
355 }
356
357 pub fn getCpuModel(self: CrossTarget) *const Target.Cpu.Model {
358 if (self.cpu_model) |cpu_model| return cpu_model;
359 return self.getCpu().model;
360 }
361
362 pub fn getCpuFeatures(self: CrossTarget) Target.Cpu.Feature.Set {
363 return self.getCpu().features;
364 }
365
366 /// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
367 pub fn getOs(self: CrossTarget) Target.Os {
368 // `Target.current.os` works when doing `zig build` because Zig generates a build executable using
369 // native OS version range. However this will not be accurate otherwise, and
370 // will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
371 var adjusted_os = if (self.os_tag) |os_tag| Target.Os.defaultVersionRange(os_tag) else Target.current.os;
372
373 if (self.os_version_min) |min| switch (min) {
374 .none => {},
375 .semver => |semver| switch (self.getOsTag()) {
376 .linux => adjusted_os.version_range.linux.range.min = semver,
377 else => adjusted_os.version_range.semver.min = semver,
378 },
379 .windows => |win_ver| adjusted_os.version_range.windows.min = win_ver,
380 };
381
382 if (self.os_version_max) |max| switch (max) {
383 .none => {},
384 .semver => |semver| switch (self.getOsTag()) {
385 .linux => adjusted_os.version_range.linux.range.max = semver,
386 else => adjusted_os.version_range.semver.max = semver,
387 },
388 .windows => |win_ver| adjusted_os.version_range.windows.max = win_ver,
389 };
390
391 if (self.glibc_version) |glibc| {
392 assert(self.isGnuLibC());
393 adjusted_os.version_range.linux.glibc = glibc;
394 }
395
396 return adjusted_os;
397 }
398
399 pub fn getOsTag(self: CrossTarget) Target.Os.Tag {
400 return self.os_tag orelse Target.current.os.tag;
401 }
402
403 /// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
404 pub fn getOsVersionMin(self: CrossTarget) OsVersion {
405 if (self.os_version_min) |version_min| return version_min;
406 var tmp: CrossTarget = undefined;
407 tmp.updateOsVersionRange(self.getOs());
408 return tmp.os_version_min.?;
409 }
410
411 /// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
412 pub fn getOsVersionMax(self: CrossTarget) OsVersion {
413 if (self.os_version_max) |version_max| return version_max;
414 var tmp: CrossTarget = undefined;
415 tmp.updateOsVersionRange(self.getOs());
416 return tmp.os_version_max.?;
417 }
418
419 /// TODO deprecated, use `std.zig.system.NativeTargetInfo.detect`.
420 pub fn getAbi(self: CrossTarget) Target.Abi {
421 if (self.abi) |abi| return abi;
422
423 if (self.os_tag == null) {
424 // This works when doing `zig build` because Zig generates a build executable using
425 // native CPU model & features. However this will not be accurate otherwise, and
426 // will need to be integrated with `std.zig.system.NativeTargetInfo.detect`.
427 return Target.current.abi;
428 }
429
430 return Target.Abi.default(self.getCpuArch(), self.getOs());
431 }
432
433 pub fn isFreeBSD(self: CrossTarget) bool {
434 return self.getOsTag() == .freebsd;
435 }
436
437 pub fn isDarwin(self: CrossTarget) bool {
438 return self.getOsTag().isDarwin();
439 }
440
441 pub fn isNetBSD(self: CrossTarget) bool {
442 return self.getOsTag() == .netbsd;
443 }
444
445 pub fn isUefi(self: CrossTarget) bool {
446 return self.getOsTag() == .uefi;
447 }
448
449 pub fn isDragonFlyBSD(self: CrossTarget) bool {
450 return self.getOsTag() == .dragonfly;
451 }
452
453 pub fn isLinux(self: CrossTarget) bool {
454 return self.getOsTag() == .linux;
455 }
456
457 pub fn isWindows(self: CrossTarget) bool {
458 return self.getOsTag() == .windows;
459 }
460
461 pub fn oFileExt(self: CrossTarget) [:0]const u8 {
462 return self.getAbi().oFileExt();
463 }
464
465 pub fn exeFileExt(self: CrossTarget) [:0]const u8 {
466 return Target.exeFileExtSimple(self.getCpuArch(), self.getOsTag());
467 }
468
469 pub fn staticLibSuffix(self: CrossTarget) [:0]const u8 {
470 return Target.staticLibSuffix_cpu_arch_abi(self.getCpuArch(), self.getAbi());
471 }
472
473 pub fn dynamicLibSuffix(self: CrossTarget) [:0]const u8 {
474 return self.getOsTag().dynamicLibSuffix();
475 }
476
477 pub fn libPrefix(self: CrossTarget) [:0]const u8 {
478 return Target.libPrefix_cpu_arch_abi(self.getCpuArch(), self.getAbi());
479 }
480
481 pub fn isNative(self: CrossTarget) bool {
482 return self.cpu_arch == null and
483 (self.cpu_model == .native or self.cpu_model == .determined_by_cpu_arch) and
484 self.cpu_features_sub.isEmpty() and self.cpu_features_add.isEmpty() and
485 self.os_tag == null and self.os_version_min == null and self.os_version_max == null and
486 self.abi == null and self.dynamic_linker.get() == null and self.glibc_version == null;
487 }
488
489 pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![:0]u8 {
490 if (self.isNative()) {
491 return mem.dupeZ(allocator, u8, "native");
492 }
493
494 const arch_name = if (self.cpu_arch) |arch| @tagName(arch) else "native";
495 const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native";
496
497 var result = try std.Buffer.allocPrint(allocator, "{}-{}", .{ arch_name, os_name });
498 defer result.deinit();
499
500 // The zig target syntax does not allow specifying a max os version with no min, so
501 // if either are present, we need the min.
502 if (self.os_version_min != null or self.os_version_max != null) {
503 switch (self.getOsVersionMin()) {
504 .none => {},
505 .semver => |v| try result.print(".{}", .{v}),
506 .windows => |v| try result.print(".{}", .{@tagName(v)}),
507 }
508 }
509 if (self.os_version_max) |max| {
510 switch (max) {
511 .none => {},
512 .semver => |v| try result.print("...{}", .{v}),
513 .windows => |v| try result.print("...{}", .{@tagName(v)}),
514 }
515 }
516
517 if (self.glibc_version) |v| {
518 try result.print("-{}.{}", .{ @tagName(self.getAbi()), v });
519 } else if (self.abi) |abi| {
520 try result.print("-{}", .{@tagName(abi)});
521 }
522
523 return result.toOwnedSlice();
524 }
525
526 pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 {
527 // TODO is there anything else worthy of the description that is not
528 // already captured in the triple?
529 return self.zigTriple(allocator);
530 }
531
532 pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 {
533 return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi());
534 }
535
536 pub fn wantSharedLibSymLinks(self: CrossTarget) bool {
537 return self.getOsTag() != .windows;
538 }
539
540 pub const VcpkgLinkage = std.builtin.LinkMode;
541
542 /// Returned slice must be freed by the caller.
543 pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![:0]u8 {
544 const arch = switch (self.getCpuArch()) {
545 .i386 => "x86",
546 .x86_64 => "x64",
547
548 .arm,
549 .armeb,
550 .thumb,
551 .thumbeb,
552 .aarch64_32,
553 => "arm",
554
555 .aarch64,
556 .aarch64_be,
557 => "arm64",
558
559 else => return error.UnsupportedVcpkgArchitecture,
560 };
561
562 const os = switch (self.getOsTag()) {
563 .windows => "windows",
564 .linux => "linux",
565 .macosx => "macos",
566 else => return error.UnsupportedVcpkgOperatingSystem,
567 };
568
569 const static_suffix = switch (linkage) {
570 .Static => "-static",
571 .Dynamic => "",
572 };
573
574 return std.fmt.allocPrint0(allocator, "{}-{}{}", .{ arch, os, static_suffix });
575 }
576
577 pub const Executor = union(enum) {
578 native,
579 qemu: []const u8,
580 wine: []const u8,
581 wasmtime: []const u8,
582 unavailable,
583 };
584
585 /// Note that even a `CrossTarget` which returns `false` for `isNative` could still be natively executed.
586 /// For example `-target arm-native` running on an aarch64 host.
587 pub fn getExternalExecutor(self: CrossTarget) Executor {
588 const cpu_arch = self.getCpuArch();
589 const os_tag = self.getOsTag();
590 const os_match = os_tag == Target.current.os.tag;
591
592 // If the OS and CPU arch match, the binary can be considered native.
593 if (os_match and cpu_arch == Target.current.cpu.arch) {
594 // However, we also need to verify that the dynamic linker path is valid.
595 // TODO Until that is implemented, we prevent returning `.native` when the OS is non-native.
596 if (self.os_tag == null) {
597 return .native;
598 }
599 }
600
601 // If the OS matches, we can use QEMU to emulate a foreign architecture.
602 if (os_match) {
603 return switch (cpu_arch) {
604 .aarch64 => Executor{ .qemu = "qemu-aarch64" },
605 .aarch64_be => Executor{ .qemu = "qemu-aarch64_be" },
606 .arm => Executor{ .qemu = "qemu-arm" },
607 .armeb => Executor{ .qemu = "qemu-armeb" },
608 .i386 => Executor{ .qemu = "qemu-i386" },
609 .mips => Executor{ .qemu = "qemu-mips" },
610 .mipsel => Executor{ .qemu = "qemu-mipsel" },
611 .mips64 => Executor{ .qemu = "qemu-mips64" },
612 .mips64el => Executor{ .qemu = "qemu-mips64el" },
613 .powerpc => Executor{ .qemu = "qemu-ppc" },
614 .powerpc64 => Executor{ .qemu = "qemu-ppc64" },
615 .powerpc64le => Executor{ .qemu = "qemu-ppc64le" },
616 .riscv32 => Executor{ .qemu = "qemu-riscv32" },
617 .riscv64 => Executor{ .qemu = "qemu-riscv64" },
618 .s390x => Executor{ .qemu = "qemu-s390x" },
619 .sparc => Executor{ .qemu = "qemu-sparc" },
620 .x86_64 => Executor{ .qemu = "qemu-x86_64" },
621 else => return .unavailable,
622 };
623 }
624
625 switch (os_tag) {
626 .windows => switch (cpu_arch.ptrBitWidth()) {
627 32 => return Executor{ .wine = "wine" },
628 64 => return Executor{ .wine = "wine64" },
629 else => return .unavailable,
630 },
631 .wasi => switch (cpu_arch.ptrBitWidth()) {
632 32 => return Executor{ .wasmtime = "wasmtime" },
633 else => return .unavailable,
634 },
635 else => return .unavailable,
636 }
637 }
638
639 pub fn isGnuLibC(self: CrossTarget) bool {
640 return Target.isGnuLibC_os_tag_abi(self.getOsTag(), self.getAbi());
641 }
642
643 pub fn setGnuLibCVersion(self: *CrossTarget, major: u32, minor: u32, patch: u32) void {
644 assert(self.isGnuLibC());
645 self.glibc_version = SemVer{ .major = major, .minor = minor, .patch = patch };
646 }
647
648 pub fn getObjectFormat(self: CrossTarget) ObjectFormat {
649 return Target.getObjectFormatSimple(self.getOsTag(), self.getCpuArch());
650 }
651
652 fn updateCpuFeatures(self: CrossTarget, set: *Target.Cpu.Feature.Set) void {
653 set.removeFeatureSet(self.cpu_features_sub);
654 set.addFeatureSet(self.cpu_features_add);
655 set.populateDependencies(self.getCpuArch().allFeaturesList());
656 set.removeFeatureSet(self.cpu_features_sub);
657 }
658
659 fn parseOs(result: *CrossTarget, diags: *ParseOptions.Diagnostics, text: []const u8) !void {
660 var it = mem.separate(text, ".");
661 const os_name = it.next().?;
662 diags.os_name = os_name;
663 const os_is_native = mem.eql(u8, os_name, "native");
664 if (!os_is_native) {
665 result.os_tag = std.meta.stringToEnum(Target.Os.Tag, os_name) orelse
666 return error.UnknownOperatingSystem;
667 }
668 const tag = result.getOsTag();
669 diags.os_tag = tag;
670
671 const version_text = it.rest();
672 if (it.next() == null) return;
673
674 switch (tag) {
675 .freestanding,
676 .ananas,
677 .cloudabi,
678 .dragonfly,
679 .fuchsia,
680 .ios,
681 .kfreebsd,
682 .lv2,
683 .solaris,
684 .haiku,
685 .minix,
686 .rtems,
687 .nacl,
688 .cnk,
689 .aix,
690 .cuda,
691 .nvcl,
692 .amdhsa,
693 .ps4,
694 .elfiamcu,
695 .tvos,
696 .watchos,
697 .mesa3d,
698 .contiki,
699 .amdpal,
700 .hermit,
701 .hurd,
702 .wasi,
703 .emscripten,
704 .uefi,
705 .other,
706 => return error.InvalidOperatingSystemVersion,
707
708 .freebsd,
709 .macosx,
710 .netbsd,
711 .openbsd,
712 .linux,
713 => {
714 var range_it = mem.separate(version_text, "...");
715
716 const min_text = range_it.next().?;
717 const min_ver = SemVer.parse(min_text) catch |err| switch (err) {
718 error.Overflow => return error.InvalidOperatingSystemVersion,
719 error.InvalidCharacter => return error.InvalidOperatingSystemVersion,
720 error.InvalidVersion => return error.InvalidOperatingSystemVersion,
721 };
722 result.os_version_min = .{ .semver = min_ver };
723
724 const max_text = range_it.next() orelse return;
725 const max_ver = SemVer.parse(max_text) catch |err| switch (err) {
726 error.Overflow => return error.InvalidOperatingSystemVersion,
727 error.InvalidCharacter => return error.InvalidOperatingSystemVersion,
728 error.InvalidVersion => return error.InvalidOperatingSystemVersion,
729 };
730 result.os_version_max = .{ .semver = max_ver };
731 },
732
733 .windows => {
734 var range_it = mem.separate(version_text, "...");
735
736 const min_text = range_it.next().?;
737 const min_ver = std.meta.stringToEnum(Target.Os.WindowsVersion, min_text) orelse
738 return error.InvalidOperatingSystemVersion;
739 result.os_version_min = .{ .windows = min_ver };
740
741 const max_text = range_it.next() orelse return;
742 const max_ver = std.meta.stringToEnum(Target.Os.WindowsVersion, max_text) orelse
743 return error.InvalidOperatingSystemVersion;
744 result.os_version_max = .{ .windows = max_ver };
745 },
746 }
747 }
748};
749
750test "CrossTarget.parse" {
751 if (Target.current.isGnuLibC()) {
752 var cross_target = try CrossTarget.parse(.{});
753 cross_target.setGnuLibCVersion(2, 1, 1);
754
755 const text = try cross_target.zigTriple(std.testing.allocator);
756 defer std.testing.allocator.free(text);
757 std.testing.expectEqualSlices(u8, "native-native-gnu.2.1.1", text);
758 }
759 {
760 const cross_target = try CrossTarget.parse(.{
761 .arch_os_abi = "aarch64-linux",
762 .cpu_features = "native",
763 });
764
765 std.testing.expect(cross_target.cpu_arch.? == .aarch64);
766 std.testing.expect(cross_target.cpu_model == .native);
767 }
768 {
769 const cross_target = try CrossTarget.parse(.{ .arch_os_abi = "native" });
770
771 std.testing.expect(cross_target.cpu_arch == null);
772 std.testing.expect(cross_target.isNative());
773
774 const text = try cross_target.zigTriple(std.testing.allocator);
775 defer std.testing.allocator.free(text);
776 std.testing.expectEqualSlices(u8, "native", text);
777 }
778 {
779 const cross_target = try CrossTarget.parse(.{
780 .arch_os_abi = "x86_64-linux-gnu",
781 .cpu_features = "x86_64-sse-sse2-avx-cx8",
782 });
783 const target = cross_target.toTarget();
784
785 std.testing.expect(target.os.tag == .linux);
786 std.testing.expect(target.abi == .gnu);
787 std.testing.expect(target.cpu.arch == .x86_64);
788 std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .sse));
789 std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .avx));
790 std.testing.expect(!Target.x86.featureSetHas(target.cpu.features, .cx8));
791 std.testing.expect(Target.x86.featureSetHas(target.cpu.features, .cmov));
792 std.testing.expect(Target.x86.featureSetHas(target.cpu.features, .fxsr));
793
794 const text = try cross_target.zigTriple(std.testing.allocator);
795 defer std.testing.allocator.free(text);
796 std.testing.expectEqualSlices(u8, "x86_64-linux-gnu", text);
797 }
798 {
799 const cross_target = try CrossTarget.parse(.{
800 .arch_os_abi = "arm-linux-musleabihf",
801 .cpu_features = "generic+v8a",
802 });
803 const target = cross_target.toTarget();
804
805 std.testing.expect(target.os.tag == .linux);
806 std.testing.expect(target.abi == .musleabihf);
807 std.testing.expect(target.cpu.arch == .arm);
808 std.testing.expect(target.cpu.model == &Target.arm.cpu.generic);
809 std.testing.expect(Target.arm.featureSetHas(target.cpu.features, .v8a));
810
811 const text = try cross_target.zigTriple(std.testing.allocator);
812 defer std.testing.allocator.free(text);
813 std.testing.expectEqualSlices(u8, "arm-linux-musleabihf", text);
814 }
815 {
816 const cross_target = try CrossTarget.parse(.{
817 .arch_os_abi = "aarch64-linux.3.10...4.4.1-gnu.2.27",
818 .cpu_features = "generic+v8a",
819 });
820 const target = cross_target.toTarget();
821
822 std.testing.expect(target.cpu.arch == .aarch64);
823 std.testing.expect(target.os.tag == .linux);
824 std.testing.expect(target.os.version_range.linux.range.min.major == 3);
825 std.testing.expect(target.os.version_range.linux.range.min.minor == 10);
826 std.testing.expect(target.os.version_range.linux.range.min.patch == 0);
827 std.testing.expect(target.os.version_range.linux.range.max.major == 4);
828 std.testing.expect(target.os.version_range.linux.range.max.minor == 4);
829 std.testing.expect(target.os.version_range.linux.range.max.patch == 1);
830 std.testing.expect(target.os.version_range.linux.glibc.major == 2);
831 std.testing.expect(target.os.version_range.linux.glibc.minor == 27);
832 std.testing.expect(target.os.version_range.linux.glibc.patch == 0);
833 std.testing.expect(target.abi == .gnu);
834
835 const text = try cross_target.zigTriple(std.testing.allocator);
836 defer std.testing.allocator.free(text);
837 std.testing.expectEqualSlices(u8, "aarch64-linux.3.10...4.4.1-gnu.2.27", text);
838 }
839}
lib/std/zig/system.zig+694-2
...@@ -1,11 +1,15 @@...@@ -1,11 +1,15 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const elf = std.elf;
2const mem = std.mem;3const mem = std.mem;
4const fs = std.fs;
3const Allocator = std.mem.Allocator;5const Allocator = std.mem.Allocator;
4const ArrayList = std.ArrayList;6const ArrayList = std.ArrayList;
5const assert = std.debug.assert;7const assert = std.debug.assert;
6const process = std.process;8const process = std.process;
9const Target = std.Target;
10const CrossTarget = std.zig.CrossTarget;
711
8const is_windows = std.Target.current.isWindows();12const is_windows = Target.current.os.tag == .windows;
913
10pub const NativePaths = struct {14pub const NativePaths = struct {
11 include_dirs: ArrayList([:0]u8),15 include_dirs: ArrayList([:0]u8),
...@@ -77,7 +81,7 @@ pub const NativePaths = struct {...@@ -77,7 +81,7 @@ pub const NativePaths = struct {
77 }81 }
7882
79 if (!is_windows) {83 if (!is_windows) {
80 const triple = try std.Target.current.linuxTriple(allocator);84 const triple = try Target.current.linuxTriple(allocator);
8185
82 // TODO: $ ld --verbose | grep SEARCH_DIR86 // TODO: $ ld --verbose | grep SEARCH_DIR
83 // the output contains some paths that end with lib64, maybe include them too?87 // the output contains some paths that end with lib64, maybe include them too?
...@@ -161,3 +165,691 @@ pub const NativePaths = struct {...@@ -161,3 +165,691 @@ pub const NativePaths = struct {
161 try array.append(item);165 try array.append(item);
162 }166 }
163};167};
168
169pub const NativeTargetInfo = struct {
170 target: Target,
171
172 dynamic_linker: DynamicLinker = DynamicLinker{},
173
174 pub const DynamicLinker = Target.DynamicLinker;
175
176 pub const DetectError = error{
177 OutOfMemory,
178 FileSystem,
179 SystemResources,
180 SymLinkLoop,
181 ProcessFdQuotaExceeded,
182 SystemFdQuotaExceeded,
183 DeviceBusy,
184 };
185
186 /// Given a `CrossTarget`, which specifies in detail which parts of the target should be detected
187 /// natively, which should be standard or default, and which are provided explicitly, this function
188 /// resolves the native components by detecting the native system, and then resolves standard/default parts
189 /// relative to that.
190 /// Any resources this function allocates are released before returning, and so there is no
191 /// deinitialization method.
192 /// TODO Remove the Allocator requirement from this function.
193 pub fn detect(allocator: *Allocator, cross_target: CrossTarget) DetectError!NativeTargetInfo {
194 const cpu = switch (cross_target.cpu_model) {
195 .native => detectNativeCpuAndFeatures(cross_target),
196 .baseline => baselineCpuAndFeatures(cross_target),
197 .determined_by_cpu_arch => if (cross_target.cpu_arch == null)
198 detectNativeCpuAndFeatures(cross_target)
199 else
200 baselineCpuAndFeatures(cross_target),
201 .explicit => |model| blk: {
202 var adjusted_model = model.toCpu(cross_target.getCpuArch());
203 cross_target.updateCpuFeatures(&adjusted_model.features);
204 break :blk adjusted_model;
205 },
206 };
207
208 var os = Target.Os.defaultVersionRange(cross_target.getOsTag());
209 if (cross_target.os_tag == null) {
210 switch (Target.current.os.tag) {
211 .linux => {
212 const uts = std.os.uname();
213 const release = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &uts.release));
214 if (std.builtin.Version.parse(release)) |ver| {
215 os.version_range.linux.range.min = ver;
216 os.version_range.linux.range.max = ver;
217 } else |err| switch (err) {
218 error.Overflow => {},
219 error.InvalidCharacter => {},
220 error.InvalidVersion => {},
221 }
222 },
223 .windows => {
224 var version_info: std.os.windows.RTL_OSVERSIONINFOW = undefined;
225 version_info.dwOSVersionInfoSize = @sizeOf(@TypeOf(version_info));
226
227 switch (std.os.windows.ntdll.RtlGetVersion(&version_info)) {
228 .SUCCESS => {},
229 else => unreachable,
230 }
231
232 // Starting from the system infos build a NTDDI-like version
233 // constant whose format is:
234 // B0 B1 B2 B3
235 // `---` `` ``--> Sub-version (Starting from Windows 10 onwards)
236 // \ `--> Service pack (Always zero in the constants defined)
237 // `--> OS version (Major & minor)
238 const os_ver: u16 = //
239 @intCast(u16, version_info.dwMajorVersion & 0xff) << 8 |
240 @intCast(u16, version_info.dwMinorVersion & 0xff);
241 const sp_ver: u8 = 0;
242 const sub_ver: u8 = if (os_ver >= 0x0A00) subver: {
243 // There's no other way to obtain this info beside
244 // checking the build number against a known set of
245 // values
246 const known_build_numbers = [_]u32{
247 10240, 10586, 14393, 15063, 16299, 17134, 17763,
248 18362, 18363,
249 };
250 var last_idx: usize = 0;
251 for (known_build_numbers) |build, i| {
252 if (version_info.dwBuildNumber >= build)
253 last_idx = i;
254 }
255 break :subver @truncate(u8, last_idx);
256 } else 0;
257
258 const version: u32 = @as(u32, os_ver) << 16 | @as(u32, sp_ver) << 8 | sub_ver;
259
260 os.version_range.windows.max = @intToEnum(Target.Os.WindowsVersion, version);
261 os.version_range.windows.min = @intToEnum(Target.Os.WindowsVersion, version);
262 },
263 .macosx => {
264 var product_version: [32]u8 = undefined;
265 var size: usize = product_version.len;
266
267 // The osproductversion sysctl was introduced first with
268 // High Sierra, thankfully that's also the baseline that Zig
269 // supports
270 std.os.sysctlbynameC(
271 "kern.osproductversion",
272 &product_version,
273 &size,
274 null,
275 0,
276 ) catch |err| switch (err) {
277 error.UnknownName => unreachable,
278 else => unreachable,
279 };
280
281 const string_version = product_version[0 .. size - 1 :0];
282 if (std.builtin.Version.parse(string_version)) |ver| {
283 os.version_range.semver.min = ver;
284 os.version_range.semver.max = ver;
285 } else |err| switch (err) {
286 error.Overflow => {},
287 error.InvalidCharacter => {},
288 error.InvalidVersion => {},
289 }
290 },
291 .freebsd => {
292 // TODO Detect native operating system version.
293 },
294 else => {},
295 }
296 }
297
298 if (cross_target.os_version_min) |min| switch (min) {
299 .none => {},
300 .semver => |semver| switch (cross_target.getOsTag()) {
301 .linux => os.version_range.linux.range.min = semver,
302 else => os.version_range.semver.min = semver,
303 },
304 .windows => |win_ver| os.version_range.windows.min = win_ver,
305 };
306
307 if (cross_target.os_version_max) |max| switch (max) {
308 .none => {},
309 .semver => |semver| switch (cross_target.getOsTag()) {
310 .linux => os.version_range.linux.range.max = semver,
311 else => os.version_range.semver.max = semver,
312 },
313 .windows => |win_ver| os.version_range.windows.max = win_ver,
314 };
315
316 if (cross_target.glibc_version) |glibc| {
317 assert(cross_target.isGnuLibC());
318 os.version_range.linux.glibc = glibc;
319 }
320
321 return detectAbiAndDynamicLinker(allocator, cpu, os, cross_target);
322 }
323
324 /// First we attempt to use the executable's own binary. If it is dynamically
325 /// linked, then it should answer both the C ABI question and the dynamic linker question.
326 /// If it is statically linked, then we try /usr/bin/env. If that does not provide the answer, then
327 /// we fall back to the defaults.
328 /// TODO Remove the Allocator requirement from this function.
329 fn detectAbiAndDynamicLinker(
330 allocator: *Allocator,
331 cpu: Target.Cpu,
332 os: Target.Os,
333 cross_target: CrossTarget,
334 ) DetectError!NativeTargetInfo {
335 const native_target_has_ld = comptime Target.current.hasDynamicLinker();
336 const is_linux = Target.current.os.tag == .linux;
337 const have_all_info = cross_target.dynamic_linker.get() != null and
338 cross_target.abi != null and (!is_linux or cross_target.abi.?.isGnu());
339 const os_is_non_native = cross_target.os_tag != null;
340 if (!native_target_has_ld or have_all_info or os_is_non_native) {
341 return defaultAbiAndDynamicLinker(cpu, os, cross_target);
342 }
343 // The current target's ABI cannot be relied on for this. For example, we may build the zig
344 // compiler for target riscv64-linux-musl and provide a tarball for users to download.
345 // A user could then run that zig compiler on riscv64-linux-gnu. This use case is well-defined
346 // and supported by Zig. But that means that we must detect the system ABI here rather than
347 // relying on `Target.current`.
348 const all_abis = comptime blk: {
349 assert(@enumToInt(Target.Abi.none) == 0);
350 const fields = std.meta.fields(Target.Abi)[1..];
351 var array: [fields.len]Target.Abi = undefined;
352 inline for (fields) |field, i| {
353 array[i] = @field(Target.Abi, field.name);
354 }
355 break :blk array;
356 };
357 var ld_info_list_buffer: [all_abis.len]LdInfo = undefined;
358 var ld_info_list_len: usize = 0;
359
360 for (all_abis) |abi| {
361 // This may be a nonsensical parameter. We detect this with error.UnknownDynamicLinkerPath and
362 // skip adding it to `ld_info_list`.
363 const target: Target = .{
364 .cpu = cpu,
365 .os = os,
366 .abi = abi,
367 };
368 const ld = target.standardDynamicLinkerPath();
369 if (ld.get() == null) continue;
370
371 ld_info_list_buffer[ld_info_list_len] = .{
372 .ld = ld,
373 .abi = abi,
374 };
375 ld_info_list_len += 1;
376 }
377 const ld_info_list = ld_info_list_buffer[0..ld_info_list_len];
378
379 if (cross_target.dynamic_linker.get()) |explicit_ld| {
380 const explicit_ld_basename = fs.path.basename(explicit_ld);
381 for (ld_info_list) |ld_info| {
382 const standard_ld_basename = fs.path.basename(ld_info.ld.get().?);
383 }
384 }
385
386 // Best case scenario: the executable is dynamically linked, and we can iterate
387 // over our own shared objects and find a dynamic linker.
388 self_exe: {
389 const lib_paths = try std.process.getSelfExeSharedLibPaths(allocator);
390 defer allocator.free(lib_paths);
391
392 var found_ld_info: LdInfo = undefined;
393 var found_ld_path: [:0]const u8 = undefined;
394
395 // Look for dynamic linker.
396 // This is O(N^M) but typical case here is N=2 and M=10.
397 find_ld: for (lib_paths) |lib_path| {
398 for (ld_info_list) |ld_info| {
399 const standard_ld_basename = fs.path.basename(ld_info.ld.get().?);
400 if (std.mem.endsWith(u8, lib_path, standard_ld_basename)) {
401 found_ld_info = ld_info;
402 found_ld_path = lib_path;
403 break :find_ld;
404 }
405 }
406 } else break :self_exe;
407
408 // Look for glibc version.
409 var os_adjusted = os;
410 if (Target.current.os.tag == .linux and found_ld_info.abi.isGnu() and
411 cross_target.glibc_version == null)
412 {
413 for (lib_paths) |lib_path| {
414 if (std.mem.endsWith(u8, lib_path, glibc_so_basename)) {
415 os_adjusted.version_range.linux.glibc = glibcVerFromSO(lib_path) catch |err| switch (err) {
416 error.UnrecognizedGnuLibCFileName => continue,
417 error.InvalidGnuLibCVersion => continue,
418 error.GnuLibCVersionUnavailable => continue,
419 else => |e| return e,
420 };
421 break;
422 }
423 }
424 }
425
426 var result: NativeTargetInfo = .{
427 .target = .{
428 .cpu = cpu,
429 .os = os_adjusted,
430 .abi = cross_target.abi orelse found_ld_info.abi,
431 },
432 .dynamic_linker = if (cross_target.dynamic_linker.get() == null)
433 DynamicLinker.init(found_ld_path)
434 else
435 cross_target.dynamic_linker,
436 };
437 return result;
438 }
439
440 const env_file = std.fs.openFileAbsoluteC("/usr/bin/env", .{}) catch |err| switch (err) {
441 error.NoSpaceLeft => unreachable,
442 error.NameTooLong => unreachable,
443 error.PathAlreadyExists => unreachable,
444 error.SharingViolation => unreachable,
445 error.InvalidUtf8 => unreachable,
446 error.BadPathName => unreachable,
447 error.PipeBusy => unreachable,
448
449 error.IsDir,
450 error.NotDir,
451 error.AccessDenied,
452 error.NoDevice,
453 error.FileNotFound,
454 error.FileTooBig,
455 error.Unexpected,
456 => return defaultAbiAndDynamicLinker(cpu, os, cross_target),
457
458 else => |e| return e,
459 };
460 defer env_file.close();
461
462 // If Zig is statically linked, such as via distributed binary static builds, the above
463 // trick won't work. The next thing we fall back to is the same thing, but for /usr/bin/env.
464 // Since that path is hard-coded into the shebang line of many portable scripts, it's a
465 // reasonably reliable path to check for.
466 return abiAndDynamicLinkerFromFile(env_file, cpu, os, ld_info_list, cross_target) catch |err| switch (err) {
467 error.FileSystem,
468 error.SystemResources,
469 error.SymLinkLoop,
470 error.ProcessFdQuotaExceeded,
471 error.SystemFdQuotaExceeded,
472 => |e| return e,
473
474 error.UnableToReadElfFile,
475 error.InvalidElfClass,
476 error.InvalidElfVersion,
477 error.InvalidElfEndian,
478 error.InvalidElfFile,
479 error.InvalidElfMagic,
480 error.Unexpected,
481 error.UnexpectedEndOfFile,
482 error.NameTooLong,
483 // Finally, we fall back on the standard path.
484 => defaultAbiAndDynamicLinker(cpu, os, cross_target),
485 };
486 }
487
488 const glibc_so_basename = "libc.so.6";
489
490 fn glibcVerFromSO(so_path: [:0]const u8) !std.builtin.Version {
491 var link_buf: [std.os.PATH_MAX]u8 = undefined;
492 const link_name = std.os.readlinkC(so_path.ptr, &link_buf) catch |err| switch (err) {
493 error.AccessDenied => return error.GnuLibCVersionUnavailable,
494 error.FileSystem => return error.FileSystem,
495 error.SymLinkLoop => return error.SymLinkLoop,
496 error.NameTooLong => unreachable,
497 error.FileNotFound => return error.GnuLibCVersionUnavailable,
498 error.SystemResources => return error.SystemResources,
499 error.NotDir => return error.GnuLibCVersionUnavailable,
500 error.Unexpected => return error.GnuLibCVersionUnavailable,
501 };
502 return glibcVerFromLinkName(link_name);
503 }
504
505 fn glibcVerFromLinkName(link_name: []const u8) !std.builtin.Version {
506 // example: "libc-2.3.4.so"
507 // example: "libc-2.27.so"
508 const prefix = "libc-";
509 const suffix = ".so";
510 if (!mem.startsWith(u8, link_name, prefix) or !mem.endsWith(u8, link_name, suffix)) {
511 return error.UnrecognizedGnuLibCFileName;
512 }
513 // chop off "libc-" and ".so"
514 const link_name_chopped = link_name[prefix.len .. link_name.len - suffix.len];
515 return std.builtin.Version.parse(link_name_chopped) catch |err| switch (err) {
516 error.Overflow => return error.InvalidGnuLibCVersion,
517 error.InvalidCharacter => return error.InvalidGnuLibCVersion,
518 error.InvalidVersion => return error.InvalidGnuLibCVersion,
519 };
520 }
521
522 pub const AbiAndDynamicLinkerFromFileError = error{
523 FileSystem,
524 SystemResources,
525 SymLinkLoop,
526 ProcessFdQuotaExceeded,
527 SystemFdQuotaExceeded,
528 UnableToReadElfFile,
529 InvalidElfClass,
530 InvalidElfVersion,
531 InvalidElfEndian,
532 InvalidElfFile,
533 InvalidElfMagic,
534 Unexpected,
535 UnexpectedEndOfFile,
536 NameTooLong,
537 };
538
539 pub fn abiAndDynamicLinkerFromFile(
540 file: fs.File,
541 cpu: Target.Cpu,
542 os: Target.Os,
543 ld_info_list: []const LdInfo,
544 cross_target: CrossTarget,
545 ) AbiAndDynamicLinkerFromFileError!NativeTargetInfo {
546 var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 align(@alignOf(elf.Elf64_Ehdr)) = undefined;
547 _ = try preadFull(file, &hdr_buf, 0, hdr_buf.len);
548 const hdr32 = @ptrCast(*elf.Elf32_Ehdr, &hdr_buf);
549 const hdr64 = @ptrCast(*elf.Elf64_Ehdr, &hdr_buf);
550 if (!mem.eql(u8, hdr32.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
551 const elf_endian: std.builtin.Endian = switch (hdr32.e_ident[elf.EI_DATA]) {
552 elf.ELFDATA2LSB => .Little,
553 elf.ELFDATA2MSB => .Big,
554 else => return error.InvalidElfEndian,
555 };
556 const need_bswap = elf_endian != std.builtin.endian;
557 if (hdr32.e_ident[elf.EI_VERSION] != 1) return error.InvalidElfVersion;
558
559 const is_64 = switch (hdr32.e_ident[elf.EI_CLASS]) {
560 elf.ELFCLASS32 => false,
561 elf.ELFCLASS64 => true,
562 else => return error.InvalidElfClass,
563 };
564 var phoff = elfInt(is_64, need_bswap, hdr32.e_phoff, hdr64.e_phoff);
565 const phentsize = elfInt(is_64, need_bswap, hdr32.e_phentsize, hdr64.e_phentsize);
566 const phnum = elfInt(is_64, need_bswap, hdr32.e_phnum, hdr64.e_phnum);
567
568 var result: NativeTargetInfo = .{
569 .target = .{
570 .cpu = cpu,
571 .os = os,
572 .abi = cross_target.abi orelse Target.Abi.default(cpu.arch, os),
573 },
574 .dynamic_linker = cross_target.dynamic_linker,
575 };
576 var rpath_offset: ?u64 = null; // Found inside PT_DYNAMIC
577 const look_for_ld = cross_target.dynamic_linker.get() == null;
578
579 var ph_buf: [16 * @sizeOf(elf.Elf64_Phdr)]u8 align(@alignOf(elf.Elf64_Phdr)) = undefined;
580 if (phentsize > @sizeOf(elf.Elf64_Phdr)) return error.InvalidElfFile;
581
582 var ph_i: u16 = 0;
583 while (ph_i < phnum) {
584 // Reserve some bytes so that we can deref the 64-bit struct fields
585 // even when the ELF file is 32-bits.
586 const ph_reserve: usize = @sizeOf(elf.Elf64_Phdr) - @sizeOf(elf.Elf32_Phdr);
587 const ph_read_byte_len = try preadFull(file, ph_buf[0 .. ph_buf.len - ph_reserve], phoff, phentsize);
588 var ph_buf_i: usize = 0;
589 while (ph_buf_i < ph_read_byte_len and ph_i < phnum) : ({
590 ph_i += 1;
591 phoff += phentsize;
592 ph_buf_i += phentsize;
593 }) {
594 const ph32 = @ptrCast(*elf.Elf32_Phdr, @alignCast(@alignOf(elf.Elf32_Phdr), &ph_buf[ph_buf_i]));
595 const ph64 = @ptrCast(*elf.Elf64_Phdr, @alignCast(@alignOf(elf.Elf64_Phdr), &ph_buf[ph_buf_i]));
596 const p_type = elfInt(is_64, need_bswap, ph32.p_type, ph64.p_type);
597 switch (p_type) {
598 elf.PT_INTERP => if (look_for_ld) {
599 const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);
600 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);
601 if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong;
602 _ = try preadFull(file, result.dynamic_linker.buffer[0..p_filesz], p_offset, p_filesz);
603 // PT_INTERP includes a null byte in p_filesz.
604 const len = p_filesz - 1;
605 // dynamic_linker.max_byte is "max", not "len".
606 // We know it will fit in u8 because we check against dynamic_linker.buffer.len above.
607 result.dynamic_linker.max_byte = @intCast(u8, len - 1);
608
609 // Use it to determine ABI.
610 const full_ld_path = result.dynamic_linker.buffer[0..len];
611 for (ld_info_list) |ld_info| {
612 const standard_ld_basename = fs.path.basename(ld_info.ld.get().?);
613 if (std.mem.endsWith(u8, full_ld_path, standard_ld_basename)) {
614 result.target.abi = ld_info.abi;
615 break;
616 }
617 }
618 },
619 // We only need this for detecting glibc version.
620 elf.PT_DYNAMIC => if (Target.current.os.tag == .linux and result.target.isGnuLibC() and
621 cross_target.glibc_version == null)
622 {
623 var dyn_off = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);
624 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);
625 const dyn_size: u64 = if (is_64) @sizeOf(elf.Elf64_Dyn) else @sizeOf(elf.Elf32_Dyn);
626 const dyn_num = p_filesz / dyn_size;
627 var dyn_buf: [16 * @sizeOf(elf.Elf64_Dyn)]u8 align(@alignOf(elf.Elf64_Dyn)) = undefined;
628 var dyn_i: usize = 0;
629 dyn: while (dyn_i < dyn_num) {
630 // Reserve some bytes so that we can deref the 64-bit struct fields
631 // even when the ELF file is 32-bits.
632 const dyn_reserve: usize = @sizeOf(elf.Elf64_Dyn) - @sizeOf(elf.Elf32_Dyn);
633 const dyn_read_byte_len = try preadFull(
634 file,
635 dyn_buf[0 .. dyn_buf.len - dyn_reserve],
636 dyn_off,
637 dyn_size,
638 );
639 var dyn_buf_i: usize = 0;
640 while (dyn_buf_i < dyn_read_byte_len and dyn_i < dyn_num) : ({
641 dyn_i += 1;
642 dyn_off += dyn_size;
643 dyn_buf_i += dyn_size;
644 }) {
645 const dyn32 = @ptrCast(
646 *elf.Elf32_Dyn,
647 @alignCast(@alignOf(elf.Elf32_Dyn), &dyn_buf[dyn_buf_i]),
648 );
649 const dyn64 = @ptrCast(
650 *elf.Elf64_Dyn,
651 @alignCast(@alignOf(elf.Elf64_Dyn), &dyn_buf[dyn_buf_i]),
652 );
653 const tag = elfInt(is_64, need_bswap, dyn32.d_tag, dyn64.d_tag);
654 const val = elfInt(is_64, need_bswap, dyn32.d_val, dyn64.d_val);
655 if (tag == elf.DT_RUNPATH) {
656 rpath_offset = val;
657 break :dyn;
658 }
659 }
660 }
661 },
662 else => continue,
663 }
664 }
665 }
666
667 if (Target.current.os.tag == .linux and result.target.isGnuLibC() and cross_target.glibc_version == null) {
668 if (rpath_offset) |rpoff| {
669 const shstrndx = elfInt(is_64, need_bswap, hdr32.e_shstrndx, hdr64.e_shstrndx);
670
671 var shoff = elfInt(is_64, need_bswap, hdr32.e_shoff, hdr64.e_shoff);
672 const shentsize = elfInt(is_64, need_bswap, hdr32.e_shentsize, hdr64.e_shentsize);
673 const str_section_off = shoff + @as(u64, shentsize) * @as(u64, shstrndx);
674
675 var sh_buf: [16 * @sizeOf(elf.Elf64_Shdr)]u8 align(@alignOf(elf.Elf64_Shdr)) = undefined;
676 if (sh_buf.len < shentsize) return error.InvalidElfFile;
677
678 _ = try preadFull(file, &sh_buf, str_section_off, shentsize);
679 const shstr32 = @ptrCast(*elf.Elf32_Shdr, @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf));
680 const shstr64 = @ptrCast(*elf.Elf64_Shdr, @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf));
681 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);
682 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);
683 var strtab_buf: [4096:0]u8 = undefined;
684 const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len);
685 const shstrtab_read_len = try preadFull(file, &strtab_buf, shstrtab_off, shstrtab_len);
686 const shstrtab = strtab_buf[0..shstrtab_read_len];
687
688 const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum);
689 var sh_i: u16 = 0;
690 const dynstr: ?struct { offset: u64, size: u64 } = find_dyn_str: while (sh_i < shnum) {
691 // Reserve some bytes so that we can deref the 64-bit struct fields
692 // even when the ELF file is 32-bits.
693 const sh_reserve: usize = @sizeOf(elf.Elf64_Shdr) - @sizeOf(elf.Elf32_Shdr);
694 const sh_read_byte_len = try preadFull(
695 file,
696 sh_buf[0 .. sh_buf.len - sh_reserve],
697 shoff,
698 shentsize,
699 );
700 var sh_buf_i: usize = 0;
701 while (sh_buf_i < sh_read_byte_len and sh_i < shnum) : ({
702 sh_i += 1;
703 shoff += shentsize;
704 sh_buf_i += shentsize;
705 }) {
706 const sh32 = @ptrCast(
707 *elf.Elf32_Shdr,
708 @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf[sh_buf_i]),
709 );
710 const sh64 = @ptrCast(
711 *elf.Elf64_Shdr,
712 @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf[sh_buf_i]),
713 );
714 const sh_name_off = elfInt(is_64, need_bswap, sh32.sh_name, sh64.sh_name);
715 // TODO this pointer cast should not be necessary
716 const sh_name = mem.toSliceConst(u8, @ptrCast([*:0]u8, shstrtab[sh_name_off..].ptr));
717 if (mem.eql(u8, sh_name, ".dynstr")) {
718 break :find_dyn_str .{
719 .offset = elfInt(is_64, need_bswap, sh32.sh_offset, sh64.sh_offset),
720 .size = elfInt(is_64, need_bswap, sh32.sh_size, sh64.sh_size),
721 };
722 }
723 }
724 } else null;
725
726 if (dynstr) |ds| {
727 const strtab_len = std.math.min(ds.size, strtab_buf.len);
728 const strtab_read_len = try preadFull(file, &strtab_buf, ds.offset, shstrtab_len);
729 const strtab = strtab_buf[0..strtab_read_len];
730 // TODO this pointer cast should not be necessary
731 const rpath_list = mem.toSliceConst(u8, @ptrCast([*:0]u8, strtab[rpoff..].ptr));
732 var it = mem.tokenize(rpath_list, ":");
733 while (it.next()) |rpath| {
734 var dir = fs.cwd().openDirList(rpath) catch |err| switch (err) {
735 error.NameTooLong => unreachable,
736 error.InvalidUtf8 => unreachable,
737 error.BadPathName => unreachable,
738 error.DeviceBusy => unreachable,
739
740 error.FileNotFound,
741 error.NotDir,
742 error.AccessDenied,
743 error.NoDevice,
744 => continue,
745
746 error.ProcessFdQuotaExceeded,
747 error.SystemFdQuotaExceeded,
748 error.SystemResources,
749 error.SymLinkLoop,
750 error.Unexpected,
751 => |e| return e,
752 };
753 defer dir.close();
754
755 var link_buf: [std.os.PATH_MAX]u8 = undefined;
756 const link_name = std.os.readlinkatC(
757 dir.fd,
758 glibc_so_basename,
759 &link_buf,
760 ) catch |err| switch (err) {
761 error.NameTooLong => unreachable,
762
763 error.AccessDenied,
764 error.FileNotFound,
765 error.NotDir,
766 => continue,
767
768 error.SystemResources,
769 error.FileSystem,
770 error.SymLinkLoop,
771 error.Unexpected,
772 => |e| return e,
773 };
774 result.target.os.version_range.linux.glibc = glibcVerFromLinkName(
775 link_name,
776 ) catch |err| switch (err) {
777 error.UnrecognizedGnuLibCFileName,
778 error.InvalidGnuLibCVersion,
779 => continue,
780 };
781 break;
782 }
783 }
784 }
785 }
786
787 return result;
788 }
789
790 fn preadFull(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize {
791 var i: u64 = 0;
792 while (i < min_read_len) {
793 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {
794 error.OperationAborted => unreachable, // Windows-only
795 error.WouldBlock => unreachable, // Did not request blocking mode
796 error.SystemResources => return error.SystemResources,
797 error.IsDir => return error.UnableToReadElfFile,
798 error.BrokenPipe => return error.UnableToReadElfFile,
799 error.ConnectionResetByPeer => return error.UnableToReadElfFile,
800 error.Unexpected => return error.Unexpected,
801 error.InputOutput => return error.FileSystem,
802 };
803 if (len == 0) return error.UnexpectedEndOfFile;
804 i += len;
805 }
806 return i;
807 }
808
809 fn defaultAbiAndDynamicLinker(cpu: Target.Cpu, os: Target.Os, cross_target: CrossTarget) !NativeTargetInfo {
810 const target: Target = .{
811 .cpu = cpu,
812 .os = os,
813 .abi = cross_target.abi orelse Target.Abi.default(cpu.arch, os),
814 };
815 return NativeTargetInfo{
816 .target = target,
817 .dynamic_linker = if (cross_target.dynamic_linker.get() == null)
818 target.standardDynamicLinkerPath()
819 else
820 cross_target.dynamic_linker,
821 };
822 }
823
824 pub const LdInfo = struct {
825 ld: DynamicLinker,
826 abi: Target.Abi,
827 };
828
829 fn elfInt(is_64: bool, need_bswap: bool, int_32: var, int_64: var) @TypeOf(int_64) {
830 if (is_64) {
831 if (need_bswap) {
832 return @byteSwap(@TypeOf(int_64), int_64);
833 } else {
834 return int_64;
835 }
836 } else {
837 if (need_bswap) {
838 return @byteSwap(@TypeOf(int_32), int_32);
839 } else {
840 return int_32;
841 }
842 }
843 }
844
845 fn detectNativeCpuAndFeatures(cross_target: CrossTarget) Target.Cpu {
846 // TODO Detect native CPU model & features. Until that is implemented we use baseline.
847 return baselineCpuAndFeatures(cross_target);
848 }
849
850 fn baselineCpuAndFeatures(cross_target: CrossTarget) Target.Cpu {
851 var adjusted_baseline = Target.Cpu.baseline(cross_target.getCpuArch());
852 cross_target.updateCpuFeatures(&adjusted_baseline.features);
853 return adjusted_baseline;
854 }
855};
src-self-hosted/c_int.zig+1-1
...@@ -70,7 +70,7 @@ pub const CInt = struct {...@@ -70,7 +70,7 @@ pub const CInt = struct {
7070
71 pub fn sizeInBits(cint: CInt, self: Target) u32 {71 pub fn sizeInBits(cint: CInt, self: Target) u32 {
72 const arch = self.getArch();72 const arch = self.getArch();
73 switch (self.getOs()) {73 switch (self.os.tag) {
74 .freestanding, .other => switch (self.getArch()) {74 .freestanding, .other => switch (self.getArch()) {
75 .msp430 => switch (cint.id) {75 .msp430 => switch (cint.id) {
76 .Short,76 .Short,
src-self-hosted/clang.zig+1-1
...@@ -1050,7 +1050,7 @@ pub const struct_ZigClangExprEvalResult = extern struct {...@@ -1050,7 +1050,7 @@ pub const struct_ZigClangExprEvalResult = extern struct {
10501050
1051pub const struct_ZigClangAPValue = extern struct {1051pub const struct_ZigClangAPValue = extern struct {
1052 Kind: ZigClangAPValueKind,1052 Kind: ZigClangAPValueKind,
1053 Data: if (builtin.os == .windows and builtin.abi == .msvc) [52]u8 else [68]u8,1053 Data: if (builtin.os.tag == .windows and builtin.abi == .msvc) [52]u8 else [68]u8,
1054};1054};
1055pub extern fn ZigClangVarDecl_getTypeSourceInfo_getType(self: *const struct_ZigClangVarDecl) struct_ZigClangQualType;1055pub extern fn ZigClangVarDecl_getTypeSourceInfo_getType(self: *const struct_ZigClangVarDecl) struct_ZigClangQualType;
10561056
src-self-hosted/introspect.zig+1-9
...@@ -1,4 +1,4 @@...@@ -1,4 +1,4 @@
1// Introspection and determination of system libraries needed by zig.1//! Introspection and determination of system libraries needed by zig.
22
3const std = @import("std");3const std = @import("std");
4const mem = std.mem;4const mem = std.mem;
...@@ -6,14 +6,6 @@ const fs = std.fs;...@@ -6,14 +6,6 @@ const fs = std.fs;
66
7const warn = std.debug.warn;7const warn = std.debug.warn;
88
9pub fn detectDynamicLinker(allocator: *mem.Allocator, target: std.Target) ![:0]u8 {
10 if (target == .Native) {
11 return @import("libc_installation.zig").detectNativeDynamicLinker(allocator);
12 } else {
13 return target.getStandardDynamicLinkerPath(allocator);
14 }
15}
16
17/// Caller must free result9/// Caller must free result
18pub fn testZigInstallPrefix(allocator: *mem.Allocator, test_path: []const u8) ![]u8 {10pub fn testZigInstallPrefix(allocator: *mem.Allocator, test_path: []const u8) ![]u8 {
19 const test_zig_dir = try fs.path.join(allocator, &[_][]const u8{ test_path, "lib", "zig" });11 const test_zig_dir = try fs.path.join(allocator, &[_][]const u8{ test_path, "lib", "zig" });
src-self-hosted/libc_installation.zig+12-114
...@@ -7,11 +7,7 @@ const Allocator = std.mem.Allocator;...@@ -7,11 +7,7 @@ const Allocator = std.mem.Allocator;
7const Batch = std.event.Batch;7const Batch = std.event.Batch;
88
9const is_darwin = Target.current.isDarwin();9const is_darwin = Target.current.isDarwin();
10const is_windows = Target.current.isWindows();10const is_windows = Target.current.os.tag == .windows;
11const is_freebsd = Target.current.isFreeBSD();
12const is_netbsd = Target.current.isNetBSD();
13const is_linux = Target.current.isLinux();
14const is_dragonfly = Target.current.isDragonFlyBSD();
15const is_gnu = Target.current.isGnu();11const is_gnu = Target.current.isGnu();
1612
17usingnamespace @import("windows_sdk.zig");13usingnamespace @import("windows_sdk.zig");
...@@ -99,27 +95,27 @@ pub const LibCInstallation = struct {...@@ -99,27 +95,27 @@ pub const LibCInstallation = struct {
99 return error.ParseError;95 return error.ParseError;
100 }96 }
101 if (self.crt_dir == null and !is_darwin) {97 if (self.crt_dir == null and !is_darwin) {
102 try stderr.print("crt_dir may not be empty for {}\n", .{@tagName(Target.current.getOs())});98 try stderr.print("crt_dir may not be empty for {}\n", .{@tagName(Target.current.os.tag)});
103 return error.ParseError;99 return error.ParseError;
104 }100 }
105 if (self.static_crt_dir == null and is_windows and is_gnu) {101 if (self.static_crt_dir == null and is_windows and is_gnu) {
106 try stderr.print("static_crt_dir may not be empty for {}-{}\n", .{102 try stderr.print("static_crt_dir may not be empty for {}-{}\n", .{
107 @tagName(Target.current.getOs()),103 @tagName(Target.current.os.tag),
108 @tagName(Target.current.getAbi()),104 @tagName(Target.current.abi),
109 });105 });
110 return error.ParseError;106 return error.ParseError;
111 }107 }
112 if (self.msvc_lib_dir == null and is_windows and !is_gnu) {108 if (self.msvc_lib_dir == null and is_windows and !is_gnu) {
113 try stderr.print("msvc_lib_dir may not be empty for {}-{}\n", .{109 try stderr.print("msvc_lib_dir may not be empty for {}-{}\n", .{
114 @tagName(Target.current.getOs()),110 @tagName(Target.current.os.tag),
115 @tagName(Target.current.getAbi()),111 @tagName(Target.current.abi),
116 });112 });
117 return error.ParseError;113 return error.ParseError;
118 }114 }
119 if (self.kernel32_lib_dir == null and is_windows and !is_gnu) {115 if (self.kernel32_lib_dir == null and is_windows and !is_gnu) {
120 try stderr.print("kernel32_lib_dir may not be empty for {}-{}\n", .{116 try stderr.print("kernel32_lib_dir may not be empty for {}-{}\n", .{
121 @tagName(Target.current.getOs()),117 @tagName(Target.current.os.tag),
122 @tagName(Target.current.getAbi()),118 @tagName(Target.current.abi),
123 });119 });
124 return error.ParseError;120 return error.ParseError;
125 }121 }
...@@ -216,10 +212,10 @@ pub const LibCInstallation = struct {...@@ -216,10 +212,10 @@ pub const LibCInstallation = struct {
216 var batch = Batch(FindError!void, 2, .auto_async).init();212 var batch = Batch(FindError!void, 2, .auto_async).init();
217 errdefer batch.wait() catch {};213 errdefer batch.wait() catch {};
218 batch.add(&async self.findNativeIncludeDirPosix(args));214 batch.add(&async self.findNativeIncludeDirPosix(args));
219 if (is_freebsd or is_netbsd) {215 switch (Target.current.os.tag) {
220 self.crt_dir = try std.mem.dupeZ(args.allocator, u8, "/usr/lib");216 .freebsd, .netbsd => self.crt_dir = try std.mem.dupeZ(args.allocator, u8, "/usr/lib"),
221 } else if (is_linux or is_dragonfly) {217 .linux, .dragonfly => batch.add(&async self.findNativeCrtDirPosix(args)),
222 batch.add(&async self.findNativeCrtDirPosix(args));218 else => {},
223 }219 }
224 break :blk batch.wait();220 break :blk batch.wait();
225 };221 };
...@@ -616,104 +612,6 @@ fn printVerboseInvocation(...@@ -616,104 +612,6 @@ fn printVerboseInvocation(
616 }612 }
617}613}
618614
619/// Caller owns returned memory.
620pub fn detectNativeDynamicLinker(allocator: *Allocator) error{
621 OutOfMemory,
622 TargetHasNoDynamicLinker,
623 UnknownDynamicLinkerPath,
624}![:0]u8 {
625 if (!comptime Target.current.hasDynamicLinker()) {
626 return error.TargetHasNoDynamicLinker;
627 }
628
629 // The current target's ABI cannot be relied on for this. For example, we may build the zig
630 // compiler for target riscv64-linux-musl and provide a tarball for users to download.
631 // A user could then run that zig compiler on riscv64-linux-gnu. This use case is well-defined
632 // and supported by Zig. But that means that we must detect the system ABI here rather than
633 // relying on `std.Target.current`.
634
635 const LdInfo = struct {
636 ld_path: []u8,
637 abi: Target.Abi,
638 };
639 var ld_info_list = std.ArrayList(LdInfo).init(allocator);
640 defer {
641 for (ld_info_list.toSlice()) |ld_info| allocator.free(ld_info.ld_path);
642 ld_info_list.deinit();
643 }
644
645 const all_abis = comptime blk: {
646 const fields = std.meta.fields(Target.Abi);
647 var array: [fields.len]Target.Abi = undefined;
648 inline for (fields) |field, i| {
649 array[i] = @field(Target.Abi, field.name);
650 }
651 break :blk array;
652 };
653 for (all_abis) |abi| {
654 // This may be a nonsensical parameter. We detect this with error.UnknownDynamicLinkerPath and
655 // skip adding it to `ld_info_list`.
656 const target: Target = .{
657 .Cross = .{
658 .cpu = Target.Cpu.baseline(Target.current.getArch()),
659 .os = Target.current.getOs(),
660 .abi = abi,
661 },
662 };
663 const standard_ld_path = target.getStandardDynamicLinkerPath(allocator) catch |err| switch (err) {
664 error.OutOfMemory => return error.OutOfMemory,
665 error.UnknownDynamicLinkerPath, error.TargetHasNoDynamicLinker => continue,
666 };
667 errdefer allocator.free(standard_ld_path);
668 try ld_info_list.append(.{
669 .ld_path = standard_ld_path,
670 .abi = abi,
671 });
672 }
673
674 // Best case scenario: the zig compiler is dynamically linked, and we can iterate
675 // over our own shared objects and find a dynamic linker.
676 {
677 const lib_paths = try std.process.getSelfExeSharedLibPaths(allocator);
678 defer allocator.free(lib_paths);
679
680 // This is O(N^M) but typical case here is N=2 and M=10.
681 for (lib_paths) |lib_path| {
682 for (ld_info_list.toSlice()) |ld_info| {
683 const standard_ld_basename = fs.path.basename(ld_info.ld_path);
684 if (std.mem.endsWith(u8, lib_path, standard_ld_basename)) {
685 return std.mem.dupeZ(allocator, u8, lib_path);
686 }
687 }
688 }
689 }
690
691 // If Zig is statically linked, such as via distributed binary static builds, the above
692 // trick won't work. What are we left with? Try to run the system C compiler and get
693 // it to tell us the dynamic linker path.
694 // TODO: instead of this, look at the shared libs of /usr/bin/env.
695 for (ld_info_list.toSlice()) |ld_info| {
696 const standard_ld_basename = fs.path.basename(ld_info.ld_path);
697
698 const full_ld_path = ccPrintFileName(.{
699 .allocator = allocator,
700 .search_basename = standard_ld_basename,
701 .want_dirname = .full_path,
702 }) catch |err| switch (err) {
703 error.OutOfMemory => return error.OutOfMemory,
704 error.LibCRuntimeNotFound,
705 error.CCompilerExitCode,
706 error.CCompilerCrashed,
707 error.UnableToSpawnCCompiler,
708 => continue,
709 };
710 return full_ld_path;
711 }
712
713 // Finally, we fall back on the standard path.
714 return Target.current.getStandardDynamicLinkerPath(allocator);
715}
716
717const Search = struct {615const Search = struct {
718 path: []const u8,616 path: []const u8,
719 version: []const u8,617 version: []const u8,
src-self-hosted/link.zig+2-2
...@@ -515,7 +515,7 @@ const DarwinPlatform = struct {...@@ -515,7 +515,7 @@ const DarwinPlatform = struct {
515 break :blk ver;515 break :blk ver;
516 },516 },
517 .None => blk: {517 .None => blk: {
518 assert(comp.target.getOs() == .macosx);518 assert(comp.target.os.tag == .macosx);
519 result.kind = .MacOS;519 result.kind = .MacOS;
520 break :blk "10.14";520 break :blk "10.14";
521 },521 },
...@@ -534,7 +534,7 @@ const DarwinPlatform = struct {...@@ -534,7 +534,7 @@ const DarwinPlatform = struct {
534 }534 }
535535
536 if (result.kind == .IPhoneOS) {536 if (result.kind == .IPhoneOS) {
537 switch (comp.target.getArch()) {537 switch (comp.target.cpu.arch) {
538 .i386,538 .i386,
539 .x86_64,539 .x86_64,
540 => result.kind = .IPhoneOSSimulator,540 => result.kind = .IPhoneOSSimulator,
src-self-hosted/main.zig+10-10
...@@ -79,9 +79,9 @@ pub fn main() !void {...@@ -79,9 +79,9 @@ pub fn main() !void {
79 } else if (mem.eql(u8, cmd, "libc")) {79 } else if (mem.eql(u8, cmd, "libc")) {
80 return cmdLibC(allocator, cmd_args);80 return cmdLibC(allocator, cmd_args);
81 } else if (mem.eql(u8, cmd, "targets")) {81 } else if (mem.eql(u8, cmd, "targets")) {
82 // TODO figure out the current target rather than using the target that was specified when82 const info = try std.zig.system.NativeTargetInfo.detect(allocator);
83 // compiling the compiler83 defer info.deinit(allocator);
84 return @import("print_targets.zig").cmdTargets(allocator, cmd_args, stdout, Target.current);84 return @import("print_targets.zig").cmdTargets(allocator, cmd_args, stdout, info.target);
85 } else if (mem.eql(u8, cmd, "version")) {85 } else if (mem.eql(u8, cmd, "version")) {
86 return cmdVersion(allocator, cmd_args);86 return cmdVersion(allocator, cmd_args);
87 } else if (mem.eql(u8, cmd, "zen")) {87 } else if (mem.eql(u8, cmd, "zen")) {
...@@ -792,7 +792,7 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro...@@ -792,7 +792,7 @@ async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtErro
792}792}
793793
794fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void {794fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void {
795 try stdout.print("{}\n", .{std.mem.toSliceConst(u8, c.ZIG_VERSION_STRING)});795 try stdout.print("{}\n", .{c.ZIG_VERSION_STRING});
796}796}
797797
798fn cmdHelp(allocator: *Allocator, args: []const []const u8) !void {798fn cmdHelp(allocator: *Allocator, args: []const []const u8) !void {
...@@ -863,12 +863,12 @@ fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void {...@@ -863,12 +863,12 @@ fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void {
863 \\ZIG_DIA_GUIDS_LIB {}863 \\ZIG_DIA_GUIDS_LIB {}
864 \\864 \\
865 , .{865 , .{
866 std.mem.toSliceConst(u8, c.ZIG_CMAKE_BINARY_DIR),866 c.ZIG_CMAKE_BINARY_DIR,
867 std.mem.toSliceConst(u8, c.ZIG_CXX_COMPILER),867 c.ZIG_CXX_COMPILER,
868 std.mem.toSliceConst(u8, c.ZIG_LLD_INCLUDE_PATH),868 c.ZIG_LLD_INCLUDE_PATH,
869 std.mem.toSliceConst(u8, c.ZIG_LLD_LIBRARIES),869 c.ZIG_LLD_LIBRARIES,
870 std.mem.toSliceConst(u8, c.ZIG_LLVM_CONFIG_EXE),870 c.ZIG_LLVM_CONFIG_EXE,
871 std.mem.toSliceConst(u8, c.ZIG_DIA_GUIDS_LIB),871 c.ZIG_DIA_GUIDS_LIB,
872 });872 });
873}873}
874874
src-self-hosted/print_targets.zig+6-6
...@@ -124,7 +124,7 @@ pub fn cmdTargets(...@@ -124,7 +124,7 @@ pub fn cmdTargets(
124124
125 try jws.objectField("os");125 try jws.objectField("os");
126 try jws.beginArray();126 try jws.beginArray();
127 inline for (@typeInfo(Target.Os).Enum.fields) |field| {127 inline for (@typeInfo(Target.Os.Tag).Enum.fields) |field| {
128 try jws.arrayElem();128 try jws.arrayElem();
129 try jws.emitString(field.name);129 try jws.emitString(field.name);
130 }130 }
...@@ -201,16 +201,16 @@ pub fn cmdTargets(...@@ -201,16 +201,16 @@ pub fn cmdTargets(
201 try jws.objectField("cpu");201 try jws.objectField("cpu");
202 try jws.beginObject();202 try jws.beginObject();
203 try jws.objectField("arch");203 try jws.objectField("arch");
204 try jws.emitString(@tagName(native_target.getArch()));204 try jws.emitString(@tagName(native_target.cpu.arch));
205205
206 try jws.objectField("name");206 try jws.objectField("name");
207 const cpu = native_target.getCpu();207 const cpu = native_target.cpu;
208 try jws.emitString(cpu.model.name);208 try jws.emitString(cpu.model.name);
209209
210 {210 {
211 try jws.objectField("features");211 try jws.objectField("features");
212 try jws.beginArray();212 try jws.beginArray();
213 for (native_target.getArch().allFeaturesList()) |feature, i_usize| {213 for (native_target.cpu.arch.allFeaturesList()) |feature, i_usize| {
214 const index = @intCast(Target.Cpu.Feature.Set.Index, i_usize);214 const index = @intCast(Target.Cpu.Feature.Set.Index, i_usize);
215 if (cpu.features.isEnabled(index)) {215 if (cpu.features.isEnabled(index)) {
216 try jws.arrayElem();216 try jws.arrayElem();
...@@ -222,9 +222,9 @@ pub fn cmdTargets(...@@ -222,9 +222,9 @@ pub fn cmdTargets(
222 try jws.endObject();222 try jws.endObject();
223 }223 }
224 try jws.objectField("os");224 try jws.objectField("os");
225 try jws.emitString(@tagName(native_target.getOs()));225 try jws.emitString(@tagName(native_target.os.tag));
226 try jws.objectField("abi");226 try jws.objectField("abi");
227 try jws.emitString(@tagName(native_target.getAbi()));227 try jws.emitString(@tagName(native_target.abi));
228 // TODO implement native glibc version detection in self-hosted228 // TODO implement native glibc version detection in self-hosted
229 try jws.endObject();229 try jws.endObject();
230230
src-self-hosted/stage2.zig+279-124
...@@ -10,6 +10,7 @@ const Allocator = mem.Allocator;...@@ -10,6 +10,7 @@ const Allocator = mem.Allocator;
10const ArrayList = std.ArrayList;10const ArrayList = std.ArrayList;
11const Buffer = std.Buffer;11const Buffer = std.Buffer;
12const Target = std.Target;12const Target = std.Target;
13const CrossTarget = std.zig.CrossTarget;
13const self_hosted_main = @import("main.zig");14const self_hosted_main = @import("main.zig");
14const errmsg = @import("errmsg.zig");15const errmsg = @import("errmsg.zig");
15const DepTokenizer = @import("dep_tokenizer.zig").Tokenizer;16const DepTokenizer = @import("dep_tokenizer.zig").Tokenizer;
...@@ -87,7 +88,7 @@ const Error = extern enum {...@@ -87,7 +88,7 @@ const Error = extern enum {
87 NotLazy,88 NotLazy,
88 IsAsync,89 IsAsync,
89 ImportOutsidePkgPath,90 ImportOutsidePkgPath,
90 UnknownCpu,91 UnknownCpuModel,
91 UnknownCpuFeature,92 UnknownCpuFeature,
92 InvalidCpuFeatures,93 InvalidCpuFeatures,
93 InvalidLlvmCpuFeaturesFormat,94 InvalidLlvmCpuFeaturesFormat,
...@@ -110,6 +111,8 @@ const Error = extern enum {...@@ -110,6 +111,8 @@ const Error = extern enum {
110 WindowsSdkNotFound,111 WindowsSdkNotFound,
111 UnknownDynamicLinkerPath,112 UnknownDynamicLinkerPath,
112 TargetHasNoDynamicLinker,113 TargetHasNoDynamicLinker,
114 InvalidAbiVersion,
115 InvalidOperatingSystemVersion,
113};116};
114117
115const FILE = std.c.FILE;118const FILE = std.c.FILE;
...@@ -632,13 +635,9 @@ export fn stage2_cmd_targets(zig_triple: [*:0]const u8) c_int {...@@ -632,13 +635,9 @@ export fn stage2_cmd_targets(zig_triple: [*:0]const u8) c_int {
632}635}
633636
634fn cmdTargets(zig_triple: [*:0]const u8) !void {637fn cmdTargets(zig_triple: [*:0]const u8) !void {
635 var target = try Target.parse(.{ .arch_os_abi = mem.toSliceConst(u8, zig_triple) });638 var cross_target = try CrossTarget.parse(.{ .arch_os_abi = mem.toSliceConst(u8, zig_triple) });
636 target.Cross.cpu = blk: {639 var dynamic_linker: ?[*:0]u8 = null;
637 const llvm = @import("llvm.zig");640 const target = try crossTargetToTarget(cross_target, &dynamic_linker);
638 const llvm_cpu_name = llvm.GetHostCPUName();
639 const llvm_cpu_features = llvm.GetNativeFeatures();
640 break :blk try detectNativeCpuWithLLVM(target.getArch(), llvm_cpu_name, llvm_cpu_features);
641 };
642 return @import("print_targets.zig").cmdTargets(641 return @import("print_targets.zig").cmdTargets(
643 std.heap.c_allocator,642 std.heap.c_allocator,
644 &[0][]u8{},643 &[0][]u8{},
...@@ -652,16 +651,24 @@ export fn stage2_target_parse(...@@ -652,16 +651,24 @@ export fn stage2_target_parse(
652 target: *Stage2Target,651 target: *Stage2Target,
653 zig_triple: ?[*:0]const u8,652 zig_triple: ?[*:0]const u8,
654 mcpu: ?[*:0]const u8,653 mcpu: ?[*:0]const u8,
654 dynamic_linker: ?[*:0]const u8,
655) Error {655) Error {
656 stage2TargetParse(target, zig_triple, mcpu) catch |err| switch (err) {656 stage2TargetParse(target, zig_triple, mcpu, dynamic_linker) catch |err| switch (err) {
657 error.OutOfMemory => return .OutOfMemory,657 error.OutOfMemory => return .OutOfMemory,
658 error.UnknownArchitecture => return .UnknownArchitecture,658 error.UnknownArchitecture => return .UnknownArchitecture,
659 error.UnknownOperatingSystem => return .UnknownOperatingSystem,659 error.UnknownOperatingSystem => return .UnknownOperatingSystem,
660 error.UnknownApplicationBinaryInterface => return .UnknownApplicationBinaryInterface,660 error.UnknownApplicationBinaryInterface => return .UnknownApplicationBinaryInterface,
661 error.MissingOperatingSystem => return .MissingOperatingSystem,661 error.MissingOperatingSystem => return .MissingOperatingSystem,
662 error.MissingArchitecture => return .MissingArchitecture,
663 error.InvalidLlvmCpuFeaturesFormat => return .InvalidLlvmCpuFeaturesFormat,662 error.InvalidLlvmCpuFeaturesFormat => return .InvalidLlvmCpuFeaturesFormat,
664 error.UnexpectedExtraField => return .SemanticAnalyzeFail,663 error.UnexpectedExtraField => return .SemanticAnalyzeFail,
664 error.InvalidAbiVersion => return .InvalidAbiVersion,
665 error.InvalidOperatingSystemVersion => return .InvalidOperatingSystemVersion,
666 error.FileSystem => return .FileSystem,
667 error.SymLinkLoop => return .SymLinkLoop,
668 error.SystemResources => return .SystemResources,
669 error.ProcessFdQuotaExceeded => return .ProcessFdQuotaExceeded,
670 error.SystemFdQuotaExceeded => return .SystemFdQuotaExceeded,
671 error.DeviceBusy => return .DeviceBusy,
665 };672 };
666 return .None;673 return .None;
667}674}
...@@ -670,17 +677,20 @@ fn stage2TargetParse(...@@ -670,17 +677,20 @@ fn stage2TargetParse(
670 stage1_target: *Stage2Target,677 stage1_target: *Stage2Target,
671 zig_triple_oz: ?[*:0]const u8,678 zig_triple_oz: ?[*:0]const u8,
672 mcpu_oz: ?[*:0]const u8,679 mcpu_oz: ?[*:0]const u8,
680 dynamic_linker_oz: ?[*:0]const u8,
673) !void {681) !void {
674 const target: Target = if (zig_triple_oz) |zig_triple_z| blk: {682 const target: CrossTarget = if (zig_triple_oz) |zig_triple_z| blk: {
675 const zig_triple = mem.toSliceConst(u8, zig_triple_z);683 const zig_triple = mem.toSliceConst(u8, zig_triple_z);
676 const mcpu = if (mcpu_oz) |mcpu_z| mem.toSliceConst(u8, mcpu_z) else "baseline";684 const mcpu = if (mcpu_oz) |mcpu_z| mem.toSliceConst(u8, mcpu_z) else null;
677 var diags: std.Target.ParseOptions.Diagnostics = .{};685 const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.toSliceConst(u8, dl_z) else null;
678 break :blk Target.parse(.{686 var diags: CrossTarget.ParseOptions.Diagnostics = .{};
687 break :blk CrossTarget.parse(.{
679 .arch_os_abi = zig_triple,688 .arch_os_abi = zig_triple,
680 .cpu_features = mcpu,689 .cpu_features = mcpu,
690 .dynamic_linker = dynamic_linker,
681 .diagnostics = &diags,691 .diagnostics = &diags,
682 }) catch |err| switch (err) {692 }) catch |err| switch (err) {
683 error.UnknownCpu => {693 error.UnknownCpuModel => {
684 std.debug.warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{694 std.debug.warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{
685 diags.cpu_name.?,695 diags.cpu_name.?,
686 @tagName(diags.arch.?),696 @tagName(diags.arch.?),
...@@ -706,73 +716,11 @@ fn stage2TargetParse(...@@ -706,73 +716,11 @@ fn stage2TargetParse(
706 },716 },
707 else => |e| return e,717 else => |e| return e,
708 };718 };
709 } else Target.Native;719 } else .{};
710720
711 try stage1_target.fromTarget(target);721 try stage1_target.fromTarget(target);
712}722}
713723
714fn initStage1TargetCpuFeatures(stage1_target: *Stage2Target, cpu: Target.Cpu) !void {
715 const allocator = std.heap.c_allocator;
716 const cache_hash = try std.fmt.allocPrint0(allocator, "{}\n{}", .{
717 cpu.model.name,
718 cpu.features.asBytes(),
719 });
720 errdefer allocator.free(cache_hash);
721
722 const generic_arch_name = cpu.arch.genericName();
723 var builtin_str_buffer = try std.Buffer.allocPrint(allocator,
724 \\Cpu{{
725 \\ .arch = .{},
726 \\ .model = &Target.{}.cpu.{},
727 \\ .features = Target.{}.featureSet(&[_]Target.{}.Feature{{
728 \\
729 , .{
730 @tagName(cpu.arch),
731 generic_arch_name,
732 cpu.model.name,
733 generic_arch_name,
734 generic_arch_name,
735 });
736 defer builtin_str_buffer.deinit();
737
738 var llvm_features_buffer = try std.Buffer.initSize(allocator, 0);
739 defer llvm_features_buffer.deinit();
740
741 for (cpu.arch.allFeaturesList()) |feature, index_usize| {
742 const index = @intCast(Target.Cpu.Feature.Set.Index, index_usize);
743 const is_enabled = cpu.features.isEnabled(index);
744
745 if (feature.llvm_name) |llvm_name| {
746 const plus_or_minus = "-+"[@boolToInt(is_enabled)];
747 try llvm_features_buffer.appendByte(plus_or_minus);
748 try llvm_features_buffer.append(llvm_name);
749 try llvm_features_buffer.append(",");
750 }
751
752 if (is_enabled) {
753 // TODO some kind of "zig identifier escape" function rather than
754 // unconditionally using @"" syntax
755 try builtin_str_buffer.append(" .@\"");
756 try builtin_str_buffer.append(feature.name);
757 try builtin_str_buffer.append("\",\n");
758 }
759 }
760
761 try builtin_str_buffer.append(
762 \\ }),
763 \\};
764 \\
765 );
766
767 assert(mem.endsWith(u8, llvm_features_buffer.toSliceConst(), ","));
768 llvm_features_buffer.shrink(llvm_features_buffer.len() - 1);
769
770 stage1_target.llvm_cpu_name = if (cpu.model.llvm_name) |s| s.ptr else null;
771 stage1_target.llvm_cpu_features = llvm_features_buffer.toOwnedSlice().ptr;
772 stage1_target.builtin_str = builtin_str_buffer.toOwnedSlice().ptr;
773 stage1_target.cache_hash = cache_hash.ptr;
774}
775
776// ABI warning724// ABI warning
777const Stage2LibCInstallation = extern struct {725const Stage2LibCInstallation = extern struct {
778 include_dir: [*:0]const u8,726 include_dir: [*:0]const u8,
...@@ -948,15 +896,18 @@ const Stage2Target = extern struct {...@@ -948,15 +896,18 @@ const Stage2Target = extern struct {
948896
949 is_native: bool,897 is_native: bool,
950898
951 glibc_version: ?*Stage2GLibCVersion, // null means default899 glibc_or_darwin_version: ?*Stage2SemVer,
952900
953 llvm_cpu_name: ?[*:0]const u8,901 llvm_cpu_name: ?[*:0]const u8,
954 llvm_cpu_features: ?[*:0]const u8,902 llvm_cpu_features: ?[*:0]const u8,
955 builtin_str: ?[*:0]const u8,903 cpu_builtin_str: ?[*:0]const u8,
956 cache_hash: ?[*:0]const u8,904 cache_hash: ?[*:0]const u8,
905 os_builtin_str: ?[*:0]const u8,
957906
958 fn toTarget(in_target: Stage2Target) Target {907 dynamic_linker: ?[*:0]const u8,
959 if (in_target.is_native) return .Native;908
909 fn toTarget(in_target: Stage2Target) CrossTarget {
910 if (in_target.is_native) return .{};
960911
961 const in_arch = in_target.arch - 1; // skip over ZigLLVM_UnknownArch912 const in_arch = in_target.arch - 1; // skip over ZigLLVM_UnknownArch
962 const in_os = in_target.os;913 const in_os = in_target.os;
...@@ -965,66 +916,270 @@ const Stage2Target = extern struct {...@@ -965,66 +916,270 @@ const Stage2Target = extern struct {
965 return .{916 return .{
966 .Cross = .{917 .Cross = .{
967 .cpu = Target.Cpu.baseline(enumInt(Target.Cpu.Arch, in_arch)),918 .cpu = Target.Cpu.baseline(enumInt(Target.Cpu.Arch, in_arch)),
968 .os = enumInt(Target.Os, in_os),919 .os = Target.Os.defaultVersionRange(enumInt(Target.Os.Tag, in_os)),
969 .abi = enumInt(Target.Abi, in_abi),920 .abi = enumInt(Target.Abi, in_abi),
970 },921 },
971 };922 };
972 }923 }
973924
974 fn fromTarget(self: *Stage2Target, target: Target) !void {925 fn fromTarget(self: *Stage2Target, cross_target: CrossTarget) !void {
975 const cpu = switch (target) {926 const allocator = std.heap.c_allocator;
976 .Native => blk: {927
977 // TODO self-host CPU model and feature detection instead of relying on LLVM928 var dynamic_linker: ?[*:0]u8 = null;
978 const llvm = @import("llvm.zig");929 const target = try crossTargetToTarget(cross_target, &dynamic_linker);
979 const llvm_cpu_name = llvm.GetHostCPUName();930
980 const llvm_cpu_features = llvm.GetNativeFeatures();931 var cache_hash = try std.Buffer.allocPrint(allocator, "{}\n{}\n", .{
981 break :blk try detectNativeCpuWithLLVM(target.getArch(), llvm_cpu_name, llvm_cpu_features);932 target.cpu.model.name,
982 },933 target.cpu.features.asBytes(),
983 .Cross => target.getCpu(),934 });
935 defer cache_hash.deinit();
936
937 const generic_arch_name = target.cpu.arch.genericName();
938 var cpu_builtin_str_buffer = try std.Buffer.allocPrint(allocator,
939 \\Cpu{{
940 \\ .arch = .{},
941 \\ .model = &Target.{}.cpu.{},
942 \\ .features = Target.{}.featureSet(&[_]Target.{}.Feature{{
943 \\
944 , .{
945 @tagName(target.cpu.arch),
946 generic_arch_name,
947 target.cpu.model.name,
948 generic_arch_name,
949 generic_arch_name,
950 });
951 defer cpu_builtin_str_buffer.deinit();
952
953 var llvm_features_buffer = try std.Buffer.initSize(allocator, 0);
954 defer llvm_features_buffer.deinit();
955
956 for (target.cpu.arch.allFeaturesList()) |feature, index_usize| {
957 const index = @intCast(Target.Cpu.Feature.Set.Index, index_usize);
958 const is_enabled = target.cpu.features.isEnabled(index);
959
960 if (feature.llvm_name) |llvm_name| {
961 const plus_or_minus = "-+"[@boolToInt(is_enabled)];
962 try llvm_features_buffer.appendByte(plus_or_minus);
963 try llvm_features_buffer.append(llvm_name);
964 try llvm_features_buffer.append(",");
965 }
966
967 if (is_enabled) {
968 // TODO some kind of "zig identifier escape" function rather than
969 // unconditionally using @"" syntax
970 try cpu_builtin_str_buffer.append(" .@\"");
971 try cpu_builtin_str_buffer.append(feature.name);
972 try cpu_builtin_str_buffer.append("\",\n");
973 }
974 }
975
976 try cpu_builtin_str_buffer.append(
977 \\ }),
978 \\};
979 \\
980 );
981
982 assert(mem.endsWith(u8, llvm_features_buffer.toSliceConst(), ","));
983 llvm_features_buffer.shrink(llvm_features_buffer.len() - 1);
984
985 var os_builtin_str_buffer = try std.Buffer.allocPrint(allocator,
986 \\Os{{
987 \\ .tag = .{},
988 \\ .version_range = .{{
989 , .{@tagName(target.os.tag)});
990 defer os_builtin_str_buffer.deinit();
991
992 // We'll re-use the OS version range builtin string for the cache hash.
993 const os_builtin_str_ver_start_index = os_builtin_str_buffer.len();
994
995 @setEvalBranchQuota(2000);
996 switch (target.os.tag) {
997 .freestanding,
998 .ananas,
999 .cloudabi,
1000 .dragonfly,
1001 .fuchsia,
1002 .ios,
1003 .kfreebsd,
1004 .lv2,
1005 .solaris,
1006 .haiku,
1007 .minix,
1008 .rtems,
1009 .nacl,
1010 .cnk,
1011 .aix,
1012 .cuda,
1013 .nvcl,
1014 .amdhsa,
1015 .ps4,
1016 .elfiamcu,
1017 .tvos,
1018 .watchos,
1019 .mesa3d,
1020 .contiki,
1021 .amdpal,
1022 .hermit,
1023 .hurd,
1024 .wasi,
1025 .emscripten,
1026 .uefi,
1027 .other,
1028 => try os_builtin_str_buffer.append(" .none = {} }\n"),
1029
1030 .freebsd,
1031 .macosx,
1032 .netbsd,
1033 .openbsd,
1034 => try os_builtin_str_buffer.print(
1035 \\ .semver = .{{
1036 \\ .min = .{{
1037 \\ .major = {},
1038 \\ .minor = {},
1039 \\ .patch = {},
1040 \\ }},
1041 \\ .max = .{{
1042 \\ .major = {},
1043 \\ .minor = {},
1044 \\ .patch = {},
1045 \\ }},
1046 \\ }}}},
1047 \\
1048 , .{
1049 target.os.version_range.semver.min.major,
1050 target.os.version_range.semver.min.minor,
1051 target.os.version_range.semver.min.patch,
1052
1053 target.os.version_range.semver.max.major,
1054 target.os.version_range.semver.max.minor,
1055 target.os.version_range.semver.max.patch,
1056 }),
1057
1058 .linux => try os_builtin_str_buffer.print(
1059 \\ .linux = .{{
1060 \\ .range = .{{
1061 \\ .min = .{{
1062 \\ .major = {},
1063 \\ .minor = {},
1064 \\ .patch = {},
1065 \\ }},
1066 \\ .max = .{{
1067 \\ .major = {},
1068 \\ .minor = {},
1069 \\ .patch = {},
1070 \\ }},
1071 \\ }},
1072 \\ .glibc = .{{
1073 \\ .major = {},
1074 \\ .minor = {},
1075 \\ .patch = {},
1076 \\ }},
1077 \\ }}}},
1078 \\
1079 , .{
1080 target.os.version_range.linux.range.min.major,
1081 target.os.version_range.linux.range.min.minor,
1082 target.os.version_range.linux.range.min.patch,
1083
1084 target.os.version_range.linux.range.max.major,
1085 target.os.version_range.linux.range.max.minor,
1086 target.os.version_range.linux.range.max.patch,
1087
1088 target.os.version_range.linux.glibc.major,
1089 target.os.version_range.linux.glibc.minor,
1090 target.os.version_range.linux.glibc.patch,
1091 }),
1092
1093 .windows => try os_builtin_str_buffer.print(
1094 \\ .windows = .{{
1095 \\ .min = .{},
1096 \\ .max = .{},
1097 \\ }}}},
1098 \\
1099 , .{
1100 @tagName(target.os.version_range.windows.min),
1101 @tagName(target.os.version_range.windows.max),
1102 }),
1103 }
1104 try os_builtin_str_buffer.append("};\n");
1105
1106 try cache_hash.append(
1107 os_builtin_str_buffer.toSlice()[os_builtin_str_ver_start_index..os_builtin_str_buffer.len()],
1108 );
1109
1110 const glibc_or_darwin_version = blk: {
1111 if (target.isGnuLibC()) {
1112 const stage1_glibc = try std.heap.c_allocator.create(Stage2SemVer);
1113 const stage2_glibc = target.os.version_range.linux.glibc;
1114 stage1_glibc.* = .{
1115 .major = stage2_glibc.major,
1116 .minor = stage2_glibc.minor,
1117 .patch = stage2_glibc.patch,
1118 };
1119 break :blk stage1_glibc;
1120 } else if (target.isDarwin()) {
1121 const stage1_semver = try std.heap.c_allocator.create(Stage2SemVer);
1122 const stage2_semver = target.os.version_range.semver.min;
1123 stage1_semver.* = .{
1124 .major = stage2_semver.major,
1125 .minor = stage2_semver.minor,
1126 .patch = stage2_semver.patch,
1127 };
1128 break :blk stage1_semver;
1129 } else {
1130 break :blk null;
1131 }
984 };1132 };
1133
985 self.* = .{1134 self.* = .{
986 .arch = @enumToInt(target.getArch()) + 1, // skip over ZigLLVM_UnknownArch1135 .arch = @enumToInt(target.cpu.arch) + 1, // skip over ZigLLVM_UnknownArch
987 .vendor = 0,1136 .vendor = 0,
988 .os = @enumToInt(target.getOs()),1137 .os = @enumToInt(target.os.tag),
989 .abi = @enumToInt(target.getAbi()),1138 .abi = @enumToInt(target.abi),
990 .llvm_cpu_name = null,1139 .llvm_cpu_name = if (target.cpu.model.llvm_name) |s| s.ptr else null,
991 .llvm_cpu_features = null,1140 .llvm_cpu_features = llvm_features_buffer.toOwnedSlice().ptr,
992 .builtin_str = null,1141 .cpu_builtin_str = cpu_builtin_str_buffer.toOwnedSlice().ptr,
993 .cache_hash = null,1142 .os_builtin_str = os_builtin_str_buffer.toOwnedSlice().ptr,
994 .is_native = target == .Native,1143 .cache_hash = cache_hash.toOwnedSlice().ptr,
995 .glibc_version = null,1144 .is_native = cross_target.isNative(),
1145 .glibc_or_darwin_version = glibc_or_darwin_version,
1146 .dynamic_linker = dynamic_linker,
996 };1147 };
997 try initStage1TargetCpuFeatures(self, cpu);
998 }1148 }
999};1149};
10001150
1151fn enumInt(comptime Enum: type, int: c_int) Enum {
1152 return @intToEnum(Enum, @intCast(@TagType(Enum), int));
1153}
1154
1155fn crossTargetToTarget(cross_target: CrossTarget, dynamic_linker_ptr: *?[*:0]u8) !Target {
1156 var info = try std.zig.system.NativeTargetInfo.detect(std.heap.c_allocator, cross_target);
1157 if (cross_target.cpu_arch == null or cross_target.cpu_model == .native) {
1158 // TODO We want to just use detected_info.target but implementing
1159 // CPU model & feature detection is todo so here we rely on LLVM.
1160 const llvm = @import("llvm.zig");
1161 const llvm_cpu_name = llvm.GetHostCPUName();
1162 const llvm_cpu_features = llvm.GetNativeFeatures();
1163 const arch = std.Target.current.cpu.arch;
1164 info.target.cpu = try detectNativeCpuWithLLVM(arch, llvm_cpu_name, llvm_cpu_features);
1165 cross_target.updateCpuFeatures(&info.target.cpu.features);
1166 info.target.cpu.arch = cross_target.getCpuArch();
1167 }
1168 if (info.dynamic_linker.get()) |dl| {
1169 dynamic_linker_ptr.* = try mem.dupeZ(std.heap.c_allocator, u8, dl);
1170 } else {
1171 dynamic_linker_ptr.* = null;
1172 }
1173 return info.target;
1174}
1175
1001// ABI warning1176// ABI warning
1002const Stage2GLibCVersion = extern struct {1177const Stage2SemVer = extern struct {
1003 major: u32,1178 major: u32,
1004 minor: u32,1179 minor: u32,
1005 patch: u32,1180 patch: u32,
1006};1181};
10071182
1008// ABI warning
1009export fn stage2_detect_dynamic_linker(in_target: *const Stage2Target, out_ptr: *[*:0]u8, out_len: *usize) Error {
1010 const target = in_target.toTarget();
1011 const result = @import("introspect.zig").detectDynamicLinker(
1012 std.heap.c_allocator,
1013 target,
1014 ) catch |err| switch (err) {
1015 error.OutOfMemory => return .OutOfMemory,
1016 error.UnknownDynamicLinkerPath => return .UnknownDynamicLinkerPath,
1017 error.TargetHasNoDynamicLinker => return .TargetHasNoDynamicLinker,
1018 };
1019 out_ptr.* = result.ptr;
1020 out_len.* = result.len;
1021 return .None;
1022}
1023
1024fn enumInt(comptime Enum: type, int: c_int) Enum {
1025 return @intToEnum(Enum, @intCast(@TagType(Enum), int));
1026}
1027
1028// ABI warning1183// ABI warning
1029const Stage2NativePaths = extern struct {1184const Stage2NativePaths = extern struct {
1030 include_dirs_ptr: [*][*:0]u8,1185 include_dirs_ptr: [*][*:0]u8,
src-self-hosted/translate_c.zig+1-1
...@@ -4849,7 +4849,7 @@ fn transPreprocessorEntities(c: *Context, unit: *ZigClangASTUnit) Error!void {...@@ -4849,7 +4849,7 @@ fn transPreprocessorEntities(c: *Context, unit: *ZigClangASTUnit) Error!void {
4849 }4849 }
48504850
4851 const begin_c = ZigClangSourceManager_getCharacterData(c.source_manager, begin_loc);4851 const begin_c = ZigClangSourceManager_getCharacterData(c.source_manager, begin_loc);
4852 const slice = begin_c[0..mem.len(u8, begin_c)];4852 const slice = begin_c[0..mem.len(begin_c)];
48534853
4854 tok_list.shrink(0);4854 tok_list.shrink(0);
4855 var tokenizer = std.c.Tokenizer{4855 var tokenizer = std.c.Tokenizer{
src-self-hosted/util.zig-22
...@@ -34,25 +34,3 @@ pub fn initializeAllTargets() void {...@@ -34,25 +34,3 @@ pub fn initializeAllTargets() void {
34 llvm.InitializeAllAsmPrinters();34 llvm.InitializeAllAsmPrinters();
35 llvm.InitializeAllAsmParsers();35 llvm.InitializeAllAsmParsers();
36}36}
37
38pub fn getTriple(allocator: *std.mem.Allocator, self: std.Target) !std.Buffer {
39 var result = try std.Buffer.initSize(allocator, 0);
40 errdefer result.deinit();
41
42 // LLVM WebAssembly output support requires the target to be activated at
43 // build type with -DCMAKE_LLVM_EXPIERMENTAL_TARGETS_TO_BUILD=WebAssembly.
44 //
45 // LLVM determines the output format based on the abi suffix,
46 // defaulting to an object based on the architecture. The default format in
47 // LLVM 6 sets the wasm arch output incorrectly to ELF. We need to
48 // explicitly set this ourself in order for it to work.
49 //
50 // This is fixed in LLVM 7 and you will be able to get wasm output by
51 // using the target triple `wasm32-unknown-unknown-unknown`.
52 const env_name = if (self.isWasm()) "wasm" else @tagName(self.getAbi());
53
54 var out = &std.io.BufferOutStream.init(&result).stream;
55 try out.print("{}-unknown-{}-{}", .{ @tagName(self.getArch()), @tagName(self.getOs()), env_name });
56
57 return result;
58}
src/all_types.hpp-4
...@@ -2250,14 +2250,11 @@ struct CodeGen {...@@ -2250,14 +2250,11 @@ struct CodeGen {
2250 bool test_is_evented;2250 bool test_is_evented;
2251 CodeModel code_model;2251 CodeModel code_model;
22522252
2253 Buf *mmacosx_version_min;
2254 Buf *mios_version_min;
2255 Buf *root_out_name;2253 Buf *root_out_name;
2256 Buf *test_filter;2254 Buf *test_filter;
2257 Buf *test_name_prefix;2255 Buf *test_name_prefix;
2258 Buf *zig_lib_dir;2256 Buf *zig_lib_dir;
2259 Buf *zig_std_dir;2257 Buf *zig_std_dir;
2260 Buf *dynamic_linker_path;
2261 Buf *version_script_path;2258 Buf *version_script_path;
22622259
2263 const char **llvm_argv;2260 const char **llvm_argv;
...@@ -3267,7 +3264,6 @@ struct IrInstSrcContainerInitList {...@@ -3267,7 +3264,6 @@ struct IrInstSrcContainerInitList {
3267struct IrInstSrcContainerInitFieldsField {3264struct IrInstSrcContainerInitFieldsField {
3268 Buf *name;3265 Buf *name;
3269 AstNode *source_node;3266 AstNode *source_node;
3270 TypeStructField *type_struct_field;
3271 IrInstSrc *result_loc;3267 IrInstSrc *result_loc;
3272};3268};
32733269
src/analyze.cpp+51-33
...@@ -1135,7 +1135,7 @@ Error type_val_resolve_zero_bits(CodeGen *g, ZigValue *type_val, ZigType *parent...@@ -1135,7 +1135,7 @@ Error type_val_resolve_zero_bits(CodeGen *g, ZigValue *type_val, ZigType *parent
1135 // Self-referencing types via pointers are allowed and have non-zero size1135 // Self-referencing types via pointers are allowed and have non-zero size
1136 ZigType *ty = type_val->data.x_type;1136 ZigType *ty = type_val->data.x_type;
1137 while (ty->id == ZigTypeIdPointer &&1137 while (ty->id == ZigTypeIdPointer &&
1138 !ty->data.unionation.resolve_loop_flag_zero_bits)1138 !ty->data.pointer.resolve_loop_flag_zero_bits)
1139 {1139 {
1140 ty = ty->data.pointer.child_type;1140 ty = ty->data.pointer.child_type;
1141 }1141 }
...@@ -3963,7 +3963,7 @@ static void resolve_decl_var(CodeGen *g, TldVar *tld_var, bool allow_lazy) {...@@ -3963,7 +3963,7 @@ static void resolve_decl_var(CodeGen *g, TldVar *tld_var, bool allow_lazy) {
39633963
3964 // TODO more validation for types that can't be used for export/extern variables3964 // TODO more validation for types that can't be used for export/extern variables
3965 ZigType *implicit_type = nullptr;3965 ZigType *implicit_type = nullptr;
3966 if (explicit_type != nullptr && explicit_type->id == ZigTypeIdInvalid) {3966 if (explicit_type != nullptr && type_is_invalid(explicit_type)) {
3967 implicit_type = explicit_type;3967 implicit_type = explicit_type;
3968 } else if (var_decl->expr) {3968 } else if (var_decl->expr) {
3969 init_value = analyze_const_value(g, tld_var->base.parent_scope, var_decl->expr, explicit_type,3969 init_value = analyze_const_value(g, tld_var->base.parent_scope, var_decl->expr, explicit_type,
...@@ -5401,6 +5401,8 @@ bool generic_fn_type_id_eql(GenericFnTypeId *a, GenericFnTypeId *b) {...@@ -5401,6 +5401,8 @@ bool generic_fn_type_id_eql(GenericFnTypeId *a, GenericFnTypeId *b) {
54015401
5402static bool can_mutate_comptime_var_state(ZigValue *value) {5402static bool can_mutate_comptime_var_state(ZigValue *value) {
5403 assert(value != nullptr);5403 assert(value != nullptr);
5404 if (value->special == ConstValSpecialUndef)
5405 return false;
5404 switch (value->type->id) {5406 switch (value->type->id) {
5405 case ZigTypeIdInvalid:5407 case ZigTypeIdInvalid:
5406 zig_unreachable();5408 zig_unreachable();
...@@ -5429,6 +5431,8 @@ static bool can_mutate_comptime_var_state(ZigValue *value) {...@@ -5429,6 +5431,8 @@ static bool can_mutate_comptime_var_state(ZigValue *value) {
5429 return value->data.x_ptr.mut == ConstPtrMutComptimeVar;5431 return value->data.x_ptr.mut == ConstPtrMutComptimeVar;
54305432
5431 case ZigTypeIdArray:5433 case ZigTypeIdArray:
5434 if (value->special == ConstValSpecialUndef)
5435 return false;
5432 if (value->type->data.array.len == 0)5436 if (value->type->data.array.len == 0)
5433 return false;5437 return false;
5434 switch (value->data.x_array.special) {5438 switch (value->data.x_array.special) {
...@@ -6701,8 +6705,16 @@ bool const_values_equal_ptr(ZigValue *a, ZigValue *b) {...@@ -6701,8 +6705,16 @@ bool const_values_equal_ptr(ZigValue *a, ZigValue *b) {
6701}6705}
67026706
6703static bool const_values_equal_array(CodeGen *g, ZigValue *a, ZigValue *b, size_t len) {6707static bool const_values_equal_array(CodeGen *g, ZigValue *a, ZigValue *b, size_t len) {
6704 assert(a->data.x_array.special != ConstArraySpecialUndef);6708 if (a->data.x_array.special == ConstArraySpecialUndef &&
6705 assert(b->data.x_array.special != ConstArraySpecialUndef);6709 b->data.x_array.special == ConstArraySpecialUndef)
6710 {
6711 return true;
6712 }
6713 if (a->data.x_array.special == ConstArraySpecialUndef ||
6714 b->data.x_array.special == ConstArraySpecialUndef)
6715 {
6716 return false;
6717 }
6706 if (a->data.x_array.special == ConstArraySpecialBuf &&6718 if (a->data.x_array.special == ConstArraySpecialBuf &&
6707 b->data.x_array.special == ConstArraySpecialBuf)6719 b->data.x_array.special == ConstArraySpecialBuf)
6708 {6720 {
...@@ -6724,8 +6736,6 @@ static bool const_values_equal_array(CodeGen *g, ZigValue *a, ZigValue *b, size_...@@ -6724,8 +6736,6 @@ static bool const_values_equal_array(CodeGen *g, ZigValue *a, ZigValue *b, size_
67246736
6725bool const_values_equal(CodeGen *g, ZigValue *a, ZigValue *b) {6737bool const_values_equal(CodeGen *g, ZigValue *a, ZigValue *b) {
6726 if (a->type->id != b->type->id) return false;6738 if (a->type->id != b->type->id) return false;
6727 assert(a->special == ConstValSpecialStatic);
6728 assert(b->special == ConstValSpecialStatic);
6729 if (a->type == b->type) {6739 if (a->type == b->type) {
6730 switch (type_has_one_possible_value(g, a->type)) {6740 switch (type_has_one_possible_value(g, a->type)) {
6731 case OnePossibleValueInvalid:6741 case OnePossibleValueInvalid:
...@@ -6736,6 +6746,11 @@ bool const_values_equal(CodeGen *g, ZigValue *a, ZigValue *b) {...@@ -6736,6 +6746,11 @@ bool const_values_equal(CodeGen *g, ZigValue *a, ZigValue *b) {
6736 return true;6746 return true;
6737 }6747 }
6738 }6748 }
6749 if (a->special == ConstValSpecialUndef || b->special == ConstValSpecialUndef) {
6750 return a->special == b->special;
6751 }
6752 assert(a->special == ConstValSpecialStatic);
6753 assert(b->special == ConstValSpecialStatic);
6739 switch (a->type->id) {6754 switch (a->type->id) {
6740 case ZigTypeIdOpaque:6755 case ZigTypeIdOpaque:
6741 zig_unreachable();6756 zig_unreachable();
...@@ -8719,7 +8734,6 @@ static void resolve_llvm_types_optional(CodeGen *g, ZigType *type, ResolveStatus...@@ -8719,7 +8734,6 @@ static void resolve_llvm_types_optional(CodeGen *g, ZigType *type, ResolveStatus
8719 if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return;8734 if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return;
8720 }8735 }
87218736
8722 LLVMTypeRef child_llvm_type = get_llvm_type(g, child_type);
8723 ZigLLVMDIType *child_llvm_di_type = get_llvm_di_type(g, child_type);8737 ZigLLVMDIType *child_llvm_di_type = get_llvm_di_type(g, child_type);
8724 if (type->data.maybe.resolve_status >= wanted_resolve_status) return;8738 if (type->data.maybe.resolve_status >= wanted_resolve_status) return;
87258739
...@@ -8729,35 +8743,28 @@ static void resolve_llvm_types_optional(CodeGen *g, ZigType *type, ResolveStatus...@@ -8729,35 +8743,28 @@ static void resolve_llvm_types_optional(CodeGen *g, ZigType *type, ResolveStatus
8729 };8743 };
8730 LLVMStructSetBody(type->llvm_type, elem_types, 2, false);8744 LLVMStructSetBody(type->llvm_type, elem_types, 2, false);
87318745
8732 uint64_t val_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, child_llvm_type);8746 uint64_t val_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, maybe_child_index);
8733 uint64_t val_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, child_llvm_type);8747 uint64_t maybe_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, maybe_null_index);
8734 uint64_t val_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 0);
87358748
8736 uint64_t maybe_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, bool_llvm_type);8749 ZigLLVMDIType *di_element_types[2];
8737 uint64_t maybe_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, bool_llvm_type);8750 di_element_types[maybe_child_index] =
8738 uint64_t maybe_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 1);
8739
8740 uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, type->llvm_type);
8741 uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, type->llvm_type);
8742
8743 ZigLLVMDIType *di_element_types[] = {
8744 ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),8751 ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
8745 "val", di_file, line,8752 "val", di_file, line,
8746 val_debug_size_in_bits,8753 8 * child_type->abi_size,
8747 val_debug_align_in_bits,8754 8 * child_type->abi_align,
8748 val_offset_in_bits,8755 val_offset_in_bits,
8749 ZigLLVM_DIFlags_Zero, child_llvm_di_type),8756 ZigLLVM_DIFlags_Zero, child_llvm_di_type);
8757 di_element_types[maybe_null_index] =
8750 ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),8758 ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type),
8751 "maybe", di_file, line,8759 "maybe", di_file, line,
8752 maybe_debug_size_in_bits,8760 8*g->builtin_types.entry_bool->abi_size,
8753 maybe_debug_align_in_bits,8761 8*g->builtin_types.entry_bool->abi_align,
8754 maybe_offset_in_bits,8762 maybe_offset_in_bits,
8755 ZigLLVM_DIFlags_Zero, bool_llvm_di_type),8763 ZigLLVM_DIFlags_Zero, bool_llvm_di_type);
8756 };
8757 ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,8764 ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder,
8758 compile_unit_scope,8765 compile_unit_scope,
8759 buf_ptr(&type->name),8766 buf_ptr(&type->name),
8760 di_file, line, debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero,8767 di_file, line, 8 * type->abi_size, 8 * type->abi_align, ZigLLVM_DIFlags_Zero,
8761 nullptr, di_element_types, 2, 0, nullptr, "");8768 nullptr, di_element_types, 2, 0, nullptr, "");
87628769
8763 ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type);8770 ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type);
...@@ -9398,13 +9405,24 @@ void copy_const_val(CodeGen *g, ZigValue *dest, ZigValue *src) {...@@ -9398,13 +9405,24 @@ void copy_const_val(CodeGen *g, ZigValue *dest, ZigValue *src) {
9398 dest->data.x_struct.fields[i]->parent.data.p_struct.field_index = i;9405 dest->data.x_struct.fields[i]->parent.data.p_struct.field_index = i;
9399 }9406 }
9400 } else if (dest->type->id == ZigTypeIdArray) {9407 } else if (dest->type->id == ZigTypeIdArray) {
9401 if (dest->data.x_array.special == ConstArraySpecialNone) {9408 switch (dest->data.x_array.special) {
9402 dest->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(dest->type->data.array.len);9409 case ConstArraySpecialNone: {
9403 for (uint64_t i = 0; i < dest->type->data.array.len; i += 1) {9410 dest->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(dest->type->data.array.len);
9404 copy_const_val(g, &dest->data.x_array.data.s_none.elements[i], &src->data.x_array.data.s_none.elements[i]);9411 for (uint64_t i = 0; i < dest->type->data.array.len; i += 1) {
9405 dest->data.x_array.data.s_none.elements[i].parent.id = ConstParentIdArray;9412 copy_const_val(g, &dest->data.x_array.data.s_none.elements[i], &src->data.x_array.data.s_none.elements[i]);
9406 dest->data.x_array.data.s_none.elements[i].parent.data.p_array.array_val = dest;9413 dest->data.x_array.data.s_none.elements[i].parent.id = ConstParentIdArray;
9407 dest->data.x_array.data.s_none.elements[i].parent.data.p_array.elem_index = i;9414 dest->data.x_array.data.s_none.elements[i].parent.data.p_array.array_val = dest;
9415 dest->data.x_array.data.s_none.elements[i].parent.data.p_array.elem_index = i;
9416 }
9417 break;
9418 }
9419 case ConstArraySpecialUndef: {
9420 // Nothing to copy; the above memcpy did everything we needed.
9421 break;
9422 }
9423 case ConstArraySpecialBuf: {
9424 dest->data.x_array.data.s_buf = buf_create_from_buf(src->data.x_array.data.s_buf);
9425 break;
9408 }9426 }
9409 }9427 }
9410 } else if (type_has_optional_repr(dest->type) && dest->data.x_optional != nullptr) {9428 } else if (type_has_optional_repr(dest->type) && dest->data.x_optional != nullptr) {
src/codegen.cpp+24-90
...@@ -32,31 +32,6 @@ enum ResumeId {...@@ -32,31 +32,6 @@ enum ResumeId {
32 ResumeIdCall,32 ResumeIdCall,
33};33};
3434
35static void init_darwin_native(CodeGen *g) {
36 char *osx_target = getenv("MACOSX_DEPLOYMENT_TARGET");
37 char *ios_target = getenv("IPHONEOS_DEPLOYMENT_TARGET");
38
39 // Allow conflicts among OSX and iOS, but choose the default platform.
40 if (osx_target && ios_target) {
41 if (g->zig_target->arch == ZigLLVM_arm ||
42 g->zig_target->arch == ZigLLVM_aarch64 ||
43 g->zig_target->arch == ZigLLVM_thumb)
44 {
45 osx_target = nullptr;
46 } else {
47 ios_target = nullptr;
48 }
49 }
50
51 if (osx_target) {
52 g->mmacosx_version_min = buf_create_from_str(osx_target);
53 } else if (ios_target) {
54 g->mios_version_min = buf_create_from_str(ios_target);
55 } else if (g->zig_target->os != OsIOS) {
56 g->mmacosx_version_min = buf_create_from_str("10.14");
57 }
58}
59
60static ZigPackage *new_package(const char *root_src_dir, const char *root_src_path, const char *pkg_path) {35static ZigPackage *new_package(const char *root_src_dir, const char *root_src_path, const char *pkg_path) {
61 ZigPackage *entry = heap::c_allocator.create<ZigPackage>();36 ZigPackage *entry = heap::c_allocator.create<ZigPackage>();
62 entry->package_table.init(4);37 entry->package_table.init(4);
...@@ -160,14 +135,6 @@ void codegen_add_framework(CodeGen *g, const char *framework) {...@@ -160,14 +135,6 @@ void codegen_add_framework(CodeGen *g, const char *framework) {
160 g->darwin_frameworks.append(buf_create_from_str(framework));135 g->darwin_frameworks.append(buf_create_from_str(framework));
161}136}
162137
163void codegen_set_mmacosx_version_min(CodeGen *g, Buf *mmacosx_version_min) {
164 g->mmacosx_version_min = mmacosx_version_min;
165}
166
167void codegen_set_mios_version_min(CodeGen *g, Buf *mios_version_min) {
168 g->mios_version_min = mios_version_min;
169}
170
171void codegen_set_rdynamic(CodeGen *g, bool rdynamic) {138void codegen_set_rdynamic(CodeGen *g, bool rdynamic) {
172 g->linker_rdynamic = rdynamic;139 g->linker_rdynamic = rdynamic;
173}140}
...@@ -973,7 +940,7 @@ static Buf *panic_msg_buf(PanicMsgId msg_id) {...@@ -973,7 +940,7 @@ static Buf *panic_msg_buf(PanicMsgId msg_id) {
973 case PanicMsgIdExactDivisionRemainder:940 case PanicMsgIdExactDivisionRemainder:
974 return buf_create_from_str("exact division produced remainder");941 return buf_create_from_str("exact division produced remainder");
975 case PanicMsgIdUnwrapOptionalFail:942 case PanicMsgIdUnwrapOptionalFail:
976 return buf_create_from_str("attempt to unwrap null");943 return buf_create_from_str("attempt to use null value");
977 case PanicMsgIdUnreachable:944 case PanicMsgIdUnreachable:
978 return buf_create_from_str("reached unreachable code");945 return buf_create_from_str("reached unreachable code");
979 case PanicMsgIdInvalidErrorCode:946 case PanicMsgIdInvalidErrorCode:
...@@ -4483,7 +4450,7 @@ static LLVMValueRef ir_render_union_field_ptr(CodeGen *g, IrExecutableGen *execu...@@ -4483,7 +4450,7 @@ static LLVMValueRef ir_render_union_field_ptr(CodeGen *g, IrExecutableGen *execu
44834450
4484 if (!type_has_bits(field->type_entry)) {4451 if (!type_has_bits(field->type_entry)) {
4485 ZigType *tag_type = union_type->data.unionation.tag_type;4452 ZigType *tag_type = union_type->data.unionation.tag_type;
4486 if (!instruction->initializing || !type_has_bits(tag_type))4453 if (!instruction->initializing || tag_type == nullptr || !type_has_bits(tag_type))
4487 return nullptr;4454 return nullptr;
44884455
4489 // The field has no bits but we still have to change the discriminant4456 // The field has no bits but we still have to change the discriminant
...@@ -8543,25 +8510,24 @@ Buf *codegen_generate_builtin_source(CodeGen *g) {...@@ -8543,25 +8510,24 @@ Buf *codegen_generate_builtin_source(CodeGen *g) {
8543 buf_appendf(contents, "pub const link_mode = LinkMode.%s;\n", link_type);8510 buf_appendf(contents, "pub const link_mode = LinkMode.%s;\n", link_type);
8544 buf_appendf(contents, "pub const is_test = %s;\n", bool_to_str(g->is_test_build));8511 buf_appendf(contents, "pub const is_test = %s;\n", bool_to_str(g->is_test_build));
8545 buf_appendf(contents, "pub const single_threaded = %s;\n", bool_to_str(g->is_single_threaded));8512 buf_appendf(contents, "pub const single_threaded = %s;\n", bool_to_str(g->is_single_threaded));
8546 buf_appendf(contents, "pub const os = Os.%s;\n", cur_os);8513 buf_append_str(contents, "/// Deprecated: use `std.Target.cpu.arch`\n");
8547 buf_appendf(contents, "pub const arch = Arch.%s;\n", cur_arch);8514 buf_appendf(contents, "pub const arch = Arch.%s;\n", cur_arch);
8548 buf_appendf(contents, "pub const abi = Abi.%s;\n", cur_abi);8515 buf_appendf(contents, "pub const abi = Abi.%s;\n", cur_abi);
8549 {8516 {
8550 buf_append_str(contents, "pub const cpu: Cpu = ");8517 buf_append_str(contents, "pub const cpu: Cpu = ");
8551 if (g->zig_target->builtin_str != nullptr) {8518 if (g->zig_target->cpu_builtin_str != nullptr) {
8552 buf_append_str(contents, g->zig_target->builtin_str);8519 buf_append_str(contents, g->zig_target->cpu_builtin_str);
8553 } else {8520 } else {
8554 buf_append_str(contents, "Target.Cpu.baseline(arch);\n");8521 buf_appendf(contents, "Target.Cpu.baseline(.%s);\n", cur_arch);
8555 }8522 }
8556 }8523 }
8557 if (g->libc_link_lib != nullptr && g->zig_target->glibc_version != nullptr) {8524 {
8558 buf_appendf(contents,8525 buf_append_str(contents, "pub const os = ");
8559 "pub const glibc_version: ?Version = Version{.major = %d, .minor = %d, .patch = %d};\n",8526 if (g->zig_target->os_builtin_str != nullptr) {
8560 g->zig_target->glibc_version->major,8527 buf_append_str(contents, g->zig_target->os_builtin_str);
8561 g->zig_target->glibc_version->minor,8528 } else {
8562 g->zig_target->glibc_version->patch);8529 buf_appendf(contents, "Target.Os.defaultVersionRange(.%s);\n", cur_os);
8563 } else {8530 }
8564 buf_appendf(contents, "pub const glibc_version: ?Version = null;\n");
8565 }8531 }
8566 buf_appendf(contents, "pub const object_format = ObjectFormat.%s;\n", cur_obj_fmt);8532 buf_appendf(contents, "pub const object_format = ObjectFormat.%s;\n", cur_obj_fmt);
8567 buf_appendf(contents, "pub const mode = %s;\n", build_mode_to_str(g->build_mode));8533 buf_appendf(contents, "pub const mode = %s;\n", build_mode_to_str(g->build_mode));
...@@ -8656,10 +8622,10 @@ static Error define_builtin_compile_vars(CodeGen *g) {...@@ -8656,10 +8622,10 @@ static Error define_builtin_compile_vars(CodeGen *g) {
8656 if (g->zig_target->cache_hash != nullptr) {8622 if (g->zig_target->cache_hash != nullptr) {
8657 cache_str(&cache_hash, g->zig_target->cache_hash);8623 cache_str(&cache_hash, g->zig_target->cache_hash);
8658 }8624 }
8659 if (g->zig_target->glibc_version != nullptr) {8625 if (g->zig_target->glibc_or_darwin_version != nullptr) {
8660 cache_int(&cache_hash, g->zig_target->glibc_version->major);8626 cache_int(&cache_hash, g->zig_target->glibc_or_darwin_version->major);
8661 cache_int(&cache_hash, g->zig_target->glibc_version->minor);8627 cache_int(&cache_hash, g->zig_target->glibc_or_darwin_version->minor);
8662 cache_int(&cache_hash, g->zig_target->glibc_version->patch);8628 cache_int(&cache_hash, g->zig_target->glibc_or_darwin_version->patch);
8663 }8629 }
8664 cache_bool(&cache_hash, g->have_err_ret_tracing);8630 cache_bool(&cache_hash, g->have_err_ret_tracing);
8665 cache_bool(&cache_hash, g->libc_link_lib != nullptr);8631 cache_bool(&cache_hash, g->libc_link_lib != nullptr);
...@@ -8866,28 +8832,6 @@ static void init(CodeGen *g) {...@@ -8866,28 +8832,6 @@ static void init(CodeGen *g) {
8866 }8832 }
8867}8833}
88688834
8869static void detect_dynamic_linker(CodeGen *g) {
8870 Error err;
8871
8872 if (g->dynamic_linker_path != nullptr)
8873 return;
8874 if (!g->have_dynamic_link)
8875 return;
8876 if (g->out_type == OutTypeObj || (g->out_type == OutTypeLib && !g->is_dynamic))
8877 return;
8878
8879 char *dynamic_linker_ptr;
8880 size_t dynamic_linker_len;
8881 if ((err = stage2_detect_dynamic_linker(g->zig_target, &dynamic_linker_ptr, &dynamic_linker_len))) {
8882 if (err == ErrorTargetHasNoDynamicLinker) return;
8883 fprintf(stderr, "Unable to detect dynamic linker: %s\n", err_str(err));
8884 exit(1);
8885 }
8886 g->dynamic_linker_path = buf_create_from_mem(dynamic_linker_ptr, dynamic_linker_len);
8887 // Skips heap::c_allocator because the memory is allocated by stage2 library.
8888 free(dynamic_linker_ptr);
8889}
8890
8891static void detect_libc(CodeGen *g) {8835static void detect_libc(CodeGen *g) {
8892 Error err;8836 Error err;
88938837
...@@ -10323,10 +10267,13 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {...@@ -10323,10 +10267,13 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
10323 if (g->zig_target->cache_hash != nullptr) {10267 if (g->zig_target->cache_hash != nullptr) {
10324 cache_str(ch, g->zig_target->cache_hash);10268 cache_str(ch, g->zig_target->cache_hash);
10325 }10269 }
10326 if (g->zig_target->glibc_version != nullptr) {10270 if (g->zig_target->glibc_or_darwin_version != nullptr) {
10327 cache_int(ch, g->zig_target->glibc_version->major);10271 cache_int(ch, g->zig_target->glibc_or_darwin_version->major);
10328 cache_int(ch, g->zig_target->glibc_version->minor);10272 cache_int(ch, g->zig_target->glibc_or_darwin_version->minor);
10329 cache_int(ch, g->zig_target->glibc_version->patch);10273 cache_int(ch, g->zig_target->glibc_or_darwin_version->patch);
10274 }
10275 if (g->zig_target->dynamic_linker != nullptr) {
10276 cache_str(ch, g->zig_target->dynamic_linker);
10330 }10277 }
10331 cache_int(ch, detect_subsystem(g));10278 cache_int(ch, detect_subsystem(g));
10332 cache_bool(ch, g->strip_debug_symbols);10279 cache_bool(ch, g->strip_debug_symbols);
...@@ -10354,8 +10301,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {...@@ -10354,8 +10301,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
10354 cache_bool(ch, g->emit_bin);10301 cache_bool(ch, g->emit_bin);
10355 cache_bool(ch, g->emit_llvm_ir);10302 cache_bool(ch, g->emit_llvm_ir);
10356 cache_bool(ch, g->emit_asm);10303 cache_bool(ch, g->emit_asm);
10357 cache_buf_opt(ch, g->mmacosx_version_min);
10358 cache_buf_opt(ch, g->mios_version_min);
10359 cache_usize(ch, g->version_major);10304 cache_usize(ch, g->version_major);
10360 cache_usize(ch, g->version_minor);10305 cache_usize(ch, g->version_minor);
10361 cache_usize(ch, g->version_patch);10306 cache_usize(ch, g->version_patch);
...@@ -10370,7 +10315,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {...@@ -10370,7 +10315,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
10370 cache_str(ch, g->libc->msvc_lib_dir);10315 cache_str(ch, g->libc->msvc_lib_dir);
10371 cache_str(ch, g->libc->kernel32_lib_dir);10316 cache_str(ch, g->libc->kernel32_lib_dir);
10372 }10317 }
10373 cache_buf_opt(ch, g->dynamic_linker_path);
10374 cache_buf_opt(ch, g->version_script_path);10318 cache_buf_opt(ch, g->version_script_path);
1037510319
10376 // gen_c_objects appends objects to g->link_objects which we want to include in the hash10320 // gen_c_objects appends objects to g->link_objects which we want to include in the hash
...@@ -10467,7 +10411,6 @@ void codegen_build_and_link(CodeGen *g) {...@@ -10467,7 +10411,6 @@ void codegen_build_and_link(CodeGen *g) {
10467 g->have_err_ret_tracing = detect_err_ret_tracing(g);10411 g->have_err_ret_tracing = detect_err_ret_tracing(g);
10468 g->have_sanitize_c = detect_sanitize_c(g);10412 g->have_sanitize_c = detect_sanitize_c(g);
10469 detect_libc(g);10413 detect_libc(g);
10470 detect_dynamic_linker(g);
1047110414
10472 Buf digest = BUF_INIT;10415 Buf digest = BUF_INIT;
10473 if (g->enable_cache) {10416 if (g->enable_cache) {
...@@ -10664,7 +10607,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o...@@ -10664,7 +10607,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o
10664 child_gen->verbose_cc = parent_gen->verbose_cc;10607 child_gen->verbose_cc = parent_gen->verbose_cc;
10665 child_gen->verbose_llvm_cpu_features = parent_gen->verbose_llvm_cpu_features;10608 child_gen->verbose_llvm_cpu_features = parent_gen->verbose_llvm_cpu_features;
10666 child_gen->llvm_argv = parent_gen->llvm_argv;10609 child_gen->llvm_argv = parent_gen->llvm_argv;
10667 child_gen->dynamic_linker_path = parent_gen->dynamic_linker_path;
1066810610
10669 codegen_set_strip(child_gen, parent_gen->strip_debug_symbols);10611 codegen_set_strip(child_gen, parent_gen->strip_debug_symbols);
10670 child_gen->want_pic = parent_gen->have_pic ? WantPICEnabled : WantPICDisabled;10612 child_gen->want_pic = parent_gen->have_pic ? WantPICEnabled : WantPICDisabled;
...@@ -10672,9 +10614,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o...@@ -10672,9 +10614,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o
1067210614
10673 codegen_set_errmsg_color(child_gen, parent_gen->err_color);10615 codegen_set_errmsg_color(child_gen, parent_gen->err_color);
1067410616
10675 codegen_set_mmacosx_version_min(child_gen, parent_gen->mmacosx_version_min);
10676 codegen_set_mios_version_min(child_gen, parent_gen->mios_version_min);
10677
10678 child_gen->enable_cache = true;10617 child_gen->enable_cache = true;
1067910618
10680 return child_gen;10619 return child_gen;
...@@ -10782,11 +10721,6 @@ CodeGen *codegen_create(Buf *main_pkg_path, Buf *root_src_path, const ZigTarget...@@ -10782,11 +10721,6 @@ CodeGen *codegen_create(Buf *main_pkg_path, Buf *root_src_path, const ZigTarget
10782 g->each_lib_rpath = false;10721 g->each_lib_rpath = false;
10783 } else {10722 } else {
10784 g->each_lib_rpath = true;10723 g->each_lib_rpath = true;
10785
10786 if (target_os_is_darwin(g->zig_target->os)) {
10787 init_darwin_native(g);
10788 }
10789
10790 }10724 }
1079110725
10792 if (target_os_requires_libc(g->zig_target->os)) {10726 if (target_os_requires_libc(g->zig_target->os)) {
src/codegen.hpp-2
...@@ -35,8 +35,6 @@ LinkLib *codegen_add_link_lib(CodeGen *codegen, Buf *lib);...@@ -35,8 +35,6 @@ LinkLib *codegen_add_link_lib(CodeGen *codegen, Buf *lib);
35void codegen_add_framework(CodeGen *codegen, const char *name);35void codegen_add_framework(CodeGen *codegen, const char *name);
36void codegen_add_rpath(CodeGen *codegen, const char *name);36void codegen_add_rpath(CodeGen *codegen, const char *name);
37void codegen_set_rdynamic(CodeGen *g, bool rdynamic);37void codegen_set_rdynamic(CodeGen *g, bool rdynamic);
38void codegen_set_mmacosx_version_min(CodeGen *g, Buf *mmacosx_version_min);
39void codegen_set_mios_version_min(CodeGen *g, Buf *mios_version_min);
40void codegen_set_linker_script(CodeGen *g, const char *linker_script);38void codegen_set_linker_script(CodeGen *g, const char *linker_script);
41void codegen_set_test_filter(CodeGen *g, Buf *filter);39void codegen_set_test_filter(CodeGen *g, Buf *filter);
42void codegen_set_test_name_prefix(CodeGen *g, Buf *prefix);40void codegen_set_test_name_prefix(CodeGen *g, Buf *prefix);
src/compiler.cpp-25
...@@ -4,31 +4,6 @@...@@ -4,31 +4,6 @@
44
5#include <stdio.h>5#include <stdio.h>
66
7Buf *get_self_libc_path(void) {
8 static Buf saved_libc_path = BUF_INIT;
9 static bool searched_for_libc = false;
10
11 for (;;) {
12 if (saved_libc_path.list.length != 0) {
13 return &saved_libc_path;
14 }
15 if (searched_for_libc)
16 return nullptr;
17 ZigList<Buf *> lib_paths = {};
18 Error err;
19 if ((err = os_self_exe_shared_libs(lib_paths)))
20 return nullptr;
21 for (size_t i = 0; i < lib_paths.length; i += 1) {
22 Buf *lib_path = lib_paths.at(i);
23 if (buf_ends_with_str(lib_path, "libc.so.6")) {
24 buf_init_from_buf(&saved_libc_path, lib_path);
25 return &saved_libc_path;
26 }
27 }
28 searched_for_libc = true;
29 }
30}
31
32Error get_compiler_id(Buf **result) {7Error get_compiler_id(Buf **result) {
33 static Buf saved_compiler_id = BUF_INIT;8 static Buf saved_compiler_id = BUF_INIT;
349
src/compiler.hpp-1
...@@ -12,7 +12,6 @@...@@ -12,7 +12,6 @@
12#include "error.hpp"12#include "error.hpp"
1313
14Error get_compiler_id(Buf **result);14Error get_compiler_id(Buf **result);
15Buf *get_self_libc_path(void);
1615
17Buf *get_zig_lib_dir(void);16Buf *get_zig_lib_dir(void);
18Buf *get_zig_special_dir(Buf *zig_lib_dir);17Buf *get_zig_special_dir(Buf *zig_lib_dir);
src/error.cpp+2
...@@ -81,6 +81,8 @@ const char *err_str(Error err) {...@@ -81,6 +81,8 @@ const char *err_str(Error err) {
81 case ErrorWindowsSdkNotFound: return "Windows SDK not found";81 case ErrorWindowsSdkNotFound: return "Windows SDK not found";
82 case ErrorUnknownDynamicLinkerPath: return "unknown dynamic linker path";82 case ErrorUnknownDynamicLinkerPath: return "unknown dynamic linker path";
83 case ErrorTargetHasNoDynamicLinker: return "target has no dynamic linker";83 case ErrorTargetHasNoDynamicLinker: return "target has no dynamic linker";
84 case ErrorInvalidAbiVersion: return "invalid C ABI version";
85 case ErrorInvalidOperatingSystemVersion: return "invalid operating system version";
84 }86 }
85 return "(invalid error)";87 return "(invalid error)";
86}88}
src/glibc.cpp+13-50
...@@ -55,7 +55,7 @@ Error glibc_load_metadata(ZigGLibCAbi **out_result, Buf *zig_lib_dir, bool verbo...@@ -55,7 +55,7 @@ Error glibc_load_metadata(ZigGLibCAbi **out_result, Buf *zig_lib_dir, bool verbo
55 Optional<Slice<uint8_t>> opt_component = SplitIterator_next(&it);55 Optional<Slice<uint8_t>> opt_component = SplitIterator_next(&it);
56 if (!opt_component.is_some) break;56 if (!opt_component.is_some) break;
57 Buf *ver_buf = buf_create_from_slice(opt_component.value);57 Buf *ver_buf = buf_create_from_slice(opt_component.value);
58 ZigGLibCVersion *this_ver = glibc_abi->all_versions.add_one();58 Stage2SemVer *this_ver = glibc_abi->all_versions.add_one();
59 if ((err = target_parse_glibc_version(this_ver, buf_ptr(ver_buf)))) {59 if ((err = target_parse_glibc_version(this_ver, buf_ptr(ver_buf)))) {
60 if (verbose) {60 if (verbose) {
61 fprintf(stderr, "Unable to parse glibc version '%s': %s\n", buf_ptr(ver_buf), err_str(err));61 fprintf(stderr, "Unable to parse glibc version '%s': %s\n", buf_ptr(ver_buf), err_str(err));
...@@ -186,9 +186,9 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con...@@ -186,9 +186,9 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con
186 cache_buf(cache_hash, compiler_id);186 cache_buf(cache_hash, compiler_id);
187 cache_int(cache_hash, target->arch);187 cache_int(cache_hash, target->arch);
188 cache_int(cache_hash, target->abi);188 cache_int(cache_hash, target->abi);
189 cache_int(cache_hash, target->glibc_version->major);189 cache_int(cache_hash, target->glibc_or_darwin_version->major);
190 cache_int(cache_hash, target->glibc_version->minor);190 cache_int(cache_hash, target->glibc_or_darwin_version->minor);
191 cache_int(cache_hash, target->glibc_version->patch);191 cache_int(cache_hash, target->glibc_or_darwin_version->patch);
192192
193 Buf digest = BUF_INIT;193 Buf digest = BUF_INIT;
194 buf_resize(&digest, 0);194 buf_resize(&digest, 0);
...@@ -224,10 +224,10 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con...@@ -224,10 +224,10 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con
224224
225 uint8_t target_ver_index = 0;225 uint8_t target_ver_index = 0;
226 for (;target_ver_index < glibc_abi->all_versions.length; target_ver_index += 1) {226 for (;target_ver_index < glibc_abi->all_versions.length; target_ver_index += 1) {
227 const ZigGLibCVersion *this_ver = &glibc_abi->all_versions.at(target_ver_index);227 const Stage2SemVer *this_ver = &glibc_abi->all_versions.at(target_ver_index);
228 if (this_ver->major == target->glibc_version->major &&228 if (this_ver->major == target->glibc_or_darwin_version->major &&
229 this_ver->minor == target->glibc_version->minor &&229 this_ver->minor == target->glibc_or_darwin_version->minor &&
230 this_ver->patch == target->glibc_version->patch)230 this_ver->patch == target->glibc_or_darwin_version->patch)
231 {231 {
232 break;232 break;
233 }233 }
...@@ -235,9 +235,9 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con...@@ -235,9 +235,9 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con
235 if (target_ver_index == glibc_abi->all_versions.length) {235 if (target_ver_index == glibc_abi->all_versions.length) {
236 if (verbose) {236 if (verbose) {
237 fprintf(stderr, "Unrecognized glibc version: %d.%d.%d\n",237 fprintf(stderr, "Unrecognized glibc version: %d.%d.%d\n",
238 target->glibc_version->major,238 target->glibc_or_darwin_version->major,
239 target->glibc_version->minor,239 target->glibc_or_darwin_version->minor,
240 target->glibc_version->patch);240 target->glibc_or_darwin_version->patch);
241 }241 }
242 return ErrorUnknownABI;242 return ErrorUnknownABI;
243 }243 }
...@@ -246,7 +246,7 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con...@@ -246,7 +246,7 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con
246 Buf *map_contents = buf_alloc();246 Buf *map_contents = buf_alloc();
247247
248 for (uint8_t ver_i = 0; ver_i < glibc_abi->all_versions.length; ver_i += 1) {248 for (uint8_t ver_i = 0; ver_i < glibc_abi->all_versions.length; ver_i += 1) {
249 const ZigGLibCVersion *ver = &glibc_abi->all_versions.at(ver_i);249 const Stage2SemVer *ver = &glibc_abi->all_versions.at(ver_i);
250 if (ver->patch == 0) {250 if (ver->patch == 0) {
251 buf_appendf(map_contents, "GLIBC_%d.%d { };\n", ver->major, ver->minor);251 buf_appendf(map_contents, "GLIBC_%d.%d { };\n", ver->major, ver->minor);
252 } else {252 } else {
...@@ -294,7 +294,7 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con...@@ -294,7 +294,7 @@ Error glibc_build_dummies_and_maps(CodeGen *g, const ZigGLibCAbi *glibc_abi, con
294 uint8_t ver_index = ver_list->versions[ver_i];294 uint8_t ver_index = ver_list->versions[ver_i];
295295
296 Buf *stub_name;296 Buf *stub_name;
297 const ZigGLibCVersion *ver = &glibc_abi->all_versions.at(ver_index);297 const Stage2SemVer *ver = &glibc_abi->all_versions.at(ver_index);
298 const char *sym_name = buf_ptr(libc_fn->name);298 const char *sym_name = buf_ptr(libc_fn->name);
299 if (ver->patch == 0) {299 if (ver->patch == 0) {
300 stub_name = buf_sprintf("%s_%d_%d", sym_name, ver->major, ver->minor);300 stub_name = buf_sprintf("%s_%d_%d", sym_name, ver->major, ver->minor);
...@@ -362,43 +362,6 @@ bool eql_glibc_target(const ZigTarget *a, const ZigTarget *b) {...@@ -362,43 +362,6 @@ bool eql_glibc_target(const ZigTarget *a, const ZigTarget *b) {
362 a->abi == b->abi;362 a->abi == b->abi;
363}363}
364364
365#ifdef ZIG_OS_LINUX
366#include <unistd.h>
367Error glibc_detect_native_version(ZigGLibCVersion *glibc_ver) {
368 Buf *self_libc_path = get_self_libc_path();
369 if (self_libc_path == nullptr) {
370 // TODO There is still more we could do to detect the native glibc version. For example,
371 // we could look at the ELF file of `/usr/bin/env`, find `libc.so.6`, and then `readlink`
372 // to find out the glibc version. This is relevant for the static zig builds distributed
373 // on the download page, since the above detection based on zig's own dynamic linking
374 // will not work.
375
376 return ErrorUnknownABI;
377 }
378 Buf *link_name = buf_alloc();
379 buf_resize(link_name, 4096);
380 ssize_t amt = readlink(buf_ptr(self_libc_path), buf_ptr(link_name), buf_len(link_name));
381 if (amt == -1) {
382 return ErrorUnknownABI;
383 }
384 buf_resize(link_name, amt);
385 if (!buf_starts_with_str(link_name, "libc-") || !buf_ends_with_str(link_name, ".so")) {
386 return ErrorUnknownABI;
387 }
388 // example: "libc-2.3.4.so"
389 // example: "libc-2.27.so"
390 buf_resize(link_name, buf_len(link_name) - 3); // chop off ".so"
391 glibc_ver->major = 2;
392 glibc_ver->minor = 0;
393 glibc_ver->patch = 0;
394 return target_parse_glibc_version(glibc_ver, buf_ptr(link_name) + 5);
395}
396#else
397Error glibc_detect_native_version(ZigGLibCVersion *glibc_ver) {
398 return ErrorUnknownABI;
399}
400#endif
401
402size_t glibc_lib_count(void) {365size_t glibc_lib_count(void) {
403 return array_length(glibc_libs);366 return array_length(glibc_libs);
404}367}
src/glibc.hpp+1-4
...@@ -32,7 +32,7 @@ struct ZigGLibCAbi {...@@ -32,7 +32,7 @@ struct ZigGLibCAbi {
32 Buf *abi_txt_path;32 Buf *abi_txt_path;
33 Buf *vers_txt_path;33 Buf *vers_txt_path;
34 Buf *fns_txt_path;34 Buf *fns_txt_path;
35 ZigList<ZigGLibCVersion> all_versions;35 ZigList<Stage2SemVer> all_versions;
36 ZigList<ZigGLibCFn> all_functions;36 ZigList<ZigGLibCFn> all_functions;
37 // The value is a pointer to all_functions.length items and each item is an index37 // The value is a pointer to all_functions.length items and each item is an index
38 // into all_functions.38 // into all_functions.
...@@ -43,9 +43,6 @@ Error glibc_load_metadata(ZigGLibCAbi **out_result, Buf *zig_lib_dir, bool verbo...@@ -43,9 +43,6 @@ Error glibc_load_metadata(ZigGLibCAbi **out_result, Buf *zig_lib_dir, bool verbo
43Error glibc_build_dummies_and_maps(CodeGen *codegen, const ZigGLibCAbi *glibc_abi, const ZigTarget *target,43Error glibc_build_dummies_and_maps(CodeGen *codegen, const ZigGLibCAbi *glibc_abi, const ZigTarget *target,
44 Buf **out_dir, bool verbose, Stage2ProgressNode *progress_node);44 Buf **out_dir, bool verbose, Stage2ProgressNode *progress_node);
4545
46// returns ErrorUnknownABI when glibc is not the native libc
47Error glibc_detect_native_version(ZigGLibCVersion *glibc_ver);
48
49size_t glibc_lib_count(void);46size_t glibc_lib_count(void);
50const ZigGLibCLib *glibc_lib_enum(size_t index);47const ZigGLibCLib *glibc_lib_enum(size_t index);
51const ZigGLibCLib *glibc_lib_find(const char *name);48const ZigGLibCLib *glibc_lib_find(const char *name);
src/ir.cpp+33-3
...@@ -17829,6 +17829,7 @@ static IrInstGen *ir_analyze_instruction_export(IrAnalyze *ira, IrInstSrcExport...@@ -17829,6 +17829,7 @@ static IrInstGen *ir_analyze_instruction_export(IrAnalyze *ira, IrInstSrcExport
17829 }17829 }
17830 } break;17830 } break;
17831 case ZigTypeIdInt:17831 case ZigTypeIdInt:
17832 want_var_export = true;
17832 break;17833 break;
17833 case ZigTypeIdVoid:17834 case ZigTypeIdVoid:
17834 case ZigTypeIdBool:17835 case ZigTypeIdBool:
...@@ -20399,6 +20400,17 @@ static ZigType *adjust_ptr_len(CodeGen *g, ZigType *ptr_type, PtrLen ptr_len) {...@@ -20399,6 +20400,17 @@ static ZigType *adjust_ptr_len(CodeGen *g, ZigType *ptr_type, PtrLen ptr_len) {
20399 ptr_type->data.pointer.allow_zero);20400 ptr_type->data.pointer.allow_zero);
20400}20401}
2040120402
20403static ZigType *adjust_ptr_allow_zero(CodeGen *g, ZigType *ptr_type, bool allow_zero) {
20404 assert(ptr_type->id == ZigTypeIdPointer);
20405 return get_pointer_to_type_extra(g,
20406 ptr_type->data.pointer.child_type,
20407 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
20408 ptr_type->data.pointer.ptr_len,
20409 ptr_type->data.pointer.explicit_alignment,
20410 ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes,
20411 allow_zero);
20412}
20413
20402static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemPtr *elem_ptr_instruction) {20414static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemPtr *elem_ptr_instruction) {
20403 Error err;20415 Error err;
20404 IrInstGen *array_ptr = elem_ptr_instruction->array_ptr->child;20416 IrInstGen *array_ptr = elem_ptr_instruction->array_ptr->child;
...@@ -25956,6 +25968,8 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i...@@ -25956,6 +25968,8 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
25956 ZigType *non_sentinel_slice_ptr_type;25968 ZigType *non_sentinel_slice_ptr_type;
25957 ZigType *elem_type;25969 ZigType *elem_type;
2595825970
25971 bool generate_non_null_assert = false;
25972
25959 if (array_type->id == ZigTypeIdArray) {25973 if (array_type->id == ZigTypeIdArray) {
25960 elem_type = array_type->data.array.child_type;25974 elem_type = array_type->data.array.child_type;
25961 bool is_comptime_const = ptr_ptr->value->special == ConstValSpecialStatic &&25975 bool is_comptime_const = ptr_ptr->value->special == ConstValSpecialStatic &&
...@@ -25983,6 +25997,14 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i...@@ -25983,6 +25997,14 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
25983 elem_type = array_type->data.pointer.child_type;25997 elem_type = array_type->data.pointer.child_type;
25984 if (array_type->data.pointer.ptr_len == PtrLenC) {25998 if (array_type->data.pointer.ptr_len == PtrLenC) {
25985 array_type = adjust_ptr_len(ira->codegen, array_type, PtrLenUnknown);25999 array_type = adjust_ptr_len(ira->codegen, array_type, PtrLenUnknown);
26000
26001 // C pointers are allowzero by default.
26002 // However, we want to be able to slice them without generating an allowzero slice (see issue #4401).
26003 // To achieve this, we generate a runtime safety check and make the slice type non-allowzero.
26004 if (array_type->data.pointer.allow_zero) {
26005 array_type = adjust_ptr_allow_zero(ira->codegen, array_type, false);
26006 generate_non_null_assert = true;
26007 }
25986 }26008 }
25987 ZigType *maybe_sentineled_slice_ptr_type = array_type;26009 ZigType *maybe_sentineled_slice_ptr_type = array_type;
25988 non_sentinel_slice_ptr_type = adjust_ptr_sentinel(ira->codegen, maybe_sentineled_slice_ptr_type, nullptr);26010 non_sentinel_slice_ptr_type = adjust_ptr_sentinel(ira->codegen, maybe_sentineled_slice_ptr_type, nullptr);
...@@ -26254,7 +26276,6 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i...@@ -26254,7 +26276,6 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
2625426276
26255 IrInstGen *result_loc = ir_resolve_result(ira, &instruction->base.base, instruction->result_loc,26277 IrInstGen *result_loc = ir_resolve_result(ira, &instruction->base.base, instruction->result_loc,
26256 return_type, nullptr, true, true);26278 return_type, nullptr, true, true);
26257
26258 if (result_loc != nullptr) {26279 if (result_loc != nullptr) {
26259 if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) {26280 if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) {
26260 return result_loc;26281 return result_loc;
...@@ -26267,8 +26288,17 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i...@@ -26267,8 +26288,17 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
26267 return ira->codegen->invalid_inst_gen;26288 return ira->codegen->invalid_inst_gen;
26268 }26289 }
2626926290
26270 return ir_build_slice_gen(ira, &instruction->base.base, return_type,26291 if (generate_non_null_assert) {
26271 ptr_ptr, casted_start, end, instruction->safety_check_on, result_loc);26292 IrInstGen *ptr_val = ir_get_deref(ira, &instruction->base.base, ptr_ptr, nullptr);
26293
26294 if (type_is_invalid(ptr_val->value->type))
26295 return ira->codegen->invalid_inst_gen;
26296
26297 ir_build_assert_non_null(ira, &instruction->base.base, ptr_val);
26298 }
26299
26300 return ir_build_slice_gen(ira, &instruction->base.base, return_type, ptr_ptr,
26301 casted_start, end, instruction->safety_check_on, result_loc);
26272}26302}
2627326303
26274static IrInstGen *ir_analyze_instruction_has_field(IrAnalyze *ira, IrInstSrcHasField *instruction) {26304static IrInstGen *ir_analyze_instruction_has_field(IrAnalyze *ira, IrInstSrcHasField *instruction) {
src/link.cpp+19-112
...@@ -1751,9 +1751,9 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1751,9 +1751,9 @@ static void construct_linker_job_elf(LinkJob *lj) {
1751 }1751 }
17521752
1753 if (g->have_dynamic_link && (is_dyn_lib || g->out_type == OutTypeExe)) {1753 if (g->have_dynamic_link && (is_dyn_lib || g->out_type == OutTypeExe)) {
1754 assert(g->dynamic_linker_path != nullptr);1754 assert(g->zig_target->dynamic_linker != nullptr);
1755 lj->args.append("-dynamic-linker");1755 lj->args.append("-dynamic-linker");
1756 lj->args.append(buf_ptr(g->dynamic_linker_path));1756 lj->args.append(g->zig_target->dynamic_linker);
1757 }1757 }
1758 }1758 }
17591759
...@@ -2371,99 +2371,6 @@ static void construct_linker_job_coff(LinkJob *lj) {...@@ -2371,99 +2371,6 @@ static void construct_linker_job_coff(LinkJob *lj) {
2371 }2371 }
2372}2372}
23732373
2374
2375// Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2376// grouped values as integers. Numbers which are not provided are set to 0.
2377// return true if the entire string was parsed (9.2), or all groups were
2378// parsed (10.3.5extrastuff).
2379static bool darwin_get_release_version(const char *str, int *major, int *minor, int *micro, bool *had_extra) {
2380 *had_extra = false;
2381
2382 *major = 0;
2383 *minor = 0;
2384 *micro = 0;
2385
2386 if (*str == '\0')
2387 return false;
2388
2389 char *end;
2390 *major = (int)strtol(str, &end, 10);
2391 if (*str != '\0' && *end == '\0')
2392 return true;
2393 if (*end != '.')
2394 return false;
2395
2396 str = end + 1;
2397 *minor = (int)strtol(str, &end, 10);
2398 if (*str != '\0' && *end == '\0')
2399 return true;
2400 if (*end != '.')
2401 return false;
2402
2403 str = end + 1;
2404 *micro = (int)strtol(str, &end, 10);
2405 if (*str != '\0' && *end == '\0')
2406 return true;
2407 if (str == end)
2408 return false;
2409 *had_extra = true;
2410 return true;
2411}
2412
2413enum DarwinPlatformKind {
2414 MacOS,
2415 IPhoneOS,
2416 IPhoneOSSimulator,
2417};
2418
2419struct DarwinPlatform {
2420 DarwinPlatformKind kind;
2421 int major;
2422 int minor;
2423 int micro;
2424};
2425
2426static void get_darwin_platform(LinkJob *lj, DarwinPlatform *platform) {
2427 CodeGen *g = lj->codegen;
2428
2429 if (g->mmacosx_version_min) {
2430 platform->kind = MacOS;
2431 } else if (g->mios_version_min) {
2432 platform->kind = IPhoneOS;
2433 } else if (g->zig_target->os == OsMacOSX) {
2434 platform->kind = MacOS;
2435 g->mmacosx_version_min = buf_create_from_str("10.14");
2436 } else {
2437 zig_panic("unable to infer -mmacosx-version-min or -mios-version-min");
2438 }
2439
2440 bool had_extra;
2441 if (platform->kind == MacOS) {
2442 if (!darwin_get_release_version(buf_ptr(g->mmacosx_version_min),
2443 &platform->major, &platform->minor, &platform->micro, &had_extra) ||
2444 had_extra || platform->major != 10 || platform->minor >= 100 || platform->micro >= 100)
2445 {
2446 zig_panic("invalid -mmacosx-version-min");
2447 }
2448 } else if (platform->kind == IPhoneOS) {
2449 if (!darwin_get_release_version(buf_ptr(g->mios_version_min),
2450 &platform->major, &platform->minor, &platform->micro, &had_extra) ||
2451 had_extra || platform->major >= 10 || platform->minor >= 100 || platform->micro >= 100)
2452 {
2453 zig_panic("invalid -mios-version-min");
2454 }
2455 } else {
2456 zig_unreachable();
2457 }
2458
2459 if (platform->kind == IPhoneOS &&
2460 (g->zig_target->arch == ZigLLVM_x86 ||
2461 g->zig_target->arch == ZigLLVM_x86_64))
2462 {
2463 platform->kind = IPhoneOSSimulator;
2464 }
2465}
2466
2467static void construct_linker_job_macho(LinkJob *lj) {2374static void construct_linker_job_macho(LinkJob *lj) {
2468 CodeGen *g = lj->codegen;2375 CodeGen *g = lj->codegen;
24692376
...@@ -2507,25 +2414,25 @@ static void construct_linker_job_macho(LinkJob *lj) {...@@ -2507,25 +2414,25 @@ static void construct_linker_job_macho(LinkJob *lj) {
2507 lj->args.append("-arch");2414 lj->args.append("-arch");
2508 lj->args.append(get_darwin_arch_string(g->zig_target));2415 lj->args.append(get_darwin_arch_string(g->zig_target));
25092416
2510 DarwinPlatform platform;2417 if (g->zig_target->glibc_or_darwin_version != nullptr) {
2511 get_darwin_platform(lj, &platform);2418 if (g->zig_target->os == OsMacOSX) {
2512 switch (platform.kind) {
2513 case MacOS:
2514 lj->args.append("-macosx_version_min");2419 lj->args.append("-macosx_version_min");
2515 break;2420 } else if (g->zig_target->os == OsIOS) {
2516 case IPhoneOS:2421 if (g->zig_target->arch == ZigLLVM_x86 || g->zig_target->arch == ZigLLVM_x86_64) {
2517 lj->args.append("-iphoneos_version_min");2422 lj->args.append("-ios_simulator_version_min");
2518 break;2423 } else {
2519 case IPhoneOSSimulator:2424 lj->args.append("-iphoneos_version_min");
2520 lj->args.append("-ios_simulator_version_min");2425 }
2521 break;2426 }
2522 }2427 Buf *version_string = buf_sprintf("%d.%d.%d",
2523 Buf *version_string = buf_sprintf("%d.%d.%d", platform.major, platform.minor, platform.micro);2428 g->zig_target->glibc_or_darwin_version->major,
2524 lj->args.append(buf_ptr(version_string));2429 g->zig_target->glibc_or_darwin_version->minor,
25252430 g->zig_target->glibc_or_darwin_version->patch);
2526 lj->args.append("-sdk_version");2431 lj->args.append(buf_ptr(version_string));
2527 lj->args.append(buf_ptr(version_string));
25282432
2433 lj->args.append("-sdk_version");
2434 lj->args.append(buf_ptr(version_string));
2435 }
25292436
2530 if (g->out_type == OutTypeExe) {2437 if (g->out_type == OutTypeExe) {
2531 lj->args.append("-pie");2438 lj->args.append("-pie");
src/main.cpp+12-54
...@@ -89,8 +89,7 @@ static int print_full_usage(const char *arg0, FILE *file, int return_code) {...@@ -89,8 +89,7 @@ static int print_full_usage(const char *arg0, FILE *file, int return_code) {
89 " --single-threaded source may assume it is only used single-threaded\n"89 " --single-threaded source may assume it is only used single-threaded\n"
90 " -dynamic create a shared library (.so; .dll; .dylib)\n"90 " -dynamic create a shared library (.so; .dll; .dylib)\n"
91 " --strip exclude debug symbols\n"91 " --strip exclude debug symbols\n"
92 " -target [name] <arch><sub>-<os>-<abi> see the targets command\n"92 " -target [name] <arch>-<os>-<abi> see the targets command\n"
93 " -target-glibc [version] target a specific glibc version (default: 2.17)\n"
94 " --verbose-tokenize enable compiler debug output for tokenization\n"93 " --verbose-tokenize enable compiler debug output for tokenization\n"
95 " --verbose-ast enable compiler debug output for AST parsing\n"94 " --verbose-ast enable compiler debug output for AST parsing\n"
96 " --verbose-link enable compiler debug output for linking\n"95 " --verbose-link enable compiler debug output for linking\n"
...@@ -128,8 +127,6 @@ static int print_full_usage(const char *arg0, FILE *file, int return_code) {...@@ -128,8 +127,6 @@ static int print_full_usage(const char *arg0, FILE *file, int return_code) {
128 " --subsystem [subsystem] (windows) /SUBSYSTEM:<subsystem> to the linker\n"127 " --subsystem [subsystem] (windows) /SUBSYSTEM:<subsystem> to the linker\n"
129 " -F[dir] (darwin) add search path for frameworks\n"128 " -F[dir] (darwin) add search path for frameworks\n"
130 " -framework [name] (darwin) link against framework\n"129 " -framework [name] (darwin) link against framework\n"
131 " -mios-version-min [ver] (darwin) set iOS deployment target\n"
132 " -mmacosx-version-min [ver] (darwin) set Mac OS X deployment target\n"
133 " --ver-major [ver] dynamic library semver major version\n"130 " --ver-major [ver] dynamic library semver major version\n"
134 " --ver-minor [ver] dynamic library semver minor version\n"131 " --ver-minor [ver] dynamic library semver minor version\n"
135 " --ver-patch [ver] dynamic library semver patch version\n"132 " --ver-patch [ver] dynamic library semver patch version\n"
...@@ -404,7 +401,7 @@ static int main0(int argc, char **argv) {...@@ -404,7 +401,7 @@ static int main0(int argc, char **argv) {
404 bool link_eh_frame_hdr = false;401 bool link_eh_frame_hdr = false;
405 ErrColor color = ErrColorAuto;402 ErrColor color = ErrColorAuto;
406 CacheOpt enable_cache = CacheOptAuto;403 CacheOpt enable_cache = CacheOptAuto;
407 Buf *dynamic_linker = nullptr;404 const char *dynamic_linker = nullptr;
408 const char *libc_txt = nullptr;405 const char *libc_txt = nullptr;
409 ZigList<const char *> clang_argv = {0};406 ZigList<const char *> clang_argv = {0};
410 ZigList<const char *> lib_dirs = {0};407 ZigList<const char *> lib_dirs = {0};
...@@ -415,11 +412,8 @@ static int main0(int argc, char **argv) {...@@ -415,11 +412,8 @@ static int main0(int argc, char **argv) {
415 bool have_libc = false;412 bool have_libc = false;
416 const char *target_string = nullptr;413 const char *target_string = nullptr;
417 bool rdynamic = false;414 bool rdynamic = false;
418 const char *mmacosx_version_min = nullptr;
419 const char *mios_version_min = nullptr;
420 const char *linker_script = nullptr;415 const char *linker_script = nullptr;
421 Buf *version_script = nullptr;416 Buf *version_script = nullptr;
422 const char *target_glibc = nullptr;
423 ZigList<const char *> rpath_list = {0};417 ZigList<const char *> rpath_list = {0};
424 bool each_lib_rpath = false;418 bool each_lib_rpath = false;
425 ZigList<const char *> objects = {0};419 ZigList<const char *> objects = {0};
...@@ -502,7 +496,10 @@ static int main0(int argc, char **argv) {...@@ -502,7 +496,10 @@ static int main0(int argc, char **argv) {
502 os_path_join(get_zig_special_dir(zig_lib_dir), buf_create_from_str("build_runner.zig"), build_runner_path);496 os_path_join(get_zig_special_dir(zig_lib_dir), buf_create_from_str("build_runner.zig"), build_runner_path);
503497
504 ZigTarget target;498 ZigTarget target;
505 get_native_target(&target);499 if ((err = target_parse_triple(&target, "native", nullptr, nullptr))) {
500 fprintf(stderr, "Unable to get native target: %s\n", err_str(err));
501 return EXIT_FAILURE;
502 }
506503
507 Buf *build_file_buf = buf_create_from_str((build_file != nullptr) ? build_file : "build.zig");504 Buf *build_file_buf = buf_create_from_str((build_file != nullptr) ? build_file : "build.zig");
508 Buf build_file_abs = os_path_resolve(&build_file_buf, 1);505 Buf build_file_abs = os_path_resolve(&build_file_buf, 1);
...@@ -769,7 +766,7 @@ static int main0(int argc, char **argv) {...@@ -769,7 +766,7 @@ static int main0(int argc, char **argv) {
769 } else if (strcmp(arg, "--name") == 0) {766 } else if (strcmp(arg, "--name") == 0) {
770 out_name = argv[i];767 out_name = argv[i];
771 } else if (strcmp(arg, "--dynamic-linker") == 0) {768 } else if (strcmp(arg, "--dynamic-linker") == 0) {
772 dynamic_linker = buf_create_from_str(argv[i]);769 dynamic_linker = argv[i];
773 } else if (strcmp(arg, "--libc") == 0) {770 } else if (strcmp(arg, "--libc") == 0) {
774 libc_txt = argv[i];771 libc_txt = argv[i];
775 } else if (strcmp(arg, "-D") == 0) {772 } else if (strcmp(arg, "-D") == 0) {
...@@ -843,18 +840,12 @@ static int main0(int argc, char **argv) {...@@ -843,18 +840,12 @@ static int main0(int argc, char **argv) {
843 cache_dir = argv[i];840 cache_dir = argv[i];
844 } else if (strcmp(arg, "-target") == 0) {841 } else if (strcmp(arg, "-target") == 0) {
845 target_string = argv[i];842 target_string = argv[i];
846 } else if (strcmp(arg, "-mmacosx-version-min") == 0) {
847 mmacosx_version_min = argv[i];
848 } else if (strcmp(arg, "-mios-version-min") == 0) {
849 mios_version_min = argv[i];
850 } else if (strcmp(arg, "-framework") == 0) {843 } else if (strcmp(arg, "-framework") == 0) {
851 frameworks.append(argv[i]);844 frameworks.append(argv[i]);
852 } else if (strcmp(arg, "--linker-script") == 0) {845 } else if (strcmp(arg, "--linker-script") == 0) {
853 linker_script = argv[i];846 linker_script = argv[i];
854 } else if (strcmp(arg, "--version-script") == 0) {847 } else if (strcmp(arg, "--version-script") == 0) {
855 version_script = buf_create_from_str(argv[i]); 848 version_script = buf_create_from_str(argv[i]);
856 } else if (strcmp(arg, "-target-glibc") == 0) {
857 target_glibc = argv[i];
858 } else if (strcmp(arg, "-rpath") == 0) {849 } else if (strcmp(arg, "-rpath") == 0) {
859 rpath_list.append(argv[i]);850 rpath_list.append(argv[i]);
860 } else if (strcmp(arg, "--test-filter") == 0) {851 } else if (strcmp(arg, "--test-filter") == 0) {
...@@ -977,34 +968,11 @@ static int main0(int argc, char **argv) {...@@ -977,34 +968,11 @@ static int main0(int argc, char **argv) {
977 init_all_targets();968 init_all_targets();
978969
979 ZigTarget target;970 ZigTarget target;
980 if ((err = target_parse_triple(&target, target_string, mcpu))) {971 if ((err = target_parse_triple(&target, target_string, mcpu, dynamic_linker))) {
981 fprintf(stderr, "invalid target: %s\n"972 fprintf(stderr, "invalid target: %s\n"
982 "See `%s targets` to display valid targets.\n", err_str(err), arg0);973 "See `%s targets` to display valid targets.\n", err_str(err), arg0);
983 return print_error_usage(arg0);974 return print_error_usage(arg0);
984 }975 }
985 if (target_is_glibc(&target)) {
986 target.glibc_version = heap::c_allocator.create<ZigGLibCVersion>();
987
988 if (target_glibc != nullptr) {
989 if ((err = target_parse_glibc_version(target.glibc_version, target_glibc))) {
990 fprintf(stderr, "invalid glibc version '%s': %s\n", target_glibc, err_str(err));
991 return print_error_usage(arg0);
992 }
993 } else {
994 target_init_default_glibc_version(&target);
995#if defined(ZIG_OS_LINUX)
996 if (target.is_native) {
997 // TODO self-host glibc version detection, and then this logic can go away
998 if ((err = glibc_detect_native_version(target.glibc_version))) {
999 // Fall back to the default version.
1000 }
1001 }
1002#endif
1003 }
1004 } else if (target_glibc != nullptr) {
1005 fprintf(stderr, "'%s' is not a glibc-compatible target", target_string);
1006 return print_error_usage(arg0);
1007 }
1008976
1009 Buf zig_triple_buf = BUF_INIT;977 Buf zig_triple_buf = BUF_INIT;
1010 target_triple_zig(&zig_triple_buf, &target);978 target_triple_zig(&zig_triple_buf, &target);
...@@ -1225,7 +1193,6 @@ static int main0(int argc, char **argv) {...@@ -1225,7 +1193,6 @@ static int main0(int argc, char **argv) {
12251193
1226 codegen_set_strip(g, strip);1194 codegen_set_strip(g, strip);
1227 g->is_dynamic = is_dynamic;1195 g->is_dynamic = is_dynamic;
1228 g->dynamic_linker_path = dynamic_linker;
1229 g->verbose_tokenize = verbose_tokenize;1196 g->verbose_tokenize = verbose_tokenize;
1230 g->verbose_ast = verbose_ast;1197 g->verbose_ast = verbose_ast;
1231 g->verbose_link = verbose_link;1198 g->verbose_link = verbose_link;
...@@ -1264,18 +1231,6 @@ static int main0(int argc, char **argv) {...@@ -1264,18 +1231,6 @@ static int main0(int argc, char **argv) {
1264 }1231 }
12651232
1266 codegen_set_rdynamic(g, rdynamic);1233 codegen_set_rdynamic(g, rdynamic);
1267 if (mmacosx_version_min && mios_version_min) {
1268 fprintf(stderr, "-mmacosx-version-min and -mios-version-min options not allowed together\n");
1269 return main_exit(root_progress_node, EXIT_FAILURE);
1270 }
1271
1272 if (mmacosx_version_min) {
1273 codegen_set_mmacosx_version_min(g, buf_create_from_str(mmacosx_version_min));
1274 }
1275
1276 if (mios_version_min) {
1277 codegen_set_mios_version_min(g, buf_create_from_str(mios_version_min));
1278 }
12791234
1280 if (test_filter) {1235 if (test_filter) {
1281 codegen_set_test_filter(g, buf_create_from_str(test_filter));1236 codegen_set_test_filter(g, buf_create_from_str(test_filter));
...@@ -1364,7 +1319,10 @@ static int main0(int argc, char **argv) {...@@ -1364,7 +1319,10 @@ static int main0(int argc, char **argv) {
1364 return main_exit(root_progress_node, EXIT_SUCCESS);1319 return main_exit(root_progress_node, EXIT_SUCCESS);
1365 } else if (cmd == CmdTest) {1320 } else if (cmd == CmdTest) {
1366 ZigTarget native;1321 ZigTarget native;
1367 get_native_target(&native);1322 if ((err = target_parse_triple(&native, "native", nullptr, nullptr))) {
1323 fprintf(stderr, "Unable to get native target: %s\n", err_str(err));
1324 return EXIT_FAILURE;
1325 }
13681326
1369 g->enable_cache = get_cache_opt(enable_cache, output_dir == nullptr);1327 g->enable_cache = get_cache_opt(enable_cache, output_dir == nullptr);
1370 codegen_build_and_link(g);1328 codegen_build_and_link(g);
src/os.cpp+2-2
...@@ -1073,8 +1073,8 @@ static Error set_file_times(OsFile file, OsTimeStamp ts) {...@@ -1073,8 +1073,8 @@ static Error set_file_times(OsFile file, OsTimeStamp ts) {
1073 return ErrorNone;1073 return ErrorNone;
1074#else1074#else
1075 struct timespec times[2] = {1075 struct timespec times[2] = {
1076 { ts.sec, ts.nsec },1076 { (time_t)ts.sec, (time_t)ts.nsec },
1077 { ts.sec, ts.nsec },1077 { (time_t)ts.sec, (time_t)ts.nsec },
1078 };1078 };
1079 if (futimens(file, times) == -1) {1079 if (futimens(file, times) == -1) {
1080 switch (errno) {1080 switch (errno) {
src/stage2.cpp+106-9
...@@ -91,7 +91,109 @@ void stage2_progress_complete_one(Stage2ProgressNode *node) {}...@@ -91,7 +91,109 @@ void stage2_progress_complete_one(Stage2ProgressNode *node) {}
91void stage2_progress_disable_tty(Stage2Progress *progress) {}91void stage2_progress_disable_tty(Stage2Progress *progress) {}
92void stage2_progress_update_node(Stage2ProgressNode *node, size_t completed_count, size_t estimated_total_items){}92void stage2_progress_update_node(Stage2ProgressNode *node, size_t completed_count, size_t estimated_total_items){}
9393
94Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu) {94static Os get_zig_os_type(ZigLLVM_OSType os_type) {
95 switch (os_type) {
96 case ZigLLVM_UnknownOS:
97 return OsFreestanding;
98 case ZigLLVM_Ananas:
99 return OsAnanas;
100 case ZigLLVM_CloudABI:
101 return OsCloudABI;
102 case ZigLLVM_DragonFly:
103 return OsDragonFly;
104 case ZigLLVM_FreeBSD:
105 return OsFreeBSD;
106 case ZigLLVM_Fuchsia:
107 return OsFuchsia;
108 case ZigLLVM_IOS:
109 return OsIOS;
110 case ZigLLVM_KFreeBSD:
111 return OsKFreeBSD;
112 case ZigLLVM_Linux:
113 return OsLinux;
114 case ZigLLVM_Lv2:
115 return OsLv2;
116 case ZigLLVM_Darwin:
117 case ZigLLVM_MacOSX:
118 return OsMacOSX;
119 case ZigLLVM_NetBSD:
120 return OsNetBSD;
121 case ZigLLVM_OpenBSD:
122 return OsOpenBSD;
123 case ZigLLVM_Solaris:
124 return OsSolaris;
125 case ZigLLVM_Win32:
126 return OsWindows;
127 case ZigLLVM_Haiku:
128 return OsHaiku;
129 case ZigLLVM_Minix:
130 return OsMinix;
131 case ZigLLVM_RTEMS:
132 return OsRTEMS;
133 case ZigLLVM_NaCl:
134 return OsNaCl;
135 case ZigLLVM_CNK:
136 return OsCNK;
137 case ZigLLVM_AIX:
138 return OsAIX;
139 case ZigLLVM_CUDA:
140 return OsCUDA;
141 case ZigLLVM_NVCL:
142 return OsNVCL;
143 case ZigLLVM_AMDHSA:
144 return OsAMDHSA;
145 case ZigLLVM_PS4:
146 return OsPS4;
147 case ZigLLVM_ELFIAMCU:
148 return OsELFIAMCU;
149 case ZigLLVM_TvOS:
150 return OsTvOS;
151 case ZigLLVM_WatchOS:
152 return OsWatchOS;
153 case ZigLLVM_Mesa3D:
154 return OsMesa3D;
155 case ZigLLVM_Contiki:
156 return OsContiki;
157 case ZigLLVM_AMDPAL:
158 return OsAMDPAL;
159 case ZigLLVM_HermitCore:
160 return OsHermitCore;
161 case ZigLLVM_Hurd:
162 return OsHurd;
163 case ZigLLVM_WASI:
164 return OsWASI;
165 case ZigLLVM_Emscripten:
166 return OsEmscripten;
167 }
168 zig_unreachable();
169}
170
171static void get_native_target(ZigTarget *target) {
172 // first zero initialize
173 *target = {};
174
175 ZigLLVM_OSType os_type;
176 ZigLLVM_ObjectFormatType oformat; // ignored; based on arch/os
177 ZigLLVMGetNativeTarget(
178 &target->arch,
179 &target->vendor,
180 &os_type,
181 &target->abi,
182 &oformat);
183 target->os = get_zig_os_type(os_type);
184 target->is_native = true;
185 if (target->abi == ZigLLVM_UnknownEnvironment) {
186 target->abi = target_default_abi(target->arch, target->os);
187 }
188 if (target_is_glibc(target)) {
189 target->glibc_or_darwin_version = heap::c_allocator.create<Stage2SemVer>();
190 target_init_default_glibc_version(target);
191 }
192}
193
194Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu,
195 const char *dynamic_linker)
196{
95 Error err;197 Error err;
96198
97 if (zig_triple == nullptr) {199 if (zig_triple == nullptr) {
...@@ -100,13 +202,11 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons...@@ -100,13 +202,11 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons
100 if (mcpu == nullptr) {202 if (mcpu == nullptr) {
101 target->llvm_cpu_name = ZigLLVMGetHostCPUName();203 target->llvm_cpu_name = ZigLLVMGetHostCPUName();
102 target->llvm_cpu_features = ZigLLVMGetNativeFeatures();204 target->llvm_cpu_features = ZigLLVMGetNativeFeatures();
103 target->builtin_str = "Target.Cpu.baseline(arch);\n";
104 target->cache_hash = "native\n\n";205 target->cache_hash = "native\n\n";
105 } else if (strcmp(mcpu, "baseline") == 0) {206 } else if (strcmp(mcpu, "baseline") == 0) {
106 target->is_native = false;207 target->is_native = false;
107 target->llvm_cpu_name = "";208 target->llvm_cpu_name = "";
108 target->llvm_cpu_features = "";209 target->llvm_cpu_features = "";
109 target->builtin_str = "Target.Cpu.baseline(arch);\n";
110 target->cache_hash = "baseline\n\n";210 target->cache_hash = "baseline\n\n";
111 } else {211 } else {
112 const char *msg = "stage0 can't handle CPU/features in the target";212 const char *msg = "stage0 can't handle CPU/features in the target";
...@@ -148,10 +248,12 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons...@@ -148,10 +248,12 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons
148 const char *msg = "stage0 can't handle CPU/features in the target";248 const char *msg = "stage0 can't handle CPU/features in the target";
149 stage2_panic(msg, strlen(msg));249 stage2_panic(msg, strlen(msg));
150 }250 }
151 target->builtin_str = "Target.Cpu.baseline(arch);\n";
152 target->cache_hash = "\n\n";251 target->cache_hash = "\n\n";
153 }252 }
154253
254 if (dynamic_linker != nullptr) {
255 target->dynamic_linker = dynamic_linker;
256 }
155 return ErrorNone;257 return ErrorNone;
156}258}
157259
...@@ -186,11 +288,6 @@ enum Error stage2_libc_find_native(struct Stage2LibCInstallation *libc) {...@@ -186,11 +288,6 @@ enum Error stage2_libc_find_native(struct Stage2LibCInstallation *libc) {
186 stage2_panic(msg, strlen(msg));288 stage2_panic(msg, strlen(msg));
187}289}
188290
189enum Error stage2_detect_dynamic_linker(const struct ZigTarget *target, char **out_ptr, size_t *out_len) {
190 const char *msg = "stage0 called stage2_detect_dynamic_linker";
191 stage2_panic(msg, strlen(msg));
192}
193
194enum Error stage2_detect_native_paths(struct Stage2NativePaths *native_paths) {291enum Error stage2_detect_native_paths(struct Stage2NativePaths *native_paths) {
195 native_paths->include_dirs_ptr = nullptr;292 native_paths->include_dirs_ptr = nullptr;
196 native_paths->include_dirs_len = 0;293 native_paths->include_dirs_len = 0;
src/stage2.h+11-11
...@@ -103,6 +103,8 @@ enum Error {...@@ -103,6 +103,8 @@ enum Error {
103 ErrorWindowsSdkNotFound,103 ErrorWindowsSdkNotFound,
104 ErrorUnknownDynamicLinkerPath,104 ErrorUnknownDynamicLinkerPath,
105 ErrorTargetHasNoDynamicLinker,105 ErrorTargetHasNoDynamicLinker,
106 ErrorInvalidAbiVersion,
107 ErrorInvalidOperatingSystemVersion,
106};108};
107109
108// ABI warning110// ABI warning
...@@ -268,14 +270,12 @@ enum Os {...@@ -268,14 +270,12 @@ enum Os {
268};270};
269271
270// ABI warning272// ABI warning
271struct ZigGLibCVersion {273struct Stage2SemVer {
272 uint32_t major; // always 2274 uint32_t major;
273 uint32_t minor;275 uint32_t minor;
274 uint32_t patch;276 uint32_t patch;
275};277};
276278
277struct Stage2TargetData;
278
279// ABI warning279// ABI warning
280struct ZigTarget {280struct ZigTarget {
281 enum ZigLLVM_ArchType arch;281 enum ZigLLVM_ArchType arch;
...@@ -286,20 +286,20 @@ struct ZigTarget {...@@ -286,20 +286,20 @@ struct ZigTarget {
286286
287 bool is_native;287 bool is_native;
288288
289 struct ZigGLibCVersion *glibc_version; // null means default289 // null means default. this is double-purposed to be darwin min version
290 struct Stage2SemVer *glibc_or_darwin_version;
290291
291 const char *llvm_cpu_name;292 const char *llvm_cpu_name;
292 const char *llvm_cpu_features;293 const char *llvm_cpu_features;
293 const char *builtin_str;294 const char *cpu_builtin_str;
294 const char *cache_hash;295 const char *cache_hash;
296 const char *os_builtin_str;
297 const char *dynamic_linker;
295};298};
296299
297// ABI warning300// ABI warning
298ZIG_EXTERN_C enum Error stage2_detect_dynamic_linker(const struct ZigTarget *target,301ZIG_EXTERN_C enum Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu,
299 char **out_ptr, size_t *out_len);302 const char *dynamic_linker);
300
301// ABI warning
302ZIG_EXTERN_C enum Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu);
303303
304304
305// ABI warning305// ABI warning
src/target.cpp+4-104
...@@ -287,83 +287,6 @@ ZigLLVM_OSType get_llvm_os_type(Os os_type) {...@@ -287,83 +287,6 @@ ZigLLVM_OSType get_llvm_os_type(Os os_type) {
287 zig_unreachable();287 zig_unreachable();
288}288}
289289
290static Os get_zig_os_type(ZigLLVM_OSType os_type) {
291 switch (os_type) {
292 case ZigLLVM_UnknownOS:
293 return OsFreestanding;
294 case ZigLLVM_Ananas:
295 return OsAnanas;
296 case ZigLLVM_CloudABI:
297 return OsCloudABI;
298 case ZigLLVM_DragonFly:
299 return OsDragonFly;
300 case ZigLLVM_FreeBSD:
301 return OsFreeBSD;
302 case ZigLLVM_Fuchsia:
303 return OsFuchsia;
304 case ZigLLVM_IOS:
305 return OsIOS;
306 case ZigLLVM_KFreeBSD:
307 return OsKFreeBSD;
308 case ZigLLVM_Linux:
309 return OsLinux;
310 case ZigLLVM_Lv2:
311 return OsLv2;
312 case ZigLLVM_Darwin:
313 case ZigLLVM_MacOSX:
314 return OsMacOSX;
315 case ZigLLVM_NetBSD:
316 return OsNetBSD;
317 case ZigLLVM_OpenBSD:
318 return OsOpenBSD;
319 case ZigLLVM_Solaris:
320 return OsSolaris;
321 case ZigLLVM_Win32:
322 return OsWindows;
323 case ZigLLVM_Haiku:
324 return OsHaiku;
325 case ZigLLVM_Minix:
326 return OsMinix;
327 case ZigLLVM_RTEMS:
328 return OsRTEMS;
329 case ZigLLVM_NaCl:
330 return OsNaCl;
331 case ZigLLVM_CNK:
332 return OsCNK;
333 case ZigLLVM_AIX:
334 return OsAIX;
335 case ZigLLVM_CUDA:
336 return OsCUDA;
337 case ZigLLVM_NVCL:
338 return OsNVCL;
339 case ZigLLVM_AMDHSA:
340 return OsAMDHSA;
341 case ZigLLVM_PS4:
342 return OsPS4;
343 case ZigLLVM_ELFIAMCU:
344 return OsELFIAMCU;
345 case ZigLLVM_TvOS:
346 return OsTvOS;
347 case ZigLLVM_WatchOS:
348 return OsWatchOS;
349 case ZigLLVM_Mesa3D:
350 return OsMesa3D;
351 case ZigLLVM_Contiki:
352 return OsContiki;
353 case ZigLLVM_AMDPAL:
354 return OsAMDPAL;
355 case ZigLLVM_HermitCore:
356 return OsHermitCore;
357 case ZigLLVM_Hurd:
358 return OsHurd;
359 case ZigLLVM_WASI:
360 return OsWASI;
361 case ZigLLVM_Emscripten:
362 return OsEmscripten;
363 }
364 zig_unreachable();
365}
366
367const char *target_os_name(Os os_type) {290const char *target_os_name(Os os_type) {
368 switch (os_type) {291 switch (os_type) {
369 case OsFreestanding:292 case OsFreestanding:
...@@ -424,7 +347,7 @@ const char *target_abi_name(ZigLLVM_EnvironmentType abi) {...@@ -424,7 +347,7 @@ const char *target_abi_name(ZigLLVM_EnvironmentType abi) {
424 return ZigLLVMGetEnvironmentTypeName(abi);347 return ZigLLVMGetEnvironmentTypeName(abi);
425}348}
426349
427Error target_parse_glibc_version(ZigGLibCVersion *glibc_ver, const char *text) {350Error target_parse_glibc_version(Stage2SemVer *glibc_ver, const char *text) {
428 glibc_ver->major = 2;351 glibc_ver->major = 2;
429 glibc_ver->minor = 0;352 glibc_ver->minor = 0;
430 glibc_ver->patch = 0;353 glibc_ver->patch = 0;
...@@ -447,31 +370,8 @@ Error target_parse_glibc_version(ZigGLibCVersion *glibc_ver, const char *text) {...@@ -447,31 +370,8 @@ Error target_parse_glibc_version(ZigGLibCVersion *glibc_ver, const char *text) {
447 return ErrorNone;370 return ErrorNone;
448}371}
449372
450void get_native_target(ZigTarget *target) {
451 // first zero initialize
452 *target = {};
453
454 ZigLLVM_OSType os_type;
455 ZigLLVM_ObjectFormatType oformat; // ignored; based on arch/os
456 ZigLLVMGetNativeTarget(
457 &target->arch,
458 &target->vendor,
459 &os_type,
460 &target->abi,
461 &oformat);
462 target->os = get_zig_os_type(os_type);
463 target->is_native = true;
464 if (target->abi == ZigLLVM_UnknownEnvironment) {
465 target->abi = target_default_abi(target->arch, target->os);
466 }
467 if (target_is_glibc(target)) {
468 target->glibc_version = heap::c_allocator.create<ZigGLibCVersion>();
469 target_init_default_glibc_version(target);
470 }
471}
472
473void target_init_default_glibc_version(ZigTarget *target) {373void target_init_default_glibc_version(ZigTarget *target) {
474 *target->glibc_version = {2, 17, 0};374 *target->glibc_or_darwin_version = {2, 17, 0};
475}375}
476376
477Error target_parse_arch(ZigLLVM_ArchType *out_arch, const char *arch_ptr, size_t arch_len) {377Error target_parse_arch(ZigLLVM_ArchType *out_arch, const char *arch_ptr, size_t arch_len) {
...@@ -510,8 +410,8 @@ Error target_parse_abi(ZigLLVM_EnvironmentType *out_abi, const char *abi_ptr, si...@@ -510,8 +410,8 @@ Error target_parse_abi(ZigLLVM_EnvironmentType *out_abi, const char *abi_ptr, si
510 return ErrorUnknownABI;410 return ErrorUnknownABI;
511}411}
512412
513Error target_parse_triple(ZigTarget *target, const char *triple, const char *mcpu) {413Error target_parse_triple(ZigTarget *target, const char *triple, const char *mcpu, const char *dynamic_linker) {
514 return stage2_target_parse(target, triple, mcpu);414 return stage2_target_parse(target, triple, mcpu, dynamic_linker);
515}415}
516416
517const char *target_arch_name(ZigLLVM_ArchType arch) {417const char *target_arch_name(ZigLLVM_ArchType arch) {
src/target.hpp+2-3
...@@ -41,12 +41,12 @@ enum CIntType {...@@ -41,12 +41,12 @@ enum CIntType {
41 CIntTypeCount,41 CIntTypeCount,
42};42};
4343
44Error target_parse_triple(ZigTarget *target, const char *triple, const char *mcpu);44Error target_parse_triple(ZigTarget *target, const char *triple, const char *mcpu, const char *dynamic_linker);
45Error target_parse_arch(ZigLLVM_ArchType *arch, const char *arch_ptr, size_t arch_len);45Error target_parse_arch(ZigLLVM_ArchType *arch, const char *arch_ptr, size_t arch_len);
46Error target_parse_os(Os *os, const char *os_ptr, size_t os_len);46Error target_parse_os(Os *os, const char *os_ptr, size_t os_len);
47Error target_parse_abi(ZigLLVM_EnvironmentType *abi, const char *abi_ptr, size_t abi_len);47Error target_parse_abi(ZigLLVM_EnvironmentType *abi, const char *abi_ptr, size_t abi_len);
4848
49Error target_parse_glibc_version(ZigGLibCVersion *out, const char *text);49Error target_parse_glibc_version(Stage2SemVer *out, const char *text);
50void target_init_default_glibc_version(ZigTarget *target);50void target_init_default_glibc_version(ZigTarget *target);
5151
52size_t target_arch_count(void);52size_t target_arch_count(void);
...@@ -73,7 +73,6 @@ ZigLLVM_ObjectFormatType target_oformat_enum(size_t index);...@@ -73,7 +73,6 @@ ZigLLVM_ObjectFormatType target_oformat_enum(size_t index);
73const char *target_oformat_name(ZigLLVM_ObjectFormatType oformat);73const char *target_oformat_name(ZigLLVM_ObjectFormatType oformat);
74ZigLLVM_ObjectFormatType target_object_format(const ZigTarget *target);74ZigLLVM_ObjectFormatType target_object_format(const ZigTarget *target);
7575
76void get_native_target(ZigTarget *target);
77void target_triple_llvm(Buf *triple, const ZigTarget *target);76void target_triple_llvm(Buf *triple, const ZigTarget *target);
78void target_triple_zig(Buf *triple, const ZigTarget *target);77void target_triple_zig(Buf *triple, const ZigTarget *target);
7978
test/assemble_and_link.zig+2-2
...@@ -1,8 +1,8 @@...@@ -1,8 +1,8 @@
1const builtin = @import("builtin");1const std = @import("std");
2const tests = @import("tests.zig");2const tests = @import("tests.zig");
33
4pub fn addCases(cases: *tests.CompareOutputContext) void {4pub fn addCases(cases: *tests.CompareOutputContext) void {
5 if (builtin.os == builtin.Os.linux and builtin.arch == builtin.Arch.x86_64) {5 if (std.Target.current.os.tag == .linux and std.Target.current.cpu.arch == .x86_64) {
6 cases.addAsm("hello world linux x86_64",6 cases.addAsm("hello world linux x86_64",
7 \\.text7 \\.text
8 \\.globl _start8 \\.globl _start
test/cli.zig+2-3
...@@ -1,5 +1,4 @@...@@ -1,5 +1,4 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");
3const testing = std.testing;2const testing = std.testing;
4const process = std.process;3const process = std.process;
5const fs = std.fs;4const fs = std.fs;
...@@ -93,11 +92,11 @@ fn testZigInitLib(zig_exe: []const u8, dir_path: []const u8) !void {...@@ -93,11 +92,11 @@ fn testZigInitLib(zig_exe: []const u8, dir_path: []const u8) !void {
93fn testZigInitExe(zig_exe: []const u8, dir_path: []const u8) !void {92fn testZigInitExe(zig_exe: []const u8, dir_path: []const u8) !void {
94 _ = try exec(dir_path, &[_][]const u8{ zig_exe, "init-exe" });93 _ = try exec(dir_path, &[_][]const u8{ zig_exe, "init-exe" });
95 const run_result = try exec(dir_path, &[_][]const u8{ zig_exe, "build", "run" });94 const run_result = try exec(dir_path, &[_][]const u8{ zig_exe, "build", "run" });
96 testing.expect(std.mem.eql(u8, run_result.stderr, "All your base are belong to us.\n"));95 testing.expect(std.mem.eql(u8, run_result.stderr, "All your codebase are belong to us.\n"));
97}96}
9897
99fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {98fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {
100 if (builtin.os != .linux or builtin.arch != .x86_64) return;99 if (std.Target.current.os.tag != .linux or std.Target.current.cpu.arch != .x86_64) return;
101100
102 const example_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.zig" });101 const example_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.zig" });
103 const example_s_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.s" });102 const example_s_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.s" });
test/compare_output.zig+4-5
...@@ -1,4 +1,3 @@...@@ -1,4 +1,3 @@
1const builtin = @import("builtin");
2const std = @import("std");1const std = @import("std");
3const os = std.os;2const os = std.os;
4const tests = @import("tests.zig");3const tests = @import("tests.zig");
...@@ -131,8 +130,8 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -131,8 +130,8 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
131 , "Hello, world!\n 12 12 a\n");130 , "Hello, world!\n 12 12 a\n");
132131
133 cases.addC("number literals",132 cases.addC("number literals",
134 \\const builtin = @import("builtin");133 \\const std = @import("std");
135 \\const is_windows = builtin.os == builtin.Os.windows;134 \\const is_windows = std.Target.current.os.tag == .windows;
136 \\const c = @cImport({135 \\const c = @cImport({
137 \\ if (is_windows) {136 \\ if (is_windows) {
138 \\ // See https://github.com/ziglang/zig/issues/515137 \\ // See https://github.com/ziglang/zig/issues/515
...@@ -306,8 +305,8 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -306,8 +305,8 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
306 , "");305 , "");
307306
308 cases.addC("casting between float and integer types",307 cases.addC("casting between float and integer types",
309 \\const builtin = @import("builtin");308 \\const std = @import("std");
310 \\const is_windows = builtin.os == builtin.Os.windows;309 \\const is_windows = std.Target.current.os.tag == .windows;
311 \\const c = @cImport({310 \\const c = @cImport({
312 \\ if (is_windows) {311 \\ if (is_windows) {
313 \\ // See https://github.com/ziglang/zig/issues/515312 \\ // See https://github.com/ziglang/zig/issues/515
test/compile_errors.zig+10-15
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
2const builtin = @import("builtin");2const std = @import("std");
3const Target = @import("std").Target;
43
5pub fn addCases(cases: *tests.CompileErrorContext) void {4pub fn addCases(cases: *tests.CompileErrorContext) void {
6 cases.addTest("type mismatch with tuple concatenation",5 cases.addTest("type mismatch with tuple concatenation",
...@@ -387,12 +386,10 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -387,12 +386,10 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
387 , &[_][]const u8{386 , &[_][]const u8{
388 "tmp.zig:3:5: error: target arch 'wasm32' does not support calling with a new stack",387 "tmp.zig:3:5: error: target arch 'wasm32' does not support calling with a new stack",
389 });388 });
390 tc.target = Target{389 tc.target = std.zig.CrossTarget{
391 .Cross = .{390 .cpu_arch = .wasm32,
392 .cpu = Target.Cpu.baseline(.wasm32),391 .os_tag = .wasi,
393 .os = .wasi,392 .abi = .none,
394 .abi = .none,
395 },
396 };393 };
397 break :x tc;394 break :x tc;
398 });395 });
...@@ -788,12 +785,10 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -788,12 +785,10 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
788 , &[_][]const u8{785 , &[_][]const u8{
789 "tmp.zig:2:14: error: could not find 'foo' in the inputs or outputs",786 "tmp.zig:2:14: error: could not find 'foo' in the inputs or outputs",
790 });787 });
791 tc.target = Target{788 tc.target = std.zig.CrossTarget{
792 .Cross = .{789 .cpu_arch = .x86_64,
793 .cpu = Target.Cpu.baseline(.x86_64),790 .os_tag = .linux,
794 .os = .linux,791 .abi = .gnu,
795 .abi = .gnu,
796 },
797 };792 };
798 break :x tc;793 break :x tc;
799 });794 });
...@@ -1453,7 +1448,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -1453,7 +1448,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
1453 "tmp.zig:2:18: error: invalid operands to binary expression: 'error{A}' and 'error{B}'",1448 "tmp.zig:2:18: error: invalid operands to binary expression: 'error{A}' and 'error{B}'",
1454 });1449 });
14551450
1456 if (builtin.os == builtin.Os.linux) {1451 if (std.Target.current.os.tag == .linux) {
1457 cases.addTest("implicit dependency on libc",1452 cases.addTest("implicit dependency on libc",
1458 \\extern "c" fn exit(u8) void;1453 \\extern "c" fn exit(u8) void;
1459 \\export fn entry() void {1454 \\export fn entry() void {
test/runtime_safety.zig+13
...@@ -745,4 +745,17 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -745,4 +745,17 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
745 \\ (await p) catch unreachable;745 \\ (await p) catch unreachable;
746 \\}746 \\}
747 );747 );
748
749 // Slicing a C pointer returns a non-allowzero slice, thus we need to emit
750 // a safety check to ensure the pointer is not null.
751 cases.addRuntimeSafety("slicing null C pointer",
752 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
753 \\ @import("std").os.exit(126);
754 \\}
755 \\
756 \\pub fn main() void {
757 \\ var ptr: [*c]const u32 = null;
758 \\ var slice = ptr[0..3];
759 \\}
760 );
748}761}
test/src/translate_c.zig+3-2
...@@ -7,6 +7,7 @@ const fmt = std.fmt;...@@ -7,6 +7,7 @@ const fmt = std.fmt;
7const mem = std.mem;7const mem = std.mem;
8const fs = std.fs;8const fs = std.fs;
9const warn = std.debug.warn;9const warn = std.debug.warn;
10const CrossTarget = std.zig.CrossTarget;
1011
11pub const TranslateCContext = struct {12pub const TranslateCContext = struct {
12 b: *build.Builder,13 b: *build.Builder,
...@@ -19,7 +20,7 @@ pub const TranslateCContext = struct {...@@ -19,7 +20,7 @@ pub const TranslateCContext = struct {
19 sources: ArrayList(SourceFile),20 sources: ArrayList(SourceFile),
20 expected_lines: ArrayList([]const u8),21 expected_lines: ArrayList([]const u8),
21 allow_warnings: bool,22 allow_warnings: bool,
22 target: std.Target = .Native,23 target: CrossTarget = CrossTarget{},
2324
24 const SourceFile = struct {25 const SourceFile = struct {
25 filename: []const u8,26 filename: []const u8,
...@@ -75,7 +76,7 @@ pub const TranslateCContext = struct {...@@ -75,7 +76,7 @@ pub const TranslateCContext = struct {
75 pub fn addWithTarget(76 pub fn addWithTarget(
76 self: *TranslateCContext,77 self: *TranslateCContext,
77 name: []const u8,78 name: []const u8,
78 target: std.Target,79 target: CrossTarget,
79 source: []const u8,80 source: []const u8,
80 expected_lines: []const []const u8,81 expected_lines: []const []const u8,
81 ) void {82 ) void {
test/stack_traces.zig+38-39
...@@ -1,4 +1,3 @@...@@ -1,4 +1,3 @@
1const builtin = @import("builtin");
2const std = @import("std");1const std = @import("std");
3const os = std.os;2const os = std.os;
4const tests = @import("tests.zig");3const tests = @import("tests.zig");
...@@ -43,32 +42,32 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -43,32 +42,32 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
43 \\}42 \\}
44 ;43 ;
4544
46 switch (builtin.os) {45 switch (std.Target.current.os.tag) {
47 .freebsd => {46 .freebsd => {
48 cases.addCase(47 cases.addCase(
49 "return",48 "return",
50 source_return,49 source_return,
51 [_][]const u8{50 [_][]const u8{
52 // debug51 // debug
53 \\error: TheSkyIsFalling52 \\error: TheSkyIsFalling
54 \\source.zig:4:5: [address] in main (test)53 \\source.zig:4:5: [address] in main (test)
55 \\ return error.TheSkyIsFalling;54 \\ return error.TheSkyIsFalling;
56 \\ ^55 \\ ^
57 \\56 \\
58 ,57 ,
59 // release-safe58 // release-safe
60 \\error: TheSkyIsFalling59 \\error: TheSkyIsFalling
61 \\source.zig:4:5: [address] in std.start.main (test)60 \\source.zig:4:5: [address] in std.start.main (test)
62 \\ return error.TheSkyIsFalling;61 \\ return error.TheSkyIsFalling;
63 \\ ^62 \\ ^
64 \\63 \\
65 ,64 ,
66 // release-fast65 // release-fast
67 \\error: TheSkyIsFalling66 \\error: TheSkyIsFalling
68 \\67 \\
69 ,68 ,
70 // release-small69 // release-small
71 \\error: TheSkyIsFalling70 \\error: TheSkyIsFalling
72 \\71 \\
73 },72 },
74 );73 );
...@@ -77,7 +76,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -77,7 +76,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
77 source_try_return,76 source_try_return,
78 [_][]const u8{77 [_][]const u8{
79 // debug78 // debug
80 \\error: TheSkyIsFalling79 \\error: TheSkyIsFalling
81 \\source.zig:4:5: [address] in foo (test)80 \\source.zig:4:5: [address] in foo (test)
82 \\ return error.TheSkyIsFalling;81 \\ return error.TheSkyIsFalling;
83 \\ ^82 \\ ^
...@@ -87,7 +86,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -87,7 +86,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
87 \\86 \\
88 ,87 ,
89 // release-safe88 // release-safe
90 \\error: TheSkyIsFalling89 \\error: TheSkyIsFalling
91 \\source.zig:4:5: [address] in std.start.main (test)90 \\source.zig:4:5: [address] in std.start.main (test)
92 \\ return error.TheSkyIsFalling;91 \\ return error.TheSkyIsFalling;
93 \\ ^92 \\ ^
...@@ -97,11 +96,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -97,11 +96,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
97 \\96 \\
98 ,97 ,
99 // release-fast98 // release-fast
100 \\error: TheSkyIsFalling99 \\error: TheSkyIsFalling
101 \\100 \\
102 ,101 ,
103 // release-small102 // release-small
104 \\error: TheSkyIsFalling103 \\error: TheSkyIsFalling
105 \\104 \\
106 },105 },
107 );106 );
...@@ -110,7 +109,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -110,7 +109,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
110 source_try_try_return_return,109 source_try_try_return_return,
111 [_][]const u8{110 [_][]const u8{
112 // debug111 // debug
113 \\error: TheSkyIsFalling112 \\error: TheSkyIsFalling
114 \\source.zig:12:5: [address] in make_error (test)113 \\source.zig:12:5: [address] in make_error (test)
115 \\ return error.TheSkyIsFalling;114 \\ return error.TheSkyIsFalling;
116 \\ ^115 \\ ^
...@@ -126,7 +125,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -126,7 +125,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
126 \\125 \\
127 ,126 ,
128 // release-safe127 // release-safe
129 \\error: TheSkyIsFalling128 \\error: TheSkyIsFalling
130 \\source.zig:12:5: [address] in std.start.main (test)129 \\source.zig:12:5: [address] in std.start.main (test)
131 \\ return error.TheSkyIsFalling;130 \\ return error.TheSkyIsFalling;
132 \\ ^131 \\ ^
...@@ -142,11 +141,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -142,11 +141,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
142 \\141 \\
143 ,142 ,
144 // release-fast143 // release-fast
145 \\error: TheSkyIsFalling144 \\error: TheSkyIsFalling
146 \\145 \\
147 ,146 ,
148 // release-small147 // release-small
149 \\error: TheSkyIsFalling148 \\error: TheSkyIsFalling
150 \\149 \\
151 },150 },
152 );151 );
...@@ -157,25 +156,25 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -157,25 +156,25 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
157 source_return,156 source_return,
158 [_][]const u8{157 [_][]const u8{
159 // debug158 // debug
160 \\error: TheSkyIsFalling159 \\error: TheSkyIsFalling
161 \\source.zig:4:5: [address] in main (test)160 \\source.zig:4:5: [address] in main (test)
162 \\ return error.TheSkyIsFalling;161 \\ return error.TheSkyIsFalling;
163 \\ ^162 \\ ^
164 \\163 \\
165 ,164 ,
166 // release-safe165 // release-safe
167 \\error: TheSkyIsFalling166 \\error: TheSkyIsFalling
168 \\source.zig:4:5: [address] in std.start.posixCallMainAndExit (test)167 \\source.zig:4:5: [address] in std.start.posixCallMainAndExit (test)
169 \\ return error.TheSkyIsFalling;168 \\ return error.TheSkyIsFalling;
170 \\ ^169 \\ ^
171 \\170 \\
172 ,171 ,
173 // release-fast172 // release-fast
174 \\error: TheSkyIsFalling173 \\error: TheSkyIsFalling
175 \\174 \\
176 ,175 ,
177 // release-small176 // release-small
178 \\error: TheSkyIsFalling177 \\error: TheSkyIsFalling
179 \\178 \\
180 },179 },
181 );180 );
...@@ -184,7 +183,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -184,7 +183,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
184 source_try_return,183 source_try_return,
185 [_][]const u8{184 [_][]const u8{
186 // debug185 // debug
187 \\error: TheSkyIsFalling186 \\error: TheSkyIsFalling
188 \\source.zig:4:5: [address] in foo (test)187 \\source.zig:4:5: [address] in foo (test)
189 \\ return error.TheSkyIsFalling;188 \\ return error.TheSkyIsFalling;
190 \\ ^189 \\ ^
...@@ -194,7 +193,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -194,7 +193,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
194 \\193 \\
195 ,194 ,
196 // release-safe195 // release-safe
197 \\error: TheSkyIsFalling196 \\error: TheSkyIsFalling
198 \\source.zig:4:5: [address] in std.start.posixCallMainAndExit (test)197 \\source.zig:4:5: [address] in std.start.posixCallMainAndExit (test)
199 \\ return error.TheSkyIsFalling;198 \\ return error.TheSkyIsFalling;
200 \\ ^199 \\ ^
...@@ -204,11 +203,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -204,11 +203,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
204 \\203 \\
205 ,204 ,
206 // release-fast205 // release-fast
207 \\error: TheSkyIsFalling206 \\error: TheSkyIsFalling
208 \\207 \\
209 ,208 ,
210 // release-small209 // release-small
211 \\error: TheSkyIsFalling210 \\error: TheSkyIsFalling
212 \\211 \\
213 },212 },
214 );213 );
...@@ -217,7 +216,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -217,7 +216,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
217 source_try_try_return_return,216 source_try_try_return_return,
218 [_][]const u8{217 [_][]const u8{
219 // debug218 // debug
220 \\error: TheSkyIsFalling219 \\error: TheSkyIsFalling
221 \\source.zig:12:5: [address] in make_error (test)220 \\source.zig:12:5: [address] in make_error (test)
222 \\ return error.TheSkyIsFalling;221 \\ return error.TheSkyIsFalling;
223 \\ ^222 \\ ^
...@@ -233,7 +232,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -233,7 +232,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
233 \\232 \\
234 ,233 ,
235 // release-safe234 // release-safe
236 \\error: TheSkyIsFalling235 \\error: TheSkyIsFalling
237 \\source.zig:12:5: [address] in std.start.posixCallMainAndExit (test)236 \\source.zig:12:5: [address] in std.start.posixCallMainAndExit (test)
238 \\ return error.TheSkyIsFalling;237 \\ return error.TheSkyIsFalling;
239 \\ ^238 \\ ^
...@@ -249,11 +248,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -249,11 +248,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
249 \\248 \\
250 ,249 ,
251 // release-fast250 // release-fast
252 \\error: TheSkyIsFalling251 \\error: TheSkyIsFalling
253 \\252 \\
254 ,253 ,
255 // release-small254 // release-small
256 \\error: TheSkyIsFalling255 \\error: TheSkyIsFalling
257 \\256 \\
258 },257 },
259 );258 );
...@@ -278,11 +277,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -278,11 +277,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
278 \\277 \\
279 ,278 ,
280 // release-fast279 // release-fast
281 \\error: TheSkyIsFalling280 \\error: TheSkyIsFalling
282 \\281 \\
283 ,282 ,
284 // release-small283 // release-small
285 \\error: TheSkyIsFalling284 \\error: TheSkyIsFalling
286 \\285 \\
287 },286 },
288 );287 );
...@@ -311,11 +310,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -311,11 +310,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
311 \\310 \\
312 ,311 ,
313 // release-fast312 // release-fast
314 \\error: TheSkyIsFalling313 \\error: TheSkyIsFalling
315 \\314 \\
316 ,315 ,
317 // release-small316 // release-small
318 \\error: TheSkyIsFalling317 \\error: TheSkyIsFalling
319 \\318 \\
320 },319 },
321 );320 );
...@@ -356,11 +355,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -356,11 +355,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
356 \\355 \\
357 ,356 ,
358 // release-fast357 // release-fast
359 \\error: TheSkyIsFalling358 \\error: TheSkyIsFalling
360 \\359 \\
361 ,360 ,
362 // release-small361 // release-small
363 \\error: TheSkyIsFalling362 \\error: TheSkyIsFalling
364 \\363 \\
365 },364 },
366 );365 );
...@@ -371,7 +370,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -371,7 +370,7 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
371 source_return,370 source_return,
372 [_][]const u8{371 [_][]const u8{
373 // debug372 // debug
374 \\error: TheSkyIsFalling373 \\error: TheSkyIsFalling
375 \\source.zig:4:5: [address] in main (test.obj)374 \\source.zig:4:5: [address] in main (test.obj)
376 \\ return error.TheSkyIsFalling;375 \\ return error.TheSkyIsFalling;
377 \\ ^376 \\ ^
...@@ -381,11 +380,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -381,11 +380,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
381 // --disabled-- results in segmenetation fault380 // --disabled-- results in segmenetation fault
382 "",381 "",
383 // release-fast382 // release-fast
384 \\error: TheSkyIsFalling383 \\error: TheSkyIsFalling
385 \\384 \\
386 ,385 ,
387 // release-small386 // release-small
388 \\error: TheSkyIsFalling387 \\error: TheSkyIsFalling
389 \\388 \\
390 },389 },
391 );390 );
...@@ -407,11 +406,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -407,11 +406,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
407 // --disabled-- results in segmenetation fault406 // --disabled-- results in segmenetation fault
408 "",407 "",
409 // release-fast408 // release-fast
410 \\error: TheSkyIsFalling409 \\error: TheSkyIsFalling
411 \\410 \\
412 ,411 ,
413 // release-small412 // release-small
414 \\error: TheSkyIsFalling413 \\error: TheSkyIsFalling
415 \\414 \\
416 },415 },
417 );416 );
...@@ -439,11 +438,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {...@@ -439,11 +438,11 @@ pub fn addCases(cases: *tests.StackTracesContext) void {
439 // --disabled-- results in segmenetation fault438 // --disabled-- results in segmenetation fault
440 "",439 "",
441 // release-fast440 // release-fast
442 \\error: TheSkyIsFalling441 \\error: TheSkyIsFalling
443 \\442 \\
444 ,443 ,
445 // release-small444 // release-small
446 \\error: TheSkyIsFalling445 \\error: TheSkyIsFalling
447 \\446 \\
448 },447 },
449 );448 );
test/stage1/behavior/asm.zig+4-3
...@@ -1,9 +1,10 @@...@@ -1,9 +1,10 @@
1const std = @import("std");1const std = @import("std");
2const config = @import("builtin");
3const expect = std.testing.expect;2const expect = std.testing.expect;
43
4const is_x86_64_linux = std.Target.current.cpu.arch == .x86_64 and std.Target.current.os.tag == .linux;
5
5comptime {6comptime {
6 if (config.arch == config.Arch.x86_64 and config.os == config.Os.linux) {7 if (is_x86_64_linux) {
7 asm (8 asm (
8 \\.globl this_is_my_alias;9 \\.globl this_is_my_alias;
9 \\.type this_is_my_alias, @function;10 \\.type this_is_my_alias, @function;
...@@ -13,7 +14,7 @@ comptime {...@@ -13,7 +14,7 @@ comptime {
13}14}
1415
15test "module level assembly" {16test "module level assembly" {
16 if (config.arch == config.Arch.x86_64 and config.os == config.Os.linux) {17 if (is_x86_64_linux) {
17 expect(this_is_my_alias() == 1234);18 expect(this_is_my_alias() == 1234);
18 }19 }
19}20}
test/stage1/behavior/byteswap.zig+2-3
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const std = @import("std");1const std = @import("std");
2const expect = std.testing.expect;2const expect = std.testing.expect;
3const builtin = @import("builtin");
43
5test "@byteSwap integers" {4test "@byteSwap integers" {
6 const ByteSwapIntTest = struct {5 const ByteSwapIntTest = struct {
...@@ -41,10 +40,10 @@ test "@byteSwap integers" {...@@ -41,10 +40,10 @@ test "@byteSwap integers" {
4140
42test "@byteSwap vectors" {41test "@byteSwap vectors" {
43 // https://github.com/ziglang/zig/issues/356342 // https://github.com/ziglang/zig/issues/3563
44 if (builtin.os == .dragonfly) return error.SkipZigTest;43 if (std.Target.current.os.tag == .dragonfly) return error.SkipZigTest;
4544
46 // https://github.com/ziglang/zig/issues/331745 // https://github.com/ziglang/zig/issues/3317
47 if (builtin.arch == .mipsel) return error.SkipZigTest;46 if (std.Target.current.cpu.arch == .mipsel) return error.SkipZigTest;
4847
49 const ByteSwapVectorTest = struct {48 const ByteSwapVectorTest = struct {
50 fn run() void {49 fn run() void {
test/stage1/behavior/eval.zig+25
...@@ -807,3 +807,28 @@ test "return 0 from function that has u0 return type" {...@@ -807,3 +807,28 @@ test "return 0 from function that has u0 return type" {
807 }807 }
808 }808 }
809}809}
810
811test "two comptime calls with array default initialized to undefined" {
812 const S = struct {
813 const CrossTarget = struct {
814 dynamic_linker: DynamicLinker = DynamicLinker{},
815
816 pub fn parse() void {
817 var result: CrossTarget = .{ };
818 result.getCpuArch();
819 }
820
821 pub fn getCpuArch(self: CrossTarget) void { }
822 };
823
824 const DynamicLinker = struct {
825 buffer: [255]u8 = undefined,
826 };
827
828 };
829
830 comptime {
831 S.CrossTarget.parse();
832 S.CrossTarget.parse();
833 }
834}
test/stage1/behavior/math.zig+10-10
...@@ -529,7 +529,7 @@ test "comptime_int xor" {...@@ -529,7 +529,7 @@ test "comptime_int xor" {
529}529}
530530
531test "f128" {531test "f128" {
532 if (std.Target.current.isWindows()) {532 if (std.Target.current.os.tag == .windows) {
533 // TODO https://github.com/ziglang/zig/issues/508533 // TODO https://github.com/ziglang/zig/issues/508
534 return error.SkipZigTest;534 return error.SkipZigTest;
535 }535 }
...@@ -631,7 +631,7 @@ test "NaN comparison" {...@@ -631,7 +631,7 @@ test "NaN comparison" {
631 // TODO: https://github.com/ziglang/zig/issues/3338631 // TODO: https://github.com/ziglang/zig/issues/3338
632 return error.SkipZigTest;632 return error.SkipZigTest;
633 }633 }
634 if (std.Target.current.isWindows()) {634 if (std.Target.current.os.tag == .windows) {
635 // TODO https://github.com/ziglang/zig/issues/508635 // TODO https://github.com/ziglang/zig/issues/508
636 return error.SkipZigTest;636 return error.SkipZigTest;
637 }637 }
...@@ -666,14 +666,14 @@ test "128-bit multiplication" {...@@ -666,14 +666,14 @@ test "128-bit multiplication" {
666test "vector comparison" {666test "vector comparison" {
667 const S = struct {667 const S = struct {
668 fn doTheTest() void {668 fn doTheTest() void {
669 var a: @Vector(6, i32) = [_]i32{1, 3, -1, 5, 7, 9};669 var a: @Vector(6, i32) = [_]i32{ 1, 3, -1, 5, 7, 9 };
670 var b: @Vector(6, i32) = [_]i32{-1, 3, 0, 6, 10, -10};670 var b: @Vector(6, i32) = [_]i32{ -1, 3, 0, 6, 10, -10 };
671 expect(mem.eql(bool, &@as([6]bool, a < b), &[_]bool{false, false, true, true, true, false}));671 expect(mem.eql(bool, &@as([6]bool, a < b), &[_]bool{ false, false, true, true, true, false }));
672 expect(mem.eql(bool, &@as([6]bool, a <= b), &[_]bool{false, true, true, true, true, false}));672 expect(mem.eql(bool, &@as([6]bool, a <= b), &[_]bool{ false, true, true, true, true, false }));
673 expect(mem.eql(bool, &@as([6]bool, a == b), &[_]bool{false, true, false, false, false, false}));673 expect(mem.eql(bool, &@as([6]bool, a == b), &[_]bool{ false, true, false, false, false, false }));
674 expect(mem.eql(bool, &@as([6]bool, a != b), &[_]bool{true, false, true, true, true, true}));674 expect(mem.eql(bool, &@as([6]bool, a != b), &[_]bool{ true, false, true, true, true, true }));
675 expect(mem.eql(bool, &@as([6]bool, a > b), &[_]bool{true, false, false, false, false, true}));675 expect(mem.eql(bool, &@as([6]bool, a > b), &[_]bool{ true, false, false, false, false, true }));
676 expect(mem.eql(bool, &@as([6]bool, a >= b), &[_]bool{true, true, false, false, false, true}));676 expect(mem.eql(bool, &@as([6]bool, a >= b), &[_]bool{ true, true, false, false, false, true }));
677 }677 }
678 };678 };
679 S.doTheTest();679 S.doTheTest();
test/stage1/behavior/misc.zig+1-1
...@@ -335,7 +335,7 @@ test "string concatenation" {...@@ -335,7 +335,7 @@ test "string concatenation" {
335 comptime expect(@TypeOf(a) == *const [12:0]u8);335 comptime expect(@TypeOf(a) == *const [12:0]u8);
336 comptime expect(@TypeOf(b) == *const [12:0]u8);336 comptime expect(@TypeOf(b) == *const [12:0]u8);
337337
338 const len = mem.len(u8, b);338 const len = mem.len(b);
339 const len_with_null = len + 1;339 const len_with_null = len + 1;
340 {340 {
341 var i: u32 = 0;341 var i: u32 = 0;
test/stage1/behavior/namespace_depends_on_compile_var.zig+4-4
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");1const std = @import("std");
2const expect = @import("std").testing.expect;2const expect = std.testing.expect;
33
4test "namespace depends on compile var" {4test "namespace depends on compile var" {
5 if (some_namespace.a_bool) {5 if (some_namespace.a_bool) {
...@@ -8,7 +8,7 @@ test "namespace depends on compile var" {...@@ -8,7 +8,7 @@ test "namespace depends on compile var" {
8 expect(!some_namespace.a_bool);8 expect(!some_namespace.a_bool);
9 }9 }
10}10}
11const some_namespace = switch (builtin.os) {11const some_namespace = switch (std.builtin.os.tag) {
12 builtin.Os.linux => @import("namespace_depends_on_compile_var/a.zig"),12 .linux => @import("namespace_depends_on_compile_var/a.zig"),
13 else => @import("namespace_depends_on_compile_var/b.zig"),13 else => @import("namespace_depends_on_compile_var/b.zig"),
14};14};
test/stage1/behavior/slice.zig+11
...@@ -43,6 +43,17 @@ test "C pointer" {...@@ -43,6 +43,17 @@ test "C pointer" {
43 expectEqualSlices(u8, "kjdhfkjdhf", slice);43 expectEqualSlices(u8, "kjdhfkjdhf", slice);
44}44}
4545
46test "C pointer slice access" {
47 var buf: [10]u32 = [1]u32{42} ** 10;
48 const c_ptr = @ptrCast([*c]const u32, &buf);
49
50 comptime expectEqual([]const u32, @TypeOf(c_ptr[0..1]));
51
52 for (c_ptr[0..5]) |*cl| {
53 expectEqual(@as(u32, 42), cl.*);
54 }
55}
56
46fn sliceSum(comptime q: []const u8) i32 {57fn sliceSum(comptime q: []const u8) i32 {
47 comptime var result = 0;58 comptime var result = 0;
48 inline for (q) |item| {59 inline for (q) |item| {
test/stage1/behavior/vector.zig+1-2
...@@ -2,7 +2,6 @@ const std = @import("std");...@@ -2,7 +2,6 @@ const std = @import("std");
2const mem = std.mem;2const mem = std.mem;
3const expect = std.testing.expect;3const expect = std.testing.expect;
4const expectEqual = std.testing.expectEqual;4const expectEqual = std.testing.expectEqual;
5const builtin = @import("builtin");
65
7test "implicit cast vector to array - bool" {6test "implicit cast vector to array - bool" {
8 const S = struct {7 const S = struct {
...@@ -114,7 +113,7 @@ test "array to vector" {...@@ -114,7 +113,7 @@ test "array to vector" {
114113
115test "vector casts of sizes not divisable by 8" {114test "vector casts of sizes not divisable by 8" {
116 // https://github.com/ziglang/zig/issues/3563115 // https://github.com/ziglang/zig/issues/3563
117 if (builtin.os == .dragonfly) return error.SkipZigTest;116 if (std.Target.current.os.tag == .dragonfly) return error.SkipZigTest;
118117
119 const S = struct {118 const S = struct {
120 fn doTheTest() void {119 fn doTheTest() void {
test/standalone.zig+2-2
...@@ -18,10 +18,10 @@ pub fn addCases(cases: *tests.StandaloneContext) void {...@@ -18,10 +18,10 @@ pub fn addCases(cases: *tests.StandaloneContext) void {
18 cases.addBuildFile("test/standalone/use_alias/build.zig");18 cases.addBuildFile("test/standalone/use_alias/build.zig");
19 cases.addBuildFile("test/standalone/brace_expansion/build.zig");19 cases.addBuildFile("test/standalone/brace_expansion/build.zig");
20 cases.addBuildFile("test/standalone/empty_env/build.zig");20 cases.addBuildFile("test/standalone/empty_env/build.zig");
21 if (std.Target.current.getOs() != .wasi) {21 if (std.Target.current.os.tag != .wasi) {
22 cases.addBuildFile("test/standalone/load_dynamic_library/build.zig");22 cases.addBuildFile("test/standalone/load_dynamic_library/build.zig");
23 }23 }
24 if (std.Target.current.getArch() == .x86_64) { // TODO add C ABI support for other architectures24 if (std.Target.current.cpu.arch == .x86_64) { // TODO add C ABI support for other architectures
25 cases.addBuildFile("test/stage1/c_abi/build.zig");25 cases.addBuildFile("test/stage1/c_abi/build.zig");
26 }26 }
27}27}
test/standalone/global_linkage/build.zig created+23
...@@ -0,0 +1,23 @@
1const Builder = @import("std").build.Builder;
2
3pub fn build(b: *Builder) void {
4 const mode = b.standardReleaseOptions();
5 const target = b.standardTargetOptions(null);
6
7 const obj1 = b.addStaticLibrary("obj1", "obj1.zig");
8 obj1.setBuildMode(mode);
9 obj1.setTheTarget(target);
10
11 const obj2 = b.addStaticLibrary("obj2", "obj2.zig");
12 obj2.setBuildMode(mode);
13 obj2.setTheTarget(target);
14
15 const main = b.addTest("main.zig");
16 main.setBuildMode(mode);
17 main.setTheTarget(target);
18 main.linkLibrary(obj1);
19 main.linkLibrary(obj2);
20
21 const test_step = b.step("test", "Test it");
22 test_step.dependOn(&main.step);
23}
test/standalone/global_linkage/main.zig created+9
...@@ -0,0 +1,9 @@
1const std = @import("std");
2
3extern var obj1_integer: usize;
4extern var obj2_integer: usize;
5
6test "access the external integers" {
7 std.testing.expect(obj1_integer == 421);
8 std.testing.expect(obj2_integer == 422);
9}
test/standalone/global_linkage/obj1.zig created+7
...@@ -0,0 +1,7 @@
1extern var internal_integer: usize = 1;
2extern var obj1_integer: usize = 421;
3
4comptime {
5 @export(internal_integer, .{ .name = "internal_integer", .linkage = .Internal });
6 @export(obj1_integer, .{ .name = "obj1_integer", .linkage = .Strong });
7}
test/standalone/global_linkage/obj2.zig created+7
...@@ -0,0 +1,7 @@
1extern var internal_integer: usize = 2;
2extern var obj2_integer: usize = 422;
3
4comptime {
5 @export(internal_integer, .{ .name = "internal_integer", .linkage = .Internal });
6 @export(obj2_integer, .{ .name = "obj2_integer", .linkage = .Strong });
7}
test/tests.zig+78-115
...@@ -1,16 +1,15 @@...@@ -1,16 +1,15 @@
1const std = @import("std");1const std = @import("std");
2const builtin = std.builtin;
2const debug = std.debug;3const debug = std.debug;
3const warn = debug.warn;4const warn = debug.warn;
4const build = std.build;5const build = std.build;
5pub const Target = build.Target;6const CrossTarget = std.zig.CrossTarget;
6pub const CrossTarget = build.CrossTarget;
7const Buffer = std.Buffer;7const Buffer = std.Buffer;
8const io = std.io;8const io = std.io;
9const fs = std.fs;9const fs = std.fs;
10const mem = std.mem;10const mem = std.mem;
11const fmt = std.fmt;11const fmt = std.fmt;
12const ArrayList = std.ArrayList;12const ArrayList = std.ArrayList;
13const builtin = @import("builtin");
14const Mode = builtin.Mode;13const Mode = builtin.Mode;
15const LibExeObjStep = build.LibExeObjStep;14const LibExeObjStep = build.LibExeObjStep;
1615
...@@ -31,7 +30,7 @@ pub const RunTranslatedCContext = @import("src/run_translated_c.zig").RunTransla...@@ -31,7 +30,7 @@ pub const RunTranslatedCContext = @import("src/run_translated_c.zig").RunTransla
31pub const CompareOutputContext = @import("src/compare_output.zig").CompareOutputContext;30pub const CompareOutputContext = @import("src/compare_output.zig").CompareOutputContext;
3231
33const TestTarget = struct {32const TestTarget = struct {
34 target: Target = .Native,33 target: CrossTarget = @as(CrossTarget, .{}),
35 mode: builtin.Mode = .Debug,34 mode: builtin.Mode = .Debug,
36 link_libc: bool = false,35 link_libc: bool = false,
37 single_threaded: bool = false,36 single_threaded: bool = false,
...@@ -53,93 +52,77 @@ const test_targets = blk: {...@@ -53,93 +52,77 @@ const test_targets = blk: {
53 },52 },
5453
55 TestTarget{54 TestTarget{
56 .target = Target{55 .target = .{
57 .Cross = CrossTarget{56 .cpu_arch = .x86_64,
58 .cpu = Target.Cpu.baseline(.x86_64),57 .os_tag = .linux,
59 .os = .linux,58 .abi = .none,
60 .abi = .none,
61 },
62 },59 },
63 },60 },
64 TestTarget{61 TestTarget{
65 .target = Target{62 .target = .{
66 .Cross = CrossTarget{63 .cpu_arch = .x86_64,
67 .cpu = Target.Cpu.baseline(.x86_64),64 .os_tag = .linux,
68 .os = .linux,65 .abi = .gnu,
69 .abi = .gnu,
70 },
71 },66 },
72 .link_libc = true,67 .link_libc = true,
73 },68 },
74 TestTarget{69 TestTarget{
75 .target = Target{70 .target = .{
76 .Cross = CrossTarget{71 .cpu_arch = .x86_64,
77 .cpu = Target.Cpu.baseline(.x86_64),72 .os_tag = .linux,
78 .os = .linux,73 .abi = .musl,
79 .abi = .musl,
80 },
81 },74 },
82 .link_libc = true,75 .link_libc = true,
83 },76 },
8477
85 TestTarget{78 TestTarget{
86 .target = Target{79 .target = .{
87 .Cross = CrossTarget{80 .cpu_arch = .i386,
88 .cpu = Target.Cpu.baseline(.i386),81 .os_tag = .linux,
89 .os = .linux,82 .abi = .none,
90 .abi = .none,
91 },
92 },83 },
93 },84 },
94 TestTarget{85 TestTarget{
95 .target = Target{86 .target = .{
96 .Cross = CrossTarget{87 .cpu_arch = .i386,
97 .cpu = Target.Cpu.baseline(.i386),88 .os_tag = .linux,
98 .os = .linux,89 .abi = .musl,
99 .abi = .musl,
100 },
101 },90 },
102 .link_libc = true,91 .link_libc = true,
103 },92 },
10493
105 TestTarget{94 TestTarget{
106 .target = Target{95 .target = .{
107 .Cross = CrossTarget{96 .cpu_arch = .aarch64,
108 .cpu = Target.Cpu.baseline(.aarch64),97 .os_tag = .linux,
109 .os = .linux,98 .abi = .none,
110 .abi = .none,
111 },
112 },99 },
113 },100 },
114 TestTarget{101 TestTarget{
115 .target = Target{102 .target = .{
116 .Cross = CrossTarget{103 .cpu_arch = .aarch64,
117 .cpu = Target.Cpu.baseline(.aarch64),104 .os_tag = .linux,
118 .os = .linux,105 .abi = .musl,
119 .abi = .musl,
120 },
121 },106 },
122 .link_libc = true,107 .link_libc = true,
123 },108 },
124 TestTarget{109 TestTarget{
125 .target = Target{110 .target = .{
126 .Cross = CrossTarget{111 .cpu_arch = .aarch64,
127 .cpu = Target.Cpu.baseline(.aarch64),112 .os_tag = .linux,
128 .os = .linux,113 .abi = .gnu,
129 .abi = .gnu,
130 },
131 },114 },
132 .link_libc = true,115 .link_libc = true,
133 },116 },
134117
135 TestTarget{118 TestTarget{
136 .target = Target.parse(.{119 .target = CrossTarget.parse(.{
137 .arch_os_abi = "arm-linux-none",120 .arch_os_abi = "arm-linux-none",
138 .cpu_features = "generic+v8a",121 .cpu_features = "generic+v8a",
139 }) catch unreachable,122 }) catch unreachable,
140 },123 },
141 TestTarget{124 TestTarget{
142 .target = Target.parse(.{125 .target = CrossTarget.parse(.{
143 .arch_os_abi = "arm-linux-musleabihf",126 .arch_os_abi = "arm-linux-musleabihf",
144 .cpu_features = "generic+v8a",127 .cpu_features = "generic+v8a",
145 }) catch unreachable,128 }) catch unreachable,
...@@ -147,7 +130,7 @@ const test_targets = blk: {...@@ -147,7 +130,7 @@ const test_targets = blk: {
147 },130 },
148 // TODO https://github.com/ziglang/zig/issues/3287131 // TODO https://github.com/ziglang/zig/issues/3287
149 //TestTarget{132 //TestTarget{
150 // .target = Target.parse(.{133 // .target = CrossTarget.parse(.{
151 // .arch_os_abi = "arm-linux-gnueabihf",134 // .arch_os_abi = "arm-linux-gnueabihf",
152 // .cpu_features = "generic+v8a",135 // .cpu_features = "generic+v8a",
153 // }) catch unreachable,136 // }) catch unreachable,
...@@ -155,75 +138,61 @@ const test_targets = blk: {...@@ -155,75 +138,61 @@ const test_targets = blk: {
155 //},138 //},
156139
157 TestTarget{140 TestTarget{
158 .target = Target{141 .target = .{
159 .Cross = CrossTarget{142 .cpu_arch = .mipsel,
160 .cpu = Target.Cpu.baseline(.mipsel),143 .os_tag = .linux,
161 .os = .linux,144 .abi = .none,
162 .abi = .none,
163 },
164 },145 },
165 },146 },
166 TestTarget{147 TestTarget{
167 .target = Target{148 .target = .{
168 .Cross = CrossTarget{149 .cpu_arch = .mipsel,
169 .cpu = Target.Cpu.baseline(.mipsel),150 .os_tag = .linux,
170 .os = .linux,151 .abi = .musl,
171 .abi = .musl,
172 },
173 },152 },
174 .link_libc = true,153 .link_libc = true,
175 },154 },
176155
177 TestTarget{156 TestTarget{
178 .target = Target{157 .target = .{
179 .Cross = CrossTarget{158 .cpu_arch = .x86_64,
180 .cpu = Target.Cpu.baseline(.x86_64),159 .os_tag = .macosx,
181 .os = .macosx,160 .abi = .gnu,
182 .abi = .gnu,
183 },
184 },161 },
185 // TODO https://github.com/ziglang/zig/issues/3295162 // TODO https://github.com/ziglang/zig/issues/3295
186 .disable_native = true,163 .disable_native = true,
187 },164 },
188165
189 TestTarget{166 TestTarget{
190 .target = Target{167 .target = .{
191 .Cross = CrossTarget{168 .cpu_arch = .i386,
192 .cpu = Target.Cpu.baseline(.i386),169 .os_tag = .windows,
193 .os = .windows,170 .abi = .msvc,
194 .abi = .msvc,
195 },
196 },171 },
197 },172 },
198173
199 TestTarget{174 TestTarget{
200 .target = Target{175 .target = .{
201 .Cross = CrossTarget{176 .cpu_arch = .x86_64,
202 .cpu = Target.Cpu.baseline(.x86_64),177 .os_tag = .windows,
203 .os = .windows,178 .abi = .msvc,
204 .abi = .msvc,
205 },
206 },179 },
207 },180 },
208181
209 TestTarget{182 TestTarget{
210 .target = Target{183 .target = .{
211 .Cross = CrossTarget{184 .cpu_arch = .i386,
212 .cpu = Target.Cpu.baseline(.i386),185 .os_tag = .windows,
213 .os = .windows,186 .abi = .gnu,
214 .abi = .gnu,
215 },
216 },187 },
217 .link_libc = true,188 .link_libc = true,
218 },189 },
219190
220 TestTarget{191 TestTarget{
221 .target = Target{192 .target = .{
222 .Cross = CrossTarget{193 .cpu_arch = .x86_64,
223 .cpu = Target.Cpu.baseline(.x86_64),194 .os_tag = .windows,
224 .os = .windows,195 .abi = .gnu,
225 .abi = .gnu,
226 },
227 },196 },
228 .link_libc = true,197 .link_libc = true,
229 },198 },
...@@ -432,13 +401,13 @@ pub fn addPkgTests(...@@ -432,13 +401,13 @@ pub fn addPkgTests(
432 const step = b.step(b.fmt("test-{}", .{name}), desc);401 const step = b.step(b.fmt("test-{}", .{name}), desc);
433402
434 for (test_targets) |test_target| {403 for (test_targets) |test_target| {
435 if (skip_non_native and test_target.target != .Native)404 if (skip_non_native and !test_target.target.isNative())
436 continue;405 continue;
437406
438 if (skip_libc and test_target.link_libc)407 if (skip_libc and test_target.link_libc)
439 continue;408 continue;
440409
441 if (test_target.link_libc and test_target.target.osRequiresLibC()) {410 if (test_target.link_libc and test_target.target.getOs().requiresLibC()) {
442 // This would be a redundant test.411 // This would be a redundant test.
443 continue;412 continue;
444 }413 }
...@@ -448,8 +417,8 @@ pub fn addPkgTests(...@@ -448,8 +417,8 @@ pub fn addPkgTests(
448417
449 const ArchTag = @TagType(builtin.Arch);418 const ArchTag = @TagType(builtin.Arch);
450 if (test_target.disable_native and419 if (test_target.disable_native and
451 test_target.target.getOs() == builtin.os and420 test_target.target.getOsTag() == std.Target.current.os.tag and
452 test_target.target.getArch() == builtin.arch)421 test_target.target.getCpuArch() == std.Target.current.cpu.arch)
453 {422 {
454 continue;423 continue;
455 }424 }
...@@ -459,17 +428,14 @@ pub fn addPkgTests(...@@ -459,17 +428,14 @@ pub fn addPkgTests(
459 } else false;428 } else false;
460 if (!want_this_mode) continue;429 if (!want_this_mode) continue;
461430
462 const libc_prefix = if (test_target.target.osRequiresLibC())431 const libc_prefix = if (test_target.target.getOs().requiresLibC())
463 ""432 ""
464 else if (test_target.link_libc)433 else if (test_target.link_libc)
465 "c"434 "c"
466 else435 else
467 "bare";436 "bare";
468437
469 const triple_prefix = if (test_target.target == .Native)438 const triple_prefix = test_target.target.zigTriple(b.allocator) catch unreachable;
470 @as([]const u8, "native")
471 else
472 test_target.target.zigTripleNoSubArch(b.allocator) catch unreachable;
473439
474 const these_tests = b.addTest(root_src);440 const these_tests = b.addTest(root_src);
475 const single_threaded_txt = if (test_target.single_threaded) "single" else "multi";441 const single_threaded_txt = if (test_target.single_threaded) "single" else "multi";
...@@ -483,7 +449,7 @@ pub fn addPkgTests(...@@ -483,7 +449,7 @@ pub fn addPkgTests(
483 these_tests.single_threaded = test_target.single_threaded;449 these_tests.single_threaded = test_target.single_threaded;
484 these_tests.setFilter(test_filter);450 these_tests.setFilter(test_filter);
485 these_tests.setBuildMode(test_target.mode);451 these_tests.setBuildMode(test_target.mode);
486 these_tests.setTheTarget(test_target.target);452 these_tests.setTarget(test_target.target);
487 if (test_target.link_libc) {453 if (test_target.link_libc) {
488 these_tests.linkSystemLibrary("c");454 these_tests.linkSystemLibrary("c");
489 }455 }
...@@ -660,7 +626,7 @@ pub const StackTracesContext = struct {...@@ -660,7 +626,7 @@ pub const StackTracesContext = struct {
660 const delims = [_][]const u8{ ":", ":", ":", " in " };626 const delims = [_][]const u8{ ":", ":", ":", " in " };
661 var marks = [_]usize{0} ** 4;627 var marks = [_]usize{0} ** 4;
662 // offset search past `[drive]:` on windows628 // offset search past `[drive]:` on windows
663 var pos: usize = if (builtin.os == .windows) 2 else 0;629 var pos: usize = if (std.Target.current.os.tag == .windows) 2 else 0;
664 for (delims) |delim, i| {630 for (delims) |delim, i| {
665 marks[i] = mem.indexOfPos(u8, line, pos, delim) orelse {631 marks[i] = mem.indexOfPos(u8, line, pos, delim) orelse {
666 try buf.append(line);632 try buf.append(line);
...@@ -713,7 +679,7 @@ pub const CompileErrorContext = struct {...@@ -713,7 +679,7 @@ pub const CompileErrorContext = struct {
713 link_libc: bool,679 link_libc: bool,
714 is_exe: bool,680 is_exe: bool,
715 is_test: bool,681 is_test: bool,
716 target: Target = .Native,682 target: CrossTarget = CrossTarget{},
717683
718 const SourceFile = struct {684 const SourceFile = struct {
719 filename: []const u8,685 filename: []const u8,
...@@ -805,12 +771,9 @@ pub const CompileErrorContext = struct {...@@ -805,12 +771,9 @@ pub const CompileErrorContext = struct {
805 zig_args.append("--output-dir") catch unreachable;771 zig_args.append("--output-dir") catch unreachable;
806 zig_args.append(b.pathFromRoot(b.cache_root)) catch unreachable;772 zig_args.append(b.pathFromRoot(b.cache_root)) catch unreachable;
807773
808 switch (self.case.target) {774 if (!self.case.target.isNative()) {
809 .Native => {},775 try zig_args.append("-target");
810 .Cross => {776 try zig_args.append(try self.case.target.zigTriple(b.allocator));
811 try zig_args.append("-target");
812 try zig_args.append(try self.case.target.zigTriple(b.allocator));
813 },
814 }777 }
815778
816 switch (self.build_mode) {779 switch (self.build_mode) {
test/translate_c.zig+11-13
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
2const builtin = @import("builtin");2const std = @import("std");
3const Target = @import("std").Target;3const CrossTarget = std.zig.CrossTarget;
44
5pub fn addCases(cases: *tests.TranslateCContext) void {5pub fn addCases(cases: *tests.TranslateCContext) void {
6 cases.add("macro line continuation",6 cases.add("macro line continuation",
...@@ -665,7 +665,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -665,7 +665,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
665 \\}665 \\}
666 });666 });
667667
668 if (builtin.os != builtin.Os.windows) {668 if (std.Target.current.os.tag != .windows) {
669 // Windows treats this as an enum with type c_int669 // Windows treats this as an enum with type c_int
670 cases.add("big negative enum init values when C ABI supports long long enums",670 cases.add("big negative enum init values when C ABI supports long long enums",
671 \\enum EnumWithInits {671 \\enum EnumWithInits {
...@@ -1064,7 +1064,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1064,7 +1064,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1064 \\}1064 \\}
1065 });1065 });
10661066
1067 if (builtin.os != builtin.Os.windows) {1067 if (std.Target.current.os.tag != .windows) {
1068 // sysv_abi not currently supported on windows1068 // sysv_abi not currently supported on windows
1069 cases.add("Macro qualified functions",1069 cases.add("Macro qualified functions",
1070 \\void __attribute__((sysv_abi)) foo(void);1070 \\void __attribute__((sysv_abi)) foo(void);
...@@ -1093,12 +1093,10 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1093,12 +1093,10 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1093 \\pub const fn1 = ?fn (u8) callconv(.C) void;1093 \\pub const fn1 = ?fn (u8) callconv(.C) void;
1094 });1094 });
10951095
1096 cases.addWithTarget("Calling convention", tests.Target{1096 cases.addWithTarget("Calling convention", .{
1097 .Cross = .{1097 .cpu_arch = .i386,
1098 .cpu = Target.Cpu.baseline(.i386),1098 .os_tag = .linux,
1099 .os = .linux,1099 .abi = .none,
1100 .abi = .none,
1101 },
1102 },1100 },
1103 \\void __attribute__((fastcall)) foo1(float *a);1101 \\void __attribute__((fastcall)) foo1(float *a);
1104 \\void __attribute__((stdcall)) foo2(float *a);1102 \\void __attribute__((stdcall)) foo2(float *a);
...@@ -1113,7 +1111,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1113,7 +1111,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1113 \\pub fn foo5(a: [*c]f32) callconv(.Thiscall) void;1111 \\pub fn foo5(a: [*c]f32) callconv(.Thiscall) void;
1114 });1112 });
11151113
1116 cases.addWithTarget("Calling convention", Target.parse(.{1114 cases.addWithTarget("Calling convention", CrossTarget.parse(.{
1117 .arch_os_abi = "arm-linux-none",1115 .arch_os_abi = "arm-linux-none",
1118 .cpu_features = "generic+v8_5a",1116 .cpu_features = "generic+v8_5a",
1119 }) catch unreachable,1117 }) catch unreachable,
...@@ -1124,7 +1122,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1124,7 +1122,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1124 \\pub fn foo2(a: [*c]f32) callconv(.AAPCSVFP) void;1122 \\pub fn foo2(a: [*c]f32) callconv(.AAPCSVFP) void;
1125 });1123 });
11261124
1127 cases.addWithTarget("Calling convention", Target.parse(.{1125 cases.addWithTarget("Calling convention", CrossTarget.parse(.{
1128 .arch_os_abi = "aarch64-linux-none",1126 .arch_os_abi = "aarch64-linux-none",
1129 .cpu_features = "generic+v8_5a",1127 .cpu_features = "generic+v8_5a",
1130 }) catch unreachable,1128 }) catch unreachable,
...@@ -1596,7 +1594,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1596,7 +1594,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1596 \\}1594 \\}
1597 });1595 });
15981596
1599 if (builtin.os != .windows) {1597 if (std.Target.current.os.tag != .windows) {
1600 // When clang uses the <arch>-windows-none triple it behaves as MSVC and1598 // When clang uses the <arch>-windows-none triple it behaves as MSVC and
1601 // interprets the inner `struct Bar` as an anonymous structure1599 // interprets the inner `struct Bar` as an anonymous structure
1602 cases.add("type referenced struct",1600 cases.add("type referenced struct",