authorgravatar for leroycepearson@geemili.xyzLeRoyce Pearson <leroycepearson@geemili.xyz> 2020-04-02 21:46:48-06:00
committergravatar for leroycepearson@geemili.xyzLeRoyce Pearson <leroycepearson@geemili.xyz> 2020-04-02 21:46:48-06:00
log35c462caf0c0763c14d0f1303197c86a63c51f03
tree46591490be3dcf41f664c411385b62de9b1326d2
parent457f557c37947af6ce90a82a70e08e59526af0dc
parente7f555ca550cc73288adbdf4ec8d0e4abbc7a987

Merge branch 'master' into feature-file-locks


151 files changed, 5715 insertions(+), 4377 deletions(-)

CMakeLists.txt+13-4
...@@ -224,7 +224,7 @@ set(EMBEDDED_SOFTFLOAT_SOURCES...@@ -224,7 +224,7 @@ set(EMBEDDED_SOFTFLOAT_SOURCES
224add_library(embedded_softfloat STATIC ${EMBEDDED_SOFTFLOAT_SOURCES})224add_library(embedded_softfloat STATIC ${EMBEDDED_SOFTFLOAT_SOURCES})
225if(MSVC)225if(MSVC)
226 set_target_properties(embedded_softfloat PROPERTIES226 set_target_properties(embedded_softfloat PROPERTIES
227 COMPILE_FLAGS "-std=c99 /w"227 COMPILE_FLAGS "/w /O2"
228 )228 )
229else()229else()
230 set_target_properties(embedded_softfloat PROPERTIES230 set_target_properties(embedded_softfloat PROPERTIES
...@@ -315,12 +315,17 @@ include_directories(...@@ -315,12 +315,17 @@ include_directories(
315)315)
316316
317# These have to go before the -Wno- flags317# These have to go before the -Wno- flags
318set(EXE_CFLAGS "-std=c++14")318if(MSVC)
319 set(EXE_CFLAGS "/std:c++14")
320else(MSVC)
321 set(EXE_CFLAGS "-std=c++14")
322endif(MSVC)
323
319if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")324if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
320 if(MSVC)325 if(MSVC)
321 set(EXE_CFLAGS "${EXE_CFLAGS} /w")326 set(EXE_CFLAGS "${EXE_CFLAGS} /w")
322 else()327 else()
323 set(EXE_CFLAGS "${EXE_CFLAGS} -Werror -Wall")328 set(EXE_CFLAGS "${EXE_CFLAGS} -Werror -Wall -Werror=implicit-fallthrough")
324 endif()329 endif()
325endif()330endif()
326331
...@@ -333,7 +338,11 @@ else()...@@ -333,7 +338,11 @@ else()
333 endif()338 endif()
334endif()339endif()
335340
336set(OPTIMIZED_C_FLAGS "-std=c99 -O3")341if(MSVC)
342 set(OPTIMIZED_C_FLAGS "/O2")
343else(MSVC)
344 set(OPTIMIZED_C_FLAGS "-std=c99 -O3")
345endif(MSVC)
337346
338set(EXE_LDFLAGS " ")347set(EXE_LDFLAGS " ")
339if(MSVC)348if(MSVC)
README.md+2-2
...@@ -54,8 +54,8 @@ make install...@@ -54,8 +54,8 @@ make install
54##### MacOS54##### MacOS
5555
56```56```
57brew install cmake llvm@1057brew install cmake llvm
58brew outdated llvm@10 || brew upgrade llvm@1058brew outdated llvm || brew upgrade llvm
59mkdir build59mkdir build
60cd build60cd build
61cmake .. -DCMAKE_PREFIX_PATH=$(brew --prefix llvm)61cmake .. -DCMAKE_PREFIX_PATH=$(brew --prefix llvm)
ci/azure/linux_script+5-1
...@@ -12,7 +12,11 @@ sudo apt-get update -q...@@ -12,7 +12,11 @@ sudo apt-get update -q
1212
13sudo apt-get remove -y llvm-*13sudo apt-get remove -y llvm-*
14sudo rm -rf /usr/local/*14sudo rm -rf /usr/local/*
15sudo apt-get install -y libxml2-dev libclang-10-dev llvm-10 llvm-10-dev liblld-10-dev cmake s3cmd gcc-7 g++-7 qemu15sudo apt-get install -y libxml2-dev libclang-10-dev llvm-10 llvm-10-dev liblld-10-dev cmake s3cmd gcc-7 g++-7
16
17wget https://ziglang.org/deps/qemu-5.0.0-rc1-x86_64-alpinelinux.tar.xz
18tar xf qemu-5.0.0-rc1-x86_64-alpinelinux.tar.xz
19PATH=$PWD/qemu-5.0.0-rc1/bin:$PATH
1620
17# Make the `zig version` number consistent.21# Make the `zig version` number consistent.
18# This will affect the cmake command below.22# This will affect the cmake command below.
ci/srht/update_download_page+1
...@@ -71,6 +71,7 @@ export X86_64_FREEBSD_SHASUM="$(echo "$X86_64_FREEBSD_JSON" | jq .shasum -r)"...@@ -71,6 +71,7 @@ export X86_64_FREEBSD_SHASUM="$(echo "$X86_64_FREEBSD_JSON" | jq .shasum -r)"
71git clone https://github.com/ziglang/www.ziglang.org --depth 171git clone https://github.com/ziglang/www.ziglang.org --depth 1
72cd www.ziglang.org72cd www.ziglang.org
73export MASTER_DATE="$(date +%Y-%m-%d)"73export MASTER_DATE="$(date +%Y-%m-%d)"
74export MASTER_VERSION="$VERSION"
74"../$ZIG" run update-download-page.zig75"../$ZIG" run update-download-page.zig
7576
76$S3CMD put -P --no-mime-magic --add-header="cache-control: public, max-age=31536000, immutable" "../$SRC_TARBALL" s3://ziglang.org/builds/77$S3CMD put -P --no-mime-magic --add-header="cache-control: public, max-age=31536000, immutable" "../$SRC_TARBALL" s3://ziglang.org/builds/
cmake/Findlld.cmake+1
...@@ -24,6 +24,7 @@ else()...@@ -24,6 +24,7 @@ else()
24 string(TOUPPER ${_libname_} _prettylibname_)24 string(TOUPPER ${_libname_} _prettylibname_)
25 find_library(LLD_${_prettylibname_}_LIB NAMES ${_libname_}25 find_library(LLD_${_prettylibname_}_LIB NAMES ${_libname_}
26 PATHS26 PATHS
27 ${LLD_LIBDIRS}
27 /usr/lib/llvm-10/lib28 /usr/lib/llvm-10/lib
28 /usr/local/llvm100/lib29 /usr/local/llvm100/lib
29 /mingw64/lib30 /mingw64/lib
doc/docgen.zig+48-29
...@@ -321,7 +321,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -321,7 +321,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
321 var last_action = Action.Open;321 var last_action = Action.Open;
322 var last_columns: ?u8 = null;322 var last_columns: ?u8 = null;
323323
324 var toc_buf = try std.Buffer.initSize(allocator, 0);324 var toc_buf = std.ArrayList(u8).init(allocator);
325 defer toc_buf.deinit();325 defer toc_buf.deinit();
326326
327 var toc = toc_buf.outStream();327 var toc = toc_buf.outStream();
...@@ -607,7 +607,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -607,7 +607,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
607}607}
608608
609fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {609fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
610 var buf = try std.Buffer.initSize(allocator, 0);610 var buf = std.ArrayList(u8).init(allocator);
611 defer buf.deinit();611 defer buf.deinit();
612612
613 const out = buf.outStream();613 const out = buf.outStream();
...@@ -626,7 +626,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {...@@ -626,7 +626,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
626}626}
627627
628fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {628fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
629 var buf = try std.Buffer.initSize(allocator, 0);629 var buf = std.ArrayList(u8).init(allocator);
630 defer buf.deinit();630 defer buf.deinit();
631631
632 const out = buf.outStream();632 const out = buf.outStream();
...@@ -672,7 +672,7 @@ test "term color" {...@@ -672,7 +672,7 @@ test "term color" {
672}672}
673673
674fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {674fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
675 var buf = try std.Buffer.initSize(allocator, 0);675 var buf = std.ArrayList(u8).init(allocator);
676 defer buf.deinit();676 defer buf.deinit();
677677
678 var out = buf.outStream();678 var out = buf.outStream();
...@@ -1048,7 +1048,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1048,7 +1048,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1048 allocator,1048 allocator,
1049 &[_][]const u8{ tmp_dir_name, name_plus_ext },1049 &[_][]const u8{ tmp_dir_name, name_plus_ext },
1050 );1050 );
1051 try io.writeFile(tmp_source_file_name, trimmed_raw_source);1051 try fs.cwd().writeFile(tmp_source_file_name, trimmed_raw_source);
10521052
1053 switch (code.id) {1053 switch (code.id) {
1054 Code.Id.Exe => |expected_outcome| code_block: {1054 Code.Id.Exe => |expected_outcome| code_block: {
...@@ -1106,18 +1106,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1106,18 +1106,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1106 }1106 }
1107 }1107 }
1108 if (expected_outcome == .BuildFail) {1108 if (expected_outcome == .BuildFail) {
1109 const result = try ChildProcess.exec(1109 const result = try ChildProcess.exec(.{
1110 allocator,1110 .allocator = allocator,
1111 build_args.toSliceConst(),1111 .argv = build_args.span(),
1112 null,1112 .env_map = &env_map,
1113 &env_map,1113 .max_output_bytes = max_doc_file_size,
1114 max_doc_file_size,1114 });
1115 );
1116 switch (result.term) {1115 switch (result.term) {
1117 .Exited => |exit_code| {1116 .Exited => |exit_code| {
1118 if (exit_code == 0) {1117 if (exit_code == 0) {
1119 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});1118 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
1120 for (build_args.toSliceConst()) |arg|1119 for (build_args.span()) |arg|
1121 warn("{} ", .{arg})1120 warn("{} ", .{arg})
1122 else1121 else
1123 warn("\n", .{});1122 warn("\n", .{});
...@@ -1126,7 +1125,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1126,7 +1125,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1126 },1125 },
1127 else => {1126 else => {
1128 warn("{}\nThe following command crashed:\n", .{result.stderr});1127 warn("{}\nThe following command crashed:\n", .{result.stderr});
1129 for (build_args.toSliceConst()) |arg|1128 for (build_args.span()) |arg|
1130 warn("{} ", .{arg})1129 warn("{} ", .{arg})
1131 else1130 else
1132 warn("\n", .{});1131 warn("\n", .{});
...@@ -1138,7 +1137,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1138,7 +1137,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1138 try out.print("\n{}</code></pre>\n", .{colored_stderr});1137 try out.print("\n{}</code></pre>\n", .{colored_stderr});
1139 break :code_block;1138 break :code_block;
1140 }1139 }
1141 const exec_result = exec(allocator, &env_map, build_args.toSliceConst()) catch1140 const exec_result = exec(allocator, &env_map, build_args.span()) catch
1142 return parseError(tokenizer, code.source_token, "example failed to compile", .{});1141 return parseError(tokenizer, code.source_token, "example failed to compile", .{});
11431142
1144 if (code.target_str) |triple| {1143 if (code.target_str) |triple| {
...@@ -1167,7 +1166,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1167,7 +1166,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1167 var exited_with_signal = false;1166 var exited_with_signal = false;
11681167
1169 const result = if (expected_outcome == ExpectedOutcome.Fail) blk: {1168 const result = if (expected_outcome == ExpectedOutcome.Fail) blk: {
1170 const result = try ChildProcess.exec(allocator, run_args, null, &env_map, max_doc_file_size);1169 const result = try ChildProcess.exec(.{
1170 .allocator = allocator,
1171 .argv = run_args,
1172 .env_map = &env_map,
1173 .max_output_bytes = max_doc_file_size,
1174 });
1171 switch (result.term) {1175 switch (result.term) {
1172 .Exited => |exit_code| {1176 .Exited => |exit_code| {
1173 if (exit_code == 0) {1177 if (exit_code == 0) {
...@@ -1234,7 +1238,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1234,7 +1238,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1234 try test_args.appendSlice(&[_][]const u8{ "-target", triple });1238 try test_args.appendSlice(&[_][]const u8{ "-target", triple });
1235 try out.print(" -target {}", .{triple});1239 try out.print(" -target {}", .{triple});
1236 }1240 }
1237 const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed", .{});1241 const result = exec(allocator, &env_map, test_args.span()) catch return parseError(tokenizer, code.source_token, "test failed", .{});
1238 const escaped_stderr = try escapeHtml(allocator, result.stderr);1242 const escaped_stderr = try escapeHtml(allocator, result.stderr);
1239 const escaped_stdout = try escapeHtml(allocator, result.stdout);1243 const escaped_stdout = try escapeHtml(allocator, result.stdout);
1240 try out.print("\n{}{}</code></pre>\n", .{ escaped_stderr, escaped_stdout });1244 try out.print("\n{}{}</code></pre>\n", .{ escaped_stderr, escaped_stdout });
...@@ -1268,12 +1272,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1268,12 +1272,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1268 try out.print(" --release-small", .{});1272 try out.print(" --release-small", .{});
1269 },1273 },
1270 }1274 }
1271 const result = try ChildProcess.exec(allocator, test_args.toSliceConst(), null, &env_map, max_doc_file_size);1275 const result = try ChildProcess.exec(.{
1276 .allocator = allocator,
1277 .argv = test_args.span(),
1278 .env_map = &env_map,
1279 .max_output_bytes = max_doc_file_size,
1280 });
1272 switch (result.term) {1281 switch (result.term) {
1273 .Exited => |exit_code| {1282 .Exited => |exit_code| {
1274 if (exit_code == 0) {1283 if (exit_code == 0) {
1275 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});1284 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
1276 for (test_args.toSliceConst()) |arg|1285 for (test_args.span()) |arg|
1277 warn("{} ", .{arg})1286 warn("{} ", .{arg})
1278 else1287 else
1279 warn("\n", .{});1288 warn("\n", .{});
...@@ -1282,7 +1291,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1282,7 +1291,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1282 },1291 },
1283 else => {1292 else => {
1284 warn("{}\nThe following command crashed:\n", .{result.stderr});1293 warn("{}\nThe following command crashed:\n", .{result.stderr});
1285 for (test_args.toSliceConst()) |arg|1294 for (test_args.span()) |arg|
1286 warn("{} ", .{arg})1295 warn("{} ", .{arg})
1287 else1296 else
1288 warn("\n", .{});1297 warn("\n", .{});
...@@ -1326,12 +1335,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1326,12 +1335,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1326 },1335 },
1327 }1336 }
13281337
1329 const result = try ChildProcess.exec(allocator, test_args.toSliceConst(), null, &env_map, max_doc_file_size);1338 const result = try ChildProcess.exec(.{
1339 .allocator = allocator,
1340 .argv = test_args.span(),
1341 .env_map = &env_map,
1342 .max_output_bytes = max_doc_file_size,
1343 });
1330 switch (result.term) {1344 switch (result.term) {
1331 .Exited => |exit_code| {1345 .Exited => |exit_code| {
1332 if (exit_code == 0) {1346 if (exit_code == 0) {
1333 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});1347 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
1334 for (test_args.toSliceConst()) |arg|1348 for (test_args.span()) |arg|
1335 warn("{} ", .{arg})1349 warn("{} ", .{arg})
1336 else1350 else
1337 warn("\n", .{});1351 warn("\n", .{});
...@@ -1340,7 +1354,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1340,7 +1354,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1340 },1354 },
1341 else => {1355 else => {
1342 warn("{}\nThe following command crashed:\n", .{result.stderr});1356 warn("{}\nThe following command crashed:\n", .{result.stderr});
1343 for (test_args.toSliceConst()) |arg|1357 for (test_args.span()) |arg|
1344 warn("{} ", .{arg})1358 warn("{} ", .{arg})
1345 else1359 else
1346 warn("\n", .{});1360 warn("\n", .{});
...@@ -1418,12 +1432,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1418,12 +1432,17 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1418 }1432 }
14191433
1420 if (maybe_error_match) |error_match| {1434 if (maybe_error_match) |error_match| {
1421 const result = try ChildProcess.exec(allocator, build_args.toSliceConst(), null, &env_map, max_doc_file_size);1435 const result = try ChildProcess.exec(.{
1436 .allocator = allocator,
1437 .argv = build_args.span(),
1438 .env_map = &env_map,
1439 .max_output_bytes = max_doc_file_size,
1440 });
1422 switch (result.term) {1441 switch (result.term) {
1423 .Exited => |exit_code| {1442 .Exited => |exit_code| {
1424 if (exit_code == 0) {1443 if (exit_code == 0) {
1425 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});1444 warn("{}\nThe following command incorrectly succeeded:\n", .{result.stderr});
1426 for (build_args.toSliceConst()) |arg|1445 for (build_args.span()) |arg|
1427 warn("{} ", .{arg})1446 warn("{} ", .{arg})
1428 else1447 else
1429 warn("\n", .{});1448 warn("\n", .{});
...@@ -1432,7 +1451,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1432,7 +1451,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1432 },1451 },
1433 else => {1452 else => {
1434 warn("{}\nThe following command crashed:\n", .{result.stderr});1453 warn("{}\nThe following command crashed:\n", .{result.stderr});
1435 for (build_args.toSliceConst()) |arg|1454 for (build_args.span()) |arg|
1436 warn("{} ", .{arg})1455 warn("{} ", .{arg})
1437 else1456 else
1438 warn("\n", .{});1457 warn("\n", .{});
...@@ -1447,7 +1466,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1447,7 +1466,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1447 const colored_stderr = try termColor(allocator, escaped_stderr);1466 const colored_stderr = try termColor(allocator, escaped_stderr);
1448 try out.print("\n{}", .{colored_stderr});1467 try out.print("\n{}", .{colored_stderr});
1449 } else {1468 } else {
1450 _ = exec(allocator, &env_map, build_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{});1469 _ = exec(allocator, &env_map, build_args.span()) catch return parseError(tokenizer, code.source_token, "example failed to compile", .{});
1451 }1470 }
1452 if (!code.is_inline) {1471 if (!code.is_inline) {
1453 try out.print("</code></pre>\n", .{});1472 try out.print("</code></pre>\n", .{});
...@@ -1484,7 +1503,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1484,7 +1503,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1484 try test_args.appendSlice(&[_][]const u8{ "-target", triple });1503 try test_args.appendSlice(&[_][]const u8{ "-target", triple });
1485 try out.print(" -target {}", .{triple});1504 try out.print(" -target {}", .{triple});
1486 }1505 }
1487 const result = exec(allocator, &env_map, test_args.toSliceConst()) catch return parseError(tokenizer, code.source_token, "test failed", .{});1506 const result = exec(allocator, &env_map, test_args.span()) catch return parseError(tokenizer, code.source_token, "test failed", .{});
1488 const escaped_stderr = try escapeHtml(allocator, result.stderr);1507 const escaped_stderr = try escapeHtml(allocator, result.stderr);
1489 const escaped_stdout = try escapeHtml(allocator, result.stdout);1508 const escaped_stdout = try escapeHtml(allocator, result.stdout);
1490 try out.print("\n{}{}</code></pre>\n", .{ escaped_stderr, escaped_stdout });1509 try out.print("\n{}{}</code></pre>\n", .{ escaped_stderr, escaped_stdout });
...@@ -1497,7 +1516,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1497,7 +1516,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1497}1516}
14981517
1499fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult {1518fn exec(allocator: *mem.Allocator, env_map: *std.BufMap, args: []const []const u8) !ChildProcess.ExecResult {
1500 const result = try ChildProcess.exec2(.{1519 const result = try ChildProcess.exec(.{
1501 .allocator = allocator,1520 .allocator = allocator,
1502 .argv = args,1521 .argv = args,
1503 .env_map = env_map,1522 .env_map = env_map,
doc/langref.html.in+2-2
...@@ -4953,7 +4953,7 @@ const mem = std.mem;...@@ -4953,7 +4953,7 @@ const mem = std.mem;
4953test "cast *[1][*]const u8 to [*]const ?[*]const u8" {4953test "cast *[1][*]const u8 to [*]const ?[*]const u8" {
4954 const window_name = [1][*]const u8{"window name"};4954 const window_name = [1][*]const u8{"window name"};
4955 const x: [*]const ?[*]const u8 = &window_name;4955 const x: [*]const ?[*]const u8 = &window_name;
4956 assert(mem.eql(u8, std.mem.toSliceConst(u8, @ptrCast([*:0]const u8, x[0].?)), "window name"));4956 assert(mem.eql(u8, std.mem.spanZ(@ptrCast([*:0]const u8, x[0].?)), "window name"));
4957}4957}
4958 {#code_end#}4958 {#code_end#}
4959 {#header_close#}4959 {#header_close#}
...@@ -9310,7 +9310,7 @@ test "string literal to constant slice" {...@@ -9310,7 +9310,7 @@ test "string literal to constant slice" {
9310 </p>9310 </p>
9311 <p>9311 <p>
9312 Sometimes the lifetime of a pointer may be more complicated. For example, when using9312 Sometimes the lifetime of a pointer may be more complicated. For example, when using
9313 {#syntax#}std.ArrayList(T).toSlice(){#endsyntax#}, the returned slice has a lifetime that remains9313 {#syntax#}std.ArrayList(T).span(){#endsyntax#}, the returned slice has a lifetime that remains
9314 valid until the next time the list is resized, such as by appending new elements.9314 valid until the next time the list is resized, such as by appending new elements.
9315 </p>9315 </p>
9316 <p>9316 <p>
lib/std/array_list.zig+29-4
...@@ -189,16 +189,30 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {...@@ -189,16 +189,30 @@ pub fn AlignedArrayList(comptime T: type, comptime alignment: ?u29) type {
189 self.len += items.len;189 self.len += items.len;
190 }190 }
191191
192 /// Append a value to the list `n` times. Allocates more memory192 /// Same as `append` except it returns the number of bytes written, which is always the same
193 /// as necessary.193 /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
194 /// This function may be called only when `T` is `u8`.
195 fn appendWrite(self: *Self, m: []const u8) !usize {
196 try self.appendSlice(m);
197 return m.len;
198 }
199
200 /// Initializes an OutStream which will append to the list.
201 /// This function may be called only when `T` is `u8`.
202 pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) {
203 return .{ .context = self };
204 }
205
206 /// Append a value to the list `n` times.
207 /// Allocates more memory as necessary.
194 pub fn appendNTimes(self: *Self, value: T, n: usize) !void {208 pub fn appendNTimes(self: *Self, value: T, n: usize) !void {
195 const old_len = self.len;209 const old_len = self.len;
196 try self.resize(self.len + n);210 try self.resize(self.len + n);
197 mem.set(T, self.items[old_len..self.len], value);211 mem.set(T, self.items[old_len..self.len], value);
198 }212 }
199213
200 /// Adjust the list's length to `new_len`. Doesn't initialize214 /// Adjust the list's length to `new_len`.
201 /// added items if any.215 /// Does not initialize added items if any.
202 pub fn resize(self: *Self, new_len: usize) !void {216 pub fn resize(self: *Self, new_len: usize) !void {
203 try self.ensureCapacity(new_len);217 try self.ensureCapacity(new_len);
204 self.len = new_len;218 self.len = new_len;
...@@ -479,3 +493,14 @@ test "std.ArrayList: ArrayList(T) of struct T" {...@@ -479,3 +493,14 @@ test "std.ArrayList: ArrayList(T) of struct T" {
479 try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(testing.allocator) });493 try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(testing.allocator) });
480 testing.expect(root.sub_items.items[0].integer == 42);494 testing.expect(root.sub_items.items[0].integer == 42);
481}495}
496
497test "std.ArrayList(u8) implements outStream" {
498 var buffer = ArrayList(u8).init(std.testing.allocator);
499 defer buffer.deinit();
500
501 const x: i32 = 42;
502 const y: i32 = 1234;
503 try buffer.outStream().print("x: {}\ny: {}\n", .{ x, y });
504
505 testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.span());
506}
lib/std/array_list_sentineled.zig created+224
...@@ -0,0 +1,224 @@
1const std = @import("std.zig");
2const debug = std.debug;
3const mem = std.mem;
4const Allocator = mem.Allocator;
5const assert = debug.assert;
6const testing = std.testing;
7const ArrayList = std.ArrayList;
8
9/// A contiguous, growable list of items in memory, with a sentinel after them.
10/// The sentinel is maintained when appending, resizing, etc.
11/// If you do not need a sentinel, consider using `ArrayList` instead.
12pub fn ArrayListSentineled(comptime T: type, comptime sentinel: T) type {
13 return struct {
14 list: ArrayList(T),
15
16 const Self = @This();
17
18 /// Must deinitialize with deinit.
19 pub fn init(allocator: *Allocator, m: []const T) !Self {
20 var self = try initSize(allocator, m.len);
21 mem.copy(T, self.list.items, m);
22 return self;
23 }
24
25 /// Initialize memory to size bytes of undefined values.
26 /// Must deinitialize with deinit.
27 pub fn initSize(allocator: *Allocator, size: usize) !Self {
28 var self = initNull(allocator);
29 try self.resize(size);
30 return self;
31 }
32
33 /// Initialize with capacity to hold at least num bytes.
34 /// Must deinitialize with deinit.
35 pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
36 var self = Self{ .list = try ArrayList(T).initCapacity(allocator, num + 1) };
37 self.list.appendAssumeCapacity(sentinel);
38 return self;
39 }
40
41 /// Must deinitialize with deinit.
42 /// None of the other operations are valid until you do one of these:
43 /// * `replaceContents`
44 /// * `resize`
45 pub fn initNull(allocator: *Allocator) Self {
46 return Self{ .list = ArrayList(T).init(allocator) };
47 }
48
49 /// Must deinitialize with deinit.
50 pub fn initFromBuffer(buffer: Self) !Self {
51 return Self.init(buffer.list.allocator, buffer.span());
52 }
53
54 /// Takes ownership of the passed in slice. The slice must have been
55 /// allocated with `allocator`.
56 /// Must deinitialize with deinit.
57 pub fn fromOwnedSlice(allocator: *Allocator, slice: []T) !Self {
58 var self = Self{ .list = ArrayList(T).fromOwnedSlice(allocator, slice) };
59 try self.list.append(sentinel);
60 return self;
61 }
62
63 /// The caller owns the returned memory. The list becomes null and is safe to `deinit`.
64 pub fn toOwnedSlice(self: *Self) [:sentinel]T {
65 const allocator = self.list.allocator;
66 const result = self.list.toOwnedSlice();
67 self.* = initNull(allocator);
68 return result[0 .. result.len - 1 :sentinel];
69 }
70
71 /// Only works when `T` is `u8`.
72 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Self {
73 const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) {
74 error.Overflow => return error.OutOfMemory,
75 };
76 var self = try Self.initSize(allocator, size);
77 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);
78 return self;
79 }
80
81 pub fn deinit(self: *Self) void {
82 self.list.deinit();
83 }
84
85 pub fn span(self: var) @TypeOf(self.list.items[0 .. self.list.len - 1 :sentinel]) {
86 return self.list.span()[0..self.len() :sentinel];
87 }
88
89 pub fn shrink(self: *Self, new_len: usize) void {
90 assert(new_len <= self.len());
91 self.list.shrink(new_len + 1);
92 self.list.items[self.len()] = sentinel;
93 }
94
95 pub fn resize(self: *Self, new_len: usize) !void {
96 try self.list.resize(new_len + 1);
97 self.list.items[self.len()] = sentinel;
98 }
99
100 pub fn isNull(self: Self) bool {
101 return self.list.len == 0;
102 }
103
104 pub fn len(self: Self) usize {
105 return self.list.len - 1;
106 }
107
108 pub fn capacity(self: Self) usize {
109 return if (self.list.items.len > 0)
110 self.list.items.len - 1
111 else
112 0;
113 }
114
115 pub fn appendSlice(self: *Self, m: []const T) !void {
116 const old_len = self.len();
117 try self.resize(old_len + m.len);
118 mem.copy(T, self.list.span()[old_len..], m);
119 }
120
121 pub fn append(self: *Self, byte: T) !void {
122 const old_len = self.len();
123 try self.resize(old_len + 1);
124 self.list.span()[old_len] = byte;
125 }
126
127 pub fn eql(self: Self, m: []const T) bool {
128 return mem.eql(T, self.span(), m);
129 }
130
131 pub fn startsWith(self: Self, m: []const T) bool {
132 if (self.len() < m.len) return false;
133 return mem.eql(T, self.list.items[0..m.len], m);
134 }
135
136 pub fn endsWith(self: Self, m: []const T) bool {
137 const l = self.len();
138 if (l < m.len) return false;
139 const start = l - m.len;
140 return mem.eql(T, self.list.items[start..l], m);
141 }
142
143 pub fn replaceContents(self: *Self, m: []const T) !void {
144 try self.resize(m.len);
145 mem.copy(T, self.list.span(), m);
146 }
147
148 /// Initializes an OutStream which will append to the list.
149 /// This function may be called only when `T` is `u8`.
150 pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) {
151 return .{ .context = self };
152 }
153
154 /// Same as `append` except it returns the number of bytes written, which is always the same
155 /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
156 /// This function may be called only when `T` is `u8`.
157 pub fn appendWrite(self: *Self, m: []const u8) !usize {
158 try self.appendSlice(m);
159 return m.len;
160 }
161 };
162}
163
164test "simple" {
165 var buf = try ArrayListSentineled(u8, 0).init(testing.allocator, "");
166 defer buf.deinit();
167
168 testing.expect(buf.len() == 0);
169 try buf.appendSlice("hello");
170 try buf.appendSlice(" ");
171 try buf.appendSlice("world");
172 testing.expect(buf.eql("hello world"));
173 testing.expect(mem.eql(u8, mem.spanZ(buf.span().ptr), buf.span()));
174
175 var buf2 = try ArrayListSentineled(u8, 0).initFromBuffer(buf);
176 defer buf2.deinit();
177 testing.expect(buf.eql(buf2.span()));
178
179 testing.expect(buf.startsWith("hell"));
180 testing.expect(buf.endsWith("orld"));
181
182 try buf2.resize(4);
183 testing.expect(buf.startsWith(buf2.span()));
184}
185
186test "initSize" {
187 var buf = try ArrayListSentineled(u8, 0).initSize(testing.allocator, 3);
188 defer buf.deinit();
189 testing.expect(buf.len() == 3);
190 try buf.appendSlice("hello");
191 testing.expect(mem.eql(u8, buf.span()[3..], "hello"));
192}
193
194test "initCapacity" {
195 var buf = try ArrayListSentineled(u8, 0).initCapacity(testing.allocator, 10);
196 defer buf.deinit();
197 testing.expect(buf.len() == 0);
198 testing.expect(buf.capacity() >= 10);
199 const old_cap = buf.capacity();
200 try buf.appendSlice("hello");
201 testing.expect(buf.len() == 5);
202 testing.expect(buf.capacity() == old_cap);
203 testing.expect(mem.eql(u8, buf.span(), "hello"));
204}
205
206test "print" {
207 var buf = try ArrayListSentineled(u8, 0).init(testing.allocator, "");
208 defer buf.deinit();
209
210 try buf.outStream().print("Hello {} the {}", .{ 2, "world" });
211 testing.expect(buf.eql("Hello 2 the world"));
212}
213
214test "outStream" {
215 var buffer = try ArrayListSentineled(u8, 0).initSize(testing.allocator, 0);
216 defer buffer.deinit();
217 const buf_stream = buffer.outStream();
218
219 const x: i32 = 42;
220 const y: i32 = 1234;
221 try buf_stream.print("x: {}\ny: {}\n", .{ x, y });
222
223 testing.expect(mem.eql(u8, buffer.span(), "x: 42\ny: 1234\n"));
224}
lib/std/atomic/queue.zig+1-1
...@@ -227,7 +227,7 @@ fn startPuts(ctx: *Context) u8 {...@@ -227,7 +227,7 @@ fn startPuts(ctx: *Context) u8 {
227 var r = std.rand.DefaultPrng.init(0xdeadbeef);227 var r = std.rand.DefaultPrng.init(0xdeadbeef);
228 while (put_count != 0) : (put_count -= 1) {228 while (put_count != 0) : (put_count -= 1) {
229 std.time.sleep(1); // let the os scheduler be our fuzz229 std.time.sleep(1); // let the os scheduler be our fuzz
230 const x = @bitCast(i32, r.random.scalar(u32));230 const x = @bitCast(i32, r.random.int(u32));
231 const node = ctx.allocator.create(Queue(i32).Node) catch unreachable;231 const node = ctx.allocator.create(Queue(i32).Node) catch unreachable;
232 node.* = .{232 node.* = .{
233 .prev = undefined,233 .prev = undefined,
lib/std/atomic/stack.zig+1-1
...@@ -150,7 +150,7 @@ fn startPuts(ctx: *Context) u8 {...@@ -150,7 +150,7 @@ fn startPuts(ctx: *Context) u8 {
150 var r = std.rand.DefaultPrng.init(0xdeadbeef);150 var r = std.rand.DefaultPrng.init(0xdeadbeef);
151 while (put_count != 0) : (put_count -= 1) {151 while (put_count != 0) : (put_count -= 1) {
152 std.time.sleep(1); // let the os scheduler be our fuzz152 std.time.sleep(1); // let the os scheduler be our fuzz
153 const x = @bitCast(i32, r.random.scalar(u32));153 const x = @bitCast(i32, r.random.int(u32));
154 const node = ctx.allocator.create(Stack(i32).Node) catch unreachable;154 const node = ctx.allocator.create(Stack(i32).Node) catch unreachable;
155 node.* = Stack(i32).Node{155 node.* = Stack(i32).Node{
156 .next = undefined,156 .next = undefined,
lib/std/buffer.zig deleted-225
...@@ -1,225 +0,0 @@
1const std = @import("std.zig");
2const debug = std.debug;
3const mem = std.mem;
4const Allocator = mem.Allocator;
5const assert = debug.assert;
6const testing = std.testing;
7const ArrayList = std.ArrayList;
8
9/// A buffer that allocates memory and maintains a null byte at the end.
10pub const Buffer = struct {
11 list: ArrayList(u8),
12
13 /// Must deinitialize with deinit.
14 pub fn init(allocator: *Allocator, m: []const u8) !Buffer {
15 var self = try initSize(allocator, m.len);
16 mem.copy(u8, self.list.items, m);
17 return self;
18 }
19
20 /// Initialize memory to size bytes of undefined values.
21 /// Must deinitialize with deinit.
22 pub fn initSize(allocator: *Allocator, size: usize) !Buffer {
23 var self = initNull(allocator);
24 try self.resize(size);
25 return self;
26 }
27
28 /// Initialize with capacity to hold at least num bytes.
29 /// Must deinitialize with deinit.
30 pub fn initCapacity(allocator: *Allocator, num: usize) !Buffer {
31 var self = Buffer{ .list = try ArrayList(u8).initCapacity(allocator, num + 1) };
32 self.list.appendAssumeCapacity(0);
33 return self;
34 }
35
36 /// Must deinitialize with deinit.
37 /// None of the other operations are valid until you do one of these:
38 /// * ::replaceContents
39 /// * ::resize
40 pub fn initNull(allocator: *Allocator) Buffer {
41 return Buffer{ .list = ArrayList(u8).init(allocator) };
42 }
43
44 /// Must deinitialize with deinit.
45 pub fn initFromBuffer(buffer: Buffer) !Buffer {
46 return Buffer.init(buffer.list.allocator, buffer.toSliceConst());
47 }
48
49 /// Buffer takes ownership of the passed in slice. The slice must have been
50 /// allocated with `allocator`.
51 /// Must deinitialize with deinit.
52 pub fn fromOwnedSlice(allocator: *Allocator, slice: []u8) !Buffer {
53 var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) };
54 try self.list.append(0);
55 return self;
56 }
57
58 /// The caller owns the returned memory. The Buffer becomes null and
59 /// is safe to `deinit`.
60 pub fn toOwnedSlice(self: *Buffer) [:0]u8 {
61 const allocator = self.list.allocator;
62 const result = self.list.toOwnedSlice();
63 self.* = initNull(allocator);
64 return result[0 .. result.len - 1 :0];
65 }
66
67 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer {
68 const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) {
69 error.Overflow => return error.OutOfMemory,
70 };
71 var self = try Buffer.initSize(allocator, size);
72 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);
73 return self;
74 }
75
76 pub fn deinit(self: *Buffer) void {
77 self.list.deinit();
78 }
79
80 pub fn span(self: var) @TypeOf(self.list.items[0 .. self.list.len - 1 :0]) {
81 return self.list.span()[0..self.len() :0];
82 }
83
84 /// Deprecated: use `span`
85 pub fn toSlice(self: Buffer) [:0]u8 {
86 return self.span();
87 }
88
89 /// Deprecated: use `span`
90 pub fn toSliceConst(self: Buffer) [:0]const u8 {
91 return self.span();
92 }
93
94 pub fn shrink(self: *Buffer, new_len: usize) void {
95 assert(new_len <= self.len());
96 self.list.shrink(new_len + 1);
97 self.list.items[self.len()] = 0;
98 }
99
100 pub fn resize(self: *Buffer, new_len: usize) !void {
101 try self.list.resize(new_len + 1);
102 self.list.items[self.len()] = 0;
103 }
104
105 pub fn isNull(self: Buffer) bool {
106 return self.list.len == 0;
107 }
108
109 pub fn len(self: Buffer) usize {
110 return self.list.len - 1;
111 }
112
113 pub fn capacity(self: Buffer) usize {
114 return if (self.list.items.len > 0)
115 self.list.items.len - 1
116 else
117 0;
118 }
119
120 pub fn append(self: *Buffer, m: []const u8) !void {
121 const old_len = self.len();
122 try self.resize(old_len + m.len);
123 mem.copy(u8, self.list.toSlice()[old_len..], m);
124 }
125
126 pub fn appendByte(self: *Buffer, byte: u8) !void {
127 const old_len = self.len();
128 try self.resize(old_len + 1);
129 self.list.toSlice()[old_len] = byte;
130 }
131
132 pub fn eql(self: Buffer, m: []const u8) bool {
133 return mem.eql(u8, self.toSliceConst(), m);
134 }
135
136 pub fn startsWith(self: Buffer, m: []const u8) bool {
137 if (self.len() < m.len) return false;
138 return mem.eql(u8, self.list.items[0..m.len], m);
139 }
140
141 pub fn endsWith(self: Buffer, m: []const u8) bool {
142 const l = self.len();
143 if (l < m.len) return false;
144 const start = l - m.len;
145 return mem.eql(u8, self.list.items[start..l], m);
146 }
147
148 pub fn replaceContents(self: *Buffer, m: []const u8) !void {
149 try self.resize(m.len);
150 mem.copy(u8, self.list.toSlice(), m);
151 }
152
153 pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) {
154 return .{ .context = self };
155 }
156
157 /// Same as `append` except it returns the number of bytes written, which is always the same
158 /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
159 pub fn appendWrite(self: *Buffer, m: []const u8) !usize {
160 try self.append(m);
161 return m.len;
162 }
163};
164
165test "simple Buffer" {
166 var buf = try Buffer.init(testing.allocator, "");
167 defer buf.deinit();
168
169 testing.expect(buf.len() == 0);
170 try buf.append("hello");
171 try buf.append(" ");
172 try buf.append("world");
173 testing.expect(buf.eql("hello world"));
174 testing.expect(mem.eql(u8, mem.toSliceConst(u8, buf.toSliceConst().ptr), buf.toSliceConst()));
175
176 var buf2 = try Buffer.initFromBuffer(buf);
177 defer buf2.deinit();
178 testing.expect(buf.eql(buf2.toSliceConst()));
179
180 testing.expect(buf.startsWith("hell"));
181 testing.expect(buf.endsWith("orld"));
182
183 try buf2.resize(4);
184 testing.expect(buf.startsWith(buf2.toSlice()));
185}
186
187test "Buffer.initSize" {
188 var buf = try Buffer.initSize(testing.allocator, 3);
189 defer buf.deinit();
190 testing.expect(buf.len() == 3);
191 try buf.append("hello");
192 testing.expect(mem.eql(u8, buf.toSliceConst()[3..], "hello"));
193}
194
195test "Buffer.initCapacity" {
196 var buf = try Buffer.initCapacity(testing.allocator, 10);
197 defer buf.deinit();
198 testing.expect(buf.len() == 0);
199 testing.expect(buf.capacity() >= 10);
200 const old_cap = buf.capacity();
201 try buf.append("hello");
202 testing.expect(buf.len() == 5);
203 testing.expect(buf.capacity() == old_cap);
204 testing.expect(mem.eql(u8, buf.toSliceConst(), "hello"));
205}
206
207test "Buffer.print" {
208 var buf = try Buffer.init(testing.allocator, "");
209 defer buf.deinit();
210
211 try buf.outStream().print("Hello {} the {}", .{ 2, "world" });
212 testing.expect(buf.eql("Hello 2 the world"));
213}
214
215test "Buffer.outStream" {
216 var buffer = try Buffer.initSize(testing.allocator, 0);
217 defer buffer.deinit();
218 const buf_stream = buffer.outStream();
219
220 const x: i32 = 42;
221 const y: i32 = 1234;
222 try buf_stream.print("x: {}\ny: {}\n", .{ x, y });
223
224 testing.expect(mem.eql(u8, buffer.toSlice(), "x: 42\ny: 1234\n"));
225}
lib/std/build.zig+29-32
...@@ -355,7 +355,7 @@ pub const Builder = struct {...@@ -355,7 +355,7 @@ pub const Builder = struct {
355 }355 }
356 }356 }
357357
358 for (wanted_steps.toSliceConst()) |s| {358 for (wanted_steps.span()) |s| {
359 try self.makeOneStep(s);359 try self.makeOneStep(s);
360 }360 }
361 }361 }
...@@ -372,7 +372,7 @@ pub const Builder = struct {...@@ -372,7 +372,7 @@ pub const Builder = struct {
372 const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step);372 const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step);
373 const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls);373 const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls);
374374
375 for (self.installed_files.toSliceConst()) |installed_file| {375 for (self.installed_files.span()) |installed_file| {
376 const full_path = self.getInstallPath(installed_file.dir, installed_file.path);376 const full_path = self.getInstallPath(installed_file.dir, installed_file.path);
377 if (self.verbose) {377 if (self.verbose) {
378 warn("rm {}\n", .{full_path});378 warn("rm {}\n", .{full_path});
...@@ -390,7 +390,7 @@ pub const Builder = struct {...@@ -390,7 +390,7 @@ pub const Builder = struct {
390 }390 }
391 s.loop_flag = true;391 s.loop_flag = true;
392392
393 for (s.dependencies.toSlice()) |dep| {393 for (s.dependencies.span()) |dep| {
394 self.makeOneStep(dep) catch |err| {394 self.makeOneStep(dep) catch |err| {
395 if (err == error.DependencyLoopDetected) {395 if (err == error.DependencyLoopDetected) {
396 warn(" {}\n", .{s.name});396 warn(" {}\n", .{s.name});
...@@ -405,7 +405,7 @@ pub const Builder = struct {...@@ -405,7 +405,7 @@ pub const Builder = struct {
405 }405 }
406406
407 fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step {407 fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step {
408 for (self.top_level_steps.toSliceConst()) |top_level_step| {408 for (self.top_level_steps.span()) |top_level_step| {
409 if (mem.eql(u8, top_level_step.step.name, name)) {409 if (mem.eql(u8, top_level_step.step.name, name)) {
410 return &top_level_step.step;410 return &top_level_step.step;
411 }411 }
...@@ -470,7 +470,7 @@ pub const Builder = struct {...@@ -470,7 +470,7 @@ pub const Builder = struct {
470 return null;470 return null;
471 },471 },
472 UserValue.Scalar => |s| return &[_][]const u8{s},472 UserValue.Scalar => |s| return &[_][]const u8{s},
473 UserValue.List => |lst| return lst.toSliceConst(),473 UserValue.List => |lst| return lst.span(),
474 },474 },
475 }475 }
476 }476 }
...@@ -866,7 +866,7 @@ pub const Builder = struct {...@@ -866,7 +866,7 @@ pub const Builder = struct {
866 pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {866 pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {
867 // TODO report error for ambiguous situations867 // TODO report error for ambiguous situations
868 const exe_extension = @as(CrossTarget, .{}).exeFileExt();868 const exe_extension = @as(CrossTarget, .{}).exeFileExt();
869 for (self.search_prefixes.toSliceConst()) |search_prefix| {869 for (self.search_prefixes.span()) |search_prefix| {
870 for (names) |name| {870 for (names) |name| {
871 if (fs.path.isAbsolute(name)) {871 if (fs.path.isAbsolute(name)) {
872 return name;872 return name;
...@@ -1010,7 +1010,7 @@ pub const Builder = struct {...@@ -1010,7 +1010,7 @@ pub const Builder = struct {
1010 .desc = tok_it.rest(),1010 .desc = tok_it.rest(),
1011 });1011 });
1012 }1012 }
1013 return list.toSliceConst();1013 return list.span();
1014 }1014 }
10151015
1016 fn getPkgConfigList(self: *Builder) ![]const PkgConfigPkg {1016 fn getPkgConfigList(self: *Builder) ![]const PkgConfigPkg {
...@@ -1139,7 +1139,7 @@ pub const LibExeObjStep = struct {...@@ -1139,7 +1139,7 @@ pub const LibExeObjStep = struct {
1139 out_lib_filename: []const u8,1139 out_lib_filename: []const u8,
1140 out_pdb_filename: []const u8,1140 out_pdb_filename: []const u8,
1141 packages: ArrayList(Pkg),1141 packages: ArrayList(Pkg),
1142 build_options_contents: std.Buffer,1142 build_options_contents: std.ArrayList(u8),
1143 system_linker_hack: bool = false,1143 system_linker_hack: bool = false,
11441144
1145 object_src: []const u8,1145 object_src: []const u8,
...@@ -1274,7 +1274,7 @@ pub const LibExeObjStep = struct {...@@ -1274,7 +1274,7 @@ pub const LibExeObjStep = struct {
1274 .lib_paths = ArrayList([]const u8).init(builder.allocator),1274 .lib_paths = ArrayList([]const u8).init(builder.allocator),
1275 .framework_dirs = ArrayList([]const u8).init(builder.allocator),1275 .framework_dirs = ArrayList([]const u8).init(builder.allocator),
1276 .object_src = undefined,1276 .object_src = undefined,
1277 .build_options_contents = std.Buffer.initSize(builder.allocator, 0) catch unreachable,1277 .build_options_contents = std.ArrayList(u8).init(builder.allocator),
1278 .c_std = Builder.CStd.C99,1278 .c_std = Builder.CStd.C99,
1279 .override_lib_dir = null,1279 .override_lib_dir = null,
1280 .main_pkg_path = null,1280 .main_pkg_path = null,
...@@ -1395,7 +1395,7 @@ pub const LibExeObjStep = struct {...@@ -1395,7 +1395,7 @@ pub const LibExeObjStep = struct {
1395 if (isLibCLibrary(name)) {1395 if (isLibCLibrary(name)) {
1396 return self.is_linking_libc;1396 return self.is_linking_libc;
1397 }1397 }
1398 for (self.link_objects.toSliceConst()) |link_object| {1398 for (self.link_objects.span()) |link_object| {
1399 switch (link_object) {1399 switch (link_object) {
1400 LinkObject.SystemLib => |n| if (mem.eql(u8, n, name)) return true,1400 LinkObject.SystemLib => |n| if (mem.eql(u8, n, name)) return true,
1401 else => continue,1401 else => continue,
...@@ -1599,10 +1599,7 @@ pub const LibExeObjStep = struct {...@@ -1599,10 +1599,7 @@ pub const LibExeObjStep = struct {
1599 self.main_pkg_path = dir_path;1599 self.main_pkg_path = dir_path;
1600 }1600 }
16011601
1602 /// Deprecated; just set the field directly.1602 pub const setDisableGenH = @compileError("deprecated; set the emit_h field directly");
1603 pub fn setDisableGenH(self: *LibExeObjStep, is_disabled: bool) void {
1604 self.emit_h = !is_disabled;
1605 }
16061603
1607 pub fn setLibCFile(self: *LibExeObjStep, libc_file: ?[]const u8) void {1604 pub fn setLibCFile(self: *LibExeObjStep, libc_file: ?[]const u8) void {
1608 self.libc_file = libc_file;1605 self.libc_file = libc_file;
...@@ -1762,7 +1759,7 @@ pub const LibExeObjStep = struct {...@@ -1762,7 +1759,7 @@ pub const LibExeObjStep = struct {
1762 self.include_dirs.append(IncludeDir{ .OtherStep = other }) catch unreachable;1759 self.include_dirs.append(IncludeDir{ .OtherStep = other }) catch unreachable;
17631760
1764 // Inherit dependency on system libraries1761 // Inherit dependency on system libraries
1765 for (other.link_objects.toSliceConst()) |link_object| {1762 for (other.link_objects.span()) |link_object| {
1766 switch (link_object) {1763 switch (link_object) {
1767 .SystemLib => |name| self.linkSystemLibrary(name),1764 .SystemLib => |name| self.linkSystemLibrary(name),
1768 else => continue,1765 else => continue,
...@@ -1802,7 +1799,7 @@ pub const LibExeObjStep = struct {...@@ -1802,7 +1799,7 @@ pub const LibExeObjStep = struct {
18021799
1803 if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder));1800 if (self.root_src) |root_src| try zig_args.append(root_src.getPath(builder));
18041801
1805 for (self.link_objects.toSlice()) |link_object| {1802 for (self.link_objects.span()) |link_object| {
1806 switch (link_object) {1803 switch (link_object) {
1807 .StaticPath => |static_path| {1804 .StaticPath => |static_path| {
1808 try zig_args.append("--object");1805 try zig_args.append("--object");
...@@ -1850,12 +1847,12 @@ pub const LibExeObjStep = struct {...@@ -1850,12 +1847,12 @@ pub const LibExeObjStep = struct {
1850 }1847 }
1851 }1848 }
18521849
1853 if (self.build_options_contents.len() > 0) {1850 if (self.build_options_contents.len > 0) {
1854 const build_options_file = try fs.path.join(1851 const build_options_file = try fs.path.join(
1855 builder.allocator,1852 builder.allocator,
1856 &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) },1853 &[_][]const u8{ builder.cache_root, builder.fmt("{}_build_options.zig", .{self.name}) },
1857 );1854 );
1858 try std.io.writeFile(build_options_file, self.build_options_contents.toSliceConst());1855 try fs.cwd().writeFile(build_options_file, self.build_options_contents.span());
1859 try zig_args.append("--pkg-begin");1856 try zig_args.append("--pkg-begin");
1860 try zig_args.append("build_options");1857 try zig_args.append("build_options");
1861 try zig_args.append(builder.pathFromRoot(build_options_file));1858 try zig_args.append(builder.pathFromRoot(build_options_file));
...@@ -1963,22 +1960,22 @@ pub const LibExeObjStep = struct {...@@ -1963,22 +1960,22 @@ pub const LibExeObjStep = struct {
1963 try zig_args.append(cross.cpu.model.name);1960 try zig_args.append(cross.cpu.model.name);
1964 }1961 }
1965 } else {1962 } else {
1966 var mcpu_buffer = try std.Buffer.init(builder.allocator, "-mcpu=");1963 var mcpu_buffer = std.ArrayList(u8).init(builder.allocator);
1967 try mcpu_buffer.append(cross.cpu.model.name);1964
1965 try mcpu_buffer.outStream().print("-mcpu={}", .{cross.cpu.model.name});
19681966
1969 for (all_features) |feature, i_usize| {1967 for (all_features) |feature, i_usize| {
1970 const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize);1968 const i = @intCast(std.Target.Cpu.Feature.Set.Index, i_usize);
1971 const in_cpu_set = populated_cpu_features.isEnabled(i);1969 const in_cpu_set = populated_cpu_features.isEnabled(i);
1972 const in_actual_set = cross.cpu.features.isEnabled(i);1970 const in_actual_set = cross.cpu.features.isEnabled(i);
1973 if (in_cpu_set and !in_actual_set) {1971 if (in_cpu_set and !in_actual_set) {
1974 try mcpu_buffer.appendByte('-');1972 try mcpu_buffer.outStream().print("-{}", .{feature.name});
1975 try mcpu_buffer.append(feature.name);
1976 } else if (!in_cpu_set and in_actual_set) {1973 } else if (!in_cpu_set and in_actual_set) {
1977 try mcpu_buffer.appendByte('+');1974 try mcpu_buffer.outStream().print("+{}", .{feature.name});
1978 try mcpu_buffer.append(feature.name);
1979 }1975 }
1980 }1976 }
1981 try zig_args.append(mcpu_buffer.toSliceConst());1977
1978 try zig_args.append(mcpu_buffer.toOwnedSlice());
1982 }1979 }
19831980
1984 if (self.target.dynamic_linker.get()) |dynamic_linker| {1981 if (self.target.dynamic_linker.get()) |dynamic_linker| {
...@@ -2040,7 +2037,7 @@ pub const LibExeObjStep = struct {...@@ -2040,7 +2037,7 @@ pub const LibExeObjStep = struct {
2040 try zig_args.append("--test-cmd-bin");2037 try zig_args.append("--test-cmd-bin");
2041 },2038 },
2042 }2039 }
2043 for (self.packages.toSliceConst()) |pkg| {2040 for (self.packages.span()) |pkg| {
2044 try zig_args.append("--pkg-begin");2041 try zig_args.append("--pkg-begin");
2045 try zig_args.append(pkg.name);2042 try zig_args.append(pkg.name);
2046 try zig_args.append(builder.pathFromRoot(pkg.path));2043 try zig_args.append(builder.pathFromRoot(pkg.path));
...@@ -2057,7 +2054,7 @@ pub const LibExeObjStep = struct {...@@ -2057,7 +2054,7 @@ pub const LibExeObjStep = struct {
2057 try zig_args.append("--pkg-end");2054 try zig_args.append("--pkg-end");
2058 }2055 }
20592056
2060 for (self.include_dirs.toSliceConst()) |include_dir| {2057 for (self.include_dirs.span()) |include_dir| {
2061 switch (include_dir) {2058 switch (include_dir) {
2062 .RawPath => |include_path| {2059 .RawPath => |include_path| {
2063 try zig_args.append("-I");2060 try zig_args.append("-I");
...@@ -2075,18 +2072,18 @@ pub const LibExeObjStep = struct {...@@ -2075,18 +2072,18 @@ pub const LibExeObjStep = struct {
2075 }2072 }
2076 }2073 }
20772074
2078 for (self.lib_paths.toSliceConst()) |lib_path| {2075 for (self.lib_paths.span()) |lib_path| {
2079 try zig_args.append("-L");2076 try zig_args.append("-L");
2080 try zig_args.append(lib_path);2077 try zig_args.append(lib_path);
2081 }2078 }
20822079
2083 for (self.c_macros.toSliceConst()) |c_macro| {2080 for (self.c_macros.span()) |c_macro| {
2084 try zig_args.append("-D");2081 try zig_args.append("-D");
2085 try zig_args.append(c_macro);2082 try zig_args.append(c_macro);
2086 }2083 }
20872084
2088 if (self.target.isDarwin()) {2085 if (self.target.isDarwin()) {
2089 for (self.framework_dirs.toSliceConst()) |dir| {2086 for (self.framework_dirs.span()) |dir| {
2090 try zig_args.append("-F");2087 try zig_args.append("-F");
2091 try zig_args.append(dir);2088 try zig_args.append(dir);
2092 }2089 }
...@@ -2146,12 +2143,12 @@ pub const LibExeObjStep = struct {...@@ -2146,12 +2143,12 @@ pub const LibExeObjStep = struct {
2146 }2143 }
21472144
2148 if (self.kind == Kind.Test) {2145 if (self.kind == Kind.Test) {
2149 try builder.spawnChild(zig_args.toSliceConst());2146 try builder.spawnChild(zig_args.span());
2150 } else {2147 } else {
2151 try zig_args.append("--cache");2148 try zig_args.append("--cache");
2152 try zig_args.append("on");2149 try zig_args.append("on");
21532150
2154 const output_dir_nl = try builder.execFromStep(zig_args.toSliceConst(), &self.step);2151 const output_dir_nl = try builder.execFromStep(zig_args.span(), &self.step);
2155 const build_output_dir = mem.trimRight(u8, output_dir_nl, "\r\n");2152 const build_output_dir = mem.trimRight(u8, output_dir_nl, "\r\n");
21562153
2157 if (self.output_dir) |output_dir| {2154 if (self.output_dir) |output_dir| {
lib/std/build/emit_raw.zig+6-6
...@@ -72,7 +72,7 @@ const BinaryElfOutput = struct {...@@ -72,7 +72,7 @@ const BinaryElfOutput = struct {
72 newSegment.binaryOffset = 0;72 newSegment.binaryOffset = 0;
73 newSegment.firstSection = null;73 newSegment.firstSection = null;
7474
75 for (self.sections.toSlice()) |section| {75 for (self.sections.span()) |section| {
76 if (sectionWithinSegment(section, phdr)) {76 if (sectionWithinSegment(section, phdr)) {
77 if (section.segment) |sectionSegment| {77 if (section.segment) |sectionSegment| {
78 if (sectionSegment.elfOffset > newSegment.elfOffset) {78 if (sectionSegment.elfOffset > newSegment.elfOffset) {
...@@ -92,7 +92,7 @@ const BinaryElfOutput = struct {...@@ -92,7 +92,7 @@ const BinaryElfOutput = struct {
92 }92 }
93 }93 }
9494
95 sort.sort(*BinaryElfSegment, self.segments.toSlice(), segmentSortCompare);95 sort.sort(*BinaryElfSegment, self.segments.span(), segmentSortCompare);
9696
97 if (self.segments.len > 0) {97 if (self.segments.len > 0) {
98 const firstSegment = self.segments.at(0);98 const firstSegment = self.segments.at(0);
...@@ -105,19 +105,19 @@ const BinaryElfOutput = struct {...@@ -105,19 +105,19 @@ const BinaryElfOutput = struct {
105105
106 const basePhysicalAddress = firstSegment.physicalAddress;106 const basePhysicalAddress = firstSegment.physicalAddress;
107107
108 for (self.segments.toSlice()) |segment| {108 for (self.segments.span()) |segment| {
109 segment.binaryOffset = segment.physicalAddress - basePhysicalAddress;109 segment.binaryOffset = segment.physicalAddress - basePhysicalAddress;
110 }110 }
111 }111 }
112 }112 }
113113
114 for (self.sections.toSlice()) |section| {114 for (self.sections.span()) |section| {
115 if (section.segment) |segment| {115 if (section.segment) |segment| {
116 section.binaryOffset = segment.binaryOffset + (section.elfOffset - segment.elfOffset);116 section.binaryOffset = segment.binaryOffset + (section.elfOffset - segment.elfOffset);
117 }117 }
118 }118 }
119119
120 sort.sort(*BinaryElfSection, self.sections.toSlice(), sectionSortCompare);120 sort.sort(*BinaryElfSection, self.sections.span(), sectionSortCompare);
121121
122 return self;122 return self;
123 }123 }
...@@ -165,7 +165,7 @@ fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !v...@@ -165,7 +165,7 @@ fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !v
165 var binary_elf_output = try BinaryElfOutput.parse(allocator, elf_file);165 var binary_elf_output = try BinaryElfOutput.parse(allocator, elf_file);
166 defer binary_elf_output.deinit();166 defer binary_elf_output.deinit();
167167
168 for (binary_elf_output.sections.toSlice()) |section| {168 for (binary_elf_output.sections.span()) |section| {
169 try writeBinaryElfSection(elf_file, out_file, section);169 try writeBinaryElfSection(elf_file, out_file, section);
170 }170 }
171}171}
lib/std/build/run.zig+3-3
...@@ -139,7 +139,7 @@ pub const RunStep = struct {...@@ -139,7 +139,7 @@ pub const RunStep = struct {
139 const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root;139 const cwd = if (self.cwd) |cwd| self.builder.pathFromRoot(cwd) else self.builder.build_root;
140140
141 var argv_list = ArrayList([]const u8).init(self.builder.allocator);141 var argv_list = ArrayList([]const u8).init(self.builder.allocator);
142 for (self.argv.toSlice()) |arg| {142 for (self.argv.span()) |arg| {
143 switch (arg) {143 switch (arg) {
144 Arg.Bytes => |bytes| try argv_list.append(bytes),144 Arg.Bytes => |bytes| try argv_list.append(bytes),
145 Arg.Artifact => |artifact| {145 Arg.Artifact => |artifact| {
...@@ -153,7 +153,7 @@ pub const RunStep = struct {...@@ -153,7 +153,7 @@ pub const RunStep = struct {
153 }153 }
154 }154 }
155155
156 const argv = argv_list.toSliceConst();156 const argv = argv_list.span();
157157
158 const child = std.ChildProcess.init(argv, self.builder.allocator) catch unreachable;158 const child = std.ChildProcess.init(argv, self.builder.allocator) catch unreachable;
159 defer child.deinit();159 defer child.deinit();
...@@ -289,7 +289,7 @@ pub const RunStep = struct {...@@ -289,7 +289,7 @@ pub const RunStep = struct {
289 }289 }
290290
291 fn addPathForDynLibs(self: *RunStep, artifact: *LibExeObjStep) void {291 fn addPathForDynLibs(self: *RunStep, artifact: *LibExeObjStep) void {
292 for (artifact.link_objects.toSliceConst()) |link_object| {292 for (artifact.link_objects.span()) |link_object| {
293 switch (link_object) {293 switch (link_object) {
294 .OtherStep => |other| {294 .OtherStep => |other| {
295 if (other.target.isWindows() and other.isDynamicLibrary()) {295 if (other.target.isWindows() and other.isDynamicLibrary()) {
lib/std/build/translate_c.zig+1-1
...@@ -71,7 +71,7 @@ pub const TranslateCStep = struct {...@@ -71,7 +71,7 @@ pub const TranslateCStep = struct {
7171
72 try argv_list.append(self.source.getPath(self.builder));72 try argv_list.append(self.source.getPath(self.builder));
7373
74 const output_path_nl = try self.builder.execFromStep(argv_list.toSliceConst(), &self.step);74 const output_path_nl = try self.builder.execFromStep(argv_list.span(), &self.step);
75 const output_path = mem.trimRight(u8, output_path_nl, "\r\n");75 const output_path = mem.trimRight(u8, output_path_nl, "\r\n");
7676
77 self.out_basename = fs.path.basename(output_path);77 self.out_basename = fs.path.basename(output_path);
lib/std/build/write_file.zig+2-2
...@@ -59,7 +59,7 @@ pub const WriteFileStep = struct {...@@ -59,7 +59,7 @@ pub const WriteFileStep = struct {
59 // new random bytes when WriteFileStep implementation is modified59 // new random bytes when WriteFileStep implementation is modified
60 // in a non-backwards-compatible way.60 // in a non-backwards-compatible way.
61 hash.update("eagVR1dYXoE7ARDP");61 hash.update("eagVR1dYXoE7ARDP");
62 for (self.files.toSliceConst()) |file| {62 for (self.files.span()) |file| {
63 hash.update(file.basename);63 hash.update(file.basename);
64 hash.update(file.bytes);64 hash.update(file.bytes);
65 hash.update("|");65 hash.update("|");
...@@ -80,7 +80,7 @@ pub const WriteFileStep = struct {...@@ -80,7 +80,7 @@ pub const WriteFileStep = struct {
80 };80 };
81 var dir = try fs.cwd().openDir(self.output_dir, .{});81 var dir = try fs.cwd().openDir(self.output_dir, .{});
82 defer dir.close();82 defer dir.close();
83 for (self.files.toSliceConst()) |file| {83 for (self.files.span()) |file| {
84 dir.writeFile(file.basename, file.bytes) catch |err| {84 dir.writeFile(file.basename, file.bytes) catch |err| {
85 warn("unable to write {} into {}: {}\n", .{85 warn("unable to write {} into {}: {}\n", .{
86 file.basename,86 file.basename,
lib/std/c.zig+45-13
...@@ -73,7 +73,6 @@ pub extern "c" fn abort() noreturn;...@@ -73,7 +73,6 @@ pub extern "c" fn abort() noreturn;
73pub extern "c" fn exit(code: c_int) noreturn;73pub extern "c" fn exit(code: c_int) noreturn;
74pub extern "c" fn isatty(fd: fd_t) c_int;74pub extern "c" fn isatty(fd: fd_t) c_int;
75pub extern "c" fn close(fd: fd_t) c_int;75pub extern "c" fn close(fd: fd_t) c_int;
76pub extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int;
77pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;76pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;
78pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t;77pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t;
79pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;78pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;
...@@ -86,7 +85,6 @@ pub extern "c" fn pread(fd: fd_t, buf: [*]u8, nbyte: usize, offset: u64) isize;...@@ -86,7 +85,6 @@ pub extern "c" fn pread(fd: fd_t, buf: [*]u8, nbyte: usize, offset: u64) isize;
86pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: u64) isize;85pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: u64) isize;
87pub extern "c" fn writev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint) isize;86pub extern "c" fn writev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint) isize;
88pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: u64) isize;87pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: u64) isize;
89pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int;
90pub extern "c" fn write(fd: fd_t, buf: [*]const u8, nbyte: usize) isize;88pub extern "c" fn write(fd: fd_t, buf: [*]const u8, nbyte: usize) isize;
91pub extern "c" fn pwrite(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: u64) isize;89pub extern "c" fn pwrite(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: u64) isize;
92pub extern "c" fn mmap(addr: ?*align(page_size) c_void, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: u64) *c_void;90pub extern "c" fn mmap(addr: ?*align(page_size) c_void, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: u64) *c_void;
...@@ -114,15 +112,10 @@ pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int;...@@ -114,15 +112,10 @@ pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int;
114pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;112pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
115pub extern "c" fn readlinkat(dirfd: fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;113pub extern "c" fn readlinkat(dirfd: fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize;
116pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;114pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
117pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
118pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
119pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
120pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
121pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;115pub extern "c" fn setreuid(ruid: c_uint, euid: c_uint) c_int;
122pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int;116pub extern "c" fn setregid(rgid: c_uint, egid: c_uint) c_int;
123pub extern "c" fn rmdir(path: [*:0]const u8) c_int;117pub extern "c" fn rmdir(path: [*:0]const u8) c_int;
124pub extern "c" fn getenv(name: [*:0]const u8) ?[*:0]u8;118pub extern "c" fn getenv(name: [*:0]const u8) ?[*:0]u8;
125pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
126pub extern "c" fn sysctl(name: [*]const c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int;119pub extern "c" fn sysctl(name: [*]const c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int;
127pub extern "c" fn sysctlbyname(name: [*:0]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int;120pub extern "c" fn sysctlbyname(name: [*:0]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int;
128pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*usize) c_int;121pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*usize) c_int;
...@@ -133,7 +126,6 @@ pub extern "c" fn uname(buf: *utsname) c_int;...@@ -133,7 +126,6 @@ pub extern "c" fn uname(buf: *utsname) c_int;
133126
134pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int;127pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int;
135pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int;128pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int;
136pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
137pub extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]fd_t) c_int;129pub extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]fd_t) c_int;
138pub extern "c" fn listen(sockfd: fd_t, backlog: c_uint) c_int;130pub extern "c" fn listen(sockfd: fd_t, backlog: c_uint) c_int;
139pub extern "c" fn getsockname(sockfd: fd_t, noalias addr: *sockaddr, noalias addrlen: *socklen_t) c_int;131pub extern "c" fn getsockname(sockfd: fd_t, noalias addr: *sockaddr, noalias addrlen: *socklen_t) c_int;
...@@ -161,12 +153,55 @@ pub extern fn recvfrom(...@@ -161,12 +153,55 @@ pub extern fn recvfrom(
161 noalias addrlen: ?*socklen_t,153 noalias addrlen: ?*socklen_t,
162) isize;154) isize;
163155
156pub usingnamespace switch (builtin.os.tag) {
157 .netbsd => struct {
158 pub const clock_getres = __clock_getres50;
159 pub const clock_gettime = __clock_gettime50;
160 pub const fstat = __fstat50;
161 pub const getdents = __getdents30;
162 pub const getrusage = __getrusage50;
163 pub const gettimeofday = __gettimeofday50;
164 pub const nanosleep = __nanosleep50;
165 pub const sched_yield = __libc_thr_yield;
166 pub const sigaction = __sigaction14;
167 pub const sigaltstack = __sigaltstack14;
168 pub const sigprocmask = __sigprocmask14;
169 pub const stat = __stat50;
170 },
171 .macosx, .ios, .watchos, .tvos => struct {
172 // XXX: close -> close$NOCANCEL
173 // XXX: getdirentries -> _getdirentries64
174 pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
175 pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
176 pub const fstat = @"fstat$INODE64";
177 pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
178 pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
179 pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
180 pub extern "c" fn sched_yield() c_int;
181 pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
182 pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
183 pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
184 pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int;
185 },
186 else => struct {
187 pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
188 pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
189 pub extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int;
190 pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
191 pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
192 pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
193 pub extern "c" fn sched_yield() c_int;
194 pub extern "c" fn sigaction(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
195 pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
196 pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
197 pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int;
198 },
199};
200
164pub extern "c" fn kill(pid: pid_t, sig: c_int) c_int;201pub extern "c" fn kill(pid: pid_t, sig: c_int) c_int;
165pub extern "c" fn getdirentries(fd: fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize;202pub extern "c" fn getdirentries(fd: fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize;
166pub extern "c" fn setgid(ruid: c_uint, euid: c_uint) c_int;203pub extern "c" fn setgid(ruid: c_uint, euid: c_uint) c_int;
167pub extern "c" fn setuid(uid: c_uint) c_int;204pub extern "c" fn setuid(uid: c_uint) c_int;
168pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
169pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
170205
171pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?*c_void;206pub extern "c" fn aligned_alloc(alignment: usize, size: usize) ?*c_void;
172pub extern "c" fn malloc(usize) ?*c_void;207pub extern "c" fn malloc(usize) ?*c_void;
...@@ -174,7 +209,6 @@ pub extern "c" fn realloc(?*c_void, usize) ?*c_void;...@@ -174,7 +209,6 @@ pub extern "c" fn realloc(?*c_void, usize) ?*c_void;
174pub extern "c" fn free(*c_void) void;209pub extern "c" fn free(*c_void) void;
175pub extern "c" fn posix_memalign(memptr: **c_void, alignment: usize, size: usize) c_int;210pub extern "c" fn posix_memalign(memptr: **c_void, alignment: usize, size: usize) c_int;
176211
177// Deprecated
178pub extern "c" fn futimes(fd: fd_t, times: *[2]timeval) c_int;212pub extern "c" fn futimes(fd: fd_t, times: *[2]timeval) c_int;
179pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int;213pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int;
180214
...@@ -230,8 +264,6 @@ pub extern "c" fn dn_expand(...@@ -230,8 +264,6 @@ pub extern "c" fn dn_expand(
230 length: c_int,264 length: c_int,
231) c_int;265) c_int;
232266
233pub extern "c" fn sched_yield() c_int;
234
235pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};267pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{};
236pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int;268pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int;
237pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int;269pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int;
lib/std/c/netbsd.zig+33-11
...@@ -10,36 +10,58 @@ pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize...@@ -10,36 +10,58 @@ pub const dl_iterate_phdr_callback = extern fn (info: *dl_phdr_info, size: usize
10pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;10pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*c_void) c_int;
1111
12pub extern "c" fn __fstat50(fd: fd_t, buf: *Stat) c_int;12pub extern "c" fn __fstat50(fd: fd_t, buf: *Stat) c_int;
13pub extern "c" fn __stat50(path: [*:0]const u8, buf: *Stat) c_int;
13pub extern "c" fn __clock_gettime50(clk_id: c_int, tp: *timespec) c_int;14pub extern "c" fn __clock_gettime50(clk_id: c_int, tp: *timespec) c_int;
14pub extern "c" fn __clock_getres50(clk_id: c_int, tp: *timespec) c_int;15pub extern "c" fn __clock_getres50(clk_id: c_int, tp: *timespec) c_int;
15pub extern "c" fn __getdents30(fd: c_int, buf_ptr: [*]u8, nbytes: usize) c_int;16pub extern "c" fn __getdents30(fd: c_int, buf_ptr: [*]u8, nbytes: usize) c_int;
16pub extern "c" fn __sigaltstack14(ss: ?*stack_t, old_ss: ?*stack_t) c_int;17pub extern "c" fn __sigaltstack14(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
18pub extern "c" fn __nanosleep50(rqtp: *const timespec, rmtp: ?*timespec) c_int;
19pub extern "c" fn __sigaction14(sig: c_int, noalias act: *const Sigaction, noalias oact: ?*Sigaction) c_int;
20pub extern "c" fn __sigprocmask14(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
21pub extern "c" fn __socket30(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
22pub extern "c" fn __gettimeofday50(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
23pub extern "c" fn __getrusage50(who: c_int, usage: *rusage) c_int;
24// libc aliases this as sched_yield
25pub extern "c" fn __libc_thr_yield() c_int;
1726
18pub const pthread_mutex_t = extern struct {27pub const pthread_mutex_t = extern struct {
19 ptm_magic: c_uint = 0x33330003,28 ptm_magic: u32 = 0x33330003,
20 ptm_errorcheck: padded_spin_t = 0,29 ptm_errorcheck: padded_pthread_spin_t = 0,
21 ptm_unused: padded_spin_t = 0,30 ptm_ceiling: padded_pthread_spin_t = 0,
22 ptm_owner: usize = 0,31 ptm_owner: usize = 0,
23 ptm_waiters: ?*u8 = null,32 ptm_waiters: ?*u8 = null,
24 ptm_recursed: c_uint = 0,33 ptm_recursed: u32 = 0,
25 ptm_spare2: ?*c_void = null,34 ptm_spare2: ?*c_void = null,
26};35};
36
27pub const pthread_cond_t = extern struct {37pub const pthread_cond_t = extern struct {
28 ptc_magic: c_uint = 0x55550005,38 ptc_magic: u32 = 0x55550005,
29 ptc_lock: pthread_spin_t = 0,39 ptc_lock: pthread_spin_t = 0,
30 ptc_waiters_first: ?*u8 = null,40 ptc_waiters_first: ?*u8 = null,
31 ptc_waiters_last: ?*u8 = null,41 ptc_waiters_last: ?*u8 = null,
32 ptc_mutex: ?*pthread_mutex_t = null,42 ptc_mutex: ?*pthread_mutex_t = null,
33 ptc_private: ?*c_void = null,43 ptc_private: ?*c_void = null,
34};44};
35const pthread_spin_t = if (builtin.arch == .arm or .arch == .powerpc) c_int else u8;45
36const padded_spin_t = switch (builtin.arch) {46const pthread_spin_t = switch (builtin.arch) {
37 .sparc, .sparcel, .sparcv9, .i386, .x86_64, .le64 => u32,47 .aarch64, .aarch64_be, .aarch64_32 => u8,
38 else => spin_t,48 .mips, .mipsel, .mips64, .mips64el => u32,
49 .powerpc, .powerpc64, .powerpc64le => i32,
50 .i386, .x86_64 => u8,
51 .arm, .armeb, .thumb, .thumbeb => i32,
52 .sparc, .sparcel, .sparcv9 => u8,
53 .riscv32, .riscv64 => u32,
54 else => @compileError("undefined pthread_spin_t for this arch"),
55};
56
57const padded_pthread_spin_t = switch (builtin.arch) {
58 .i386, .x86_64 => u32,
59 .sparc, .sparcel, .sparcv9 => u32,
60 else => pthread_spin_t,
39};61};
4062
41pub const pthread_attr_t = extern struct {63pub const pthread_attr_t = extern struct {
42 pta_magic: u32,64 pta_magic: u32,
43 pta_flags: c_int,65 pta_flags: i32,
44 pta_private: *c_void,66 pta_private: ?*c_void,
45};67};
lib/std/child_process.zig+13-33
...@@ -10,7 +10,7 @@ const windows = os.windows;...@@ -10,7 +10,7 @@ const windows = os.windows;
10const mem = std.mem;10const mem = std.mem;
11const debug = std.debug;11const debug = std.debug;
12const BufMap = std.BufMap;12const BufMap = std.BufMap;
13const Buffer = std.Buffer;13const ArrayListSentineled = std.ArrayListSentineled;
14const builtin = @import("builtin");14const builtin = @import("builtin");
15const Os = builtin.Os;15const Os = builtin.Os;
16const TailQueue = std.TailQueue;16const TailQueue = std.TailQueue;
...@@ -175,29 +175,11 @@ pub const ChildProcess = struct {...@@ -175,29 +175,11 @@ pub const ChildProcess = struct {
175 stderr: []u8,175 stderr: []u8,
176 };176 };
177177
178 /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.178 pub const exec2 = @compileError("deprecated: exec2 is renamed to exec");
179 /// If it succeeds, the caller owns result.stdout and result.stderr memory.
180 /// TODO deprecate in favor of exec2
181 pub fn exec(
182 allocator: *mem.Allocator,
183 argv: []const []const u8,
184 cwd: ?[]const u8,
185 env_map: ?*const BufMap,
186 max_output_bytes: usize,
187 ) !ExecResult {
188 return exec2(.{
189 .allocator = allocator,
190 .argv = argv,
191 .cwd = cwd,
192 .env_map = env_map,
193 .max_output_bytes = max_output_bytes,
194 });
195 }
196179
197 /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.180 /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns.
198 /// If it succeeds, the caller owns result.stdout and result.stderr memory.181 /// If it succeeds, the caller owns result.stdout and result.stderr memory.
199 /// TODO rename to exec182 pub fn exec(args: struct {
200 pub fn exec2(args: struct {
201 allocator: *mem.Allocator,183 allocator: *mem.Allocator,
202 argv: []const []const u8,184 argv: []const []const u8,
203 cwd: ?[]const u8 = null,185 cwd: ?[]const u8 = null,
...@@ -370,7 +352,7 @@ pub const ChildProcess = struct {...@@ -370,7 +352,7 @@ pub const ChildProcess = struct {
370352
371 const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore);353 const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore);
372 const dev_null_fd = if (any_ignore)354 const dev_null_fd = if (any_ignore)
373 os.openC("/dev/null", os.O_RDWR, 0) catch |err| switch (err) {355 os.openZ("/dev/null", os.O_RDWR, 0) catch |err| switch (err) {
374 error.PathAlreadyExists => unreachable,356 error.PathAlreadyExists => unreachable,
375 error.NoSpaceLeft => unreachable,357 error.NoSpaceLeft => unreachable,
376 error.FileTooBig => unreachable,358 error.FileTooBig => unreachable,
...@@ -775,38 +757,36 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1...@@ -775,38 +757,36 @@ fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u1
775}757}
776758
777/// Caller must dealloc.759/// Caller must dealloc.
778/// Guarantees a null byte at result[result.len].760fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 {
779fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![]u8 {761 var buf = try ArrayListSentineled(u8, 0).initSize(allocator, 0);
780 var buf = try Buffer.initSize(allocator, 0);
781 defer buf.deinit();762 defer buf.deinit();
782763 const buf_stream = buf.outStream();
783 var buf_stream = buf.outStream();
784764
785 for (argv) |arg, arg_i| {765 for (argv) |arg, arg_i| {
786 if (arg_i != 0) try buf.appendByte(' ');766 if (arg_i != 0) try buf_stream.writeByte(' ');
787 if (mem.indexOfAny(u8, arg, " \t\n\"") == null) {767 if (mem.indexOfAny(u8, arg, " \t\n\"") == null) {
788 try buf.append(arg);768 try buf_stream.writeAll(arg);
789 continue;769 continue;
790 }770 }
791 try buf.appendByte('"');771 try buf_stream.writeByte('"');
792 var backslash_count: usize = 0;772 var backslash_count: usize = 0;
793 for (arg) |byte| {773 for (arg) |byte| {
794 switch (byte) {774 switch (byte) {
795 '\\' => backslash_count += 1,775 '\\' => backslash_count += 1,
796 '"' => {776 '"' => {
797 try buf_stream.writeByteNTimes('\\', backslash_count * 2 + 1);777 try buf_stream.writeByteNTimes('\\', backslash_count * 2 + 1);
798 try buf.appendByte('"');778 try buf_stream.writeByte('"');
799 backslash_count = 0;779 backslash_count = 0;
800 },780 },
801 else => {781 else => {
802 try buf_stream.writeByteNTimes('\\', backslash_count);782 try buf_stream.writeByteNTimes('\\', backslash_count);
803 try buf.appendByte(byte);783 try buf_stream.writeByte(byte);
804 backslash_count = 0;784 backslash_count = 0;
805 },785 },
806 }786 }
807 }787 }
808 try buf_stream.writeByteNTimes('\\', backslash_count * 2);788 try buf_stream.writeByteNTimes('\\', backslash_count * 2);
809 try buf.appendByte('"');789 try buf_stream.writeByte('"');
810 }790 }
811791
812 return buf.toOwnedSlice();792 return buf.toOwnedSlice();
lib/std/coff.zig+2-2
...@@ -145,7 +145,7 @@ pub const Coff = struct {...@@ -145,7 +145,7 @@ pub const Coff = struct {
145 blk: while (i < debug_dir_entry_count) : (i += 1) {145 blk: while (i < debug_dir_entry_count) : (i += 1) {
146 const debug_dir_entry = try in.readStruct(DebugDirectoryEntry);146 const debug_dir_entry = try in.readStruct(DebugDirectoryEntry);
147 if (debug_dir_entry.type == IMAGE_DEBUG_TYPE_CODEVIEW) {147 if (debug_dir_entry.type == IMAGE_DEBUG_TYPE_CODEVIEW) {
148 for (self.sections.toSlice()) |*section| {148 for (self.sections.span()) |*section| {
149 const section_start = section.header.virtual_address;149 const section_start = section.header.virtual_address;
150 const section_size = section.header.misc.virtual_size;150 const section_size = section.header.misc.virtual_size;
151 const rva = debug_dir_entry.address_of_raw_data;151 const rva = debug_dir_entry.address_of_raw_data;
...@@ -211,7 +211,7 @@ pub const Coff = struct {...@@ -211,7 +211,7 @@ pub const Coff = struct {
211 }211 }
212212
213 pub fn getSection(self: *Coff, comptime name: []const u8) ?*Section {213 pub fn getSection(self: *Coff, comptime name: []const u8) ?*Section {
214 for (self.sections.toSlice()) |*sec| {214 for (self.sections.span()) |*sec| {
215 if (mem.eql(u8, sec.header.name[0..name.len], name)) {215 if (mem.eql(u8, sec.header.name[0..name.len], name)) {
216 return sec;216 return sec;
217 }217 }
lib/std/crypto/gimli.zig+2
...@@ -23,10 +23,12 @@ pub const State = struct {...@@ -23,10 +23,12 @@ pub const State = struct {
2323
24 const Self = @This();24 const Self = @This();
2525
26 /// TODO follow the span() convention instead of having this and `toSliceConst`
26 pub fn toSlice(self: *Self) []u8 {27 pub fn toSlice(self: *Self) []u8 {
27 return mem.sliceAsBytes(self.data[0..]);28 return mem.sliceAsBytes(self.data[0..]);
28 }29 }
2930
31 /// TODO follow the span() convention instead of having this and `toSlice`
30 pub fn toSliceConst(self: *Self) []const u8 {32 pub fn toSliceConst(self: *Self) []const u8 {
31 return mem.sliceAsBytes(self.data[0..]);33 return mem.sliceAsBytes(self.data[0..]);
32 }34 }
lib/std/debug.zig+17-12
...@@ -735,7 +735,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -735,7 +735,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
735 for (present) |_| {735 for (present) |_| {
736 const name_offset = try pdb_stream.inStream().readIntLittle(u32);736 const name_offset = try pdb_stream.inStream().readIntLittle(u32);
737 const name_index = try pdb_stream.inStream().readIntLittle(u32);737 const name_index = try pdb_stream.inStream().readIntLittle(u32);
738 const name = mem.toSlice(u8, @ptrCast([*:0]u8, name_bytes.ptr + name_offset));738 const name = mem.spanZ(@ptrCast([*:0]u8, name_bytes.ptr + name_offset));
739 if (mem.eql(u8, name, "/names")) {739 if (mem.eql(u8, name, "/names")) {
740 break :str_tab_index name_index;740 break :str_tab_index name_index;
741 }741 }
...@@ -1131,7 +1131,7 @@ pub const DebugInfo = struct {...@@ -1131,7 +1131,7 @@ pub const DebugInfo = struct {
1131 const obj_di = try self.allocator.create(ModuleDebugInfo);1131 const obj_di = try self.allocator.create(ModuleDebugInfo);
1132 errdefer self.allocator.destroy(obj_di);1132 errdefer self.allocator.destroy(obj_di);
11331133
1134 const macho_path = mem.toSliceConst(u8, std.c._dyld_get_image_name(i));1134 const macho_path = mem.spanZ(std.c._dyld_get_image_name(i));
1135 obj_di.* = openMachODebugInfo(self.allocator, macho_path) catch |err| switch (err) {1135 obj_di.* = openMachODebugInfo(self.allocator, macho_path) catch |err| switch (err) {
1136 error.FileNotFound => return error.MissingDebugInfo,1136 error.FileNotFound => return error.MissingDebugInfo,
1137 else => return err,1137 else => return err,
...@@ -1254,10 +1254,7 @@ pub const DebugInfo = struct {...@@ -1254,10 +1254,7 @@ pub const DebugInfo = struct {
1254 if (context.address >= seg_start and context.address < seg_end) {1254 if (context.address >= seg_start and context.address < seg_end) {
1255 // Android libc uses NULL instead of an empty string to mark the1255 // Android libc uses NULL instead of an empty string to mark the
1256 // main program1256 // main program
1257 context.name = if (info.dlpi_name) |dlpi_name|1257 context.name = mem.spanZ(info.dlpi_name) orelse "";
1258 mem.toSliceConst(u8, dlpi_name)
1259 else
1260 "";
1261 context.base_address = info.dlpi_addr;1258 context.base_address = info.dlpi_addr;
1262 // Stop the iteration1259 // Stop the iteration
1263 return error.Found;1260 return error.Found;
...@@ -1426,7 +1423,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) {...@@ -1426,7 +1423,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) {
1426 return SymbolInfo{};1423 return SymbolInfo{};
14271424
1428 assert(symbol.ofile.?.n_strx < self.strings.len);1425 assert(symbol.ofile.?.n_strx < self.strings.len);
1429 const o_file_path = mem.toSliceConst(u8, self.strings.ptr + symbol.ofile.?.n_strx);1426 const o_file_path = mem.spanZ(self.strings.ptr + symbol.ofile.?.n_strx);
14301427
1431 // Check if its debug infos are already in the cache1428 // Check if its debug infos are already in the cache
1432 var o_file_di = self.ofiles.getValue(o_file_path) orelse1429 var o_file_di = self.ofiles.getValue(o_file_path) orelse
...@@ -1483,7 +1480,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) {...@@ -1483,7 +1480,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) {
1483 const mod_index = for (self.sect_contribs) |sect_contrib| {1480 const mod_index = for (self.sect_contribs) |sect_contrib| {
1484 if (sect_contrib.Section > self.coff.sections.len) continue;1481 if (sect_contrib.Section > self.coff.sections.len) continue;
1485 // Remember that SectionContribEntry.Section is 1-based.1482 // Remember that SectionContribEntry.Section is 1-based.
1486 coff_section = &self.coff.sections.toSlice()[sect_contrib.Section - 1];1483 coff_section = &self.coff.sections.span()[sect_contrib.Section - 1];
14871484
1488 const vaddr_start = coff_section.header.virtual_address + sect_contrib.Offset;1485 const vaddr_start = coff_section.header.virtual_address + sect_contrib.Offset;
1489 const vaddr_end = vaddr_start + sect_contrib.Size;1486 const vaddr_end = vaddr_start + sect_contrib.Size;
...@@ -1510,7 +1507,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) {...@@ -1510,7 +1507,7 @@ pub const ModuleDebugInfo = switch (builtin.os.tag) {
1510 const vaddr_start = coff_section.header.virtual_address + proc_sym.CodeOffset;1507 const vaddr_start = coff_section.header.virtual_address + proc_sym.CodeOffset;
1511 const vaddr_end = vaddr_start + proc_sym.CodeSize;1508 const vaddr_end = vaddr_start + proc_sym.CodeSize;
1512 if (relocated_address >= vaddr_start and relocated_address < vaddr_end) {1509 if (relocated_address >= vaddr_start and relocated_address < vaddr_end) {
1513 break mem.toSliceConst(u8, @ptrCast([*:0]u8, proc_sym) + @sizeOf(pdb.ProcSym));1510 break mem.spanZ(@ptrCast([*:0]u8, proc_sym) + @sizeOf(pdb.ProcSym));
1514 }1511 }
1515 },1512 },
1516 else => {},1513 else => {},
...@@ -1669,7 +1666,11 @@ fn getDebugInfoAllocator() *mem.Allocator {...@@ -1669,7 +1666,11 @@ fn getDebugInfoAllocator() *mem.Allocator {
1669}1666}
16701667
1671/// Whether or not the current target can print useful debug information when a segfault occurs.1668/// Whether or not the current target can print useful debug information when a segfault occurs.
1672pub const have_segfault_handling_support = builtin.os.tag == .linux or builtin.os.tag == .windows;1669pub const have_segfault_handling_support = switch (builtin.os.tag) {
1670 .linux, .netbsd => true,
1671 .windows => true,
1672 else => false,
1673};
1673pub const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler"))1674pub const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler"))
1674 root.enable_segfault_handler1675 root.enable_segfault_handler
1675else1676else
...@@ -1721,13 +1722,17 @@ fn resetSegfaultHandler() void {...@@ -1721,13 +1722,17 @@ fn resetSegfaultHandler() void {
1721 os.sigaction(os.SIGBUS, &act, null);1722 os.sigaction(os.SIGBUS, &act, null);
1722}1723}
17231724
1724fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: *const c_void) callconv(.C) noreturn {1725fn handleSegfaultLinux(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) noreturn {
1725 // Reset to the default handler so that if a segfault happens in this handler it will crash1726 // Reset to the default handler so that if a segfault happens in this handler it will crash
1726 // the process. Also when this handler returns, the original instruction will be repeated1727 // the process. Also when this handler returns, the original instruction will be repeated
1727 // and the resulting segfault will crash the process rather than continually dump stack traces.1728 // and the resulting segfault will crash the process rather than continually dump stack traces.
1728 resetSegfaultHandler();1729 resetSegfaultHandler();
17291730
1730 const addr = @ptrToInt(info.fields.sigfault.addr);1731 const addr = switch (builtin.os.tag) {
1732 .linux => @ptrToInt(info.fields.sigfault.addr),
1733 .netbsd => @ptrToInt(info.info.reason.fault.addr),
1734 else => unreachable,
1735 };
1731 switch (sig) {1736 switch (sig) {
1732 os.SIGSEGV => std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr}),1737 os.SIGSEGV => std.debug.warn("Segmentation fault at address 0x{x}\n", .{addr}),
1733 os.SIGILL => std.debug.warn("Illegal instruction at address 0x{x}\n", .{addr}),1738 os.SIGILL => std.debug.warn("Illegal instruction at address 0x{x}\n", .{addr}),
lib/std/dwarf.zig+7-7
...@@ -82,7 +82,7 @@ const Die = struct {...@@ -82,7 +82,7 @@ const Die = struct {
82 };82 };
8383
84 fn getAttr(self: *const Die, id: u64) ?*const FormValue {84 fn getAttr(self: *const Die, id: u64) ?*const FormValue {
85 for (self.attrs.toSliceConst()) |*attr| {85 for (self.attrs.span()) |*attr| {
86 if (attr.id == id) return &attr.value;86 if (attr.id == id) return &attr.value;
87 }87 }
88 return null;88 return null;
...@@ -375,7 +375,7 @@ fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64...@@ -375,7 +375,7 @@ fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64
375}375}
376376
377fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry {377fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry {
378 for (abbrev_table.toSliceConst()) |*table_entry| {378 for (abbrev_table.span()) |*table_entry| {
379 if (table_entry.abbrev_code == abbrev_code) return table_entry;379 if (table_entry.abbrev_code == abbrev_code) return table_entry;
380 }380 }
381 return null;381 return null;
...@@ -399,7 +399,7 @@ pub const DwarfInfo = struct {...@@ -399,7 +399,7 @@ pub const DwarfInfo = struct {
399 }399 }
400400
401 fn getSymbolName(di: *DwarfInfo, address: u64) ?[]const u8 {401 fn getSymbolName(di: *DwarfInfo, address: u64) ?[]const u8 {
402 for (di.func_list.toSliceConst()) |*func| {402 for (di.func_list.span()) |*func| {
403 if (func.pc_range) |range| {403 if (func.pc_range) |range| {
404 if (address >= range.start and address < range.end) {404 if (address >= range.start and address < range.end) {
405 return func.name;405 return func.name;
...@@ -588,7 +588,7 @@ pub const DwarfInfo = struct {...@@ -588,7 +588,7 @@ pub const DwarfInfo = struct {
588 }588 }
589589
590 fn findCompileUnit(di: *DwarfInfo, target_address: u64) !*const CompileUnit {590 fn findCompileUnit(di: *DwarfInfo, target_address: u64) !*const CompileUnit {
591 for (di.compile_unit_list.toSlice()) |*compile_unit| {591 for (di.compile_unit_list.span()) |*compile_unit| {
592 if (compile_unit.pc_range) |range| {592 if (compile_unit.pc_range) |range| {
593 if (target_address >= range.start and target_address < range.end) return compile_unit;593 if (target_address >= range.start and target_address < range.end) return compile_unit;
594 }594 }
...@@ -636,7 +636,7 @@ pub const DwarfInfo = struct {...@@ -636,7 +636,7 @@ pub const DwarfInfo = struct {
636 /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found,636 /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found,
637 /// seeks in the stream and parses it.637 /// seeks in the stream and parses it.
638 fn getAbbrevTable(di: *DwarfInfo, abbrev_offset: u64) !*const AbbrevTable {638 fn getAbbrevTable(di: *DwarfInfo, abbrev_offset: u64) !*const AbbrevTable {
639 for (di.abbrev_table_list.toSlice()) |*header| {639 for (di.abbrev_table_list.span()) |*header| {
640 if (header.offset == abbrev_offset) {640 if (header.offset == abbrev_offset) {
641 return &header.table;641 return &header.table;
642 }642 }
...@@ -690,7 +690,7 @@ pub const DwarfInfo = struct {...@@ -690,7 +690,7 @@ pub const DwarfInfo = struct {
690 .attrs = ArrayList(Die.Attr).init(di.allocator()),690 .attrs = ArrayList(Die.Attr).init(di.allocator()),
691 };691 };
692 try result.attrs.resize(table_entry.attrs.len);692 try result.attrs.resize(table_entry.attrs.len);
693 for (table_entry.attrs.toSliceConst()) |attr, i| {693 for (table_entry.attrs.span()) |attr, i| {
694 result.attrs.items[i] = Die.Attr{694 result.attrs.items[i] = Die.Attr{
695 .id = attr.attr_id,695 .id = attr.attr_id,
696 .value = try parseFormValue(di.allocator(), in_stream, attr.form_id, is_64),696 .value = try parseFormValue(di.allocator(), in_stream, attr.form_id, is_64),
...@@ -757,7 +757,7 @@ pub const DwarfInfo = struct {...@@ -757,7 +757,7 @@ pub const DwarfInfo = struct {
757 }757 }
758758
759 var file_entries = ArrayList(FileEntry).init(di.allocator());759 var file_entries = ArrayList(FileEntry).init(di.allocator());
760 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);760 var prog = LineNumberProgram.init(default_is_stmt, include_directories.span(), &file_entries, target_address);
761761
762 while (true) {762 while (true) {
763 const file_name = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));763 const file_name = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));
lib/std/dynamic_library.zig+13-7
...@@ -254,9 +254,11 @@ pub const ElfDynLib = struct {...@@ -254,9 +254,11 @@ pub const ElfDynLib = struct {
254 };254 };
255 }255 }
256256
257 pub const openC = @compileError("deprecated: renamed to openZ");
258
257 /// Trusts the file. Malicious file will be able to execute arbitrary code.259 /// Trusts the file. Malicious file will be able to execute arbitrary code.
258 pub fn openC(path_c: [*:0]const u8) !ElfDynLib {260 pub fn openZ(path_c: [*:0]const u8) !ElfDynLib {
259 return open(mem.toSlice(u8, path_c));261 return open(mem.spanZ(path_c));
260 }262 }
261263
262 /// Trusts the file264 /// Trusts the file
...@@ -285,7 +287,7 @@ pub const ElfDynLib = struct {...@@ -285,7 +287,7 @@ pub const ElfDynLib = struct {
285 if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue;287 if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue;
286 if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue;288 if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue;
287 if (0 == self.syms[i].st_shndx) continue;289 if (0 == self.syms[i].st_shndx) continue;
288 if (!mem.eql(u8, name, mem.toSliceConst(u8, self.strings + self.syms[i].st_name))) continue;290 if (!mem.eql(u8, name, mem.spanZ(self.strings + self.syms[i].st_name))) continue;
289 if (maybe_versym) |versym| {291 if (maybe_versym) |versym| {
290 if (!checkver(self.verdef.?, versym[i], vername, self.strings))292 if (!checkver(self.verdef.?, versym[i], vername, self.strings))
291 continue;293 continue;
...@@ -316,7 +318,7 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [...@@ -316,7 +318,7 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [
316 def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next);318 def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next);
317 }319 }
318 const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux);320 const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux);
319 return mem.eql(u8, vername, mem.toSliceConst(u8, strings + aux.vda_name));321 return mem.eql(u8, vername, mem.spanZ(strings + aux.vda_name));
320}322}
321323
322pub const WindowsDynLib = struct {324pub const WindowsDynLib = struct {
...@@ -329,7 +331,9 @@ pub const WindowsDynLib = struct {...@@ -329,7 +331,9 @@ pub const WindowsDynLib = struct {
329 return openW(&path_w);331 return openW(&path_w);
330 }332 }
331333
332 pub fn openC(path_c: [*:0]const u8) !WindowsDynLib {334 pub const openC = @compileError("deprecated: renamed to openZ");
335
336 pub fn openZ(path_c: [*:0]const u8) !WindowsDynLib {
333 const path_w = try windows.cStrToPrefixedFileW(path_c);337 const path_w = try windows.cStrToPrefixedFileW(path_c);
334 return openW(&path_w);338 return openW(&path_w);
335 }339 }
...@@ -362,10 +366,12 @@ pub const DlDynlib = struct {...@@ -362,10 +366,12 @@ pub const DlDynlib = struct {
362366
363 pub fn open(path: []const u8) !DlDynlib {367 pub fn open(path: []const u8) !DlDynlib {
364 const path_c = try os.toPosixPath(path);368 const path_c = try os.toPosixPath(path);
365 return openC(&path_c);369 return openZ(&path_c);
366 }370 }
367371
368 pub fn openC(path_c: [*:0]const u8) !DlDynlib {372 pub const openC = @compileError("deprecated: renamed to openZ");
373
374 pub fn openZ(path_c: [*:0]const u8) !DlDynlib {
369 return DlDynlib{375 return DlDynlib{
370 .handle = system.dlopen(path_c, system.RTLD_LAZY) orelse {376 .handle = system.dlopen(path_c, system.RTLD_LAZY) orelse {
371 return error.FileNotFound;377 return error.FileNotFound;
lib/std/event/loop.zig+2-2
...@@ -1096,10 +1096,10 @@ pub const Loop = struct {...@@ -1096,10 +1096,10 @@ pub const Loop = struct {
1096 msg.result = noasync os.preadv(msg.fd, msg.iov, msg.offset);1096 msg.result = noasync os.preadv(msg.fd, msg.iov, msg.offset);
1097 },1097 },
1098 .open => |*msg| {1098 .open => |*msg| {
1099 msg.result = noasync os.openC(msg.path, msg.flags, msg.mode);1099 msg.result = noasync os.openZ(msg.path, msg.flags, msg.mode);
1100 },1100 },
1101 .openat => |*msg| {1101 .openat => |*msg| {
1102 msg.result = noasync os.openatC(msg.fd, msg.path, msg.flags, msg.mode);1102 msg.result = noasync os.openatZ(msg.fd, msg.path, msg.flags, msg.mode);
1103 },1103 },
1104 .faccessat => |*msg| {1104 .faccessat => |*msg| {
1105 msg.result = noasync os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags);1105 msg.result = noasync os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags);
lib/std/fifo.zig+50-25
...@@ -160,7 +160,7 @@ pub fn LinearFifo(...@@ -160,7 +160,7 @@ pub fn LinearFifo(
160 return self.readableSliceMut(offset);160 return self.readableSliceMut(offset);
161 }161 }
162162
163 /// Discard first `count` bytes of readable data163 /// Discard first `count` items in the fifo
164 pub fn discard(self: *Self, count: usize) void {164 pub fn discard(self: *Self, count: usize) void {
165 assert(count <= self.count);165 assert(count <= self.count);
166 { // set old range to undefined. Note: may be wrapped around166 { // set old range to undefined. Note: may be wrapped around
...@@ -199,7 +199,7 @@ pub fn LinearFifo(...@@ -199,7 +199,7 @@ pub fn LinearFifo(
199 return c;199 return c;
200 }200 }
201201
202 /// Read data from the fifo into `dst`, returns number of bytes copied.202 /// Read data from the fifo into `dst`, returns number of items copied.
203 pub fn read(self: *Self, dst: []T) usize {203 pub fn read(self: *Self, dst: []T) usize {
204 var dst_left = dst;204 var dst_left = dst;
205205
...@@ -215,7 +215,17 @@ pub fn LinearFifo(...@@ -215,7 +215,17 @@ pub fn LinearFifo(
215 return dst.len - dst_left.len;215 return dst.len - dst_left.len;
216 }216 }
217217
218 /// Returns number of bytes available in fifo218 /// Same as `read` except it returns an error union
219 /// The purpose of this function existing is to match `std.io.InStream` API.
220 fn readFn(self: *Self, dest: []u8) error{}!usize {
221 return self.read(dest);
222 }
223
224 pub fn inStream(self: *Self) std.io.InStream(*Self, error{}, readFn) {
225 return .{ .context = self };
226 }
227
228 /// Returns number of items available in fifo
219 pub fn writableLength(self: Self) usize {229 pub fn writableLength(self: Self) usize {
220 return self.buf.len - self.count;230 return self.buf.len - self.count;
221 }231 }
...@@ -233,9 +243,9 @@ pub fn LinearFifo(...@@ -233,9 +243,9 @@ pub fn LinearFifo(
233 }243 }
234 }244 }
235245
236 /// Returns a writable buffer of at least `size` bytes, allocating memory as needed.246 /// Returns a writable buffer of at least `size` items, allocating memory as needed.
237 /// Use `fifo.update` once you've written data to it.247 /// Use `fifo.update` once you've written data to it.
238 pub fn writeableWithSize(self: *Self, size: usize) ![]T {248 pub fn writableWithSize(self: *Self, size: usize) ![]T {
239 try self.ensureUnusedCapacity(size);249 try self.ensureUnusedCapacity(size);
240250
241 // try to avoid realigning buffer251 // try to avoid realigning buffer
...@@ -247,7 +257,7 @@ pub fn LinearFifo(...@@ -247,7 +257,7 @@ pub fn LinearFifo(
247 return slice;257 return slice;
248 }258 }
249259
250 /// Update the tail location of the buffer (usually follows use of writable/writeableWithSize)260 /// Update the tail location of the buffer (usually follows use of writable/writableWithSize)
251 pub fn update(self: *Self, count: usize) void {261 pub fn update(self: *Self, count: usize) void {
252 assert(self.count + count <= self.buf.len);262 assert(self.count + count <= self.buf.len);
253 self.count += count;263 self.count += count;
...@@ -279,7 +289,7 @@ pub fn LinearFifo(...@@ -279,7 +289,7 @@ pub fn LinearFifo(
279 } else {289 } else {
280 tail %= self.buf.len;290 tail %= self.buf.len;
281 }291 }
282 self.buf[tail] = byte;292 self.buf[tail] = item;
283 self.update(1);293 self.update(1);
284 }294 }
285295
...@@ -291,24 +301,16 @@ pub fn LinearFifo(...@@ -291,24 +301,16 @@ pub fn LinearFifo(
291 return self.writeAssumeCapacity(src);301 return self.writeAssumeCapacity(src);
292 }302 }
293303
294 pub usingnamespace if (T == u8)304 /// Same as `write` except it returns the number of bytes written, which is always the same
295 struct {305 /// as `bytes.len`. The purpose of this function existing is to match `std.io.OutStream` API.
296 const OutStream = std.io.OutStream(*Self, Error, appendWrite);306 fn appendWrite(self: *Self, bytes: []const u8) error{OutOfMemory}!usize {
297 const Error = error{OutOfMemory};307 try self.write(bytes);
298308 return bytes.len;
299 /// Same as `write` except it returns the number of bytes written, which is always the same309 }
300 /// as `bytes.len`. The purpose of this function existing is to match `std.io.OutStream` API.
301 pub fn appendWrite(fifo: *Self, bytes: []const u8) Error!usize {
302 try fifo.write(bytes);
303 return bytes.len;
304 }
305310
306 pub fn outStream(self: *Self) OutStream {311 pub fn outStream(self: *Self) std.io.OutStream(*Self, error{OutOfMemory}, appendWrite) {
307 return .{ .context = self };312 return .{ .context = self };
308 }313 }
309 }
310 else
311 struct {};
312314
313 /// Make `count` items available before the current read location315 /// Make `count` items available before the current read location
314 fn rewind(self: *Self, count: usize) void {316 fn rewind(self: *Self, count: usize) void {
...@@ -395,7 +397,7 @@ test "LinearFifo(u8, .Dynamic)" {...@@ -395,7 +397,7 @@ test "LinearFifo(u8, .Dynamic)" {
395 }397 }
396398
397 {399 {
398 const buf = try fifo.writeableWithSize(12);400 const buf = try fifo.writableWithSize(12);
399 testing.expectEqual(@as(usize, 12), buf.len);401 testing.expectEqual(@as(usize, 12), buf.len);
400 var i: u8 = 0;402 var i: u8 = 0;
401 while (i < 10) : (i += 1) {403 while (i < 10) : (i += 1) {
...@@ -422,6 +424,15 @@ test "LinearFifo(u8, .Dynamic)" {...@@ -422,6 +424,15 @@ test "LinearFifo(u8, .Dynamic)" {
422 testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);424 testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);
423 testing.expectEqual(@as(usize, 0), fifo.readableLength());425 testing.expectEqual(@as(usize, 0), fifo.readableLength());
424 }426 }
427
428 {
429 try fifo.outStream().writeAll("This is a test");
430 var result: [30]u8 = undefined;
431 testing.expectEqualSlices(u8, "This", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?);
432 testing.expectEqualSlices(u8, "is", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?);
433 testing.expectEqualSlices(u8, "a", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?);
434 testing.expectEqualSlices(u8, "test", (try fifo.inStream().readUntilDelimiterOrEof(&result, ' ')).?);
435 }
425}436}
426437
427test "LinearFifo" {438test "LinearFifo" {
...@@ -445,6 +456,20 @@ test "LinearFifo" {...@@ -445,6 +456,20 @@ test "LinearFifo" {
445 testing.expectEqual(@as(T, 1), try fifo.readItem());456 testing.expectEqual(@as(T, 1), try fifo.readItem());
446 testing.expectEqual(@as(T, 0), try fifo.readItem());457 testing.expectEqual(@as(T, 0), try fifo.readItem());
447 testing.expectEqual(@as(T, 1), try fifo.readItem());458 testing.expectEqual(@as(T, 1), try fifo.readItem());
459 testing.expectEqual(@as(usize, 0), fifo.readableLength());
460 }
461
462 {
463 try fifo.writeItem(1);
464 try fifo.writeItem(1);
465 try fifo.writeItem(1);
466 testing.expectEqual(@as(usize, 3), fifo.readableLength());
467 }
468
469 {
470 var readBuf: [3]T = undefined;
471 const n = fifo.read(&readBuf);
472 testing.expectEqual(@as(usize, 3), n); // NOTE: It should be the number of items.
448 }473 }
449 }474 }
450 }475 }
lib/std/fmt/parse_float.zig+51-71
...@@ -30,6 +30,7 @@...@@ -30,6 +30,7 @@
30// - Does not handle denormals30// - Does not handle denormals
3131
32const std = @import("../std.zig");32const std = @import("../std.zig");
33const ascii = std.ascii;
3334
34const max_digits = 25;35const max_digits = 25;
3536
...@@ -190,14 +191,6 @@ const ParseResult = enum {...@@ -190,14 +191,6 @@ const ParseResult = enum {
190 MinusInf,191 MinusInf,
191};192};
192193
193inline fn isDigit(c: u8) bool {
194 return c >= '0' and c <= '9';
195}
196
197inline fn isSpace(c: u8) bool {
198 return (c >= 0x09 and c <= 0x13) or c == 0x20;
199}
200
201fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {194fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {
202 var digit_index: usize = 0;195 var digit_index: usize = 0;
203 var negative = false;196 var negative = false;
...@@ -207,52 +200,49 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {...@@ -207,52 +200,49 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {
207 var state = State.MaybeSign;200 var state = State.MaybeSign;
208201
209 var i: usize = 0;202 var i: usize = 0;
210 loop: while (i < s.len) {203 while (i < s.len) {
211 const c = s[i];204 const c = s[i];
212205
213 switch (state) {206 switch (state) {
214 State.MaybeSign => {207 .MaybeSign => {
215 state = State.LeadingMantissaZeros;208 state = .LeadingMantissaZeros;
216209
217 if (c == '+') {210 if (c == '+') {
218 i += 1;211 i += 1;
219 } else if (c == '-') {212 } else if (c == '-') {
220 n.negative = true;213 n.negative = true;
221 i += 1;214 i += 1;
222 } else if (isDigit(c) or c == '.') {215 } else if (ascii.isDigit(c) or c == '.') {
223 // continue216 // continue
224 } else {217 } else {
225 return error.InvalidCharacter;218 return error.InvalidCharacter;
226 }219 }
227 },220 },
228221 .LeadingMantissaZeros => {
229 State.LeadingMantissaZeros => {
230 if (c == '0') {222 if (c == '0') {
231 i += 1;223 i += 1;
232 } else if (c == '.') {224 } else if (c == '.') {
233 i += 1;225 i += 1;
234 state = State.LeadingFractionalZeros;226 state = .LeadingFractionalZeros;
235 } else {227 } else {
236 state = State.MantissaIntegral;228 state = .MantissaIntegral;
237 }229 }
238 },230 },
239231 .LeadingFractionalZeros => {
240 State.LeadingFractionalZeros => {
241 if (c == '0') {232 if (c == '0') {
242 i += 1;233 i += 1;
243 if (n.exponent > std.math.minInt(i32)) {234 if (n.exponent > std.math.minInt(i32)) {
244 n.exponent -= 1;235 n.exponent -= 1;
245 }236 }
246 } else {237 } else {
247 state = State.MantissaFractional;238 state = .MantissaFractional;
248 }239 }
249 },240 },
250241 .MantissaIntegral => {
251 State.MantissaIntegral => {242 if (ascii.isDigit(c)) {
252 if (isDigit(c)) {
253 if (digit_index < max_digits) {243 if (digit_index < max_digits) {
254 n.mantissa *%= 10;244 n.mantissa *%= 10;
255 n.mantissa += s[i] - '0';245 n.mantissa += c - '0';
256 digit_index += 1;246 digit_index += 1;
257 } else if (n.exponent < std.math.maxInt(i32)) {247 } else if (n.exponent < std.math.maxInt(i32)) {
258 n.exponent += 1;248 n.exponent += 1;
...@@ -261,14 +251,13 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {...@@ -261,14 +251,13 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {
261 i += 1;251 i += 1;
262 } else if (c == '.') {252 } else if (c == '.') {
263 i += 1;253 i += 1;
264 state = State.MantissaFractional;254 state = .MantissaFractional;
265 } else {255 } else {
266 state = State.MantissaFractional;256 state = .MantissaFractional;
267 }257 }
268 },258 },
269259 .MantissaFractional => {
270 State.MantissaFractional => {260 if (ascii.isDigit(c)) {
271 if (isDigit(c)) {
272 if (digit_index < max_digits) {261 if (digit_index < max_digits) {
273 n.mantissa *%= 10;262 n.mantissa *%= 10;
274 n.mantissa += c - '0';263 n.mantissa += c - '0';
...@@ -279,13 +268,12 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {...@@ -279,13 +268,12 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {
279 i += 1;268 i += 1;
280 } else if (c == 'e' or c == 'E') {269 } else if (c == 'e' or c == 'E') {
281 i += 1;270 i += 1;
282 state = State.ExponentSign;271 state = .ExponentSign;
283 } else {272 } else {
284 state = State.ExponentSign;273 state = .ExponentSign;
285 }274 }
286 },275 },
287276 .ExponentSign => {
288 State.ExponentSign => {
289 if (c == '+') {277 if (c == '+') {
290 i += 1;278 i += 1;
291 } else if (c == '-') {279 } else if (c == '-') {
...@@ -293,20 +281,18 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {...@@ -293,20 +281,18 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {
293 i += 1;281 i += 1;
294 }282 }
295283
296 state = State.LeadingExponentZeros;284 state = .LeadingExponentZeros;
297 },285 },
298286 .LeadingExponentZeros => {
299 State.LeadingExponentZeros => {
300 if (c == '0') {287 if (c == '0') {
301 i += 1;288 i += 1;
302 } else {289 } else {
303 state = State.Exponent;290 state = .Exponent;
304 }291 }
305 },292 },
306293 .Exponent => {
307 State.Exponent => {294 if (ascii.isDigit(c)) {
308 if (isDigit(c)) {295 if (exponent < std.math.maxInt(i32) / 10) {
309 if (exponent < std.math.maxInt(i32)) {
310 exponent *= 10;296 exponent *= 10;
311 exponent += @intCast(i32, c - '0');297 exponent += @intCast(i32, c - '0');
312 }298 }
...@@ -323,29 +309,21 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {...@@ -323,29 +309,21 @@ fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult {
323 n.exponent += exponent;309 n.exponent += exponent;
324310
325 if (n.mantissa == 0) {311 if (n.mantissa == 0) {
326 return if (n.negative) ParseResult.MinusZero else ParseResult.PlusZero;312 return if (n.negative) .MinusZero else .PlusZero;
327 } else if (n.exponent > 309) {313 } else if (n.exponent > 309) {
328 return if (n.negative) ParseResult.MinusInf else ParseResult.PlusInf;314 return if (n.negative) .MinusInf else .PlusInf;
329 } else if (n.exponent < -328) {315 } else if (n.exponent < -328) {
330 return if (n.negative) ParseResult.MinusZero else ParseResult.PlusZero;316 return if (n.negative) .MinusZero else .PlusZero;
331 }317 }
332318
333 return ParseResult.Ok;319 return .Ok;
334}
335
336inline fn isLower(c: u8) bool {
337 return c -% 'a' < 26;
338}
339
340inline fn toUpper(c: u8) u8 {
341 return if (isLower(c)) (c & 0x5f) else c;
342}320}
343321
344fn caseInEql(a: []const u8, b: []const u8) bool {322fn caseInEql(a: []const u8, b: []const u8) bool {
345 if (a.len != b.len) return false;323 if (a.len != b.len) return false;
346324
347 for (a) |_, i| {325 for (a) |_, i| {
348 if (toUpper(a[i]) != toUpper(b[i])) {326 if (ascii.toUpper(a[i]) != ascii.toUpper(b[i])) {
349 return false;327 return false;
350 }328 }
351 }329 }
...@@ -373,11 +351,11 @@ pub fn parseFloat(comptime T: type, s: []const u8) !T {...@@ -373,11 +351,11 @@ pub fn parseFloat(comptime T: type, s: []const u8) !T {
373 };351 };
374352
375 return switch (try parseRepr(s, &r)) {353 return switch (try parseRepr(s, &r)) {
376 ParseResult.Ok => convertRepr(T, r),354 .Ok => convertRepr(T, r),
377 ParseResult.PlusZero => 0.0,355 .PlusZero => 0.0,
378 ParseResult.MinusZero => -@as(T, 0.0),356 .MinusZero => -@as(T, 0.0),
379 ParseResult.PlusInf => std.math.inf(T),357 .PlusInf => std.math.inf(T),
380 ParseResult.MinusInf => -std.math.inf(T),358 .MinusInf => -std.math.inf(T),
381 };359 };
382}360}
383361
...@@ -396,26 +374,28 @@ test "fmt.parseFloat" {...@@ -396,26 +374,28 @@ test "fmt.parseFloat" {
396 testing.expectError(error.InvalidCharacter, parseFloat(T, "1abc"));374 testing.expectError(error.InvalidCharacter, parseFloat(T, "1abc"));
397375
398 expectEqual(try parseFloat(T, "0"), 0.0);376 expectEqual(try parseFloat(T, "0"), 0.0);
399 expectEqual((try parseFloat(T, "0")), 0.0);377 expectEqual(try parseFloat(T, "0"), 0.0);
400 expectEqual((try parseFloat(T, "+0")), 0.0);378 expectEqual(try parseFloat(T, "+0"), 0.0);
401 expectEqual((try parseFloat(T, "-0")), 0.0);379 expectEqual(try parseFloat(T, "-0"), 0.0);
402380
403 expectEqual((try parseFloat(T, "0e0")), 0);381 expectEqual(try parseFloat(T, "0e0"), 0);
404 expectEqual((try parseFloat(T, "2e3")), 2000.0);382 expectEqual(try parseFloat(T, "2e3"), 2000.0);
405 expectEqual((try parseFloat(T, "1e0")), 1.0);383 expectEqual(try parseFloat(T, "1e0"), 1.0);
406 expectEqual((try parseFloat(T, "-2e3")), -2000.0);384 expectEqual(try parseFloat(T, "-2e3"), -2000.0);
407 expectEqual((try parseFloat(T, "-1e0")), -1.0);385 expectEqual(try parseFloat(T, "-1e0"), -1.0);
408 expectEqual((try parseFloat(T, "1.234e3")), 1234);386 expectEqual(try parseFloat(T, "1.234e3"), 1234);
409387
410 expect(approxEq(T, try parseFloat(T, "3.141"), 3.141, epsilon));388 expect(approxEq(T, try parseFloat(T, "3.141"), 3.141, epsilon));
411 expect(approxEq(T, try parseFloat(T, "-3.141"), -3.141, epsilon));389 expect(approxEq(T, try parseFloat(T, "-3.141"), -3.141, epsilon));
412390
413 expectEqual((try parseFloat(T, "1e-700")), 0);391 expectEqual(try parseFloat(T, "1e-700"), 0);
414 expectEqual((try parseFloat(T, "1e+700")), std.math.inf(T));392 expectEqual(try parseFloat(T, "1e+700"), std.math.inf(T));
415393
416 expectEqual(@bitCast(Z, try parseFloat(T, "nAn")), @bitCast(Z, std.math.nan(T)));394 expectEqual(@bitCast(Z, try parseFloat(T, "nAn")), @bitCast(Z, std.math.nan(T)));
417 expectEqual((try parseFloat(T, "inF")), std.math.inf(T));395 expectEqual(try parseFloat(T, "inF"), std.math.inf(T));
418 expectEqual((try parseFloat(T, "-INF")), -std.math.inf(T));396 expectEqual(try parseFloat(T, "-INF"), -std.math.inf(T));
397
398 expectEqual(try parseFloat(T, "0.4e0066999999999999999999999999999999999999999999999999999"), std.math.inf(T));
419399
420 if (T != f16) {400 if (T != f16) {
421 expect(approxEq(T, try parseFloat(T, "1e-2"), 0.01, epsilon));401 expect(approxEq(T, try parseFloat(T, "1e-2"), 0.01, epsilon));
lib/std/fs.zig+121-98
...@@ -11,13 +11,18 @@ const math = std.math;...@@ -11,13 +11,18 @@ const math = std.math;
11pub const path = @import("fs/path.zig");11pub const path = @import("fs/path.zig");
12pub const File = @import("fs/file.zig").File;12pub const File = @import("fs/file.zig").File;
1313
14// TODO audit these APIs with respect to Dir and absolute paths
15
14pub const symLink = os.symlink;16pub const symLink = os.symlink;
15pub const symLinkC = os.symlinkC;17pub const symLinkZ = os.symlinkZ;
18pub const symLinkC = @compileError("deprecated: renamed to symlinkZ");
16pub const rename = os.rename;19pub const rename = os.rename;
17pub const renameC = os.renameC;20pub const renameZ = os.renameZ;
21pub const renameC = @compileError("deprecated: renamed to renameZ");
18pub const renameW = os.renameW;22pub const renameW = os.renameW;
19pub const realpath = os.realpath;23pub const realpath = os.realpath;
20pub const realpathC = os.realpathC;24pub const realpathZ = os.realpathZ;
25pub const realpathC = @compileError("deprecated: renamed to realpathZ");
21pub const realpathW = os.realpathW;26pub const realpathW = os.realpathW;
2227
23pub const getAppDataDir = @import("fs/get_app_data_dir.zig").getAppDataDir;28pub const getAppDataDir = @import("fs/get_app_data_dir.zig").getAppDataDir;
...@@ -120,7 +125,7 @@ pub const AtomicFile = struct {...@@ -120,7 +125,7 @@ pub const AtomicFile = struct {
120 file: File,125 file: File,
121 // TODO either replace this with rand_buf or use []u16 on Windows126 // TODO either replace this with rand_buf or use []u16 on Windows
122 tmp_path_buf: [TMP_PATH_LEN:0]u8,127 tmp_path_buf: [TMP_PATH_LEN:0]u8,
123 dest_path: []const u8,128 dest_basename: []const u8,
124 file_open: bool,129 file_open: bool,
125 file_exists: bool,130 file_exists: bool,
126 close_dir_on_deinit: bool,131 close_dir_on_deinit: bool,
...@@ -131,17 +136,23 @@ pub const AtomicFile = struct {...@@ -131,17 +136,23 @@ pub const AtomicFile = struct {
131 const RANDOM_BYTES = 12;136 const RANDOM_BYTES = 12;
132 const TMP_PATH_LEN = base64.Base64Encoder.calcSize(RANDOM_BYTES);137 const TMP_PATH_LEN = base64.Base64Encoder.calcSize(RANDOM_BYTES);
133138
134 /// TODO rename this. Callers should go through Dir API139 /// Note that the `Dir.atomicFile` API may be more handy than this lower-level function.
135 pub fn init2(dest_path: []const u8, mode: File.Mode, dir: Dir, close_dir_on_deinit: bool) InitError!AtomicFile {140 pub fn init(
141 dest_basename: []const u8,
142 mode: File.Mode,
143 dir: Dir,
144 close_dir_on_deinit: bool,
145 ) InitError!AtomicFile {
136 var rand_buf: [RANDOM_BYTES]u8 = undefined;146 var rand_buf: [RANDOM_BYTES]u8 = undefined;
137 var tmp_path_buf: [TMP_PATH_LEN:0]u8 = undefined;147 var tmp_path_buf: [TMP_PATH_LEN:0]u8 = undefined;
148 // TODO: should be able to use TMP_PATH_LEN here.
138 tmp_path_buf[base64.Base64Encoder.calcSize(RANDOM_BYTES)] = 0;149 tmp_path_buf[base64.Base64Encoder.calcSize(RANDOM_BYTES)] = 0;
139150
140 while (true) {151 while (true) {
141 try crypto.randomBytes(rand_buf[0..]);152 try crypto.randomBytes(rand_buf[0..]);
142 base64_encoder.encode(&tmp_path_buf, &rand_buf);153 base64_encoder.encode(&tmp_path_buf, &rand_buf);
143154
144 const file = dir.createFileC(155 const file = dir.createFileZ(
145 &tmp_path_buf,156 &tmp_path_buf,
146 .{ .mode = mode, .exclusive = true },157 .{ .mode = mode, .exclusive = true },
147 ) catch |err| switch (err) {158 ) catch |err| switch (err) {
...@@ -152,7 +163,7 @@ pub const AtomicFile = struct {...@@ -152,7 +163,7 @@ pub const AtomicFile = struct {
152 return AtomicFile{163 return AtomicFile{
153 .file = file,164 .file = file,
154 .tmp_path_buf = tmp_path_buf,165 .tmp_path_buf = tmp_path_buf,
155 .dest_path = dest_path,166 .dest_basename = dest_basename,
156 .file_open = true,167 .file_open = true,
157 .file_exists = true,168 .file_exists = true,
158 .close_dir_on_deinit = close_dir_on_deinit,169 .close_dir_on_deinit = close_dir_on_deinit,
...@@ -161,11 +172,6 @@ pub const AtomicFile = struct {...@@ -161,11 +172,6 @@ pub const AtomicFile = struct {
161 }172 }
162 }173 }
163174
164 /// Deprecated. Use `Dir.atomicFile`.
165 pub fn init(dest_path: []const u8, mode: File.Mode) InitError!AtomicFile {
166 return cwd().atomicFile(dest_path, .{ .mode = mode });
167 }
168
169 /// always call deinit, even after successful finish()175 /// always call deinit, even after successful finish()
170 pub fn deinit(self: *AtomicFile) void {176 pub fn deinit(self: *AtomicFile) void {
171 if (self.file_open) {177 if (self.file_open) {
...@@ -173,7 +179,7 @@ pub const AtomicFile = struct {...@@ -173,7 +179,7 @@ pub const AtomicFile = struct {
173 self.file_open = false;179 self.file_open = false;
174 }180 }
175 if (self.file_exists) {181 if (self.file_exists) {
176 self.dir.deleteFileC(&self.tmp_path_buf) catch {};182 self.dir.deleteFileZ(&self.tmp_path_buf) catch {};
177 self.file_exists = false;183 self.file_exists = false;
178 }184 }
179 if (self.close_dir_on_deinit) {185 if (self.close_dir_on_deinit) {
...@@ -189,12 +195,12 @@ pub const AtomicFile = struct {...@@ -189,12 +195,12 @@ pub const AtomicFile = struct {
189 self.file_open = false;195 self.file_open = false;
190 }196 }
191 if (std.Target.current.os.tag == .windows) {197 if (std.Target.current.os.tag == .windows) {
192 const dest_path_w = try os.windows.sliceToPrefixedFileW(self.dest_path);198 const dest_path_w = try os.windows.sliceToPrefixedFileW(self.dest_basename);
193 const tmp_path_w = try os.windows.cStrToPrefixedFileW(&self.tmp_path_buf);199 const tmp_path_w = try os.windows.cStrToPrefixedFileW(&self.tmp_path_buf);
194 try os.renameatW(self.dir.fd, &tmp_path_w, self.dir.fd, &dest_path_w, os.windows.TRUE);200 try os.renameatW(self.dir.fd, &tmp_path_w, self.dir.fd, &dest_path_w, os.windows.TRUE);
195 self.file_exists = false;201 self.file_exists = false;
196 } else {202 } else {
197 const dest_path_c = try os.toPosixPath(self.dest_path);203 const dest_path_c = try os.toPosixPath(self.dest_basename);
198 try os.renameatZ(self.dir.fd, &self.tmp_path_buf, self.dir.fd, &dest_path_c);204 try os.renameatZ(self.dir.fd, &self.tmp_path_buf, self.dir.fd, &dest_path_c);
199 self.file_exists = false;205 self.file_exists = false;
200 }206 }
...@@ -213,7 +219,7 @@ pub fn makeDirAbsolute(absolute_path: []const u8) !void {...@@ -213,7 +219,7 @@ pub fn makeDirAbsolute(absolute_path: []const u8) !void {
213219
214/// Same as `makeDirAbsolute` except the parameter is a null-terminated UTF8-encoded string.220/// Same as `makeDirAbsolute` except the parameter is a null-terminated UTF8-encoded string.
215pub fn makeDirAbsoluteZ(absolute_path_z: [*:0]const u8) !void {221pub fn makeDirAbsoluteZ(absolute_path_z: [*:0]const u8) !void {
216 assert(path.isAbsoluteC(absolute_path_z));222 assert(path.isAbsoluteZ(absolute_path_z));
217 return os.mkdirZ(absolute_path_z, default_new_dir_mode);223 return os.mkdirZ(absolute_path_z, default_new_dir_mode);
218}224}
219225
...@@ -224,18 +230,25 @@ pub fn makeDirAbsoluteW(absolute_path_w: [*:0]const u16) !void {...@@ -224,18 +230,25 @@ pub fn makeDirAbsoluteW(absolute_path_w: [*:0]const u16) !void {
224 os.windows.CloseHandle(handle);230 os.windows.CloseHandle(handle);
225}231}
226232
227/// Deprecated; use `Dir.deleteDir`.233pub const deleteDir = @compileError("deprecated; use dir.deleteDir or deleteDirAbsolute");
228pub fn deleteDir(dir_path: []const u8) !void {234pub const deleteDirC = @compileError("deprecated; use dir.deleteDirZ or deleteDirAbsoluteZ");
235pub const deleteDirW = @compileError("deprecated; use dir.deleteDirW or deleteDirAbsoluteW");
236
237/// Same as `Dir.deleteDir` except the path is absolute.
238pub fn deleteDirAbsolute(dir_path: []const u8) !void {
239 assert(path.isAbsolute(dir_path));
229 return os.rmdir(dir_path);240 return os.rmdir(dir_path);
230}241}
231242
232/// Deprecated; use `Dir.deleteDirC`.243/// Same as `deleteDirAbsolute` except the path parameter is null-terminated.
233pub fn deleteDirC(dir_path: [*:0]const u8) !void {244pub fn deleteDirAbsoluteZ(dir_path: [*:0]const u8) !void {
234 return os.rmdirC(dir_path);245 assert(path.isAbsoluteZ(dir_path));
246 return os.rmdirZ(dir_path);
235}247}
236248
237/// Deprecated; use `Dir.deleteDirW`.249/// Same as `deleteDirAbsolute` except the path parameter is WTF-16 and target OS is assumed Windows.
238pub fn deleteDirW(dir_path: [*:0]const u16) !void {250pub fn deleteDirAbsoluteW(dir_path: [*:0]const u16) !void {
251 assert(path.isAbsoluteWindowsW(dir_path));
239 return os.rmdirW(dir_path);252 return os.rmdirW(dir_path);
240}253}
241254
...@@ -412,7 +425,7 @@ pub const Dir = struct {...@@ -412,7 +425,7 @@ pub const Dir = struct {
412 const next_index = self.index + linux_entry.reclen();425 const next_index = self.index + linux_entry.reclen();
413 self.index = next_index;426 self.index = next_index;
414427
415 const name = mem.toSlice(u8, @ptrCast([*:0]u8, &linux_entry.d_name));428 const name = mem.spanZ(@ptrCast([*:0]u8, &linux_entry.d_name));
416429
417 // skip . and .. entries430 // skip . and .. entries
418 if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {431 if (mem.eql(u8, name, ".") or mem.eql(u8, name, "..")) {
...@@ -573,8 +586,7 @@ pub const Dir = struct {...@@ -573,8 +586,7 @@ pub const Dir = struct {
573 return self.openFileZ(&path_c, flags);586 return self.openFileZ(&path_c, flags);
574 }587 }
575588
576 /// Deprecated; use `openFileZ`.589 pub const openFileC = @compileError("deprecated: renamed to openFileZ");
577 pub const openFileC = openFileZ;
578590
579 /// Same as `openFile` but the path parameter is null-terminated.591 /// Same as `openFile` but the path parameter is null-terminated.
580 pub fn openFileZ(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File {592 pub fn openFileZ(self: Dir, sub_path: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File {
...@@ -603,7 +615,7 @@ pub const Dir = struct {...@@ -603,7 +615,7 @@ pub const Dir = struct {
603 const fd = if (need_async_thread and !flags.always_blocking)615 const fd = if (need_async_thread and !flags.always_blocking)
604 try std.event.Loop.instance.?.openatZ(self.fd, sub_path, os_flags, 0)616 try std.event.Loop.instance.?.openatZ(self.fd, sub_path, os_flags, 0)
605 else617 else
606 try os.openatC(self.fd, sub_path, os_flags, 0);618 try os.openatZ(self.fd, sub_path, os_flags, 0);
607619
608 // use fcntl file locking if no lock flag was given620 // use fcntl file locking if no lock flag was given
609 if (flags.lock and lock_flag == 0) {621 if (flags.lock and lock_flag == 0) {
...@@ -652,11 +664,13 @@ pub const Dir = struct {...@@ -652,11 +664,13 @@ pub const Dir = struct {
652 return self.createFileW(&path_w, flags);664 return self.createFileW(&path_w, flags);
653 }665 }
654 const path_c = try os.toPosixPath(sub_path);666 const path_c = try os.toPosixPath(sub_path);
655 return self.createFileC(&path_c, flags);667 return self.createFileZ(&path_c, flags);
656 }668 }
657669
670 pub const createFileC = @compileError("deprecated: renamed to createFileZ");
671
658 /// Same as `createFile` but the path parameter is null-terminated.672 /// Same as `createFile` but the path parameter is null-terminated.
659 pub fn createFileC(self: Dir, sub_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File {673 pub fn createFileZ(self: Dir, sub_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File {
660 if (builtin.os.tag == .windows) {674 if (builtin.os.tag == .windows) {
661 const path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);675 const path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);
662 return self.createFileW(&path_w, flags);676 return self.createFileW(&path_w, flags);
...@@ -676,7 +690,7 @@ pub const Dir = struct {...@@ -676,7 +690,7 @@ pub const Dir = struct {
676 const fd = if (need_async_thread)690 const fd = if (need_async_thread)
677 try std.event.Loop.instance.?.openatZ(self.fd, sub_path_c, os_flags, flags.mode)691 try std.event.Loop.instance.?.openatZ(self.fd, sub_path_c, os_flags, flags.mode)
678 else692 else
679 try os.openatC(self.fd, sub_path_c, os_flags, flags.mode);693 try os.openatZ(self.fd, sub_path_c, os_flags, flags.mode);
680694
681 if (flags.lock and lock_flag == 0) {695 if (flags.lock and lock_flag == 0) {
682 // TODO: integrate async I/O696 // TODO: integrate async I/O
...@@ -713,27 +727,16 @@ pub const Dir = struct {...@@ -713,27 +727,16 @@ pub const Dir = struct {
713 });727 });
714 }728 }
715729
716 /// Deprecated; call `openFile` directly.730 pub const openRead = @compileError("deprecated in favor of openFile");
717 pub fn openRead(self: Dir, sub_path: []const u8) File.OpenError!File {731 pub const openReadC = @compileError("deprecated in favor of openFileZ");
718 return self.openFile(sub_path, .{});732 pub const openReadW = @compileError("deprecated in favor of openFileW");
719 }
720
721 /// Deprecated; call `openFileZ` directly.
722 pub fn openReadC(self: Dir, sub_path: [*:0]const u8) File.OpenError!File {
723 return self.openFileZ(sub_path, .{});
724 }
725
726 /// Deprecated; call `openFileW` directly.
727 pub fn openReadW(self: Dir, sub_path: [*:0]const u16) File.OpenError!File {
728 return self.openFileW(sub_path, .{});
729 }
730733
731 pub fn makeDir(self: Dir, sub_path: []const u8) !void {734 pub fn makeDir(self: Dir, sub_path: []const u8) !void {
732 try os.mkdirat(self.fd, sub_path, default_new_dir_mode);735 try os.mkdirat(self.fd, sub_path, default_new_dir_mode);
733 }736 }
734737
735 pub fn makeDirZ(self: Dir, sub_path: [*:0]const u8) !void {738 pub fn makeDirZ(self: Dir, sub_path: [*:0]const u8) !void {
736 try os.mkdiratC(self.fd, sub_path, default_new_dir_mode);739 try os.mkdiratZ(self.fd, sub_path, default_new_dir_mode);
737 }740 }
738741
739 pub fn makeDirW(self: Dir, sub_path: [*:0]const u16) !void {742 pub fn makeDirW(self: Dir, sub_path: [*:0]const u16) !void {
...@@ -807,20 +810,22 @@ pub const Dir = struct {...@@ -807,20 +810,22 @@ pub const Dir = struct {
807 return self.openDirW(&sub_path_w, args);810 return self.openDirW(&sub_path_w, args);
808 } else {811 } else {
809 const sub_path_c = try os.toPosixPath(sub_path);812 const sub_path_c = try os.toPosixPath(sub_path);
810 return self.openDirC(&sub_path_c, args);813 return self.openDirZ(&sub_path_c, args);
811 }814 }
812 }815 }
813816
817 pub const openDirC = @compileError("deprecated: renamed to openDirZ");
818
814 /// Same as `openDir` except the parameter is null-terminated.819 /// Same as `openDir` except the parameter is null-terminated.
815 pub fn openDirC(self: Dir, sub_path_c: [*:0]const u8, args: OpenDirOptions) OpenError!Dir {820 pub fn openDirZ(self: Dir, sub_path_c: [*:0]const u8, args: OpenDirOptions) OpenError!Dir {
816 if (builtin.os.tag == .windows) {821 if (builtin.os.tag == .windows) {
817 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);822 const sub_path_w = try os.windows.cStrToPrefixedFileW(sub_path_c);
818 return self.openDirW(&sub_path_w, args);823 return self.openDirW(&sub_path_w, args);
819 } else if (!args.iterate) {824 } else if (!args.iterate) {
820 const O_PATH = if (@hasDecl(os, "O_PATH")) os.O_PATH else 0;825 const O_PATH = if (@hasDecl(os, "O_PATH")) os.O_PATH else 0;
821 return self.openDirFlagsC(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC | O_PATH);826 return self.openDirFlagsZ(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC | O_PATH);
822 } else {827 } else {
823 return self.openDirFlagsC(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC);828 return self.openDirFlagsZ(sub_path_c, os.O_DIRECTORY | os.O_RDONLY | os.O_CLOEXEC);
824 }829 }
825 }830 }
826831
...@@ -836,11 +841,11 @@ pub const Dir = struct {...@@ -836,11 +841,11 @@ pub const Dir = struct {
836 }841 }
837842
838 /// `flags` must contain `os.O_DIRECTORY`.843 /// `flags` must contain `os.O_DIRECTORY`.
839 fn openDirFlagsC(self: Dir, sub_path_c: [*:0]const u8, flags: u32) OpenError!Dir {844 fn openDirFlagsZ(self: Dir, sub_path_c: [*:0]const u8, flags: u32) OpenError!Dir {
840 const result = if (need_async_thread)845 const result = if (need_async_thread)
841 std.event.Loop.instance.?.openatZ(self.fd, sub_path_c, flags, 0)846 std.event.Loop.instance.?.openatZ(self.fd, sub_path_c, flags, 0)
842 else847 else
843 os.openatC(self.fd, sub_path_c, flags, 0);848 os.openatZ(self.fd, sub_path_c, flags, 0);
844 const fd = result catch |err| switch (err) {849 const fd = result catch |err| switch (err) {
845 error.FileTooBig => unreachable, // can't happen for directories850 error.FileTooBig => unreachable, // can't happen for directories
846 error.IsDir => unreachable, // we're providing O_DIRECTORY851 error.IsDir => unreachable, // we're providing O_DIRECTORY
...@@ -858,7 +863,7 @@ pub const Dir = struct {...@@ -858,7 +863,7 @@ pub const Dir = struct {
858 .fd = undefined,863 .fd = undefined,
859 };864 };
860865
861 const path_len_bytes = @intCast(u16, mem.toSliceConst(u16, sub_path_w).len * 2);866 const path_len_bytes = @intCast(u16, mem.lenZ(sub_path_w) * 2);
862 var nt_name = w.UNICODE_STRING{867 var nt_name = w.UNICODE_STRING{
863 .Length = path_len_bytes,868 .Length = path_len_bytes,
864 .MaximumLength = path_len_bytes,869 .MaximumLength = path_len_bytes,
...@@ -916,9 +921,11 @@ pub const Dir = struct {...@@ -916,9 +921,11 @@ pub const Dir = struct {
916 };921 };
917 }922 }
918923
924 pub const deleteFileC = @compileError("deprecated: renamed to deleteFileZ");
925
919 /// Same as `deleteFile` except the parameter is null-terminated.926 /// Same as `deleteFile` except the parameter is null-terminated.
920 pub fn deleteFileC(self: Dir, sub_path_c: [*:0]const u8) DeleteFileError!void {927 pub fn deleteFileZ(self: Dir, sub_path_c: [*:0]const u8) DeleteFileError!void {
921 os.unlinkatC(self.fd, sub_path_c, 0) catch |err| switch (err) {928 os.unlinkatZ(self.fd, sub_path_c, 0) catch |err| switch (err) {
922 error.DirNotEmpty => unreachable, // not passing AT_REMOVEDIR929 error.DirNotEmpty => unreachable, // not passing AT_REMOVEDIR
923 else => |e| return e,930 else => |e| return e,
924 };931 };
...@@ -957,12 +964,12 @@ pub const Dir = struct {...@@ -957,12 +964,12 @@ pub const Dir = struct {
957 return self.deleteDirW(&sub_path_w);964 return self.deleteDirW(&sub_path_w);
958 }965 }
959 const sub_path_c = try os.toPosixPath(sub_path);966 const sub_path_c = try os.toPosixPath(sub_path);
960 return self.deleteDirC(&sub_path_c);967 return self.deleteDirZ(&sub_path_c);
961 }968 }
962969
963 /// Same as `deleteDir` except the parameter is null-terminated.970 /// Same as `deleteDir` except the parameter is null-terminated.
964 pub fn deleteDirC(self: Dir, sub_path_c: [*:0]const u8) DeleteDirError!void {971 pub fn deleteDirZ(self: Dir, sub_path_c: [*:0]const u8) DeleteDirError!void {
965 os.unlinkatC(self.fd, sub_path_c, os.AT_REMOVEDIR) catch |err| switch (err) {972 os.unlinkatZ(self.fd, sub_path_c, os.AT_REMOVEDIR) catch |err| switch (err) {
966 error.IsDir => unreachable, // not possible since we pass AT_REMOVEDIR973 error.IsDir => unreachable, // not possible since we pass AT_REMOVEDIR
967 else => |e| return e,974 else => |e| return e,
968 };975 };
...@@ -982,12 +989,14 @@ pub const Dir = struct {...@@ -982,12 +989,14 @@ pub const Dir = struct {
982 /// Asserts that the path parameter has no null bytes.989 /// Asserts that the path parameter has no null bytes.
983 pub fn readLink(self: Dir, sub_path: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {990 pub fn readLink(self: Dir, sub_path: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
984 const sub_path_c = try os.toPosixPath(sub_path);991 const sub_path_c = try os.toPosixPath(sub_path);
985 return self.readLinkC(&sub_path_c, buffer);992 return self.readLinkZ(&sub_path_c, buffer);
986 }993 }
987994
995 pub const readLinkC = @compileError("deprecated: renamed to readLinkZ");
996
988 /// Same as `readLink`, except the `pathname` parameter is null-terminated.997 /// Same as `readLink`, except the `pathname` parameter is null-terminated.
989 pub fn readLinkC(self: Dir, sub_path_c: [*:0]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {998 pub fn readLinkZ(self: Dir, sub_path_c: [*:0]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
990 return os.readlinkatC(self.fd, sub_path_c, buffer);999 return os.readlinkatZ(self.fd, sub_path_c, buffer);
991 }1000 }
9921001
993 /// On success, caller owns returned buffer.1002 /// On success, caller owns returned buffer.
...@@ -1005,7 +1014,7 @@ pub const Dir = struct {...@@ -1005,7 +1014,7 @@ pub const Dir = struct {
1005 max_bytes: usize,1014 max_bytes: usize,
1006 comptime A: u29,1015 comptime A: u29,
1007 ) ![]align(A) u8 {1016 ) ![]align(A) u8 {
1008 var file = try self.openRead(file_path);1017 var file = try self.openFile(file_path, .{});
1009 defer file.close();1018 defer file.close();
10101019
1011 const size = math.cast(usize, try file.getEndPos()) catch math.maxInt(usize);1020 const size = math.cast(usize, try file.getEndPos()) catch math.maxInt(usize);
...@@ -1329,9 +1338,9 @@ pub const Dir = struct {...@@ -1329,9 +1338,9 @@ pub const Dir = struct {
1329 pub fn atomicFile(self: Dir, dest_path: []const u8, options: AtomicFileOptions) !AtomicFile {1338 pub fn atomicFile(self: Dir, dest_path: []const u8, options: AtomicFileOptions) !AtomicFile {
1330 if (path.dirname(dest_path)) |dirname| {1339 if (path.dirname(dest_path)) |dirname| {
1331 const dir = try self.openDir(dirname, .{});1340 const dir = try self.openDir(dirname, .{});
1332 return AtomicFile.init2(path.basename(dest_path), options.mode, dir, true);1341 return AtomicFile.init(path.basename(dest_path), options.mode, dir, true);
1333 } else {1342 } else {
1334 return AtomicFile.init2(dest_path, options.mode, self, false);1343 return AtomicFile.init(dest_path, options.mode, self, false);
1335 }1344 }
1336 }1345 }
1337};1346};
...@@ -1358,9 +1367,11 @@ pub fn openFileAbsolute(absolute_path: []const u8, flags: File.OpenFlags) File.O...@@ -1358,9 +1367,11 @@ pub fn openFileAbsolute(absolute_path: []const u8, flags: File.OpenFlags) File.O
1358 return cwd().openFile(absolute_path, flags);1367 return cwd().openFile(absolute_path, flags);
1359}1368}
13601369
1370pub const openFileAbsoluteC = @compileError("deprecated: renamed to openFileAbsoluteZ");
1371
1361/// Same as `openFileAbsolute` but the path parameter is null-terminated.1372/// Same as `openFileAbsolute` but the path parameter is null-terminated.
1362pub fn openFileAbsoluteC(absolute_path_c: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File {1373pub fn openFileAbsoluteZ(absolute_path_c: [*:0]const u8, flags: File.OpenFlags) File.OpenError!File {
1363 assert(path.isAbsoluteC(absolute_path_c));1374 assert(path.isAbsoluteZ(absolute_path_c));
1364 return cwd().openFileZ(absolute_path_c, flags);1375 return cwd().openFileZ(absolute_path_c, flags);
1365}1376}
13661377
...@@ -1381,10 +1392,12 @@ pub fn createFileAbsolute(absolute_path: []const u8, flags: File.CreateFlags) Fi...@@ -1381,10 +1392,12 @@ pub fn createFileAbsolute(absolute_path: []const u8, flags: File.CreateFlags) Fi
1381 return cwd().createFile(absolute_path, flags);1392 return cwd().createFile(absolute_path, flags);
1382}1393}
13831394
1395pub const createFileAbsoluteC = @compileError("deprecated: renamed to createFileAbsoluteZ");
1396
1384/// Same as `createFileAbsolute` but the path parameter is null-terminated.1397/// Same as `createFileAbsolute` but the path parameter is null-terminated.
1385pub fn createFileAbsoluteC(absolute_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File {1398pub fn createFileAbsoluteZ(absolute_path_c: [*:0]const u8, flags: File.CreateFlags) File.OpenError!File {
1386 assert(path.isAbsoluteC(absolute_path_c));1399 assert(path.isAbsoluteZ(absolute_path_c));
1387 return cwd().createFileC(absolute_path_c, flags);1400 return cwd().createFileZ(absolute_path_c, flags);
1388}1401}
13891402
1390/// Same as `createFileAbsolute` but the path parameter is WTF-16 encoded.1403/// Same as `createFileAbsolute` but the path parameter is WTF-16 encoded.
...@@ -1402,10 +1415,12 @@ pub fn deleteFileAbsolute(absolute_path: []const u8) DeleteFileError!void {...@@ -1402,10 +1415,12 @@ pub fn deleteFileAbsolute(absolute_path: []const u8) DeleteFileError!void {
1402 return cwd().deleteFile(absolute_path);1415 return cwd().deleteFile(absolute_path);
1403}1416}
14041417
1418pub const deleteFileAbsoluteC = @compileError("deprecated: renamed to deleteFileAbsoluteZ");
1419
1405/// Same as `deleteFileAbsolute` except the parameter is null-terminated.1420/// Same as `deleteFileAbsolute` except the parameter is null-terminated.
1406pub fn deleteFileAbsoluteC(absolute_path_c: [*:0]const u8) DeleteFileError!void {1421pub fn deleteFileAbsoluteZ(absolute_path_c: [*:0]const u8) DeleteFileError!void {
1407 assert(path.isAbsoluteC(absolute_path_c));1422 assert(path.isAbsoluteZ(absolute_path_c));
1408 return cwd().deleteFileC(absolute_path_c);1423 return cwd().deleteFileZ(absolute_path_c);
1409}1424}
14101425
1411/// Same as `deleteFileAbsolute` except the parameter is WTF-16 encoded.1426/// Same as `deleteFileAbsolute` except the parameter is WTF-16 encoded.
...@@ -1433,15 +1448,31 @@ pub fn deleteTreeAbsolute(absolute_path: []const u8) !void {...@@ -1433,15 +1448,31 @@ pub fn deleteTreeAbsolute(absolute_path: []const u8) !void {
1433 return dir.deleteTree(path.basename(absolute_path));1448 return dir.deleteTree(path.basename(absolute_path));
1434}1449}
14351450
1451/// Same as `Dir.readLink`, except it asserts the path is absolute.
1452pub fn readLinkAbsolute(pathname: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
1453 assert(path.isAbsolute(pathname));
1454 return os.readlink(pathname, buffer);
1455}
1456
1457/// Same as `readLink`, except the path parameter is null-terminated.
1458pub fn readLinkAbsoluteZ(pathname_c: [*]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
1459 assert(path.isAbsoluteZ(pathname_c));
1460 return os.readlinkZ(pathname_c, buffer);
1461}
1462
1463pub const readLink = @compileError("deprecated; use Dir.readLink or readLinkAbsolute");
1464pub const readLinkC = @compileError("deprecated; use Dir.readLinkZ or readLinkAbsoluteZ");
1465
1436pub const Walker = struct {1466pub const Walker = struct {
1437 stack: std.ArrayList(StackItem),1467 stack: std.ArrayList(StackItem),
1438 name_buffer: std.Buffer,1468 name_buffer: std.ArrayList(u8),
14391469
1440 pub const Entry = struct {1470 pub const Entry = struct {
1441 /// The containing directory. This can be used to operate directly on `basename`1471 /// The containing directory. This can be used to operate directly on `basename`
1442 /// rather than `path`, avoiding `error.NameTooLong` for deeply nested paths.1472 /// rather than `path`, avoiding `error.NameTooLong` for deeply nested paths.
1443 /// The directory remains open until `next` or `deinit` is called.1473 /// The directory remains open until `next` or `deinit` is called.
1444 dir: Dir,1474 dir: Dir,
1475 /// TODO make this null terminated for API convenience
1445 basename: []const u8,1476 basename: []const u8,
14461477
1447 path: []const u8,1478 path: []const u8,
...@@ -1460,12 +1491,12 @@ pub const Walker = struct {...@@ -1460,12 +1491,12 @@ pub const Walker = struct {
1460 while (true) {1491 while (true) {
1461 if (self.stack.len == 0) return null;1492 if (self.stack.len == 0) return null;
1462 // `top` becomes invalid after appending to `self.stack`.1493 // `top` becomes invalid after appending to `self.stack`.
1463 const top = &self.stack.toSlice()[self.stack.len - 1];1494 const top = &self.stack.span()[self.stack.len - 1];
1464 const dirname_len = top.dirname_len;1495 const dirname_len = top.dirname_len;
1465 if (try top.dir_it.next()) |base| {1496 if (try top.dir_it.next()) |base| {
1466 self.name_buffer.shrink(dirname_len);1497 self.name_buffer.shrink(dirname_len);
1467 try self.name_buffer.appendByte(path.sep);1498 try self.name_buffer.append(path.sep);
1468 try self.name_buffer.append(base.name);1499 try self.name_buffer.appendSlice(base.name);
1469 if (base.kind == .Directory) {1500 if (base.kind == .Directory) {
1470 var new_dir = top.dir_it.dir.openDir(base.name, .{ .iterate = true }) catch |err| switch (err) {1501 var new_dir = top.dir_it.dir.openDir(base.name, .{ .iterate = true }) catch |err| switch (err) {
1471 error.NameTooLong => unreachable, // no path sep in base.name1502 error.NameTooLong => unreachable, // no path sep in base.name
...@@ -1475,14 +1506,14 @@ pub const Walker = struct {...@@ -1475,14 +1506,14 @@ pub const Walker = struct {
1475 errdefer new_dir.close();1506 errdefer new_dir.close();
1476 try self.stack.append(StackItem{1507 try self.stack.append(StackItem{
1477 .dir_it = new_dir.iterate(),1508 .dir_it = new_dir.iterate(),
1478 .dirname_len = self.name_buffer.len(),1509 .dirname_len = self.name_buffer.len,
1479 });1510 });
1480 }1511 }
1481 }1512 }
1482 return Entry{1513 return Entry{
1483 .dir = top.dir_it.dir,1514 .dir = top.dir_it.dir,
1484 .basename = self.name_buffer.toSliceConst()[dirname_len + 1 ..],1515 .basename = self.name_buffer.span()[dirname_len + 1 ..],
1485 .path = self.name_buffer.toSliceConst(),1516 .path = self.name_buffer.span(),
1486 .kind = base.kind,1517 .kind = base.kind,
1487 };1518 };
1488 } else {1519 } else {
...@@ -1508,9 +1539,11 @@ pub fn walkPath(allocator: *Allocator, dir_path: []const u8) !Walker {...@@ -1508,9 +1539,11 @@ pub fn walkPath(allocator: *Allocator, dir_path: []const u8) !Walker {
1508 var dir = try cwd().openDir(dir_path, .{ .iterate = true });1539 var dir = try cwd().openDir(dir_path, .{ .iterate = true });
1509 errdefer dir.close();1540 errdefer dir.close();
15101541
1511 var name_buffer = try std.Buffer.init(allocator, dir_path);1542 var name_buffer = std.ArrayList(u8).init(allocator);
1512 errdefer name_buffer.deinit();1543 errdefer name_buffer.deinit();
15131544
1545 try name_buffer.appendSlice(dir_path);
1546
1514 var walker = Walker{1547 var walker = Walker{
1515 .stack = std.ArrayList(Walker.StackItem).init(allocator),1548 .stack = std.ArrayList(Walker.StackItem).init(allocator),
1516 .name_buffer = name_buffer,1549 .name_buffer = name_buffer,
...@@ -1524,31 +1557,21 @@ pub fn walkPath(allocator: *Allocator, dir_path: []const u8) !Walker {...@@ -1524,31 +1557,21 @@ pub fn walkPath(allocator: *Allocator, dir_path: []const u8) !Walker {
1524 return walker;1557 return walker;
1525}1558}
15261559
1527/// Deprecated; use `Dir.readLink`.
1528pub fn readLink(pathname: []const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
1529 return os.readlink(pathname, buffer);
1530}
1531
1532/// Deprecated; use `Dir.readLinkC`.
1533pub fn readLinkC(pathname_c: [*]const u8, buffer: *[MAX_PATH_BYTES]u8) ![]u8 {
1534 return os.readlinkC(pathname_c, buffer);
1535}
1536
1537pub const OpenSelfExeError = os.OpenError || os.windows.CreateFileError || SelfExePathError || os.FcntlError;1560pub const OpenSelfExeError = os.OpenError || os.windows.CreateFileError || SelfExePathError || os.FcntlError;
15381561
1539pub fn openSelfExe() OpenSelfExeError!File {1562pub fn openSelfExe() OpenSelfExeError!File {
1540 if (builtin.os.tag == .linux) {1563 if (builtin.os.tag == .linux) {
1541 return openFileAbsoluteC("/proc/self/exe", .{});1564 return openFileAbsoluteZ("/proc/self/exe", .{});
1542 }1565 }
1543 if (builtin.os.tag == .windows) {1566 if (builtin.os.tag == .windows) {
1544 const wide_slice = selfExePathW();1567 const wide_slice = selfExePathW();
1545 const prefixed_path_w = try os.windows.wToPrefixedFileW(wide_slice);1568 const prefixed_path_w = try os.windows.wToPrefixedFileW(wide_slice);
1546 return cwd().openReadW(&prefixed_path_w);1569 return cwd().openFileW(&prefixed_path_w, .{});
1547 }1570 }
1548 var buf: [MAX_PATH_BYTES]u8 = undefined;1571 var buf: [MAX_PATH_BYTES]u8 = undefined;
1549 const self_exe_path = try selfExePath(&buf);1572 const self_exe_path = try selfExePath(&buf);
1550 buf[self_exe_path.len] = 0;1573 buf[self_exe_path.len] = 0;
1551 return openFileAbsoluteC(self_exe_path[0..self_exe_path.len :0].ptr, .{});1574 return openFileAbsoluteZ(self_exe_path[0..self_exe_path.len :0].ptr, .{});
1552}1575}
15531576
1554test "openSelfExe" {1577test "openSelfExe" {
...@@ -1582,23 +1605,23 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {...@@ -1582,23 +1605,23 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {
1582 var u32_len: u32 = out_buffer.len;1605 var u32_len: u32 = out_buffer.len;
1583 const rc = std.c._NSGetExecutablePath(out_buffer, &u32_len);1606 const rc = std.c._NSGetExecutablePath(out_buffer, &u32_len);
1584 if (rc != 0) return error.NameTooLong;1607 if (rc != 0) return error.NameTooLong;
1585 return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer));1608 return mem.spanZ(@ptrCast([*:0]u8, out_buffer));
1586 }1609 }
1587 switch (builtin.os.tag) {1610 switch (builtin.os.tag) {
1588 .linux => return os.readlinkC("/proc/self/exe", out_buffer),1611 .linux => return os.readlinkZ("/proc/self/exe", out_buffer),
1589 .freebsd, .dragonfly => {1612 .freebsd, .dragonfly => {
1590 var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC, os.KERN_PROC_PATHNAME, -1 };1613 var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC, os.KERN_PROC_PATHNAME, -1 };
1591 var out_len: usize = out_buffer.len;1614 var out_len: usize = out_buffer.len;
1592 try os.sysctl(&mib, out_buffer, &out_len, null, 0);1615 try os.sysctl(&mib, out_buffer, &out_len, null, 0);
1593 // TODO could this slice from 0 to out_len instead?1616 // TODO could this slice from 0 to out_len instead?
1594 return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer));1617 return mem.spanZ(@ptrCast([*:0]u8, out_buffer));
1595 },1618 },
1596 .netbsd => {1619 .netbsd => {
1597 var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC_ARGS, -1, os.KERN_PROC_PATHNAME };1620 var mib = [4]c_int{ os.CTL_KERN, os.KERN_PROC_ARGS, -1, os.KERN_PROC_PATHNAME };
1598 var out_len: usize = out_buffer.len;1621 var out_len: usize = out_buffer.len;
1599 try os.sysctl(&mib, out_buffer, &out_len, null, 0);1622 try os.sysctl(&mib, out_buffer, &out_len, null, 0);
1600 // TODO could this slice from 0 to out_len instead?1623 // TODO could this slice from 0 to out_len instead?
1601 return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer));1624 return mem.spanZ(@ptrCast([*:0]u8, out_buffer));
1602 },1625 },
1603 .windows => {1626 .windows => {
1604 const utf16le_slice = selfExePathW();1627 const utf16le_slice = selfExePathW();
...@@ -1613,7 +1636,7 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {...@@ -1613,7 +1636,7 @@ pub fn selfExePath(out_buffer: *[MAX_PATH_BYTES]u8) SelfExePathError![]u8 {
1613/// The result is UTF16LE-encoded.1636/// The result is UTF16LE-encoded.
1614pub fn selfExePathW() [:0]const u16 {1637pub fn selfExePathW() [:0]const u16 {
1615 const image_path_name = &os.windows.peb().ProcessParameters.ImagePathName;1638 const image_path_name = &os.windows.peb().ProcessParameters.ImagePathName;
1616 return mem.toSliceConst(u16, @ptrCast([*:0]const u16, image_path_name.Buffer));1639 return mem.spanZ(@ptrCast([*:0]const u16, image_path_name.Buffer));
1617}1640}
16181641
1619/// `selfExeDirPath` except allocates the result on the heap.1642/// `selfExeDirPath` except allocates the result on the heap.
lib/std/fs/file.zig+1-1
...@@ -110,7 +110,7 @@ pub const File = struct {...@@ -110,7 +110,7 @@ pub const File = struct {
110 if (self.isTty()) {110 if (self.isTty()) {
111 if (self.handle == os.STDOUT_FILENO or self.handle == os.STDERR_FILENO) {111 if (self.handle == os.STDOUT_FILENO or self.handle == os.STDERR_FILENO) {
112 // Use getenvC to workaround https://github.com/ziglang/zig/issues/3511112 // Use getenvC to workaround https://github.com/ziglang/zig/issues/3511
113 if (os.getenvC("TERM")) |term| {113 if (os.getenvZ("TERM")) |term| {
114 if (std.mem.eql(u8, term, "dumb"))114 if (std.mem.eql(u8, term, "dumb"))
115 return false;115 return false;
116 }116 }
lib/std/fs/get_app_data_dir.zig+1-1
...@@ -24,7 +24,7 @@ pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataD...@@ -24,7 +24,7 @@ pub fn getAppDataDir(allocator: *mem.Allocator, appname: []const u8) GetAppDataD
24 )) {24 )) {
25 os.windows.S_OK => {25 os.windows.S_OK => {
26 defer os.windows.ole32.CoTaskMemFree(@ptrCast(*c_void, dir_path_ptr));26 defer os.windows.ole32.CoTaskMemFree(@ptrCast(*c_void, dir_path_ptr));
27 const global_dir = unicode.utf16leToUtf8Alloc(allocator, mem.toSliceConst(u16, dir_path_ptr)) catch |err| switch (err) {27 const global_dir = unicode.utf16leToUtf8Alloc(allocator, mem.spanZ(dir_path_ptr)) catch |err| switch (err) {
28 error.UnexpectedSecondSurrogateHalf => return error.AppDataDirUnavailable,28 error.UnexpectedSecondSurrogateHalf => return error.AppDataDirUnavailable,
29 error.ExpectedSecondSurrogateHalf => return error.AppDataDirUnavailable,29 error.ExpectedSecondSurrogateHalf => return error.AppDataDirUnavailable,
30 error.DanglingSurrogateHalf => return error.AppDataDirUnavailable,30 error.DanglingSurrogateHalf => return error.AppDataDirUnavailable,
lib/std/fs/path.zig+14-8
...@@ -128,11 +128,13 @@ test "join" {...@@ -128,11 +128,13 @@ test "join" {
128 testJoinPosix(&[_][]const u8{ "a/", "/c" }, "a/c");128 testJoinPosix(&[_][]const u8{ "a/", "/c" }, "a/c");
129}129}
130130
131pub fn isAbsoluteC(path_c: [*:0]const u8) bool {131pub const isAbsoluteC = @compileError("deprecated: renamed to isAbsoluteZ");
132
133pub fn isAbsoluteZ(path_c: [*:0]const u8) bool {
132 if (builtin.os.tag == .windows) {134 if (builtin.os.tag == .windows) {
133 return isAbsoluteWindowsC(path_c);135 return isAbsoluteWindowsZ(path_c);
134 } else {136 } else {
135 return isAbsolutePosixC(path_c);137 return isAbsolutePosixZ(path_c);
136 }138 }
137}139}
138140
...@@ -172,19 +174,23 @@ pub fn isAbsoluteWindows(path: []const u8) bool {...@@ -172,19 +174,23 @@ pub fn isAbsoluteWindows(path: []const u8) bool {
172}174}
173175
174pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool {176pub fn isAbsoluteWindowsW(path_w: [*:0]const u16) bool {
175 return isAbsoluteWindowsImpl(u16, mem.toSliceConst(u16, path_w));177 return isAbsoluteWindowsImpl(u16, mem.spanZ(path_w));
176}178}
177179
178pub fn isAbsoluteWindowsC(path_c: [*:0]const u8) bool {180pub const isAbsoluteWindowsC = @compileError("deprecated: renamed to isAbsoluteWindowsZ");
179 return isAbsoluteWindowsImpl(u8, mem.toSliceConst(u8, path_c));181
182pub fn isAbsoluteWindowsZ(path_c: [*:0]const u8) bool {
183 return isAbsoluteWindowsImpl(u8, mem.spanZ(path_c));
180}184}
181185
182pub fn isAbsolutePosix(path: []const u8) bool {186pub fn isAbsolutePosix(path: []const u8) bool {
183 return path.len > 0 and path[0] == sep_posix;187 return path.len > 0 and path[0] == sep_posix;
184}188}
185189
186pub fn isAbsolutePosixC(path_c: [*:0]const u8) bool {190pub const isAbsolutePosixC = @compileError("deprecated: renamed to isAbsolutePosixZ");
187 return isAbsolutePosix(mem.toSliceConst(u8, path_c));191
192pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool {
193 return isAbsolutePosix(mem.spanZ(path_c));
188}194}
189195
190test "isAbsoluteWindows" {196test "isAbsoluteWindows" {
lib/std/fs/watch.zig+1-1
...@@ -326,7 +326,7 @@ pub fn Watch(comptime V: type) type {...@@ -326,7 +326,7 @@ pub fn Watch(comptime V: type) type {
326 var basename_with_null_consumed = false;326 var basename_with_null_consumed = false;
327 defer if (!basename_with_null_consumed) self.allocator.free(basename_with_null);327 defer if (!basename_with_null_consumed) self.allocator.free(basename_with_null);
328328
329 const wd = try os.inotify_add_watchC(329 const wd = try os.inotify_add_watchZ(
330 self.os_data.inotify_fd,330 self.os_data.inotify_fd,
331 dirname_with_null.ptr,331 dirname_with_null.ptr,
332 os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_EXCL_UNLINK,332 os.linux.IN_CLOSE_WRITE | os.linux.IN_ONLYDIR | os.linux.IN_EXCL_UNLINK,
lib/std/hash/adler.zig+29-8
...@@ -42,18 +42,23 @@ pub const Adler32 = struct {...@@ -42,18 +42,23 @@ pub const Adler32 = struct {
4242
43 s2 %= base;43 s2 %= base;
44 } else {44 } else {
45 const n = nmax / 16; // note: 16 | nmax
46
45 var i: usize = 0;47 var i: usize = 0;
46 while (i + nmax <= input.len) : (i += nmax) {
47 const n = nmax / 16; // note: 16 | nmax
4848
49 while (i + nmax <= input.len) {
49 var rounds: usize = 0;50 var rounds: usize = 0;
50 while (rounds < n) : (rounds += 1) {51 while (rounds < n) : (rounds += 1) {
51 comptime var j: usize = 0;52 comptime var j: usize = 0;
52 inline while (j < 16) : (j += 1) {53 inline while (j < 16) : (j += 1) {
53 s1 +%= input[i + n * j];54 s1 +%= input[i + j];
54 s2 +%= s1;55 s2 +%= s1;
55 }56 }
57 i += 16;
56 }58 }
59
60 s1 %= base;
61 s2 %= base;
57 }62 }
5863
59 if (i < input.len) {64 if (i < input.len) {
...@@ -89,19 +94,35 @@ pub const Adler32 = struct {...@@ -89,19 +94,35 @@ pub const Adler32 = struct {
89};94};
9095
91test "adler32 sanity" {96test "adler32 sanity" {
92 testing.expect(Adler32.hash("a") == 0x620062);97 testing.expectEqual(@as(u32, 0x620062), Adler32.hash("a"));
93 testing.expect(Adler32.hash("example") == 0xbc002ed);98 testing.expectEqual(@as(u32, 0xbc002ed), Adler32.hash("example"));
94}99}
95100
96test "adler32 long" {101test "adler32 long" {
97 const long1 = [_]u8{1} ** 1024;102 const long1 = [_]u8{1} ** 1024;
98 testing.expect(Adler32.hash(long1[0..]) == 0x06780401);103 testing.expectEqual(@as(u32, 0x06780401), Adler32.hash(long1[0..]));
99104
100 const long2 = [_]u8{1} ** 1025;105 const long2 = [_]u8{1} ** 1025;
101 testing.expect(Adler32.hash(long2[0..]) == 0x0a7a0402);106 testing.expectEqual(@as(u32, 0x0a7a0402), Adler32.hash(long2[0..]));
102}107}
103108
104test "adler32 very long" {109test "adler32 very long" {
105 const long = [_]u8{1} ** 5553;110 const long = [_]u8{1} ** 5553;
106 testing.expect(Adler32.hash(long[0..]) == 0x707f15b2);111 testing.expectEqual(@as(u32, 0x707f15b2), Adler32.hash(long[0..]));
112}
113
114test "adler32 very long with variation" {
115 const long = comptime blk: {
116 @setEvalBranchQuota(7000);
117 var result: [6000]u8 = undefined;
118
119 var i: usize = 0;
120 while (i < result.len) : (i += 1) {
121 result[i] = @truncate(u8, i);
122 }
123
124 break :blk result;
125 };
126
127 testing.expectEqual(@as(u32, 0x5af38d6e), std.hash.Adler32.hash(long[0..]));
107}128}
lib/std/heap.zig+1-2
...@@ -51,8 +51,7 @@ var wasm_page_allocator_state = Allocator{...@@ -51,8 +51,7 @@ var wasm_page_allocator_state = Allocator{
51 .shrinkFn = WasmPageAllocator.shrink,51 .shrinkFn = WasmPageAllocator.shrink,
52};52};
5353
54/// Deprecated. Use `page_allocator`.54pub const direct_allocator = @compileError("deprecated; use std.heap.page_allocator");
55pub const direct_allocator = page_allocator;
5655
57const PageAllocator = struct {56const PageAllocator = struct {
58 fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 {57 fn alloc(allocator: *Allocator, n: usize, alignment: u29) error{OutOfMemory}![]u8 {
lib/std/http/headers.zig+8-8
...@@ -129,7 +129,7 @@ pub const Headers = struct {...@@ -129,7 +129,7 @@ pub const Headers = struct {
129 self.index.deinit();129 self.index.deinit();
130 }130 }
131 {131 {
132 for (self.data.toSliceConst()) |entry| {132 for (self.data.span()) |entry| {
133 entry.deinit();133 entry.deinit();
134 }134 }
135 self.data.deinit();135 self.data.deinit();
...@@ -141,14 +141,14 @@ pub const Headers = struct {...@@ -141,14 +141,14 @@ pub const Headers = struct {
141 errdefer other.deinit();141 errdefer other.deinit();
142 try other.data.ensureCapacity(self.data.len);142 try other.data.ensureCapacity(self.data.len);
143 try other.index.initCapacity(self.index.entries.len);143 try other.index.initCapacity(self.index.entries.len);
144 for (self.data.toSliceConst()) |entry| {144 for (self.data.span()) |entry| {
145 try other.append(entry.name, entry.value, entry.never_index);145 try other.append(entry.name, entry.value, entry.never_index);
146 }146 }
147 return other;147 return other;
148 }148 }
149149
150 pub fn toSlice(self: Self) []const HeaderEntry {150 pub fn toSlice(self: Self) []const HeaderEntry {
151 return self.data.toSliceConst();151 return self.data.span();
152 }152 }
153153
154 pub fn append(self: *Self, name: []const u8, value: []const u8, never_index: ?bool) !void {154 pub fn append(self: *Self, name: []const u8, value: []const u8, never_index: ?bool) !void {
...@@ -279,7 +279,7 @@ pub const Headers = struct {...@@ -279,7 +279,7 @@ pub const Headers = struct {
279279
280 const buf = try allocator.alloc(HeaderEntry, dex.len);280 const buf = try allocator.alloc(HeaderEntry, dex.len);
281 var n: usize = 0;281 var n: usize = 0;
282 for (dex.toSliceConst()) |idx| {282 for (dex.span()) |idx| {
283 buf[n] = self.data.at(idx);283 buf[n] = self.data.at(idx);
284 n += 1;284 n += 1;
285 }285 }
...@@ -302,7 +302,7 @@ pub const Headers = struct {...@@ -302,7 +302,7 @@ pub const Headers = struct {
302 // adapted from mem.join302 // adapted from mem.join
303 const total_len = blk: {303 const total_len = blk: {
304 var sum: usize = dex.len - 1; // space for separator(s)304 var sum: usize = dex.len - 1; // space for separator(s)
305 for (dex.toSliceConst()) |idx|305 for (dex.span()) |idx|
306 sum += self.data.at(idx).value.len;306 sum += self.data.at(idx).value.len;
307 break :blk sum;307 break :blk sum;
308 };308 };
...@@ -334,7 +334,7 @@ pub const Headers = struct {...@@ -334,7 +334,7 @@ pub const Headers = struct {
334 }334 }
335 }335 }
336 { // fill up indexes again; we know capacity is fine from before336 { // fill up indexes again; we know capacity is fine from before
337 for (self.data.toSliceConst()) |entry, i| {337 for (self.data.span()) |entry, i| {
338 var dex = &self.index.get(entry.name).?.value;338 var dex = &self.index.get(entry.name).?.value;
339 dex.appendAssumeCapacity(i);339 dex.appendAssumeCapacity(i);
340 }340 }
...@@ -495,8 +495,8 @@ test "Headers.getIndices" {...@@ -495,8 +495,8 @@ test "Headers.getIndices" {
495 try h.append("set-cookie", "y=2", null);495 try h.append("set-cookie", "y=2", null);
496496
497 testing.expect(null == h.getIndices("not-present"));497 testing.expect(null == h.getIndices("not-present"));
498 testing.expectEqualSlices(usize, &[_]usize{0}, h.getIndices("foo").?.toSliceConst());498 testing.expectEqualSlices(usize, &[_]usize{0}, h.getIndices("foo").?.span());
499 testing.expectEqualSlices(usize, &[_]usize{ 1, 2 }, h.getIndices("set-cookie").?.toSliceConst());499 testing.expectEqualSlices(usize, &[_]usize{ 1, 2 }, h.getIndices("set-cookie").?.span());
500}500}
501501
502test "Headers.get" {502test "Headers.get" {
lib/std/io.zig+17-10
...@@ -128,16 +128,6 @@ pub const BufferedAtomicFile = @import("io/buffered_atomic_file.zig").BufferedAt...@@ -128,16 +128,6 @@ pub const BufferedAtomicFile = @import("io/buffered_atomic_file.zig").BufferedAt
128128
129pub const StreamSource = @import("io/stream_source.zig").StreamSource;129pub const StreamSource = @import("io/stream_source.zig").StreamSource;
130130
131/// Deprecated; use `std.fs.Dir.writeFile`.
132pub fn writeFile(path: []const u8, data: []const u8) !void {
133 return fs.cwd().writeFile(path, data);
134}
135
136/// Deprecated; use `std.fs.Dir.readFileAlloc`.
137pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 {
138 return fs.cwd().readFileAlloc(allocator, path, math.maxInt(usize));
139}
140
141/// An OutStream that doesn't write to anything.131/// An OutStream that doesn't write to anything.
142pub const null_out_stream = @as(NullOutStream, .{ .context = {} });132pub const null_out_stream = @as(NullOutStream, .{ .context = {} });
143133
...@@ -151,5 +141,22 @@ test "null_out_stream" {...@@ -151,5 +141,22 @@ test "null_out_stream" {
151}141}
152142
153test "" {143test "" {
144 _ = @import("io/bit_in_stream.zig");
145 _ = @import("io/bit_out_stream.zig");
146 _ = @import("io/buffered_atomic_file.zig");
147 _ = @import("io/buffered_in_stream.zig");
148 _ = @import("io/buffered_out_stream.zig");
149 _ = @import("io/c_out_stream.zig");
150 _ = @import("io/counting_out_stream.zig");
151 _ = @import("io/fixed_buffer_stream.zig");
152 _ = @import("io/in_stream.zig");
153 _ = @import("io/out_stream.zig");
154 _ = @import("io/peek_stream.zig");
155 _ = @import("io/seekable_stream.zig");
156 _ = @import("io/serialization.zig");
157 _ = @import("io/stream_source.zig");
154 _ = @import("io/test.zig");158 _ = @import("io/test.zig");
155}159}
160
161pub const writeFile = @compileError("deprecated: use std.fs.Dir.writeFile with math.maxInt(usize)");
162pub const readFileAlloc = @compileError("deprecated: use std.fs.Dir.readFileAlloc");
lib/std/io/buffered_atomic_file.zig+2-1
...@@ -15,6 +15,7 @@ pub const BufferedAtomicFile = struct {...@@ -15,6 +15,7 @@ pub const BufferedAtomicFile = struct {
1515
16 /// TODO when https://github.com/ziglang/zig/issues/2761 is solved16 /// TODO when https://github.com/ziglang/zig/issues/2761 is solved
17 /// this API will not need an allocator17 /// this API will not need an allocator
18 /// TODO integrate this with Dir API
18 pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile {19 pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile {
19 var self = try allocator.create(BufferedAtomicFile);20 var self = try allocator.create(BufferedAtomicFile);
20 self.* = BufferedAtomicFile{21 self.* = BufferedAtomicFile{
...@@ -25,7 +26,7 @@ pub const BufferedAtomicFile = struct {...@@ -25,7 +26,7 @@ pub const BufferedAtomicFile = struct {
25 };26 };
26 errdefer allocator.destroy(self);27 errdefer allocator.destroy(self);
2728
28 self.atomic_file = try fs.AtomicFile.init(dest_path, File.default_mode);29 self.atomic_file = try fs.cwd().atomicFile(dest_path, .{});
29 errdefer self.atomic_file.deinit();30 errdefer self.atomic_file.deinit();
3031
31 self.file_stream = self.atomic_file.file.outStream();32 self.file_stream = self.atomic_file.file.outStream();
lib/std/io/c_out_stream.zig+2-2
...@@ -36,9 +36,9 @@ test "" {...@@ -36,9 +36,9 @@ test "" {
36 const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile;36 const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile;
37 defer {37 defer {
38 _ = std.c.fclose(out_file);38 _ = std.c.fclose(out_file);
39 fs.cwd().deleteFileC(filename) catch {};39 std.fs.cwd().deleteFileZ(filename) catch {};
40 }40 }
4141
42 const out_stream = &io.COutStream.init(out_file).stream;42 const out_stream = cOutStream(out_file);
43 try out_stream.print("hi: {}\n", .{@as(i32, 123)});43 try out_stream.print("hi: {}\n", .{@as(i32, 123)});
44}44}
lib/std/io/in_stream.zig+1-8
...@@ -3,7 +3,6 @@ const builtin = std.builtin;...@@ -3,7 +3,6 @@ const builtin = std.builtin;
3const math = std.math;3const math = std.math;
4const assert = std.debug.assert;4const assert = std.debug.assert;
5const mem = std.mem;5const mem = std.mem;
6const Buffer = std.Buffer;
7const testing = std.testing;6const testing = std.testing;
87
9pub fn InStream(8pub fn InStream(
...@@ -48,13 +47,7 @@ pub fn InStream(...@@ -48,13 +47,7 @@ pub fn InStream(
48 if (amt_read < buf.len) return error.EndOfStream;47 if (amt_read < buf.len) return error.EndOfStream;
49 }48 }
5049
51 /// Deprecated: use `readAllArrayList`.50 pub const readAllBuffer = @compileError("deprecated; use readAllArrayList()");
52 pub fn readAllBuffer(self: Self, buffer: *Buffer, max_size: usize) !void {
53 buffer.list.shrink(0);
54 try self.readAllArrayList(&buffer.list, max_size);
55 errdefer buffer.shrink(0);
56 try buffer.list.append(0);
57 }
5851
59 /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found.52 /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found.
60 /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned53 /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned
lib/std/io/peek_stream.zig+4-4
...@@ -24,7 +24,7 @@ pub fn PeekStream(...@@ -24,7 +24,7 @@ pub fn PeekStream(
24 .Static => struct {24 .Static => struct {
25 pub fn init(base: InStreamType) Self {25 pub fn init(base: InStreamType) Self {
26 return .{26 return .{
27 .base = base,27 .unbuffered_in_stream = base,
28 .fifo = FifoType.init(),28 .fifo = FifoType.init(),
29 };29 };
30 }30 }
...@@ -32,7 +32,7 @@ pub fn PeekStream(...@@ -32,7 +32,7 @@ pub fn PeekStream(
32 .Slice => struct {32 .Slice => struct {
33 pub fn init(base: InStreamType, buf: []u8) Self {33 pub fn init(base: InStreamType, buf: []u8) Self {
34 return .{34 return .{
35 .base = base,35 .unbuffered_in_stream = base,
36 .fifo = FifoType.init(buf),36 .fifo = FifoType.init(buf),
37 };37 };
38 }38 }
...@@ -40,7 +40,7 @@ pub fn PeekStream(...@@ -40,7 +40,7 @@ pub fn PeekStream(
40 .Dynamic => struct {40 .Dynamic => struct {
41 pub fn init(base: InStreamType, allocator: *mem.Allocator) Self {41 pub fn init(base: InStreamType, allocator: *mem.Allocator) Self {
42 return .{42 return .{
43 .base = base,43 .unbuffered_in_stream = base,
44 .fifo = FifoType.init(allocator),44 .fifo = FifoType.init(allocator),
45 };45 };
46 }46 }
...@@ -61,7 +61,7 @@ pub fn PeekStream(...@@ -61,7 +61,7 @@ pub fn PeekStream(
61 if (dest_index == dest.len) return dest_index;61 if (dest_index == dest.len) return dest_index;
6262
63 // ask the backing stream for more63 // ask the backing stream for more
64 dest_index += try self.base.read(dest[dest_index..]);64 dest_index += try self.unbuffered_in_stream.read(dest[dest_index..]);
65 return dest_index;65 return dest_index;
66 }66 }
6767
lib/std/io/serialization.zig+50-49
...@@ -5,6 +5,7 @@ const assert = std.debug.assert;...@@ -5,6 +5,7 @@ const assert = std.debug.assert;
5const math = std.math;5const math = std.math;
6const meta = std.meta;6const meta = std.meta;
7const trait = meta.trait;7const trait = meta.trait;
8const testing = std.testing;
89
9pub const Packing = enum {10pub const Packing = enum {
10 /// Pack data to byte alignment11 /// Pack data to byte alignment
...@@ -273,7 +274,7 @@ pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, co...@@ -273,7 +274,7 @@ pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, co
273 if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);274 if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);
274275
275 if (comptime trait.isPacked(T) and packing != .Bit) {276 if (comptime trait.isPacked(T) and packing != .Bit) {
276 var packed_serializer = Serializer(endian, .Bit, Error).init(self.out_stream);277 var packed_serializer = Serializer(endian, .Bit, OutStreamType).init(self.out_stream);
277 try packed_serializer.serialize(value);278 try packed_serializer.serialize(value);
278 try packed_serializer.flush();279 try packed_serializer.flush();
279 return;280 return;
...@@ -364,28 +365,28 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi...@@ -364,28 +365,28 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi
364365
365 var data_mem: [total_bytes]u8 = undefined;366 var data_mem: [total_bytes]u8 = undefined;
366 var out = io.fixedBufferStream(&data_mem);367 var out = io.fixedBufferStream(&data_mem);
367 var serializer = serializer(endian, packing, out.outStream());368 var _serializer = serializer(endian, packing, out.outStream());
368369
369 var in = io.fixedBufferStream(&data_mem);370 var in = io.fixedBufferStream(&data_mem);
370 var deserializer = Deserializer(endian, packing, in.inStream());371 var _deserializer = deserializer(endian, packing, in.inStream());
371372
372 comptime var i = 0;373 comptime var i = 0;
373 inline while (i <= max_test_bitsize) : (i += 1) {374 inline while (i <= max_test_bitsize) : (i += 1) {
374 const U = std.meta.IntType(false, i);375 const U = std.meta.IntType(false, i);
375 const S = std.meta.IntType(true, i);376 const S = std.meta.IntType(true, i);
376 try serializer.serializeInt(@as(U, i));377 try _serializer.serializeInt(@as(U, i));
377 if (i != 0) try serializer.serializeInt(@as(S, -1)) else try serializer.serialize(@as(S, 0));378 if (i != 0) try _serializer.serializeInt(@as(S, -1)) else try _serializer.serialize(@as(S, 0));
378 }379 }
379 try serializer.flush();380 try _serializer.flush();
380381
381 i = 0;382 i = 0;
382 inline while (i <= max_test_bitsize) : (i += 1) {383 inline while (i <= max_test_bitsize) : (i += 1) {
383 const U = std.meta.IntType(false, i);384 const U = std.meta.IntType(false, i);
384 const S = std.meta.IntType(true, i);385 const S = std.meta.IntType(true, i);
385 const x = try deserializer.deserializeInt(U);386 const x = try _deserializer.deserializeInt(U);
386 const y = try deserializer.deserializeInt(S);387 const y = try _deserializer.deserializeInt(S);
387 expect(x == @as(U, i));388 testing.expect(x == @as(U, i));
388 if (i != 0) expect(y == @as(S, -1)) else expect(y == 0);389 if (i != 0) testing.expect(y == @as(S, -1)) else testing.expect(y == 0);
389 }390 }
390391
391 const u8_bit_count = comptime meta.bitCount(u8);392 const u8_bit_count = comptime meta.bitCount(u8);
...@@ -395,7 +396,7 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi...@@ -395,7 +396,7 @@ fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packi
395 const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);396 const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);
396 const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;397 const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;
397398
398 expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);399 testing.expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);
399400
400 //Verify that empty error set works with serializer.401 //Verify that empty error set works with serializer.
401 //deserializer is covered by FixedBufferStream402 //deserializer is covered by FixedBufferStream
...@@ -421,35 +422,35 @@ fn testIntSerializerDeserializerInfNaN(...@@ -421,35 +422,35 @@ fn testIntSerializerDeserializerInfNaN(
421 var data_mem: [mem_size]u8 = undefined;422 var data_mem: [mem_size]u8 = undefined;
422423
423 var out = io.fixedBufferStream(&data_mem);424 var out = io.fixedBufferStream(&data_mem);
424 var serializer = serializer(endian, packing, out.outStream());425 var _serializer = serializer(endian, packing, out.outStream());
425426
426 var in = io.fixedBufferStream(&data_mem);427 var in = io.fixedBufferStream(&data_mem);
427 var deserializer = deserializer(endian, packing, in.inStream());428 var _deserializer = deserializer(endian, packing, in.inStream());
428429
429 //@TODO: isInf/isNan not currently implemented for f128.430 //@TODO: isInf/isNan not currently implemented for f128.
430 try serializer.serialize(std.math.nan(f16));431 try _serializer.serialize(std.math.nan(f16));
431 try serializer.serialize(std.math.inf(f16));432 try _serializer.serialize(std.math.inf(f16));
432 try serializer.serialize(std.math.nan(f32));433 try _serializer.serialize(std.math.nan(f32));
433 try serializer.serialize(std.math.inf(f32));434 try _serializer.serialize(std.math.inf(f32));
434 try serializer.serialize(std.math.nan(f64));435 try _serializer.serialize(std.math.nan(f64));
435 try serializer.serialize(std.math.inf(f64));436 try _serializer.serialize(std.math.inf(f64));
436 //try serializer.serialize(std.math.nan(f128));437 //try serializer.serialize(std.math.nan(f128));
437 //try serializer.serialize(std.math.inf(f128));438 //try serializer.serialize(std.math.inf(f128));
438 const nan_check_f16 = try deserializer.deserialize(f16);439 const nan_check_f16 = try _deserializer.deserialize(f16);
439 const inf_check_f16 = try deserializer.deserialize(f16);440 const inf_check_f16 = try _deserializer.deserialize(f16);
440 const nan_check_f32 = try deserializer.deserialize(f32);441 const nan_check_f32 = try _deserializer.deserialize(f32);
441 deserializer.alignToByte();442 _deserializer.alignToByte();
442 const inf_check_f32 = try deserializer.deserialize(f32);443 const inf_check_f32 = try _deserializer.deserialize(f32);
443 const nan_check_f64 = try deserializer.deserialize(f64);444 const nan_check_f64 = try _deserializer.deserialize(f64);
444 const inf_check_f64 = try deserializer.deserialize(f64);445 const inf_check_f64 = try _deserializer.deserialize(f64);
445 //const nan_check_f128 = try deserializer.deserialize(f128);446 //const nan_check_f128 = try deserializer.deserialize(f128);
446 //const inf_check_f128 = try deserializer.deserialize(f128);447 //const inf_check_f128 = try deserializer.deserialize(f128);
447 expect(std.math.isNan(nan_check_f16));448 testing.expect(std.math.isNan(nan_check_f16));
448 expect(std.math.isInf(inf_check_f16));449 testing.expect(std.math.isInf(inf_check_f16));
449 expect(std.math.isNan(nan_check_f32));450 testing.expect(std.math.isNan(nan_check_f32));
450 expect(std.math.isInf(inf_check_f32));451 testing.expect(std.math.isInf(inf_check_f32));
451 expect(std.math.isNan(nan_check_f64));452 testing.expect(std.math.isNan(nan_check_f64));
452 expect(std.math.isInf(inf_check_f64));453 testing.expect(std.math.isInf(inf_check_f64));
453 //expect(std.math.isNan(nan_check_f128));454 //expect(std.math.isNan(nan_check_f128));
454 //expect(std.math.isInf(inf_check_f128));455 //expect(std.math.isInf(inf_check_f128));
455}456}
...@@ -461,8 +462,8 @@ test "Serializer/Deserializer Int: Inf/NaN" {...@@ -461,8 +462,8 @@ test "Serializer/Deserializer Int: Inf/NaN" {
461 try testIntSerializerDeserializerInfNaN(.Little, .Bit);462 try testIntSerializerDeserializerInfNaN(.Little, .Bit);
462}463}
463464
464fn testAlternateSerializer(self: var, serializer: var) !void {465fn testAlternateSerializer(self: var, _serializer: var) !void {
465 try serializer.serialize(self.f_f16);466 try _serializer.serialize(self.f_f16);
466}467}
467468
468fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {469fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
...@@ -502,8 +503,8 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing:...@@ -502,8 +503,8 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing:
502 f_f16: f16,503 f_f16: f16,
503 f_unused_u32: u32,504 f_unused_u32: u32,
504505
505 pub fn deserialize(self: *@This(), deserializer: var) !void {506 pub fn deserialize(self: *@This(), _deserializer: var) !void {
506 try deserializer.deserializeInto(&self.f_f16);507 try _deserializer.deserializeInto(&self.f_f16);
507 self.f_unused_u32 = 47;508 self.f_unused_u32 = 47;
508 }509 }
509510
...@@ -550,15 +551,15 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing:...@@ -550,15 +551,15 @@ fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing:
550551
551 var data_mem: [@sizeOf(MyStruct)]u8 = undefined;552 var data_mem: [@sizeOf(MyStruct)]u8 = undefined;
552 var out = io.fixedBufferStream(&data_mem);553 var out = io.fixedBufferStream(&data_mem);
553 var serializer = serializer(endian, packing, out.outStream());554 var _serializer = serializer(endian, packing, out.outStream());
554555
555 var in = io.fixedBufferStream(&data_mem);556 var in = io.fixedBufferStream(&data_mem);
556 var deserializer = deserializer(endian, packing, in.inStream());557 var _deserializer = deserializer(endian, packing, in.inStream());
557558
558 try serializer.serialize(my_inst);559 try _serializer.serialize(my_inst);
559560
560 const my_copy = try deserializer.deserialize(MyStruct);561 const my_copy = try _deserializer.deserialize(MyStruct);
561 expect(meta.eql(my_copy, my_inst));562 testing.expect(meta.eql(my_copy, my_inst));
562}563}
563564
564test "Serializer/Deserializer generic" {565test "Serializer/Deserializer generic" {
...@@ -584,18 +585,18 @@ fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !v...@@ -584,18 +585,18 @@ fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !v
584 };585 };
585586
586 var data_mem: [4]u8 = undefined;587 var data_mem: [4]u8 = undefined;
587 var out = io.fixedBufferStream.init(&data_mem);588 var out = io.fixedBufferStream(&data_mem);
588 var serializer = serializer(endian, packing, out.outStream());589 var _serializer = serializer(endian, packing, out.outStream());
589590
590 var in = io.fixedBufferStream(&data_mem);591 var in = io.fixedBufferStream(&data_mem);
591 var deserializer = deserializer(endian, packing, in.inStream());592 var _deserializer = deserializer(endian, packing, in.inStream());
592593
593 try serializer.serialize(@as(u14, 3));594 try _serializer.serialize(@as(u14, 3));
594 expectError(error.InvalidEnumTag, deserializer.deserialize(A));595 testing.expectError(error.InvalidEnumTag, _deserializer.deserialize(A));
595 out.pos = 0;596 out.pos = 0;
596 try serializer.serialize(@as(u14, 3));597 try _serializer.serialize(@as(u14, 3));
597 try serializer.serialize(@as(u14, 88));598 try _serializer.serialize(@as(u14, 88));
598 expectError(error.InvalidEnumTag, deserializer.deserialize(C));599 testing.expectError(error.InvalidEnumTag, _deserializer.deserialize(C));
599}600}
600601
601test "Deserializer bad data" {602test "Deserializer bad data" {
lib/std/json.zig+328-95
...@@ -1233,42 +1233,119 @@ pub const Value = union(enum) {...@@ -1233,42 +1233,119 @@ pub const Value = union(enum) {
1233 Array: Array,1233 Array: Array,
1234 Object: ObjectMap,1234 Object: ObjectMap,
12351235
1236 pub fn jsonStringify(
1237 value: @This(),
1238 options: StringifyOptions,
1239 out_stream: var,
1240 ) @TypeOf(out_stream).Error!void {
1241 switch (value) {
1242 .Null => try stringify(null, options, out_stream),
1243 .Bool => |inner| try stringify(inner, options, out_stream),
1244 .Integer => |inner| try stringify(inner, options, out_stream),
1245 .Float => |inner| try stringify(inner, options, out_stream),
1246 .String => |inner| try stringify(inner, options, out_stream),
1247 .Array => |inner| try stringify(inner.span(), options, out_stream),
1248 .Object => |inner| {
1249 try out_stream.writeByte('{');
1250 var field_output = false;
1251 var child_options = options;
1252 if (child_options.whitespace) |*child_whitespace| {
1253 child_whitespace.indent_level += 1;
1254 }
1255 var it = inner.iterator();
1256 while (it.next()) |entry| {
1257 if (!field_output) {
1258 field_output = true;
1259 } else {
1260 try out_stream.writeByte(',');
1261 }
1262 if (child_options.whitespace) |child_whitespace| {
1263 try out_stream.writeByte('\n');
1264 try child_whitespace.outputIndent(out_stream);
1265 }
1266
1267 try stringify(entry.key, options, out_stream);
1268 try out_stream.writeByte(':');
1269 if (child_options.whitespace) |child_whitespace| {
1270 if (child_whitespace.separator) {
1271 try out_stream.writeByte(' ');
1272 }
1273 }
1274 try stringify(entry.value, child_options, out_stream);
1275 }
1276 if (field_output) {
1277 if (options.whitespace) |whitespace| {
1278 try out_stream.writeByte('\n');
1279 try whitespace.outputIndent(out_stream);
1280 }
1281 }
1282 try out_stream.writeByte('}');
1283 },
1284 }
1285 }
1286
1236 pub fn dump(self: Value) void {1287 pub fn dump(self: Value) void {
1237 var held = std.debug.getStderrMutex().acquire();1288 var held = std.debug.getStderrMutex().acquire();
1238 defer held.release();1289 defer held.release();
12391290
1240 const stderr = std.debug.getStderrStream();1291 const stderr = std.debug.getStderrStream();
1241 self.dumpStream(stderr, 1024) catch return;1292 std.json.stringify(self, std.json.StringifyOptions{ .whitespace = null }, stderr) catch return;
1242 }1293 }
1294};
12431295
1244 pub fn dumpIndent(self: Value, comptime indent: usize) void {1296test "Value.jsonStringify" {
1245 if (indent == 0) {1297 {
1246 self.dump();1298 var buffer: [10]u8 = undefined;
1247 } else {1299 var fbs = std.io.fixedBufferStream(&buffer);
1248 var held = std.debug.getStderrMutex().acquire();1300 try @as(Value, .Null).jsonStringify(.{}, fbs.outStream());
1249 defer held.release();1301 testing.expectEqualSlices(u8, fbs.getWritten(), "null");
1250
1251 const stderr = std.debug.getStderrStream();
1252 self.dumpStreamIndent(indent, stderr, 1024) catch return;
1253 }
1254 }1302 }
12551303 {
1256 pub fn dumpStream(self: @This(), stream: var, comptime max_depth: usize) !void {1304 var buffer: [10]u8 = undefined;
1257 var w = std.json.WriteStream(@TypeOf(stream).Child, max_depth).init(stream);1305 var fbs = std.io.fixedBufferStream(&buffer);
1258 w.newline = "";1306 try (Value{ .Bool = true }).jsonStringify(.{}, fbs.outStream());
1259 w.one_indent = "";1307 testing.expectEqualSlices(u8, fbs.getWritten(), "true");
1260 w.space = "";
1261 try w.emitJson(self);
1262 }1308 }
12631309 {
1264 pub fn dumpStreamIndent(self: @This(), comptime indent: usize, stream: var, comptime max_depth: usize) !void {1310 var buffer: [10]u8 = undefined;
1265 var one_indent = " " ** indent;1311 var fbs = std.io.fixedBufferStream(&buffer);
12661312 try (Value{ .Integer = 42 }).jsonStringify(.{}, fbs.outStream());
1267 var w = std.json.WriteStream(@TypeOf(stream).Child, max_depth).init(stream);1313 testing.expectEqualSlices(u8, fbs.getWritten(), "42");
1268 w.one_indent = one_indent;
1269 try w.emitJson(self);
1270 }1314 }
1271};1315 {
1316 var buffer: [10]u8 = undefined;
1317 var fbs = std.io.fixedBufferStream(&buffer);
1318 try (Value{ .Float = 42 }).jsonStringify(.{}, fbs.outStream());
1319 testing.expectEqualSlices(u8, fbs.getWritten(), "4.2e+01");
1320 }
1321 {
1322 var buffer: [10]u8 = undefined;
1323 var fbs = std.io.fixedBufferStream(&buffer);
1324 try (Value{ .String = "weeee" }).jsonStringify(.{}, fbs.outStream());
1325 testing.expectEqualSlices(u8, fbs.getWritten(), "\"weeee\"");
1326 }
1327 {
1328 var buffer: [10]u8 = undefined;
1329 var fbs = std.io.fixedBufferStream(&buffer);
1330 try (Value{
1331 .Array = Array.fromOwnedSlice(undefined, &[_]Value{
1332 .{ .Integer = 1 },
1333 .{ .Integer = 2 },
1334 .{ .Integer = 3 },
1335 }),
1336 }).jsonStringify(.{}, fbs.outStream());
1337 testing.expectEqualSlices(u8, fbs.getWritten(), "[1,2,3]");
1338 }
1339 {
1340 var buffer: [10]u8 = undefined;
1341 var fbs = std.io.fixedBufferStream(&buffer);
1342 var obj = ObjectMap.init(testing.allocator);
1343 defer obj.deinit();
1344 try obj.putNoClobber("a", .{ .String = "b" });
1345 try (Value{ .Object = obj }).jsonStringify(.{}, fbs.outStream());
1346 testing.expectEqualSlices(u8, fbs.getWritten(), "{\"a\":\"b\"}");
1347 }
1348}
12721349
1273pub const ParseOptions = struct {1350pub const ParseOptions = struct {
1274 allocator: ?*Allocator = null,1351 allocator: ?*Allocator = null,
...@@ -1658,9 +1735,6 @@ test "parse into tagged union" {...@@ -1658,9 +1735,6 @@ test "parse into tagged union" {
1658}1735}
16591736
1660test "parseFree descends into tagged union" {1737test "parseFree descends into tagged union" {
1661 // tagged unions are broken on arm64: https://github.com/ziglang/zig/issues/4492
1662 if (std.builtin.arch == .aarch64) return error.SkipZigTest;
1663
1664 var fail_alloc = testing.FailingAllocator.init(testing.allocator, 1);1738 var fail_alloc = testing.FailingAllocator.init(testing.allocator, 1);
1665 const options = ParseOptions{ .allocator = &fail_alloc.allocator };1739 const options = ParseOptions{ .allocator = &fail_alloc.allocator };
1666 const T = union(enum) {1740 const T = union(enum) {
...@@ -1947,7 +2021,7 @@ pub const Parser = struct {...@@ -1947,7 +2021,7 @@ pub const Parser = struct {
1947 }2021 }
19482022
1949 fn pushToParent(p: *Parser, value: *const Value) !void {2023 fn pushToParent(p: *Parser, value: *const Value) !void {
1950 switch (p.stack.toSlice()[p.stack.len - 1]) {2024 switch (p.stack.span()[p.stack.len - 1]) {
1951 // Object Parent -> [ ..., object, <key>, value ]2025 // Object Parent -> [ ..., object, <key>, value ]
1952 Value.String => |key| {2026 Value.String => |key| {
1953 _ = p.stack.pop();2027 _ = p.stack.pop();
...@@ -2244,11 +2318,86 @@ test "string copy option" {...@@ -2244,11 +2318,86 @@ test "string copy option" {
2244}2318}
22452319
2246pub const StringifyOptions = struct {2320pub const StringifyOptions = struct {
2247 // TODO: indentation options?2321 pub const Whitespace = struct {
2248 // TODO: make escaping '/' in strings optional?2322 /// How many indentation levels deep are we?
2249 // TODO: allow picking if []u8 is string or array?2323 indent_level: usize = 0,
2324
2325 pub const Indentation = union(enum) {
2326 Space: u8,
2327 Tab: void,
2328 };
2329
2330 /// What character(s) should be used for indentation?
2331 indent: Indentation = Indentation{ .Space = 4 },
2332
2333 fn outputIndent(
2334 whitespace: @This(),
2335 out_stream: var,
2336 ) @TypeOf(out_stream).Error!void {
2337 var char: u8 = undefined;
2338 var n_chars: usize = undefined;
2339 switch (whitespace.indent) {
2340 .Space => |n_spaces| {
2341 char = ' ';
2342 n_chars = n_spaces;
2343 },
2344 .Tab => {
2345 char = '\t';
2346 n_chars = 1;
2347 },
2348 }
2349 n_chars *= whitespace.indent_level;
2350 try out_stream.writeByteNTimes(char, n_chars);
2351 }
2352
2353 /// After a colon, should whitespace be inserted?
2354 separator: bool = true,
2355 };
2356
2357 /// Controls the whitespace emitted
2358 whitespace: ?Whitespace = null,
2359
2360 /// Should []u8 be serialised as a string? or an array?
2361 pub const StringOptions = union(enum) {
2362 Array,
2363
2364 /// String output options
2365 const StringOutputOptions = struct {
2366 /// Should '/' be escaped in strings?
2367 escape_solidus: bool = false,
2368
2369 /// Should unicode characters be escaped in strings?
2370 escape_unicode: bool = false,
2371 };
2372 String: StringOutputOptions,
2373 };
2374
2375 string: StringOptions = StringOptions{ .String = .{} },
2250};2376};
22512377
2378fn outputUnicodeEscape(
2379 codepoint: u21,
2380 out_stream: var,
2381) !void {
2382 if (codepoint <= 0xFFFF) {
2383 // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),
2384 // then it may be represented as a six-character sequence: a reverse solidus, followed
2385 // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.
2386 try out_stream.writeAll("\\u");
2387 try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2388 } else {
2389 assert(codepoint <= 0x10FFFF);
2390 // To escape an extended character that is not in the Basic Multilingual Plane,
2391 // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.
2392 const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
2393 const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
2394 try out_stream.writeAll("\\u");
2395 try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2396 try out_stream.writeAll("\\u");
2397 try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2398 }
2399}
2400
2252pub fn stringify(2401pub fn stringify(
2253 value: var,2402 value: var,
2254 options: StringifyOptions,2403 options: StringifyOptions,
...@@ -2265,11 +2414,14 @@ pub fn stringify(...@@ -2265,11 +2414,14 @@ pub fn stringify(
2265 .Bool => {2414 .Bool => {
2266 return out_stream.writeAll(if (value) "true" else "false");2415 return out_stream.writeAll(if (value) "true" else "false");
2267 },2416 },
2417 .Null => {
2418 return out_stream.writeAll("null");
2419 },
2268 .Optional => {2420 .Optional => {
2269 if (value) |payload| {2421 if (value) |payload| {
2270 return try stringify(payload, options, out_stream);2422 return try stringify(payload, options, out_stream);
2271 } else {2423 } else {
2272 return out_stream.writeAll("null");2424 return try stringify(null, options, out_stream);
2273 }2425 }
2274 },2426 },
2275 .Enum => {2427 .Enum => {
...@@ -2300,8 +2452,12 @@ pub fn stringify(...@@ -2300,8 +2452,12 @@ pub fn stringify(
2300 return value.jsonStringify(options, out_stream);2452 return value.jsonStringify(options, out_stream);
2301 }2453 }
23022454
2303 try out_stream.writeAll("{");2455 try out_stream.writeByte('{');
2304 comptime var field_output = false;2456 comptime var field_output = false;
2457 var child_options = options;
2458 if (child_options.whitespace) |*child_whitespace| {
2459 child_whitespace.indent_level += 1;
2460 }
2305 inline for (S.fields) |Field, field_i| {2461 inline for (S.fields) |Field, field_i| {
2306 // don't include void fields2462 // don't include void fields
2307 if (Field.field_type == void) continue;2463 if (Field.field_type == void) continue;
...@@ -2309,14 +2465,28 @@ pub fn stringify(...@@ -2309,14 +2465,28 @@ pub fn stringify(
2309 if (!field_output) {2465 if (!field_output) {
2310 field_output = true;2466 field_output = true;
2311 } else {2467 } else {
2312 try out_stream.writeAll(",");2468 try out_stream.writeByte(',');
2469 }
2470 if (child_options.whitespace) |child_whitespace| {
2471 try out_stream.writeByte('\n');
2472 try child_whitespace.outputIndent(out_stream);
2313 }2473 }
2314
2315 try stringify(Field.name, options, out_stream);2474 try stringify(Field.name, options, out_stream);
2316 try out_stream.writeAll(":");2475 try out_stream.writeByte(':');
2317 try stringify(@field(value, Field.name), options, out_stream);2476 if (child_options.whitespace) |child_whitespace| {
2477 if (child_whitespace.separator) {
2478 try out_stream.writeByte(' ');
2479 }
2480 }
2481 try stringify(@field(value, Field.name), child_options, out_stream);
2482 }
2483 if (field_output) {
2484 if (options.whitespace) |whitespace| {
2485 try out_stream.writeByte('\n');
2486 try whitespace.outputIndent(out_stream);
2487 }
2318 }2488 }
2319 try out_stream.writeAll("}");2489 try out_stream.writeByte('}');
2320 return;2490 return;
2321 },2491 },
2322 .Pointer => |ptr_info| switch (ptr_info.size) {2492 .Pointer => |ptr_info| switch (ptr_info.size) {
...@@ -2332,17 +2502,26 @@ pub fn stringify(...@@ -2332,17 +2502,26 @@ pub fn stringify(
2332 },2502 },
2333 // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972)2503 // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972)
2334 .Slice => {2504 .Slice => {
2335 if (ptr_info.child == u8 and std.unicode.utf8ValidateSlice(value)) {2505 if (ptr_info.child == u8 and options.string == .String and std.unicode.utf8ValidateSlice(value)) {
2336 try out_stream.writeAll("\"");2506 try out_stream.writeByte('\"');
2337 var i: usize = 0;2507 var i: usize = 0;
2338 while (i < value.len) : (i += 1) {2508 while (i < value.len) : (i += 1) {
2339 switch (value[i]) {2509 switch (value[i]) {
2340 // normal ascii characters2510 // normal ascii character
2341 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => try out_stream.writeAll(value[i .. i + 1]),2511 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => |c| try out_stream.writeByte(c),
2342 // control characters with short escapes2512 // only 2 characters that *must* be escaped
2343 '\\' => try out_stream.writeAll("\\\\"),2513 '\\' => try out_stream.writeAll("\\\\"),
2344 '\"' => try out_stream.writeAll("\\\""),2514 '\"' => try out_stream.writeAll("\\\""),
2345 '/' => try out_stream.writeAll("\\/"),2515 // solidus is optional to escape
2516 '/' => {
2517 if (options.string.String.escape_solidus) {
2518 try out_stream.writeAll("\\/");
2519 } else {
2520 try out_stream.writeByte('\\');
2521 }
2522 },
2523 // control characters with short escapes
2524 // TODO: option to switch between unicode and 'short' forms?
2346 0x8 => try out_stream.writeAll("\\b"),2525 0x8 => try out_stream.writeAll("\\b"),
2347 0xC => try out_stream.writeAll("\\f"),2526 0xC => try out_stream.writeAll("\\f"),
2348 '\n' => try out_stream.writeAll("\\n"),2527 '\n' => try out_stream.writeAll("\\n"),
...@@ -2350,39 +2529,43 @@ pub fn stringify(...@@ -2350,39 +2529,43 @@ pub fn stringify(
2350 '\t' => try out_stream.writeAll("\\t"),2529 '\t' => try out_stream.writeAll("\\t"),
2351 else => {2530 else => {
2352 const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;2531 const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;
2353 const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;2532 // control characters (only things left with 1 byte length) should always be printed as unicode escapes
2354 if (codepoint <= 0xFFFF) {2533 if (ulen == 1 or options.string.String.escape_unicode) {
2355 // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),2534 const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;
2356 // then it may be represented as a six-character sequence: a reverse solidus, followed2535 try outputUnicodeEscape(codepoint, out_stream);
2357 // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.
2358 try out_stream.writeAll("\\u");
2359 try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2360 } else {2536 } else {
2361 // To escape an extended character that is not in the Basic Multilingual Plane,2537 try out_stream.writeAll(value[i .. i + ulen]);
2362 // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.
2363 const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
2364 const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
2365 try out_stream.writeAll("\\u");
2366 try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2367 try out_stream.writeAll("\\u");
2368 try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2369 }2538 }
2370 i += ulen - 1;2539 i += ulen - 1;
2371 },2540 },
2372 }2541 }
2373 }2542 }
2374 try out_stream.writeAll("\"");2543 try out_stream.writeByte('\"');
2375 return;2544 return;
2376 }2545 }
23772546
2378 try out_stream.writeAll("[");2547 try out_stream.writeByte('[');
2548 var child_options = options;
2549 if (child_options.whitespace) |*whitespace| {
2550 whitespace.indent_level += 1;
2551 }
2379 for (value) |x, i| {2552 for (value) |x, i| {
2380 if (i != 0) {2553 if (i != 0) {
2381 try out_stream.writeAll(",");2554 try out_stream.writeByte(',');
2555 }
2556 if (child_options.whitespace) |child_whitespace| {
2557 try out_stream.writeByte('\n');
2558 try child_whitespace.outputIndent(out_stream);
2382 }2559 }
2383 try stringify(x, options, out_stream);2560 try stringify(x, child_options, out_stream);
2384 }2561 }
2385 try out_stream.writeAll("]");2562 if (value.len != 0) {
2563 if (options.whitespace) |whitespace| {
2564 try out_stream.writeByte('\n');
2565 try whitespace.outputIndent(out_stream);
2566 }
2567 }
2568 try out_stream.writeByte(']');
2386 return;2569 return;
2387 },2570 },
2388 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),2571 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
...@@ -2393,7 +2576,7 @@ pub fn stringify(...@@ -2393,7 +2576,7 @@ pub fn stringify(
2393 unreachable;2576 unreachable;
2394}2577}
23952578
2396fn teststringify(expected: []const u8, value: var) !void {2579fn teststringify(expected: []const u8, value: var, options: StringifyOptions) !void {
2397 const ValidationOutStream = struct {2580 const ValidationOutStream = struct {
2398 const Self = @This();2581 const Self = @This();
2399 pub const OutStream = std.io.OutStream(*Self, Error, write);2582 pub const OutStream = std.io.OutStream(*Self, Error, write);
...@@ -2445,55 +2628,105 @@ fn teststringify(expected: []const u8, value: var) !void {...@@ -2445,55 +2628,105 @@ fn teststringify(expected: []const u8, value: var) !void {
2445 };2628 };
24462629
2447 var vos = ValidationOutStream.init(expected);2630 var vos = ValidationOutStream.init(expected);
2448 try stringify(value, StringifyOptions{}, vos.outStream());2631 try stringify(value, options, vos.outStream());
2449 if (vos.expected_remaining.len > 0) return error.NotEnoughData;2632 if (vos.expected_remaining.len > 0) return error.NotEnoughData;
2450}2633}
24512634
2452test "stringify basic types" {2635test "stringify basic types" {
2453 try teststringify("false", false);2636 try teststringify("false", false, StringifyOptions{});
2454 try teststringify("true", true);2637 try teststringify("true", true, StringifyOptions{});
2455 try teststringify("null", @as(?u8, null));2638 try teststringify("null", @as(?u8, null), StringifyOptions{});
2456 try teststringify("null", @as(?*u32, null));2639 try teststringify("null", @as(?*u32, null), StringifyOptions{});
2457 try teststringify("42", 42);2640 try teststringify("42", 42, StringifyOptions{});
2458 try teststringify("4.2e+01", 42.0);2641 try teststringify("4.2e+01", 42.0, StringifyOptions{});
2459 try teststringify("42", @as(u8, 42));2642 try teststringify("42", @as(u8, 42), StringifyOptions{});
2460 try teststringify("42", @as(u128, 42));2643 try teststringify("42", @as(u128, 42), StringifyOptions{});
2461 try teststringify("4.2e+01", @as(f32, 42));2644 try teststringify("4.2e+01", @as(f32, 42), StringifyOptions{});
2462 try teststringify("4.2e+01", @as(f64, 42));2645 try teststringify("4.2e+01", @as(f64, 42), StringifyOptions{});
2463}2646}
24642647
2465test "stringify string" {2648test "stringify string" {
2466 try teststringify("\"hello\"", "hello");2649 try teststringify("\"hello\"", "hello", StringifyOptions{});
2467 try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r");2650 try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{});
2468 try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}");2651 try teststringify("\"with\\nescapes\\r\"", "with\nescapes\r", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2469 try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}");2652 try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{});
2470 try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}");2653 try teststringify("\"with unicode\\u0001\"", "with unicode\u{1}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2471 try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}");2654 try teststringify("\"with unicode\u{80}\"", "with unicode\u{80}", StringifyOptions{});
2472 try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}");2655 try teststringify("\"with unicode\\u0080\"", "with unicode\u{80}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2473 try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}");2656 try teststringify("\"with unicode\u{FF}\"", "with unicode\u{FF}", StringifyOptions{});
2474 try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}");2657 try teststringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2475 try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}");2658 try teststringify("\"with unicode\u{100}\"", "with unicode\u{100}", StringifyOptions{});
2476 try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}");2659 try teststringify("\"with unicode\\u0100\"", "with unicode\u{100}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2660 try teststringify("\"with unicode\u{800}\"", "with unicode\u{800}", StringifyOptions{});
2661 try teststringify("\"with unicode\\u0800\"", "with unicode\u{800}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2662 try teststringify("\"with unicode\u{8000}\"", "with unicode\u{8000}", StringifyOptions{});
2663 try teststringify("\"with unicode\\u8000\"", "with unicode\u{8000}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2664 try teststringify("\"with unicode\u{D799}\"", "with unicode\u{D799}", StringifyOptions{});
2665 try teststringify("\"with unicode\\ud799\"", "with unicode\u{D799}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2666 try teststringify("\"with unicode\u{10000}\"", "with unicode\u{10000}", StringifyOptions{});
2667 try teststringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2668 try teststringify("\"with unicode\u{10FFFF}\"", "with unicode\u{10FFFF}", StringifyOptions{});
2669 try teststringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
2477}2670}
24782671
2479test "stringify tagged unions" {2672test "stringify tagged unions" {
2480 try teststringify("42", union(enum) {2673 try teststringify("42", union(enum) {
2481 Foo: u32,2674 Foo: u32,
2482 Bar: bool,2675 Bar: bool,
2483 }{ .Foo = 42 });2676 }{ .Foo = 42 }, StringifyOptions{});
2484}2677}
24852678
2486test "stringify struct" {2679test "stringify struct" {
2487 try teststringify("{\"foo\":42}", struct {2680 try teststringify("{\"foo\":42}", struct {
2488 foo: u32,2681 foo: u32,
2489 }{ .foo = 42 });2682 }{ .foo = 42 }, StringifyOptions{});
2683}
2684
2685test "stringify struct with indentation" {
2686 try teststringify(
2687 \\{
2688 \\ "foo": 42,
2689 \\ "bar": [
2690 \\ 1,
2691 \\ 2,
2692 \\ 3
2693 \\ ]
2694 \\}
2695 ,
2696 struct {
2697 foo: u32,
2698 bar: [3]u32,
2699 }{
2700 .foo = 42,
2701 .bar = .{ 1, 2, 3 },
2702 },
2703 StringifyOptions{
2704 .whitespace = .{},
2705 },
2706 );
2707 try teststringify(
2708 "{\n\t\"foo\":42,\n\t\"bar\":[\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n}",
2709 struct {
2710 foo: u32,
2711 bar: [3]u32,
2712 }{
2713 .foo = 42,
2714 .bar = .{ 1, 2, 3 },
2715 },
2716 StringifyOptions{
2717 .whitespace = .{
2718 .indent = .Tab,
2719 .separator = false,
2720 },
2721 },
2722 );
2490}2723}
24912724
2492test "stringify struct with void field" {2725test "stringify struct with void field" {
2493 try teststringify("{\"foo\":42}", struct {2726 try teststringify("{\"foo\":42}", struct {
2494 foo: u32,2727 foo: u32,
2495 bar: void = {},2728 bar: void = {},
2496 }{ .foo = 42 });2729 }{ .foo = 42 }, StringifyOptions{});
2497}2730}
24982731
2499test "stringify array of structs" {2732test "stringify array of structs" {
...@@ -2504,7 +2737,7 @@ test "stringify array of structs" {...@@ -2504,7 +2737,7 @@ test "stringify array of structs" {
2504 MyStruct{ .foo = 42 },2737 MyStruct{ .foo = 42 },
2505 MyStruct{ .foo = 100 },2738 MyStruct{ .foo = 100 },
2506 MyStruct{ .foo = 1000 },2739 MyStruct{ .foo = 1000 },
2507 });2740 }, StringifyOptions{});
2508}2741}
25092742
2510test "stringify struct with custom stringifier" {2743test "stringify struct with custom stringifier" {
...@@ -2518,7 +2751,7 @@ test "stringify struct with custom stringifier" {...@@ -2518,7 +2751,7 @@ test "stringify struct with custom stringifier" {
2518 ) !void {2751 ) !void {
2519 try out_stream.writeAll("[\"something special\",");2752 try out_stream.writeAll("[\"something special\",");
2520 try stringify(42, options, out_stream);2753 try stringify(42, options, out_stream);
2521 try out_stream.writeAll("]");2754 try out_stream.writeByte(']');
2522 }2755 }
2523 }{ .foo = 42 });2756 }{ .foo = 42 }, StringifyOptions{});
2524}2757}
lib/std/json/test.zig+3-5
...@@ -1751,11 +1751,9 @@ test "i_number_double_huge_neg_exp" {...@@ -1751,11 +1751,9 @@ test "i_number_double_huge_neg_exp" {
1751}1751}
17521752
1753test "i_number_huge_exp" {1753test "i_number_huge_exp" {
1754 return error.SkipZigTest;1754 any(
1755 // FIXME Integer overflow in parseFloat1755 \\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
1756 // any(1756 );
1757 // \\[0.4e00669999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999969999999006]
1758 // );
1759}1757}
17601758
1761test "i_number_neg_int_huge_exp" {1759test "i_number_neg_int_huge_exp" {
lib/std/json/write_stream.zig+27-59
...@@ -21,14 +21,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -21,14 +21,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
2121
22 pub const Stream = OutStream;22 pub const Stream = OutStream;
2323
24 /// The string used for indenting.24 whitespace: std.json.StringifyOptions.Whitespace = std.json.StringifyOptions.Whitespace{
25 one_indent: []const u8 = " ",25 .indent_level = 0,
2626 .indent = .{ .Space = 1 },
27 /// The string used as a newline character.27 },
28 newline: []const u8 = "\n",
29
30 /// The string used as spacing.
31 space: []const u8 = " ",
3228
33 stream: OutStream,29 stream: OutStream,
34 state_index: usize,30 state_index: usize,
...@@ -49,12 +45,14 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -49,12 +45,14 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
49 assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField45 assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField
50 try self.stream.writeByte('[');46 try self.stream.writeByte('[');
51 self.state[self.state_index] = State.ArrayStart;47 self.state[self.state_index] = State.ArrayStart;
48 self.whitespace.indent_level += 1;
52 }49 }
5350
54 pub fn beginObject(self: *Self) !void {51 pub fn beginObject(self: *Self) !void {
55 assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField52 assert(self.state[self.state_index] == State.Value); // need to call arrayElem or objectField
56 try self.stream.writeByte('{');53 try self.stream.writeByte('{');
57 self.state[self.state_index] = State.ObjectStart;54 self.state[self.state_index] = State.ObjectStart;
55 self.whitespace.indent_level += 1;
58 }56 }
5957
60 pub fn arrayElem(self: *Self) !void {58 pub fn arrayElem(self: *Self) !void {
...@@ -90,8 +88,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -90,8 +88,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
90 self.pushState(.Value);88 self.pushState(.Value);
91 try self.indent();89 try self.indent();
92 try self.writeEscapedString(name);90 try self.writeEscapedString(name);
93 try self.stream.writeAll(":");91 try self.stream.writeByte(':');
94 try self.stream.writeAll(self.space);92 if (self.whitespace.separator) {
93 try self.stream.writeByte(' ');
94 }
95 },95 },
96 }96 }
97 }97 }
...@@ -103,10 +103,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -103,10 +103,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
103 .ObjectStart => unreachable,103 .ObjectStart => unreachable,
104 .Object => unreachable,104 .Object => unreachable,
105 .ArrayStart => {105 .ArrayStart => {
106 self.whitespace.indent_level -= 1;
106 try self.stream.writeByte(']');107 try self.stream.writeByte(']');
107 self.popState();108 self.popState();
108 },109 },
109 .Array => {110 .Array => {
111 self.whitespace.indent_level -= 1;
110 try self.indent();112 try self.indent();
111 self.popState();113 self.popState();
112 try self.stream.writeByte(']');114 try self.stream.writeByte(']');
...@@ -121,10 +123,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -121,10 +123,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
121 .ArrayStart => unreachable,123 .ArrayStart => unreachable,
122 .Array => unreachable,124 .Array => unreachable,
123 .ObjectStart => {125 .ObjectStart => {
126 self.whitespace.indent_level -= 1;
124 try self.stream.writeByte('}');127 try self.stream.writeByte('}');
125 self.popState();128 self.popState();
126 },129 },
127 .Object => {130 .Object => {
131 self.whitespace.indent_level -= 1;
128 try self.indent();132 try self.indent();
129 self.popState();133 self.popState();
130 try self.stream.writeByte('}');134 try self.stream.writeByte('}');
...@@ -134,17 +138,13 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -134,17 +138,13 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
134138
135 pub fn emitNull(self: *Self) !void {139 pub fn emitNull(self: *Self) !void {
136 assert(self.state[self.state_index] == State.Value);140 assert(self.state[self.state_index] == State.Value);
137 try self.stream.writeAll("null");141 try self.stringify(null);
138 self.popState();142 self.popState();
139 }143 }
140144
141 pub fn emitBool(self: *Self, value: bool) !void {145 pub fn emitBool(self: *Self, value: bool) !void {
142 assert(self.state[self.state_index] == State.Value);146 assert(self.state[self.state_index] == State.Value);
143 if (value) {147 try self.stringify(value);
144 try self.stream.writeAll("true");
145 } else {
146 try self.stream.writeAll("false");
147 }
148 self.popState();148 self.popState();
149 }149 }
150150
...@@ -185,57 +185,19 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -185,57 +185,19 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
185 }185 }
186186
187 fn writeEscapedString(self: *Self, string: []const u8) !void {187 fn writeEscapedString(self: *Self, string: []const u8) !void {
188 try self.stream.writeByte('"');188 assert(std.unicode.utf8ValidateSlice(string));
189 for (string) |s| {189 try self.stringify(string);
190 switch (s) {
191 '"' => try self.stream.writeAll("\\\""),
192 '\t' => try self.stream.writeAll("\\t"),
193 '\r' => try self.stream.writeAll("\\r"),
194 '\n' => try self.stream.writeAll("\\n"),
195 8 => try self.stream.writeAll("\\b"),
196 12 => try self.stream.writeAll("\\f"),
197 '\\' => try self.stream.writeAll("\\\\"),
198 else => try self.stream.writeByte(s),
199 }
200 }
201 try self.stream.writeByte('"');
202 }190 }
203191
204 /// Writes the complete json into the output stream192 /// Writes the complete json into the output stream
205 pub fn emitJson(self: *Self, json: std.json.Value) Stream.Error!void {193 pub fn emitJson(self: *Self, json: std.json.Value) Stream.Error!void {
206 switch (json) {194 try self.stringify(json);
207 .Null => try self.emitNull(),
208 .Bool => |inner| try self.emitBool(inner),
209 .Integer => |inner| try self.emitNumber(inner),
210 .Float => |inner| try self.emitNumber(inner),
211 .String => |inner| try self.emitString(inner),
212 .Array => |inner| {
213 try self.beginArray();
214 for (inner.toSliceConst()) |elem| {
215 try self.arrayElem();
216 try self.emitJson(elem);
217 }
218 try self.endArray();
219 },
220 .Object => |inner| {
221 try self.beginObject();
222 var it = inner.iterator();
223 while (it.next()) |entry| {
224 try self.objectField(entry.key);
225 try self.emitJson(entry.value);
226 }
227 try self.endObject();
228 },
229 }
230 }195 }
231196
232 fn indent(self: *Self) !void {197 fn indent(self: *Self) !void {
233 assert(self.state_index >= 1);198 assert(self.state_index >= 1);
234 try self.stream.writeAll(self.newline);199 try self.stream.writeByte('\n');
235 var i: usize = 0;200 try self.whitespace.outputIndent(self.stream);
236 while (i < self.state_index - 1) : (i += 1) {
237 try self.stream.writeAll(self.one_indent);
238 }
239 }201 }
240202
241 fn pushState(self: *Self, state: State) void {203 fn pushState(self: *Self, state: State) void {
...@@ -246,6 +208,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -246,6 +208,12 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
246 fn popState(self: *Self) void {208 fn popState(self: *Self) void {
247 self.state_index -= 1;209 self.state_index -= 1;
248 }210 }
211
212 fn stringify(self: *Self, value: var) !void {
213 try std.json.stringify(value, std.json.StringifyOptions{
214 .whitespace = self.whitespace,
215 }, self.stream);
216 }
249 };217 };
250}218}
251219
lib/std/mem.zig+51-28
...@@ -341,11 +341,7 @@ pub fn zeroes(comptime T: type) T {...@@ -341,11 +341,7 @@ pub fn zeroes(comptime T: type) T {
341 }341 }
342 },342 },
343 .Array => |info| {343 .Array => |info| {
344 var array: T = undefined;344 return [_]info.child{zeroes(info.child)} ** info.len;
345 for (array) |*element| {
346 element.* = zeroes(info.child);
347 }
348 return array;
349 },345 },
350 .Vector,346 .Vector,
351 .ErrorUnion,347 .ErrorUnion,
...@@ -496,15 +492,8 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {...@@ -496,15 +492,8 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
496 return true;492 return true;
497}493}
498494
499/// Deprecated. Use `spanZ`.495pub const toSliceConst = @compileError("deprecated; use std.mem.spanZ");
500pub fn toSliceConst(comptime T: type, ptr: [*:0]const T) [:0]const T {496pub const toSlice = @compileError("deprecated; use std.mem.spanZ");
501 return ptr[0..lenZ(ptr) :0];
502}
503
504/// Deprecated. Use `spanZ`.
505pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {
506 return ptr[0..lenZ(ptr) :0];
507}
508497
509/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and498/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and
510/// returns a slice. If there is a sentinel on the input type, there will be a499/// returns a slice. If there is a sentinel on the input type, there will be a
...@@ -512,36 +501,54 @@ pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {...@@ -512,36 +501,54 @@ pub fn toSlice(comptime T: type, ptr: [*:0]T) [:0]T {
512/// the constness of the input type. `[*c]` pointers are assumed to be 0-terminated,501/// the constness of the input type. `[*c]` pointers are assumed to be 0-terminated,
513/// and assumed to not allow null.502/// and assumed to not allow null.
514pub fn Span(comptime T: type) type {503pub fn Span(comptime T: type) type {
515 var ptr_info = @typeInfo(T).Pointer;504 switch(@typeInfo(T)) {
516 switch (ptr_info.size) {505 .Optional => |optional_info| {
517 .One => switch (@typeInfo(ptr_info.child)) {506 return ?Span(optional_info.child);
518 .Array => |info| {
519 ptr_info.child = info.child;
520 ptr_info.sentinel = info.sentinel;
521 },
522 else => @compileError("invalid type given to std.mem.Span"),
523 },507 },
524 .C => {508 .Pointer => |ptr_info| {
525 ptr_info.sentinel = 0;509 var new_ptr_info = ptr_info;
526 ptr_info.is_allowzero = false;510 switch (ptr_info.size) {
511 .One => switch (@typeInfo(ptr_info.child)) {
512 .Array => |info| {
513 new_ptr_info.child = info.child;
514 new_ptr_info.sentinel = info.sentinel;
515 },
516 else => @compileError("invalid type given to std.mem.Span"),
517 },
518 .C => {
519 new_ptr_info.sentinel = 0;
520 new_ptr_info.is_allowzero = false;
521 },
522 .Many, .Slice => {},
523 }
524 new_ptr_info.size = .Slice;
525 return @Type(std.builtin.TypeInfo{ .Pointer = new_ptr_info });
527 },526 },
528 .Many, .Slice => {},527 else => @compileError("invalid type given to std.mem.Span"),
529 }528 }
530 ptr_info.size = .Slice;
531 return @Type(std.builtin.TypeInfo{ .Pointer = ptr_info });
532}529}
533530
534test "Span" {531test "Span" {
535 testing.expect(Span(*[5]u16) == []u16);532 testing.expect(Span(*[5]u16) == []u16);
533 testing.expect(Span(?*[5]u16) == ?[]u16);
536 testing.expect(Span(*const [5]u16) == []const u16);534 testing.expect(Span(*const [5]u16) == []const u16);
535 testing.expect(Span(?*const [5]u16) == ?[]const u16);
537 testing.expect(Span([]u16) == []u16);536 testing.expect(Span([]u16) == []u16);
537 testing.expect(Span(?[]u16) == ?[]u16);
538 testing.expect(Span([]const u8) == []const u8);538 testing.expect(Span([]const u8) == []const u8);
539 testing.expect(Span(?[]const u8) == ?[]const u8);
539 testing.expect(Span([:1]u16) == [:1]u16);540 testing.expect(Span([:1]u16) == [:1]u16);
541 testing.expect(Span(?[:1]u16) == ?[:1]u16);
540 testing.expect(Span([:1]const u8) == [:1]const u8);542 testing.expect(Span([:1]const u8) == [:1]const u8);
543 testing.expect(Span(?[:1]const u8) == ?[:1]const u8);
541 testing.expect(Span([*:1]u16) == [:1]u16);544 testing.expect(Span([*:1]u16) == [:1]u16);
545 testing.expect(Span(?[*:1]u16) == ?[:1]u16);
542 testing.expect(Span([*:1]const u8) == [:1]const u8);546 testing.expect(Span([*:1]const u8) == [:1]const u8);
547 testing.expect(Span(?[*:1]const u8) == ?[:1]const u8);
543 testing.expect(Span([*c]u16) == [:0]u16);548 testing.expect(Span([*c]u16) == [:0]u16);
549 testing.expect(Span(?[*c]u16) == ?[:0]u16);
544 testing.expect(Span([*c]const u8) == [:0]const u8);550 testing.expect(Span([*c]const u8) == [:0]const u8);
551 testing.expect(Span(?[*c]const u8) == ?[:0]const u8);
545}552}
546553
547/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and554/// Takes a pointer to an array, a sentinel-terminated pointer, or a slice, and
...@@ -552,6 +559,13 @@ test "Span" {...@@ -552,6 +559,13 @@ test "Span" {
552/// When there is both a sentinel and an array length or slice length, the559/// When there is both a sentinel and an array length or slice length, the
553/// length value is used instead of the sentinel.560/// length value is used instead of the sentinel.
554pub fn span(ptr: var) Span(@TypeOf(ptr)) {561pub fn span(ptr: var) Span(@TypeOf(ptr)) {
562 if (@typeInfo(@TypeOf(ptr)) == .Optional) {
563 if (ptr) |non_null| {
564 return span(non_null);
565 } else {
566 return null;
567 }
568 }
555 const Result = Span(@TypeOf(ptr));569 const Result = Span(@TypeOf(ptr));
556 const l = len(ptr);570 const l = len(ptr);
557 if (@typeInfo(Result).Pointer.sentinel) |s| {571 if (@typeInfo(Result).Pointer.sentinel) |s| {
...@@ -566,12 +580,20 @@ test "span" {...@@ -566,12 +580,20 @@ test "span" {
566 const ptr = @as([*:3]u16, array[0..2 :3]);580 const ptr = @as([*:3]u16, array[0..2 :3]);
567 testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));581 testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));
568 testing.expect(eql(u16, span(&array), &[_]u16{ 1, 2, 3, 4, 5 }));582 testing.expect(eql(u16, span(&array), &[_]u16{ 1, 2, 3, 4, 5 }));
583 testing.expectEqual(@as(?[:0]u16, null), span(@as(?[*:0]u16, null)));
569}584}
570585
571/// Same as `span`, except when there is both a sentinel and an array586/// Same as `span`, except when there is both a sentinel and an array
572/// length or slice length, scans the memory for the sentinel value587/// length or slice length, scans the memory for the sentinel value
573/// rather than using the length.588/// rather than using the length.
574pub fn spanZ(ptr: var) Span(@TypeOf(ptr)) {589pub fn spanZ(ptr: var) Span(@TypeOf(ptr)) {
590 if (@typeInfo(@TypeOf(ptr)) == .Optional) {
591 if (ptr) |non_null| {
592 return spanZ(non_null);
593 } else {
594 return null;
595 }
596 }
575 const Result = Span(@TypeOf(ptr));597 const Result = Span(@TypeOf(ptr));
576 const l = lenZ(ptr);598 const l = lenZ(ptr);
577 if (@typeInfo(Result).Pointer.sentinel) |s| {599 if (@typeInfo(Result).Pointer.sentinel) |s| {
...@@ -586,6 +608,7 @@ test "spanZ" {...@@ -586,6 +608,7 @@ test "spanZ" {
586 const ptr = @as([*:3]u16, array[0..2 :3]);608 const ptr = @as([*:3]u16, array[0..2 :3]);
587 testing.expect(eql(u16, spanZ(ptr), &[_]u16{ 1, 2 }));609 testing.expect(eql(u16, spanZ(ptr), &[_]u16{ 1, 2 }));
588 testing.expect(eql(u16, spanZ(&array), &[_]u16{ 1, 2, 3, 4, 5 }));610 testing.expect(eql(u16, spanZ(&array), &[_]u16{ 1, 2, 3, 4, 5 }));
611 testing.expectEqual(@as(?[:0]u16, null), spanZ(@as(?[*:0]u16, null)));
589}612}
590613
591/// Takes a pointer to an array, an array, a sentinel-terminated pointer,614/// Takes a pointer to an array, an array, a sentinel-terminated pointer,
lib/std/net.zig+26-27
...@@ -397,13 +397,12 @@ pub const AddressList = struct {...@@ -397,13 +397,12 @@ pub const AddressList = struct {
397397
398/// All memory allocated with `allocator` will be freed before this function returns.398/// All memory allocated with `allocator` will be freed before this function returns.
399pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16) !fs.File {399pub fn tcpConnectToHost(allocator: *mem.Allocator, name: []const u8, port: u16) !fs.File {
400 const list = getAddressList(allocator, name, port);400 const list = try getAddressList(allocator, name, port);
401 defer list.deinit();401 defer list.deinit();
402402
403 const addrs = list.addrs.toSliceConst();403 if (list.addrs.len == 0) return error.UnknownHostName;
404 if (addrs.len == 0) return error.UnknownHostName;
405404
406 return tcpConnectToAddress(addrs[0], port);405 return tcpConnectToAddress(list.addrs[0]);
407}406}
408407
409pub fn tcpConnectToAddress(address: Address) !fs.File {408pub fn tcpConnectToAddress(address: Address) !fs.File {
...@@ -491,7 +490,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*...@@ -491,7 +490,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
491490
492 if (info.canonname) |n| {491 if (info.canonname) |n| {
493 if (result.canon_name == null) {492 if (result.canon_name == null) {
494 result.canon_name = try mem.dupe(arena, u8, mem.toSliceConst(u8, n));493 result.canon_name = try mem.dupe(arena, u8, mem.spanZ(n));
495 }494 }
496 }495 }
497 i += 1;496 i += 1;
...@@ -505,7 +504,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*...@@ -505,7 +504,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
505 var lookup_addrs = std.ArrayList(LookupAddr).init(allocator);504 var lookup_addrs = std.ArrayList(LookupAddr).init(allocator);
506 defer lookup_addrs.deinit();505 defer lookup_addrs.deinit();
507506
508 var canon = std.Buffer.initNull(arena);507 var canon = std.ArrayListSentineled(u8, 0).initNull(arena);
509 defer canon.deinit();508 defer canon.deinit();
510509
511 try linuxLookupName(&lookup_addrs, &canon, name, family, flags, port);510 try linuxLookupName(&lookup_addrs, &canon, name, family, flags, port);
...@@ -515,7 +514,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*...@@ -515,7 +514,7 @@ pub fn getAddressList(allocator: *mem.Allocator, name: []const u8, port: u16) !*
515 result.canon_name = canon.toOwnedSlice();514 result.canon_name = canon.toOwnedSlice();
516 }515 }
517516
518 for (lookup_addrs.toSliceConst()) |lookup_addr, i| {517 for (lookup_addrs.span()) |lookup_addr, i| {
519 result.addrs[i] = lookup_addr.addr;518 result.addrs[i] = lookup_addr.addr;
520 assert(result.addrs[i].getPort() == port);519 assert(result.addrs[i].getPort() == port);
521 }520 }
...@@ -540,7 +539,7 @@ const DAS_ORDER_SHIFT = 0;...@@ -540,7 +539,7 @@ const DAS_ORDER_SHIFT = 0;
540539
541fn linuxLookupName(540fn linuxLookupName(
542 addrs: *std.ArrayList(LookupAddr),541 addrs: *std.ArrayList(LookupAddr),
543 canon: *std.Buffer,542 canon: *std.ArrayListSentineled(u8, 0),
544 opt_name: ?[]const u8,543 opt_name: ?[]const u8,
545 family: os.sa_family_t,544 family: os.sa_family_t,
546 flags: u32,545 flags: u32,
...@@ -568,7 +567,7 @@ fn linuxLookupName(...@@ -568,7 +567,7 @@ fn linuxLookupName(
568 // No further processing is needed if there are fewer than 2567 // No further processing is needed if there are fewer than 2
569 // results or if there are only IPv4 results.568 // results or if there are only IPv4 results.
570 if (addrs.len == 1 or family == os.AF_INET) return;569 if (addrs.len == 1 or family == os.AF_INET) return;
571 const all_ip4 = for (addrs.toSliceConst()) |addr| {570 const all_ip4 = for (addrs.span()) |addr| {
572 if (addr.addr.any.family != os.AF_INET) break false;571 if (addr.addr.any.family != os.AF_INET) break false;
573 } else true;572 } else true;
574 if (all_ip4) return;573 if (all_ip4) return;
...@@ -580,7 +579,7 @@ fn linuxLookupName(...@@ -580,7 +579,7 @@ fn linuxLookupName(
580 // So far the label/precedence table cannot be customized.579 // So far the label/precedence table cannot be customized.
581 // This implementation is ported from musl libc.580 // This implementation is ported from musl libc.
582 // A more idiomatic "ziggy" implementation would be welcome.581 // A more idiomatic "ziggy" implementation would be welcome.
583 for (addrs.toSlice()) |*addr, i| {582 for (addrs.span()) |*addr, i| {
584 var key: i32 = 0;583 var key: i32 = 0;
585 var sa6: os.sockaddr_in6 = undefined;584 var sa6: os.sockaddr_in6 = undefined;
586 @memset(@ptrCast([*]u8, &sa6), 0, @sizeOf(os.sockaddr_in6));585 @memset(@ptrCast([*]u8, &sa6), 0, @sizeOf(os.sockaddr_in6));
...@@ -645,7 +644,7 @@ fn linuxLookupName(...@@ -645,7 +644,7 @@ fn linuxLookupName(
645 key |= (MAXADDRS - @intCast(i32, i)) << DAS_ORDER_SHIFT;644 key |= (MAXADDRS - @intCast(i32, i)) << DAS_ORDER_SHIFT;
646 addr.sortkey = key;645 addr.sortkey = key;
647 }646 }
648 std.sort.sort(LookupAddr, addrs.toSlice(), addrCmpLessThan);647 std.sort.sort(LookupAddr, addrs.span(), addrCmpLessThan);
649}648}
650649
651const Policy = struct {650const Policy = struct {
...@@ -799,12 +798,12 @@ fn linuxLookupNameFromNull(...@@ -799,12 +798,12 @@ fn linuxLookupNameFromNull(
799798
800fn linuxLookupNameFromHosts(799fn linuxLookupNameFromHosts(
801 addrs: *std.ArrayList(LookupAddr),800 addrs: *std.ArrayList(LookupAddr),
802 canon: *std.Buffer,801 canon: *std.ArrayListSentineled(u8, 0),
803 name: []const u8,802 name: []const u8,
804 family: os.sa_family_t,803 family: os.sa_family_t,
805 port: u16,804 port: u16,
806) !void {805) !void {
807 const file = fs.openFileAbsoluteC("/etc/hosts", .{}) catch |err| switch (err) {806 const file = fs.openFileAbsoluteZ("/etc/hosts", .{}) catch |err| switch (err) {
808 error.FileNotFound,807 error.FileNotFound,
809 error.NotDir,808 error.NotDir,
810 error.AccessDenied,809 error.AccessDenied,
...@@ -869,7 +868,7 @@ pub fn isValidHostName(hostname: []const u8) bool {...@@ -869,7 +868,7 @@ pub fn isValidHostName(hostname: []const u8) bool {
869868
870fn linuxLookupNameFromDnsSearch(869fn linuxLookupNameFromDnsSearch(
871 addrs: *std.ArrayList(LookupAddr),870 addrs: *std.ArrayList(LookupAddr),
872 canon: *std.Buffer,871 canon: *std.ArrayListSentineled(u8, 0),
873 name: []const u8,872 name: []const u8,
874 family: os.sa_family_t,873 family: os.sa_family_t,
875 port: u16,874 port: u16,
...@@ -888,7 +887,7 @@ fn linuxLookupNameFromDnsSearch(...@@ -888,7 +887,7 @@ fn linuxLookupNameFromDnsSearch(
888 const search = if (rc.search.isNull() or dots >= rc.ndots or mem.endsWith(u8, name, "."))887 const search = if (rc.search.isNull() or dots >= rc.ndots or mem.endsWith(u8, name, "."))
889 &[_]u8{}888 &[_]u8{}
890 else889 else
891 rc.search.toSliceConst();890 rc.search.span();
892891
893 var canon_name = name;892 var canon_name = name;
894893
...@@ -901,14 +900,14 @@ fn linuxLookupNameFromDnsSearch(...@@ -901,14 +900,14 @@ fn linuxLookupNameFromDnsSearch(
901 // name is not a CNAME record) and serves as a buffer for passing900 // name is not a CNAME record) and serves as a buffer for passing
902 // the full requested name to name_from_dns.901 // the full requested name to name_from_dns.
903 try canon.resize(canon_name.len);902 try canon.resize(canon_name.len);
904 mem.copy(u8, canon.toSlice(), canon_name);903 mem.copy(u8, canon.span(), canon_name);
905 try canon.appendByte('.');904 try canon.append('.');
906905
907 var tok_it = mem.tokenize(search, " \t");906 var tok_it = mem.tokenize(search, " \t");
908 while (tok_it.next()) |tok| {907 while (tok_it.next()) |tok| {
909 canon.shrink(canon_name.len + 1);908 canon.shrink(canon_name.len + 1);
910 try canon.append(tok);909 try canon.appendSlice(tok);
911 try linuxLookupNameFromDns(addrs, canon, canon.toSliceConst(), family, rc, port);910 try linuxLookupNameFromDns(addrs, canon, canon.span(), family, rc, port);
912 if (addrs.len != 0) return;911 if (addrs.len != 0) return;
913 }912 }
914913
...@@ -918,13 +917,13 @@ fn linuxLookupNameFromDnsSearch(...@@ -918,13 +917,13 @@ fn linuxLookupNameFromDnsSearch(
918917
919const dpc_ctx = struct {918const dpc_ctx = struct {
920 addrs: *std.ArrayList(LookupAddr),919 addrs: *std.ArrayList(LookupAddr),
921 canon: *std.Buffer,920 canon: *std.ArrayListSentineled(u8, 0),
922 port: u16,921 port: u16,
923};922};
924923
925fn linuxLookupNameFromDns(924fn linuxLookupNameFromDns(
926 addrs: *std.ArrayList(LookupAddr),925 addrs: *std.ArrayList(LookupAddr),
927 canon: *std.Buffer,926 canon: *std.ArrayListSentineled(u8, 0),
928 name: []const u8,927 name: []const u8,
929 family: os.sa_family_t,928 family: os.sa_family_t,
930 rc: ResolvConf,929 rc: ResolvConf,
...@@ -979,7 +978,7 @@ const ResolvConf = struct {...@@ -979,7 +978,7 @@ const ResolvConf = struct {
979 attempts: u32,978 attempts: u32,
980 ndots: u32,979 ndots: u32,
981 timeout: u32,980 timeout: u32,
982 search: std.Buffer,981 search: std.ArrayListSentineled(u8, 0),
983 ns: std.ArrayList(LookupAddr),982 ns: std.ArrayList(LookupAddr),
984983
985 fn deinit(rc: *ResolvConf) void {984 fn deinit(rc: *ResolvConf) void {
...@@ -994,14 +993,14 @@ const ResolvConf = struct {...@@ -994,14 +993,14 @@ const ResolvConf = struct {
994fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void {993fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void {
995 rc.* = ResolvConf{994 rc.* = ResolvConf{
996 .ns = std.ArrayList(LookupAddr).init(allocator),995 .ns = std.ArrayList(LookupAddr).init(allocator),
997 .search = std.Buffer.initNull(allocator),996 .search = std.ArrayListSentineled(u8, 0).initNull(allocator),
998 .ndots = 1,997 .ndots = 1,
999 .timeout = 5,998 .timeout = 5,
1000 .attempts = 2,999 .attempts = 2,
1001 };1000 };
1002 errdefer rc.deinit();1001 errdefer rc.deinit();
10031002
1004 const file = fs.openFileAbsoluteC("/etc/resolv.conf", .{}) catch |err| switch (err) {1003 const file = fs.openFileAbsoluteZ("/etc/resolv.conf", .{}) catch |err| switch (err) {
1005 error.FileNotFound,1004 error.FileNotFound,
1006 error.NotDir,1005 error.NotDir,
1007 error.AccessDenied,1006 error.AccessDenied,
...@@ -1080,9 +1079,9 @@ fn resMSendRc(...@@ -1080,9 +1079,9 @@ fn resMSendRc(
1080 defer ns_list.deinit();1079 defer ns_list.deinit();
10811080
1082 try ns_list.resize(rc.ns.len);1081 try ns_list.resize(rc.ns.len);
1083 const ns = ns_list.toSlice();1082 const ns = ns_list.span();
10841083
1085 for (rc.ns.toSliceConst()) |iplit, i| {1084 for (rc.ns.span()) |iplit, i| {
1086 ns[i] = iplit.addr;1085 ns[i] = iplit.addr;
1087 assert(ns[i].getPort() == 53);1086 assert(ns[i].getPort() == 53);
1088 if (iplit.addr.any.family != os.AF_INET) {1087 if (iplit.addr.any.family != os.AF_INET) {
...@@ -1266,7 +1265,7 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8)...@@ -1266,7 +1265,7 @@ fn dnsParseCallback(ctx: dpc_ctx, rr: u8, data: []const u8, packet: []const u8)
1266 var tmp: [256]u8 = undefined;1265 var tmp: [256]u8 = undefined;
1267 // Returns len of compressed name. strlen to get canon name.1266 // Returns len of compressed name. strlen to get canon name.
1268 _ = try os.dn_expand(packet, data, &tmp);1267 _ = try os.dn_expand(packet, data, &tmp);
1269 const canon_name = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &tmp));1268 const canon_name = mem.spanZ(@ptrCast([*:0]const u8, &tmp));
1270 if (isValidHostName(canon_name)) {1269 if (isValidHostName(canon_name)) {
1271 try ctx.canon.replaceContents(canon_name);1270 try ctx.canon.replaceContents(canon_name);
1272 }1271 }
lib/std/os.zig+105-83
...@@ -163,7 +163,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {...@@ -163,7 +163,7 @@ pub fn getrandom(buffer: []u8) GetRandomError!void {
163}163}
164164
165fn getRandomBytesDevURandom(buf: []u8) !void {165fn getRandomBytesDevURandom(buf: []u8) !void {
166 const fd = try openC("/dev/urandom", O_RDONLY | O_CLOEXEC, 0);166 const fd = try openZ("/dev/urandom", O_RDONLY | O_CLOEXEC, 0);
167 defer close(fd);167 defer close(fd);
168168
169 const st = try fstat(fd);169 const st = try fstat(fd);
...@@ -853,13 +853,15 @@ pub const OpenError = error{...@@ -853,13 +853,15 @@ pub const OpenError = error{
853/// TODO support windows853/// TODO support windows
854pub fn open(file_path: []const u8, flags: u32, perm: usize) OpenError!fd_t {854pub fn open(file_path: []const u8, flags: u32, perm: usize) OpenError!fd_t {
855 const file_path_c = try toPosixPath(file_path);855 const file_path_c = try toPosixPath(file_path);
856 return openC(&file_path_c, flags, perm);856 return openZ(&file_path_c, flags, perm);
857}857}
858858
859pub const openC = @compileError("deprecated: renamed to openZ");
860
859/// Open and possibly create a file. Keeps trying if it gets interrupted.861/// Open and possibly create a file. Keeps trying if it gets interrupted.
860/// See also `open`.862/// See also `open`.
861/// TODO support windows863/// TODO support windows
862pub fn openC(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t {864pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t {
863 while (true) {865 while (true) {
864 const rc = system.open(file_path, flags, perm);866 const rc = system.open(file_path, flags, perm);
865 switch (errno(rc)) {867 switch (errno(rc)) {
...@@ -895,14 +897,16 @@ pub fn openC(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t {...@@ -895,14 +897,16 @@ pub fn openC(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t {
895/// TODO support windows897/// TODO support windows
896pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: u32, mode: mode_t) OpenError!fd_t {898pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: u32, mode: mode_t) OpenError!fd_t {
897 const file_path_c = try toPosixPath(file_path);899 const file_path_c = try toPosixPath(file_path);
898 return openatC(dir_fd, &file_path_c, flags, mode);900 return openatZ(dir_fd, &file_path_c, flags, mode);
899}901}
900902
903pub const openatC = @compileError("deprecated: renamed to openatZ");
904
901/// Open and possibly create a file. Keeps trying if it gets interrupted.905/// Open and possibly create a file. Keeps trying if it gets interrupted.
902/// `file_path` is relative to the open directory handle `dir_fd`.906/// `file_path` is relative to the open directory handle `dir_fd`.
903/// See also `openat`.907/// See also `openat`.
904/// TODO support windows908/// TODO support windows
905pub fn openatC(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) OpenError!fd_t {909pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) OpenError!fd_t {
906 while (true) {910 while (true) {
907 const rc = system.openat(dir_fd, file_path, flags, mode);911 const rc = system.openat(dir_fd, file_path, flags, mode);
908 switch (errno(rc)) {912 switch (errno(rc)) {
...@@ -959,8 +963,7 @@ pub const ExecveError = error{...@@ -959,8 +963,7 @@ pub const ExecveError = error{
959 NameTooLong,963 NameTooLong,
960} || UnexpectedError;964} || UnexpectedError;
961965
962/// Deprecated in favor of `execveZ`.966pub const execveC = @compileError("deprecated: use execveZ");
963pub const execveC = execveZ;
964967
965/// Like `execve` except the parameters are null-terminated,968/// Like `execve` except the parameters are null-terminated,
966/// matching the syscall API on all targets. This removes the need for an allocator.969/// matching the syscall API on all targets. This removes the need for an allocator.
...@@ -992,8 +995,7 @@ pub fn execveZ(...@@ -992,8 +995,7 @@ pub fn execveZ(
992 }995 }
993}996}
994997
995/// Deprecated in favor of `execvpeZ`.998pub const execvpeC = @compileError("deprecated in favor of execvpeZ");
996pub const execvpeC = execvpeZ;
997999
998pub const Arg0Expand = enum {1000pub const Arg0Expand = enum {
999 expand,1001 expand,
...@@ -1012,7 +1014,7 @@ pub fn execvpeZ_expandArg0(...@@ -1012,7 +1014,7 @@ pub fn execvpeZ_expandArg0(
1012 },1014 },
1013 envp: [*:null]const ?[*:0]const u8,1015 envp: [*:null]const ?[*:0]const u8,
1014) ExecveError {1016) ExecveError {
1015 const file_slice = mem.toSliceConst(u8, file);1017 const file_slice = mem.spanZ(file);
1016 if (mem.indexOfScalar(u8, file_slice, '/') != null) return execveZ(file, child_argv, envp);1018 if (mem.indexOfScalar(u8, file_slice, '/') != null) return execveZ(file, child_argv, envp);
10171019
1018 const PATH = getenvZ("PATH") orelse "/usr/local/bin:/bin/:/usr/bin";1020 const PATH = getenvZ("PATH") orelse "/usr/local/bin:/bin/:/usr/bin";
...@@ -1076,7 +1078,7 @@ pub fn execvpe_expandArg0(...@@ -1076,7 +1078,7 @@ pub fn execvpe_expandArg0(
1076 mem.set(?[*:0]u8, argv_buf, null);1078 mem.set(?[*:0]u8, argv_buf, null);
1077 defer {1079 defer {
1078 for (argv_buf) |arg| {1080 for (argv_buf) |arg| {
1079 const arg_buf = if (arg) |ptr| mem.toSlice(u8, ptr) else break;1081 const arg_buf = mem.spanZ(arg) orelse break;
1080 allocator.free(arg_buf);1082 allocator.free(arg_buf);
1081 }1083 }
1082 allocator.free(argv_buf);1084 allocator.free(argv_buf);
...@@ -1189,30 +1191,32 @@ pub fn getenv(key: []const u8) ?[]const u8 {...@@ -1189,30 +1191,32 @@ pub fn getenv(key: []const u8) ?[]const u8 {
1189 return null;1191 return null;
1190}1192}
11911193
1192/// Deprecated in favor of `getenvZ`.1194pub const getenvC = @compileError("Deprecated in favor of `getenvZ`");
1193pub const getenvC = getenvZ;
11941195
1195/// Get an environment variable with a null-terminated name.1196/// Get an environment variable with a null-terminated name.
1196/// See also `getenv`.1197/// See also `getenv`.
1197pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {1198pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
1198 if (builtin.link_libc) {1199 if (builtin.link_libc) {
1199 const value = system.getenv(key) orelse return null;1200 const value = system.getenv(key) orelse return null;
1200 return mem.toSliceConst(u8, value);1201 return mem.spanZ(value);
1201 }1202 }
1202 if (builtin.os.tag == .windows) {1203 if (builtin.os.tag == .windows) {
1203 @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.");1204 @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.");
1204 }1205 }
1205 return getenv(mem.toSliceConst(u8, key));1206 return getenv(mem.spanZ(key));
1206}1207}
12071208
1208/// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name.1209/// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name.
1209/// See also `getenv`.1210/// See also `getenv`.
1211/// This function first attempts a case-sensitive lookup. If no match is found, and `key`
1212/// is ASCII, then it attempts a second case-insensitive lookup.
1210pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {1213pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {
1211 if (builtin.os.tag != .windows) {1214 if (builtin.os.tag != .windows) {
1212 @compileError("std.os.getenvW is a Windows-only API");1215 @compileError("std.os.getenvW is a Windows-only API");
1213 }1216 }
1214 const key_slice = mem.toSliceConst(u16, key);1217 const key_slice = mem.spanZ(key);
1215 const ptr = windows.peb().ProcessParameters.Environment;1218 const ptr = windows.peb().ProcessParameters.Environment;
1219 var ascii_match: ?[:0]const u16 = null;
1216 var i: usize = 0;1220 var i: usize = 0;
1217 while (ptr[i] != 0) {1221 while (ptr[i] != 0) {
1218 const key_start = i;1222 const key_start = i;
...@@ -1228,9 +1232,20 @@ pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {...@@ -1228,9 +1232,20 @@ pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {
12281232
1229 if (mem.eql(u16, key_slice, this_key)) return this_value;1233 if (mem.eql(u16, key_slice, this_key)) return this_value;
12301234
1235 ascii_check: {
1236 if (ascii_match != null) break :ascii_check;
1237 if (key_slice.len != this_key.len) break :ascii_check;
1238 for (key_slice) |a_c, key_index| {
1239 const a = math.cast(u8, a_c) catch break :ascii_check;
1240 const b = math.cast(u8, this_key[key_index]) catch break :ascii_check;
1241 if (std.ascii.toLower(a) != std.ascii.toLower(b)) break :ascii_check;
1242 }
1243 ascii_match = this_value;
1244 }
1245
1231 i += 1; // skip over null byte1246 i += 1; // skip over null byte
1232 }1247 }
1233 return null;1248 return ascii_match;
1234}1249}
12351250
1236pub const GetCwdError = error{1251pub const GetCwdError = error{
...@@ -1250,7 +1265,7 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {...@@ -1250,7 +1265,7 @@ pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
1250 break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));1265 break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));
1251 };1266 };
1252 switch (err) {1267 switch (err) {
1253 0 => return mem.toSlice(u8, @ptrCast([*:0]u8, out_buffer.ptr)),1268 0 => return mem.spanZ(@ptrCast([*:0]u8, out_buffer.ptr)),
1254 EFAULT => unreachable,1269 EFAULT => unreachable,
1255 EINVAL => unreachable,1270 EINVAL => unreachable,
1256 ENOENT => return error.CurrentWorkingDirectoryUnlinked,1271 ENOENT => return error.CurrentWorkingDirectoryUnlinked,
...@@ -1288,13 +1303,15 @@ pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!...@@ -1288,13 +1303,15 @@ pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!
1288 } else {1303 } else {
1289 const target_path_c = try toPosixPath(target_path);1304 const target_path_c = try toPosixPath(target_path);
1290 const sym_link_path_c = try toPosixPath(sym_link_path);1305 const sym_link_path_c = try toPosixPath(sym_link_path);
1291 return symlinkC(&target_path_c, &sym_link_path_c);1306 return symlinkZ(&target_path_c, &sym_link_path_c);
1292 }1307 }
1293}1308}
12941309
1310pub const symlinkC = @compileError("deprecated: renamed to symlinkZ");
1311
1295/// This is the same as `symlink` except the parameters are null-terminated pointers.1312/// This is the same as `symlink` except the parameters are null-terminated pointers.
1296/// See also `symlink`.1313/// See also `symlink`.
1297pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void {1314pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void {
1298 if (builtin.os.tag == .windows) {1315 if (builtin.os.tag == .windows) {
1299 const target_path_w = try windows.cStrToPrefixedFileW(target_path);1316 const target_path_w = try windows.cStrToPrefixedFileW(target_path);
1300 const sym_link_path_w = try windows.cStrToPrefixedFileW(sym_link_path);1317 const sym_link_path_w = try windows.cStrToPrefixedFileW(sym_link_path);
...@@ -1323,10 +1340,12 @@ pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLin...@@ -1323,10 +1340,12 @@ pub fn symlinkC(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLin
1323pub fn symlinkat(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {1340pub fn symlinkat(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {
1324 const target_path_c = try toPosixPath(target_path);1341 const target_path_c = try toPosixPath(target_path);
1325 const sym_link_path_c = try toPosixPath(sym_link_path);1342 const sym_link_path_c = try toPosixPath(sym_link_path);
1326 return symlinkatC(target_path_c, newdirfd, sym_link_path_c);1343 return symlinkatZ(target_path_c, newdirfd, sym_link_path_c);
1327}1344}
13281345
1329pub fn symlinkatC(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:0]const u8) SymLinkError!void {1346pub const symlinkatC = @compileError("deprecated: renamed to symlinkatZ");
1347
1348pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:0]const u8) SymLinkError!void {
1330 switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {1349 switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {
1331 0 => return,1350 0 => return,
1332 EFAULT => unreachable,1351 EFAULT => unreachable,
...@@ -1375,12 +1394,14 @@ pub fn unlink(file_path: []const u8) UnlinkError!void {...@@ -1375,12 +1394,14 @@ pub fn unlink(file_path: []const u8) UnlinkError!void {
1375 return windows.DeleteFileW(&file_path_w);1394 return windows.DeleteFileW(&file_path_w);
1376 } else {1395 } else {
1377 const file_path_c = try toPosixPath(file_path);1396 const file_path_c = try toPosixPath(file_path);
1378 return unlinkC(&file_path_c);1397 return unlinkZ(&file_path_c);
1379 }1398 }
1380}1399}
13811400
1401pub const unlinkC = @compileError("deprecated: renamed to unlinkZ");
1402
1382/// Same as `unlink` except the parameter is a null terminated UTF8-encoded string.1403/// Same as `unlink` except the parameter is a null terminated UTF8-encoded string.
1383pub fn unlinkC(file_path: [*:0]const u8) UnlinkError!void {1404pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void {
1384 if (builtin.os.tag == .windows) {1405 if (builtin.os.tag == .windows) {
1385 const file_path_w = try windows.cStrToPrefixedFileW(file_path);1406 const file_path_w = try windows.cStrToPrefixedFileW(file_path);
1386 return windows.DeleteFileW(&file_path_w);1407 return windows.DeleteFileW(&file_path_w);
...@@ -1417,11 +1438,13 @@ pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!vo...@@ -1417,11 +1438,13 @@ pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!vo
1417 return unlinkatW(dirfd, &file_path_w, flags);1438 return unlinkatW(dirfd, &file_path_w, flags);
1418 }1439 }
1419 const file_path_c = try toPosixPath(file_path);1440 const file_path_c = try toPosixPath(file_path);
1420 return unlinkatC(dirfd, &file_path_c, flags);1441 return unlinkatZ(dirfd, &file_path_c, flags);
1421}1442}
14221443
1444pub const unlinkatC = @compileError("deprecated: renamed to unlinkatZ");
1445
1423/// Same as `unlinkat` but `file_path` is a null-terminated string.1446/// Same as `unlinkat` but `file_path` is a null-terminated string.
1424pub fn unlinkatC(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void {1447pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void {
1425 if (builtin.os.tag == .windows) {1448 if (builtin.os.tag == .windows) {
1426 const file_path_w = try windows.cStrToPrefixedFileW(file_path_c);1449 const file_path_w = try windows.cStrToPrefixedFileW(file_path_c);
1427 return unlinkatW(dirfd, &file_path_w, flags);1450 return unlinkatW(dirfd, &file_path_w, flags);
...@@ -1459,7 +1482,7 @@ pub fn unlinkatW(dirfd: fd_t, sub_path_w: [*:0]const u16, flags: u32) UnlinkatEr...@@ -1459,7 +1482,7 @@ pub fn unlinkatW(dirfd: fd_t, sub_path_w: [*:0]const u16, flags: u32) UnlinkatEr
1459 else1482 else
1460 @as(w.ULONG, w.FILE_DELETE_ON_CLOSE | w.FILE_NON_DIRECTORY_FILE);1483 @as(w.ULONG, w.FILE_DELETE_ON_CLOSE | w.FILE_NON_DIRECTORY_FILE);
14611484
1462 const path_len_bytes = @intCast(u16, mem.toSliceConst(u16, sub_path_w).len * 2);1485 const path_len_bytes = @intCast(u16, mem.lenZ(sub_path_w) * 2);
1463 var nt_name = w.UNICODE_STRING{1486 var nt_name = w.UNICODE_STRING{
1464 .Length = path_len_bytes,1487 .Length = path_len_bytes,
1465 .MaximumLength = path_len_bytes,1488 .MaximumLength = path_len_bytes,
...@@ -1543,12 +1566,14 @@ pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {...@@ -1543,12 +1566,14 @@ pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {
1543 } else {1566 } else {
1544 const old_path_c = try toPosixPath(old_path);1567 const old_path_c = try toPosixPath(old_path);
1545 const new_path_c = try toPosixPath(new_path);1568 const new_path_c = try toPosixPath(new_path);
1546 return renameC(&old_path_c, &new_path_c);1569 return renameZ(&old_path_c, &new_path_c);
1547 }1570 }
1548}1571}
15491572
1573pub const renameC = @compileError("deprecated: renamed to renameZ");
1574
1550/// Same as `rename` except the parameters are null-terminated byte arrays.1575/// Same as `rename` except the parameters are null-terminated byte arrays.
1551pub fn renameC(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void {1576pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void {
1552 if (builtin.os.tag == .windows) {1577 if (builtin.os.tag == .windows) {
1553 const old_path_w = try windows.cStrToPrefixedFileW(old_path);1578 const old_path_w = try windows.cStrToPrefixedFileW(old_path);
1554 const new_path_w = try windows.cStrToPrefixedFileW(new_path);1579 const new_path_w = try windows.cStrToPrefixedFileW(new_path);
...@@ -1715,11 +1740,13 @@ pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!v...@@ -1715,11 +1740,13 @@ pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!v
1715 return mkdiratW(dir_fd, &sub_dir_path_w, mode);1740 return mkdiratW(dir_fd, &sub_dir_path_w, mode);
1716 } else {1741 } else {
1717 const sub_dir_path_c = try toPosixPath(sub_dir_path);1742 const sub_dir_path_c = try toPosixPath(sub_dir_path);
1718 return mkdiratC(dir_fd, &sub_dir_path_c, mode);1743 return mkdiratZ(dir_fd, &sub_dir_path_c, mode);
1719 }1744 }
1720}1745}
17211746
1722pub fn mkdiratC(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirError!void {1747pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ");
1748
1749pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
1723 if (builtin.os.tag == .windows) {1750 if (builtin.os.tag == .windows) {
1724 const sub_dir_path_w = try windows.cStrToPrefixedFileW(sub_dir_path);1751 const sub_dir_path_w = try windows.cStrToPrefixedFileW(sub_dir_path);
1725 return mkdiratW(dir_fd, &sub_dir_path_w, mode);1752 return mkdiratW(dir_fd, &sub_dir_path_w, mode);
...@@ -1810,12 +1837,14 @@ pub fn rmdir(dir_path: []const u8) DeleteDirError!void {...@@ -1810,12 +1837,14 @@ pub fn rmdir(dir_path: []const u8) DeleteDirError!void {
1810 return windows.RemoveDirectoryW(&dir_path_w);1837 return windows.RemoveDirectoryW(&dir_path_w);
1811 } else {1838 } else {
1812 const dir_path_c = try toPosixPath(dir_path);1839 const dir_path_c = try toPosixPath(dir_path);
1813 return rmdirC(&dir_path_c);1840 return rmdirZ(&dir_path_c);
1814 }1841 }
1815}1842}
18161843
1844pub const rmdirC = @compileError("deprecated: renamed to rmdirZ");
1845
1817/// Same as `rmdir` except the parameter is null-terminated.1846/// Same as `rmdir` except the parameter is null-terminated.
1818pub fn rmdirC(dir_path: [*:0]const u8) DeleteDirError!void {1847pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void {
1819 if (builtin.os.tag == .windows) {1848 if (builtin.os.tag == .windows) {
1820 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);1849 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
1821 return windows.RemoveDirectoryW(&dir_path_w);1850 return windows.RemoveDirectoryW(&dir_path_w);
...@@ -1857,12 +1886,14 @@ pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {...@@ -1857,12 +1886,14 @@ pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {
1857 @compileError("TODO implement chdir for Windows");1886 @compileError("TODO implement chdir for Windows");
1858 } else {1887 } else {
1859 const dir_path_c = try toPosixPath(dir_path);1888 const dir_path_c = try toPosixPath(dir_path);
1860 return chdirC(&dir_path_c);1889 return chdirZ(&dir_path_c);
1861 }1890 }
1862}1891}
18631892
1893pub const chdirC = @compileError("deprecated: renamed to chdirZ");
1894
1864/// Same as `chdir` except the parameter is null-terminated.1895/// Same as `chdir` except the parameter is null-terminated.
1865pub fn chdirC(dir_path: [*:0]const u8) ChangeCurDirError!void {1896pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void {
1866 if (builtin.os.tag == .windows) {1897 if (builtin.os.tag == .windows) {
1867 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);1898 const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
1868 @compileError("TODO implement chdir for Windows");1899 @compileError("TODO implement chdir for Windows");
...@@ -1919,12 +1950,14 @@ pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {...@@ -1919,12 +1950,14 @@ pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
1919 @compileError("TODO implement readlink for Windows");1950 @compileError("TODO implement readlink for Windows");
1920 } else {1951 } else {
1921 const file_path_c = try toPosixPath(file_path);1952 const file_path_c = try toPosixPath(file_path);
1922 return readlinkC(&file_path_c, out_buffer);1953 return readlinkZ(&file_path_c, out_buffer);
1923 }1954 }
1924}1955}
19251956
1957pub const readlinkC = @compileError("deprecated: renamed to readlinkZ");
1958
1926/// Same as `readlink` except `file_path` is null-terminated.1959/// Same as `readlink` except `file_path` is null-terminated.
1927pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {1960pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
1928 if (builtin.os.tag == .windows) {1961 if (builtin.os.tag == .windows) {
1929 const file_path_w = try windows.cStrToPrefixedFileW(file_path);1962 const file_path_w = try windows.cStrToPrefixedFileW(file_path);
1930 @compileError("TODO implement readlink for Windows");1963 @compileError("TODO implement readlink for Windows");
...@@ -1945,7 +1978,9 @@ pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8...@@ -1945,7 +1978,9 @@ pub fn readlinkC(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8
1945 }1978 }
1946}1979}
19471980
1948pub fn readlinkatC(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {1981pub const readlinkatC = @compileError("deprecated: renamed to readlinkatZ");
1982
1983pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
1949 if (builtin.os.tag == .windows) {1984 if (builtin.os.tag == .windows) {
1950 const file_path_w = try windows.cStrToPrefixedFileW(file_path);1985 const file_path_w = try windows.cStrToPrefixedFileW(file_path);
1951 @compileError("TODO implement readlink for Windows");1986 @compileError("TODO implement readlink for Windows");
...@@ -2044,7 +2079,7 @@ pub fn isatty(handle: fd_t) bool {...@@ -2044,7 +2079,7 @@ pub fn isatty(handle: fd_t) bool {
2044 }2079 }
2045 if (builtin.os.tag == .linux) {2080 if (builtin.os.tag == .linux) {
2046 var wsz: linux.winsize = undefined;2081 var wsz: linux.winsize = undefined;
2047 return linux.syscall3(linux.SYS_ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;2082 return linux.syscall3(.ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
2048 }2083 }
2049 unreachable;2084 unreachable;
2050}2085}
...@@ -2532,14 +2567,7 @@ pub const FStatError = error{...@@ -2532,14 +2567,7 @@ pub const FStatError = error{
2532pub fn fstat(fd: fd_t) FStatError!Stat {2567pub fn fstat(fd: fd_t) FStatError!Stat {
2533 var stat: Stat = undefined;2568 var stat: Stat = undefined;
25342569
2535 const symbol_name = if (comptime std.Target.current.isDarwin())2570 switch (errno(system.fstat(fd, &stat))) {
2536 "fstat$INODE64"
2537 else if (std.Target.current.os.tag == .netbsd)
2538 "__fstat50"
2539 else
2540 "fstat";
2541
2542 switch (errno(@field(system, symbol_name)(fd, &stat))) {
2543 0 => return stat,2571 0 => return stat,
2544 EINVAL => unreachable,2572 EINVAL => unreachable,
2545 EBADF => unreachable, // Always a race condition.2573 EBADF => unreachable, // Always a race condition.
...@@ -2553,10 +2581,12 @@ const FStatAtError = FStatError || error{NameTooLong};...@@ -2553,10 +2581,12 @@ const FStatAtError = FStatError || error{NameTooLong};
25532581
2554pub fn fstatat(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError![]Stat {2582pub fn fstatat(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError![]Stat {
2555 const pathname_c = try toPosixPath(pathname);2583 const pathname_c = try toPosixPath(pathname);
2556 return fstatatC(dirfd, &pathname_c, flags);2584 return fstatatZ(dirfd, &pathname_c, flags);
2557}2585}
25582586
2559pub fn fstatatC(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!Stat {2587pub const fstatatC = @compileError("deprecated: renamed to fstatatZ");
2588
2589pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!Stat {
2560 var stat: Stat = undefined;2590 var stat: Stat = undefined;
2561 switch (errno(system.fstatat(dirfd, pathname, &stat, flags))) {2591 switch (errno(system.fstatat(dirfd, pathname, &stat, flags))) {
2562 0 => return stat,2592 0 => return stat,
...@@ -2668,11 +2698,13 @@ pub const INotifyAddWatchError = error{...@@ -2668,11 +2698,13 @@ pub const INotifyAddWatchError = error{
2668/// add a watch to an initialized inotify instance2698/// add a watch to an initialized inotify instance
2669pub fn inotify_add_watch(inotify_fd: i32, pathname: []const u8, mask: u32) INotifyAddWatchError!i32 {2699pub fn inotify_add_watch(inotify_fd: i32, pathname: []const u8, mask: u32) INotifyAddWatchError!i32 {
2670 const pathname_c = try toPosixPath(pathname);2700 const pathname_c = try toPosixPath(pathname);
2671 return inotify_add_watchC(inotify_fd, &pathname_c, mask);2701 return inotify_add_watchZ(inotify_fd, &pathname_c, mask);
2672}2702}
26732703
2704pub const inotify_add_watchC = @compileError("deprecated: renamed to inotify_add_watchZ");
2705
2674/// Same as `inotify_add_watch` except pathname is null-terminated.2706/// Same as `inotify_add_watch` except pathname is null-terminated.
2675pub fn inotify_add_watchC(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {2707pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {
2676 const rc = system.inotify_add_watch(inotify_fd, pathname, mask);2708 const rc = system.inotify_add_watch(inotify_fd, pathname, mask);
2677 switch (errno(rc)) {2709 switch (errno(rc)) {
2678 0 => return @intCast(i32, rc),2710 0 => return @intCast(i32, rc),
...@@ -2829,11 +2861,10 @@ pub fn access(path: []const u8, mode: u32) AccessError!void {...@@ -2829,11 +2861,10 @@ pub fn access(path: []const u8, mode: u32) AccessError!void {
2829 return;2861 return;
2830 }2862 }
2831 const path_c = try toPosixPath(path);2863 const path_c = try toPosixPath(path);
2832 return accessC(&path_c, mode);2864 return accessZ(&path_c, mode);
2833}2865}
28342866
2835/// Deprecated in favor of `accessZ`.2867pub const accessC = @compileError("Deprecated in favor of `accessZ`");
2836pub const accessC = accessZ;
28372868
2838/// Same as `access` except `path` is null-terminated.2869/// Same as `access` except `path` is null-terminated.
2839pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {2870pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {
...@@ -2920,7 +2951,7 @@ pub fn faccessatW(dirfd: fd_t, sub_path_w: [*:0]const u16, mode: u32, flags: u32...@@ -2920,7 +2951,7 @@ pub fn faccessatW(dirfd: fd_t, sub_path_w: [*:0]const u16, mode: u32, flags: u32
2920 return;2951 return;
2921 }2952 }
29222953
2923 const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) {2954 const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) {
2924 error.Overflow => return error.NameTooLong,2955 error.Overflow => return error.NameTooLong,
2925 };2956 };
2926 var nt_name = windows.UNICODE_STRING{2957 var nt_name = windows.UNICODE_STRING{
...@@ -3019,7 +3050,9 @@ pub fn sysctl(...@@ -3019,7 +3050,9 @@ pub fn sysctl(
3019 }3050 }
3020}3051}
30213052
3022pub fn sysctlbynameC(3053pub const sysctlbynameC = @compileError("deprecated: renamed to sysctlbynameZ");
3054
3055pub fn sysctlbynameZ(
3023 name: [*:0]const u8,3056 name: [*:0]const u8,
3024 oldp: ?*c_void,3057 oldp: ?*c_void,
3025 oldlenp: ?*usize,3058 oldlenp: ?*usize,
...@@ -3224,23 +3257,25 @@ pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathE...@@ -3224,23 +3257,25 @@ pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathE
3224 return realpathW(&pathname_w, out_buffer);3257 return realpathW(&pathname_w, out_buffer);
3225 }3258 }
3226 const pathname_c = try toPosixPath(pathname);3259 const pathname_c = try toPosixPath(pathname);
3227 return realpathC(&pathname_c, out_buffer);3260 return realpathZ(&pathname_c, out_buffer);
3228}3261}
32293262
3263pub const realpathC = @compileError("deprecated: renamed realpathZ");
3264
3230/// Same as `realpath` except `pathname` is null-terminated.3265/// Same as `realpath` except `pathname` is null-terminated.
3231pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {3266pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
3232 if (builtin.os.tag == .windows) {3267 if (builtin.os.tag == .windows) {
3233 const pathname_w = try windows.cStrToPrefixedFileW(pathname);3268 const pathname_w = try windows.cStrToPrefixedFileW(pathname);
3234 return realpathW(&pathname_w, out_buffer);3269 return realpathW(&pathname_w, out_buffer);
3235 }3270 }
3236 if (builtin.os.tag == .linux and !builtin.link_libc) {3271 if (builtin.os.tag == .linux and !builtin.link_libc) {
3237 const fd = try openC(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0);3272 const fd = try openZ(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0);
3238 defer close(fd);3273 defer close(fd);
32393274
3240 var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined;3275 var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined;
3241 const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", .{fd}) catch unreachable;3276 const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", .{fd}) catch unreachable;
32423277
3243 return readlinkC(@ptrCast([*:0]const u8, proc_path.ptr), out_buffer);3278 return readlinkZ(@ptrCast([*:0]const u8, proc_path.ptr), out_buffer);
3244 }3279 }
3245 const result_path = std.c.realpath(pathname, out_buffer) orelse switch (std.c._errno().*) {3280 const result_path = std.c.realpath(pathname, out_buffer) orelse switch (std.c._errno().*) {
3246 EINVAL => unreachable,3281 EINVAL => unreachable,
...@@ -3255,7 +3290,7 @@ pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP...@@ -3255,7 +3290,7 @@ pub fn realpathC(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealP
3255 EIO => return error.InputOutput,3290 EIO => return error.InputOutput,
3256 else => |err| return unexpectedErrno(@intCast(usize, err)),3291 else => |err| return unexpectedErrno(@intCast(usize, err)),
3257 };3292 };
3258 return mem.toSlice(u8, result_path);3293 return mem.spanZ(result_path);
3259}3294}
32603295
3261/// Same as `realpath` except `pathname` is null-terminated and UTF16LE-encoded.3296/// Same as `realpath` except `pathname` is null-terminated and UTF16LE-encoded.
...@@ -3399,12 +3434,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {...@@ -3399,12 +3434,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
3399 return;3434 return;
3400 }3435 }
34013436
3402 const symbol_name = if (std.Target.current.os.tag == .netbsd)3437 switch (errno(system.clock_gettime(clk_id, tp))) {
3403 "__clock_gettime50"
3404 else
3405 "clock_gettime";
3406
3407 switch (errno(@field(system, symbol_name)(clk_id, tp))) {
3408 0 => return,3438 0 => return,
3409 EFAULT => unreachable,3439 EFAULT => unreachable,
3410 EINVAL => return error.UnsupportedClock,3440 EINVAL => return error.UnsupportedClock,
...@@ -3426,12 +3456,7 @@ pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {...@@ -3426,12 +3456,7 @@ pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
3426 return;3456 return;
3427 }3457 }
34283458
3429 const symbol_name = if (std.Target.current.os.tag == .netbsd)3459 switch (errno(system.clock_getres(clk_id, res))) {
3430 "__clock_getres50"
3431 else
3432 "clock_getres";
3433
3434 switch (errno(@field(system, symbol_name)(clk_id, res))) {
3435 0 => return,3460 0 => return,
3436 EFAULT => unreachable,3461 EFAULT => unreachable,
3437 EINVAL => return error.UnsupportedClock,3462 EINVAL => return error.UnsupportedClock,
...@@ -3497,12 +3522,7 @@ pub const SigaltstackError = error{...@@ -3497,12 +3522,7 @@ pub const SigaltstackError = error{
3497} || UnexpectedError;3522} || UnexpectedError;
34983523
3499pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {3524pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
3500 const symbol_name = if (std.Target.current.os.tag == .netbsd)3525 switch (errno(system.sigaltstack(ss, old_ss))) {
3501 "__sigaltstack14"
3502 else
3503 "sigaltstack";
3504
3505 switch (errno(@field(system, symbol_name)(ss, old_ss))) {
3506 0 => return,3526 0 => return,
3507 EFAULT => unreachable,3527 EFAULT => unreachable,
3508 EINVAL => unreachable,3528 EINVAL => unreachable,
...@@ -3564,7 +3584,7 @@ pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;...@@ -3564,7 +3584,7 @@ pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;
3564pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {3584pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
3565 if (builtin.link_libc) {3585 if (builtin.link_libc) {
3566 switch (errno(system.gethostname(name_buffer, name_buffer.len))) {3586 switch (errno(system.gethostname(name_buffer, name_buffer.len))) {
3567 0 => return mem.toSlice(u8, @ptrCast([*:0]u8, name_buffer)),3587 0 => return mem.spanZ(@ptrCast([*:0]u8, name_buffer)),
3568 EFAULT => unreachable,3588 EFAULT => unreachable,
3569 ENAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this3589 ENAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this
3570 EPERM => return error.PermissionDenied,3590 EPERM => return error.PermissionDenied,
...@@ -3573,7 +3593,7 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {...@@ -3573,7 +3593,7 @@ pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
3573 }3593 }
3574 if (builtin.os.tag == .linux) {3594 if (builtin.os.tag == .linux) {
3575 const uts = uname();3595 const uts = uname();
3576 const hostname = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &uts.nodename));3596 const hostname = mem.spanZ(@ptrCast([*:0]const u8, &uts.nodename));
3577 mem.copy(u8, name_buffer, hostname);3597 mem.copy(u8, name_buffer, hostname);
3578 return name_buffer[0..hostname.len];3598 return name_buffer[0..hostname.len];
3579 }3599 }
...@@ -4260,7 +4280,9 @@ pub const MemFdCreateError = error{...@@ -4260,7 +4280,9 @@ pub const MemFdCreateError = error{
4260 SystemOutdated,4280 SystemOutdated,
4261} || UnexpectedError;4281} || UnexpectedError;
42624282
4263pub fn memfd_createC(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {4283pub const memfd_createC = @compileError("deprecated: renamed to memfd_createZ");
4284
4285pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {
4264 // memfd_create is available only in glibc versions starting with 2.27.4286 // memfd_create is available only in glibc versions starting with 2.27.
4265 const use_c = std.c.versionCheck(.{ .major = 2, .minor = 27, .patch = 0 }).ok;4287 const use_c = std.c.versionCheck(.{ .major = 2, .minor = 27, .patch = 0 }).ok;
4266 const sys = if (use_c) std.c else linux;4288 const sys = if (use_c) std.c else linux;
...@@ -4291,7 +4313,7 @@ fn toMemFdPath(name: []const u8) ![MFD_MAX_NAME_LEN:0]u8 {...@@ -4291,7 +4313,7 @@ fn toMemFdPath(name: []const u8) ![MFD_MAX_NAME_LEN:0]u8 {
42914313
4292pub fn memfd_create(name: []const u8, flags: u32) !fd_t {4314pub fn memfd_create(name: []const u8, flags: u32) !fd_t {
4293 const name_t = try toMemFdPath(name);4315 const name_t = try toMemFdPath(name);
4294 return memfd_createC(&name_t, flags);4316 return memfd_createZ(&name_t, flags);
4295}4317}
42964318
4297pub fn getrusage(who: i32) rusage {4319pub fn getrusage(who: i32) rusage {
lib/std/os/bits/linux.zig+128-25
...@@ -88,11 +88,29 @@ pub const FUTEX_PRIVATE_FLAG = 128;...@@ -88,11 +88,29 @@ pub const FUTEX_PRIVATE_FLAG = 128;
8888
89pub const FUTEX_CLOCK_REALTIME = 256;89pub const FUTEX_CLOCK_REALTIME = 256;
9090
91pub const PROT_NONE = 0;91/// page can not be accessed
92pub const PROT_READ = 1;92pub const PROT_NONE = 0x0;
93pub const PROT_WRITE = 2;93
94pub const PROT_EXEC = 4;94/// page can be read
95pub const PROT_READ = 0x1;
96
97/// page can be written
98pub const PROT_WRITE = 0x2;
99
100/// page can be executed
101pub const PROT_EXEC = 0x4;
102
103/// page may be used for atomic ops
104pub const PROT_SEM = switch (builtin.arch) {
105 // TODO: also xtensa
106 .mips, .mipsel, .mips64, .mips64el => 0x10,
107 else => 0x8,
108};
109
110/// mprotect flag: extend change to start of growsdown vma
95pub const PROT_GROWSDOWN = 0x01000000;111pub const PROT_GROWSDOWN = 0x01000000;
112
113/// mprotect flag: extend change to end of growsup vma
96pub const PROT_GROWSUP = 0x02000000;114pub const PROT_GROWSUP = 0x02000000;
97115
98/// Share changes116/// Share changes
...@@ -617,6 +635,11 @@ pub const CLONE_IO = 0x80000000;...@@ -617,6 +635,11 @@ pub const CLONE_IO = 0x80000000;
617/// Clear any signal handler and reset to SIG_DFL.635/// Clear any signal handler and reset to SIG_DFL.
618pub const CLONE_CLEAR_SIGHAND = 0x100000000;636pub const CLONE_CLEAR_SIGHAND = 0x100000000;
619637
638// cloning flags intersect with CSIGNAL so can be used with unshare and clone3 syscalls only.
639
640/// New time namespace
641pub const CLONE_NEWTIME = 0x00000080;
642
620pub const EFD_SEMAPHORE = 1;643pub const EFD_SEMAPHORE = 1;
621pub const EFD_CLOEXEC = O_CLOEXEC;644pub const EFD_CLOEXEC = O_CLOEXEC;
622pub const EFD_NONBLOCK = O_NONBLOCK;645pub const EFD_NONBLOCK = O_NONBLOCK;
...@@ -790,13 +813,13 @@ pub const app_mask: sigset_t = [2]u32{ 0xfffffffc, 0x7fffffff } ++ [_]u32{0xffff...@@ -790,13 +813,13 @@ pub const app_mask: sigset_t = [2]u32{ 0xfffffffc, 0x7fffffff } ++ [_]u32{0xffff
790pub const k_sigaction = if (is_mips)813pub const k_sigaction = if (is_mips)
791 extern struct {814 extern struct {
792 flags: usize,815 flags: usize,
793 sigaction: ?extern fn (i32, *siginfo_t, *c_void) void,816 sigaction: ?extern fn (i32, *siginfo_t, ?*c_void) void,
794 mask: [4]u32,817 mask: [4]u32,
795 restorer: extern fn () void,818 restorer: extern fn () void,
796 }819 }
797else820else
798 extern struct {821 extern struct {
799 sigaction: ?extern fn (i32, *siginfo_t, *c_void) void,822 sigaction: ?extern fn (i32, *siginfo_t, ?*c_void) void,
800 flags: usize,823 flags: usize,
801 restorer: extern fn () void,824 restorer: extern fn () void,
802 mask: [2]u32,825 mask: [2]u32,
...@@ -804,15 +827,17 @@ else...@@ -804,15 +827,17 @@ else
804827
805/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.828/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
806pub const Sigaction = extern struct {829pub const Sigaction = extern struct {
807 sigaction: ?extern fn (i32, *siginfo_t, *c_void) void,830 pub const sigaction_fn = fn (i32, *siginfo_t, ?*c_void) callconv(.C) void;
831 sigaction: ?sigaction_fn,
808 mask: sigset_t,832 mask: sigset_t,
809 flags: u32,833 flags: u32,
810 restorer: ?extern fn () void = null,834 restorer: ?extern fn () void = null,
811};835};
812836
813pub const SIG_ERR = @intToPtr(extern fn (i32, *siginfo_t, *c_void) void, maxInt(usize));837pub const SIG_ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
814pub const SIG_DFL = @intToPtr(?extern fn (i32, *siginfo_t, *c_void) void, 0);838pub const SIG_DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
815pub const SIG_IGN = @intToPtr(extern fn (i32, *siginfo_t, *c_void) void, 1);839pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
840
816pub const empty_sigset = [_]u32{0} ** sigset_t.len;841pub const empty_sigset = [_]u32{0} ** sigset_t.len;
817842
818pub const in_port_t = u16;843pub const in_port_t = u16;
...@@ -1125,7 +1150,8 @@ pub const io_uring_params = extern struct {...@@ -1125,7 +1150,8 @@ pub const io_uring_params = extern struct {
1125 sq_thread_cpu: u32,1150 sq_thread_cpu: u32,
1126 sq_thread_idle: u32,1151 sq_thread_idle: u32,
1127 features: u32,1152 features: u32,
1128 resv: [4]u32,1153 wq_fd: u32,
1154 resv: [3]u32,
1129 sq_off: io_sqring_offsets,1155 sq_off: io_sqring_offsets,
1130 cq_off: io_cqring_offsets,1156 cq_off: io_cqring_offsets,
1131};1157};
...@@ -1135,6 +1161,8 @@ pub const io_uring_params = extern struct {...@@ -1135,6 +1161,8 @@ pub const io_uring_params = extern struct {
1135pub const IORING_FEAT_SINGLE_MMAP = 1 << 0;1161pub const IORING_FEAT_SINGLE_MMAP = 1 << 0;
1136pub const IORING_FEAT_NODROP = 1 << 1;1162pub const IORING_FEAT_NODROP = 1 << 1;
1137pub const IORING_FEAT_SUBMIT_STABLE = 1 << 2;1163pub const IORING_FEAT_SUBMIT_STABLE = 1 << 2;
1164pub const IORING_FEAT_RW_CUR_POS = 1 << 3;
1165pub const IORING_FEAT_CUR_PERSONALITY = 1 << 4;
11381166
1139// io_uring_params.flags1167// io_uring_params.flags
11401168
...@@ -1150,6 +1178,12 @@ pub const IORING_SETUP_SQ_AFF = 1 << 2;...@@ -1150,6 +1178,12 @@ pub const IORING_SETUP_SQ_AFF = 1 << 2;
1150/// app defines CQ size1178/// app defines CQ size
1151pub const IORING_SETUP_CQSIZE = 1 << 3;1179pub const IORING_SETUP_CQSIZE = 1 << 3;
11521180
1181/// clamp SQ/CQ ring sizes
1182pub const IORING_SETUP_CLAMP = 1 << 4;
1183
1184/// attach to existing wq
1185pub const IORING_SETUP_ATTACH_WQ = 1 << 5;
1186
1153pub const io_sqring_offsets = extern struct {1187pub const io_sqring_offsets = extern struct {
1154 /// offset of ring head1188 /// offset of ring head
1155 head: u32,1189 head: u32,
...@@ -1192,7 +1226,7 @@ pub const io_cqring_offsets = extern struct {...@@ -1192,7 +1226,7 @@ pub const io_cqring_offsets = extern struct {
1192};1226};
11931227
1194pub const io_uring_sqe = extern struct {1228pub const io_uring_sqe = extern struct {
1195 opcode: u8,1229 opcode: IORING_OP,
1196 flags: u8,1230 flags: u8,
1197 ioprio: u16,1231 ioprio: u16,
1198 fd: i32,1232 fd: i32,
...@@ -1212,31 +1246,53 @@ pub const io_uring_sqe = extern struct {...@@ -1212,31 +1246,53 @@ pub const io_uring_sqe = extern struct {
1212 timeout_flags: u32,1246 timeout_flags: u32,
1213 accept_flags: u32,1247 accept_flags: u32,
1214 cancel_flags: u32,1248 cancel_flags: u32,
1249 open_flags: u32,
1250 statx_flags: u32,
1251 fadvise_flags: u32,
1215 };1252 };
1216 union2: union2,1253 union2: union2,
1217 user_data: u64,1254 user_data: u64,
1218 pub const union3 = extern union {1255 pub const union3 = extern union {
1219 buf_index: u16,1256 struct1: extern struct {
1257 /// index into fixed buffers, if used
1258 buf_index: u16,
1259
1260 /// personality to use, if used
1261 personality: u16,
1262 },
1220 __pad2: [3]u64,1263 __pad2: [3]u64,
1221 };1264 };
1222 union3: union3,1265 union3: union3,
1223};1266};
12241267
1268pub const IOSQE_BIT = extern enum {
1269 FIXED_FILE,
1270 IO_DRAIN,
1271 IO_LINK,
1272 IO_HARDLINK,
1273 ASYNC,
1274
1275 _,
1276};
1277
1225// io_uring_sqe.flags1278// io_uring_sqe.flags
12261279
1227/// use fixed fileset1280/// use fixed fileset
1228pub const IOSQE_FIXED_FILE = 1 << 0;1281pub const IOSQE_FIXED_FILE = 1 << IOSQE_BIT.FIXED_FILE;
12291282
1230/// issue after inflight IO1283/// issue after inflight IO
1231pub const IOSQE_IO_DRAIN = 1 << 1;1284pub const IOSQE_IO_DRAIN = 1 << IOSQE_BIT.IO_DRAIN;
12321285
1233/// links next sqe1286/// links next sqe
1234pub const IOSQE_IO_LINK = 1 << 2;1287pub const IOSQE_IO_LINK = 1 << IOSQE_BIT.IO_LINK;
12351288
1236/// like LINK, but stronger1289/// like LINK, but stronger
1237pub const IOSQE_IO_HARDLINK = 1 << 3;1290pub const IOSQE_IO_HARDLINK = 1 << IOSQE_BIT.IO_HARDLINK;
1291
1292/// always go async
1293pub const IOSQE_ASYNC = 1 << IOSQE_BIT.ASYNC;
12381294
1239pub const IORING_OP = extern enum {1295pub const IORING_OP = extern enum(u8) {
1240 NOP,1296 NOP,
1241 READV,1297 READV,
1242 WRITEV,1298 WRITEV,
...@@ -1254,6 +1310,19 @@ pub const IORING_OP = extern enum {...@@ -1254,6 +1310,19 @@ pub const IORING_OP = extern enum {
1254 ASYNC_CANCEL,1310 ASYNC_CANCEL,
1255 LINK_TIMEOUT,1311 LINK_TIMEOUT,
1256 CONNECT,1312 CONNECT,
1313 FALLOCATE,
1314 OPENAT,
1315 CLOSE,
1316 FILES_UPDATE,
1317 STATX,
1318 READ,
1319 WRITE,
1320 FADVISE,
1321 MADVISE,
1322 SEND,
1323 RECV,
1324 OPENAT2,
1325 EPOLL_CTL,
12571326
1258 _,1327 _,
1259};1328};
...@@ -1283,13 +1352,21 @@ pub const IORING_ENTER_GETEVENTS = 1 << 0;...@@ -1283,13 +1352,21 @@ pub const IORING_ENTER_GETEVENTS = 1 << 0;
1283pub const IORING_ENTER_SQ_WAKEUP = 1 << 1;1352pub const IORING_ENTER_SQ_WAKEUP = 1 << 1;
12841353
1285// io_uring_register opcodes and arguments1354// io_uring_register opcodes and arguments
1286pub const IORING_REGISTER_BUFFERS = 0;1355pub const IORING_REGISTER = extern enum(u32) {
1287pub const IORING_UNREGISTER_BUFFERS = 1;1356 REGISTER_BUFFERS,
1288pub const IORING_REGISTER_FILES = 2;1357 UNREGISTER_BUFFERS,
1289pub const IORING_UNREGISTER_FILES = 3;1358 REGISTER_FILES,
1290pub const IORING_REGISTER_EVENTFD = 4;1359 UNREGISTER_FILES,
1291pub const IORING_UNREGISTER_EVENTFD = 5;1360 REGISTER_EVENTFD,
1292pub const IORING_REGISTER_FILES_UPDATE = 6;1361 UNREGISTER_EVENTFD,
1362 REGISTER_FILES_UPDATE,
1363 REGISTER_EVENTFD_ASYNC,
1364 REGISTER_PROBE,
1365 REGISTER_PERSONALITY,
1366 UNREGISTER_PERSONALITY,
1367
1368 _,
1369};
12931370
1294pub const io_uring_files_update = struct {1371pub const io_uring_files_update = struct {
1295 offset: u32,1372 offset: u32,
...@@ -1297,6 +1374,32 @@ pub const io_uring_files_update = struct {...@@ -1297,6 +1374,32 @@ pub const io_uring_files_update = struct {
1297 fds: u64,1374 fds: u64,
1298};1375};
12991376
1377pub const IO_URING_OP_SUPPORTED = 1 << 0;
1378
1379pub const io_uring_probe_op = struct {
1380 op: IORING_OP,
1381
1382 resv: u8,
1383
1384 /// IO_URING_OP_* flags
1385 flags: u16,
1386
1387 resv2: u32,
1388};
1389
1390pub const io_uring_probe = struct {
1391 /// last opcode supported
1392 last_op: IORING_OP,
1393
1394 /// Number of io_uring_probe_op following
1395 ops_len: u8,
1396
1397 resv: u16,
1398 resv2: u32[3],
1399
1400 // Followed by up to `ops_len` io_uring_probe_op structures
1401};
1402
1300pub const utsname = extern struct {1403pub const utsname = extern struct {
1301 sysname: [64:0]u8,1404 sysname: [64:0]u8,
1302 nodename: [64:0]u8,1405 nodename: [64:0]u8,
lib/std/os/bits/linux/arm-eabi.zig+404-398
...@@ -10,404 +10,410 @@ const uid_t = linux.uid_t;...@@ -10,404 +10,410 @@ const uid_t = linux.uid_t;
10const gid_t = linux.gid_t;10const gid_t = linux.gid_t;
11const pid_t = linux.pid_t;11const pid_t = linux.pid_t;
1212
13pub const SYS_restart_syscall = 0;13pub const SYS = extern enum(usize) {
14pub const SYS_exit = 1;14 restart_syscall = 0,
15pub const SYS_fork = 2;15 exit = 1,
16pub const SYS_read = 3;16 fork = 2,
17pub const SYS_write = 4;17 read = 3,
18pub const SYS_open = 5;18 write = 4,
19pub const SYS_close = 6;19 open = 5,
20pub const SYS_creat = 8;20 close = 6,
21pub const SYS_link = 9;21 creat = 8,
22pub const SYS_unlink = 10;22 link = 9,
23pub const SYS_execve = 11;23 unlink = 10,
24pub const SYS_chdir = 12;24 execve = 11,
25pub const SYS_mknod = 14;25 chdir = 12,
26pub const SYS_chmod = 15;26 mknod = 14,
27pub const SYS_lchown = 16;27 chmod = 15,
28pub const SYS_lseek = 19;28 lchown = 16,
29pub const SYS_getpid = 20;29 lseek = 19,
30pub const SYS_mount = 21;30 getpid = 20,
31pub const SYS_setuid = 23;31 mount = 21,
32pub const SYS_getuid = 24;32 setuid = 23,
33pub const SYS_ptrace = 26;33 getuid = 24,
34pub const SYS_pause = 29;34 ptrace = 26,
35pub const SYS_access = 33;35 pause = 29,
36pub const SYS_nice = 34;36 access = 33,
37pub const SYS_sync = 36;37 nice = 34,
38pub const SYS_kill = 37;38 sync = 36,
39pub const SYS_rename = 38;39 kill = 37,
40pub const SYS_mkdir = 39;40 rename = 38,
41pub const SYS_rmdir = 40;41 mkdir = 39,
42pub const SYS_dup = 41;42 rmdir = 40,
43pub const SYS_pipe = 42;43 dup = 41,
44pub const SYS_times = 43;44 pipe = 42,
45pub const SYS_brk = 45;45 times = 43,
46pub const SYS_setgid = 46;46 brk = 45,
47pub const SYS_getgid = 47;47 setgid = 46,
48pub const SYS_geteuid = 49;48 getgid = 47,
49pub const SYS_getegid = 50;49 geteuid = 49,
50pub const SYS_acct = 51;50 getegid = 50,
51pub const SYS_umount2 = 52;51 acct = 51,
52pub const SYS_ioctl = 54;52 umount2 = 52,
53pub const SYS_fcntl = 55;53 ioctl = 54,
54pub const SYS_setpgid = 57;54 fcntl = 55,
55pub const SYS_umask = 60;55 setpgid = 57,
56pub const SYS_chroot = 61;56 umask = 60,
57pub const SYS_ustat = 62;57 chroot = 61,
58pub const SYS_dup2 = 63;58 ustat = 62,
59pub const SYS_getppid = 64;59 dup2 = 63,
60pub const SYS_getpgrp = 65;60 getppid = 64,
61pub const SYS_setsid = 66;61 getpgrp = 65,
62pub const SYS_sigaction = 67;62 setsid = 66,
63pub const SYS_setreuid = 70;63 sigaction = 67,
64pub const SYS_setregid = 71;64 setreuid = 70,
65pub const SYS_sigsuspend = 72;65 setregid = 71,
66pub const SYS_sigpending = 73;66 sigsuspend = 72,
67pub const SYS_sethostname = 74;67 sigpending = 73,
68pub const SYS_setrlimit = 75;68 sethostname = 74,
69pub const SYS_getrusage = 77;69 setrlimit = 75,
70pub const SYS_gettimeofday = 78;70 getrusage = 77,
71pub const SYS_settimeofday = 79;71 gettimeofday = 78,
72pub const SYS_getgroups = 80;72 settimeofday = 79,
73pub const SYS_setgroups = 81;73 getgroups = 80,
74pub const SYS_symlink = 83;74 setgroups = 81,
75pub const SYS_readlink = 85;75 symlink = 83,
76pub const SYS_uselib = 86;76 readlink = 85,
77pub const SYS_swapon = 87;77 uselib = 86,
78pub const SYS_reboot = 88;78 swapon = 87,
79pub const SYS_munmap = 91;79 reboot = 88,
80pub const SYS_truncate = 92;80 munmap = 91,
81pub const SYS_ftruncate = 93;81 truncate = 92,
82pub const SYS_fchmod = 94;82 ftruncate = 93,
83pub const SYS_fchown = 95;83 fchmod = 94,
84pub const SYS_getpriority = 96;84 fchown = 95,
85pub const SYS_setpriority = 97;85 getpriority = 96,
86pub const SYS_statfs = 99;86 setpriority = 97,
87pub const SYS_fstatfs = 100;87 statfs = 99,
88pub const SYS_syslog = 103;88 fstatfs = 100,
89pub const SYS_setitimer = 104;89 syslog = 103,
90pub const SYS_getitimer = 105;90 setitimer = 104,
91pub const SYS_stat = 106;91 getitimer = 105,
92pub const SYS_lstat = 107;92 stat = 106,
93pub const SYS_fstat = 108;93 lstat = 107,
94pub const SYS_vhangup = 111;94 fstat = 108,
95pub const SYS_wait4 = 114;95 vhangup = 111,
96pub const SYS_swapoff = 115;96 wait4 = 114,
97pub const SYS_sysinfo = 116;97 swapoff = 115,
98pub const SYS_fsync = 118;98 sysinfo = 116,
99pub const SYS_sigreturn = 119;99 fsync = 118,
100pub const SYS_clone = 120;100 sigreturn = 119,
101pub const SYS_setdomainname = 121;101 clone = 120,
102pub const SYS_uname = 122;102 setdomainname = 121,
103pub const SYS_adjtimex = 124;103 uname = 122,
104pub const SYS_mprotect = 125;104 adjtimex = 124,
105pub const SYS_sigprocmask = 126;105 mprotect = 125,
106pub const SYS_init_module = 128;106 sigprocmask = 126,
107pub const SYS_delete_module = 129;107 init_module = 128,
108pub const SYS_quotactl = 131;108 delete_module = 129,
109pub const SYS_getpgid = 132;109 quotactl = 131,
110pub const SYS_fchdir = 133;110 getpgid = 132,
111pub const SYS_bdflush = 134;111 fchdir = 133,
112pub const SYS_sysfs = 135;112 bdflush = 134,
113pub const SYS_personality = 136;113 sysfs = 135,
114pub const SYS_setfsuid = 138;114 personality = 136,
115pub const SYS_setfsgid = 139;115 setfsuid = 138,
116pub const SYS__llseek = 140;116 setfsgid = 139,
117pub const SYS_getdents = 141;117 _llseek = 140,
118pub const SYS__newselect = 142;118 getdents = 141,
119pub const SYS_flock = 143;119 _newselect = 142,
120pub const SYS_msync = 144;120 flock = 143,
121pub const SYS_readv = 145;121 msync = 144,
122pub const SYS_writev = 146;122 readv = 145,
123pub const SYS_getsid = 147;123 writev = 146,
124pub const SYS_fdatasync = 148;124 getsid = 147,
125pub const SYS__sysctl = 149;125 fdatasync = 148,
126pub const SYS_mlock = 150;126 _sysctl = 149,
127pub const SYS_munlock = 151;127 mlock = 150,
128pub const SYS_mlockall = 152;128 munlock = 151,
129pub const SYS_munlockall = 153;129 mlockall = 152,
130pub const SYS_sched_setparam = 154;130 munlockall = 153,
131pub const SYS_sched_getparam = 155;131 sched_setparam = 154,
132pub const SYS_sched_setscheduler = 156;132 sched_getparam = 155,
133pub const SYS_sched_getscheduler = 157;133 sched_setscheduler = 156,
134pub const SYS_sched_yield = 158;134 sched_getscheduler = 157,
135pub const SYS_sched_get_priority_max = 159;135 sched_yield = 158,
136pub const SYS_sched_get_priority_min = 160;136 sched_get_priority_max = 159,
137pub const SYS_sched_rr_get_interval = 161;137 sched_get_priority_min = 160,
138pub const SYS_nanosleep = 162;138 sched_rr_get_interval = 161,
139pub const SYS_mremap = 163;139 nanosleep = 162,
140pub const SYS_setresuid = 164;140 mremap = 163,
141pub const SYS_getresuid = 165;141 setresuid = 164,
142pub const SYS_poll = 168;142 getresuid = 165,
143pub const SYS_nfsservctl = 169;143 poll = 168,
144pub const SYS_setresgid = 170;144 nfsservctl = 169,
145pub const SYS_getresgid = 171;145 setresgid = 170,
146pub const SYS_prctl = 172;146 getresgid = 171,
147pub const SYS_rt_sigreturn = 173;147 prctl = 172,
148pub const SYS_rt_sigaction = 174;148 rt_sigreturn = 173,
149pub const SYS_rt_sigprocmask = 175;149 rt_sigaction = 174,
150pub const SYS_rt_sigpending = 176;150 rt_sigprocmask = 175,
151pub const SYS_rt_sigtimedwait = 177;151 rt_sigpending = 176,
152pub const SYS_rt_sigqueueinfo = 178;152 rt_sigtimedwait = 177,
153pub const SYS_rt_sigsuspend = 179;153 rt_sigqueueinfo = 178,
154pub const SYS_pread64 = 180;154 rt_sigsuspend = 179,
155pub const SYS_pwrite64 = 181;155 pread64 = 180,
156pub const SYS_chown = 182;156 pwrite64 = 181,
157pub const SYS_getcwd = 183;157 chown = 182,
158pub const SYS_capget = 184;158 getcwd = 183,
159pub const SYS_capset = 185;159 capget = 184,
160pub const SYS_sigaltstack = 186;160 capset = 185,
161pub const SYS_sendfile = 187;161 sigaltstack = 186,
162pub const SYS_vfork = 190;162 sendfile = 187,
163pub const SYS_ugetrlimit = 191;163 vfork = 190,
164pub const SYS_mmap2 = 192;164 ugetrlimit = 191,
165pub const SYS_truncate64 = 193;165 mmap2 = 192,
166pub const SYS_ftruncate64 = 194;166 truncate64 = 193,
167pub const SYS_stat64 = 195;167 ftruncate64 = 194,
168pub const SYS_lstat64 = 196;168 stat64 = 195,
169pub const SYS_fstat64 = 197;169 lstat64 = 196,
170pub const SYS_lchown32 = 198;170 fstat64 = 197,
171pub const SYS_getuid32 = 199;171 lchown32 = 198,
172pub const SYS_getgid32 = 200;172 getuid32 = 199,
173pub const SYS_geteuid32 = 201;173 getgid32 = 200,
174pub const SYS_getegid32 = 202;174 geteuid32 = 201,
175pub const SYS_setreuid32 = 203;175 getegid32 = 202,
176pub const SYS_setregid32 = 204;176 setreuid32 = 203,
177pub const SYS_getgroups32 = 205;177 setregid32 = 204,
178pub const SYS_setgroups32 = 206;178 getgroups32 = 205,
179pub const SYS_fchown32 = 207;179 setgroups32 = 206,
180pub const SYS_setresuid32 = 208;180 fchown32 = 207,
181pub const SYS_getresuid32 = 209;181 setresuid32 = 208,
182pub const SYS_setresgid32 = 210;182 getresuid32 = 209,
183pub const SYS_getresgid32 = 211;183 setresgid32 = 210,
184pub const SYS_chown32 = 212;184 getresgid32 = 211,
185pub const SYS_setuid32 = 213;185 chown32 = 212,
186pub const SYS_setgid32 = 214;186 setuid32 = 213,
187pub const SYS_setfsuid32 = 215;187 setgid32 = 214,
188pub const SYS_setfsgid32 = 216;188 setfsuid32 = 215,
189pub const SYS_getdents64 = 217;189 setfsgid32 = 216,
190pub const SYS_pivot_root = 218;190 getdents64 = 217,
191pub const SYS_mincore = 219;191 pivot_root = 218,
192pub const SYS_madvise = 220;192 mincore = 219,
193pub const SYS_fcntl64 = 221;193 madvise = 220,
194pub const SYS_gettid = 224;194 fcntl64 = 221,
195pub const SYS_readahead = 225;195 gettid = 224,
196pub const SYS_setxattr = 226;196 readahead = 225,
197pub const SYS_lsetxattr = 227;197 setxattr = 226,
198pub const SYS_fsetxattr = 228;198 lsetxattr = 227,
199pub const SYS_getxattr = 229;199 fsetxattr = 228,
200pub const SYS_lgetxattr = 230;200 getxattr = 229,
201pub const SYS_fgetxattr = 231;201 lgetxattr = 230,
202pub const SYS_listxattr = 232;202 fgetxattr = 231,
203pub const SYS_llistxattr = 233;203 listxattr = 232,
204pub const SYS_flistxattr = 234;204 llistxattr = 233,
205pub const SYS_removexattr = 235;205 flistxattr = 234,
206pub const SYS_lremovexattr = 236;206 removexattr = 235,
207pub const SYS_fremovexattr = 237;207 lremovexattr = 236,
208pub const SYS_tkill = 238;208 fremovexattr = 237,
209pub const SYS_sendfile64 = 239;209 tkill = 238,
210pub const SYS_futex = 240;210 sendfile64 = 239,
211pub const SYS_sched_setaffinity = 241;211 futex = 240,
212pub const SYS_sched_getaffinity = 242;212 sched_setaffinity = 241,
213pub const SYS_io_setup = 243;213 sched_getaffinity = 242,
214pub const SYS_io_destroy = 244;214 io_setup = 243,
215pub const SYS_io_getevents = 245;215 io_destroy = 244,
216pub const SYS_io_submit = 246;216 io_getevents = 245,
217pub const SYS_io_cancel = 247;217 io_submit = 246,
218pub const SYS_exit_group = 248;218 io_cancel = 247,
219pub const SYS_lookup_dcookie = 249;219 exit_group = 248,
220pub const SYS_epoll_create = 250;220 lookup_dcookie = 249,
221pub const SYS_epoll_ctl = 251;221 epoll_create = 250,
222pub const SYS_epoll_wait = 252;222 epoll_ctl = 251,
223pub const SYS_remap_file_pages = 253;223 epoll_wait = 252,
224pub const SYS_set_tid_address = 256;224 remap_file_pages = 253,
225pub const SYS_timer_create = 257;225 set_tid_address = 256,
226pub const SYS_timer_settime = 258;226 timer_create = 257,
227pub const SYS_timer_gettime = 259;227 timer_settime = 258,
228pub const SYS_timer_getoverrun = 260;228 timer_gettime = 259,
229pub const SYS_timer_delete = 261;229 timer_getoverrun = 260,
230pub const SYS_clock_settime = 262;230 timer_delete = 261,
231pub const SYS_clock_gettime = 263;231 clock_settime = 262,
232pub const SYS_clock_getres = 264;232 clock_gettime = 263,
233pub const SYS_clock_nanosleep = 265;233 clock_getres = 264,
234pub const SYS_statfs64 = 266;234 clock_nanosleep = 265,
235pub const SYS_fstatfs64 = 267;235 statfs64 = 266,
236pub const SYS_tgkill = 268;236 fstatfs64 = 267,
237pub const SYS_utimes = 269;237 tgkill = 268,
238pub const SYS_fadvise64_64 = 270;238 utimes = 269,
239pub const SYS_arm_fadvise64_64 = 270;239 fadvise64_64 = 270,
240pub const SYS_pciconfig_iobase = 271;240 arm_fadvise64_64 = 270,
241pub const SYS_pciconfig_read = 272;241 pciconfig_iobase = 271,
242pub const SYS_pciconfig_write = 273;242 pciconfig_read = 272,
243pub const SYS_mq_open = 274;243 pciconfig_write = 273,
244pub const SYS_mq_unlink = 275;244 mq_open = 274,
245pub const SYS_mq_timedsend = 276;245 mq_unlink = 275,
246pub const SYS_mq_timedreceive = 277;246 mq_timedsend = 276,
247pub const SYS_mq_notify = 278;247 mq_timedreceive = 277,
248pub const SYS_mq_getsetattr = 279;248 mq_notify = 278,
249pub const SYS_waitid = 280;249 mq_getsetattr = 279,
250pub const SYS_socket = 281;250 waitid = 280,
251pub const SYS_bind = 282;251 socket = 281,
252pub const SYS_connect = 283;252 bind = 282,
253pub const SYS_listen = 284;253 connect = 283,
254pub const SYS_accept = 285;254 listen = 284,
255pub const SYS_getsockname = 286;255 accept = 285,
256pub const SYS_getpeername = 287;256 getsockname = 286,
257pub const SYS_socketpair = 288;257 getpeername = 287,
258pub const SYS_send = 289;258 socketpair = 288,
259pub const SYS_sendto = 290;259 send = 289,
260pub const SYS_recv = 291;260 sendto = 290,
261pub const SYS_recvfrom = 292;261 recv = 291,
262pub const SYS_shutdown = 293;262 recvfrom = 292,
263pub const SYS_setsockopt = 294;263 shutdown = 293,
264pub const SYS_getsockopt = 295;264 setsockopt = 294,
265pub const SYS_sendmsg = 296;265 getsockopt = 295,
266pub const SYS_recvmsg = 297;266 sendmsg = 296,
267pub const SYS_semop = 298;267 recvmsg = 297,
268pub const SYS_semget = 299;268 semop = 298,
269pub const SYS_semctl = 300;269 semget = 299,
270pub const SYS_msgsnd = 301;270 semctl = 300,
271pub const SYS_msgrcv = 302;271 msgsnd = 301,
272pub const SYS_msgget = 303;272 msgrcv = 302,
273pub const SYS_msgctl = 304;273 msgget = 303,
274pub const SYS_shmat = 305;274 msgctl = 304,
275pub const SYS_shmdt = 306;275 shmat = 305,
276pub const SYS_shmget = 307;276 shmdt = 306,
277pub const SYS_shmctl = 308;277 shmget = 307,
278pub const SYS_add_key = 309;278 shmctl = 308,
279pub const SYS_request_key = 310;279 add_key = 309,
280pub const SYS_keyctl = 311;280 request_key = 310,
281pub const SYS_semtimedop = 312;281 keyctl = 311,
282pub const SYS_vserver = 313;282 semtimedop = 312,
283pub const SYS_ioprio_set = 314;283 vserver = 313,
284pub const SYS_ioprio_get = 315;284 ioprio_set = 314,
285pub const SYS_inotify_init = 316;285 ioprio_get = 315,
286pub const SYS_inotify_add_watch = 317;286 inotify_init = 316,
287pub const SYS_inotify_rm_watch = 318;287 inotify_add_watch = 317,
288pub const SYS_mbind = 319;288 inotify_rm_watch = 318,
289pub const SYS_get_mempolicy = 320;289 mbind = 319,
290pub const SYS_set_mempolicy = 321;290 get_mempolicy = 320,
291pub const SYS_openat = 322;291 set_mempolicy = 321,
292pub const SYS_mkdirat = 323;292 openat = 322,
293pub const SYS_mknodat = 324;293 mkdirat = 323,
294pub const SYS_fchownat = 325;294 mknodat = 324,
295pub const SYS_futimesat = 326;295 fchownat = 325,
296pub const SYS_fstatat64 = 327;296 futimesat = 326,
297pub const SYS_unlinkat = 328;297 fstatat64 = 327,
298pub const SYS_renameat = 329;298 unlinkat = 328,
299pub const SYS_linkat = 330;299 renameat = 329,
300pub const SYS_symlinkat = 331;300 linkat = 330,
301pub const SYS_readlinkat = 332;301 symlinkat = 331,
302pub const SYS_fchmodat = 333;302 readlinkat = 332,
303pub const SYS_faccessat = 334;303 fchmodat = 333,
304pub const SYS_pselect6 = 335;304 faccessat = 334,
305pub const SYS_ppoll = 336;305 pselect6 = 335,
306pub const SYS_unshare = 337;306 ppoll = 336,
307pub const SYS_set_robust_list = 338;307 unshare = 337,
308pub const SYS_get_robust_list = 339;308 set_robust_list = 338,
309pub const SYS_splice = 340;309 get_robust_list = 339,
310pub const SYS_sync_file_range2 = 341;310 splice = 340,
311pub const SYS_arm_sync_file_range = 341;311 sync_file_range2 = 341,
312pub const SYS_tee = 342;312 arm_sync_file_range = 341,
313pub const SYS_vmsplice = 343;313 tee = 342,
314pub const SYS_move_pages = 344;314 vmsplice = 343,
315pub const SYS_getcpu = 345;315 move_pages = 344,
316pub const SYS_epoll_pwait = 346;316 getcpu = 345,
317pub const SYS_kexec_load = 347;317 epoll_pwait = 346,
318pub const SYS_utimensat = 348;318 kexec_load = 347,
319pub const SYS_signalfd = 349;319 utimensat = 348,
320pub const SYS_timerfd_create = 350;320 signalfd = 349,
321pub const SYS_eventfd = 351;321 timerfd_create = 350,
322pub const SYS_fallocate = 352;322 eventfd = 351,
323pub const SYS_timerfd_settime = 353;323 fallocate = 352,
324pub const SYS_timerfd_gettime = 354;324 timerfd_settime = 353,
325pub const SYS_signalfd4 = 355;325 timerfd_gettime = 354,
326pub const SYS_eventfd2 = 356;326 signalfd4 = 355,
327pub const SYS_epoll_create1 = 357;327 eventfd2 = 356,
328pub const SYS_dup3 = 358;328 epoll_create1 = 357,
329pub const SYS_pipe2 = 359;329 dup3 = 358,
330pub const SYS_inotify_init1 = 360;330 pipe2 = 359,
331pub const SYS_preadv = 361;331 inotify_init1 = 360,
332pub const SYS_pwritev = 362;332 preadv = 361,
333pub const SYS_rt_tgsigqueueinfo = 363;333 pwritev = 362,
334pub const SYS_perf_event_open = 364;334 rt_tgsigqueueinfo = 363,
335pub const SYS_recvmmsg = 365;335 perf_event_open = 364,
336pub const SYS_accept4 = 366;336 recvmmsg = 365,
337pub const SYS_fanotify_init = 367;337 accept4 = 366,
338pub const SYS_fanotify_mark = 368;338 fanotify_init = 367,
339pub const SYS_prlimit64 = 369;339 fanotify_mark = 368,
340pub const SYS_name_to_handle_at = 370;340 prlimit64 = 369,
341pub const SYS_open_by_handle_at = 371;341 name_to_handle_at = 370,
342pub const SYS_clock_adjtime = 372;342 open_by_handle_at = 371,
343pub const SYS_syncfs = 373;343 clock_adjtime = 372,
344pub const SYS_sendmmsg = 374;344 syncfs = 373,
345pub const SYS_setns = 375;345 sendmmsg = 374,
346pub const SYS_process_vm_readv = 376;346 setns = 375,
347pub const SYS_process_vm_writev = 377;347 process_vm_readv = 376,
348pub const SYS_kcmp = 378;348 process_vm_writev = 377,
349pub const SYS_finit_module = 379;349 kcmp = 378,
350pub const SYS_sched_setattr = 380;350 finit_module = 379,
351pub const SYS_sched_getattr = 381;351 sched_setattr = 380,
352pub const SYS_renameat2 = 382;352 sched_getattr = 381,
353pub const SYS_seccomp = 383;353 renameat2 = 382,
354pub const SYS_getrandom = 384;354 seccomp = 383,
355pub const SYS_memfd_create = 385;355 getrandom = 384,
356pub const SYS_bpf = 386;356 memfd_create = 385,
357pub const SYS_execveat = 387;357 bpf = 386,
358pub const SYS_userfaultfd = 388;358 execveat = 387,
359pub const SYS_membarrier = 389;359 userfaultfd = 388,
360pub const SYS_mlock2 = 390;360 membarrier = 389,
361pub const SYS_copy_file_range = 391;361 mlock2 = 390,
362pub const SYS_preadv2 = 392;362 copy_file_range = 391,
363pub const SYS_pwritev2 = 393;363 preadv2 = 392,
364pub const SYS_pkey_mprotect = 394;364 pwritev2 = 393,
365pub const SYS_pkey_alloc = 395;365 pkey_mprotect = 394,
366pub const SYS_pkey_free = 396;366 pkey_alloc = 395,
367pub const SYS_statx = 397;367 pkey_free = 396,
368pub const SYS_rseq = 398;368 statx = 397,
369pub const SYS_io_pgetevents = 399;369 rseq = 398,
370pub const SYS_migrate_pages = 400;370 io_pgetevents = 399,
371pub const SYS_kexec_file_load = 401;371 migrate_pages = 400,
372pub const SYS_clock_gettime64 = 403;372 kexec_file_load = 401,
373pub const SYS_clock_settime64 = 404;373 clock_gettime64 = 403,
374pub const SYS_clock_adjtime64 = 405;374 clock_settime64 = 404,
375pub const SYS_clock_getres_time64 = 406;375 clock_adjtime64 = 405,
376pub const SYS_clock_nanosleep_time64 = 407;376 clock_getres_time64 = 406,
377pub const SYS_timer_gettime64 = 408;377 clock_nanosleep_time64 = 407,
378pub const SYS_timer_settime64 = 409;378 timer_gettime64 = 408,
379pub const SYS_timerfd_gettime64 = 410;379 timer_settime64 = 409,
380pub const SYS_timerfd_settime64 = 411;380 timerfd_gettime64 = 410,
381pub const SYS_utimensat_time64 = 412;381 timerfd_settime64 = 411,
382pub const SYS_pselect6_time64 = 413;382 utimensat_time64 = 412,
383pub const SYS_ppoll_time64 = 414;383 pselect6_time64 = 413,
384pub const SYS_io_pgetevents_time64 = 416;384 ppoll_time64 = 414,
385pub const SYS_recvmmsg_time64 = 417;385 io_pgetevents_time64 = 416,
386pub const SYS_mq_timedsend_time64 = 418;386 recvmmsg_time64 = 417,
387pub const SYS_mq_timedreceive_time64 = 419;387 mq_timedsend_time64 = 418,
388pub const SYS_semtimedop_time64 = 420;388 mq_timedreceive_time64 = 419,
389pub const SYS_rt_sigtimedwait_time64 = 421;389 semtimedop_time64 = 420,
390pub const SYS_futex_time64 = 422;390 rt_sigtimedwait_time64 = 421,
391pub const SYS_sched_rr_get_interval_time64 = 423;391 futex_time64 = 422,
392pub const SYS_pidfd_send_signal = 424;392 sched_rr_get_interval_time64 = 423,
393pub const SYS_io_uring_setup = 425;393 pidfd_send_signal = 424,
394pub const SYS_io_uring_enter = 426;394 io_uring_setup = 425,
395pub const SYS_io_uring_register = 427;395 io_uring_enter = 426,
396pub const SYS_open_tree = 428;396 io_uring_register = 427,
397pub const SYS_move_mount = 429;397 open_tree = 428,
398pub const SYS_fsopen = 430;398 move_mount = 429,
399pub const SYS_fsconfig = 431;399 fsopen = 430,
400pub const SYS_fsmount = 432;400 fsconfig = 431,
401pub const SYS_fspick = 433;401 fsmount = 432,
402pub const SYS_pidfd_open = 434;402 fspick = 433,
403pub const SYS_clone3 = 435;403 pidfd_open = 434,
404404 clone3 = 435,
405pub const SYS_breakpoint = 0x0f0001;405 openat2 = 437,
406pub const SYS_cacheflush = 0x0f0002;406 pidfd_getfd = 438,
407pub const SYS_usr26 = 0x0f0003;407
408pub const SYS_usr32 = 0x0f0004;408 breakpoint = 0x0f0001,
409pub const SYS_set_tls = 0x0f0005;409 cacheflush = 0x0f0002,
410pub const SYS_get_tls = 0x0f0006;410 usr26 = 0x0f0003,
411 usr32 = 0x0f0004,
412 set_tls = 0x0f0005,
413 get_tls = 0x0f0006,
414
415 _,
416};
411417
412pub const MMAP2_UNIT = 4096;418pub const MMAP2_UNIT = 4096;
413419
lib/std/os/bits/linux/arm64.zig+296-291
...@@ -11,298 +11,303 @@ const gid_t = linux.gid_t;...@@ -11,298 +11,303 @@ const gid_t = linux.gid_t;
11const pid_t = linux.pid_t;11const pid_t = linux.pid_t;
12const stack_t = linux.stack_t;12const stack_t = linux.stack_t;
13const sigset_t = linux.sigset_t;13const sigset_t = linux.sigset_t;
14pub const SYS = extern enum(usize) {
15 io_setup = 0,
16 io_destroy = 1,
17 io_submit = 2,
18 io_cancel = 3,
19 io_getevents = 4,
20 setxattr = 5,
21 lsetxattr = 6,
22 fsetxattr = 7,
23 getxattr = 8,
24 lgetxattr = 9,
25 fgetxattr = 10,
26 listxattr = 11,
27 llistxattr = 12,
28 flistxattr = 13,
29 removexattr = 14,
30 lremovexattr = 15,
31 fremovexattr = 16,
32 getcwd = 17,
33 lookup_dcookie = 18,
34 eventfd2 = 19,
35 epoll_create1 = 20,
36 epoll_ctl = 21,
37 epoll_pwait = 22,
38 dup = 23,
39 dup3 = 24,
40 fcntl = 25,
41 inotify_init1 = 26,
42 inotify_add_watch = 27,
43 inotify_rm_watch = 28,
44 ioctl = 29,
45 ioprio_set = 30,
46 ioprio_get = 31,
47 flock = 32,
48 mknodat = 33,
49 mkdirat = 34,
50 unlinkat = 35,
51 symlinkat = 36,
52 linkat = 37,
53 renameat = 38,
54 umount2 = 39,
55 mount = 40,
56 pivot_root = 41,
57 nfsservctl = 42,
58 statfs = 43,
59 fstatfs = 44,
60 truncate = 45,
61 ftruncate = 46,
62 fallocate = 47,
63 faccessat = 48,
64 chdir = 49,
65 fchdir = 50,
66 chroot = 51,
67 fchmod = 52,
68 fchmodat = 53,
69 fchownat = 54,
70 fchown = 55,
71 openat = 56,
72 close = 57,
73 vhangup = 58,
74 pipe2 = 59,
75 quotactl = 60,
76 getdents64 = 61,
77 lseek = 62,
78 read = 63,
79 write = 64,
80 readv = 65,
81 writev = 66,
82 pread64 = 67,
83 pwrite64 = 68,
84 preadv = 69,
85 pwritev = 70,
86 sendfile = 71,
87 pselect6 = 72,
88 ppoll = 73,
89 signalfd4 = 74,
90 vmsplice = 75,
91 splice = 76,
92 tee = 77,
93 readlinkat = 78,
94 fstatat = 79,
95 fstat = 80,
96 sync = 81,
97 fsync = 82,
98 fdatasync = 83,
99 sync_file_range2 = 84,
100 sync_file_range = 84,
101 timerfd_create = 85,
102 timerfd_settime = 86,
103 timerfd_gettime = 87,
104 utimensat = 88,
105 acct = 89,
106 capget = 90,
107 capset = 91,
108 personality = 92,
109 exit = 93,
110 exit_group = 94,
111 waitid = 95,
112 set_tid_address = 96,
113 unshare = 97,
114 futex = 98,
115 set_robust_list = 99,
116 get_robust_list = 100,
117 nanosleep = 101,
118 getitimer = 102,
119 setitimer = 103,
120 kexec_load = 104,
121 init_module = 105,
122 delete_module = 106,
123 timer_create = 107,
124 timer_gettime = 108,
125 timer_getoverrun = 109,
126 timer_settime = 110,
127 timer_delete = 111,
128 clock_settime = 112,
129 clock_gettime = 113,
130 clock_getres = 114,
131 clock_nanosleep = 115,
132 syslog = 116,
133 ptrace = 117,
134 sched_setparam = 118,
135 sched_setscheduler = 119,
136 sched_getscheduler = 120,
137 sched_getparam = 121,
138 sched_setaffinity = 122,
139 sched_getaffinity = 123,
140 sched_yield = 124,
141 sched_get_priority_max = 125,
142 sched_get_priority_min = 126,
143 sched_rr_get_interval = 127,
144 restart_syscall = 128,
145 kill = 129,
146 tkill = 130,
147 tgkill = 131,
148 sigaltstack = 132,
149 rt_sigsuspend = 133,
150 rt_sigaction = 134,
151 rt_sigprocmask = 135,
152 rt_sigpending = 136,
153 rt_sigtimedwait = 137,
154 rt_sigqueueinfo = 138,
155 rt_sigreturn = 139,
156 setpriority = 140,
157 getpriority = 141,
158 reboot = 142,
159 setregid = 143,
160 setgid = 144,
161 setreuid = 145,
162 setuid = 146,
163 setresuid = 147,
164 getresuid = 148,
165 setresgid = 149,
166 getresgid = 150,
167 setfsuid = 151,
168 setfsgid = 152,
169 times = 153,
170 setpgid = 154,
171 getpgid = 155,
172 getsid = 156,
173 setsid = 157,
174 getgroups = 158,
175 setgroups = 159,
176 uname = 160,
177 sethostname = 161,
178 setdomainname = 162,
179 getrlimit = 163,
180 setrlimit = 164,
181 getrusage = 165,
182 umask = 166,
183 prctl = 167,
184 getcpu = 168,
185 gettimeofday = 169,
186 settimeofday = 170,
187 adjtimex = 171,
188 getpid = 172,
189 getppid = 173,
190 getuid = 174,
191 geteuid = 175,
192 getgid = 176,
193 getegid = 177,
194 gettid = 178,
195 sysinfo = 179,
196 mq_open = 180,
197 mq_unlink = 181,
198 mq_timedsend = 182,
199 mq_timedreceive = 183,
200 mq_notify = 184,
201 mq_getsetattr = 185,
202 msgget = 186,
203 msgctl = 187,
204 msgrcv = 188,
205 msgsnd = 189,
206 semget = 190,
207 semctl = 191,
208 semtimedop = 192,
209 semop = 193,
210 shmget = 194,
211 shmctl = 195,
212 shmat = 196,
213 shmdt = 197,
214 socket = 198,
215 socketpair = 199,
216 bind = 200,
217 listen = 201,
218 accept = 202,
219 connect = 203,
220 getsockname = 204,
221 getpeername = 205,
222 sendto = 206,
223 recvfrom = 207,
224 setsockopt = 208,
225 getsockopt = 209,
226 shutdown = 210,
227 sendmsg = 211,
228 recvmsg = 212,
229 readahead = 213,
230 brk = 214,
231 munmap = 215,
232 mremap = 216,
233 add_key = 217,
234 request_key = 218,
235 keyctl = 219,
236 clone = 220,
237 execve = 221,
238 mmap = 222,
239 fadvise64 = 223,
240 swapon = 224,
241 swapoff = 225,
242 mprotect = 226,
243 msync = 227,
244 mlock = 228,
245 munlock = 229,
246 mlockall = 230,
247 munlockall = 231,
248 mincore = 232,
249 madvise = 233,
250 remap_file_pages = 234,
251 mbind = 235,
252 get_mempolicy = 236,
253 set_mempolicy = 237,
254 migrate_pages = 238,
255 move_pages = 239,
256 rt_tgsigqueueinfo = 240,
257 perf_event_open = 241,
258 accept4 = 242,
259 recvmmsg = 243,
260 arch_specific_syscall = 244,
261 wait4 = 260,
262 prlimit64 = 261,
263 fanotify_init = 262,
264 fanotify_mark = 263,
265 clock_adjtime = 266,
266 syncfs = 267,
267 setns = 268,
268 sendmmsg = 269,
269 process_vm_readv = 270,
270 process_vm_writev = 271,
271 kcmp = 272,
272 finit_module = 273,
273 sched_setattr = 274,
274 sched_getattr = 275,
275 renameat2 = 276,
276 seccomp = 277,
277 getrandom = 278,
278 memfd_create = 279,
279 bpf = 280,
280 execveat = 281,
281 userfaultfd = 282,
282 membarrier = 283,
283 mlock2 = 284,
284 copy_file_range = 285,
285 preadv2 = 286,
286 pwritev2 = 287,
287 pkey_mprotect = 288,
288 pkey_alloc = 289,
289 pkey_free = 290,
290 statx = 291,
291 io_pgetevents = 292,
292 rseq = 293,
293 kexec_file_load = 294,
294 pidfd_send_signal = 424,
295 io_uring_setup = 425,
296 io_uring_enter = 426,
297 io_uring_register = 427,
298 open_tree = 428,
299 move_mount = 429,
300 fsopen = 430,
301 fsconfig = 431,
302 fsmount = 432,
303 fspick = 433,
304 pidfd_open = 434,
305 clone3 = 435,
306 openat2 = 437,
307 pidfd_getfd = 438,
14308
15pub const SYS_io_setup = 0;309 _,
16pub const SYS_io_destroy = 1;310};
17pub const SYS_io_submit = 2;
18pub const SYS_io_cancel = 3;
19pub const SYS_io_getevents = 4;
20pub const SYS_setxattr = 5;
21pub const SYS_lsetxattr = 6;
22pub const SYS_fsetxattr = 7;
23pub const SYS_getxattr = 8;
24pub const SYS_lgetxattr = 9;
25pub const SYS_fgetxattr = 10;
26pub const SYS_listxattr = 11;
27pub const SYS_llistxattr = 12;
28pub const SYS_flistxattr = 13;
29pub const SYS_removexattr = 14;
30pub const SYS_lremovexattr = 15;
31pub const SYS_fremovexattr = 16;
32pub const SYS_getcwd = 17;
33pub const SYS_lookup_dcookie = 18;
34pub const SYS_eventfd2 = 19;
35pub const SYS_epoll_create1 = 20;
36pub const SYS_epoll_ctl = 21;
37pub const SYS_epoll_pwait = 22;
38pub const SYS_dup = 23;
39pub const SYS_dup3 = 24;
40pub const SYS_fcntl = 25;
41pub const SYS_inotify_init1 = 26;
42pub const SYS_inotify_add_watch = 27;
43pub const SYS_inotify_rm_watch = 28;
44pub const SYS_ioctl = 29;
45pub const SYS_ioprio_set = 30;
46pub const SYS_ioprio_get = 31;
47pub const SYS_flock = 32;
48pub const SYS_mknodat = 33;
49pub const SYS_mkdirat = 34;
50pub const SYS_unlinkat = 35;
51pub const SYS_symlinkat = 36;
52pub const SYS_linkat = 37;
53pub const SYS_renameat = 38;
54pub const SYS_umount2 = 39;
55pub const SYS_mount = 40;
56pub const SYS_pivot_root = 41;
57pub const SYS_nfsservctl = 42;
58pub const SYS_statfs = 43;
59pub const SYS_fstatfs = 44;
60pub const SYS_truncate = 45;
61pub const SYS_ftruncate = 46;
62pub const SYS_fallocate = 47;
63pub const SYS_faccessat = 48;
64pub const SYS_chdir = 49;
65pub const SYS_fchdir = 50;
66pub const SYS_chroot = 51;
67pub const SYS_fchmod = 52;
68pub const SYS_fchmodat = 53;
69pub const SYS_fchownat = 54;
70pub const SYS_fchown = 55;
71pub const SYS_openat = 56;
72pub const SYS_close = 57;
73pub const SYS_vhangup = 58;
74pub const SYS_pipe2 = 59;
75pub const SYS_quotactl = 60;
76pub const SYS_getdents64 = 61;
77pub const SYS_lseek = 62;
78pub const SYS_read = 63;
79pub const SYS_write = 64;
80pub const SYS_readv = 65;
81pub const SYS_writev = 66;
82pub const SYS_pread64 = 67;
83pub const SYS_pwrite64 = 68;
84pub const SYS_preadv = 69;
85pub const SYS_pwritev = 70;
86pub const SYS_sendfile = 71;
87pub const SYS_pselect6 = 72;
88pub const SYS_ppoll = 73;
89pub const SYS_signalfd4 = 74;
90pub const SYS_vmsplice = 75;
91pub const SYS_splice = 76;
92pub const SYS_tee = 77;
93pub const SYS_readlinkat = 78;
94pub const SYS_fstatat = 79;
95pub const SYS_fstat = 80;
96pub const SYS_sync = 81;
97pub const SYS_fsync = 82;
98pub const SYS_fdatasync = 83;
99pub const SYS_sync_file_range2 = 84;
100pub const SYS_sync_file_range = 84;
101pub const SYS_timerfd_create = 85;
102pub const SYS_timerfd_settime = 86;
103pub const SYS_timerfd_gettime = 87;
104pub const SYS_utimensat = 88;
105pub const SYS_acct = 89;
106pub const SYS_capget = 90;
107pub const SYS_capset = 91;
108pub const SYS_personality = 92;
109pub const SYS_exit = 93;
110pub const SYS_exit_group = 94;
111pub const SYS_waitid = 95;
112pub const SYS_set_tid_address = 96;
113pub const SYS_unshare = 97;
114pub const SYS_futex = 98;
115pub const SYS_set_robust_list = 99;
116pub const SYS_get_robust_list = 100;
117pub const SYS_nanosleep = 101;
118pub const SYS_getitimer = 102;
119pub const SYS_setitimer = 103;
120pub const SYS_kexec_load = 104;
121pub const SYS_init_module = 105;
122pub const SYS_delete_module = 106;
123pub const SYS_timer_create = 107;
124pub const SYS_timer_gettime = 108;
125pub const SYS_timer_getoverrun = 109;
126pub const SYS_timer_settime = 110;
127pub const SYS_timer_delete = 111;
128pub const SYS_clock_settime = 112;
129pub const SYS_clock_gettime = 113;
130pub const SYS_clock_getres = 114;
131pub const SYS_clock_nanosleep = 115;
132pub const SYS_syslog = 116;
133pub const SYS_ptrace = 117;
134pub const SYS_sched_setparam = 118;
135pub const SYS_sched_setscheduler = 119;
136pub const SYS_sched_getscheduler = 120;
137pub const SYS_sched_getparam = 121;
138pub const SYS_sched_setaffinity = 122;
139pub const SYS_sched_getaffinity = 123;
140pub const SYS_sched_yield = 124;
141pub const SYS_sched_get_priority_max = 125;
142pub const SYS_sched_get_priority_min = 126;
143pub const SYS_sched_rr_get_interval = 127;
144pub const SYS_restart_syscall = 128;
145pub const SYS_kill = 129;
146pub const SYS_tkill = 130;
147pub const SYS_tgkill = 131;
148pub const SYS_sigaltstack = 132;
149pub const SYS_rt_sigsuspend = 133;
150pub const SYS_rt_sigaction = 134;
151pub const SYS_rt_sigprocmask = 135;
152pub const SYS_rt_sigpending = 136;
153pub const SYS_rt_sigtimedwait = 137;
154pub const SYS_rt_sigqueueinfo = 138;
155pub const SYS_rt_sigreturn = 139;
156pub const SYS_setpriority = 140;
157pub const SYS_getpriority = 141;
158pub const SYS_reboot = 142;
159pub const SYS_setregid = 143;
160pub const SYS_setgid = 144;
161pub const SYS_setreuid = 145;
162pub const SYS_setuid = 146;
163pub const SYS_setresuid = 147;
164pub const SYS_getresuid = 148;
165pub const SYS_setresgid = 149;
166pub const SYS_getresgid = 150;
167pub const SYS_setfsuid = 151;
168pub const SYS_setfsgid = 152;
169pub const SYS_times = 153;
170pub const SYS_setpgid = 154;
171pub const SYS_getpgid = 155;
172pub const SYS_getsid = 156;
173pub const SYS_setsid = 157;
174pub const SYS_getgroups = 158;
175pub const SYS_setgroups = 159;
176pub const SYS_uname = 160;
177pub const SYS_sethostname = 161;
178pub const SYS_setdomainname = 162;
179pub const SYS_getrlimit = 163;
180pub const SYS_setrlimit = 164;
181pub const SYS_getrusage = 165;
182pub const SYS_umask = 166;
183pub const SYS_prctl = 167;
184pub const SYS_getcpu = 168;
185pub const SYS_gettimeofday = 169;
186pub const SYS_settimeofday = 170;
187pub const SYS_adjtimex = 171;
188pub const SYS_getpid = 172;
189pub const SYS_getppid = 173;
190pub const SYS_getuid = 174;
191pub const SYS_geteuid = 175;
192pub const SYS_getgid = 176;
193pub const SYS_getegid = 177;
194pub const SYS_gettid = 178;
195pub const SYS_sysinfo = 179;
196pub const SYS_mq_open = 180;
197pub const SYS_mq_unlink = 181;
198pub const SYS_mq_timedsend = 182;
199pub const SYS_mq_timedreceive = 183;
200pub const SYS_mq_notify = 184;
201pub const SYS_mq_getsetattr = 185;
202pub const SYS_msgget = 186;
203pub const SYS_msgctl = 187;
204pub const SYS_msgrcv = 188;
205pub const SYS_msgsnd = 189;
206pub const SYS_semget = 190;
207pub const SYS_semctl = 191;
208pub const SYS_semtimedop = 192;
209pub const SYS_semop = 193;
210pub const SYS_shmget = 194;
211pub const SYS_shmctl = 195;
212pub const SYS_shmat = 196;
213pub const SYS_shmdt = 197;
214pub const SYS_socket = 198;
215pub const SYS_socketpair = 199;
216pub const SYS_bind = 200;
217pub const SYS_listen = 201;
218pub const SYS_accept = 202;
219pub const SYS_connect = 203;
220pub const SYS_getsockname = 204;
221pub const SYS_getpeername = 205;
222pub const SYS_sendto = 206;
223pub const SYS_recvfrom = 207;
224pub const SYS_setsockopt = 208;
225pub const SYS_getsockopt = 209;
226pub const SYS_shutdown = 210;
227pub const SYS_sendmsg = 211;
228pub const SYS_recvmsg = 212;
229pub const SYS_readahead = 213;
230pub const SYS_brk = 214;
231pub const SYS_munmap = 215;
232pub const SYS_mremap = 216;
233pub const SYS_add_key = 217;
234pub const SYS_request_key = 218;
235pub const SYS_keyctl = 219;
236pub const SYS_clone = 220;
237pub const SYS_execve = 221;
238pub const SYS_mmap = 222;
239pub const SYS_fadvise64 = 223;
240pub const SYS_swapon = 224;
241pub const SYS_swapoff = 225;
242pub const SYS_mprotect = 226;
243pub const SYS_msync = 227;
244pub const SYS_mlock = 228;
245pub const SYS_munlock = 229;
246pub const SYS_mlockall = 230;
247pub const SYS_munlockall = 231;
248pub const SYS_mincore = 232;
249pub const SYS_madvise = 233;
250pub const SYS_remap_file_pages = 234;
251pub const SYS_mbind = 235;
252pub const SYS_get_mempolicy = 236;
253pub const SYS_set_mempolicy = 237;
254pub const SYS_migrate_pages = 238;
255pub const SYS_move_pages = 239;
256pub const SYS_rt_tgsigqueueinfo = 240;
257pub const SYS_perf_event_open = 241;
258pub const SYS_accept4 = 242;
259pub const SYS_recvmmsg = 243;
260pub const SYS_arch_specific_syscall = 244;
261pub const SYS_wait4 = 260;
262pub const SYS_prlimit64 = 261;
263pub const SYS_fanotify_init = 262;
264pub const SYS_fanotify_mark = 263;
265pub const SYS_clock_adjtime = 266;
266pub const SYS_syncfs = 267;
267pub const SYS_setns = 268;
268pub const SYS_sendmmsg = 269;
269pub const SYS_process_vm_readv = 270;
270pub const SYS_process_vm_writev = 271;
271pub const SYS_kcmp = 272;
272pub const SYS_finit_module = 273;
273pub const SYS_sched_setattr = 274;
274pub const SYS_sched_getattr = 275;
275pub const SYS_renameat2 = 276;
276pub const SYS_seccomp = 277;
277pub const SYS_getrandom = 278;
278pub const SYS_memfd_create = 279;
279pub const SYS_bpf = 280;
280pub const SYS_execveat = 281;
281pub const SYS_userfaultfd = 282;
282pub const SYS_membarrier = 283;
283pub const SYS_mlock2 = 284;
284pub const SYS_copy_file_range = 285;
285pub const SYS_preadv2 = 286;
286pub const SYS_pwritev2 = 287;
287pub const SYS_pkey_mprotect = 288;
288pub const SYS_pkey_alloc = 289;
289pub const SYS_pkey_free = 290;
290pub const SYS_statx = 291;
291pub const SYS_io_pgetevents = 292;
292pub const SYS_rseq = 293;
293pub const SYS_kexec_file_load = 294;
294pub const SYS_pidfd_send_signal = 424;
295pub const SYS_io_uring_setup = 425;
296pub const SYS_io_uring_enter = 426;
297pub const SYS_io_uring_register = 427;
298pub const SYS_open_tree = 428;
299pub const SYS_move_mount = 429;
300pub const SYS_fsopen = 430;
301pub const SYS_fsconfig = 431;
302pub const SYS_fsmount = 432;
303pub const SYS_fspick = 433;
304pub const SYS_pidfd_open = 434;
305pub const SYS_clone3 = 435;
306311
307pub const O_CREAT = 0o100;312pub const O_CREAT = 0o100;
308pub const O_EXCL = 0o200;313pub const O_EXCL = 0o200;
lib/std/os/bits/linux/errno-generic.zig+27
...@@ -368,6 +368,33 @@ pub const ENOMEDIUM = 123;...@@ -368,6 +368,33 @@ pub const ENOMEDIUM = 123;
368/// Wrong medium type368/// Wrong medium type
369pub const EMEDIUMTYPE = 124;369pub const EMEDIUMTYPE = 124;
370370
371/// Operation canceled
372pub const ECANCELED = 125;
373
374/// Required key not available
375pub const ENOKEY = 126;
376
377/// Key has expired
378pub const EKEYEXPIRED = 127;
379
380/// Key has been revoked
381pub const EKEYREVOKED = 128;
382
383/// Key was rejected by service
384pub const EKEYREJECTED = 129;
385
386// for robust mutexes
387/// Owner died
388pub const EOWNERDEAD = 130;
389/// State not recoverable
390pub const ENOTRECOVERABLE = 131;
391
392/// Operation not possible due to RF-kill
393pub const ERFKILL = 132;
394
395/// Memory page has hardware error
396pub const EHWPOISON = 133;
397
371// nameserver query return codes398// nameserver query return codes
372399
373/// DNS server returned answer with no data400/// DNS server returned answer with no data
lib/std/os/bits/linux/i386.zig+429-423
...@@ -12,429 +12,435 @@ const pid_t = linux.pid_t;...@@ -12,429 +12,435 @@ const pid_t = linux.pid_t;
12const stack_t = linux.stack_t;12const stack_t = linux.stack_t;
13const sigset_t = linux.sigset_t;13const sigset_t = linux.sigset_t;
1414
15pub const SYS_restart_syscall = 0;15pub const SYS = extern enum(usize) {
16pub const SYS_exit = 1;16 restart_syscall = 0,
17pub const SYS_fork = 2;17 exit = 1,
18pub const SYS_read = 3;18 fork = 2,
19pub const SYS_write = 4;19 read = 3,
20pub const SYS_open = 5;20 write = 4,
21pub const SYS_close = 6;21 open = 5,
22pub const SYS_waitpid = 7;22 close = 6,
23pub const SYS_creat = 8;23 waitpid = 7,
24pub const SYS_link = 9;24 creat = 8,
25pub const SYS_unlink = 10;25 link = 9,
26pub const SYS_execve = 11;26 unlink = 10,
27pub const SYS_chdir = 12;27 execve = 11,
28pub const SYS_time = 13;28 chdir = 12,
29pub const SYS_mknod = 14;29 time = 13,
30pub const SYS_chmod = 15;30 mknod = 14,
31pub const SYS_lchown = 16;31 chmod = 15,
32pub const SYS_break = 17;32 lchown = 16,
33pub const SYS_oldstat = 18;33 @"break" = 17,
34pub const SYS_lseek = 19;34 oldstat = 18,
35pub const SYS_getpid = 20;35 lseek = 19,
36pub const SYS_mount = 21;36 getpid = 20,
37pub const SYS_umount = 22;37 mount = 21,
38pub const SYS_setuid = 23;38 umount = 22,
39pub const SYS_getuid = 24;39 setuid = 23,
40pub const SYS_stime = 25;40 getuid = 24,
41pub const SYS_ptrace = 26;41 stime = 25,
42pub const SYS_alarm = 27;42 ptrace = 26,
43pub const SYS_oldfstat = 28;43 alarm = 27,
44pub const SYS_pause = 29;44 oldfstat = 28,
45pub const SYS_utime = 30;45 pause = 29,
46pub const SYS_stty = 31;46 utime = 30,
47pub const SYS_gtty = 32;47 stty = 31,
48pub const SYS_access = 33;48 gtty = 32,
49pub const SYS_nice = 34;49 access = 33,
50pub const SYS_ftime = 35;50 nice = 34,
51pub const SYS_sync = 36;51 ftime = 35,
52pub const SYS_kill = 37;52 sync = 36,
53pub const SYS_rename = 38;53 kill = 37,
54pub const SYS_mkdir = 39;54 rename = 38,
55pub const SYS_rmdir = 40;55 mkdir = 39,
56pub const SYS_dup = 41;56 rmdir = 40,
57pub const SYS_pipe = 42;57 dup = 41,
58pub const SYS_times = 43;58 pipe = 42,
59pub const SYS_prof = 44;59 times = 43,
60pub const SYS_brk = 45;60 prof = 44,
61pub const SYS_setgid = 46;61 brk = 45,
62pub const SYS_getgid = 47;62 setgid = 46,
63pub const SYS_signal = 48;63 getgid = 47,
64pub const SYS_geteuid = 49;64 signal = 48,
65pub const SYS_getegid = 50;65 geteuid = 49,
66pub const SYS_acct = 51;66 getegid = 50,
67pub const SYS_umount2 = 52;67 acct = 51,
68pub const SYS_lock = 53;68 umount2 = 52,
69pub const SYS_ioctl = 54;69 lock = 53,
70pub const SYS_fcntl = 55;70 ioctl = 54,
71pub const SYS_mpx = 56;71 fcntl = 55,
72pub const SYS_setpgid = 57;72 mpx = 56,
73pub const SYS_ulimit = 58;73 setpgid = 57,
74pub const SYS_oldolduname = 59;74 ulimit = 58,
75pub const SYS_umask = 60;75 oldolduname = 59,
76pub const SYS_chroot = 61;76 umask = 60,
77pub const SYS_ustat = 62;77 chroot = 61,
78pub const SYS_dup2 = 63;78 ustat = 62,
79pub const SYS_getppid = 64;79 dup2 = 63,
80pub const SYS_getpgrp = 65;80 getppid = 64,
81pub const SYS_setsid = 66;81 getpgrp = 65,
82pub const SYS_sigaction = 67;82 setsid = 66,
83pub const SYS_sgetmask = 68;83 sigaction = 67,
84pub const SYS_ssetmask = 69;84 sgetmask = 68,
85pub const SYS_setreuid = 70;85 ssetmask = 69,
86pub const SYS_setregid = 71;86 setreuid = 70,
87pub const SYS_sigsuspend = 72;87 setregid = 71,
88pub const SYS_sigpending = 73;88 sigsuspend = 72,
89pub const SYS_sethostname = 74;89 sigpending = 73,
90pub const SYS_setrlimit = 75;90 sethostname = 74,
91pub const SYS_getrlimit = 76;91 setrlimit = 75,
92pub const SYS_getrusage = 77;92 getrlimit = 76,
93pub const SYS_gettimeofday = 78;93 getrusage = 77,
94pub const SYS_settimeofday = 79;94 gettimeofday = 78,
95pub const SYS_getgroups = 80;95 settimeofday = 79,
96pub const SYS_setgroups = 81;96 getgroups = 80,
97pub const SYS_select = 82;97 setgroups = 81,
98pub const SYS_symlink = 83;98 select = 82,
99pub const SYS_oldlstat = 84;99 symlink = 83,
100pub const SYS_readlink = 85;100 oldlstat = 84,
101pub const SYS_uselib = 86;101 readlink = 85,
102pub const SYS_swapon = 87;102 uselib = 86,
103pub const SYS_reboot = 88;103 swapon = 87,
104pub const SYS_readdir = 89;104 reboot = 88,
105pub const SYS_mmap = 90;105 readdir = 89,
106pub const SYS_munmap = 91;106 mmap = 90,
107pub const SYS_truncate = 92;107 munmap = 91,
108pub const SYS_ftruncate = 93;108 truncate = 92,
109pub const SYS_fchmod = 94;109 ftruncate = 93,
110pub const SYS_fchown = 95;110 fchmod = 94,
111pub const SYS_getpriority = 96;111 fchown = 95,
112pub const SYS_setpriority = 97;112 getpriority = 96,
113pub const SYS_profil = 98;113 setpriority = 97,
114pub const SYS_statfs = 99;114 profil = 98,
115pub const SYS_fstatfs = 100;115 statfs = 99,
116pub const SYS_ioperm = 101;116 fstatfs = 100,
117pub const SYS_socketcall = 102;117 ioperm = 101,
118pub const SYS_syslog = 103;118 socketcall = 102,
119pub const SYS_setitimer = 104;119 syslog = 103,
120pub const SYS_getitimer = 105;120 setitimer = 104,
121pub const SYS_stat = 106;121 getitimer = 105,
122pub const SYS_lstat = 107;122 stat = 106,
123pub const SYS_fstat = 108;123 lstat = 107,
124pub const SYS_olduname = 109;124 fstat = 108,
125pub const SYS_iopl = 110;125 olduname = 109,
126pub const SYS_vhangup = 111;126 iopl = 110,
127pub const SYS_idle = 112;127 vhangup = 111,
128pub const SYS_vm86old = 113;128 idle = 112,
129pub const SYS_wait4 = 114;129 vm86old = 113,
130pub const SYS_swapoff = 115;130 wait4 = 114,
131pub const SYS_sysinfo = 116;131 swapoff = 115,
132pub const SYS_ipc = 117;132 sysinfo = 116,
133pub const SYS_fsync = 118;133 ipc = 117,
134pub const SYS_sigreturn = 119;134 fsync = 118,
135pub const SYS_clone = 120;135 sigreturn = 119,
136pub const SYS_setdomainname = 121;136 clone = 120,
137pub const SYS_uname = 122;137 setdomainname = 121,
138pub const SYS_modify_ldt = 123;138 uname = 122,
139pub const SYS_adjtimex = 124;139 modify_ldt = 123,
140pub const SYS_mprotect = 125;140 adjtimex = 124,
141pub const SYS_sigprocmask = 126;141 mprotect = 125,
142pub const SYS_create_module = 127;142 sigprocmask = 126,
143pub const SYS_init_module = 128;143 create_module = 127,
144pub const SYS_delete_module = 129;144 init_module = 128,
145pub const SYS_get_kernel_syms = 130;145 delete_module = 129,
146pub const SYS_quotactl = 131;146 get_kernel_syms = 130,
147pub const SYS_getpgid = 132;147 quotactl = 131,
148pub const SYS_fchdir = 133;148 getpgid = 132,
149pub const SYS_bdflush = 134;149 fchdir = 133,
150pub const SYS_sysfs = 135;150 bdflush = 134,
151pub const SYS_personality = 136;151 sysfs = 135,
152pub const SYS_afs_syscall = 137;152 personality = 136,
153pub const SYS_setfsuid = 138;153 afs_syscall = 137,
154pub const SYS_setfsgid = 139;154 setfsuid = 138,
155pub const SYS__llseek = 140;155 setfsgid = 139,
156pub const SYS_getdents = 141;156 _llseek = 140,
157pub const SYS__newselect = 142;157 getdents = 141,
158pub const SYS_flock = 143;158 _newselect = 142,
159pub const SYS_msync = 144;159 flock = 143,
160pub const SYS_readv = 145;160 msync = 144,
161pub const SYS_writev = 146;161 readv = 145,
162pub const SYS_getsid = 147;162 writev = 146,
163pub const SYS_fdatasync = 148;163 getsid = 147,
164pub const SYS__sysctl = 149;164 fdatasync = 148,
165pub const SYS_mlock = 150;165 _sysctl = 149,
166pub const SYS_munlock = 151;166 mlock = 150,
167pub const SYS_mlockall = 152;167 munlock = 151,
168pub const SYS_munlockall = 153;168 mlockall = 152,
169pub const SYS_sched_setparam = 154;169 munlockall = 153,
170pub const SYS_sched_getparam = 155;170 sched_setparam = 154,
171pub const SYS_sched_setscheduler = 156;171 sched_getparam = 155,
172pub const SYS_sched_getscheduler = 157;172 sched_setscheduler = 156,
173pub const SYS_sched_yield = 158;173 sched_getscheduler = 157,
174pub const SYS_sched_get_priority_max = 159;174 sched_yield = 158,
175pub const SYS_sched_get_priority_min = 160;175 sched_get_priority_max = 159,
176pub const SYS_sched_rr_get_interval = 161;176 sched_get_priority_min = 160,
177pub const SYS_nanosleep = 162;177 sched_rr_get_interval = 161,
178pub const SYS_mremap = 163;178 nanosleep = 162,
179pub const SYS_setresuid = 164;179 mremap = 163,
180pub const SYS_getresuid = 165;180 setresuid = 164,
181pub const SYS_vm86 = 166;181 getresuid = 165,
182pub const SYS_query_module = 167;182 vm86 = 166,
183pub const SYS_poll = 168;183 query_module = 167,
184pub const SYS_nfsservctl = 169;184 poll = 168,
185pub const SYS_setresgid = 170;185 nfsservctl = 169,
186pub const SYS_getresgid = 171;186 setresgid = 170,
187pub const SYS_prctl = 172;187 getresgid = 171,
188pub const SYS_rt_sigreturn = 173;188 prctl = 172,
189pub const SYS_rt_sigaction = 174;189 rt_sigreturn = 173,
190pub const SYS_rt_sigprocmask = 175;190 rt_sigaction = 174,
191pub const SYS_rt_sigpending = 176;191 rt_sigprocmask = 175,
192pub const SYS_rt_sigtimedwait = 177;192 rt_sigpending = 176,
193pub const SYS_rt_sigqueueinfo = 178;193 rt_sigtimedwait = 177,
194pub const SYS_rt_sigsuspend = 179;194 rt_sigqueueinfo = 178,
195pub const SYS_pread64 = 180;195 rt_sigsuspend = 179,
196pub const SYS_pwrite64 = 181;196 pread64 = 180,
197pub const SYS_chown = 182;197 pwrite64 = 181,
198pub const SYS_getcwd = 183;198 chown = 182,
199pub const SYS_capget = 184;199 getcwd = 183,
200pub const SYS_capset = 185;200 capget = 184,
201pub const SYS_sigaltstack = 186;201 capset = 185,
202pub const SYS_sendfile = 187;202 sigaltstack = 186,
203pub const SYS_getpmsg = 188;203 sendfile = 187,
204pub const SYS_putpmsg = 189;204 getpmsg = 188,
205pub const SYS_vfork = 190;205 putpmsg = 189,
206pub const SYS_ugetrlimit = 191;206 vfork = 190,
207pub const SYS_mmap2 = 192;207 ugetrlimit = 191,
208pub const SYS_truncate64 = 193;208 mmap2 = 192,
209pub const SYS_ftruncate64 = 194;209 truncate64 = 193,
210pub const SYS_stat64 = 195;210 ftruncate64 = 194,
211pub const SYS_lstat64 = 196;211 stat64 = 195,
212pub const SYS_fstat64 = 197;212 lstat64 = 196,
213pub const SYS_lchown32 = 198;213 fstat64 = 197,
214pub const SYS_getuid32 = 199;214 lchown32 = 198,
215pub const SYS_getgid32 = 200;215 getuid32 = 199,
216pub const SYS_geteuid32 = 201;216 getgid32 = 200,
217pub const SYS_getegid32 = 202;217 geteuid32 = 201,
218pub const SYS_setreuid32 = 203;218 getegid32 = 202,
219pub const SYS_setregid32 = 204;219 setreuid32 = 203,
220pub const SYS_getgroups32 = 205;220 setregid32 = 204,
221pub const SYS_setgroups32 = 206;221 getgroups32 = 205,
222pub const SYS_fchown32 = 207;222 setgroups32 = 206,
223pub const SYS_setresuid32 = 208;223 fchown32 = 207,
224pub const SYS_getresuid32 = 209;224 setresuid32 = 208,
225pub const SYS_setresgid32 = 210;225 getresuid32 = 209,
226pub const SYS_getresgid32 = 211;226 setresgid32 = 210,
227pub const SYS_chown32 = 212;227 getresgid32 = 211,
228pub const SYS_setuid32 = 213;228 chown32 = 212,
229pub const SYS_setgid32 = 214;229 setuid32 = 213,
230pub const SYS_setfsuid32 = 215;230 setgid32 = 214,
231pub const SYS_setfsgid32 = 216;231 setfsuid32 = 215,
232pub const SYS_pivot_root = 217;232 setfsgid32 = 216,
233pub const SYS_mincore = 218;233 pivot_root = 217,
234pub const SYS_madvise = 219;234 mincore = 218,
235pub const SYS_getdents64 = 220;235 madvise = 219,
236pub const SYS_fcntl64 = 221;236 getdents64 = 220,
237pub const SYS_gettid = 224;237 fcntl64 = 221,
238pub const SYS_readahead = 225;238 gettid = 224,
239pub const SYS_setxattr = 226;239 readahead = 225,
240pub const SYS_lsetxattr = 227;240 setxattr = 226,
241pub const SYS_fsetxattr = 228;241 lsetxattr = 227,
242pub const SYS_getxattr = 229;242 fsetxattr = 228,
243pub const SYS_lgetxattr = 230;243 getxattr = 229,
244pub const SYS_fgetxattr = 231;244 lgetxattr = 230,
245pub const SYS_listxattr = 232;245 fgetxattr = 231,
246pub const SYS_llistxattr = 233;246 listxattr = 232,
247pub const SYS_flistxattr = 234;247 llistxattr = 233,
248pub const SYS_removexattr = 235;248 flistxattr = 234,
249pub const SYS_lremovexattr = 236;249 removexattr = 235,
250pub const SYS_fremovexattr = 237;250 lremovexattr = 236,
251pub const SYS_tkill = 238;251 fremovexattr = 237,
252pub const SYS_sendfile64 = 239;252 tkill = 238,
253pub const SYS_futex = 240;253 sendfile64 = 239,
254pub const SYS_sched_setaffinity = 241;254 futex = 240,
255pub const SYS_sched_getaffinity = 242;255 sched_setaffinity = 241,
256pub const SYS_set_thread_area = 243;256 sched_getaffinity = 242,
257pub const SYS_get_thread_area = 244;257 set_thread_area = 243,
258pub const SYS_io_setup = 245;258 get_thread_area = 244,
259pub const SYS_io_destroy = 246;259 io_setup = 245,
260pub const SYS_io_getevents = 247;260 io_destroy = 246,
261pub const SYS_io_submit = 248;261 io_getevents = 247,
262pub const SYS_io_cancel = 249;262 io_submit = 248,
263pub const SYS_fadvise64 = 250;263 io_cancel = 249,
264pub const SYS_exit_group = 252;264 fadvise64 = 250,
265pub const SYS_lookup_dcookie = 253;265 exit_group = 252,
266pub const SYS_epoll_create = 254;266 lookup_dcookie = 253,
267pub const SYS_epoll_ctl = 255;267 epoll_create = 254,
268pub const SYS_epoll_wait = 256;268 epoll_ctl = 255,
269pub const SYS_remap_file_pages = 257;269 epoll_wait = 256,
270pub const SYS_set_tid_address = 258;270 remap_file_pages = 257,
271pub const SYS_timer_create = 259;271 set_tid_address = 258,
272pub const SYS_timer_settime = SYS_timer_create + 1;272 timer_create = 259,
273pub const SYS_timer_gettime = SYS_timer_create + 2;273 timer_settime, // SYS_timer_create + 1
274pub const SYS_timer_getoverrun = SYS_timer_create + 3;274 timer_gettime, // SYS_timer_create + 2
275pub const SYS_timer_delete = SYS_timer_create + 4;275 timer_getoverrun, // SYS_timer_create + 3
276pub const SYS_clock_settime = SYS_timer_create + 5;276 timer_delete, // SYS_timer_create + 4
277pub const SYS_clock_gettime = SYS_timer_create + 6;277 clock_settime, // SYS_timer_create + 5
278pub const SYS_clock_getres = SYS_timer_create + 7;278 clock_gettime, // SYS_timer_create + 6
279pub const SYS_clock_nanosleep = SYS_timer_create + 8;279 clock_getres, // SYS_timer_create + 7
280pub const SYS_statfs64 = 268;280 clock_nanosleep, // SYS_timer_create + 8
281pub const SYS_fstatfs64 = 269;281 statfs64 = 268,
282pub const SYS_tgkill = 270;282 fstatfs64 = 269,
283pub const SYS_utimes = 271;283 tgkill = 270,
284pub const SYS_fadvise64_64 = 272;284 utimes = 271,
285pub const SYS_vserver = 273;285 fadvise64_64 = 272,
286pub const SYS_mbind = 274;286 vserver = 273,
287pub const SYS_get_mempolicy = 275;287 mbind = 274,
288pub const SYS_set_mempolicy = 276;288 get_mempolicy = 275,
289pub const SYS_mq_open = 277;289 set_mempolicy = 276,
290pub const SYS_mq_unlink = SYS_mq_open + 1;290 mq_open = 277,
291pub const SYS_mq_timedsend = SYS_mq_open + 2;291 mq_unlink, // SYS_mq_open + 1
292pub const SYS_mq_timedreceive = SYS_mq_open + 3;292 mq_timedsend, // SYS_mq_open + 2
293pub const SYS_mq_notify = SYS_mq_open + 4;293 mq_timedreceive, // SYS_mq_open + 3
294pub const SYS_mq_getsetattr = SYS_mq_open + 5;294 mq_notify, // SYS_mq_open + 4
295pub const SYS_kexec_load = 283;295 mq_getsetattr, // SYS_mq_open + 5
296pub const SYS_waitid = 284;296 kexec_load = 283,
297pub const SYS_add_key = 286;297 waitid = 284,
298pub const SYS_request_key = 287;298 add_key = 286,
299pub const SYS_keyctl = 288;299 request_key = 287,
300pub const SYS_ioprio_set = 289;300 keyctl = 288,
301pub const SYS_ioprio_get = 290;301 ioprio_set = 289,
302pub const SYS_inotify_init = 291;302 ioprio_get = 290,
303pub const SYS_inotify_add_watch = 292;303 inotify_init = 291,
304pub const SYS_inotify_rm_watch = 293;304 inotify_add_watch = 292,
305pub const SYS_migrate_pages = 294;305 inotify_rm_watch = 293,
306pub const SYS_openat = 295;306 migrate_pages = 294,
307pub const SYS_mkdirat = 296;307 openat = 295,
308pub const SYS_mknodat = 297;308 mkdirat = 296,
309pub const SYS_fchownat = 298;309 mknodat = 297,
310pub const SYS_futimesat = 299;310 fchownat = 298,
311pub const SYS_fstatat64 = 300;311 futimesat = 299,
312pub const SYS_unlinkat = 301;312 fstatat64 = 300,
313pub const SYS_renameat = 302;313 unlinkat = 301,
314pub const SYS_linkat = 303;314 renameat = 302,
315pub const SYS_symlinkat = 304;315 linkat = 303,
316pub const SYS_readlinkat = 305;316 symlinkat = 304,
317pub const SYS_fchmodat = 306;317 readlinkat = 305,
318pub const SYS_faccessat = 307;318 fchmodat = 306,
319pub const SYS_pselect6 = 308;319 faccessat = 307,
320pub const SYS_ppoll = 309;320 pselect6 = 308,
321pub const SYS_unshare = 310;321 ppoll = 309,
322pub const SYS_set_robust_list = 311;322 unshare = 310,
323pub const SYS_get_robust_list = 312;323 set_robust_list = 311,
324pub const SYS_splice = 313;324 get_robust_list = 312,
325pub const SYS_sync_file_range = 314;325 splice = 313,
326pub const SYS_tee = 315;326 sync_file_range = 314,
327pub const SYS_vmsplice = 316;327 tee = 315,
328pub const SYS_move_pages = 317;328 vmsplice = 316,
329pub const SYS_getcpu = 318;329 move_pages = 317,
330pub const SYS_epoll_pwait = 319;330 getcpu = 318,
331pub const SYS_utimensat = 320;331 epoll_pwait = 319,
332pub const SYS_signalfd = 321;332 utimensat = 320,
333pub const SYS_timerfd_create = 322;333 signalfd = 321,
334pub const SYS_eventfd = 323;334 timerfd_create = 322,
335pub const SYS_fallocate = 324;335 eventfd = 323,
336pub const SYS_timerfd_settime = 325;336 fallocate = 324,
337pub const SYS_timerfd_gettime = 326;337 timerfd_settime = 325,
338pub const SYS_signalfd4 = 327;338 timerfd_gettime = 326,
339pub const SYS_eventfd2 = 328;339 signalfd4 = 327,
340pub const SYS_epoll_create1 = 329;340 eventfd2 = 328,
341pub const SYS_dup3 = 330;341 epoll_create1 = 329,
342pub const SYS_pipe2 = 331;342 dup3 = 330,
343pub const SYS_inotify_init1 = 332;343 pipe2 = 331,
344pub const SYS_preadv = 333;344 inotify_init1 = 332,
345pub const SYS_pwritev = 334;345 preadv = 333,
346pub const SYS_rt_tgsigqueueinfo = 335;346 pwritev = 334,
347pub const SYS_perf_event_open = 336;347 rt_tgsigqueueinfo = 335,
348pub const SYS_recvmmsg = 337;348 perf_event_open = 336,
349pub const SYS_fanotify_init = 338;349 recvmmsg = 337,
350pub const SYS_fanotify_mark = 339;350 fanotify_init = 338,
351pub const SYS_prlimit64 = 340;351 fanotify_mark = 339,
352pub const SYS_name_to_handle_at = 341;352 prlimit64 = 340,
353pub const SYS_open_by_handle_at = 342;353 name_to_handle_at = 341,
354pub const SYS_clock_adjtime = 343;354 open_by_handle_at = 342,
355pub const SYS_syncfs = 344;355 clock_adjtime = 343,
356pub const SYS_sendmmsg = 345;356 syncfs = 344,
357pub const SYS_setns = 346;357 sendmmsg = 345,
358pub const SYS_process_vm_readv = 347;358 setns = 346,
359pub const SYS_process_vm_writev = 348;359 process_vm_readv = 347,
360pub const SYS_kcmp = 349;360 process_vm_writev = 348,
361pub const SYS_finit_module = 350;361 kcmp = 349,
362pub const SYS_sched_setattr = 351;362 finit_module = 350,
363pub const SYS_sched_getattr = 352;363 sched_setattr = 351,
364pub const SYS_renameat2 = 353;364 sched_getattr = 352,
365pub const SYS_seccomp = 354;365 renameat2 = 353,
366pub const SYS_getrandom = 355;366 seccomp = 354,
367pub const SYS_memfd_create = 356;367 getrandom = 355,
368pub const SYS_bpf = 357;368 memfd_create = 356,
369pub const SYS_execveat = 358;369 bpf = 357,
370pub const SYS_socket = 359;370 execveat = 358,
371pub const SYS_socketpair = 360;371 socket = 359,
372pub const SYS_bind = 361;372 socketpair = 360,
373pub const SYS_connect = 362;373 bind = 361,
374pub const SYS_listen = 363;374 connect = 362,
375pub const SYS_accept4 = 364;375 listen = 363,
376pub const SYS_getsockopt = 365;376 accept4 = 364,
377pub const SYS_setsockopt = 366;377 getsockopt = 365,
378pub const SYS_getsockname = 367;378 setsockopt = 366,
379pub const SYS_getpeername = 368;379 getsockname = 367,
380pub const SYS_sendto = 369;380 getpeername = 368,
381pub const SYS_sendmsg = 370;381 sendto = 369,
382pub const SYS_recvfrom = 371;382 sendmsg = 370,
383pub const SYS_recvmsg = 372;383 recvfrom = 371,
384pub const SYS_shutdown = 373;384 recvmsg = 372,
385pub const SYS_userfaultfd = 374;385 shutdown = 373,
386pub const SYS_membarrier = 375;386 userfaultfd = 374,
387pub const SYS_mlock2 = 376;387 membarrier = 375,
388pub const SYS_copy_file_range = 377;388 mlock2 = 376,
389pub const SYS_preadv2 = 378;389 copy_file_range = 377,
390pub const SYS_pwritev2 = 379;390 preadv2 = 378,
391pub const SYS_pkey_mprotect = 380;391 pwritev2 = 379,
392pub const SYS_pkey_alloc = 381;392 pkey_mprotect = 380,
393pub const SYS_pkey_free = 382;393 pkey_alloc = 381,
394pub const SYS_statx = 383;394 pkey_free = 382,
395pub const SYS_arch_prctl = 384;395 statx = 383,
396pub const SYS_io_pgetevents = 385;396 arch_prctl = 384,
397pub const SYS_rseq = 386;397 io_pgetevents = 385,
398pub const SYS_semget = 393;398 rseq = 386,
399pub const SYS_semctl = 394;399 semget = 393,
400pub const SYS_shmget = 395;400 semctl = 394,
401pub const SYS_shmctl = 396;401 shmget = 395,
402pub const SYS_shmat = 397;402 shmctl = 396,
403pub const SYS_shmdt = 398;403 shmat = 397,
404pub const SYS_msgget = 399;404 shmdt = 398,
405pub const SYS_msgsnd = 400;405 msgget = 399,
406pub const SYS_msgrcv = 401;406 msgsnd = 400,
407pub const SYS_msgctl = 402;407 msgrcv = 401,
408pub const SYS_clock_gettime64 = 403;408 msgctl = 402,
409pub const SYS_clock_settime64 = 404;409 clock_gettime64 = 403,
410pub const SYS_clock_adjtime64 = 405;410 clock_settime64 = 404,
411pub const SYS_clock_getres_time64 = 406;411 clock_adjtime64 = 405,
412pub const SYS_clock_nanosleep_time64 = 407;412 clock_getres_time64 = 406,
413pub const SYS_timer_gettime64 = 408;413 clock_nanosleep_time64 = 407,
414pub const SYS_timer_settime64 = 409;414 timer_gettime64 = 408,
415pub const SYS_timerfd_gettime64 = 410;415 timer_settime64 = 409,
416pub const SYS_timerfd_settime64 = 411;416 timerfd_gettime64 = 410,
417pub const SYS_utimensat_time64 = 412;417 timerfd_settime64 = 411,
418pub const SYS_pselect6_time64 = 413;418 utimensat_time64 = 412,
419pub const SYS_ppoll_time64 = 414;419 pselect6_time64 = 413,
420pub const SYS_io_pgetevents_time64 = 416;420 ppoll_time64 = 414,
421pub const SYS_recvmmsg_time64 = 417;421 io_pgetevents_time64 = 416,
422pub const SYS_mq_timedsend_time64 = 418;422 recvmmsg_time64 = 417,
423pub const SYS_mq_timedreceive_time64 = 419;423 mq_timedsend_time64 = 418,
424pub const SYS_semtimedop_time64 = 420;424 mq_timedreceive_time64 = 419,
425pub const SYS_rt_sigtimedwait_time64 = 421;425 semtimedop_time64 = 420,
426pub const SYS_futex_time64 = 422;426 rt_sigtimedwait_time64 = 421,
427pub const SYS_sched_rr_get_interval_time64 = 423;427 futex_time64 = 422,
428pub const SYS_pidfd_send_signal = 424;428 sched_rr_get_interval_time64 = 423,
429pub const SYS_io_uring_setup = 425;429 pidfd_send_signal = 424,
430pub const SYS_io_uring_enter = 426;430 io_uring_setup = 425,
431pub const SYS_io_uring_register = 427;431 io_uring_enter = 426,
432pub const SYS_open_tree = 428;432 io_uring_register = 427,
433pub const SYS_move_mount = 429;433 open_tree = 428,
434pub const SYS_fsopen = 430;434 move_mount = 429,
435pub const SYS_fsconfig = 431;435 fsopen = 430,
436pub const SYS_fsmount = 432;436 fsconfig = 431,
437pub const SYS_fspick = 433;437 fsmount = 432,
438 fspick = 433,
439 openat2 = 437,
440 pidfd_getfd = 438,
441
442 _,
443};
438444
439pub const O_CREAT = 0o100;445pub const O_CREAT = 0o100;
440pub const O_EXCL = 0o200;446pub const O_EXCL = 0o200;
lib/std/os/bits/linux/mipsel.zig+376-369
...@@ -7,375 +7,382 @@ const uid_t = linux.uid_t;...@@ -7,375 +7,382 @@ const uid_t = linux.uid_t;
7const gid_t = linux.gid_t;7const gid_t = linux.gid_t;
8const pid_t = linux.pid_t;8const pid_t = linux.pid_t;
99
10pub const SYS_Linux = 4000;10pub const SYS = extern enum(usize) {
11pub const SYS_syscall = (SYS_Linux + 0);11 pub const Linux = 4000;
12pub const SYS_exit = (SYS_Linux + 1);12
13pub const SYS_fork = (SYS_Linux + 2);13 syscall = Linux + 0,
14pub const SYS_read = (SYS_Linux + 3);14 exit = Linux + 1,
15pub const SYS_write = (SYS_Linux + 4);15 fork = Linux + 2,
16pub const SYS_open = (SYS_Linux + 5);16 read = Linux + 3,
17pub const SYS_close = (SYS_Linux + 6);17 write = Linux + 4,
18pub const SYS_waitpid = (SYS_Linux + 7);18 open = Linux + 5,
19pub const SYS_creat = (SYS_Linux + 8);19 close = Linux + 6,
20pub const SYS_link = (SYS_Linux + 9);20 waitpid = Linux + 7,
21pub const SYS_unlink = (SYS_Linux + 10);21 creat = Linux + 8,
22pub const SYS_execve = (SYS_Linux + 11);22 link = Linux + 9,
23pub const SYS_chdir = (SYS_Linux + 12);23 unlink = Linux + 10,
24pub const SYS_time = (SYS_Linux + 13);24 execve = Linux + 11,
25pub const SYS_mknod = (SYS_Linux + 14);25 chdir = Linux + 12,
26pub const SYS_chmod = (SYS_Linux + 15);26 time = Linux + 13,
27pub const SYS_lchown = (SYS_Linux + 16);27 mknod = Linux + 14,
28pub const SYS_break = (SYS_Linux + 17);28 chmod = Linux + 15,
29pub const SYS_unused18 = (SYS_Linux + 18);29 lchown = Linux + 16,
30pub const SYS_lseek = (SYS_Linux + 19);30 @"break" = Linux + 17,
31pub const SYS_getpid = (SYS_Linux + 20);31 unused18 = Linux + 18,
32pub const SYS_mount = (SYS_Linux + 21);32 lseek = Linux + 19,
33pub const SYS_umount = (SYS_Linux + 22);33 getpid = Linux + 20,
34pub const SYS_setuid = (SYS_Linux + 23);34 mount = Linux + 21,
35pub const SYS_getuid = (SYS_Linux + 24);35 umount = Linux + 22,
36pub const SYS_stime = (SYS_Linux + 25);36 setuid = Linux + 23,
37pub const SYS_ptrace = (SYS_Linux + 26);37 getuid = Linux + 24,
38pub const SYS_alarm = (SYS_Linux + 27);38 stime = Linux + 25,
39pub const SYS_unused28 = (SYS_Linux + 28);39 ptrace = Linux + 26,
40pub const SYS_pause = (SYS_Linux + 29);40 alarm = Linux + 27,
41pub const SYS_utime = (SYS_Linux + 30);41 unused28 = Linux + 28,
42pub const SYS_stty = (SYS_Linux + 31);42 pause = Linux + 29,
43pub const SYS_gtty = (SYS_Linux + 32);43 utime = Linux + 30,
44pub const SYS_access = (SYS_Linux + 33);44 stty = Linux + 31,
45pub const SYS_nice = (SYS_Linux + 34);45 gtty = Linux + 32,
46pub const SYS_ftime = (SYS_Linux + 35);46 access = Linux + 33,
47pub const SYS_sync = (SYS_Linux + 36);47 nice = Linux + 34,
48pub const SYS_kill = (SYS_Linux + 37);48 ftime = Linux + 35,
49pub const SYS_rename = (SYS_Linux + 38);49 sync = Linux + 36,
50pub const SYS_mkdir = (SYS_Linux + 39);50 kill = Linux + 37,
51pub const SYS_rmdir = (SYS_Linux + 40);51 rename = Linux + 38,
52pub const SYS_dup = (SYS_Linux + 41);52 mkdir = Linux + 39,
53pub const SYS_pipe = (SYS_Linux + 42);53 rmdir = Linux + 40,
54pub const SYS_times = (SYS_Linux + 43);54 dup = Linux + 41,
55pub const SYS_prof = (SYS_Linux + 44);55 pipe = Linux + 42,
56pub const SYS_brk = (SYS_Linux + 45);56 times = Linux + 43,
57pub const SYS_setgid = (SYS_Linux + 46);57 prof = Linux + 44,
58pub const SYS_getgid = (SYS_Linux + 47);58 brk = Linux + 45,
59pub const SYS_signal = (SYS_Linux + 48);59 setgid = Linux + 46,
60pub const SYS_geteuid = (SYS_Linux + 49);60 getgid = Linux + 47,
61pub const SYS_getegid = (SYS_Linux + 50);61 signal = Linux + 48,
62pub const SYS_acct = (SYS_Linux + 51);62 geteuid = Linux + 49,
63pub const SYS_umount2 = (SYS_Linux + 52);63 getegid = Linux + 50,
64pub const SYS_lock = (SYS_Linux + 53);64 acct = Linux + 51,
65pub const SYS_ioctl = (SYS_Linux + 54);65 umount2 = Linux + 52,
66pub const SYS_fcntl = (SYS_Linux + 55);66 lock = Linux + 53,
67pub const SYS_mpx = (SYS_Linux + 56);67 ioctl = Linux + 54,
68pub const SYS_setpgid = (SYS_Linux + 57);68 fcntl = Linux + 55,
69pub const SYS_ulimit = (SYS_Linux + 58);69 mpx = Linux + 56,
70pub const SYS_unused59 = (SYS_Linux + 59);70 setpgid = Linux + 57,
71pub const SYS_umask = (SYS_Linux + 60);71 ulimit = Linux + 58,
72pub const SYS_chroot = (SYS_Linux + 61);72 unused59 = Linux + 59,
73pub const SYS_ustat = (SYS_Linux + 62);73 umask = Linux + 60,
74pub const SYS_dup2 = (SYS_Linux + 63);74 chroot = Linux + 61,
75pub const SYS_getppid = (SYS_Linux + 64);75 ustat = Linux + 62,
76pub const SYS_getpgrp = (SYS_Linux + 65);76 dup2 = Linux + 63,
77pub const SYS_setsid = (SYS_Linux + 66);77 getppid = Linux + 64,
78pub const SYS_sigaction = (SYS_Linux + 67);78 getpgrp = Linux + 65,
79pub const SYS_sgetmask = (SYS_Linux + 68);79 setsid = Linux + 66,
80pub const SYS_ssetmask = (SYS_Linux + 69);80 sigaction = Linux + 67,
81pub const SYS_setreuid = (SYS_Linux + 70);81 sgetmask = Linux + 68,
82pub const SYS_setregid = (SYS_Linux + 71);82 ssetmask = Linux + 69,
83pub const SYS_sigsuspend = (SYS_Linux + 72);83 setreuid = Linux + 70,
84pub const SYS_sigpending = (SYS_Linux + 73);84 setregid = Linux + 71,
85pub const SYS_sethostname = (SYS_Linux + 74);85 sigsuspend = Linux + 72,
86pub const SYS_setrlimit = (SYS_Linux + 75);86 sigpending = Linux + 73,
87pub const SYS_getrlimit = (SYS_Linux + 76);87 sethostname = Linux + 74,
88pub const SYS_getrusage = (SYS_Linux + 77);88 setrlimit = Linux + 75,
89pub const SYS_gettimeofday = (SYS_Linux + 78);89 getrlimit = Linux + 76,
90pub const SYS_settimeofday = (SYS_Linux + 79);90 getrusage = Linux + 77,
91pub const SYS_getgroups = (SYS_Linux + 80);91 gettimeofday = Linux + 78,
92pub const SYS_setgroups = (SYS_Linux + 81);92 settimeofday = Linux + 79,
93pub const SYS_reserved82 = (SYS_Linux + 82);93 getgroups = Linux + 80,
94pub const SYS_symlink = (SYS_Linux + 83);94 setgroups = Linux + 81,
95pub const SYS_unused84 = (SYS_Linux + 84);95 reserved82 = Linux + 82,
96pub const SYS_readlink = (SYS_Linux + 85);96 symlink = Linux + 83,
97pub const SYS_uselib = (SYS_Linux + 86);97 unused84 = Linux + 84,
98pub const SYS_swapon = (SYS_Linux + 87);98 readlink = Linux + 85,
99pub const SYS_reboot = (SYS_Linux + 88);99 uselib = Linux + 86,
100pub const SYS_readdir = (SYS_Linux + 89);100 swapon = Linux + 87,
101pub const SYS_mmap = (SYS_Linux + 90);101 reboot = Linux + 88,
102pub const SYS_munmap = (SYS_Linux + 91);102 readdir = Linux + 89,
103pub const SYS_truncate = (SYS_Linux + 92);103 mmap = Linux + 90,
104pub const SYS_ftruncate = (SYS_Linux + 93);104 munmap = Linux + 91,
105pub const SYS_fchmod = (SYS_Linux + 94);105 truncate = Linux + 92,
106pub const SYS_fchown = (SYS_Linux + 95);106 ftruncate = Linux + 93,
107pub const SYS_getpriority = (SYS_Linux + 96);107 fchmod = Linux + 94,
108pub const SYS_setpriority = (SYS_Linux + 97);108 fchown = Linux + 95,
109pub const SYS_profil = (SYS_Linux + 98);109 getpriority = Linux + 96,
110pub const SYS_statfs = (SYS_Linux + 99);110 setpriority = Linux + 97,
111pub const SYS_fstatfs = (SYS_Linux + 100);111 profil = Linux + 98,
112pub const SYS_ioperm = (SYS_Linux + 101);112 statfs = Linux + 99,
113pub const SYS_socketcall = (SYS_Linux + 102);113 fstatfs = Linux + 100,
114pub const SYS_syslog = (SYS_Linux + 103);114 ioperm = Linux + 101,
115pub const SYS_setitimer = (SYS_Linux + 104);115 socketcall = Linux + 102,
116pub const SYS_getitimer = (SYS_Linux + 105);116 syslog = Linux + 103,
117pub const SYS_stat = (SYS_Linux + 106);117 setitimer = Linux + 104,
118pub const SYS_lstat = (SYS_Linux + 107);118 getitimer = Linux + 105,
119pub const SYS_fstat = (SYS_Linux + 108);119 stat = Linux + 106,
120pub const SYS_unused109 = (SYS_Linux + 109);120 lstat = Linux + 107,
121pub const SYS_iopl = (SYS_Linux + 110);121 fstat = Linux + 108,
122pub const SYS_vhangup = (SYS_Linux + 111);122 unused109 = Linux + 109,
123pub const SYS_idle = (SYS_Linux + 112);123 iopl = Linux + 110,
124pub const SYS_vm86 = (SYS_Linux + 113);124 vhangup = Linux + 111,
125pub const SYS_wait4 = (SYS_Linux + 114);125 idle = Linux + 112,
126pub const SYS_swapoff = (SYS_Linux + 115);126 vm86 = Linux + 113,
127pub const SYS_sysinfo = (SYS_Linux + 116);127 wait4 = Linux + 114,
128pub const SYS_ipc = (SYS_Linux + 117);128 swapoff = Linux + 115,
129pub const SYS_fsync = (SYS_Linux + 118);129 sysinfo = Linux + 116,
130pub const SYS_sigreturn = (SYS_Linux + 119);130 ipc = Linux + 117,
131pub const SYS_clone = (SYS_Linux + 120);131 fsync = Linux + 118,
132pub const SYS_setdomainname = (SYS_Linux + 121);132 sigreturn = Linux + 119,
133pub const SYS_uname = (SYS_Linux + 122);133 clone = Linux + 120,
134pub const SYS_modify_ldt = (SYS_Linux + 123);134 setdomainname = Linux + 121,
135pub const SYS_adjtimex = (SYS_Linux + 124);135 uname = Linux + 122,
136pub const SYS_mprotect = (SYS_Linux + 125);136 modify_ldt = Linux + 123,
137pub const SYS_sigprocmask = (SYS_Linux + 126);137 adjtimex = Linux + 124,
138pub const SYS_create_module = (SYS_Linux + 127);138 mprotect = Linux + 125,
139pub const SYS_init_module = (SYS_Linux + 128);139 sigprocmask = Linux + 126,
140pub const SYS_delete_module = (SYS_Linux + 129);140 create_module = Linux + 127,
141pub const SYS_get_kernel_syms = (SYS_Linux + 130);141 init_module = Linux + 128,
142pub const SYS_quotactl = (SYS_Linux + 131);142 delete_module = Linux + 129,
143pub const SYS_getpgid = (SYS_Linux + 132);143 get_kernel_syms = Linux + 130,
144pub const SYS_fchdir = (SYS_Linux + 133);144 quotactl = Linux + 131,
145pub const SYS_bdflush = (SYS_Linux + 134);145 getpgid = Linux + 132,
146pub const SYS_sysfs = (SYS_Linux + 135);146 fchdir = Linux + 133,
147pub const SYS_personality = (SYS_Linux + 136);147 bdflush = Linux + 134,
148pub const SYS_afs_syscall = (SYS_Linux + 137);148 sysfs = Linux + 135,
149pub const SYS_setfsuid = (SYS_Linux + 138);149 personality = Linux + 136,
150pub const SYS_setfsgid = (SYS_Linux + 139);150 afs_syscall = Linux + 137,
151pub const SYS__llseek = (SYS_Linux + 140);151 setfsuid = Linux + 138,
152pub const SYS_getdents = (SYS_Linux + 141);152 setfsgid = Linux + 139,
153pub const SYS__newselect = (SYS_Linux + 142);153 _llseek = Linux + 140,
154pub const SYS_flock = (SYS_Linux + 143);154 getdents = Linux + 141,
155pub const SYS_msync = (SYS_Linux + 144);155 _newselect = Linux + 142,
156pub const SYS_readv = (SYS_Linux + 145);156 flock = Linux + 143,
157pub const SYS_writev = (SYS_Linux + 146);157 msync = Linux + 144,
158pub const SYS_cacheflush = (SYS_Linux + 147);158 readv = Linux + 145,
159pub const SYS_cachectl = (SYS_Linux + 148);159 writev = Linux + 146,
160pub const SYS_sysmips = (SYS_Linux + 149);160 cacheflush = Linux + 147,
161pub const SYS_unused150 = (SYS_Linux + 150);161 cachectl = Linux + 148,
162pub const SYS_getsid = (SYS_Linux + 151);162 sysmips = Linux + 149,
163pub const SYS_fdatasync = (SYS_Linux + 152);163 unused150 = Linux + 150,
164pub const SYS__sysctl = (SYS_Linux + 153);164 getsid = Linux + 151,
165pub const SYS_mlock = (SYS_Linux + 154);165 fdatasync = Linux + 152,
166pub const SYS_munlock = (SYS_Linux + 155);166 _sysctl = Linux + 153,
167pub const SYS_mlockall = (SYS_Linux + 156);167 mlock = Linux + 154,
168pub const SYS_munlockall = (SYS_Linux + 157);168 munlock = Linux + 155,
169pub const SYS_sched_setparam = (SYS_Linux + 158);169 mlockall = Linux + 156,
170pub const SYS_sched_getparam = (SYS_Linux + 159);170 munlockall = Linux + 157,
171pub const SYS_sched_setscheduler = (SYS_Linux + 160);171 sched_setparam = Linux + 158,
172pub const SYS_sched_getscheduler = (SYS_Linux + 161);172 sched_getparam = Linux + 159,
173pub const SYS_sched_yield = (SYS_Linux + 162);173 sched_setscheduler = Linux + 160,
174pub const SYS_sched_get_priority_max = (SYS_Linux + 163);174 sched_getscheduler = Linux + 161,
175pub const SYS_sched_get_priority_min = (SYS_Linux + 164);175 sched_yield = Linux + 162,
176pub const SYS_sched_rr_get_interval = (SYS_Linux + 165);176 sched_get_priority_max = Linux + 163,
177pub const SYS_nanosleep = (SYS_Linux + 166);177 sched_get_priority_min = Linux + 164,
178pub const SYS_mremap = (SYS_Linux + 167);178 sched_rr_get_interval = Linux + 165,
179pub const SYS_accept = (SYS_Linux + 168);179 nanosleep = Linux + 166,
180pub const SYS_bind = (SYS_Linux + 169);180 mremap = Linux + 167,
181pub const SYS_connect = (SYS_Linux + 170);181 accept = Linux + 168,
182pub const SYS_getpeername = (SYS_Linux + 171);182 bind = Linux + 169,
183pub const SYS_getsockname = (SYS_Linux + 172);183 connect = Linux + 170,
184pub const SYS_getsockopt = (SYS_Linux + 173);184 getpeername = Linux + 171,
185pub const SYS_listen = (SYS_Linux + 174);185 getsockname = Linux + 172,
186pub const SYS_recv = (SYS_Linux + 175);186 getsockopt = Linux + 173,
187pub const SYS_recvfrom = (SYS_Linux + 176);187 listen = Linux + 174,
188pub const SYS_recvmsg = (SYS_Linux + 177);188 recv = Linux + 175,
189pub const SYS_send = (SYS_Linux + 178);189 recvfrom = Linux + 176,
190pub const SYS_sendmsg = (SYS_Linux + 179);190 recvmsg = Linux + 177,
191pub const SYS_sendto = (SYS_Linux + 180);191 send = Linux + 178,
192pub const SYS_setsockopt = (SYS_Linux + 181);192 sendmsg = Linux + 179,
193pub const SYS_shutdown = (SYS_Linux + 182);193 sendto = Linux + 180,
194pub const SYS_socket = (SYS_Linux + 183);194 setsockopt = Linux + 181,
195pub const SYS_socketpair = (SYS_Linux + 184);195 shutdown = Linux + 182,
196pub const SYS_setresuid = (SYS_Linux + 185);196 socket = Linux + 183,
197pub const SYS_getresuid = (SYS_Linux + 186);197 socketpair = Linux + 184,
198pub const SYS_query_module = (SYS_Linux + 187);198 setresuid = Linux + 185,
199pub const SYS_poll = (SYS_Linux + 188);199 getresuid = Linux + 186,
200pub const SYS_nfsservctl = (SYS_Linux + 189);200 query_module = Linux + 187,
201pub const SYS_setresgid = (SYS_Linux + 190);201 poll = Linux + 188,
202pub const SYS_getresgid = (SYS_Linux + 191);202 nfsservctl = Linux + 189,
203pub const SYS_prctl = (SYS_Linux + 192);203 setresgid = Linux + 190,
204pub const SYS_rt_sigreturn = (SYS_Linux + 193);204 getresgid = Linux + 191,
205pub const SYS_rt_sigaction = (SYS_Linux + 194);205 prctl = Linux + 192,
206pub const SYS_rt_sigprocmask = (SYS_Linux + 195);206 rt_sigreturn = Linux + 193,
207pub const SYS_rt_sigpending = (SYS_Linux + 196);207 rt_sigaction = Linux + 194,
208pub const SYS_rt_sigtimedwait = (SYS_Linux + 197);208 rt_sigprocmask = Linux + 195,
209pub const SYS_rt_sigqueueinfo = (SYS_Linux + 198);209 rt_sigpending = Linux + 196,
210pub const SYS_rt_sigsuspend = (SYS_Linux + 199);210 rt_sigtimedwait = Linux + 197,
211pub const SYS_pread64 = (SYS_Linux + 200);211 rt_sigqueueinfo = Linux + 198,
212pub const SYS_pwrite64 = (SYS_Linux + 201);212 rt_sigsuspend = Linux + 199,
213pub const SYS_chown = (SYS_Linux + 202);213 pread64 = Linux + 200,
214pub const SYS_getcwd = (SYS_Linux + 203);214 pwrite64 = Linux + 201,
215pub const SYS_capget = (SYS_Linux + 204);215 chown = Linux + 202,
216pub const SYS_capset = (SYS_Linux + 205);216 getcwd = Linux + 203,
217pub const SYS_sigaltstack = (SYS_Linux + 206);217 capget = Linux + 204,
218pub const SYS_sendfile = (SYS_Linux + 207);218 capset = Linux + 205,
219pub const SYS_getpmsg = (SYS_Linux + 208);219 sigaltstack = Linux + 206,
220pub const SYS_putpmsg = (SYS_Linux + 209);220 sendfile = Linux + 207,
221pub const SYS_mmap2 = (SYS_Linux + 210);221 getpmsg = Linux + 208,
222pub const SYS_truncate64 = (SYS_Linux + 211);222 putpmsg = Linux + 209,
223pub const SYS_ftruncate64 = (SYS_Linux + 212);223 mmap2 = Linux + 210,
224pub const SYS_stat64 = (SYS_Linux + 213);224 truncate64 = Linux + 211,
225pub const SYS_lstat64 = (SYS_Linux + 214);225 ftruncate64 = Linux + 212,
226pub const SYS_fstat64 = (SYS_Linux + 215);226 stat64 = Linux + 213,
227pub const SYS_pivot_root = (SYS_Linux + 216);227 lstat64 = Linux + 214,
228pub const SYS_mincore = (SYS_Linux + 217);228 fstat64 = Linux + 215,
229pub const SYS_madvise = (SYS_Linux + 218);229 pivot_root = Linux + 216,
230pub const SYS_getdents64 = (SYS_Linux + 219);230 mincore = Linux + 217,
231pub const SYS_fcntl64 = (SYS_Linux + 220);231 madvise = Linux + 218,
232pub const SYS_reserved221 = (SYS_Linux + 221);232 getdents64 = Linux + 219,
233pub const SYS_gettid = (SYS_Linux + 222);233 fcntl64 = Linux + 220,
234pub const SYS_readahead = (SYS_Linux + 223);234 reserved221 = Linux + 221,
235pub const SYS_setxattr = (SYS_Linux + 224);235 gettid = Linux + 222,
236pub const SYS_lsetxattr = (SYS_Linux + 225);236 readahead = Linux + 223,
237pub const SYS_fsetxattr = (SYS_Linux + 226);237 setxattr = Linux + 224,
238pub const SYS_getxattr = (SYS_Linux + 227);238 lsetxattr = Linux + 225,
239pub const SYS_lgetxattr = (SYS_Linux + 228);239 fsetxattr = Linux + 226,
240pub const SYS_fgetxattr = (SYS_Linux + 229);240 getxattr = Linux + 227,
241pub const SYS_listxattr = (SYS_Linux + 230);241 lgetxattr = Linux + 228,
242pub const SYS_llistxattr = (SYS_Linux + 231);242 fgetxattr = Linux + 229,
243pub const SYS_flistxattr = (SYS_Linux + 232);243 listxattr = Linux + 230,
244pub const SYS_removexattr = (SYS_Linux + 233);244 llistxattr = Linux + 231,
245pub const SYS_lremovexattr = (SYS_Linux + 234);245 flistxattr = Linux + 232,
246pub const SYS_fremovexattr = (SYS_Linux + 235);246 removexattr = Linux + 233,
247pub const SYS_tkill = (SYS_Linux + 236);247 lremovexattr = Linux + 234,
248pub const SYS_sendfile64 = (SYS_Linux + 237);248 fremovexattr = Linux + 235,
249pub const SYS_futex = (SYS_Linux + 238);249 tkill = Linux + 236,
250pub const SYS_sched_setaffinity = (SYS_Linux + 239);250 sendfile64 = Linux + 237,
251pub const SYS_sched_getaffinity = (SYS_Linux + 240);251 futex = Linux + 238,
252pub const SYS_io_setup = (SYS_Linux + 241);252 sched_setaffinity = Linux + 239,
253pub const SYS_io_destroy = (SYS_Linux + 242);253 sched_getaffinity = Linux + 240,
254pub const SYS_io_getevents = (SYS_Linux + 243);254 io_setup = Linux + 241,
255pub const SYS_io_submit = (SYS_Linux + 244);255 io_destroy = Linux + 242,
256pub const SYS_io_cancel = (SYS_Linux + 245);256 io_getevents = Linux + 243,
257pub const SYS_exit_group = (SYS_Linux + 246);257 io_submit = Linux + 244,
258pub const SYS_lookup_dcookie = (SYS_Linux + 247);258 io_cancel = Linux + 245,
259pub const SYS_epoll_create = (SYS_Linux + 248);259 exit_group = Linux + 246,
260pub const SYS_epoll_ctl = (SYS_Linux + 249);260 lookup_dcookie = Linux + 247,
261pub const SYS_epoll_wait = (SYS_Linux + 250);261 epoll_create = Linux + 248,
262pub const SYS_remap_file_pages = (SYS_Linux + 251);262 epoll_ctl = Linux + 249,
263pub const SYS_set_tid_address = (SYS_Linux + 252);263 epoll_wait = Linux + 250,
264pub const SYS_restart_syscall = (SYS_Linux + 253);264 remap_file_pages = Linux + 251,
265pub const SYS_fadvise64 = (SYS_Linux + 254);265 set_tid_address = Linux + 252,
266pub const SYS_statfs64 = (SYS_Linux + 255);266 restart_syscall = Linux + 253,
267pub const SYS_fstatfs64 = (SYS_Linux + 256);267 fadvise64 = Linux + 254,
268pub const SYS_timer_create = (SYS_Linux + 257);268 statfs64 = Linux + 255,
269pub const SYS_timer_settime = (SYS_Linux + 258);269 fstatfs64 = Linux + 256,
270pub const SYS_timer_gettime = (SYS_Linux + 259);270 timer_create = Linux + 257,
271pub const SYS_timer_getoverrun = (SYS_Linux + 260);271 timer_settime = Linux + 258,
272pub const SYS_timer_delete = (SYS_Linux + 261);272 timer_gettime = Linux + 259,
273pub const SYS_clock_settime = (SYS_Linux + 262);273 timer_getoverrun = Linux + 260,
274pub const SYS_clock_gettime = (SYS_Linux + 263);274 timer_delete = Linux + 261,
275pub const SYS_clock_getres = (SYS_Linux + 264);275 clock_settime = Linux + 262,
276pub const SYS_clock_nanosleep = (SYS_Linux + 265);276 clock_gettime = Linux + 263,
277pub const SYS_tgkill = (SYS_Linux + 266);277 clock_getres = Linux + 264,
278pub const SYS_utimes = (SYS_Linux + 267);278 clock_nanosleep = Linux + 265,
279pub const SYS_mbind = (SYS_Linux + 268);279 tgkill = Linux + 266,
280pub const SYS_get_mempolicy = (SYS_Linux + 269);280 utimes = Linux + 267,
281pub const SYS_set_mempolicy = (SYS_Linux + 270);281 mbind = Linux + 268,
282pub const SYS_mq_open = (SYS_Linux + 271);282 get_mempolicy = Linux + 269,
283pub const SYS_mq_unlink = (SYS_Linux + 272);283 set_mempolicy = Linux + 270,
284pub const SYS_mq_timedsend = (SYS_Linux + 273);284 mq_open = Linux + 271,
285pub const SYS_mq_timedreceive = (SYS_Linux + 274);285 mq_unlink = Linux + 272,
286pub const SYS_mq_notify = (SYS_Linux + 275);286 mq_timedsend = Linux + 273,
287pub const SYS_mq_getsetattr = (SYS_Linux + 276);287 mq_timedreceive = Linux + 274,
288pub const SYS_vserver = (SYS_Linux + 277);288 mq_notify = Linux + 275,
289pub const SYS_waitid = (SYS_Linux + 278);289 mq_getsetattr = Linux + 276,
290pub const SYS_add_key = (SYS_Linux + 280);290 vserver = Linux + 277,
291pub const SYS_request_key = (SYS_Linux + 281);291 waitid = Linux + 278,
292pub const SYS_keyctl = (SYS_Linux + 282);292 add_key = Linux + 280,
293pub const SYS_set_thread_area = (SYS_Linux + 283);293 request_key = Linux + 281,
294pub const SYS_inotify_init = (SYS_Linux + 284);294 keyctl = Linux + 282,
295pub const SYS_inotify_add_watch = (SYS_Linux + 285);295 set_thread_area = Linux + 283,
296pub const SYS_inotify_rm_watch = (SYS_Linux + 286);296 inotify_init = Linux + 284,
297pub const SYS_migrate_pages = (SYS_Linux + 287);297 inotify_add_watch = Linux + 285,
298pub const SYS_openat = (SYS_Linux + 288);298 inotify_rm_watch = Linux + 286,
299pub const SYS_mkdirat = (SYS_Linux + 289);299 migrate_pages = Linux + 287,
300pub const SYS_mknodat = (SYS_Linux + 290);300 openat = Linux + 288,
301pub const SYS_fchownat = (SYS_Linux + 291);301 mkdirat = Linux + 289,
302pub const SYS_futimesat = (SYS_Linux + 292);302 mknodat = Linux + 290,
303pub const SYS_fstatat64 = (SYS_Linux + 293);303 fchownat = Linux + 291,
304pub const SYS_unlinkat = (SYS_Linux + 294);304 futimesat = Linux + 292,
305pub const SYS_renameat = (SYS_Linux + 295);305 fstatat64 = Linux + 293,
306pub const SYS_linkat = (SYS_Linux + 296);306 unlinkat = Linux + 294,
307pub const SYS_symlinkat = (SYS_Linux + 297);307 renameat = Linux + 295,
308pub const SYS_readlinkat = (SYS_Linux + 298);308 linkat = Linux + 296,
309pub const SYS_fchmodat = (SYS_Linux + 299);309 symlinkat = Linux + 297,
310pub const SYS_faccessat = (SYS_Linux + 300);310 readlinkat = Linux + 298,
311pub const SYS_pselect6 = (SYS_Linux + 301);311 fchmodat = Linux + 299,
312pub const SYS_ppoll = (SYS_Linux + 302);312 faccessat = Linux + 300,
313pub const SYS_unshare = (SYS_Linux + 303);313 pselect6 = Linux + 301,
314pub const SYS_splice = (SYS_Linux + 304);314 ppoll = Linux + 302,
315pub const SYS_sync_file_range = (SYS_Linux + 305);315 unshare = Linux + 303,
316pub const SYS_tee = (SYS_Linux + 306);316 splice = Linux + 304,
317pub const SYS_vmsplice = (SYS_Linux + 307);317 sync_file_range = Linux + 305,
318pub const SYS_move_pages = (SYS_Linux + 308);318 tee = Linux + 306,
319pub const SYS_set_robust_list = (SYS_Linux + 309);319 vmsplice = Linux + 307,
320pub const SYS_get_robust_list = (SYS_Linux + 310);320 move_pages = Linux + 308,
321pub const SYS_kexec_load = (SYS_Linux + 311);321 set_robust_list = Linux + 309,
322pub const SYS_getcpu = (SYS_Linux + 312);322 get_robust_list = Linux + 310,
323pub const SYS_epoll_pwait = (SYS_Linux + 313);323 kexec_load = Linux + 311,
324pub const SYS_ioprio_set = (SYS_Linux + 314);324 getcpu = Linux + 312,
325pub const SYS_ioprio_get = (SYS_Linux + 315);325 epoll_pwait = Linux + 313,
326pub const SYS_utimensat = (SYS_Linux + 316);326 ioprio_set = Linux + 314,
327pub const SYS_signalfd = (SYS_Linux + 317);327 ioprio_get = Linux + 315,
328pub const SYS_timerfd = (SYS_Linux + 318);328 utimensat = Linux + 316,
329pub const SYS_eventfd = (SYS_Linux + 319);329 signalfd = Linux + 317,
330pub const SYS_fallocate = (SYS_Linux + 320);330 timerfd = Linux + 318,
331pub const SYS_timerfd_create = (SYS_Linux + 321);331 eventfd = Linux + 319,
332pub const SYS_timerfd_gettime = (SYS_Linux + 322);332 fallocate = Linux + 320,
333pub const SYS_timerfd_settime = (SYS_Linux + 323);333 timerfd_create = Linux + 321,
334pub const SYS_signalfd4 = (SYS_Linux + 324);334 timerfd_gettime = Linux + 322,
335pub const SYS_eventfd2 = (SYS_Linux + 325);335 timerfd_settime = Linux + 323,
336pub const SYS_epoll_create1 = (SYS_Linux + 326);336 signalfd4 = Linux + 324,
337pub const SYS_dup3 = (SYS_Linux + 327);337 eventfd2 = Linux + 325,
338pub const SYS_pipe2 = (SYS_Linux + 328);338 epoll_create1 = Linux + 326,
339pub const SYS_inotify_init1 = (SYS_Linux + 329);339 dup3 = Linux + 327,
340pub const SYS_preadv = (SYS_Linux + 330);340 pipe2 = Linux + 328,
341pub const SYS_pwritev = (SYS_Linux + 331);341 inotify_init1 = Linux + 329,
342pub const SYS_rt_tgsigqueueinfo = (SYS_Linux + 332);342 preadv = Linux + 330,
343pub const SYS_perf_event_open = (SYS_Linux + 333);343 pwritev = Linux + 331,
344pub const SYS_accept4 = (SYS_Linux + 334);344 rt_tgsigqueueinfo = Linux + 332,
345pub const SYS_recvmmsg = (SYS_Linux + 335);345 perf_event_open = Linux + 333,
346pub const SYS_fanotify_init = (SYS_Linux + 336);346 accept4 = Linux + 334,
347pub const SYS_fanotify_mark = (SYS_Linux + 337);347 recvmmsg = Linux + 335,
348pub const SYS_prlimit64 = (SYS_Linux + 338);348 fanotify_init = Linux + 336,
349pub const SYS_name_to_handle_at = (SYS_Linux + 339);349 fanotify_mark = Linux + 337,
350pub const SYS_open_by_handle_at = (SYS_Linux + 340);350 prlimit64 = Linux + 338,
351pub const SYS_clock_adjtime = (SYS_Linux + 341);351 name_to_handle_at = Linux + 339,
352pub const SYS_syncfs = (SYS_Linux + 342);352 open_by_handle_at = Linux + 340,
353pub const SYS_sendmmsg = (SYS_Linux + 343);353 clock_adjtime = Linux + 341,
354pub const SYS_setns = (SYS_Linux + 344);354 syncfs = Linux + 342,
355pub const SYS_process_vm_readv = (SYS_Linux + 345);355 sendmmsg = Linux + 343,
356pub const SYS_process_vm_writev = (SYS_Linux + 346);356 setns = Linux + 344,
357pub const SYS_kcmp = (SYS_Linux + 347);357 process_vm_readv = Linux + 345,
358pub const SYS_finit_module = (SYS_Linux + 348);358 process_vm_writev = Linux + 346,
359pub const SYS_sched_setattr = (SYS_Linux + 349);359 kcmp = Linux + 347,
360pub const SYS_sched_getattr = (SYS_Linux + 350);360 finit_module = Linux + 348,
361pub const SYS_renameat2 = (SYS_Linux + 351);361 sched_setattr = Linux + 349,
362pub const SYS_seccomp = (SYS_Linux + 352);362 sched_getattr = Linux + 350,
363pub const SYS_getrandom = (SYS_Linux + 353);363 renameat2 = Linux + 351,
364pub const SYS_memfd_create = (SYS_Linux + 354);364 seccomp = Linux + 352,
365pub const SYS_bpf = (SYS_Linux + 355);365 getrandom = Linux + 353,
366pub const SYS_execveat = (SYS_Linux + 356);366 memfd_create = Linux + 354,
367pub const SYS_userfaultfd = (SYS_Linux + 357);367 bpf = Linux + 355,
368pub const SYS_membarrier = (SYS_Linux + 358);368 execveat = Linux + 356,
369pub const SYS_mlock2 = (SYS_Linux + 359);369 userfaultfd = Linux + 357,
370pub const SYS_copy_file_range = (SYS_Linux + 360);370 membarrier = Linux + 358,
371pub const SYS_preadv2 = (SYS_Linux + 361);371 mlock2 = Linux + 359,
372pub const SYS_pwritev2 = (SYS_Linux + 362);372 copy_file_range = Linux + 360,
373pub const SYS_pkey_mprotect = (SYS_Linux + 363);373 preadv2 = Linux + 361,
374pub const SYS_pkey_alloc = (SYS_Linux + 364);374 pwritev2 = Linux + 362,
375pub const SYS_pkey_free = (SYS_Linux + 365);375 pkey_mprotect = Linux + 363,
376pub const SYS_statx = (SYS_Linux + 366);376 pkey_alloc = Linux + 364,
377pub const SYS_rseq = (SYS_Linux + 367);377 pkey_free = Linux + 365,
378pub const SYS_io_pgetevents = (SYS_Linux + 368);378 statx = Linux + 366,
379 rseq = Linux + 367,
380 io_pgetevents = Linux + 368,
381 openat2 = Linux + 437,
382 pidfd_getfd = Linux + 438,
383
384 _,
385};
379386
380pub const O_CREAT = 0o0400;387pub const O_CREAT = 0o0400;
381pub const O_EXCL = 0o02000;388pub const O_EXCL = 0o02000;
lib/std/os/bits/linux/riscv64.zig+298-292
...@@ -4,300 +4,306 @@ const uid_t = std.os.linux.uid_t;...@@ -4,300 +4,306 @@ const uid_t = std.os.linux.uid_t;
4const gid_t = std.os.linux.gid_t;4const gid_t = std.os.linux.gid_t;
5const pid_t = std.os.linux.pid_t;5const pid_t = std.os.linux.pid_t;
66
7pub const SYS_io_setup = 0;7pub const SYS = extern enum(usize) {
8pub const SYS_io_destroy = 1;8 io_setup = 0,
9pub const SYS_io_submit = 2;9 io_destroy = 1,
10pub const SYS_io_cancel = 3;10 io_submit = 2,
11pub const SYS_io_getevents = 4;11 io_cancel = 3,
12pub const SYS_setxattr = 5;12 io_getevents = 4,
13pub const SYS_lsetxattr = 6;13 setxattr = 5,
14pub const SYS_fsetxattr = 7;14 lsetxattr = 6,
15pub const SYS_getxattr = 8;15 fsetxattr = 7,
16pub const SYS_lgetxattr = 9;16 getxattr = 8,
17pub const SYS_fgetxattr = 10;17 lgetxattr = 9,
18pub const SYS_listxattr = 11;18 fgetxattr = 10,
19pub const SYS_llistxattr = 12;19 listxattr = 11,
20pub const SYS_flistxattr = 13;20 llistxattr = 12,
21pub const SYS_removexattr = 14;21 flistxattr = 13,
22pub const SYS_lremovexattr = 15;22 removexattr = 14,
23pub const SYS_fremovexattr = 16;23 lremovexattr = 15,
24pub const SYS_getcwd = 17;24 fremovexattr = 16,
25pub const SYS_lookup_dcookie = 18;25 getcwd = 17,
26pub const SYS_eventfd2 = 19;26 lookup_dcookie = 18,
27pub const SYS_epoll_create1 = 20;27 eventfd2 = 19,
28pub const SYS_epoll_ctl = 21;28 epoll_create1 = 20,
29pub const SYS_epoll_pwait = 22;29 epoll_ctl = 21,
30pub const SYS_dup = 23;30 epoll_pwait = 22,
31pub const SYS_dup3 = 24;31 dup = 23,
32pub const SYS_fcntl = 25;32 dup3 = 24,
33pub const SYS_inotify_init1 = 26;33 fcntl = 25,
34pub const SYS_inotify_add_watch = 27;34 inotify_init1 = 26,
35pub const SYS_inotify_rm_watch = 28;35 inotify_add_watch = 27,
36pub const SYS_ioctl = 29;36 inotify_rm_watch = 28,
37pub const SYS_ioprio_set = 30;37 ioctl = 29,
38pub const SYS_ioprio_get = 31;38 ioprio_set = 30,
39pub const SYS_flock = 32;39 ioprio_get = 31,
40pub const SYS_mknodat = 33;40 flock = 32,
41pub const SYS_mkdirat = 34;41 mknodat = 33,
42pub const SYS_unlinkat = 35;42 mkdirat = 34,
43pub const SYS_symlinkat = 36;43 unlinkat = 35,
44pub const SYS_linkat = 37;44 symlinkat = 36,
45pub const SYS_umount2 = 39;45 linkat = 37,
46pub const SYS_mount = 40;46 umount2 = 39,
47pub const SYS_pivot_root = 41;47 mount = 40,
48pub const SYS_nfsservctl = 42;48 pivot_root = 41,
49pub const SYS_statfs = 43;49 nfsservctl = 42,
50pub const SYS_fstatfs = 44;50 statfs = 43,
51pub const SYS_truncate = 45;51 fstatfs = 44,
52pub const SYS_ftruncate = 46;52 truncate = 45,
53pub const SYS_fallocate = 47;53 ftruncate = 46,
54pub const SYS_faccessat = 48;54 fallocate = 47,
55pub const SYS_chdir = 49;55 faccessat = 48,
56pub const SYS_fchdir = 50;56 chdir = 49,
57pub const SYS_chroot = 51;57 fchdir = 50,
58pub const SYS_fchmod = 52;58 chroot = 51,
59pub const SYS_fchmodat = 53;59 fchmod = 52,
60pub const SYS_fchownat = 54;60 fchmodat = 53,
61pub const SYS_fchown = 55;61 fchownat = 54,
62pub const SYS_openat = 56;62 fchown = 55,
63pub const SYS_close = 57;63 openat = 56,
64pub const SYS_vhangup = 58;64 close = 57,
65pub const SYS_pipe2 = 59;65 vhangup = 58,
66pub const SYS_quotactl = 60;66 pipe2 = 59,
67pub const SYS_getdents64 = 61;67 quotactl = 60,
68pub const SYS_lseek = 62;68 getdents64 = 61,
69pub const SYS_read = 63;69 lseek = 62,
70pub const SYS_write = 64;70 read = 63,
71pub const SYS_readv = 65;71 write = 64,
72pub const SYS_writev = 66;72 readv = 65,
73pub const SYS_pread64 = 67;73 writev = 66,
74pub const SYS_pwrite64 = 68;74 pread64 = 67,
75pub const SYS_preadv = 69;75 pwrite64 = 68,
76pub const SYS_pwritev = 70;76 preadv = 69,
77pub const SYS_sendfile = 71;77 pwritev = 70,
78pub const SYS_pselect6 = 72;78 sendfile = 71,
79pub const SYS_ppoll = 73;79 pselect6 = 72,
80pub const SYS_signalfd4 = 74;80 ppoll = 73,
81pub const SYS_vmsplice = 75;81 signalfd4 = 74,
82pub const SYS_splice = 76;82 vmsplice = 75,
83pub const SYS_tee = 77;83 splice = 76,
84pub const SYS_readlinkat = 78;84 tee = 77,
85pub const SYS_fstatat = 79;85 readlinkat = 78,
86pub const SYS_fstat = 80;86 fstatat = 79,
87pub const SYS_sync = 81;87 fstat = 80,
88pub const SYS_fsync = 82;88 sync = 81,
89pub const SYS_fdatasync = 83;89 fsync = 82,
90pub const SYS_sync_file_range = 84;90 fdatasync = 83,
91pub const SYS_timerfd_create = 85;91 sync_file_range = 84,
92pub const SYS_timerfd_settime = 86;92 timerfd_create = 85,
93pub const SYS_timerfd_gettime = 87;93 timerfd_settime = 86,
94pub const SYS_utimensat = 88;94 timerfd_gettime = 87,
95pub const SYS_acct = 89;95 utimensat = 88,
96pub const SYS_capget = 90;96 acct = 89,
97pub const SYS_capset = 91;97 capget = 90,
98pub const SYS_personality = 92;98 capset = 91,
99pub const SYS_exit = 93;99 personality = 92,
100pub const SYS_exit_group = 94;100 exit = 93,
101pub const SYS_waitid = 95;101 exit_group = 94,
102pub const SYS_set_tid_address = 96;102 waitid = 95,
103pub const SYS_unshare = 97;103 set_tid_address = 96,
104pub const SYS_futex = 98;104 unshare = 97,
105pub const SYS_set_robust_list = 99;105 futex = 98,
106pub const SYS_get_robust_list = 100;106 set_robust_list = 99,
107pub const SYS_nanosleep = 101;107 get_robust_list = 100,
108pub const SYS_getitimer = 102;108 nanosleep = 101,
109pub const SYS_setitimer = 103;109 getitimer = 102,
110pub const SYS_kexec_load = 104;110 setitimer = 103,
111pub const SYS_init_module = 105;111 kexec_load = 104,
112pub const SYS_delete_module = 106;112 init_module = 105,
113pub const SYS_timer_create = 107;113 delete_module = 106,
114pub const SYS_timer_gettime = 108;114 timer_create = 107,
115pub const SYS_timer_getoverrun = 109;115 timer_gettime = 108,
116pub const SYS_timer_settime = 110;116 timer_getoverrun = 109,
117pub const SYS_timer_delete = 111;117 timer_settime = 110,
118pub const SYS_clock_settime = 112;118 timer_delete = 111,
119pub const SYS_clock_gettime = 113;119 clock_settime = 112,
120pub const SYS_clock_getres = 114;120 clock_gettime = 113,
121pub const SYS_clock_nanosleep = 115;121 clock_getres = 114,
122pub const SYS_syslog = 116;122 clock_nanosleep = 115,
123pub const SYS_ptrace = 117;123 syslog = 116,
124pub const SYS_sched_setparam = 118;124 ptrace = 117,
125pub const SYS_sched_setscheduler = 119;125 sched_setparam = 118,
126pub const SYS_sched_getscheduler = 120;126 sched_setscheduler = 119,
127pub const SYS_sched_getparam = 121;127 sched_getscheduler = 120,
128pub const SYS_sched_setaffinity = 122;128 sched_getparam = 121,
129pub const SYS_sched_getaffinity = 123;129 sched_setaffinity = 122,
130pub const SYS_sched_yield = 124;130 sched_getaffinity = 123,
131pub const SYS_sched_get_priority_max = 125;131 sched_yield = 124,
132pub const SYS_sched_get_priority_min = 126;132 sched_get_priority_max = 125,
133pub const SYS_sched_rr_get_interval = 127;133 sched_get_priority_min = 126,
134pub const SYS_restart_syscall = 128;134 sched_rr_get_interval = 127,
135pub const SYS_kill = 129;135 restart_syscall = 128,
136pub const SYS_tkill = 130;136 kill = 129,
137pub const SYS_tgkill = 131;137 tkill = 130,
138pub const SYS_sigaltstack = 132;138 tgkill = 131,
139pub const SYS_rt_sigsuspend = 133;139 sigaltstack = 132,
140pub const SYS_rt_sigaction = 134;140 rt_sigsuspend = 133,
141pub const SYS_rt_sigprocmask = 135;141 rt_sigaction = 134,
142pub const SYS_rt_sigpending = 136;142 rt_sigprocmask = 135,
143pub const SYS_rt_sigtimedwait = 137;143 rt_sigpending = 136,
144pub const SYS_rt_sigqueueinfo = 138;144 rt_sigtimedwait = 137,
145pub const SYS_rt_sigreturn = 139;145 rt_sigqueueinfo = 138,
146pub const SYS_setpriority = 140;146 rt_sigreturn = 139,
147pub const SYS_getpriority = 141;147 setpriority = 140,
148pub const SYS_reboot = 142;148 getpriority = 141,
149pub const SYS_setregid = 143;149 reboot = 142,
150pub const SYS_setgid = 144;150 setregid = 143,
151pub const SYS_setreuid = 145;151 setgid = 144,
152pub const SYS_setuid = 146;152 setreuid = 145,
153pub const SYS_setresuid = 147;153 setuid = 146,
154pub const SYS_getresuid = 148;154 setresuid = 147,
155pub const SYS_setresgid = 149;155 getresuid = 148,
156pub const SYS_getresgid = 150;156 setresgid = 149,
157pub const SYS_setfsuid = 151;157 getresgid = 150,
158pub const SYS_setfsgid = 152;158 setfsuid = 151,
159pub const SYS_times = 153;159 setfsgid = 152,
160pub const SYS_setpgid = 154;160 times = 153,
161pub const SYS_getpgid = 155;161 setpgid = 154,
162pub const SYS_getsid = 156;162 getpgid = 155,
163pub const SYS_setsid = 157;163 getsid = 156,
164pub const SYS_getgroups = 158;164 setsid = 157,
165pub const SYS_setgroups = 159;165 getgroups = 158,
166pub const SYS_uname = 160;166 setgroups = 159,
167pub const SYS_sethostname = 161;167 uname = 160,
168pub const SYS_setdomainname = 162;168 sethostname = 161,
169pub const SYS_getrlimit = 163;169 setdomainname = 162,
170pub const SYS_setrlimit = 164;170 getrlimit = 163,
171pub const SYS_getrusage = 165;171 setrlimit = 164,
172pub const SYS_umask = 166;172 getrusage = 165,
173pub const SYS_prctl = 167;173 umask = 166,
174pub const SYS_getcpu = 168;174 prctl = 167,
175pub const SYS_gettimeofday = 169;175 getcpu = 168,
176pub const SYS_settimeofday = 170;176 gettimeofday = 169,
177pub const SYS_adjtimex = 171;177 settimeofday = 170,
178pub const SYS_getpid = 172;178 adjtimex = 171,
179pub const SYS_getppid = 173;179 getpid = 172,
180pub const SYS_getuid = 174;180 getppid = 173,
181pub const SYS_geteuid = 175;181 getuid = 174,
182pub const SYS_getgid = 176;182 geteuid = 175,
183pub const SYS_getegid = 177;183 getgid = 176,
184pub const SYS_gettid = 178;184 getegid = 177,
185pub const SYS_sysinfo = 179;185 gettid = 178,
186pub const SYS_mq_open = 180;186 sysinfo = 179,
187pub const SYS_mq_unlink = 181;187 mq_open = 180,
188pub const SYS_mq_timedsend = 182;188 mq_unlink = 181,
189pub const SYS_mq_timedreceive = 183;189 mq_timedsend = 182,
190pub const SYS_mq_notify = 184;190 mq_timedreceive = 183,
191pub const SYS_mq_getsetattr = 185;191 mq_notify = 184,
192pub const SYS_msgget = 186;192 mq_getsetattr = 185,
193pub const SYS_msgctl = 187;193 msgget = 186,
194pub const SYS_msgrcv = 188;194 msgctl = 187,
195pub const SYS_msgsnd = 189;195 msgrcv = 188,
196pub const SYS_semget = 190;196 msgsnd = 189,
197pub const SYS_semctl = 191;197 semget = 190,
198pub const SYS_semtimedop = 192;198 semctl = 191,
199pub const SYS_semop = 193;199 semtimedop = 192,
200pub const SYS_shmget = 194;200 semop = 193,
201pub const SYS_shmctl = 195;201 shmget = 194,
202pub const SYS_shmat = 196;202 shmctl = 195,
203pub const SYS_shmdt = 197;203 shmat = 196,
204pub const SYS_socket = 198;204 shmdt = 197,
205pub const SYS_socketpair = 199;205 socket = 198,
206pub const SYS_bind = 200;206 socketpair = 199,
207pub const SYS_listen = 201;207 bind = 200,
208pub const SYS_accept = 202;208 listen = 201,
209pub const SYS_connect = 203;209 accept = 202,
210pub const SYS_getsockname = 204;210 connect = 203,
211pub const SYS_getpeername = 205;211 getsockname = 204,
212pub const SYS_sendto = 206;212 getpeername = 205,
213pub const SYS_recvfrom = 207;213 sendto = 206,
214pub const SYS_setsockopt = 208;214 recvfrom = 207,
215pub const SYS_getsockopt = 209;215 setsockopt = 208,
216pub const SYS_shutdown = 210;216 getsockopt = 209,
217pub const SYS_sendmsg = 211;217 shutdown = 210,
218pub const SYS_recvmsg = 212;218 sendmsg = 211,
219pub const SYS_readahead = 213;219 recvmsg = 212,
220pub const SYS_brk = 214;220 readahead = 213,
221pub const SYS_munmap = 215;221 brk = 214,
222pub const SYS_mremap = 216;222 munmap = 215,
223pub const SYS_add_key = 217;223 mremap = 216,
224pub const SYS_request_key = 218;224 add_key = 217,
225pub const SYS_keyctl = 219;225 request_key = 218,
226pub const SYS_clone = 220;226 keyctl = 219,
227pub const SYS_execve = 221;227 clone = 220,
228pub const SYS_mmap = 222;228 execve = 221,
229pub const SYS_fadvise64 = 223;229 mmap = 222,
230pub const SYS_swapon = 224;230 fadvise64 = 223,
231pub const SYS_swapoff = 225;231 swapon = 224,
232pub const SYS_mprotect = 226;232 swapoff = 225,
233pub const SYS_msync = 227;233 mprotect = 226,
234pub const SYS_mlock = 228;234 msync = 227,
235pub const SYS_munlock = 229;235 mlock = 228,
236pub const SYS_mlockall = 230;236 munlock = 229,
237pub const SYS_munlockall = 231;237 mlockall = 230,
238pub const SYS_mincore = 232;238 munlockall = 231,
239pub const SYS_madvise = 233;239 mincore = 232,
240pub const SYS_remap_file_pages = 234;240 madvise = 233,
241pub const SYS_mbind = 235;241 remap_file_pages = 234,
242pub const SYS_get_mempolicy = 236;242 mbind = 235,
243pub const SYS_set_mempolicy = 237;243 get_mempolicy = 236,
244pub const SYS_migrate_pages = 238;244 set_mempolicy = 237,
245pub const SYS_move_pages = 239;245 migrate_pages = 238,
246pub const SYS_rt_tgsigqueueinfo = 240;246 move_pages = 239,
247pub const SYS_perf_event_open = 241;247 rt_tgsigqueueinfo = 240,
248pub const SYS_accept4 = 242;248 perf_event_open = 241,
249pub const SYS_recvmmsg = 243;249 accept4 = 242,
250 recvmmsg = 243,
250251
251pub const SYS_arch_specific_syscall = 244;252 pub const arch_specific_syscall = 244;
252pub const SYS_riscv_flush_icache = SYS_arch_specific_syscall + 15;253 riscv_flush_icache = arch_specific_syscall + 15,
253254
254pub const SYS_wait4 = 260;255 wait4 = 260,
255pub const SYS_prlimit64 = 261;256 prlimit64 = 261,
256pub const SYS_fanotify_init = 262;257 fanotify_init = 262,
257pub const SYS_fanotify_mark = 263;258 fanotify_mark = 263,
258pub const SYS_name_to_handle_at = 264;259 name_to_handle_at = 264,
259pub const SYS_open_by_handle_at = 265;260 open_by_handle_at = 265,
260pub const SYS_clock_adjtime = 266;261 clock_adjtime = 266,
261pub const SYS_syncfs = 267;262 syncfs = 267,
262pub const SYS_setns = 268;263 setns = 268,
263pub const SYS_sendmmsg = 269;264 sendmmsg = 269,
264pub const SYS_process_vm_readv = 270;265 process_vm_readv = 270,
265pub const SYS_process_vm_writev = 271;266 process_vm_writev = 271,
266pub const SYS_kcmp = 272;267 kcmp = 272,
267pub const SYS_finit_module = 273;268 finit_module = 273,
268pub const SYS_sched_setattr = 274;269 sched_setattr = 274,
269pub const SYS_sched_getattr = 275;270 sched_getattr = 275,
270pub const SYS_renameat2 = 276;271 renameat2 = 276,
271pub const SYS_seccomp = 277;272 seccomp = 277,
272pub const SYS_getrandom = 278;273 getrandom = 278,
273pub const SYS_memfd_create = 279;274 memfd_create = 279,
274pub const SYS_bpf = 280;275 bpf = 280,
275pub const SYS_execveat = 281;276 execveat = 281,
276pub const SYS_userfaultfd = 282;277 userfaultfd = 282,
277pub const SYS_membarrier = 283;278 membarrier = 283,
278pub const SYS_mlock2 = 284;279 mlock2 = 284,
279pub const SYS_copy_file_range = 285;280 copy_file_range = 285,
280pub const SYS_preadv2 = 286;281 preadv2 = 286,
281pub const SYS_pwritev2 = 287;282 pwritev2 = 287,
282pub const SYS_pkey_mprotect = 288;283 pkey_mprotect = 288,
283pub const SYS_pkey_alloc = 289;284 pkey_alloc = 289,
284pub const SYS_pkey_free = 290;285 pkey_free = 290,
285pub const SYS_statx = 291;286 statx = 291,
286pub const SYS_io_pgetevents = 292;287 io_pgetevents = 292,
287pub const SYS_rseq = 293;288 rseq = 293,
288pub const SYS_kexec_file_load = 294;289 kexec_file_load = 294,
289pub const SYS_pidfd_send_signal = 424;290 pidfd_send_signal = 424,
290pub const SYS_io_uring_setup = 425;291 io_uring_setup = 425,
291pub const SYS_io_uring_enter = 426;292 io_uring_enter = 426,
292pub const SYS_io_uring_register = 427;293 io_uring_register = 427,
293pub const SYS_open_tree = 428;294 open_tree = 428,
294pub const SYS_move_mount = 429;295 move_mount = 429,
295pub const SYS_fsopen = 430;296 fsopen = 430,
296pub const SYS_fsconfig = 431;297 fsconfig = 431,
297pub const SYS_fsmount = 432;298 fsmount = 432,
298pub const SYS_fspick = 433;299 fspick = 433,
299pub const SYS_pidfd_open = 434;300 pidfd_open = 434,
300pub const SYS_clone3 = 435;301 clone3 = 435,
302 openat2 = 437,
303 pidfd_getfd = 438,
304
305 _,
306};
301307
302pub const O_CREAT = 0o100;308pub const O_CREAT = 0o100;
303pub const O_EXCL = 0o200;309pub const O_EXCL = 0o200;
lib/std/os/bits/linux/x86_64.zig+354-348
...@@ -14,354 +14,360 @@ const iovec_const = linux.iovec_const;...@@ -14,354 +14,360 @@ const iovec_const = linux.iovec_const;
1414
15pub const mode_t = usize;15pub const mode_t = usize;
1616
17pub const SYS_read = 0;17pub const SYS = extern enum(usize) {
18pub const SYS_write = 1;18 read = 0,
19pub const SYS_open = 2;19 write = 1,
20pub const SYS_close = 3;20 open = 2,
21pub const SYS_stat = 4;21 close = 3,
22pub const SYS_fstat = 5;22 stat = 4,
23pub const SYS_lstat = 6;23 fstat = 5,
24pub const SYS_poll = 7;24 lstat = 6,
25pub const SYS_lseek = 8;25 poll = 7,
26pub const SYS_mmap = 9;26 lseek = 8,
27pub const SYS_mprotect = 10;27 mmap = 9,
28pub const SYS_munmap = 11;28 mprotect = 10,
29pub const SYS_brk = 12;29 munmap = 11,
30pub const SYS_rt_sigaction = 13;30 brk = 12,
31pub const SYS_rt_sigprocmask = 14;31 rt_sigaction = 13,
32pub const SYS_rt_sigreturn = 15;32 rt_sigprocmask = 14,
33pub const SYS_ioctl = 16;33 rt_sigreturn = 15,
34pub const SYS_pread = 17;34 ioctl = 16,
35pub const SYS_pwrite = 18;35 pread = 17,
36pub const SYS_readv = 19;36 pwrite = 18,
37pub const SYS_writev = 20;37 readv = 19,
38pub const SYS_access = 21;38 writev = 20,
39pub const SYS_pipe = 22;39 access = 21,
40pub const SYS_select = 23;40 pipe = 22,
41pub const SYS_sched_yield = 24;41 select = 23,
42pub const SYS_mremap = 25;42 sched_yield = 24,
43pub const SYS_msync = 26;43 mremap = 25,
44pub const SYS_mincore = 27;44 msync = 26,
45pub const SYS_madvise = 28;45 mincore = 27,
46pub const SYS_shmget = 29;46 madvise = 28,
47pub const SYS_shmat = 30;47 shmget = 29,
48pub const SYS_shmctl = 31;48 shmat = 30,
49pub const SYS_dup = 32;49 shmctl = 31,
50pub const SYS_dup2 = 33;50 dup = 32,
51pub const SYS_pause = 34;51 dup2 = 33,
52pub const SYS_nanosleep = 35;52 pause = 34,
53pub const SYS_getitimer = 36;53 nanosleep = 35,
54pub const SYS_alarm = 37;54 getitimer = 36,
55pub const SYS_setitimer = 38;55 alarm = 37,
56pub const SYS_getpid = 39;56 setitimer = 38,
57pub const SYS_sendfile = 40;57 getpid = 39,
58pub const SYS_socket = 41;58 sendfile = 40,
59pub const SYS_connect = 42;59 socket = 41,
60pub const SYS_accept = 43;60 connect = 42,
61pub const SYS_sendto = 44;61 accept = 43,
62pub const SYS_recvfrom = 45;62 sendto = 44,
63pub const SYS_sendmsg = 46;63 recvfrom = 45,
64pub const SYS_recvmsg = 47;64 sendmsg = 46,
65pub const SYS_shutdown = 48;65 recvmsg = 47,
66pub const SYS_bind = 49;66 shutdown = 48,
67pub const SYS_listen = 50;67 bind = 49,
68pub const SYS_getsockname = 51;68 listen = 50,
69pub const SYS_getpeername = 52;69 getsockname = 51,
70pub const SYS_socketpair = 53;70 getpeername = 52,
71pub const SYS_setsockopt = 54;71 socketpair = 53,
72pub const SYS_getsockopt = 55;72 setsockopt = 54,
73pub const SYS_clone = 56;73 getsockopt = 55,
74pub const SYS_fork = 57;74 clone = 56,
75pub const SYS_vfork = 58;75 fork = 57,
76pub const SYS_execve = 59;76 vfork = 58,
77pub const SYS_exit = 60;77 execve = 59,
78pub const SYS_wait4 = 61;78 exit = 60,
79pub const SYS_kill = 62;79 wait4 = 61,
80pub const SYS_uname = 63;80 kill = 62,
81pub const SYS_semget = 64;81 uname = 63,
82pub const SYS_semop = 65;82 semget = 64,
83pub const SYS_semctl = 66;83 semop = 65,
84pub const SYS_shmdt = 67;84 semctl = 66,
85pub const SYS_msgget = 68;85 shmdt = 67,
86pub const SYS_msgsnd = 69;86 msgget = 68,
87pub const SYS_msgrcv = 70;87 msgsnd = 69,
88pub const SYS_msgctl = 71;88 msgrcv = 70,
89pub const SYS_fcntl = 72;89 msgctl = 71,
90pub const SYS_flock = 73;90 fcntl = 72,
91pub const SYS_fsync = 74;91 flock = 73,
92pub const SYS_fdatasync = 75;92 fsync = 74,
93pub const SYS_truncate = 76;93 fdatasync = 75,
94pub const SYS_ftruncate = 77;94 truncate = 76,
95pub const SYS_getdents = 78;95 ftruncate = 77,
96pub const SYS_getcwd = 79;96 getdents = 78,
97pub const SYS_chdir = 80;97 getcwd = 79,
98pub const SYS_fchdir = 81;98 chdir = 80,
99pub const SYS_rename = 82;99 fchdir = 81,
100pub const SYS_mkdir = 83;100 rename = 82,
101pub const SYS_rmdir = 84;101 mkdir = 83,
102pub const SYS_creat = 85;102 rmdir = 84,
103pub const SYS_link = 86;103 creat = 85,
104pub const SYS_unlink = 87;104 link = 86,
105pub const SYS_symlink = 88;105 unlink = 87,
106pub const SYS_readlink = 89;106 symlink = 88,
107pub const SYS_chmod = 90;107 readlink = 89,
108pub const SYS_fchmod = 91;108 chmod = 90,
109pub const SYS_chown = 92;109 fchmod = 91,
110pub const SYS_fchown = 93;110 chown = 92,
111pub const SYS_lchown = 94;111 fchown = 93,
112pub const SYS_umask = 95;112 lchown = 94,
113pub const SYS_gettimeofday = 96;113 umask = 95,
114pub const SYS_getrlimit = 97;114 gettimeofday = 96,
115pub const SYS_getrusage = 98;115 getrlimit = 97,
116pub const SYS_sysinfo = 99;116 getrusage = 98,
117pub const SYS_times = 100;117 sysinfo = 99,
118pub const SYS_ptrace = 101;118 times = 100,
119pub const SYS_getuid = 102;119 ptrace = 101,
120pub const SYS_syslog = 103;120 getuid = 102,
121pub const SYS_getgid = 104;121 syslog = 103,
122pub const SYS_setuid = 105;122 getgid = 104,
123pub const SYS_setgid = 106;123 setuid = 105,
124pub const SYS_geteuid = 107;124 setgid = 106,
125pub const SYS_getegid = 108;125 geteuid = 107,
126pub const SYS_setpgid = 109;126 getegid = 108,
127pub const SYS_getppid = 110;127 setpgid = 109,
128pub const SYS_getpgrp = 111;128 getppid = 110,
129pub const SYS_setsid = 112;129 getpgrp = 111,
130pub const SYS_setreuid = 113;130 setsid = 112,
131pub const SYS_setregid = 114;131 setreuid = 113,
132pub const SYS_getgroups = 115;132 setregid = 114,
133pub const SYS_setgroups = 116;133 getgroups = 115,
134pub const SYS_setresuid = 117;134 setgroups = 116,
135pub const SYS_getresuid = 118;135 setresuid = 117,
136pub const SYS_setresgid = 119;136 getresuid = 118,
137pub const SYS_getresgid = 120;137 setresgid = 119,
138pub const SYS_getpgid = 121;138 getresgid = 120,
139pub const SYS_setfsuid = 122;139 getpgid = 121,
140pub const SYS_setfsgid = 123;140 setfsuid = 122,
141pub const SYS_getsid = 124;141 setfsgid = 123,
142pub const SYS_capget = 125;142 getsid = 124,
143pub const SYS_capset = 126;143 capget = 125,
144pub const SYS_rt_sigpending = 127;144 capset = 126,
145pub const SYS_rt_sigtimedwait = 128;145 rt_sigpending = 127,
146pub const SYS_rt_sigqueueinfo = 129;146 rt_sigtimedwait = 128,
147pub const SYS_rt_sigsuspend = 130;147 rt_sigqueueinfo = 129,
148pub const SYS_sigaltstack = 131;148 rt_sigsuspend = 130,
149pub const SYS_utime = 132;149 sigaltstack = 131,
150pub const SYS_mknod = 133;150 utime = 132,
151pub const SYS_uselib = 134;151 mknod = 133,
152pub const SYS_personality = 135;152 uselib = 134,
153pub const SYS_ustat = 136;153 personality = 135,
154pub const SYS_statfs = 137;154 ustat = 136,
155pub const SYS_fstatfs = 138;155 statfs = 137,
156pub const SYS_sysfs = 139;156 fstatfs = 138,
157pub const SYS_getpriority = 140;157 sysfs = 139,
158pub const SYS_setpriority = 141;158 getpriority = 140,
159pub const SYS_sched_setparam = 142;159 setpriority = 141,
160pub const SYS_sched_getparam = 143;160 sched_setparam = 142,
161pub const SYS_sched_setscheduler = 144;161 sched_getparam = 143,
162pub const SYS_sched_getscheduler = 145;162 sched_setscheduler = 144,
163pub const SYS_sched_get_priority_max = 146;163 sched_getscheduler = 145,
164pub const SYS_sched_get_priority_min = 147;164 sched_get_priority_max = 146,
165pub const SYS_sched_rr_get_interval = 148;165 sched_get_priority_min = 147,
166pub const SYS_mlock = 149;166 sched_rr_get_interval = 148,
167pub const SYS_munlock = 150;167 mlock = 149,
168pub const SYS_mlockall = 151;168 munlock = 150,
169pub const SYS_munlockall = 152;169 mlockall = 151,
170pub const SYS_vhangup = 153;170 munlockall = 152,
171pub const SYS_modify_ldt = 154;171 vhangup = 153,
172pub const SYS_pivot_root = 155;172 modify_ldt = 154,
173pub const SYS__sysctl = 156;173 pivot_root = 155,
174pub const SYS_prctl = 157;174 _sysctl = 156,
175pub const SYS_arch_prctl = 158;175 prctl = 157,
176pub const SYS_adjtimex = 159;176 arch_prctl = 158,
177pub const SYS_setrlimit = 160;177 adjtimex = 159,
178pub const SYS_chroot = 161;178 setrlimit = 160,
179pub const SYS_sync = 162;179 chroot = 161,
180pub const SYS_acct = 163;180 sync = 162,
181pub const SYS_settimeofday = 164;181 acct = 163,
182pub const SYS_mount = 165;182 settimeofday = 164,
183pub const SYS_umount2 = 166;183 mount = 165,
184pub const SYS_swapon = 167;184 umount2 = 166,
185pub const SYS_swapoff = 168;185 swapon = 167,
186pub const SYS_reboot = 169;186 swapoff = 168,
187pub const SYS_sethostname = 170;187 reboot = 169,
188pub const SYS_setdomainname = 171;188 sethostname = 170,
189pub const SYS_iopl = 172;189 setdomainname = 171,
190pub const SYS_ioperm = 173;190 iopl = 172,
191pub const SYS_create_module = 174;191 ioperm = 173,
192pub const SYS_init_module = 175;192 create_module = 174,
193pub const SYS_delete_module = 176;193 init_module = 175,
194pub const SYS_get_kernel_syms = 177;194 delete_module = 176,
195pub const SYS_query_module = 178;195 get_kernel_syms = 177,
196pub const SYS_quotactl = 179;196 query_module = 178,
197pub const SYS_nfsservctl = 180;197 quotactl = 179,
198pub const SYS_getpmsg = 181;198 nfsservctl = 180,
199pub const SYS_putpmsg = 182;199 getpmsg = 181,
200pub const SYS_afs_syscall = 183;200 putpmsg = 182,
201pub const SYS_tuxcall = 184;201 afs_syscall = 183,
202pub const SYS_security = 185;202 tuxcall = 184,
203pub const SYS_gettid = 186;203 security = 185,
204pub const SYS_readahead = 187;204 gettid = 186,
205pub const SYS_setxattr = 188;205 readahead = 187,
206pub const SYS_lsetxattr = 189;206 setxattr = 188,
207pub const SYS_fsetxattr = 190;207 lsetxattr = 189,
208pub const SYS_getxattr = 191;208 fsetxattr = 190,
209pub const SYS_lgetxattr = 192;209 getxattr = 191,
210pub const SYS_fgetxattr = 193;210 lgetxattr = 192,
211pub const SYS_listxattr = 194;211 fgetxattr = 193,
212pub const SYS_llistxattr = 195;212 listxattr = 194,
213pub const SYS_flistxattr = 196;213 llistxattr = 195,
214pub const SYS_removexattr = 197;214 flistxattr = 196,
215pub const SYS_lremovexattr = 198;215 removexattr = 197,
216pub const SYS_fremovexattr = 199;216 lremovexattr = 198,
217pub const SYS_tkill = 200;217 fremovexattr = 199,
218pub const SYS_time = 201;218 tkill = 200,
219pub const SYS_futex = 202;219 time = 201,
220pub const SYS_sched_setaffinity = 203;220 futex = 202,
221pub const SYS_sched_getaffinity = 204;221 sched_setaffinity = 203,
222pub const SYS_set_thread_area = 205;222 sched_getaffinity = 204,
223pub const SYS_io_setup = 206;223 set_thread_area = 205,
224pub const SYS_io_destroy = 207;224 io_setup = 206,
225pub const SYS_io_getevents = 208;225 io_destroy = 207,
226pub const SYS_io_submit = 209;226 io_getevents = 208,
227pub const SYS_io_cancel = 210;227 io_submit = 209,
228pub const SYS_get_thread_area = 211;228 io_cancel = 210,
229pub const SYS_lookup_dcookie = 212;229 get_thread_area = 211,
230pub const SYS_epoll_create = 213;230 lookup_dcookie = 212,
231pub const SYS_epoll_ctl_old = 214;231 epoll_create = 213,
232pub const SYS_epoll_wait_old = 215;232 epoll_ctl_old = 214,
233pub const SYS_remap_file_pages = 216;233 epoll_wait_old = 215,
234pub const SYS_getdents64 = 217;234 remap_file_pages = 216,
235pub const SYS_set_tid_address = 218;235 getdents64 = 217,
236pub const SYS_restart_syscall = 219;236 set_tid_address = 218,
237pub const SYS_semtimedop = 220;237 restart_syscall = 219,
238pub const SYS_fadvise64 = 221;238 semtimedop = 220,
239pub const SYS_timer_create = 222;239 fadvise64 = 221,
240pub const SYS_timer_settime = 223;240 timer_create = 222,
241pub const SYS_timer_gettime = 224;241 timer_settime = 223,
242pub const SYS_timer_getoverrun = 225;242 timer_gettime = 224,
243pub const SYS_timer_delete = 226;243 timer_getoverrun = 225,
244pub const SYS_clock_settime = 227;244 timer_delete = 226,
245pub const SYS_clock_gettime = 228;245 clock_settime = 227,
246pub const SYS_clock_getres = 229;246 clock_gettime = 228,
247pub const SYS_clock_nanosleep = 230;247 clock_getres = 229,
248pub const SYS_exit_group = 231;248 clock_nanosleep = 230,
249pub const SYS_epoll_wait = 232;249 exit_group = 231,
250pub const SYS_epoll_ctl = 233;250 epoll_wait = 232,
251pub const SYS_tgkill = 234;251 epoll_ctl = 233,
252pub const SYS_utimes = 235;252 tgkill = 234,
253pub const SYS_vserver = 236;253 utimes = 235,
254pub const SYS_mbind = 237;254 vserver = 236,
255pub const SYS_set_mempolicy = 238;255 mbind = 237,
256pub const SYS_get_mempolicy = 239;256 set_mempolicy = 238,
257pub const SYS_mq_open = 240;257 get_mempolicy = 239,
258pub const SYS_mq_unlink = 241;258 mq_open = 240,
259pub const SYS_mq_timedsend = 242;259 mq_unlink = 241,
260pub const SYS_mq_timedreceive = 243;260 mq_timedsend = 242,
261pub const SYS_mq_notify = 244;261 mq_timedreceive = 243,
262pub const SYS_mq_getsetattr = 245;262 mq_notify = 244,
263pub const SYS_kexec_load = 246;263 mq_getsetattr = 245,
264pub const SYS_waitid = 247;264 kexec_load = 246,
265pub const SYS_add_key = 248;265 waitid = 247,
266pub const SYS_request_key = 249;266 add_key = 248,
267pub const SYS_keyctl = 250;267 request_key = 249,
268pub const SYS_ioprio_set = 251;268 keyctl = 250,
269pub const SYS_ioprio_get = 252;269 ioprio_set = 251,
270pub const SYS_inotify_init = 253;270 ioprio_get = 252,
271pub const SYS_inotify_add_watch = 254;271 inotify_init = 253,
272pub const SYS_inotify_rm_watch = 255;272 inotify_add_watch = 254,
273pub const SYS_migrate_pages = 256;273 inotify_rm_watch = 255,
274pub const SYS_openat = 257;274 migrate_pages = 256,
275pub const SYS_mkdirat = 258;275 openat = 257,
276pub const SYS_mknodat = 259;276 mkdirat = 258,
277pub const SYS_fchownat = 260;277 mknodat = 259,
278pub const SYS_futimesat = 261;278 fchownat = 260,
279pub const SYS_newfstatat = 262;279 futimesat = 261,
280pub const SYS_fstatat = 262;280 newfstatat = 262,
281pub const SYS_unlinkat = 263;281 fstatat = 262,
282pub const SYS_renameat = 264;282 unlinkat = 263,
283pub const SYS_linkat = 265;283 renameat = 264,
284pub const SYS_symlinkat = 266;284 linkat = 265,
285pub const SYS_readlinkat = 267;285 symlinkat = 266,
286pub const SYS_fchmodat = 268;286 readlinkat = 267,
287pub const SYS_faccessat = 269;287 fchmodat = 268,
288pub const SYS_pselect6 = 270;288 faccessat = 269,
289pub const SYS_ppoll = 271;289 pselect6 = 270,
290pub const SYS_unshare = 272;290 ppoll = 271,
291pub const SYS_set_robust_list = 273;291 unshare = 272,
292pub const SYS_get_robust_list = 274;292 set_robust_list = 273,
293pub const SYS_splice = 275;293 get_robust_list = 274,
294pub const SYS_tee = 276;294 splice = 275,
295pub const SYS_sync_file_range = 277;295 tee = 276,
296pub const SYS_vmsplice = 278;296 sync_file_range = 277,
297pub const SYS_move_pages = 279;297 vmsplice = 278,
298pub const SYS_utimensat = 280;298 move_pages = 279,
299pub const SYS_epoll_pwait = 281;299 utimensat = 280,
300pub const SYS_signalfd = 282;300 epoll_pwait = 281,
301pub const SYS_timerfd_create = 283;301 signalfd = 282,
302pub const SYS_eventfd = 284;302 timerfd_create = 283,
303pub const SYS_fallocate = 285;303 eventfd = 284,
304pub const SYS_timerfd_settime = 286;304 fallocate = 285,
305pub const SYS_timerfd_gettime = 287;305 timerfd_settime = 286,
306pub const SYS_accept4 = 288;306 timerfd_gettime = 287,
307pub const SYS_signalfd4 = 289;307 accept4 = 288,
308pub const SYS_eventfd2 = 290;308 signalfd4 = 289,
309pub const SYS_epoll_create1 = 291;309 eventfd2 = 290,
310pub const SYS_dup3 = 292;310 epoll_create1 = 291,
311pub const SYS_pipe2 = 293;311 dup3 = 292,
312pub const SYS_inotify_init1 = 294;312 pipe2 = 293,
313pub const SYS_preadv = 295;313 inotify_init1 = 294,
314pub const SYS_pwritev = 296;314 preadv = 295,
315pub const SYS_rt_tgsigqueueinfo = 297;315 pwritev = 296,
316pub const SYS_perf_event_open = 298;316 rt_tgsigqueueinfo = 297,
317pub const SYS_recvmmsg = 299;317 perf_event_open = 298,
318pub const SYS_fanotify_init = 300;318 recvmmsg = 299,
319pub const SYS_fanotify_mark = 301;319 fanotify_init = 300,
320pub const SYS_prlimit64 = 302;320 fanotify_mark = 301,
321pub const SYS_name_to_handle_at = 303;321 prlimit64 = 302,
322pub const SYS_open_by_handle_at = 304;322 name_to_handle_at = 303,
323pub const SYS_clock_adjtime = 305;323 open_by_handle_at = 304,
324pub const SYS_syncfs = 306;324 clock_adjtime = 305,
325pub const SYS_sendmmsg = 307;325 syncfs = 306,
326pub const SYS_setns = 308;326 sendmmsg = 307,
327pub const SYS_getcpu = 309;327 setns = 308,
328pub const SYS_process_vm_readv = 310;328 getcpu = 309,
329pub const SYS_process_vm_writev = 311;329 process_vm_readv = 310,
330pub const SYS_kcmp = 312;330 process_vm_writev = 311,
331pub const SYS_finit_module = 313;331 kcmp = 312,
332pub const SYS_sched_setattr = 314;332 finit_module = 313,
333pub const SYS_sched_getattr = 315;333 sched_setattr = 314,
334pub const SYS_renameat2 = 316;334 sched_getattr = 315,
335pub const SYS_seccomp = 317;335 renameat2 = 316,
336pub const SYS_getrandom = 318;336 seccomp = 317,
337pub const SYS_memfd_create = 319;337 getrandom = 318,
338pub const SYS_kexec_file_load = 320;338 memfd_create = 319,
339pub const SYS_bpf = 321;339 kexec_file_load = 320,
340pub const SYS_execveat = 322;340 bpf = 321,
341pub const SYS_userfaultfd = 323;341 execveat = 322,
342pub const SYS_membarrier = 324;342 userfaultfd = 323,
343pub const SYS_mlock2 = 325;343 membarrier = 324,
344pub const SYS_copy_file_range = 326;344 mlock2 = 325,
345pub const SYS_preadv2 = 327;345 copy_file_range = 326,
346pub const SYS_pwritev2 = 328;346 preadv2 = 327,
347pub const SYS_pkey_mprotect = 329;347 pwritev2 = 328,
348pub const SYS_pkey_alloc = 330;348 pkey_mprotect = 329,
349pub const SYS_pkey_free = 331;349 pkey_alloc = 330,
350pub const SYS_statx = 332;350 pkey_free = 331,
351pub const SYS_io_pgetevents = 333;351 statx = 332,
352pub const SYS_rseq = 334;352 io_pgetevents = 333,
353pub const SYS_pidfd_send_signal = 424;353 rseq = 334,
354pub const SYS_io_uring_setup = 425;354 pidfd_send_signal = 424,
355pub const SYS_io_uring_enter = 426;355 io_uring_setup = 425,
356pub const SYS_io_uring_register = 427;356 io_uring_enter = 426,
357pub const SYS_open_tree = 428;357 io_uring_register = 427,
358pub const SYS_move_mount = 429;358 open_tree = 428,
359pub const SYS_fsopen = 430;359 move_mount = 429,
360pub const SYS_fsconfig = 431;360 fsopen = 430,
361pub const SYS_fsmount = 432;361 fsconfig = 431,
362pub const SYS_fspick = 433;362 fsmount = 432,
363pub const SYS_pidfd_open = 434;363 fspick = 433,
364pub const SYS_clone3 = 435;364 pidfd_open = 434,
365 clone3 = 435,
366 openat2 = 437,
367 pidfd_getfd = 438,
368
369 _,
370};
365371
366pub const O_CREAT = 0o100;372pub const O_CREAT = 0o100;
367pub const O_EXCL = 0o200;373pub const O_EXCL = 0o200;
lib/std/os/bits/netbsd.zig+114-26
...@@ -1,12 +1,22 @@...@@ -1,12 +1,22 @@
1const std = @import("../../std.zig");1const std = @import("../../std.zig");
2const builtin = std.builtin;
2const maxInt = std.math.maxInt;3const maxInt = std.math.maxInt;
34
5pub const blkcnt_t = i64;
6pub const blksize_t = i32;
7pub const clock_t = u32;
8pub const dev_t = u64;
4pub const fd_t = i32;9pub const fd_t = i32;
5pub const pid_t = i32;10pub const gid_t = u32;
6pub const mode_t = u32;
7pub const ino_t = u64;11pub const ino_t = u64;
12pub const mode_t = u32;
13pub const nlink_t = u32;
8pub const off_t = i64;14pub const off_t = i64;
15pub const pid_t = i32;
9pub const socklen_t = u32;16pub const socklen_t = u32;
17pub const time_t = i64;
18pub const uid_t = u32;
19pub const lwpid_t = i32;
1020
11/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.21/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
12pub const Kevent = extern struct {22pub const Kevent = extern struct {
...@@ -145,23 +155,20 @@ pub const msghdr_const = extern struct {...@@ -145,23 +155,20 @@ pub const msghdr_const = extern struct {
145/// in C, macros are used to hide the differences. Here we use155/// in C, macros are used to hide the differences. Here we use
146/// methods to accomplish this.156/// methods to accomplish this.
147pub const Stat = extern struct {157pub const Stat = extern struct {
148 dev: u64,158 dev: dev_t,
149 mode: u32,159 mode: mode_t,
150 ino: ino_t,160 ino: ino_t,
151 nlink: usize,161 nlink: nlink_t,
152162 uid: uid_t,
153 uid: u32,163 gid: gid_t,
154 gid: u32,164 rdev: dev_t,
155 rdev: u64,
156
157 atim: timespec,165 atim: timespec,
158 mtim: timespec,166 mtim: timespec,
159 ctim: timespec,167 ctim: timespec,
160 birthtim: timespec,168 birthtim: timespec,
161
162 size: off_t,169 size: off_t,
163 blocks: i64,170 blocks: blkcnt_t,
164 blksize: isize,171 blksize: blksize_t,
165 flags: u32,172 flags: u32,
166 gen: u32,173 gen: u32,
167 __spare: [2]u32,174 __spare: [2]u32,
...@@ -184,12 +191,14 @@ pub const timespec = extern struct {...@@ -184,12 +191,14 @@ pub const timespec = extern struct {
184 tv_nsec: isize,191 tv_nsec: isize,
185};192};
186193
194pub const MAXNAMLEN = 511;
195
187pub const dirent = extern struct {196pub const dirent = extern struct {
188 d_fileno: u64,197 d_fileno: ino_t,
189 d_reclen: u16,198 d_reclen: u16,
190 d_namlen: u16,199 d_namlen: u16,
191 d_type: u8,200 d_type: u8,
192 d_name: [512]u8,201 d_name: [MAXNAMLEN:0]u8,
193202
194 pub fn reclen(self: dirent) u16 {203 pub fn reclen(self: dirent) u16 {
195 return self.d_reclen;204 return self.d_reclen;
...@@ -697,23 +706,74 @@ pub const winsize = extern struct {...@@ -697,23 +706,74 @@ pub const winsize = extern struct {
697706
698const NSIG = 32;707const NSIG = 32;
699708
700pub const SIG_ERR = @intToPtr(extern fn (i32) void, maxInt(usize));709pub const SIG_ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
701pub const SIG_DFL = @intToPtr(extern fn (i32) void, 0);710pub const SIG_DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
702pub const SIG_IGN = @intToPtr(extern fn (i32) void, 1);711pub const SIG_IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
703712
704/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.713/// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall.
705pub const Sigaction = extern struct {714pub const Sigaction = extern struct {
715 pub const sigaction_fn = fn (i32, *siginfo_t, ?*c_void) callconv(.C) void;
706 /// signal handler716 /// signal handler
707 __sigaction_u: extern union {717 sigaction: ?sigaction_fn,
708 __sa_handler: extern fn (i32) void,718 /// signal mask to apply
709 __sa_sigaction: extern fn (i32, *__siginfo, usize) void,719 mask: sigset_t,
710 },720 /// signal options
721 flags: u32,
722};
711723
712 /// see signal options724pub const sigval_t = extern union {
713 sa_flags: u32,725 int: i32,
726 ptr: ?*c_void,
727};
714728
715 /// signal mask to apply729pub const siginfo_t = extern union {
716 sa_mask: sigset_t,730 pad: [128]u8,
731 info: _ksiginfo,
732};
733
734pub const _ksiginfo = extern struct {
735 signo: i32,
736 code: i32,
737 errno: i32,
738 // 64bit architectures insert 4bytes of padding here, this is done by
739 // correctly aligning the reason field
740 reason: extern union {
741 rt: extern struct {
742 pid: pid_t,
743 uid: uid_t,
744 value: sigval_t,
745 },
746 child: extern struct {
747 pid: pid_t,
748 uid: uid_t,
749 status: i32,
750 utime: clock_t,
751 stime: clock_t,
752 },
753 fault: extern struct {
754 addr: ?*c_void,
755 trap: i32,
756 trap2: i32,
757 trap3: i32,
758 },
759 poll: extern struct {
760 band: i32,
761 fd: i32,
762 },
763 syscall: extern struct {
764 sysnum: i32,
765 retval: [2]i32,
766 @"error": i32,
767 args: [8]u64,
768 },
769 ptrace_state: extern struct {
770 pe_report_event: i32,
771 option: extern union {
772 pe_other_pid: pid_t,
773 pe_lwp: lwpid_t,
774 },
775 },
776 } align(@sizeOf(usize)),
717};777};
718778
719pub const _SIG_WORDS = 4;779pub const _SIG_WORDS = 4;
...@@ -736,6 +796,34 @@ pub const sigset_t = extern struct {...@@ -736,6 +796,34 @@ pub const sigset_t = extern struct {
736 __bits: [_SIG_WORDS]u32,796 __bits: [_SIG_WORDS]u32,
737};797};
738798
799pub const empty_sigset = sigset_t{ .__bits = [_]u32{0} ** _SIG_WORDS };
800
801// XXX x86_64 specific
802pub const mcontext_t = extern struct {
803 gregs: [26]u64,
804 mc_tlsbase: u64,
805 fpregs: [512]u8 align(8),
806};
807
808pub const REG_RBP = 12;
809pub const REG_RIP = 21;
810pub const REG_RSP = 24;
811
812pub const ucontext_t = extern struct {
813 flags: u32,
814 link: ?*ucontext_t,
815 sigmask: sigset_t,
816 stack: stack_t,
817 mcontext: mcontext_t,
818 __pad: [switch (builtin.arch) {
819 .i386 => 4,
820 .mips, .mipsel, .mips64, .mips64el => 14,
821 .arm, .armeb, .thumb, .thumbeb => 1,
822 .sparc, .sparcel, .sparcv9 => if (@sizeOf(usize) == 4) 43 else 8,
823 else => 0,
824 }]u32,
825};
826
739pub const EPERM = 1; // Operation not permitted827pub const EPERM = 1; // Operation not permitted
740pub const ENOENT = 2; // No such file or directory828pub const ENOENT = 2; // No such file or directory
741pub const ESRCH = 3; // No such process829pub const ESRCH = 3; // No such process
lib/std/os/linux.zig+228-228
...@@ -53,46 +53,46 @@ pub fn getErrno(r: usize) u12 {...@@ -53,46 +53,46 @@ pub fn getErrno(r: usize) u12 {
53}53}
5454
55pub fn dup2(old: i32, new: i32) usize {55pub fn dup2(old: i32, new: i32) usize {
56 if (@hasDecl(@This(), "SYS_dup2")) {56 if (@hasField(SYS, "dup2")) {
57 return syscall2(SYS_dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)));57 return syscall2(.dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)));
58 } else {58 } else {
59 if (old == new) {59 if (old == new) {
60 if (std.debug.runtime_safety) {60 if (std.debug.runtime_safety) {
61 const rc = syscall2(SYS_fcntl, @bitCast(usize, @as(isize, old)), F_GETFD);61 const rc = syscall2(.fcntl, @bitCast(usize, @as(isize, old)), F_GETFD);
62 if (@bitCast(isize, rc) < 0) return rc;62 if (@bitCast(isize, rc) < 0) return rc;
63 }63 }
64 return @intCast(usize, old);64 return @intCast(usize, old);
65 } else {65 } else {
66 return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0);66 return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0);
67 }67 }
68 }68 }
69}69}
7070
71pub fn dup3(old: i32, new: i32, flags: u32) usize {71pub fn dup3(old: i32, new: i32, flags: u32) usize {
72 return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags);72 return syscall3(.dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags);
73}73}
7474
75pub fn chdir(path: [*:0]const u8) usize {75pub fn chdir(path: [*:0]const u8) usize {
76 return syscall1(SYS_chdir, @ptrToInt(path));76 return syscall1(.chdir, @ptrToInt(path));
77}77}
7878
79pub fn fchdir(fd: fd_t) usize {79pub fn fchdir(fd: fd_t) usize {
80 return syscall1(SYS_fchdir, @bitCast(usize, @as(isize, fd)));80 return syscall1(.fchdir, @bitCast(usize, @as(isize, fd)));
81}81}
8282
83pub fn chroot(path: [*:0]const u8) usize {83pub fn chroot(path: [*:0]const u8) usize {
84 return syscall1(SYS_chroot, @ptrToInt(path));84 return syscall1(.chroot, @ptrToInt(path));
85}85}
8686
87pub fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) usize {87pub fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) usize {
88 return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));88 return syscall3(.execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));
89}89}
9090
91pub fn fork() usize {91pub fn fork() usize {
92 if (@hasDecl(@This(), "SYS_fork")) {92 if (@hasField(SYS, "fork")) {
93 return syscall0(SYS_fork);93 return syscall0(.fork);
94 } else {94 } else {
95 return syscall2(SYS_clone, SIGCHLD, 0);95 return syscall2(.clone, SIGCHLD, 0);
96 }96 }
97}97}
9898
...@@ -102,7 +102,7 @@ pub fn fork() usize {...@@ -102,7 +102,7 @@ pub fn fork() usize {
102/// the compiler is not aware of how vfork affects control flow and you may102/// the compiler is not aware of how vfork affects control flow and you may
103/// see different results in optimized builds.103/// see different results in optimized builds.
104pub inline fn vfork() usize {104pub inline fn vfork() usize {
105 return @call(.{ .modifier = .always_inline }, syscall0, .{SYS_vfork});105 return @call(.{ .modifier = .always_inline }, syscall0, .{.vfork});
106}106}
107107
108pub fn futimens(fd: i32, times: *const [2]timespec) usize {108pub fn futimens(fd: i32, times: *const [2]timespec) usize {
...@@ -110,24 +110,24 @@ pub fn futimens(fd: i32, times: *const [2]timespec) usize {...@@ -110,24 +110,24 @@ pub fn futimens(fd: i32, times: *const [2]timespec) usize {
110}110}
111111
112pub fn utimensat(dirfd: i32, path: ?[*:0]const u8, times: *const [2]timespec, flags: u32) usize {112pub fn utimensat(dirfd: i32, path: ?[*:0]const u8, times: *const [2]timespec, flags: u32) usize {
113 return syscall4(SYS_utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags);113 return syscall4(.utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags);
114}114}
115115
116pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*timespec) usize {116pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*timespec) usize {
117 return syscall4(SYS_futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout));117 return syscall4(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout));
118}118}
119119
120pub fn futex_wake(uaddr: *const i32, futex_op: u32, val: i32) usize {120pub fn futex_wake(uaddr: *const i32, futex_op: u32, val: i32) usize {
121 return syscall3(SYS_futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val));121 return syscall3(.futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val));
122}122}
123123
124pub fn getcwd(buf: [*]u8, size: usize) usize {124pub fn getcwd(buf: [*]u8, size: usize) usize {
125 return syscall2(SYS_getcwd, @ptrToInt(buf), size);125 return syscall2(.getcwd, @ptrToInt(buf), size);
126}126}
127127
128pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {128pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
129 return syscall3(129 return syscall3(
130 SYS_getdents,130 .getdents,
131 @bitCast(usize, @as(isize, fd)),131 @bitCast(usize, @as(isize, fd)),
132 @ptrToInt(dirp),132 @ptrToInt(dirp),
133 std.math.min(len, maxInt(c_int)),133 std.math.min(len, maxInt(c_int)),
...@@ -136,7 +136,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {...@@ -136,7 +136,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
136136
137pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {137pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {
138 return syscall3(138 return syscall3(
139 SYS_getdents64,139 .getdents64,
140 @bitCast(usize, @as(isize, fd)),140 @bitCast(usize, @as(isize, fd)),
141 @ptrToInt(dirp),141 @ptrToInt(dirp),
142 std.math.min(len, maxInt(c_int)),142 std.math.min(len, maxInt(c_int)),
...@@ -144,61 +144,61 @@ pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {...@@ -144,61 +144,61 @@ pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {
144}144}
145145
146pub fn inotify_init1(flags: u32) usize {146pub fn inotify_init1(flags: u32) usize {
147 return syscall1(SYS_inotify_init1, flags);147 return syscall1(.inotify_init1, flags);
148}148}
149149
150pub fn inotify_add_watch(fd: i32, pathname: [*:0]const u8, mask: u32) usize {150pub fn inotify_add_watch(fd: i32, pathname: [*:0]const u8, mask: u32) usize {
151 return syscall3(SYS_inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask);151 return syscall3(.inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask);
152}152}
153153
154pub fn inotify_rm_watch(fd: i32, wd: i32) usize {154pub fn inotify_rm_watch(fd: i32, wd: i32) usize {
155 return syscall2(SYS_inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd)));155 return syscall2(.inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd)));
156}156}
157157
158pub fn readlink(noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {158pub fn readlink(noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
159 if (@hasDecl(@This(), "SYS_readlink")) {159 if (@hasField(SYS, "readlink")) {
160 return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);160 return syscall3(.readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
161 } else {161 } else {
162 return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);162 return syscall4(.readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
163 }163 }
164}164}
165165
166pub fn readlinkat(dirfd: i32, noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {166pub fn readlinkat(dirfd: i32, noalias path: [*:0]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
167 return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);167 return syscall4(.readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
168}168}
169169
170pub fn mkdir(path: [*:0]const u8, mode: u32) usize {170pub fn mkdir(path: [*:0]const u8, mode: u32) usize {
171 if (@hasDecl(@This(), "SYS_mkdir")) {171 if (@hasField(SYS, "mkdir")) {
172 return syscall2(SYS_mkdir, @ptrToInt(path), mode);172 return syscall2(.mkdir, @ptrToInt(path), mode);
173 } else {173 } else {
174 return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode);174 return syscall3(.mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode);
175 }175 }
176}176}
177177
178pub fn mkdirat(dirfd: i32, path: [*:0]const u8, mode: u32) usize {178pub fn mkdirat(dirfd: i32, path: [*:0]const u8, mode: u32) usize {
179 return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode);179 return syscall3(.mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode);
180}180}
181181
182pub fn mount(special: [*:0]const u8, dir: [*:0]const u8, fstype: [*:0]const u8, flags: u32, data: usize) usize {182pub fn mount(special: [*:0]const u8, dir: [*:0]const u8, fstype: [*:0]const u8, flags: u32, data: usize) usize {
183 return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data);183 return syscall5(.mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data);
184}184}
185185
186pub fn umount(special: [*:0]const u8) usize {186pub fn umount(special: [*:0]const u8) usize {
187 return syscall2(SYS_umount2, @ptrToInt(special), 0);187 return syscall2(.umount2, @ptrToInt(special), 0);
188}188}
189189
190pub fn umount2(special: [*:0]const u8, flags: u32) usize {190pub fn umount2(special: [*:0]const u8, flags: u32) usize {
191 return syscall2(SYS_umount2, @ptrToInt(special), flags);191 return syscall2(.umount2, @ptrToInt(special), flags);
192}192}
193193
194pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: u64) usize {194pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: u64) usize {
195 if (@hasDecl(@This(), "SYS_mmap2")) {195 if (@hasField(SYS, "mmap2")) {
196 // Make sure the offset is also specified in multiples of page size196 // Make sure the offset is also specified in multiples of page size
197 if ((offset & (MMAP2_UNIT - 1)) != 0)197 if ((offset & (MMAP2_UNIT - 1)) != 0)
198 return @bitCast(usize, @as(isize, -EINVAL));198 return @bitCast(usize, @as(isize, -EINVAL));
199199
200 return syscall6(200 return syscall6(
201 SYS_mmap2,201 .mmap2,
202 @ptrToInt(address),202 @ptrToInt(address),
203 length,203 length,
204 prot,204 prot,
...@@ -208,7 +208,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of...@@ -208,7 +208,7 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
208 );208 );
209 } else {209 } else {
210 return syscall6(210 return syscall6(
211 SYS_mmap,211 .mmap,
212 @ptrToInt(address),212 @ptrToInt(address),
213 length,213 length,
214 prot,214 prot,
...@@ -220,19 +220,19 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of...@@ -220,19 +220,19 @@ pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, of
220}220}
221221
222pub fn mprotect(address: [*]const u8, length: usize, protection: usize) usize {222pub fn mprotect(address: [*]const u8, length: usize, protection: usize) usize {
223 return syscall3(SYS_mprotect, @ptrToInt(address), length, protection);223 return syscall3(.mprotect, @ptrToInt(address), length, protection);
224}224}
225225
226pub fn munmap(address: [*]const u8, length: usize) usize {226pub fn munmap(address: [*]const u8, length: usize) usize {
227 return syscall2(SYS_munmap, @ptrToInt(address), length);227 return syscall2(.munmap, @ptrToInt(address), length);
228}228}
229229
230pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {230pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {
231 if (@hasDecl(@This(), "SYS_poll")) {231 if (@hasField(SYS, "poll")) {
232 return syscall3(SYS_poll, @ptrToInt(fds), n, @bitCast(u32, timeout));232 return syscall3(.poll, @ptrToInt(fds), n, @bitCast(u32, timeout));
233 } else {233 } else {
234 return syscall6(234 return syscall6(
235 SYS_ppoll,235 .ppoll,
236 @ptrToInt(fds),236 @ptrToInt(fds),
237 n,237 n,
238 @ptrToInt(if (timeout >= 0)238 @ptrToInt(if (timeout >= 0)
...@@ -250,12 +250,12 @@ pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {...@@ -250,12 +250,12 @@ pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {
250}250}
251251
252pub fn read(fd: i32, buf: [*]u8, count: usize) usize {252pub fn read(fd: i32, buf: [*]u8, count: usize) usize {
253 return syscall3(SYS_read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);253 return syscall3(.read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
254}254}
255255
256pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {256pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {
257 return syscall5(257 return syscall5(
258 SYS_preadv,258 .preadv,
259 @bitCast(usize, @as(isize, fd)),259 @bitCast(usize, @as(isize, fd)),
260 @ptrToInt(iov),260 @ptrToInt(iov),
261 count,261 count,
...@@ -266,7 +266,7 @@ pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {...@@ -266,7 +266,7 @@ pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {
266266
267pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: kernel_rwf) usize {267pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: kernel_rwf) usize {
268 return syscall6(268 return syscall6(
269 SYS_preadv2,269 .preadv2,
270 @bitCast(usize, @as(isize, fd)),270 @bitCast(usize, @as(isize, fd)),
271 @ptrToInt(iov),271 @ptrToInt(iov),
272 count,272 count,
...@@ -277,16 +277,16 @@ pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: k...@@ -277,16 +277,16 @@ pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: k
277}277}
278278
279pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize {279pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize {
280 return syscall3(SYS_readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);280 return syscall3(.readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
281}281}
282282
283pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize {283pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize {
284 return syscall3(SYS_writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);284 return syscall3(.writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
285}285}
286286
287pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) usize {287pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) usize {
288 return syscall5(288 return syscall5(
289 SYS_pwritev,289 .pwritev,
290 @bitCast(usize, @as(isize, fd)),290 @bitCast(usize, @as(isize, fd)),
291 @ptrToInt(iov),291 @ptrToInt(iov),
292 count,292 count,
...@@ -297,7 +297,7 @@ pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) us...@@ -297,7 +297,7 @@ pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) us
297297
298pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, flags: kernel_rwf) usize {298pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, flags: kernel_rwf) usize {
299 return syscall6(299 return syscall6(
300 SYS_pwritev2,300 .pwritev2,
301 @bitCast(usize, @as(isize, fd)),301 @bitCast(usize, @as(isize, fd)),
302 @ptrToInt(iov),302 @ptrToInt(iov),
303 count,303 count,
...@@ -308,30 +308,30 @@ pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, f...@@ -308,30 +308,30 @@ pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, f
308}308}
309309
310pub fn rmdir(path: [*:0]const u8) usize {310pub fn rmdir(path: [*:0]const u8) usize {
311 if (@hasDecl(@This(), "SYS_rmdir")) {311 if (@hasField(SYS, "rmdir")) {
312 return syscall1(SYS_rmdir, @ptrToInt(path));312 return syscall1(.rmdir, @ptrToInt(path));
313 } else {313 } else {
314 return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR);314 return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR);
315 }315 }
316}316}
317317
318pub fn symlink(existing: [*:0]const u8, new: [*:0]const u8) usize {318pub fn symlink(existing: [*:0]const u8, new: [*:0]const u8) usize {
319 if (@hasDecl(@This(), "SYS_symlink")) {319 if (@hasField(SYS, "symlink")) {
320 return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new));320 return syscall2(.symlink, @ptrToInt(existing), @ptrToInt(new));
321 } else {321 } else {
322 return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));322 return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));
323 }323 }
324}324}
325325
326pub fn symlinkat(existing: [*:0]const u8, newfd: i32, newpath: [*:0]const u8) usize {326pub fn symlinkat(existing: [*:0]const u8, newfd: i32, newpath: [*:0]const u8) usize {
327 return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath));327 return syscall3(.symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath));
328}328}
329329
330pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {330pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {
331 if (@hasDecl(@This(), "SYS_pread64")) {331 if (@hasField(SYS, "pread64")) {
332 if (require_aligned_register_pair) {332 if (require_aligned_register_pair) {
333 return syscall6(333 return syscall6(
334 SYS_pread64,334 .pread64,
335 @bitCast(usize, @as(isize, fd)),335 @bitCast(usize, @as(isize, fd)),
336 @ptrToInt(buf),336 @ptrToInt(buf),
337 count,337 count,
...@@ -341,7 +341,7 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {...@@ -341,7 +341,7 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {
341 );341 );
342 } else {342 } else {
343 return syscall5(343 return syscall5(
344 SYS_pread64,344 .pread64,
345 @bitCast(usize, @as(isize, fd)),345 @bitCast(usize, @as(isize, fd)),
346 @ptrToInt(buf),346 @ptrToInt(buf),
347 count,347 count,
...@@ -351,7 +351,7 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {...@@ -351,7 +351,7 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {
351 }351 }
352 } else {352 } else {
353 return syscall4(353 return syscall4(
354 SYS_pread,354 .pread,
355 @bitCast(usize, @as(isize, fd)),355 @bitCast(usize, @as(isize, fd)),
356 @ptrToInt(buf),356 @ptrToInt(buf),
357 count,357 count,
...@@ -361,40 +361,40 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {...@@ -361,40 +361,40 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {
361}361}
362362
363pub fn access(path: [*:0]const u8, mode: u32) usize {363pub fn access(path: [*:0]const u8, mode: u32) usize {
364 if (@hasDecl(@This(), "SYS_access")) {364 if (@hasField(SYS, "access")) {
365 return syscall2(SYS_access, @ptrToInt(path), mode);365 return syscall2(.access, @ptrToInt(path), mode);
366 } else {366 } else {
367 return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0);367 return syscall4(.faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0);
368 }368 }
369}369}
370370
371pub fn faccessat(dirfd: i32, path: [*:0]const u8, mode: u32, flags: u32) usize {371pub fn faccessat(dirfd: i32, path: [*:0]const u8, mode: u32, flags: u32) usize {
372 return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags);372 return syscall4(.faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags);
373}373}
374374
375pub fn pipe(fd: *[2]i32) usize {375pub fn pipe(fd: *[2]i32) usize {
376 if (comptime builtin.arch.isMIPS()) {376 if (comptime builtin.arch.isMIPS()) {
377 return syscall_pipe(fd);377 return syscall_pipe(fd);
378 } else if (@hasDecl(@This(), "SYS_pipe")) {378 } else if (@hasField(SYS, "pipe")) {
379 return syscall1(SYS_pipe, @ptrToInt(fd));379 return syscall1(.pipe, @ptrToInt(fd));
380 } else {380 } else {
381 return syscall2(SYS_pipe2, @ptrToInt(fd), 0);381 return syscall2(.pipe2, @ptrToInt(fd), 0);
382 }382 }
383}383}
384384
385pub fn pipe2(fd: *[2]i32, flags: u32) usize {385pub fn pipe2(fd: *[2]i32, flags: u32) usize {
386 return syscall2(SYS_pipe2, @ptrToInt(fd), flags);386 return syscall2(.pipe2, @ptrToInt(fd), flags);
387}387}
388388
389pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {389pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
390 return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);390 return syscall3(.write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
391}391}
392392
393pub fn ftruncate(fd: i32, length: u64) usize {393pub fn ftruncate(fd: i32, length: u64) usize {
394 if (@hasDecl(@This(), "SYS_ftruncate64")) {394 if (@hasField(SYS, "ftruncate64")) {
395 if (require_aligned_register_pair) {395 if (require_aligned_register_pair) {
396 return syscall4(396 return syscall4(
397 SYS_ftruncate64,397 .ftruncate64,
398 @bitCast(usize, @as(isize, fd)),398 @bitCast(usize, @as(isize, fd)),
399 0,399 0,
400 @truncate(usize, length),400 @truncate(usize, length),
...@@ -402,7 +402,7 @@ pub fn ftruncate(fd: i32, length: u64) usize {...@@ -402,7 +402,7 @@ pub fn ftruncate(fd: i32, length: u64) usize {
402 );402 );
403 } else {403 } else {
404 return syscall3(404 return syscall3(
405 SYS_ftruncate64,405 .ftruncate64,
406 @bitCast(usize, @as(isize, fd)),406 @bitCast(usize, @as(isize, fd)),
407 @truncate(usize, length),407 @truncate(usize, length),
408 @truncate(usize, length >> 32),408 @truncate(usize, length >> 32),
...@@ -410,7 +410,7 @@ pub fn ftruncate(fd: i32, length: u64) usize {...@@ -410,7 +410,7 @@ pub fn ftruncate(fd: i32, length: u64) usize {
410 }410 }
411 } else {411 } else {
412 return syscall2(412 return syscall2(
413 SYS_ftruncate,413 .ftruncate,
414 @bitCast(usize, @as(isize, fd)),414 @bitCast(usize, @as(isize, fd)),
415 @truncate(usize, length),415 @truncate(usize, length),
416 );416 );
...@@ -418,10 +418,10 @@ pub fn ftruncate(fd: i32, length: u64) usize {...@@ -418,10 +418,10 @@ pub fn ftruncate(fd: i32, length: u64) usize {
418}418}
419419
420pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {420pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
421 if (@hasDecl(@This(), "SYS_pwrite64")) {421 if (@hasField(SYS, "pwrite64")) {
422 if (require_aligned_register_pair) {422 if (require_aligned_register_pair) {
423 return syscall6(423 return syscall6(
424 SYS_pwrite64,424 .pwrite64,
425 @bitCast(usize, @as(isize, fd)),425 @bitCast(usize, @as(isize, fd)),
426 @ptrToInt(buf),426 @ptrToInt(buf),
427 count,427 count,
...@@ -431,7 +431,7 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {...@@ -431,7 +431,7 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
431 );431 );
432 } else {432 } else {
433 return syscall5(433 return syscall5(
434 SYS_pwrite64,434 .pwrite64,
435 @bitCast(usize, @as(isize, fd)),435 @bitCast(usize, @as(isize, fd)),
436 @ptrToInt(buf),436 @ptrToInt(buf),
437 count,437 count,
...@@ -441,7 +441,7 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {...@@ -441,7 +441,7 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
441 }441 }
442 } else {442 } else {
443 return syscall4(443 return syscall4(
444 SYS_pwrite,444 .pwrite,
445 @bitCast(usize, @as(isize, fd)),445 @bitCast(usize, @as(isize, fd)),
446 @ptrToInt(buf),446 @ptrToInt(buf),
447 count,447 count,
...@@ -451,19 +451,19 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {...@@ -451,19 +451,19 @@ pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
451}451}
452452
453pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize {453pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize {
454 if (@hasDecl(@This(), "SYS_rename")) {454 if (@hasField(SYS, "rename")) {
455 return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new));455 return syscall2(.rename, @ptrToInt(old), @ptrToInt(new));
456 } else if (@hasDecl(@This(), "SYS_renameat")) {456 } else if (@hasField(SYS, "renameat")) {
457 return syscall4(SYS_renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));457 return syscall4(.renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));
458 } else {458 } else {
459 return syscall5(SYS_renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0);459 return syscall5(.renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0);
460 }460 }
461}461}
462462
463pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8) usize {463pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8) usize {
464 if (@hasDecl(@This(), "SYS_renameat")) {464 if (@hasField(SYS, "renameat")) {
465 return syscall4(465 return syscall4(
466 SYS_renameat,466 .renameat,
467 @bitCast(usize, @as(isize, oldfd)),467 @bitCast(usize, @as(isize, oldfd)),
468 @ptrToInt(oldpath),468 @ptrToInt(oldpath),
469 @bitCast(usize, @as(isize, newfd)),469 @bitCast(usize, @as(isize, newfd)),
...@@ -471,7 +471,7 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const...@@ -471,7 +471,7 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const
471 );471 );
472 } else {472 } else {
473 return syscall5(473 return syscall5(
474 SYS_renameat2,474 .renameat2,
475 @bitCast(usize, @as(isize, oldfd)),475 @bitCast(usize, @as(isize, oldfd)),
476 @ptrToInt(oldpath),476 @ptrToInt(oldpath),
477 @bitCast(usize, @as(isize, newfd)),477 @bitCast(usize, @as(isize, newfd)),
...@@ -483,7 +483,7 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const...@@ -483,7 +483,7 @@ pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const
483483
484pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]const u8, flags: u32) usize {484pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]const u8, flags: u32) usize {
485 return syscall5(485 return syscall5(
486 SYS_renameat2,486 .renameat2,
487 @bitCast(usize, @as(isize, oldfd)),487 @bitCast(usize, @as(isize, oldfd)),
488 @ptrToInt(oldpath),488 @ptrToInt(oldpath),
489 @bitCast(usize, @as(isize, newfd)),489 @bitCast(usize, @as(isize, newfd)),
...@@ -493,11 +493,11 @@ pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]c...@@ -493,11 +493,11 @@ pub fn renameat2(oldfd: i32, oldpath: [*:0]const u8, newfd: i32, newpath: [*:0]c
493}493}
494494
495pub fn open(path: [*:0]const u8, flags: u32, perm: usize) usize {495pub fn open(path: [*:0]const u8, flags: u32, perm: usize) usize {
496 if (@hasDecl(@This(), "SYS_open")) {496 if (@hasField(SYS, "open")) {
497 return syscall3(SYS_open, @ptrToInt(path), flags, perm);497 return syscall3(.open, @ptrToInt(path), flags, perm);
498 } else {498 } else {
499 return syscall4(499 return syscall4(
500 SYS_openat,500 .openat,
501 @bitCast(usize, @as(isize, AT_FDCWD)),501 @bitCast(usize, @as(isize, AT_FDCWD)),
502 @ptrToInt(path),502 @ptrToInt(path),
503 flags,503 flags,
...@@ -507,32 +507,32 @@ pub fn open(path: [*:0]const u8, flags: u32, perm: usize) usize {...@@ -507,32 +507,32 @@ pub fn open(path: [*:0]const u8, flags: u32, perm: usize) usize {
507}507}
508508
509pub fn create(path: [*:0]const u8, perm: usize) usize {509pub fn create(path: [*:0]const u8, perm: usize) usize {
510 return syscall2(SYS_creat, @ptrToInt(path), perm);510 return syscall2(.creat, @ptrToInt(path), perm);
511}511}
512512
513pub fn openat(dirfd: i32, path: [*:0]const u8, flags: u32, mode: usize) usize {513pub fn openat(dirfd: i32, path: [*:0]const u8, flags: u32, mode: usize) usize {
514 // dirfd could be negative, for example AT_FDCWD is -100514 // dirfd could be negative, for example AT_FDCWD is -100
515 return syscall4(SYS_openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode);515 return syscall4(.openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode);
516}516}
517517
518/// See also `clone` (from the arch-specific include)518/// See also `clone` (from the arch-specific include)
519pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize {519pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize {
520 return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);520 return syscall5(.clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);
521}521}
522522
523/// See also `clone` (from the arch-specific include)523/// See also `clone` (from the arch-specific include)
524pub fn clone2(flags: u32, child_stack_ptr: usize) usize {524pub fn clone2(flags: u32, child_stack_ptr: usize) usize {
525 return syscall2(SYS_clone, flags, child_stack_ptr);525 return syscall2(.clone, flags, child_stack_ptr);
526}526}
527527
528pub fn close(fd: i32) usize {528pub fn close(fd: i32) usize {
529 return syscall1(SYS_close, @bitCast(usize, @as(isize, fd)));529 return syscall1(.close, @bitCast(usize, @as(isize, fd)));
530}530}
531531
532/// Can only be called on 32 bit systems. For 64 bit see `lseek`.532/// Can only be called on 32 bit systems. For 64 bit see `lseek`.
533pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {533pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {
534 return syscall5(534 return syscall5(
535 SYS__llseek,535 ._llseek,
536 @bitCast(usize, @as(isize, fd)),536 @bitCast(usize, @as(isize, fd)),
537 @truncate(usize, offset >> 32),537 @truncate(usize, offset >> 32),
538 @truncate(usize, offset),538 @truncate(usize, offset),
...@@ -543,53 +543,53 @@ pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {...@@ -543,53 +543,53 @@ pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {
543543
544/// Can only be called on 64 bit systems. For 32 bit see `llseek`.544/// Can only be called on 64 bit systems. For 32 bit see `llseek`.
545pub fn lseek(fd: i32, offset: i64, whence: usize) usize {545pub fn lseek(fd: i32, offset: i64, whence: usize) usize {
546 return syscall3(SYS_lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence);546 return syscall3(.lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence);
547}547}
548548
549pub fn exit(status: i32) noreturn {549pub fn exit(status: i32) noreturn {
550 _ = syscall1(SYS_exit, @bitCast(usize, @as(isize, status)));550 _ = syscall1(.exit, @bitCast(usize, @as(isize, status)));
551 unreachable;551 unreachable;
552}552}
553553
554pub fn exit_group(status: i32) noreturn {554pub fn exit_group(status: i32) noreturn {
555 _ = syscall1(SYS_exit_group, @bitCast(usize, @as(isize, status)));555 _ = syscall1(.exit_group, @bitCast(usize, @as(isize, status)));
556 unreachable;556 unreachable;
557}557}
558558
559pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {559pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {
560 return syscall3(SYS_getrandom, @ptrToInt(buf), count, flags);560 return syscall3(.getrandom, @ptrToInt(buf), count, flags);
561}561}
562562
563pub fn kill(pid: pid_t, sig: i32) usize {563pub fn kill(pid: pid_t, sig: i32) usize {
564 return syscall2(SYS_kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig)));564 return syscall2(.kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig)));
565}565}
566566
567pub fn tkill(tid: pid_t, sig: i32) usize {567pub fn tkill(tid: pid_t, sig: i32) usize {
568 return syscall2(SYS_tkill, @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig)));568 return syscall2(.tkill, @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig)));
569}569}
570570
571pub fn tgkill(tgid: pid_t, tid: pid_t, sig: i32) usize {571pub fn tgkill(tgid: pid_t, tid: pid_t, sig: i32) usize {
572 return syscall2(SYS_tgkill, @bitCast(usize, @as(isize, tgid)), @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig)));572 return syscall2(.tgkill, @bitCast(usize, @as(isize, tgid)), @bitCast(usize, @as(isize, tid)), @bitCast(usize, @as(isize, sig)));
573}573}
574574
575pub fn unlink(path: [*:0]const u8) usize {575pub fn unlink(path: [*:0]const u8) usize {
576 if (@hasDecl(@This(), "SYS_unlink")) {576 if (@hasField(SYS, "unlink")) {
577 return syscall1(SYS_unlink, @ptrToInt(path));577 return syscall1(.unlink, @ptrToInt(path));
578 } else {578 } else {
579 return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0);579 return syscall3(.unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0);
580 }580 }
581}581}
582582
583pub fn unlinkat(dirfd: i32, path: [*:0]const u8, flags: u32) usize {583pub fn unlinkat(dirfd: i32, path: [*:0]const u8, flags: u32) usize {
584 return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags);584 return syscall3(.unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags);
585}585}
586586
587pub fn waitpid(pid: pid_t, status: *u32, flags: u32) usize {587pub fn waitpid(pid: pid_t, status: *u32, flags: u32) usize {
588 return syscall4(SYS_wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0);588 return syscall4(.wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0);
589}589}
590590
591pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) usize {591pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) usize {
592 return syscall3(SYS_fcntl, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, cmd)), arg);592 return syscall3(.fcntl, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, cmd)), arg);
593}593}
594594
595var vdso_clock_gettime = @ptrCast(?*const c_void, init_vdso_clock_gettime);595var vdso_clock_gettime = @ptrCast(?*const c_void, init_vdso_clock_gettime);
...@@ -609,7 +609,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {...@@ -609,7 +609,7 @@ pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
609 }609 }
610 }610 }
611 }611 }
612 return syscall2(SYS_clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));612 return syscall2(.clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
613}613}
614614
615fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {615fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {
...@@ -626,86 +626,86 @@ fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {...@@ -626,86 +626,86 @@ fn init_vdso_clock_gettime(clk: i32, ts: *timespec) callconv(.C) usize {
626}626}
627627
628pub fn clock_getres(clk_id: i32, tp: *timespec) usize {628pub fn clock_getres(clk_id: i32, tp: *timespec) usize {
629 return syscall2(SYS_clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));629 return syscall2(.clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
630}630}
631631
632pub fn clock_settime(clk_id: i32, tp: *const timespec) usize {632pub fn clock_settime(clk_id: i32, tp: *const timespec) usize {
633 return syscall2(SYS_clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));633 return syscall2(.clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
634}634}
635635
636pub fn gettimeofday(tv: *timeval, tz: *timezone) usize {636pub fn gettimeofday(tv: *timeval, tz: *timezone) usize {
637 return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz));637 return syscall2(.gettimeofday, @ptrToInt(tv), @ptrToInt(tz));
638}638}
639639
640pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize {640pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize {
641 return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz));641 return syscall2(.settimeofday, @ptrToInt(tv), @ptrToInt(tz));
642}642}
643643
644pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {644pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {
645 return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));645 return syscall2(.nanosleep, @ptrToInt(req), @ptrToInt(rem));
646}646}
647647
648pub fn setuid(uid: u32) usize {648pub fn setuid(uid: u32) usize {
649 if (@hasDecl(@This(), "SYS_setuid32")) {649 if (@hasField(SYS, "setuid32")) {
650 return syscall1(SYS_setuid32, uid);650 return syscall1(.setuid32, uid);
651 } else {651 } else {
652 return syscall1(SYS_setuid, uid);652 return syscall1(.setuid, uid);
653 }653 }
654}654}
655655
656pub fn setgid(gid: u32) usize {656pub fn setgid(gid: u32) usize {
657 if (@hasDecl(@This(), "SYS_setgid32")) {657 if (@hasField(SYS, "setgid32")) {
658 return syscall1(SYS_setgid32, gid);658 return syscall1(.setgid32, gid);
659 } else {659 } else {
660 return syscall1(SYS_setgid, gid);660 return syscall1(.setgid, gid);
661 }661 }
662}662}
663663
664pub fn setreuid(ruid: u32, euid: u32) usize {664pub fn setreuid(ruid: u32, euid: u32) usize {
665 if (@hasDecl(@This(), "SYS_setreuid32")) {665 if (@hasField(SYS, "setreuid32")) {
666 return syscall2(SYS_setreuid32, ruid, euid);666 return syscall2(.setreuid32, ruid, euid);
667 } else {667 } else {
668 return syscall2(SYS_setreuid, ruid, euid);668 return syscall2(.setreuid, ruid, euid);
669 }669 }
670}670}
671671
672pub fn setregid(rgid: u32, egid: u32) usize {672pub fn setregid(rgid: u32, egid: u32) usize {
673 if (@hasDecl(@This(), "SYS_setregid32")) {673 if (@hasField(SYS, "setregid32")) {
674 return syscall2(SYS_setregid32, rgid, egid);674 return syscall2(.setregid32, rgid, egid);
675 } else {675 } else {
676 return syscall2(SYS_setregid, rgid, egid);676 return syscall2(.setregid, rgid, egid);
677 }677 }
678}678}
679679
680pub fn getuid() u32 {680pub fn getuid() u32 {
681 if (@hasDecl(@This(), "SYS_getuid32")) {681 if (@hasField(SYS, "getuid32")) {
682 return @as(u32, syscall0(SYS_getuid32));682 return @as(u32, syscall0(.getuid32));
683 } else {683 } else {
684 return @as(u32, syscall0(SYS_getuid));684 return @as(u32, syscall0(.getuid));
685 }685 }
686}686}
687687
688pub fn getgid() u32 {688pub fn getgid() u32 {
689 if (@hasDecl(@This(), "SYS_getgid32")) {689 if (@hasField(SYS, "getgid32")) {
690 return @as(u32, syscall0(SYS_getgid32));690 return @as(u32, syscall0(.getgid32));
691 } else {691 } else {
692 return @as(u32, syscall0(SYS_getgid));692 return @as(u32, syscall0(.getgid));
693 }693 }
694}694}
695695
696pub fn geteuid() u32 {696pub fn geteuid() u32 {
697 if (@hasDecl(@This(), "SYS_geteuid32")) {697 if (@hasField(SYS, "geteuid32")) {
698 return @as(u32, syscall0(SYS_geteuid32));698 return @as(u32, syscall0(.geteuid32));
699 } else {699 } else {
700 return @as(u32, syscall0(SYS_geteuid));700 return @as(u32, syscall0(.geteuid));
701 }701 }
702}702}
703703
704pub fn getegid() u32 {704pub fn getegid() u32 {
705 if (@hasDecl(@This(), "SYS_getegid32")) {705 if (@hasField(SYS, "getegid32")) {
706 return @as(u32, syscall0(SYS_getegid32));706 return @as(u32, syscall0(.getegid32));
707 } else {707 } else {
708 return @as(u32, syscall0(SYS_getegid));708 return @as(u32, syscall0(.getegid));
709 }709 }
710}710}
711711
...@@ -718,63 +718,63 @@ pub fn setegid(egid: u32) usize {...@@ -718,63 +718,63 @@ pub fn setegid(egid: u32) usize {
718}718}
719719
720pub fn getresuid(ruid: *u32, euid: *u32, suid: *u32) usize {720pub fn getresuid(ruid: *u32, euid: *u32, suid: *u32) usize {
721 if (@hasDecl(@This(), "SYS_getresuid32")) {721 if (@hasField(SYS, "getresuid32")) {
722 return syscall3(SYS_getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));722 return syscall3(.getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
723 } else {723 } else {
724 return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));724 return syscall3(.getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
725 }725 }
726}726}
727727
728pub fn getresgid(rgid: *u32, egid: *u32, sgid: *u32) usize {728pub fn getresgid(rgid: *u32, egid: *u32, sgid: *u32) usize {
729 if (@hasDecl(@This(), "SYS_getresgid32")) {729 if (@hasField(SYS, "getresgid32")) {
730 return syscall3(SYS_getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));730 return syscall3(.getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
731 } else {731 } else {
732 return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));732 return syscall3(.getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
733 }733 }
734}734}
735735
736pub fn setresuid(ruid: u32, euid: u32, suid: u32) usize {736pub fn setresuid(ruid: u32, euid: u32, suid: u32) usize {
737 if (@hasDecl(@This(), "SYS_setresuid32")) {737 if (@hasField(SYS, "setresuid32")) {
738 return syscall3(SYS_setresuid32, ruid, euid, suid);738 return syscall3(.setresuid32, ruid, euid, suid);
739 } else {739 } else {
740 return syscall3(SYS_setresuid, ruid, euid, suid);740 return syscall3(.setresuid, ruid, euid, suid);
741 }741 }
742}742}
743743
744pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize {744pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize {
745 if (@hasDecl(@This(), "SYS_setresgid32")) {745 if (@hasField(SYS, "setresgid32")) {
746 return syscall3(SYS_setresgid32, rgid, egid, sgid);746 return syscall3(.setresgid32, rgid, egid, sgid);
747 } else {747 } else {
748 return syscall3(SYS_setresgid, rgid, egid, sgid);748 return syscall3(.setresgid, rgid, egid, sgid);
749 }749 }
750}750}
751751
752pub fn getgroups(size: usize, list: *u32) usize {752pub fn getgroups(size: usize, list: *u32) usize {
753 if (@hasDecl(@This(), "SYS_getgroups32")) {753 if (@hasField(SYS, "getgroups32")) {
754 return syscall2(SYS_getgroups32, size, @ptrToInt(list));754 return syscall2(.getgroups32, size, @ptrToInt(list));
755 } else {755 } else {
756 return syscall2(SYS_getgroups, size, @ptrToInt(list));756 return syscall2(.getgroups, size, @ptrToInt(list));
757 }757 }
758}758}
759759
760pub fn setgroups(size: usize, list: *const u32) usize {760pub fn setgroups(size: usize, list: *const u32) usize {
761 if (@hasDecl(@This(), "SYS_setgroups32")) {761 if (@hasField(SYS, "setgroups32")) {
762 return syscall2(SYS_setgroups32, size, @ptrToInt(list));762 return syscall2(.setgroups32, size, @ptrToInt(list));
763 } else {763 } else {
764 return syscall2(SYS_setgroups, size, @ptrToInt(list));764 return syscall2(.setgroups, size, @ptrToInt(list));
765 }765 }
766}766}
767767
768pub fn getpid() pid_t {768pub fn getpid() pid_t {
769 return @bitCast(pid_t, @truncate(u32, syscall0(SYS_getpid)));769 return @bitCast(pid_t, @truncate(u32, syscall0(.getpid)));
770}770}
771771
772pub fn gettid() pid_t {772pub fn gettid() pid_t {
773 return @bitCast(pid_t, @truncate(u32, syscall0(SYS_gettid)));773 return @bitCast(pid_t, @truncate(u32, syscall0(.gettid)));
774}774}
775775
776pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) usize {776pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) usize {
777 return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8);777 return syscall4(.rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8);
778}778}
779779
780pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize {780pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize {
...@@ -792,7 +792,7 @@ pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigacti...@@ -792,7 +792,7 @@ pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigacti
792 var ksa_old: k_sigaction = undefined;792 var ksa_old: k_sigaction = undefined;
793 const ksa_mask_size = @sizeOf(@TypeOf(ksa_old.mask));793 const ksa_mask_size = @sizeOf(@TypeOf(ksa_old.mask));
794 @memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &act.mask), ksa_mask_size);794 @memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &act.mask), ksa_mask_size);
795 const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), ksa_mask_size);795 const result = syscall4(.rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), ksa_mask_size);
796 const err = getErrno(result);796 const err = getErrno(result);
797 if (err != 0) {797 if (err != 0) {
798 return result;798 return result;
...@@ -819,42 +819,42 @@ pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) us...@@ -819,42 +819,42 @@ pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) us
819 if (builtin.arch == .i386) {819 if (builtin.arch == .i386) {
820 return socketcall(SC_getsockname, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });820 return socketcall(SC_getsockname, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });
821 }821 }
822 return syscall3(SYS_getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));822 return syscall3(.getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
823}823}
824824
825pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {825pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
826 if (builtin.arch == .i386) {826 if (builtin.arch == .i386) {
827 return socketcall(SC_getpeername, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });827 return socketcall(SC_getpeername, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });
828 }828 }
829 return syscall3(SYS_getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));829 return syscall3(.getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
830}830}
831831
832pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {832pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {
833 if (builtin.arch == .i386) {833 if (builtin.arch == .i386) {
834 return socketcall(SC_socket, &[3]usize{ domain, socket_type, protocol });834 return socketcall(SC_socket, &[3]usize{ domain, socket_type, protocol });
835 }835 }
836 return syscall3(SYS_socket, domain, socket_type, protocol);836 return syscall3(.socket, domain, socket_type, protocol);
837}837}
838838
839pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize {839pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize {
840 if (builtin.arch == .i386) {840 if (builtin.arch == .i386) {
841 return socketcall(SC_setsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen) });841 return socketcall(SC_setsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen) });
842 }842 }
843 return syscall5(SYS_setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen));843 return syscall5(.setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen));
844}844}
845845
846pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize {846pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize {
847 if (builtin.arch == .i386) {847 if (builtin.arch == .i386) {
848 return socketcall(SC_getsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen) });848 return socketcall(SC_getsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen) });
849 }849 }
850 return syscall5(SYS_getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen));850 return syscall5(.getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen));
851}851}
852852
853pub fn sendmsg(fd: i32, msg: *msghdr_const, flags: u32) usize {853pub fn sendmsg(fd: i32, msg: *msghdr_const, flags: u32) usize {
854 if (builtin.arch == .i386) {854 if (builtin.arch == .i386) {
855 return socketcall(SC_sendmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags });855 return socketcall(SC_sendmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags });
856 }856 }
857 return syscall3(SYS_sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);857 return syscall3(.sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);
858}858}
859859
860pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize {860pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize {
...@@ -872,7 +872,7 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize...@@ -872,7 +872,7 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize
872 // batch-send all messages up to the current message872 // batch-send all messages up to the current message
873 if (next_unsent < i) {873 if (next_unsent < i) {
874 const batch_size = i - next_unsent;874 const batch_size = i - next_unsent;
875 const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);875 const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
876 if (getErrno(r) != 0) return next_unsent;876 if (getErrno(r) != 0) return next_unsent;
877 if (r < batch_size) return next_unsent + r;877 if (r < batch_size) return next_unsent + r;
878 }878 }
...@@ -888,68 +888,68 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize...@@ -888,68 +888,68 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize
888 }888 }
889 if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG_EOR)889 if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG_EOR)
890 const batch_size = kvlen - next_unsent;890 const batch_size = kvlen - next_unsent;
891 const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);891 const r = syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
892 if (getErrno(r) != 0) return r;892 if (getErrno(r) != 0) return r;
893 return next_unsent + r;893 return next_unsent + r;
894 }894 }
895 return kvlen;895 return kvlen;
896 }896 }
897 return syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags);897 return syscall4(.sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags);
898}898}
899899
900pub fn connect(fd: i32, addr: *const c_void, len: socklen_t) usize {900pub fn connect(fd: i32, addr: *const c_void, len: socklen_t) usize {
901 if (builtin.arch == .i386) {901 if (builtin.arch == .i386) {
902 return socketcall(SC_connect, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len });902 return socketcall(SC_connect, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len });
903 }903 }
904 return syscall3(SYS_connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len);904 return syscall3(.connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len);
905}905}
906906
907pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize {907pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize {
908 if (builtin.arch == .i386) {908 if (builtin.arch == .i386) {
909 return socketcall(SC_recvmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags });909 return socketcall(SC_recvmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags });
910 }910 }
911 return syscall3(SYS_recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);911 return syscall3(.recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);
912}912}
913913
914pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize {914pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize {
915 if (builtin.arch == .i386) {915 if (builtin.arch == .i386) {
916 return socketcall(SC_recvfrom, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen) });916 return socketcall(SC_recvfrom, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen) });
917 }917 }
918 return syscall6(SYS_recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));918 return syscall6(.recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));
919}919}
920920
921pub fn shutdown(fd: i32, how: i32) usize {921pub fn shutdown(fd: i32, how: i32) usize {
922 if (builtin.arch == .i386) {922 if (builtin.arch == .i386) {
923 return socketcall(SC_shutdown, &[2]usize{ @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)) });923 return socketcall(SC_shutdown, &[2]usize{ @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)) });
924 }924 }
925 return syscall2(SYS_shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)));925 return syscall2(.shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)));
926}926}
927927
928pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize {928pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize {
929 if (builtin.arch == .i386) {929 if (builtin.arch == .i386) {
930 return socketcall(SC_bind, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len) });930 return socketcall(SC_bind, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len) });
931 }931 }
932 return syscall3(SYS_bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len));932 return syscall3(.bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len));
933}933}
934934
935pub fn listen(fd: i32, backlog: u32) usize {935pub fn listen(fd: i32, backlog: u32) usize {
936 if (builtin.arch == .i386) {936 if (builtin.arch == .i386) {
937 return socketcall(SC_listen, &[2]usize{ @bitCast(usize, @as(isize, fd)), backlog });937 return socketcall(SC_listen, &[2]usize{ @bitCast(usize, @as(isize, fd)), backlog });
938 }938 }
939 return syscall2(SYS_listen, @bitCast(usize, @as(isize, fd)), backlog);939 return syscall2(.listen, @bitCast(usize, @as(isize, fd)), backlog);
940}940}
941941
942pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize {942pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize {
943 if (builtin.arch == .i386) {943 if (builtin.arch == .i386) {
944 return socketcall(SC_sendto, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen) });944 return socketcall(SC_sendto, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen) });
945 }945 }
946 return syscall6(SYS_sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen));946 return syscall6(.sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen));
947}947}
948948
949pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize {949pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize {
950 if (@hasDecl(@This(), "SYS_sendfile64")) {950 if (@hasField(SYS, "sendfile64")) {
951 return syscall4(951 return syscall4(
952 SYS_sendfile64,952 .sendfile64,
953 @bitCast(usize, @as(isize, outfd)),953 @bitCast(usize, @as(isize, outfd)),
954 @bitCast(usize, @as(isize, infd)),954 @bitCast(usize, @as(isize, infd)),
955 @ptrToInt(offset),955 @ptrToInt(offset),
...@@ -957,7 +957,7 @@ pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize {...@@ -957,7 +957,7 @@ pub fn sendfile(outfd: i32, infd: i32, offset: ?*i64, count: usize) usize {
957 );957 );
958 } else {958 } else {
959 return syscall4(959 return syscall4(
960 SYS_sendfile,960 .sendfile,
961 @bitCast(usize, @as(isize, outfd)),961 @bitCast(usize, @as(isize, outfd)),
962 @bitCast(usize, @as(isize, infd)),962 @bitCast(usize, @as(isize, infd)),
963 @ptrToInt(offset),963 @ptrToInt(offset),
...@@ -970,7 +970,7 @@ pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usiz...@@ -970,7 +970,7 @@ pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usiz
970 if (builtin.arch == .i386) {970 if (builtin.arch == .i386) {
971 return socketcall(SC_socketpair, &[4]usize{ @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]) });971 return socketcall(SC_socketpair, &[4]usize{ @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]) });
972 }972 }
973 return syscall4(SYS_socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]));973 return syscall4(.socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]));
974}974}
975975
976pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {976pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
...@@ -984,45 +984,45 @@ pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags:...@@ -984,45 +984,45 @@ pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags:
984 if (builtin.arch == .i386) {984 if (builtin.arch == .i386) {
985 return socketcall(SC_accept4, &[4]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags });985 return socketcall(SC_accept4, &[4]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags });
986 }986 }
987 return syscall4(SYS_accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags);987 return syscall4(.accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags);
988}988}
989989
990pub fn fstat(fd: i32, stat_buf: *Stat) usize {990pub fn fstat(fd: i32, stat_buf: *Stat) usize {
991 if (@hasDecl(@This(), "SYS_fstat64")) {991 if (@hasField(SYS, "fstat64")) {
992 return syscall2(SYS_fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));992 return syscall2(.fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
993 } else {993 } else {
994 return syscall2(SYS_fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));994 return syscall2(.fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
995 }995 }
996}996}
997997
998pub fn stat(pathname: [*:0]const u8, statbuf: *Stat) usize {998pub fn stat(pathname: [*:0]const u8, statbuf: *Stat) usize {
999 if (@hasDecl(@This(), "SYS_stat64")) {999 if (@hasField(SYS, "stat64")) {
1000 return syscall2(SYS_stat64, @ptrToInt(pathname), @ptrToInt(statbuf));1000 return syscall2(.stat64, @ptrToInt(pathname), @ptrToInt(statbuf));
1001 } else {1001 } else {
1002 return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf));1002 return syscall2(.stat, @ptrToInt(pathname), @ptrToInt(statbuf));
1003 }1003 }
1004}1004}
10051005
1006pub fn lstat(pathname: [*:0]const u8, statbuf: *Stat) usize {1006pub fn lstat(pathname: [*:0]const u8, statbuf: *Stat) usize {
1007 if (@hasDecl(@This(), "SYS_lstat64")) {1007 if (@hasField(SYS, "lstat64")) {
1008 return syscall2(SYS_lstat64, @ptrToInt(pathname), @ptrToInt(statbuf));1008 return syscall2(.lstat64, @ptrToInt(pathname), @ptrToInt(statbuf));
1009 } else {1009 } else {
1010 return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf));1010 return syscall2(.lstat, @ptrToInt(pathname), @ptrToInt(statbuf));
1011 }1011 }
1012}1012}
10131013
1014pub fn fstatat(dirfd: i32, path: [*:0]const u8, stat_buf: *Stat, flags: u32) usize {1014pub fn fstatat(dirfd: i32, path: [*:0]const u8, stat_buf: *Stat, flags: u32) usize {
1015 if (@hasDecl(@This(), "SYS_fstatat64")) {1015 if (@hasField(SYS, "fstatat64")) {
1016 return syscall4(SYS_fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);1016 return syscall4(.fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
1017 } else {1017 } else {
1018 return syscall4(SYS_fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);1018 return syscall4(.fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
1019 }1019 }
1020}1020}
10211021
1022pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *Statx) usize {1022pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *Statx) usize {
1023 if (@hasDecl(@This(), "SYS_statx")) {1023 if (@hasField(SYS, "statx")) {
1024 return syscall5(1024 return syscall5(
1025 SYS_statx,1025 .statx,
1026 @bitCast(usize, @as(isize, dirfd)),1026 @bitCast(usize, @as(isize, dirfd)),
1027 @ptrToInt(path),1027 @ptrToInt(path),
1028 flags,1028 flags,
...@@ -1034,59 +1034,59 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S...@@ -1034,59 +1034,59 @@ pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *S
1034}1034}
10351035
1036pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {1036pub fn listxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {
1037 return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size);1037 return syscall3(.listxattr, @ptrToInt(path), @ptrToInt(list), size);
1038}1038}
10391039
1040pub fn llistxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {1040pub fn llistxattr(path: [*:0]const u8, list: [*]u8, size: usize) usize {
1041 return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size);1041 return syscall3(.llistxattr, @ptrToInt(path), @ptrToInt(list), size);
1042}1042}
10431043
1044pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize {1044pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize {
1045 return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size);1045 return syscall3(.flistxattr, fd, @ptrToInt(list), size);
1046}1046}
10471047
1048pub fn getxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize {1048pub fn getxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize {
1049 return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);1049 return syscall4(.getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
1050}1050}
10511051
1052pub fn lgetxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize {1052pub fn lgetxattr(path: [*:0]const u8, name: [*:0]const u8, value: [*]u8, size: usize) usize {
1053 return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);1053 return syscall4(.lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
1054}1054}
10551055
1056pub fn fgetxattr(fd: usize, name: [*:0]const u8, value: [*]u8, size: usize) usize {1056pub fn fgetxattr(fd: usize, name: [*:0]const u8, value: [*]u8, size: usize) usize {
1057 return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size);1057 return syscall4(.lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size);
1058}1058}
10591059
1060pub fn setxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {1060pub fn setxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {
1061 return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);1061 return syscall5(.setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
1062}1062}
10631063
1064pub fn lsetxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {1064pub fn lsetxattr(path: [*:0]const u8, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {
1065 return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);1065 return syscall5(.lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
1066}1066}
10671067
1068pub fn fsetxattr(fd: usize, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {1068pub fn fsetxattr(fd: usize, name: [*:0]const u8, value: *const void, size: usize, flags: usize) usize {
1069 return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags);1069 return syscall5(.fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags);
1070}1070}
10711071
1072pub fn removexattr(path: [*:0]const u8, name: [*:0]const u8) usize {1072pub fn removexattr(path: [*:0]const u8, name: [*:0]const u8) usize {
1073 return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name));1073 return syscall2(.removexattr, @ptrToInt(path), @ptrToInt(name));
1074}1074}
10751075
1076pub fn lremovexattr(path: [*:0]const u8, name: [*:0]const u8) usize {1076pub fn lremovexattr(path: [*:0]const u8, name: [*:0]const u8) usize {
1077 return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name));1077 return syscall2(.lremovexattr, @ptrToInt(path), @ptrToInt(name));
1078}1078}
10791079
1080pub fn fremovexattr(fd: usize, name: [*:0]const u8) usize {1080pub fn fremovexattr(fd: usize, name: [*:0]const u8) usize {
1081 return syscall2(SYS_fremovexattr, fd, @ptrToInt(name));1081 return syscall2(.fremovexattr, fd, @ptrToInt(name));
1082}1082}
10831083
1084pub fn sched_yield() usize {1084pub fn sched_yield() usize {
1085 return syscall0(SYS_sched_yield);1085 return syscall0(.sched_yield);
1086}1086}
10871087
1088pub fn sched_getaffinity(pid: pid_t, size: usize, set: *cpu_set_t) usize {1088pub fn sched_getaffinity(pid: pid_t, size: usize, set: *cpu_set_t) usize {
1089 const rc = syscall3(SYS_sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set));1089 const rc = syscall3(.sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set));
1090 if (@bitCast(isize, rc) < 0) return rc;1090 if (@bitCast(isize, rc) < 0) return rc;
1091 if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc);1091 if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc);
1092 return 0;1092 return 0;
...@@ -1097,11 +1097,11 @@ pub fn epoll_create() usize {...@@ -1097,11 +1097,11 @@ pub fn epoll_create() usize {
1097}1097}
10981098
1099pub fn epoll_create1(flags: usize) usize {1099pub fn epoll_create1(flags: usize) usize {
1100 return syscall1(SYS_epoll_create1, flags);1100 return syscall1(.epoll_create1, flags);
1101}1101}
11021102
1103pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize {1103pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize {
1104 return syscall4(SYS_epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev));1104 return syscall4(.epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev));
1105}1105}
11061106
1107pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize {1107pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize {
...@@ -1110,7 +1110,7 @@ pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout...@@ -1110,7 +1110,7 @@ pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout
11101110
1111pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*sigset_t) usize {1111pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*sigset_t) usize {
1112 return syscall6(1112 return syscall6(
1113 SYS_epoll_pwait,1113 .epoll_pwait,
1114 @bitCast(usize, @as(isize, epoll_fd)),1114 @bitCast(usize, @as(isize, epoll_fd)),
1115 @ptrToInt(events),1115 @ptrToInt(events),
1116 @intCast(usize, maxevents),1116 @intCast(usize, maxevents),
...@@ -1121,11 +1121,11 @@ pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeou...@@ -1121,11 +1121,11 @@ pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeou
1121}1121}
11221122
1123pub fn eventfd(count: u32, flags: u32) usize {1123pub fn eventfd(count: u32, flags: u32) usize {
1124 return syscall2(SYS_eventfd2, count, flags);1124 return syscall2(.eventfd2, count, flags);
1125}1125}
11261126
1127pub fn timerfd_create(clockid: i32, flags: u32) usize {1127pub fn timerfd_create(clockid: i32, flags: u32) usize {
1128 return syscall2(SYS_timerfd_create, @bitCast(usize, @as(isize, clockid)), flags);1128 return syscall2(.timerfd_create, @bitCast(usize, @as(isize, clockid)), flags);
1129}1129}
11301130
1131pub const itimerspec = extern struct {1131pub const itimerspec = extern struct {
...@@ -1134,59 +1134,59 @@ pub const itimerspec = extern struct {...@@ -1134,59 +1134,59 @@ pub const itimerspec = extern struct {
1134};1134};
11351135
1136pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize {1136pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize {
1137 return syscall2(SYS_timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value));1137 return syscall2(.timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value));
1138}1138}
11391139
1140pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize {1140pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize {
1141 return syscall4(SYS_timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value));1141 return syscall4(.timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value));
1142}1142}
11431143
1144pub fn unshare(flags: usize) usize {1144pub fn unshare(flags: usize) usize {
1145 return syscall1(SYS_unshare, flags);1145 return syscall1(.unshare, flags);
1146}1146}
11471147
1148pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize {1148pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize {
1149 return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap));1149 return syscall2(.capget, @ptrToInt(hdrp), @ptrToInt(datap));
1150}1150}
11511151
1152pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize {1152pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize {
1153 return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap));1153 return syscall2(.capset, @ptrToInt(hdrp), @ptrToInt(datap));
1154}1154}
11551155
1156pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize {1156pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize {
1157 return syscall2(SYS_sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss));1157 return syscall2(.sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss));
1158}1158}
11591159
1160pub fn uname(uts: *utsname) usize {1160pub fn uname(uts: *utsname) usize {
1161 return syscall1(SYS_uname, @ptrToInt(uts));1161 return syscall1(.uname, @ptrToInt(uts));
1162}1162}
11631163
1164pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize {1164pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize {
1165 return syscall2(SYS_io_uring_setup, entries, @ptrToInt(p));1165 return syscall2(.io_uring_setup, entries, @ptrToInt(p));
1166}1166}
11671167
1168pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize {1168pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize {
1169 return syscall6(SYS_io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8);1169 return syscall6(.io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8);
1170}1170}
11711171
1172pub fn io_uring_register(fd: i32, opcode: u32, arg: ?*const c_void, nr_args: u32) usize {1172pub fn io_uring_register(fd: i32, opcode: IORING_REGISTER, arg: ?*const c_void, nr_args: u32) usize {
1173 return syscall4(SYS_io_uring_register, @bitCast(usize, @as(isize, fd)), opcode, @ptrToInt(arg), nr_args);1173 return syscall4(.io_uring_register, @bitCast(usize, @as(isize, fd)), @enumToInt(opcode), @ptrToInt(arg), nr_args);
1174}1174}
11751175
1176pub fn memfd_create(name: [*:0]const u8, flags: u32) usize {1176pub fn memfd_create(name: [*:0]const u8, flags: u32) usize {
1177 return syscall2(SYS_memfd_create, @ptrToInt(name), flags);1177 return syscall2(.memfd_create, @ptrToInt(name), flags);
1178}1178}
11791179
1180pub fn getrusage(who: i32, usage: *rusage) usize {1180pub fn getrusage(who: i32, usage: *rusage) usize {
1181 return syscall2(SYS_getrusage, @bitCast(usize, @as(isize, who)), @ptrToInt(usage));1181 return syscall2(.getrusage, @bitCast(usize, @as(isize, who)), @ptrToInt(usage));
1182}1182}
11831183
1184pub fn tcgetattr(fd: fd_t, termios_p: *termios) usize {1184pub fn tcgetattr(fd: fd_t, termios_p: *termios) usize {
1185 return syscall3(SYS_ioctl, @bitCast(usize, @as(isize, fd)), TCGETS, @ptrToInt(termios_p));1185 return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCGETS, @ptrToInt(termios_p));
1186}1186}
11871187
1188pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usize {1188pub fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) usize {
1189 return syscall3(SYS_ioctl, @bitCast(usize, @as(isize, fd)), TCSETS + @enumToInt(optional_action), @ptrToInt(termios_p));1189 return syscall3(.ioctl, @bitCast(usize, @as(isize, fd)), TCSETS + @enumToInt(optional_action), @ptrToInt(termios_p));
1190}1190}
11911191
1192test "" {1192test "" {
lib/std/os/linux/arm-eabi.zig+16-16
...@@ -1,36 +1,36 @@...@@ -1,36 +1,36 @@
1usingnamespace @import("../bits.zig");1usingnamespace @import("../bits.zig");
22
3pub fn syscall0(number: usize) usize {3pub fn syscall0(number: SYS) usize {
4 return asm volatile ("svc #0"4 return asm volatile ("svc #0"
5 : [ret] "={r0}" (-> usize)5 : [ret] "={r0}" (-> usize)
6 : [number] "{r7}" (number)6 : [number] "{r7}" (@enumToInt(number))
7 : "memory"7 : "memory"
8 );8 );
9}9}
1010
11pub fn syscall1(number: usize, arg1: usize) usize {11pub fn syscall1(number: SYS, arg1: usize) usize {
12 return asm volatile ("svc #0"12 return asm volatile ("svc #0"
13 : [ret] "={r0}" (-> usize)13 : [ret] "={r0}" (-> usize)
14 : [number] "{r7}" (number),14 : [number] "{r7}" (@enumToInt(number)),
15 [arg1] "{r0}" (arg1)15 [arg1] "{r0}" (arg1)
16 : "memory"16 : "memory"
17 );17 );
18}18}
1919
20pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {20pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
21 return asm volatile ("svc #0"21 return asm volatile ("svc #0"
22 : [ret] "={r0}" (-> usize)22 : [ret] "={r0}" (-> usize)
23 : [number] "{r7}" (number),23 : [number] "{r7}" (@enumToInt(number)),
24 [arg1] "{r0}" (arg1),24 [arg1] "{r0}" (arg1),
25 [arg2] "{r1}" (arg2)25 [arg2] "{r1}" (arg2)
26 : "memory"26 : "memory"
27 );27 );
28}28}
2929
30pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {30pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
31 return asm volatile ("svc #0"31 return asm volatile ("svc #0"
32 : [ret] "={r0}" (-> usize)32 : [ret] "={r0}" (-> usize)
33 : [number] "{r7}" (number),33 : [number] "{r7}" (@enumToInt(number)),
34 [arg1] "{r0}" (arg1),34 [arg1] "{r0}" (arg1),
35 [arg2] "{r1}" (arg2),35 [arg2] "{r1}" (arg2),
36 [arg3] "{r2}" (arg3)36 [arg3] "{r2}" (arg3)
...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
38 );38 );
39}39}
4040
41pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {41pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
42 return asm volatile ("svc #0"42 return asm volatile ("svc #0"
43 : [ret] "={r0}" (-> usize)43 : [ret] "={r0}" (-> usize)
44 : [number] "{r7}" (number),44 : [number] "{r7}" (@enumToInt(number)),
45 [arg1] "{r0}" (arg1),45 [arg1] "{r0}" (arg1),
46 [arg2] "{r1}" (arg2),46 [arg2] "{r1}" (arg2),
47 [arg3] "{r2}" (arg3),47 [arg3] "{r2}" (arg3),
...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
50 );50 );
51}51}
5252
53pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {53pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
54 return asm volatile ("svc #0"54 return asm volatile ("svc #0"
55 : [ret] "={r0}" (-> usize)55 : [ret] "={r0}" (-> usize)
56 : [number] "{r7}" (number),56 : [number] "{r7}" (@enumToInt(number)),
57 [arg1] "{r0}" (arg1),57 [arg1] "{r0}" (arg1),
58 [arg2] "{r1}" (arg2),58 [arg2] "{r1}" (arg2),
59 [arg3] "{r2}" (arg3),59 [arg3] "{r2}" (arg3),
...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
64}64}
6565
66pub fn syscall6(66pub fn syscall6(
67 number: usize,67 number: SYS,
68 arg1: usize,68 arg1: usize,
69 arg2: usize,69 arg2: usize,
70 arg3: usize,70 arg3: usize,
...@@ -74,7 +74,7 @@ pub fn syscall6(...@@ -74,7 +74,7 @@ pub fn syscall6(
74) usize {74) usize {
75 return asm volatile ("svc #0"75 return asm volatile ("svc #0"
76 : [ret] "={r0}" (-> usize)76 : [ret] "={r0}" (-> usize)
77 : [number] "{r7}" (number),77 : [number] "{r7}" (@enumToInt(number)),
78 [arg1] "{r0}" (arg1),78 [arg1] "{r0}" (arg1),
79 [arg2] "{r1}" (arg2),79 [arg2] "{r1}" (arg2),
80 [arg3] "{r2}" (arg3),80 [arg3] "{r2}" (arg3),
...@@ -91,7 +91,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a...@@ -91,7 +91,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a
91pub fn restore() callconv(.Naked) void {91pub fn restore() callconv(.Naked) void {
92 return asm volatile ("svc #0"92 return asm volatile ("svc #0"
93 :93 :
94 : [number] "{r7}" (@as(usize, SYS_sigreturn))94 : [number] "{r7}" (@enumToInt(SYS.sigreturn))
95 : "memory"95 : "memory"
96 );96 );
97}97}
...@@ -99,7 +99,7 @@ pub fn restore() callconv(.Naked) void {...@@ -99,7 +99,7 @@ pub fn restore() callconv(.Naked) void {
99pub fn restore_rt() callconv(.Naked) void {99pub fn restore_rt() callconv(.Naked) void {
100 return asm volatile ("svc #0"100 return asm volatile ("svc #0"
101 :101 :
102 : [number] "{r7}" (@as(usize, SYS_rt_sigreturn))102 : [number] "{r7}" (@enumToInt(SYS.rt_sigreturn))
103 : "memory"103 : "memory"
104 );104 );
105}105}
lib/std/os/linux/arm64.zig+15-15
...@@ -1,36 +1,36 @@...@@ -1,36 +1,36 @@
1usingnamespace @import("../bits.zig");1usingnamespace @import("../bits.zig");
22
3pub fn syscall0(number: usize) usize {3pub fn syscall0(number: SYS) usize {
4 return asm volatile ("svc #0"4 return asm volatile ("svc #0"
5 : [ret] "={x0}" (-> usize)5 : [ret] "={x0}" (-> usize)
6 : [number] "{x8}" (number)6 : [number] "{x8}" (@enumToInt(number))
7 : "memory", "cc"7 : "memory", "cc"
8 );8 );
9}9}
1010
11pub fn syscall1(number: usize, arg1: usize) usize {11pub fn syscall1(number: SYS, arg1: usize) usize {
12 return asm volatile ("svc #0"12 return asm volatile ("svc #0"
13 : [ret] "={x0}" (-> usize)13 : [ret] "={x0}" (-> usize)
14 : [number] "{x8}" (number),14 : [number] "{x8}" (@enumToInt(number)),
15 [arg1] "{x0}" (arg1)15 [arg1] "{x0}" (arg1)
16 : "memory", "cc"16 : "memory", "cc"
17 );17 );
18}18}
1919
20pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {20pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
21 return asm volatile ("svc #0"21 return asm volatile ("svc #0"
22 : [ret] "={x0}" (-> usize)22 : [ret] "={x0}" (-> usize)
23 : [number] "{x8}" (number),23 : [number] "{x8}" (@enumToInt(number)),
24 [arg1] "{x0}" (arg1),24 [arg1] "{x0}" (arg1),
25 [arg2] "{x1}" (arg2)25 [arg2] "{x1}" (arg2)
26 : "memory", "cc"26 : "memory", "cc"
27 );27 );
28}28}
2929
30pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {30pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
31 return asm volatile ("svc #0"31 return asm volatile ("svc #0"
32 : [ret] "={x0}" (-> usize)32 : [ret] "={x0}" (-> usize)
33 : [number] "{x8}" (number),33 : [number] "{x8}" (@enumToInt(number)),
34 [arg1] "{x0}" (arg1),34 [arg1] "{x0}" (arg1),
35 [arg2] "{x1}" (arg2),35 [arg2] "{x1}" (arg2),
36 [arg3] "{x2}" (arg3)36 [arg3] "{x2}" (arg3)
...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
38 );38 );
39}39}
4040
41pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {41pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
42 return asm volatile ("svc #0"42 return asm volatile ("svc #0"
43 : [ret] "={x0}" (-> usize)43 : [ret] "={x0}" (-> usize)
44 : [number] "{x8}" (number),44 : [number] "{x8}" (@enumToInt(number)),
45 [arg1] "{x0}" (arg1),45 [arg1] "{x0}" (arg1),
46 [arg2] "{x1}" (arg2),46 [arg2] "{x1}" (arg2),
47 [arg3] "{x2}" (arg3),47 [arg3] "{x2}" (arg3),
...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
50 );50 );
51}51}
5252
53pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {53pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
54 return asm volatile ("svc #0"54 return asm volatile ("svc #0"
55 : [ret] "={x0}" (-> usize)55 : [ret] "={x0}" (-> usize)
56 : [number] "{x8}" (number),56 : [number] "{x8}" (@enumToInt(number)),
57 [arg1] "{x0}" (arg1),57 [arg1] "{x0}" (arg1),
58 [arg2] "{x1}" (arg2),58 [arg2] "{x1}" (arg2),
59 [arg3] "{x2}" (arg3),59 [arg3] "{x2}" (arg3),
...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
64}64}
6565
66pub fn syscall6(66pub fn syscall6(
67 number: usize,67 number: SYS,
68 arg1: usize,68 arg1: usize,
69 arg2: usize,69 arg2: usize,
70 arg3: usize,70 arg3: usize,
...@@ -74,7 +74,7 @@ pub fn syscall6(...@@ -74,7 +74,7 @@ pub fn syscall6(
74) usize {74) usize {
75 return asm volatile ("svc #0"75 return asm volatile ("svc #0"
76 : [ret] "={x0}" (-> usize)76 : [ret] "={x0}" (-> usize)
77 : [number] "{x8}" (number),77 : [number] "{x8}" (@enumToInt(number)),
78 [arg1] "{x0}" (arg1),78 [arg1] "{x0}" (arg1),
79 [arg2] "{x1}" (arg2),79 [arg2] "{x1}" (arg2),
80 [arg3] "{x2}" (arg3),80 [arg3] "{x2}" (arg3),
...@@ -93,7 +93,7 @@ pub const restore = restore_rt;...@@ -93,7 +93,7 @@ pub const restore = restore_rt;
93pub fn restore_rt() callconv(.Naked) void {93pub fn restore_rt() callconv(.Naked) void {
94 return asm volatile ("svc #0"94 return asm volatile ("svc #0"
95 :95 :
96 : [number] "{x8}" (@as(usize, SYS_rt_sigreturn))96 : [number] "{x8}" (@enumToInt(SYS.rt_sigreturn))
97 : "memory", "cc"97 : "memory", "cc"
98 );98 );
99}99}
lib/std/os/linux/i386.zig+17-17
...@@ -1,36 +1,36 @@...@@ -1,36 +1,36 @@
1usingnamespace @import("../bits.zig");1usingnamespace @import("../bits.zig");
22
3pub fn syscall0(number: usize) usize {3pub fn syscall0(number: SYS) usize {
4 return asm volatile ("int $0x80"4 return asm volatile ("int $0x80"
5 : [ret] "={eax}" (-> usize)5 : [ret] "={eax}" (-> usize)
6 : [number] "{eax}" (number)6 : [number] "{eax}" (@enumToInt(number))
7 : "memory"7 : "memory"
8 );8 );
9}9}
1010
11pub fn syscall1(number: usize, arg1: usize) usize {11pub fn syscall1(number: SYS, arg1: usize) usize {
12 return asm volatile ("int $0x80"12 return asm volatile ("int $0x80"
13 : [ret] "={eax}" (-> usize)13 : [ret] "={eax}" (-> usize)
14 : [number] "{eax}" (number),14 : [number] "{eax}" (@enumToInt(number)),
15 [arg1] "{ebx}" (arg1)15 [arg1] "{ebx}" (arg1)
16 : "memory"16 : "memory"
17 );17 );
18}18}
1919
20pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {20pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
21 return asm volatile ("int $0x80"21 return asm volatile ("int $0x80"
22 : [ret] "={eax}" (-> usize)22 : [ret] "={eax}" (-> usize)
23 : [number] "{eax}" (number),23 : [number] "{eax}" (@enumToInt(number)),
24 [arg1] "{ebx}" (arg1),24 [arg1] "{ebx}" (arg1),
25 [arg2] "{ecx}" (arg2)25 [arg2] "{ecx}" (arg2)
26 : "memory"26 : "memory"
27 );27 );
28}28}
2929
30pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {30pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
31 return asm volatile ("int $0x80"31 return asm volatile ("int $0x80"
32 : [ret] "={eax}" (-> usize)32 : [ret] "={eax}" (-> usize)
33 : [number] "{eax}" (number),33 : [number] "{eax}" (@enumToInt(number)),
34 [arg1] "{ebx}" (arg1),34 [arg1] "{ebx}" (arg1),
35 [arg2] "{ecx}" (arg2),35 [arg2] "{ecx}" (arg2),
36 [arg3] "{edx}" (arg3)36 [arg3] "{edx}" (arg3)
...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
38 );38 );
39}39}
4040
41pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {41pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
42 return asm volatile ("int $0x80"42 return asm volatile ("int $0x80"
43 : [ret] "={eax}" (-> usize)43 : [ret] "={eax}" (-> usize)
44 : [number] "{eax}" (number),44 : [number] "{eax}" (@enumToInt(number)),
45 [arg1] "{ebx}" (arg1),45 [arg1] "{ebx}" (arg1),
46 [arg2] "{ecx}" (arg2),46 [arg2] "{ecx}" (arg2),
47 [arg3] "{edx}" (arg3),47 [arg3] "{edx}" (arg3),
...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
50 );50 );
51}51}
5252
53pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {53pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
54 return asm volatile ("int $0x80"54 return asm volatile ("int $0x80"
55 : [ret] "={eax}" (-> usize)55 : [ret] "={eax}" (-> usize)
56 : [number] "{eax}" (number),56 : [number] "{eax}" (@enumToInt(number)),
57 [arg1] "{ebx}" (arg1),57 [arg1] "{ebx}" (arg1),
58 [arg2] "{ecx}" (arg2),58 [arg2] "{ecx}" (arg2),
59 [arg3] "{edx}" (arg3),59 [arg3] "{edx}" (arg3),
...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
64}64}
6565
66pub fn syscall6(66pub fn syscall6(
67 number: usize,67 number: SYS,
68 arg1: usize,68 arg1: usize,
69 arg2: usize,69 arg2: usize,
70 arg3: usize,70 arg3: usize,
...@@ -84,7 +84,7 @@ pub fn syscall6(...@@ -84,7 +84,7 @@ pub fn syscall6(
84 \\ pop %%ebp84 \\ pop %%ebp
85 \\ add $4, %%esp85 \\ add $4, %%esp
86 : [ret] "={eax}" (-> usize)86 : [ret] "={eax}" (-> usize)
87 : [number] "{eax}" (number),87 : [number] "{eax}" (@enumToInt(number)),
88 [arg1] "{ebx}" (arg1),88 [arg1] "{ebx}" (arg1),
89 [arg2] "{ecx}" (arg2),89 [arg2] "{ecx}" (arg2),
90 [arg3] "{edx}" (arg3),90 [arg3] "{edx}" (arg3),
...@@ -98,7 +98,7 @@ pub fn syscall6(...@@ -98,7 +98,7 @@ pub fn syscall6(
98pub fn socketcall(call: usize, args: [*]usize) usize {98pub fn socketcall(call: usize, args: [*]usize) usize {
99 return asm volatile ("int $0x80"99 return asm volatile ("int $0x80"
100 : [ret] "={eax}" (-> usize)100 : [ret] "={eax}" (-> usize)
101 : [number] "{eax}" (@as(usize, SYS_socketcall)),101 : [number] "{eax}" (@enumToInt(SYS.socketcall)),
102 [arg1] "{ebx}" (call),102 [arg1] "{ebx}" (call),
103 [arg2] "{ecx}" (@ptrToInt(args))103 [arg2] "{ecx}" (@ptrToInt(args))
104 : "memory"104 : "memory"
...@@ -111,7 +111,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a...@@ -111,7 +111,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a
111pub fn restore() callconv(.Naked) void {111pub fn restore() callconv(.Naked) void {
112 return asm volatile ("int $0x80"112 return asm volatile ("int $0x80"
113 :113 :
114 : [number] "{eax}" (@as(usize, SYS_sigreturn))114 : [number] "{eax}" (@enumToInt(SYS.sigreturn))
115 : "memory"115 : "memory"
116 );116 );
117}117}
...@@ -119,7 +119,7 @@ pub fn restore() callconv(.Naked) void {...@@ -119,7 +119,7 @@ pub fn restore() callconv(.Naked) void {
119pub fn restore_rt() callconv(.Naked) void {119pub fn restore_rt() callconv(.Naked) void {
120 return asm volatile ("int $0x80"120 return asm volatile ("int $0x80"
121 :121 :
122 : [number] "{eax}" (@as(usize, SYS_rt_sigreturn))122 : [number] "{eax}" (@enumToInt(SYS.rt_sigreturn))
123 : "memory"123 : "memory"
124 );124 );
125}125}
lib/std/os/linux/mipsel.zig+17-17
...@@ -1,13 +1,13 @@...@@ -1,13 +1,13 @@
1usingnamespace @import("../bits.zig");1usingnamespace @import("../bits.zig");
22
3pub fn syscall0(number: usize) usize {3pub fn syscall0(number: SYS) usize {
4 return asm volatile (4 return asm volatile (
5 \\ syscall5 \\ syscall
6 \\ blez $7, 1f6 \\ blez $7, 1f
7 \\ subu $2, $0, $27 \\ subu $2, $0, $2
8 \\ 1:8 \\ 1:
9 : [ret] "={$2}" (-> usize)9 : [ret] "={$2}" (-> usize)
10 : [number] "{$2}" (number)10 : [number] "{$2}" (@enumToInt(number))
11 : "memory", "cc", "$7"11 : "memory", "cc", "$7"
12 );12 );
13}13}
...@@ -26,46 +26,46 @@ pub fn syscall_pipe(fd: *[2]i32) usize {...@@ -26,46 +26,46 @@ pub fn syscall_pipe(fd: *[2]i32) usize {
26 \\ sw $3, 4($4)26 \\ sw $3, 4($4)
27 \\ 2:27 \\ 2:
28 : [ret] "={$2}" (-> usize)28 : [ret] "={$2}" (-> usize)
29 : [number] "{$2}" (@as(usize, SYS_pipe))29 : [number] "{$2}" (@enumToInt(SYS.pipe))
30 : "memory", "cc", "$7"30 : "memory", "cc", "$7"
31 );31 );
32}32}
3333
34pub fn syscall1(number: usize, arg1: usize) usize {34pub fn syscall1(number: SYS, arg1: usize) usize {
35 return asm volatile (35 return asm volatile (
36 \\ syscall36 \\ syscall
37 \\ blez $7, 1f37 \\ blez $7, 1f
38 \\ subu $2, $0, $238 \\ subu $2, $0, $2
39 \\ 1:39 \\ 1:
40 : [ret] "={$2}" (-> usize)40 : [ret] "={$2}" (-> usize)
41 : [number] "{$2}" (number),41 : [number] "{$2}" (@enumToInt(number)),
42 [arg1] "{$4}" (arg1)42 [arg1] "{$4}" (arg1)
43 : "memory", "cc", "$7"43 : "memory", "cc", "$7"
44 );44 );
45}45}
4646
47pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {47pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
48 return asm volatile (48 return asm volatile (
49 \\ syscall49 \\ syscall
50 \\ blez $7, 1f50 \\ blez $7, 1f
51 \\ subu $2, $0, $251 \\ subu $2, $0, $2
52 \\ 1:52 \\ 1:
53 : [ret] "={$2}" (-> usize)53 : [ret] "={$2}" (-> usize)
54 : [number] "{$2}" (number),54 : [number] "{$2}" (@enumToInt(number)),
55 [arg1] "{$4}" (arg1),55 [arg1] "{$4}" (arg1),
56 [arg2] "{$5}" (arg2)56 [arg2] "{$5}" (arg2)
57 : "memory", "cc", "$7"57 : "memory", "cc", "$7"
58 );58 );
59}59}
6060
61pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {61pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
62 return asm volatile (62 return asm volatile (
63 \\ syscall63 \\ syscall
64 \\ blez $7, 1f64 \\ blez $7, 1f
65 \\ subu $2, $0, $265 \\ subu $2, $0, $2
66 \\ 1:66 \\ 1:
67 : [ret] "={$2}" (-> usize)67 : [ret] "={$2}" (-> usize)
68 : [number] "{$2}" (number),68 : [number] "{$2}" (@enumToInt(number)),
69 [arg1] "{$4}" (arg1),69 [arg1] "{$4}" (arg1),
70 [arg2] "{$5}" (arg2),70 [arg2] "{$5}" (arg2),
71 [arg3] "{$6}" (arg3)71 [arg3] "{$6}" (arg3)
...@@ -73,14 +73,14 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {...@@ -73,14 +73,14 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
73 );73 );
74}74}
7575
76pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {76pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
77 return asm volatile (77 return asm volatile (
78 \\ syscall78 \\ syscall
79 \\ blez $7, 1f79 \\ blez $7, 1f
80 \\ subu $2, $0, $280 \\ subu $2, $0, $2
81 \\ 1:81 \\ 1:
82 : [ret] "={$2}" (-> usize)82 : [ret] "={$2}" (-> usize)
83 : [number] "{$2}" (number),83 : [number] "{$2}" (@enumToInt(number)),
84 [arg1] "{$4}" (arg1),84 [arg1] "{$4}" (arg1),
85 [arg2] "{$5}" (arg2),85 [arg2] "{$5}" (arg2),
86 [arg3] "{$6}" (arg3),86 [arg3] "{$6}" (arg3),
...@@ -89,7 +89,7 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -89,7 +89,7 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
89 );89 );
90}90}
9191
92pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {92pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
93 return asm volatile (93 return asm volatile (
94 \\ .set noat94 \\ .set noat
95 \\ subu $sp, $sp, 2495 \\ subu $sp, $sp, 24
...@@ -100,7 +100,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -100,7 +100,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
100 \\ subu $2, $0, $2100 \\ subu $2, $0, $2
101 \\ 1:101 \\ 1:
102 : [ret] "={$2}" (-> usize)102 : [ret] "={$2}" (-> usize)
103 : [number] "{$2}" (number),103 : [number] "{$2}" (@enumToInt(number)),
104 [arg1] "{$4}" (arg1),104 [arg1] "{$4}" (arg1),
105 [arg2] "{$5}" (arg2),105 [arg2] "{$5}" (arg2),
106 [arg3] "{$6}" (arg3),106 [arg3] "{$6}" (arg3),
...@@ -111,7 +111,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -111,7 +111,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
111}111}
112112
113pub fn syscall6(113pub fn syscall6(
114 number: usize,114 number: SYS,
115 arg1: usize,115 arg1: usize,
116 arg2: usize,116 arg2: usize,
117 arg3: usize,117 arg3: usize,
...@@ -130,7 +130,7 @@ pub fn syscall6(...@@ -130,7 +130,7 @@ pub fn syscall6(
130 \\ subu $2, $0, $2130 \\ subu $2, $0, $2
131 \\ 1:131 \\ 1:
132 : [ret] "={$2}" (-> usize)132 : [ret] "={$2}" (-> usize)
133 : [number] "{$2}" (number),133 : [number] "{$2}" (@enumToInt(number)),
134 [arg1] "{$4}" (arg1),134 [arg1] "{$4}" (arg1),
135 [arg2] "{$5}" (arg2),135 [arg2] "{$5}" (arg2),
136 [arg3] "{$6}" (arg3),136 [arg3] "{$6}" (arg3),
...@@ -147,7 +147,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a...@@ -147,7 +147,7 @@ pub extern fn clone(func: extern fn (arg: usize) u8, stack: usize, flags: u32, a
147pub fn restore() callconv(.Naked) void {147pub fn restore() callconv(.Naked) void {
148 return asm volatile ("syscall"148 return asm volatile ("syscall"
149 :149 :
150 : [number] "{$2}" (@as(usize, SYS_sigreturn))150 : [number] "{$2}" (@enumToInt(SYS.sigreturn))
151 : "memory", "cc", "$7"151 : "memory", "cc", "$7"
152 );152 );
153}153}
...@@ -155,7 +155,7 @@ pub fn restore() callconv(.Naked) void {...@@ -155,7 +155,7 @@ pub fn restore() callconv(.Naked) void {
155pub fn restore_rt() callconv(.Naked) void {155pub fn restore_rt() callconv(.Naked) void {
156 return asm volatile ("syscall"156 return asm volatile ("syscall"
157 :157 :
158 : [number] "{$2}" (@as(usize, SYS_rt_sigreturn))158 : [number] "{$2}" (@enumToInt(SYS.rt_sigreturn))
159 : "memory", "cc", "$7"159 : "memory", "cc", "$7"
160 );160 );
161}161}
lib/std/os/linux/riscv64.zig+15-15
...@@ -1,36 +1,36 @@...@@ -1,36 +1,36 @@
1usingnamespace @import("../bits.zig");1usingnamespace @import("../bits.zig");
22
3pub fn syscall0(number: usize) usize {3pub fn syscall0(number: SYS) usize {
4 return asm volatile ("ecall"4 return asm volatile ("ecall"
5 : [ret] "={x10}" (-> usize)5 : [ret] "={x10}" (-> usize)
6 : [number] "{x17}" (number)6 : [number] "{x17}" (@enumToInt(number))
7 : "memory"7 : "memory"
8 );8 );
9}9}
1010
11pub fn syscall1(number: usize, arg1: usize) usize {11pub fn syscall1(number: SYS, arg1: usize) usize {
12 return asm volatile ("ecall"12 return asm volatile ("ecall"
13 : [ret] "={x10}" (-> usize)13 : [ret] "={x10}" (-> usize)
14 : [number] "{x17}" (number),14 : [number] "{x17}" (@enumToInt(number)),
15 [arg1] "{x10}" (arg1)15 [arg1] "{x10}" (arg1)
16 : "memory"16 : "memory"
17 );17 );
18}18}
1919
20pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {20pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
21 return asm volatile ("ecall"21 return asm volatile ("ecall"
22 : [ret] "={x10}" (-> usize)22 : [ret] "={x10}" (-> usize)
23 : [number] "{x17}" (number),23 : [number] "{x17}" (@enumToInt(number)),
24 [arg1] "{x10}" (arg1),24 [arg1] "{x10}" (arg1),
25 [arg2] "{x11}" (arg2)25 [arg2] "{x11}" (arg2)
26 : "memory"26 : "memory"
27 );27 );
28}28}
2929
30pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {30pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
31 return asm volatile ("ecall"31 return asm volatile ("ecall"
32 : [ret] "={x10}" (-> usize)32 : [ret] "={x10}" (-> usize)
33 : [number] "{x17}" (number),33 : [number] "{x17}" (@enumToInt(number)),
34 [arg1] "{x10}" (arg1),34 [arg1] "{x10}" (arg1),
35 [arg2] "{x11}" (arg2),35 [arg2] "{x11}" (arg2),
36 [arg3] "{x12}" (arg3)36 [arg3] "{x12}" (arg3)
...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
38 );38 );
39}39}
4040
41pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {41pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
42 return asm volatile ("ecall"42 return asm volatile ("ecall"
43 : [ret] "={x10}" (-> usize)43 : [ret] "={x10}" (-> usize)
44 : [number] "{x17}" (number),44 : [number] "{x17}" (@enumToInt(number)),
45 [arg1] "{x10}" (arg1),45 [arg1] "{x10}" (arg1),
46 [arg2] "{x11}" (arg2),46 [arg2] "{x11}" (arg2),
47 [arg3] "{x12}" (arg3),47 [arg3] "{x12}" (arg3),
...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
50 );50 );
51}51}
5252
53pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {53pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
54 return asm volatile ("ecall"54 return asm volatile ("ecall"
55 : [ret] "={x10}" (-> usize)55 : [ret] "={x10}" (-> usize)
56 : [number] "{x17}" (number),56 : [number] "{x17}" (@enumToInt(number)),
57 [arg1] "{x10}" (arg1),57 [arg1] "{x10}" (arg1),
58 [arg2] "{x11}" (arg2),58 [arg2] "{x11}" (arg2),
59 [arg3] "{x12}" (arg3),59 [arg3] "{x12}" (arg3),
...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
64}64}
6565
66pub fn syscall6(66pub fn syscall6(
67 number: usize,67 number: SYS,
68 arg1: usize,68 arg1: usize,
69 arg2: usize,69 arg2: usize,
70 arg3: usize,70 arg3: usize,
...@@ -74,7 +74,7 @@ pub fn syscall6(...@@ -74,7 +74,7 @@ pub fn syscall6(
74) usize {74) usize {
75 return asm volatile ("ecall"75 return asm volatile ("ecall"
76 : [ret] "={x10}" (-> usize)76 : [ret] "={x10}" (-> usize)
77 : [number] "{x17}" (number),77 : [number] "{x17}" (@enumToInt(number)),
78 [arg1] "{x10}" (arg1),78 [arg1] "{x10}" (arg1),
79 [arg2] "{x11}" (arg2),79 [arg2] "{x11}" (arg2),
80 [arg3] "{x12}" (arg3),80 [arg3] "{x12}" (arg3),
...@@ -92,7 +92,7 @@ pub const restore = restore_rt;...@@ -92,7 +92,7 @@ pub const restore = restore_rt;
92pub fn restore_rt() callconv(.Naked) void {92pub fn restore_rt() callconv(.Naked) void {
93 return asm volatile ("ecall"93 return asm volatile ("ecall"
94 :94 :
95 : [number] "{x17}" (@as(usize, SYS_rt_sigreturn))95 : [number] "{x17}" (@enumToInt(SYS.rt_sigreturn))
96 : "memory"96 : "memory"
97 );97 );
98}98}
lib/std/os/linux/tls.zig+4-4
...@@ -122,7 +122,7 @@ pub fn setThreadPointer(addr: usize) void {...@@ -122,7 +122,7 @@ pub fn setThreadPointer(addr: usize) void {
122 .seg_not_present = 0,122 .seg_not_present = 0,
123 .useable = 1,123 .useable = 1,
124 };124 };
125 const rc = std.os.linux.syscall1(std.os.linux.SYS_set_thread_area, @ptrToInt(&user_desc));125 const rc = std.os.linux.syscall1(.set_thread_area, @ptrToInt(&user_desc));
126 assert(rc == 0);126 assert(rc == 0);
127127
128 const gdt_entry_number = user_desc.entry_number;128 const gdt_entry_number = user_desc.entry_number;
...@@ -135,7 +135,7 @@ pub fn setThreadPointer(addr: usize) void {...@@ -135,7 +135,7 @@ pub fn setThreadPointer(addr: usize) void {
135 );135 );
136 },136 },
137 .x86_64 => {137 .x86_64 => {
138 const rc = std.os.linux.syscall2(std.os.linux.SYS_arch_prctl, std.os.linux.ARCH_SET_FS, addr);138 const rc = std.os.linux.syscall2(.arch_prctl, std.os.linux.ARCH_SET_FS, addr);
139 assert(rc == 0);139 assert(rc == 0);
140 },140 },
141 .aarch64 => {141 .aarch64 => {
...@@ -146,7 +146,7 @@ pub fn setThreadPointer(addr: usize) void {...@@ -146,7 +146,7 @@ pub fn setThreadPointer(addr: usize) void {
146 );146 );
147 },147 },
148 .arm => {148 .arm => {
149 const rc = std.os.linux.syscall1(std.os.linux.SYS_set_tls, addr);149 const rc = std.os.linux.syscall1(.set_tls, addr);
150 assert(rc == 0);150 assert(rc == 0);
151 },151 },
152 .riscv64 => {152 .riscv64 => {
...@@ -157,7 +157,7 @@ pub fn setThreadPointer(addr: usize) void {...@@ -157,7 +157,7 @@ pub fn setThreadPointer(addr: usize) void {
157 );157 );
158 },158 },
159 .mipsel => {159 .mipsel => {
160 const rc = std.os.linux.syscall1(std.os.linux.SYS_set_thread_area, addr);160 const rc = std.os.linux.syscall1(.set_thread_area, addr);
161 assert(rc == 0);161 assert(rc == 0);
162 },162 },
163 else => @compileError("Unsupported architecture"),163 else => @compileError("Unsupported architecture"),
lib/std/os/linux/vdso.zig+3-3
...@@ -22,7 +22,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {...@@ -22,7 +22,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
22 }) {22 }) {
23 const this_ph = @intToPtr(*elf.Phdr, ph_addr);23 const this_ph = @intToPtr(*elf.Phdr, ph_addr);
24 switch (this_ph.p_type) {24 switch (this_ph.p_type) {
25 // On WSL1 as well as older kernels, the VDSO ELF image is pre-linked in the upper half 25 // On WSL1 as well as older kernels, the VDSO ELF image is pre-linked in the upper half
26 // of the memory space (e.g. p_vaddr = 0xffffffffff700000 on WSL1).26 // of the memory space (e.g. p_vaddr = 0xffffffffff700000 on WSL1).
27 // Wrapping operations are used on this line as well as subsequent calculations relative to base27 // Wrapping operations are used on this line as well as subsequent calculations relative to base
28 // (lines 47, 78) to ensure no overflow check is tripped.28 // (lines 47, 78) to ensure no overflow check is tripped.
...@@ -70,7 +70,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {...@@ -70,7 +70,7 @@ pub fn lookup(vername: []const u8, name: []const u8) usize {
70 if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue;70 if (0 == (@as(u32, 1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue;
71 if (0 == syms[i].st_shndx) continue;71 if (0 == syms[i].st_shndx) continue;
72 const sym_name = @ptrCast([*:0]const u8, strings + syms[i].st_name);72 const sym_name = @ptrCast([*:0]const u8, strings + syms[i].st_name);
73 if (!mem.eql(u8, name, mem.toSliceConst(u8, sym_name))) continue;73 if (!mem.eql(u8, name, mem.spanZ(sym_name))) continue;
74 if (maybe_versym) |versym| {74 if (maybe_versym) |versym| {
75 if (!checkver(maybe_verdef.?, versym[i], vername, strings))75 if (!checkver(maybe_verdef.?, versym[i], vername, strings))
76 continue;76 continue;
...@@ -93,5 +93,5 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [...@@ -93,5 +93,5 @@ fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [
93 }93 }
94 const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux);94 const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux);
95 const vda_name = @ptrCast([*:0]const u8, strings + aux.vda_name);95 const vda_name = @ptrCast([*:0]const u8, strings + aux.vda_name);
96 return mem.eql(u8, vername, mem.toSliceConst(u8, vda_name));96 return mem.eql(u8, vername, mem.spanZ(vda_name));
97}97}
lib/std/os/linux/x86_64.zig+15-15
...@@ -1,36 +1,36 @@...@@ -1,36 +1,36 @@
1usingnamespace @import("../bits.zig");1usingnamespace @import("../bits.zig");
22
3pub fn syscall0(number: usize) usize {3pub fn syscall0(number: SYS) usize {
4 return asm volatile ("syscall"4 return asm volatile ("syscall"
5 : [ret] "={rax}" (-> usize)5 : [ret] "={rax}" (-> usize)
6 : [number] "{rax}" (number)6 : [number] "{rax}" (@enumToInt(number))
7 : "rcx", "r11", "memory"7 : "rcx", "r11", "memory"
8 );8 );
9}9}
1010
11pub fn syscall1(number: usize, arg1: usize) usize {11pub fn syscall1(number: SYS, arg1: usize) usize {
12 return asm volatile ("syscall"12 return asm volatile ("syscall"
13 : [ret] "={rax}" (-> usize)13 : [ret] "={rax}" (-> usize)
14 : [number] "{rax}" (number),14 : [number] "{rax}" (@enumToInt(number)),
15 [arg1] "{rdi}" (arg1)15 [arg1] "{rdi}" (arg1)
16 : "rcx", "r11", "memory"16 : "rcx", "r11", "memory"
17 );17 );
18}18}
1919
20pub fn syscall2(number: usize, arg1: usize, arg2: usize) usize {20pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize {
21 return asm volatile ("syscall"21 return asm volatile ("syscall"
22 : [ret] "={rax}" (-> usize)22 : [ret] "={rax}" (-> usize)
23 : [number] "{rax}" (number),23 : [number] "{rax}" (@enumToInt(number)),
24 [arg1] "{rdi}" (arg1),24 [arg1] "{rdi}" (arg1),
25 [arg2] "{rsi}" (arg2)25 [arg2] "{rsi}" (arg2)
26 : "rcx", "r11", "memory"26 : "rcx", "r11", "memory"
27 );27 );
28}28}
2929
30pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {30pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
31 return asm volatile ("syscall"31 return asm volatile ("syscall"
32 : [ret] "={rax}" (-> usize)32 : [ret] "={rax}" (-> usize)
33 : [number] "{rax}" (number),33 : [number] "{rax}" (@enumToInt(number)),
34 [arg1] "{rdi}" (arg1),34 [arg1] "{rdi}" (arg1),
35 [arg2] "{rsi}" (arg2),35 [arg2] "{rsi}" (arg2),
36 [arg3] "{rdx}" (arg3)36 [arg3] "{rdx}" (arg3)
...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {...@@ -38,10 +38,10 @@ pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize {
38 );38 );
39}39}
4040
41pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {41pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
42 return asm volatile ("syscall"42 return asm volatile ("syscall"
43 : [ret] "={rax}" (-> usize)43 : [ret] "={rax}" (-> usize)
44 : [number] "{rax}" (number),44 : [number] "{rax}" (@enumToInt(number)),
45 [arg1] "{rdi}" (arg1),45 [arg1] "{rdi}" (arg1),
46 [arg2] "{rsi}" (arg2),46 [arg2] "{rsi}" (arg2),
47 [arg3] "{rdx}" (arg3),47 [arg3] "{rdx}" (arg3),
...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -50,10 +50,10 @@ pub fn syscall4(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
50 );50 );
51}51}
5252
53pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {53pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
54 return asm volatile ("syscall"54 return asm volatile ("syscall"
55 : [ret] "={rax}" (-> usize)55 : [ret] "={rax}" (-> usize)
56 : [number] "{rax}" (number),56 : [number] "{rax}" (@enumToInt(number)),
57 [arg1] "{rdi}" (arg1),57 [arg1] "{rdi}" (arg1),
58 [arg2] "{rsi}" (arg2),58 [arg2] "{rsi}" (arg2),
59 [arg3] "{rdx}" (arg3),59 [arg3] "{rdx}" (arg3),
...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz...@@ -64,7 +64,7 @@ pub fn syscall5(number: usize, arg1: usize, arg2: usize, arg3: usize, arg4: usiz
64}64}
6565
66pub fn syscall6(66pub fn syscall6(
67 number: usize,67 number: SYS,
68 arg1: usize,68 arg1: usize,
69 arg2: usize,69 arg2: usize,
70 arg3: usize,70 arg3: usize,
...@@ -74,7 +74,7 @@ pub fn syscall6(...@@ -74,7 +74,7 @@ pub fn syscall6(
74) usize {74) usize {
75 return asm volatile ("syscall"75 return asm volatile ("syscall"
76 : [ret] "={rax}" (-> usize)76 : [ret] "={rax}" (-> usize)
77 : [number] "{rax}" (number),77 : [number] "{rax}" (@enumToInt(number)),
78 [arg1] "{rdi}" (arg1),78 [arg1] "{rdi}" (arg1),
79 [arg2] "{rsi}" (arg2),79 [arg2] "{rsi}" (arg2),
80 [arg3] "{rdx}" (arg3),80 [arg3] "{rdx}" (arg3),
...@@ -93,7 +93,7 @@ pub const restore = restore_rt;...@@ -93,7 +93,7 @@ pub const restore = restore_rt;
93pub fn restore_rt() callconv(.Naked) void {93pub fn restore_rt() callconv(.Naked) void {
94 return asm volatile ("syscall"94 return asm volatile ("syscall"
95 :95 :
96 : [number] "{rax}" (@as(usize, SYS_rt_sigreturn))96 : [number] "{rax}" (@enumToInt(SYS.rt_sigreturn))
97 : "rcx", "r11", "memory"97 : "rcx", "r11", "memory"
98 );98 );
99}99}
lib/std/os/test.zig+8-8
...@@ -18,8 +18,8 @@ const AtomicOrder = builtin.AtomicOrder;...@@ -18,8 +18,8 @@ const AtomicOrder = builtin.AtomicOrder;
1818
19test "makePath, put some files in it, deleteTree" {19test "makePath, put some files in it, deleteTree" {
20 try fs.cwd().makePath("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c");20 try fs.cwd().makePath("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c");
21 try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense");21 try fs.cwd().writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "c" ++ fs.path.sep_str ++ "file.txt", "nonsense");
22 try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah");22 try fs.cwd().writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah");
23 try fs.cwd().deleteTree("os_test_tmp");23 try fs.cwd().deleteTree("os_test_tmp");
24 if (fs.cwd().openDir("os_test_tmp", .{})) |dir| {24 if (fs.cwd().openDir("os_test_tmp", .{})) |dir| {
25 @panic("expected error");25 @panic("expected error");
...@@ -36,8 +36,8 @@ test "access file" {...@@ -36,8 +36,8 @@ test "access file" {
36 expect(err == error.FileNotFound);36 expect(err == error.FileNotFound);
37 }37 }
3838
39 try io.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", "");39 try fs.cwd().writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", "");
40 try os.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", os.F_OK);40 try fs.cwd().access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{});
41 try fs.cwd().deleteTree("os_test_tmp");41 try fs.cwd().deleteTree("os_test_tmp");
42}42}
4343
...@@ -65,12 +65,12 @@ test "sendfile" {...@@ -65,12 +65,12 @@ test "sendfile" {
65 },65 },
66 };66 };
6767
68 var src_file = try dir.createFileC("sendfile1.txt", .{ .read = true });68 var src_file = try dir.createFileZ("sendfile1.txt", .{ .read = true });
69 defer src_file.close();69 defer src_file.close();
7070
71 try src_file.writevAll(&vecs);71 try src_file.writevAll(&vecs);
7272
73 var dest_file = try dir.createFileC("sendfile2.txt", .{ .read = true });73 var dest_file = try dir.createFileZ("sendfile2.txt", .{ .read = true });
74 defer dest_file.close();74 defer dest_file.close();
7575
76 const header1 = "header1\n";76 const header1 = "header1\n";
...@@ -192,12 +192,12 @@ test "AtomicFile" {...@@ -192,12 +192,12 @@ test "AtomicFile" {
192 \\ this is a test file192 \\ this is a test file
193 ;193 ;
194 {194 {
195 var af = try fs.AtomicFile.init(test_out_file, File.default_mode);195 var af = try fs.cwd().atomicFile(test_out_file, .{});
196 defer af.deinit();196 defer af.deinit();
197 try af.file.writeAll(test_content);197 try af.file.writeAll(test_content);
198 try af.finish();198 try af.finish();
199 }199 }
200 const content = try io.readFileAlloc(testing.allocator, test_out_file);200 const content = try fs.cwd().readFileAlloc(testing.allocator, test_out_file, 9999);
201 defer testing.allocator.free(content);201 defer testing.allocator.free(content);
202 expect(mem.eql(u8, content, test_content));202 expect(mem.eql(u8, content, test_content));
203203
lib/std/os/windows.zig+5-5
...@@ -119,7 +119,7 @@ pub fn OpenFileW(...@@ -119,7 +119,7 @@ pub fn OpenFileW(
119119
120 var result: HANDLE = undefined;120 var result: HANDLE = undefined;
121121
122 const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) {122 const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) {
123 error.Overflow => return error.NameTooLong,123 error.Overflow => return error.NameTooLong,
124 };124 };
125 var nt_name = UNICODE_STRING{125 var nt_name = UNICODE_STRING{
...@@ -697,7 +697,7 @@ pub fn CreateDirectoryW(...@@ -697,7 +697,7 @@ pub fn CreateDirectoryW(
697 sub_path_w: [*:0]const u16,697 sub_path_w: [*:0]const u16,
698 sa: ?*SECURITY_ATTRIBUTES,698 sa: ?*SECURITY_ATTRIBUTES,
699) CreateDirectoryError!HANDLE {699) CreateDirectoryError!HANDLE {
700 const path_len_bytes = math.cast(u16, mem.toSliceConst(u16, sub_path_w).len * 2) catch |err| switch (err) {700 const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) {
701 error.Overflow => return error.NameTooLong,701 error.Overflow => return error.NameTooLong,
702 };702 };
703 var nt_name = UNICODE_STRING{703 var nt_name = UNICODE_STRING{
...@@ -905,7 +905,7 @@ pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA {...@@ -905,7 +905,7 @@ pub fn WSAStartup(majorVersion: u8, minorVersion: u8) !ws2_32.WSADATA {
905 var wsadata: ws2_32.WSADATA = undefined;905 var wsadata: ws2_32.WSADATA = undefined;
906 return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) {906 return switch (ws2_32.WSAStartup((@as(WORD, minorVersion) << 8) | majorVersion, &wsadata)) {
907 0 => wsadata,907 0 => wsadata,
908 else => |err| unexpectedWSAError(@intToEnum(WinsockError, err)),908 else => |err| unexpectedWSAError(@intToEnum(ws2_32.WinsockError, @intCast(u16, err))),
909 };909 };
910}910}
911911
...@@ -1226,7 +1226,7 @@ pub fn nanoSecondsToFileTime(ns: i64) FILETIME {...@@ -1226,7 +1226,7 @@ pub fn nanoSecondsToFileTime(ns: i64) FILETIME {
1226}1226}
12271227
1228pub fn cStrToPrefixedFileW(s: [*:0]const u8) ![PATH_MAX_WIDE:0]u16 {1228pub fn cStrToPrefixedFileW(s: [*:0]const u8) ![PATH_MAX_WIDE:0]u16 {
1229 return sliceToPrefixedFileW(mem.toSliceConst(u8, s));1229 return sliceToPrefixedFileW(mem.spanZ(s));
1230}1230}
12311231
1232pub fn sliceToPrefixedFileW(s: []const u8) ![PATH_MAX_WIDE:0]u16 {1232pub fn sliceToPrefixedFileW(s: []const u8) ![PATH_MAX_WIDE:0]u16 {
...@@ -1304,7 +1304,7 @@ pub fn unexpectedError(err: Win32Error) std.os.UnexpectedError {...@@ -1304,7 +1304,7 @@ pub fn unexpectedError(err: Win32Error) std.os.UnexpectedError {
1304 return error.Unexpected;1304 return error.Unexpected;
1305}1305}
13061306
1307pub fn unexpectedWSAError(err: WinsockError) std.os.UnexpectedError {1307pub fn unexpectedWSAError(err: ws2_32.WinsockError) std.os.UnexpectedError {
1308 return unexpectedError(@intToEnum(Win32Error, @enumToInt(err)));1308 return unexpectedError(@intToEnum(Win32Error, @enumToInt(err)));
1309}1309}
13101310
lib/std/pdb.zig+1-1
...@@ -649,7 +649,7 @@ const MsfStream = struct {...@@ -649,7 +649,7 @@ const MsfStream = struct {
649 while (true) {649 while (true) {
650 const byte = try self.inStream().readByte();650 const byte = try self.inStream().readByte();
651 if (byte == 0) {651 if (byte == 0) {
652 return list.toSlice();652 return list.span();
653 }653 }
654 try list.append(byte);654 try list.append(byte);
655 }655 }
lib/std/process.zig+7-7
...@@ -83,7 +83,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {...@@ -83,7 +83,7 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap {
8383
84 for (environ) |env| {84 for (environ) |env| {
85 if (env) |ptr| {85 if (env) |ptr| {
86 const pair = mem.toSlice(u8, ptr);86 const pair = mem.spanZ(ptr);
87 var parts = mem.separate(pair, "=");87 var parts = mem.separate(pair, "=");
88 const key = parts.next().?;88 const key = parts.next().?;
89 const value = parts.next().?;89 const value = parts.next().?;
...@@ -176,7 +176,7 @@ pub const ArgIteratorPosix = struct {...@@ -176,7 +176,7 @@ pub const ArgIteratorPosix = struct {
176176
177 const s = os.argv[self.index];177 const s = os.argv[self.index];
178 self.index += 1;178 self.index += 1;
179 return mem.toSlice(u8, s);179 return mem.spanZ(s);
180 }180 }
181181
182 pub fn skip(self: *ArgIteratorPosix) bool {182 pub fn skip(self: *ArgIteratorPosix) bool {
...@@ -401,7 +401,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {...@@ -401,7 +401,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {
401401
402 var i: usize = 0;402 var i: usize = 0;
403 while (i < count) : (i += 1) {403 while (i < count) : (i += 1) {
404 result_slice[i] = mem.toSlice(u8, argv[i]);404 result_slice[i] = mem.spanZ(argv[i]);
405 }405 }
406406
407 return result_slice;407 return result_slice;
...@@ -422,8 +422,8 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {...@@ -422,8 +422,8 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![][]u8 {
422 try slice_list.append(arg.len);422 try slice_list.append(arg.len);
423 }423 }
424424
425 const contents_slice = contents.toSliceConst();425 const contents_slice = contents.span();
426 const slice_sizes = slice_list.toSliceConst();426 const slice_sizes = slice_list.span();
427 const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len);427 const slice_list_bytes = try math.mul(usize, @sizeOf([]u8), slice_sizes.len);
428 const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len);428 const total_bytes = try math.add(usize, slice_list_bytes, contents_slice.len);
429 const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes);429 const buf = try allocator.alignedAlloc(u8, @alignOf([]u8), total_bytes);
...@@ -636,7 +636,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]...@@ -636,7 +636,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]
636 fn callback(info: *os.dl_phdr_info, size: usize, list: *List) !void {636 fn callback(info: *os.dl_phdr_info, size: usize, list: *List) !void {
637 const name = info.dlpi_name orelse return;637 const name = info.dlpi_name orelse return;
638 if (name[0] == '/') {638 if (name[0] == '/') {
639 const item = try mem.dupeZ(list.allocator, u8, mem.toSliceConst(u8, name));639 const item = try mem.dupeZ(list.allocator, u8, mem.spanZ(name));
640 errdefer list.allocator.free(item);640 errdefer list.allocator.free(item);
641 try list.append(item);641 try list.append(item);
642 }642 }
...@@ -657,7 +657,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]...@@ -657,7 +657,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0]
657 var i: u32 = 0;657 var i: u32 = 0;
658 while (i < img_count) : (i += 1) {658 while (i < img_count) : (i += 1) {
659 const name = std.c._dyld_get_image_name(i);659 const name = std.c._dyld_get_image_name(i);
660 const item = try mem.dupeZ(allocator, u8, mem.toSliceConst(u8, name));660 const item = try mem.dupeZ(allocator, u8, mem.spanZ(name));
661 errdefer allocator.free(item);661 errdefer allocator.free(item);
662 try paths.append(item);662 try paths.append(item);
663 }663 }
lib/std/rand.zig+13-19
...@@ -59,7 +59,7 @@ pub const Random = struct {...@@ -59,7 +59,7 @@ pub const Random = struct {
59 return @bitCast(T, unsigned_result);59 return @bitCast(T, unsigned_result);
60 }60 }
6161
62 /// Constant-time implementation off ::uintLessThan.62 /// Constant-time implementation off `uintLessThan`.
63 /// The results of this function may be biased.63 /// The results of this function may be biased.
64 pub fn uintLessThanBiased(r: *Random, comptime T: type, less_than: T) T {64 pub fn uintLessThanBiased(r: *Random, comptime T: type, less_than: T) T {
65 comptime assert(T.is_signed == false);65 comptime assert(T.is_signed == false);
...@@ -73,13 +73,13 @@ pub const Random = struct {...@@ -73,13 +73,13 @@ pub const Random = struct {
73 }73 }
7474
75 /// Returns an evenly distributed random unsigned integer `0 <= i < less_than`.75 /// Returns an evenly distributed random unsigned integer `0 <= i < less_than`.
76 /// This function assumes that the underlying ::fillFn produces evenly distributed values.76 /// This function assumes that the underlying `fillFn` produces evenly distributed values.
77 /// Within this assumption, the runtime of this function is exponentially distributed.77 /// Within this assumption, the runtime of this function is exponentially distributed.
78 /// If ::fillFn were backed by a true random generator,78 /// If `fillFn` were backed by a true random generator,
79 /// the runtime of this function would technically be unbounded.79 /// the runtime of this function would technically be unbounded.
80 /// However, if ::fillFn is backed by any evenly distributed pseudo random number generator,80 /// However, if `fillFn` is backed by any evenly distributed pseudo random number generator,
81 /// this function is guaranteed to return.81 /// this function is guaranteed to return.
82 /// If you need deterministic runtime bounds, use `::uintLessThanBiased`.82 /// If you need deterministic runtime bounds, use `uintLessThanBiased`.
83 pub fn uintLessThan(r: *Random, comptime T: type, less_than: T) T {83 pub fn uintLessThan(r: *Random, comptime T: type, less_than: T) T {
84 comptime assert(T.is_signed == false);84 comptime assert(T.is_signed == false);
85 comptime assert(T.bit_count <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!85 comptime assert(T.bit_count <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!
...@@ -116,7 +116,7 @@ pub const Random = struct {...@@ -116,7 +116,7 @@ pub const Random = struct {
116 return @intCast(T, m >> Small.bit_count);116 return @intCast(T, m >> Small.bit_count);
117 }117 }
118118
119 /// Constant-time implementation off ::uintAtMost.119 /// Constant-time implementation off `uintAtMost`.
120 /// The results of this function may be biased.120 /// The results of this function may be biased.
121 pub fn uintAtMostBiased(r: *Random, comptime T: type, at_most: T) T {121 pub fn uintAtMostBiased(r: *Random, comptime T: type, at_most: T) T {
122 assert(T.is_signed == false);122 assert(T.is_signed == false);
...@@ -128,7 +128,7 @@ pub const Random = struct {...@@ -128,7 +128,7 @@ pub const Random = struct {
128 }128 }
129129
130 /// Returns an evenly distributed random unsigned integer `0 <= i <= at_most`.130 /// Returns an evenly distributed random unsigned integer `0 <= i <= at_most`.
131 /// See ::uintLessThan, which this function uses in most cases,131 /// See `uintLessThan`, which this function uses in most cases,
132 /// for commentary on the runtime of this function.132 /// for commentary on the runtime of this function.
133 pub fn uintAtMost(r: *Random, comptime T: type, at_most: T) T {133 pub fn uintAtMost(r: *Random, comptime T: type, at_most: T) T {
134 assert(T.is_signed == false);134 assert(T.is_signed == false);
...@@ -139,7 +139,7 @@ pub const Random = struct {...@@ -139,7 +139,7 @@ pub const Random = struct {
139 return r.uintLessThan(T, at_most + 1);139 return r.uintLessThan(T, at_most + 1);
140 }140 }
141141
142 /// Constant-time implementation off ::intRangeLessThan.142 /// Constant-time implementation off `intRangeLessThan`.
143 /// The results of this function may be biased.143 /// The results of this function may be biased.
144 pub fn intRangeLessThanBiased(r: *Random, comptime T: type, at_least: T, less_than: T) T {144 pub fn intRangeLessThanBiased(r: *Random, comptime T: type, at_least: T, less_than: T) T {
145 assert(at_least < less_than);145 assert(at_least < less_than);
...@@ -157,7 +157,7 @@ pub const Random = struct {...@@ -157,7 +157,7 @@ pub const Random = struct {
157 }157 }
158158
159 /// Returns an evenly distributed random integer `at_least <= i < less_than`.159 /// Returns an evenly distributed random integer `at_least <= i < less_than`.
160 /// See ::uintLessThan, which this function uses in most cases,160 /// See `uintLessThan`, which this function uses in most cases,
161 /// for commentary on the runtime of this function.161 /// for commentary on the runtime of this function.
162 pub fn intRangeLessThan(r: *Random, comptime T: type, at_least: T, less_than: T) T {162 pub fn intRangeLessThan(r: *Random, comptime T: type, at_least: T, less_than: T) T {
163 assert(at_least < less_than);163 assert(at_least < less_than);
...@@ -174,7 +174,7 @@ pub const Random = struct {...@@ -174,7 +174,7 @@ pub const Random = struct {
174 }174 }
175 }175 }
176176
177 /// Constant-time implementation off ::intRangeAtMostBiased.177 /// Constant-time implementation off `intRangeAtMostBiased`.
178 /// The results of this function may be biased.178 /// The results of this function may be biased.
179 pub fn intRangeAtMostBiased(r: *Random, comptime T: type, at_least: T, at_most: T) T {179 pub fn intRangeAtMostBiased(r: *Random, comptime T: type, at_least: T, at_most: T) T {
180 assert(at_least <= at_most);180 assert(at_least <= at_most);
...@@ -192,7 +192,7 @@ pub const Random = struct {...@@ -192,7 +192,7 @@ pub const Random = struct {
192 }192 }
193193
194 /// Returns an evenly distributed random integer `at_least <= i <= at_most`.194 /// Returns an evenly distributed random integer `at_least <= i <= at_most`.
195 /// See ::uintLessThan, which this function uses in most cases,195 /// See `uintLessThan`, which this function uses in most cases,
196 /// for commentary on the runtime of this function.196 /// for commentary on the runtime of this function.
197 pub fn intRangeAtMost(r: *Random, comptime T: type, at_least: T, at_most: T) T {197 pub fn intRangeAtMost(r: *Random, comptime T: type, at_least: T, at_most: T) T {
198 assert(at_least <= at_most);198 assert(at_least <= at_most);
...@@ -209,15 +209,9 @@ pub const Random = struct {...@@ -209,15 +209,9 @@ pub const Random = struct {
209 }209 }
210 }210 }
211211
212 /// TODO: deprecated. use ::boolean or ::int instead.212 pub const scalar = @compileError("deprecated; use boolean() or int() instead");
213 pub fn scalar(r: *Random, comptime T: type) T {
214 return if (T == bool) r.boolean() else r.int(T);
215 }
216213
217 /// TODO: deprecated. renamed to ::intRangeLessThan214 pub const range = @compileError("deprecated; use intRangeLessThan()");
218 pub fn range(r: *Random, comptime T: type, start: T, end: T) T {
219 return r.intRangeLessThan(T, start, end);
220 }
221215
222 /// Return a floating point value evenly distributed in the range [0, 1).216 /// Return a floating point value evenly distributed in the range [0, 1).
223 pub fn float(r: *Random, comptime T: type) T {217 pub fn float(r: *Random, comptime T: type) T {
lib/std/sort.zig+2-2
...@@ -1227,13 +1227,13 @@ test "sort fuzz testing" {...@@ -1227,13 +1227,13 @@ test "sort fuzz testing" {
1227var fixed_buffer_mem: [100 * 1024]u8 = undefined;1227var fixed_buffer_mem: [100 * 1024]u8 = undefined;
12281228
1229fn fuzzTest(rng: *std.rand.Random) !void {1229fn fuzzTest(rng: *std.rand.Random) !void {
1230 const array_size = rng.range(usize, 0, 1000);1230 const array_size = rng.intRangeLessThan(usize, 0, 1000);
1231 var array = try testing.allocator.alloc(IdAndValue, array_size);1231 var array = try testing.allocator.alloc(IdAndValue, array_size);
1232 defer testing.allocator.free(array);1232 defer testing.allocator.free(array);
1233 // populate with random data1233 // populate with random data
1234 for (array) |*item, index| {1234 for (array) |*item, index| {
1235 item.id = index;1235 item.id = index;
1236 item.value = rng.range(i32, 0, 100);1236 item.value = rng.intRangeLessThan(i32, 0, 100);
1237 }1237 }
1238 sort(IdAndValue, array, cmpByValue);1238 sort(IdAndValue, array, cmpByValue);
12391239
lib/std/special/build_runner.zig+3-3
...@@ -116,7 +116,7 @@ pub fn main() !void {...@@ -116,7 +116,7 @@ pub fn main() !void {
116 if (builder.validateUserInputDidItFail())116 if (builder.validateUserInputDidItFail())
117 return usageAndErr(builder, true, stderr_stream);117 return usageAndErr(builder, true, stderr_stream);
118118
119 builder.make(targets.toSliceConst()) catch |err| {119 builder.make(targets.span()) catch |err| {
120 switch (err) {120 switch (err) {
121 error.InvalidStepName => {121 error.InvalidStepName => {
122 return usageAndErr(builder, true, stderr_stream);122 return usageAndErr(builder, true, stderr_stream);
...@@ -151,7 +151,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {...@@ -151,7 +151,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
151 , .{builder.zig_exe});151 , .{builder.zig_exe});
152152
153 const allocator = builder.allocator;153 const allocator = builder.allocator;
154 for (builder.top_level_steps.toSliceConst()) |top_level_step| {154 for (builder.top_level_steps.span()) |top_level_step| {
155 const name = if (&top_level_step.step == builder.default_step)155 const name = if (&top_level_step.step == builder.default_step)
156 try fmt.allocPrint(allocator, "{} (default)", .{top_level_step.step.name})156 try fmt.allocPrint(allocator, "{} (default)", .{top_level_step.step.name})
157 else157 else
...@@ -174,7 +174,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {...@@ -174,7 +174,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
174 if (builder.available_options_list.len == 0) {174 if (builder.available_options_list.len == 0) {
175 try out_stream.print(" (none)\n", .{});175 try out_stream.print(" (none)\n", .{});
176 } else {176 } else {
177 for (builder.available_options_list.toSliceConst()) |option| {177 for (builder.available_options_list.span()) |option| {
178 const name = try fmt.allocPrint(allocator, " -D{}=[{}]", .{178 const name = try fmt.allocPrint(allocator, " -D{}=[{}]", .{
179 option.name,179 option.name,
180 Builder.typeIdName(option.type_id),180 Builder.typeIdName(option.type_id),
lib/std/special/compiler_rt.zig+20-7
...@@ -10,13 +10,19 @@ comptime {...@@ -10,13 +10,19 @@ comptime {
10 const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong;10 const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong;
1111
12 switch (builtin.arch) {12 switch (builtin.arch) {
13 .i386, .x86_64 => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{ .name = "__zig_probe_stack", .linkage = linkage }),13 .i386,
14 .aarch64, .aarch64_be, .aarch64_32 => {14 .x86_64,
15 @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ .name = "__clear_cache", .linkage = linkage });15 => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{
16 },16 .name = "__zig_probe_stack",
17 .linkage = linkage,
18 }),
19
17 else => {},20 else => {},
18 }21 }
1922
23 // __clear_cache manages its own logic about whether to be exported or not.
24 _ = @import("compiler_rt/clear_cache.zig").clear_cache;
25
20 @export(@import("compiler_rt/compareXf2.zig").__lesf2, .{ .name = "__lesf2", .linkage = linkage });26 @export(@import("compiler_rt/compareXf2.zig").__lesf2, .{ .name = "__lesf2", .linkage = linkage });
21 @export(@import("compiler_rt/compareXf2.zig").__ledf2, .{ .name = "__ledf2", .linkage = linkage });27 @export(@import("compiler_rt/compareXf2.zig").__ledf2, .{ .name = "__ledf2", .linkage = linkage });
22 @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__letf2", .linkage = linkage });28 @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__letf2", .linkage = linkage });
...@@ -69,9 +75,12 @@ comptime {...@@ -69,9 +75,12 @@ comptime {
69 @export(@import("compiler_rt/divdf3.zig").__divdf3, .{ .name = "__divdf3", .linkage = linkage });75 @export(@import("compiler_rt/divdf3.zig").__divdf3, .{ .name = "__divdf3", .linkage = linkage });
70 @export(@import("compiler_rt/divtf3.zig").__divtf3, .{ .name = "__divtf3", .linkage = linkage });76 @export(@import("compiler_rt/divtf3.zig").__divtf3, .{ .name = "__divtf3", .linkage = linkage });
7177
72 @export(@import("compiler_rt/ashlti3.zig").__ashlti3, .{ .name = "__ashlti3", .linkage = linkage });78 @export(@import("compiler_rt/shift.zig").__ashldi3, .{ .name = "__ashldi3", .linkage = linkage });
73 @export(@import("compiler_rt/lshrti3.zig").__lshrti3, .{ .name = "__lshrti3", .linkage = linkage });79 @export(@import("compiler_rt/shift.zig").__ashlti3, .{ .name = "__ashlti3", .linkage = linkage });
74 @export(@import("compiler_rt/ashrti3.zig").__ashrti3, .{ .name = "__ashrti3", .linkage = linkage });80 @export(@import("compiler_rt/shift.zig").__ashrdi3, .{ .name = "__ashrdi3", .linkage = linkage });
81 @export(@import("compiler_rt/shift.zig").__ashrti3, .{ .name = "__ashrti3", .linkage = linkage });
82 @export(@import("compiler_rt/shift.zig").__lshrdi3, .{ .name = "__lshrdi3", .linkage = linkage });
83 @export(@import("compiler_rt/shift.zig").__lshrti3, .{ .name = "__lshrti3", .linkage = linkage });
7584
76 @export(@import("compiler_rt/floatsiXf.zig").__floatsidf, .{ .name = "__floatsidf", .linkage = linkage });85 @export(@import("compiler_rt/floatsiXf.zig").__floatsidf, .{ .name = "__floatsidf", .linkage = linkage });
77 @export(@import("compiler_rt/floatsiXf.zig").__floatsisf, .{ .name = "__floatsisf", .linkage = linkage });86 @export(@import("compiler_rt/floatsiXf.zig").__floatsisf, .{ .name = "__floatsisf", .linkage = linkage });
...@@ -229,6 +238,10 @@ comptime {...@@ -229,6 +238,10 @@ comptime {
229 @export(@import("compiler_rt/divsf3.zig").__aeabi_fdiv, .{ .name = "__aeabi_fdiv", .linkage = linkage });238 @export(@import("compiler_rt/divsf3.zig").__aeabi_fdiv, .{ .name = "__aeabi_fdiv", .linkage = linkage });
230 @export(@import("compiler_rt/divdf3.zig").__aeabi_ddiv, .{ .name = "__aeabi_ddiv", .linkage = linkage });239 @export(@import("compiler_rt/divdf3.zig").__aeabi_ddiv, .{ .name = "__aeabi_ddiv", .linkage = linkage });
231240
241 @export(@import("compiler_rt/shift.zig").__aeabi_llsl, .{ .name = "__aeabi_llsl", .linkage = linkage });
242 @export(@import("compiler_rt/shift.zig").__aeabi_lasr, .{ .name = "__aeabi_lasr", .linkage = linkage });
243 @export(@import("compiler_rt/shift.zig").__aeabi_llsr, .{ .name = "__aeabi_llsr", .linkage = linkage });
244
232 @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpeq, .{ .name = "__aeabi_fcmpeq", .linkage = linkage });245 @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpeq, .{ .name = "__aeabi_fcmpeq", .linkage = linkage });
233 @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmplt, .{ .name = "__aeabi_fcmplt", .linkage = linkage });246 @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmplt, .{ .name = "__aeabi_fcmplt", .linkage = linkage });
234 @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmple, .{ .name = "__aeabi_fcmple", .linkage = linkage });247 @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmple, .{ .name = "__aeabi_fcmple", .linkage = linkage });
lib/std/special/compiler_rt/ashldi3_test.zig created+32
...@@ -0,0 +1,32 @@
1const __ashldi3 = @import("shift.zig").__ashldi3;
2const testing = @import("std").testing;
3
4fn test__ashldi3(a: i64, b: i32, expected: u64) void {
5 const x = __ashldi3(a, b);
6 testing.expectEqual(@bitCast(i64, expected), x);
7}
8
9test "ashldi3" {
10 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 0, 0x123456789ABCDEF);
11 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 1, 0x2468ACF13579BDE);
12 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 2, 0x48D159E26AF37BC);
13 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 3, 0x91A2B3C4D5E6F78);
14 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 4, 0x123456789ABCDEF0);
15
16 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 28, 0x789ABCDEF0000000);
17 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 29, 0xF13579BDE0000000);
18 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 30, 0xE26AF37BC0000000);
19 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 31, 0xC4D5E6F780000000);
20
21 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 32, 0x89ABCDEF00000000);
22
23 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 33, 0x13579BDE00000000);
24 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 34, 0x26AF37BC00000000);
25 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 35, 0x4D5E6F7800000000);
26 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 36, 0x9ABCDEF000000000);
27
28 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 60, 0xF000000000000000);
29 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 61, 0xE000000000000000);
30 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 62, 0xC000000000000000);
31 test__ashldi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 63, 0x8000000000000000);
32}
lib/std/special/compiler_rt/ashlti3.zig deleted-41
...@@ -1,41 +0,0 @@
1const builtin = @import("builtin");
2const compiler_rt = @import("../compiler_rt.zig");
3
4pub fn __ashlti3(a: i128, b: i32) callconv(.C) i128 {
5 var input = twords{ .all = a };
6 var result: twords = undefined;
7
8 if (b > 63) {
9 // 64 <= b < 128
10 result.s.low = 0;
11 result.s.high = input.s.low << @intCast(u6, b - 64);
12 } else {
13 // 0 <= b < 64
14 if (b == 0) return a;
15 result.s.low = input.s.low << @intCast(u6, b);
16 result.s.high = input.s.low >> @intCast(u6, 64 - b);
17 result.s.high |= input.s.high << @intCast(u6, b);
18 }
19
20 return result.all;
21}
22
23const twords = extern union {
24 all: i128,
25 s: S,
26
27 const S = if (builtin.endian == .Little)
28 struct {
29 low: u64,
30 high: u64,
31 }
32 else
33 struct {
34 high: u64,
35 low: u64,
36 };
37};
38
39test "import ashlti3" {
40 _ = @import("ashlti3_test.zig");
41}
lib/std/special/compiler_rt/ashlti3_test.zig+2-2
...@@ -1,9 +1,9 @@...@@ -1,9 +1,9 @@
1const __ashlti3 = @import("ashlti3.zig").__ashlti3;1const __ashlti3 = @import("shift.zig").__ashlti3;
2const testing = @import("std").testing;2const testing = @import("std").testing;
33
4fn test__ashlti3(a: i128, b: i32, expected: i128) void {4fn test__ashlti3(a: i128, b: i32, expected: i128) void {
5 const x = __ashlti3(a, b);5 const x = __ashlti3(a, b);
6 testing.expect(x == expected);6 testing.expectEqual(expected, x);
7}7}
88
9test "ashlti3" {9test "ashlti3" {
lib/std/special/compiler_rt/ashrdi3_test.zig created+55
...@@ -0,0 +1,55 @@
1const __ashrdi3 = @import("shift.zig").__ashrdi3;
2const testing = @import("std").testing;
3
4fn test__ashrdi3(a: i64, b: i32, expected: u64) void {
5 const x = __ashrdi3(a, b);
6 testing.expectEqual(@bitCast(i64, expected), x);
7}
8
9test "ashrdi3" {
10 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 0, 0x123456789ABCDEF);
11 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 1, 0x91A2B3C4D5E6F7);
12 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 2, 0x48D159E26AF37B);
13 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 3, 0x2468ACF13579BD);
14 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 4, 0x123456789ABCDE);
15
16 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 28, 0x12345678);
17 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 29, 0x91A2B3C);
18 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 30, 0x48D159E);
19 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 31, 0x2468ACF);
20
21 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 32, 0x1234567);
22
23 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 33, 0x91A2B3);
24 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 34, 0x48D159);
25 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 35, 0x2468AC);
26 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 36, 0x123456);
27
28 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 60, 0);
29 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 61, 0);
30 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 62, 0);
31 test__ashrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 63, 0);
32
33 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 0, 0xFEDCBA9876543210);
34 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 1, 0xFF6E5D4C3B2A1908);
35 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 2, 0xFFB72EA61D950C84);
36 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 3, 0xFFDB97530ECA8642);
37 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 4, 0xFFEDCBA987654321);
38
39 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 28, 0xFFFFFFFFEDCBA987);
40 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 29, 0xFFFFFFFFF6E5D4C3);
41 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 30, 0xFFFFFFFFFB72EA61);
42 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 31, 0xFFFFFFFFFDB97530);
43
44 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 32, 0xFFFFFFFFFEDCBA98);
45
46 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 33, 0xFFFFFFFFFF6E5D4C);
47 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 34, 0xFFFFFFFFFFB72EA6);
48 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 35, 0xFFFFFFFFFFDB9753);
49 test__ashrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 36, 0xFFFFFFFFFFEDCBA9);
50
51 test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 60, 0xFFFFFFFFFFFFFFFA);
52 test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 61, 0xFFFFFFFFFFFFFFFD);
53 test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 62, 0xFFFFFFFFFFFFFFFE);
54 test__ashrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 63, 0xFFFFFFFFFFFFFFFF);
55}
lib/std/special/compiler_rt/ashrti3.zig deleted-42
...@@ -1,42 +0,0 @@
1const builtin = @import("builtin");
2const compiler_rt = @import("../compiler_rt.zig");
3
4pub fn __ashrti3(a: i128, b: i32) callconv(.C) i128 {
5 var input = twords{ .all = a };
6 var result: twords = undefined;
7
8 if (b > 63) {
9 // 64 <= b < 128
10 result.s.low = input.s.high >> @intCast(u6, b - 64);
11 result.s.high = input.s.high >> 63;
12 } else {
13 // 0 <= b < 64
14 if (b == 0) return a;
15 result.s.low = input.s.high << @intCast(u6, 64 - b);
16 // Avoid sign-extension here
17 result.s.low |= @bitCast(i64, @bitCast(u64, input.s.low) >> @intCast(u6, b));
18 result.s.high = input.s.high >> @intCast(u6, b);
19 }
20
21 return result.all;
22}
23
24const twords = extern union {
25 all: i128,
26 s: S,
27
28 const S = if (builtin.endian == .Little)
29 struct {
30 low: i64,
31 high: i64,
32 }
33 else
34 struct {
35 high: i64,
36 low: i64,
37 };
38};
39
40test "import ashrti3" {
41 _ = @import("ashrti3_test.zig");
42}
lib/std/special/compiler_rt/ashrti3_test.zig+2-4
...@@ -1,11 +1,9 @@...@@ -1,11 +1,9 @@
1const __ashrti3 = @import("ashrti3.zig").__ashrti3;1const __ashrti3 = @import("shift.zig").__ashrti3;
2const testing = @import("std").testing;2const testing = @import("std").testing;
33
4fn test__ashrti3(a: i128, b: i32, expected: i128) void {4fn test__ashrti3(a: i128, b: i32, expected: i128) void {
5 const x = __ashrti3(a, b);5 const x = __ashrti3(a, b);
6 // @import("std").debug.warn("got 0x{x}\nexp 0x{x}\n", .{@truncate(u64,6 testing.expectEqual(expected, x);
7 // @bitCast(u128, x) >> 64), @truncate(u64, @bitCast(u128, expected)) >> 64});
8 testing.expect(x == expected);
9}7}
108
11test "ashrti3" {9test "ashrti3" {
lib/std/special/compiler_rt/clear_cache.zig+53-37
...@@ -26,6 +26,10 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {...@@ -26,6 +26,10 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
26 .mips, .mipsel, .mips64, .mips64el => true,26 .mips, .mipsel, .mips64, .mips64el => true,
27 else => false,27 else => false,
28 };28 };
29 const riscv = switch (arch) {
30 .riscv32, .riscv64 => true,
31 else => false,
32 };
29 const powerpc64 = switch (arch) {33 const powerpc64 = switch (arch) {
30 .powerpc64, .powerpc64le => true,34 .powerpc64, .powerpc64le => true,
31 else => false,35 else => false,
...@@ -41,45 +45,42 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {...@@ -41,45 +45,42 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
41 if (x86) {45 if (x86) {
42 // Intel processors have a unified instruction and data cache46 // Intel processors have a unified instruction and data cache
43 // so there is nothing to do47 // so there is nothing to do
48 exportIt();
44 } else if (os == .windows and (arm32 or arm64)) {49 } else if (os == .windows and (arm32 or arm64)) {
45 @compileError("TODO");50 // TODO
46 // FlushInstructionCache(GetCurrentProcess(), start, end - start);51 // FlushInstructionCache(GetCurrentProcess(), start, end - start);
52 // exportIt();
47 } else if (arm32 and !apple) {53 } else if (arm32 and !apple) {
48 @compileError("TODO");54 switch (os) {
49 //#if defined(__FreeBSD__) || defined(__NetBSD__)55 .freebsd, .netbsd => {
50 // struct arm_sync_icache_args arg;56 var arg = arm_sync_icache_args{
51 //57 .addr = start,
52 // arg.addr = (uintptr_t)start;58 .len = end - start,
53 // arg.len = (uintptr_t)end - (uintptr_t)start;59 };
54 //60 const result = sysarch(ARM_SYNC_ICACHE, @ptrToInt(&arg));
55 // sysarch(ARM_SYNC_ICACHE, &arg);61 std.debug.assert(result == 0);
56 //#elif defined(__linux__)62 exportIt();
57 //// We used to include asm/unistd.h for the __ARM_NR_cacheflush define, but63 },
58 //// it also brought many other unused defines, as well as a dependency on64 .linux => {
59 //// kernel headers to be installed.65 const result = std.os.linux.syscall3(.cacheflush, start, end, 0);
60 ////66 std.debug.assert(result == 0);
61 //// This value is stable at least since Linux 3.13 and should remain so for67 exportIt();
62 //// compatibility reasons, warranting it's re-definition here.68 },
63 //#define __ARM_NR_cacheflush 0x0f000269 else => {},
64 // register int start_reg __asm("r0") = (int)(intptr_t)start;70 }
65 // const register int end_reg __asm("r1") = (int)(intptr_t)end;
66 // const register int flags __asm("r2") = 0;
67 // const register int syscall_nr __asm("r7") = __ARM_NR_cacheflush;
68 // __asm __volatile("svc 0x0"
69 // : "=r"(start_reg)
70 // : "r"(syscall_nr), "r"(start_reg), "r"(end_reg), "r"(flags));
71 // assert(start_reg == 0 && "Cache flush syscall failed.");
72 //#else
73 // compilerrt_abort();
74 //#endif
75 } else if (os == .linux and mips) {71 } else if (os == .linux and mips) {
76 @compileError("TODO");72 const flags = 3; // ICACHE | DCACHE
77 //const uintptr_t start_int = (uintptr_t)start;73 const result = std.os.linux.syscall3(.cacheflush, start, end - start, flags);
78 //const uintptr_t end_int = (uintptr_t)end;74 std.debug.assert(result == 0);
79 //syscall(__NR_cacheflush, start, (end_int - start_int), BCACHE);75 exportIt();
80 } else if (mips and os == .openbsd) {76 } else if (mips and os == .openbsd) {
81 @compileError("TODO");77 // TODO
82 //cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE);78 //cacheflush(start, (uintptr_t)end - (uintptr_t)start, BCACHE);
79 // exportIt();
80 } else if (os == .linux and riscv) {
81 const result = std.os.linux.syscall3(.riscv_flush_icache, start, end - start, 0);
82 std.debug.assert(result == 0);
83 exportIt();
83 } else if (arm64 and !apple) {84 } else if (arm64 and !apple) {
84 // Get Cache Type Info.85 // Get Cache Type Info.
85 // TODO memoize this?86 // TODO memoize this?
...@@ -118,8 +119,9 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {...@@ -118,8 +119,9 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
118 }119 }
119 }120 }
120 asm volatile ("isb sy");121 asm volatile ("isb sy");
122 exportIt();
121 } else if (powerpc64) {123 } else if (powerpc64) {
122 @compileError("TODO");124 // TODO
123 //const size_t line_size = 32;125 //const size_t line_size = 32;
124 //const size_t len = (uintptr_t)end - (uintptr_t)start;126 //const size_t len = (uintptr_t)end - (uintptr_t)start;
125 //127 //
...@@ -134,8 +136,9 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {...@@ -134,8 +136,9 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
134 //for (uintptr_t line = start_line; line < end_line; line += line_size)136 //for (uintptr_t line = start_line; line < end_line; line += line_size)
135 // __asm__ volatile("icbi 0, %0" : : "r"(line));137 // __asm__ volatile("icbi 0, %0" : : "r"(line));
136 //__asm__ volatile("isync");138 //__asm__ volatile("isync");
139 // exportIt();
137 } else if (sparc) {140 } else if (sparc) {
138 @compileError("TODO");141 // TODO
139 //const size_t dword_size = 8;142 //const size_t dword_size = 8;
140 //const size_t len = (uintptr_t)end - (uintptr_t)start;143 //const size_t len = (uintptr_t)end - (uintptr_t)start;
141 //144 //
...@@ -145,13 +148,26 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {...@@ -145,13 +148,26 @@ pub fn clear_cache(start: usize, end: usize) callconv(.C) void {
145 //148 //
146 //for (uintptr_t dword = start_dword; dword < end_dword; dword += dword_size)149 //for (uintptr_t dword = start_dword; dword < end_dword; dword += dword_size)
147 // __asm__ volatile("flush %0" : : "r"(dword));150 // __asm__ volatile("flush %0" : : "r"(dword));
151 // exportIt();
148 } else if (apple) {152 } else if (apple) {
149 // On Darwin, sys_icache_invalidate() provides this functionality153 // On Darwin, sys_icache_invalidate() provides this functionality
150 sys_icache_invalidate(start, end - start);154 sys_icache_invalidate(start, end - start);
151 } else {155 exportIt();
152 @compileError("no __clear_cache implementation available for this target");
153 }156 }
154}157}
155158
159const linkage = if (std.builtin.is_test) std.builtin.GlobalLinkage.Internal else std.builtin.GlobalLinkage.Weak;
160
161fn exportIt() void {
162 @export(clear_cache, .{ .name = "__clear_cache", .linkage = linkage });
163}
164
156// Darwin-only165// Darwin-only
157extern fn sys_icache_invalidate(start: usize, len: usize) void;166extern fn sys_icache_invalidate(start: usize, len: usize) void;
167// BSD-only
168const arm_sync_icache_args = extern struct {
169 addr: usize, // Virtual start address
170 len: usize, // Region size
171};
172const ARM_SYNC_ICACHE = 0;
173extern "c" fn sysarch(number: i32, args: usize) i32;
lib/std/special/compiler_rt/lshrdi3_test.zig created+55
...@@ -0,0 +1,55 @@
1const __lshrdi3 = @import("shift.zig").__lshrdi3;
2const testing = @import("std").testing;
3
4fn test__lshrdi3(a: i64, b: i32, expected: u64) void {
5 const x = __lshrdi3(a, b);
6 testing.expectEqual(@bitCast(i64, expected), x);
7}
8
9test "lshrdi3" {
10 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 0, 0x123456789ABCDEF);
11 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 1, 0x91A2B3C4D5E6F7);
12 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 2, 0x48D159E26AF37B);
13 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 3, 0x2468ACF13579BD);
14 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 4, 0x123456789ABCDE);
15
16 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 28, 0x12345678);
17 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 29, 0x91A2B3C);
18 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 30, 0x48D159E);
19 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 31, 0x2468ACF);
20
21 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 32, 0x1234567);
22
23 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 33, 0x91A2B3);
24 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 34, 0x48D159);
25 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 35, 0x2468AC);
26 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 36, 0x123456);
27
28 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 60, 0);
29 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 61, 0);
30 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 62, 0);
31 test__lshrdi3(@bitCast(i64, @as(u64, 0x0123456789ABCDEF)), 63, 0);
32
33 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 0, 0xFEDCBA9876543210);
34 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 1, 0x7F6E5D4C3B2A1908);
35 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 2, 0x3FB72EA61D950C84);
36 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 3, 0x1FDB97530ECA8642);
37 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 4, 0xFEDCBA987654321);
38
39 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 28, 0xFEDCBA987);
40 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 29, 0x7F6E5D4C3);
41 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 30, 0x3FB72EA61);
42 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 31, 0x1FDB97530);
43
44 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 32, 0xFEDCBA98);
45
46 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 33, 0x7F6E5D4C);
47 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 34, 0x3FB72EA6);
48 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 35, 0x1FDB9753);
49 test__lshrdi3(@bitCast(i64, @as(u64, 0xFEDCBA9876543210)), 36, 0xFEDCBA9);
50
51 test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 60, 0xA);
52 test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 61, 0x5);
53 test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 62, 0x2);
54 test__lshrdi3(@bitCast(i64, @as(u64, 0xAEDCBA9876543210)), 63, 0x1);
55}
lib/std/special/compiler_rt/lshrti3.zig deleted-41
...@@ -1,41 +0,0 @@
1const builtin = @import("builtin");
2const compiler_rt = @import("../compiler_rt.zig");
3
4pub fn __lshrti3(a: i128, b: i32) callconv(.C) i128 {
5 var input = twords{ .all = a };
6 var result: twords = undefined;
7
8 if (b > 63) {
9 // 64 <= b < 128
10 result.s.low = input.s.high >> @intCast(u6, b - 64);
11 result.s.high = 0;
12 } else {
13 // 0 <= b < 64
14 if (b == 0) return a;
15 result.s.low = input.s.high << @intCast(u6, 64 - b);
16 result.s.low |= input.s.low >> @intCast(u6, b);
17 result.s.high = input.s.high >> @intCast(u6, b);
18 }
19
20 return result.all;
21}
22
23const twords = extern union {
24 all: i128,
25 s: S,
26
27 const S = if (builtin.endian == .Little)
28 struct {
29 low: u64,
30 high: u64,
31 }
32 else
33 struct {
34 high: u64,
35 low: u64,
36 };
37};
38
39test "import lshrti3" {
40 _ = @import("lshrti3_test.zig");
41}
lib/std/special/compiler_rt/lshrti3_test.zig+2-2
...@@ -1,9 +1,9 @@...@@ -1,9 +1,9 @@
1const __lshrti3 = @import("lshrti3.zig").__lshrti3;1const __lshrti3 = @import("shift.zig").__lshrti3;
2const testing = @import("std").testing;2const testing = @import("std").testing;
33
4fn test__lshrti3(a: i128, b: i32, expected: i128) void {4fn test__lshrti3(a: i128, b: i32, expected: i128) void {
5 const x = __lshrti3(a, b);5 const x = __lshrti3(a, b);
6 testing.expect(x == expected);6 testing.expectEqual(expected, x);
7}7}
88
9test "lshrti3" {9test "lshrti3" {
lib/std/special/compiler_rt/shift.zig created+130
...@@ -0,0 +1,130 @@
1const std = @import("std");
2const builtin = std.builtin;
3const Log2Int = std.math.Log2Int;
4
5fn Dwords(comptime T: type, comptime signed_half: bool) type {
6 return extern union {
7 pub const HalfTU = std.meta.IntType(false, @divExact(T.bit_count, 2));
8 pub const HalfTS = std.meta.IntType(true, @divExact(T.bit_count, 2));
9 pub const HalfT = if (signed_half) HalfTS else HalfTU;
10
11 all: T,
12 s: if (builtin.endian == .Little)
13 struct { low: HalfT, high: HalfT }
14 else
15 struct { high: HalfT, low: HalfT },
16 };
17}
18
19// Arithmetic shift left
20// Precondition: 0 <= b < bits_in_dword
21pub fn ashlXi3(comptime T: type, a: T, b: i32) T {
22 const dwords = Dwords(T, false);
23 const S = Log2Int(dwords.HalfT);
24
25 const input = dwords{ .all = a };
26 var output: dwords = undefined;
27
28 if (b >= dwords.HalfT.bit_count) {
29 output.s.low = 0;
30 output.s.high = input.s.low << @intCast(S, b - dwords.HalfT.bit_count);
31 } else if (b == 0) {
32 return a;
33 } else {
34 output.s.low = input.s.low << @intCast(S, b);
35 output.s.high = input.s.high << @intCast(S, b);
36 output.s.high |= input.s.low >> @intCast(S, dwords.HalfT.bit_count - b);
37 }
38
39 return output.all;
40}
41
42// Arithmetic shift right
43// Precondition: 0 <= b < T.bit_count
44pub fn ashrXi3(comptime T: type, a: T, b: i32) T {
45 const dwords = Dwords(T, true);
46 const S = Log2Int(dwords.HalfT);
47
48 const input = dwords{ .all = a };
49 var output: dwords = undefined;
50
51 if (b >= dwords.HalfT.bit_count) {
52 output.s.high = input.s.high >> (dwords.HalfT.bit_count - 1);
53 output.s.low = input.s.high >> @intCast(S, b - dwords.HalfT.bit_count);
54 } else if (b == 0) {
55 return a;
56 } else {
57 output.s.high = input.s.high >> @intCast(S, b);
58 output.s.low = input.s.high << @intCast(S, dwords.HalfT.bit_count - b);
59 // Avoid sign-extension here
60 output.s.low |= @bitCast(
61 dwords.HalfT,
62 @bitCast(dwords.HalfTU, input.s.low) >> @intCast(S, b),
63 );
64 }
65
66 return output.all;
67}
68
69// Logical shift right
70// Precondition: 0 <= b < T.bit_count
71pub fn lshrXi3(comptime T: type, a: T, b: i32) T {
72 const dwords = Dwords(T, false);
73 const S = Log2Int(dwords.HalfT);
74
75 const input = dwords{ .all = a };
76 var output: dwords = undefined;
77
78 if (b >= dwords.HalfT.bit_count) {
79 output.s.high = 0;
80 output.s.low = input.s.high >> @intCast(S, b - dwords.HalfT.bit_count);
81 } else if (b == 0) {
82 return a;
83 } else {
84 output.s.high = input.s.high >> @intCast(S, b);
85 output.s.low = input.s.high << @intCast(S, dwords.HalfT.bit_count - b);
86 output.s.low |= input.s.low >> @intCast(S, b);
87 }
88
89 return output.all;
90}
91
92pub fn __ashldi3(a: i64, b: i32) callconv(.C) i64 {
93 return @call(.{ .modifier = .always_inline }, ashlXi3, .{ i64, a, b });
94}
95pub fn __ashlti3(a: i128, b: i32) callconv(.C) i128 {
96 return @call(.{ .modifier = .always_inline }, ashlXi3, .{ i128, a, b });
97}
98pub fn __ashrdi3(a: i64, b: i32) callconv(.C) i64 {
99 return @call(.{ .modifier = .always_inline }, ashrXi3, .{ i64, a, b });
100}
101pub fn __ashrti3(a: i128, b: i32) callconv(.C) i128 {
102 return @call(.{ .modifier = .always_inline }, ashrXi3, .{ i128, a, b });
103}
104pub fn __lshrdi3(a: i64, b: i32) callconv(.C) i64 {
105 return @call(.{ .modifier = .always_inline }, lshrXi3, .{ i64, a, b });
106}
107pub fn __lshrti3(a: i128, b: i32) callconv(.C) i128 {
108 return @call(.{ .modifier = .always_inline }, lshrXi3, .{ i128, a, b });
109}
110
111pub fn __aeabi_llsl(a: i64, b: i32) callconv(.AAPCS) i64 {
112 return __ashldi3(a, b);
113}
114pub fn __aeabi_lasr(a: i64, b: i32) callconv(.AAPCS) i64 {
115 return __ashrdi3(a, b);
116}
117pub fn __aeabi_llsr(a: i64, b: i32) callconv(.AAPCS) i64 {
118 return __lshrdi3(a, b);
119}
120
121test "" {
122 _ = @import("ashrdi3_test.zig");
123 _ = @import("ashrti3_test.zig");
124
125 _ = @import("ashldi3_test.zig");
126 _ = @import("ashlti3_test.zig");
127
128 _ = @import("lshrdi3_test.zig");
129 _ = @import("lshrti3_test.zig");
130}
lib/std/std.zig+1-1
...@@ -1,10 +1,10 @@...@@ -1,10 +1,10 @@
1pub const AlignedArrayList = @import("array_list.zig").AlignedArrayList;1pub const AlignedArrayList = @import("array_list.zig").AlignedArrayList;
2pub const ArrayList = @import("array_list.zig").ArrayList;2pub const ArrayList = @import("array_list.zig").ArrayList;
3pub const ArrayListSentineled = @import("array_list_sentineled.zig").ArrayListSentineled;
3pub const AutoHashMap = @import("hash_map.zig").AutoHashMap;4pub const AutoHashMap = @import("hash_map.zig").AutoHashMap;
4pub const BloomFilter = @import("bloom_filter.zig").BloomFilter;5pub const BloomFilter = @import("bloom_filter.zig").BloomFilter;
5pub const BufMap = @import("buf_map.zig").BufMap;6pub const BufMap = @import("buf_map.zig").BufMap;
6pub const BufSet = @import("buf_set.zig").BufSet;7pub const BufSet = @import("buf_set.zig").BufSet;
7pub const Buffer = @import("buffer.zig").Buffer;
8pub const ChildProcess = @import("child_process.zig").ChildProcess;8pub const ChildProcess = @import("child_process.zig").ChildProcess;
9pub const DynLib = @import("dynamic_library.zig").DynLib;9pub const DynLib = @import("dynamic_library.zig").DynLib;
10pub const HashMap = @import("hash_map.zig").HashMap;10pub const HashMap = @import("hash_map.zig").HashMap;
lib/std/target.zig+4-4
...@@ -967,15 +967,15 @@ pub const Target = struct {...@@ -967,15 +967,15 @@ pub const Target = struct {
967967
968 pub const stack_align = 16;968 pub const stack_align = 16;
969969
970 pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 {970 pub fn zigTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
971 return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator);971 return std.zig.CrossTarget.fromTarget(self).zigTriple(allocator);
972 }972 }
973973
974 pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![:0]u8 {974 pub fn linuxTripleSimple(allocator: *mem.Allocator, cpu_arch: Cpu.Arch, os_tag: Os.Tag, abi: Abi) ![]u8 {
975 return std.fmt.allocPrint0(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });975 return std.fmt.allocPrint(allocator, "{}-{}-{}", .{ @tagName(cpu_arch), @tagName(os_tag), @tagName(abi) });
976 }976 }
977977
978 pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![:0]u8 {978 pub fn linuxTriple(self: Target, allocator: *mem.Allocator) ![]u8 {
979 return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi);979 return linuxTripleSimple(allocator, self.cpu.arch, self.os.tag, self.abi);
980 }980 }
981981
lib/std/thread.zig+1-1
...@@ -464,7 +464,7 @@ pub const Thread = struct {...@@ -464,7 +464,7 @@ pub const Thread = struct {
464 var count: c_int = undefined;464 var count: c_int = undefined;
465 var count_len: usize = @sizeOf(c_int);465 var count_len: usize = @sizeOf(c_int);
466 const name = if (comptime std.Target.current.isDarwin()) "hw.logicalcpu" else "hw.ncpu";466 const name = if (comptime std.Target.current.isDarwin()) "hw.logicalcpu" else "hw.ncpu";
467 os.sysctlbynameC(name, &count, &count_len, null, 0) catch |err| switch (err) {467 os.sysctlbynameZ(name, &count, &count_len, null, 0) catch |err| switch (err) {
468 error.NameTooLong, error.UnknownName => unreachable,468 error.NameTooLong, error.UnknownName => unreachable,
469 else => |e| return e,469 else => |e| return e,
470 };470 };
lib/std/zig/cross_target.zig+18-8
...@@ -495,17 +495,19 @@ pub const CrossTarget = struct {...@@ -495,17 +495,19 @@ pub const CrossTarget = struct {
495 return self.isNativeCpu() and self.isNativeOs() and self.abi == null;495 return self.isNativeCpu() and self.isNativeOs() and self.abi == null;
496 }496 }
497497
498 pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![:0]u8 {498 pub fn zigTriple(self: CrossTarget, allocator: *mem.Allocator) error{OutOfMemory}![]u8 {
499 if (self.isNative()) {499 if (self.isNative()) {
500 return mem.dupeZ(allocator, u8, "native");500 return mem.dupe(allocator, u8, "native");
501 }501 }
502502
503 const arch_name = if (self.cpu_arch) |arch| @tagName(arch) else "native";503 const arch_name = if (self.cpu_arch) |arch| @tagName(arch) else "native";
504 const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native";504 const os_name = if (self.os_tag) |os_tag| @tagName(os_tag) else "native";
505505
506 var result = try std.Buffer.allocPrint(allocator, "{}-{}", .{ arch_name, os_name });506 var result = std.ArrayList(u8).init(allocator);
507 defer result.deinit();507 defer result.deinit();
508508
509 try result.outStream().print("{}-{}", .{ arch_name, os_name });
510
509 // The zig target syntax does not allow specifying a max os version with no min, so511 // The zig target syntax does not allow specifying a max os version with no min, so
510 // if either are present, we need the min.512 // if either are present, we need the min.
511 if (self.os_version_min != null or self.os_version_max != null) {513 if (self.os_version_min != null or self.os_version_max != null) {
...@@ -532,13 +534,13 @@ pub const CrossTarget = struct {...@@ -532,13 +534,13 @@ pub const CrossTarget = struct {
532 return result.toOwnedSlice();534 return result.toOwnedSlice();
533 }535 }
534536
535 pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 {537 pub fn allocDescription(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
536 // TODO is there anything else worthy of the description that is not538 // TODO is there anything else worthy of the description that is not
537 // already captured in the triple?539 // already captured in the triple?
538 return self.zigTriple(allocator);540 return self.zigTriple(allocator);
539 }541 }
540542
541 pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![:0]u8 {543 pub fn linuxTriple(self: CrossTarget, allocator: *mem.Allocator) ![]u8 {
542 return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi());544 return Target.linuxTripleSimple(allocator, self.getCpuArch(), self.getOsTag(), self.getAbi());
543 }545 }
544546
...@@ -549,7 +551,7 @@ pub const CrossTarget = struct {...@@ -549,7 +551,7 @@ pub const CrossTarget = struct {
549 pub const VcpkgLinkage = std.builtin.LinkMode;551 pub const VcpkgLinkage = std.builtin.LinkMode;
550552
551 /// Returned slice must be freed by the caller.553 /// Returned slice must be freed by the caller.
552 pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![:0]u8 {554 pub fn vcpkgTriplet(self: CrossTarget, allocator: *mem.Allocator, linkage: VcpkgLinkage) ![]u8 {
553 const arch = switch (self.getCpuArch()) {555 const arch = switch (self.getCpuArch()) {
554 .i386 => "x86",556 .i386 => "x86",
555 .x86_64 => "x64",557 .x86_64 => "x64",
...@@ -580,7 +582,7 @@ pub const CrossTarget = struct {...@@ -580,7 +582,7 @@ pub const CrossTarget = struct {
580 .Dynamic => "",582 .Dynamic => "",
581 };583 };
582584
583 return std.fmt.allocPrint0(allocator, "{}-{}{}", .{ arch, os, static_suffix });585 return std.fmt.allocPrint(allocator, "{}-{}{}", .{ arch, os, static_suffix });
584 }586 }
585587
586 pub const Executor = union(enum) {588 pub const Executor = union(enum) {
...@@ -763,7 +765,15 @@ test "CrossTarget.parse" {...@@ -763,7 +765,15 @@ test "CrossTarget.parse" {
763765
764 const text = try cross_target.zigTriple(std.testing.allocator);766 const text = try cross_target.zigTriple(std.testing.allocator);
765 defer std.testing.allocator.free(text);767 defer std.testing.allocator.free(text);
766 std.testing.expectEqualSlices(u8, "native-native-gnu.2.1.1", text);768
769 var buf: [256]u8 = undefined;
770 const triple = std.fmt.bufPrint(
771 buf[0..],
772 "native-native-{}.2.1.1",
773 .{@tagName(std.Target.current.abi)},
774 ) catch unreachable;
775
776 std.testing.expectEqualSlices(u8, triple, text);
767 }777 }
768 {778 {
769 const cross_target = try CrossTarget.parse(.{779 const cross_target = try CrossTarget.parse(.{
lib/std/zig/parser_test.zig+30-1
...@@ -373,6 +373,35 @@ test "zig fmt: correctly move doc comments on struct fields" {...@@ -373,6 +373,35 @@ test "zig fmt: correctly move doc comments on struct fields" {
373 );373 );
374}374}
375375
376test "zig fmt: correctly space struct fields with doc comments" {
377 try testTransform(
378 \\pub const S = struct {
379 \\ /// A
380 \\ a: u8,
381 \\ /// B
382 \\ /// B (cont)
383 \\ b: u8,
384 \\
385 \\
386 \\ /// C
387 \\ c: u8,
388 \\};
389 \\
390 ,
391 \\pub const S = struct {
392 \\ /// A
393 \\ a: u8,
394 \\ /// B
395 \\ /// B (cont)
396 \\ b: u8,
397 \\
398 \\ /// C
399 \\ c: u8,
400 \\};
401 \\
402 );
403}
404
376test "zig fmt: doc comments on param decl" {405test "zig fmt: doc comments on param decl" {
377 try testCanonical(406 try testCanonical(
378 \\pub const Allocator = struct {407 \\pub const Allocator = struct {
...@@ -2924,7 +2953,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b...@@ -2924,7 +2953,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
2924 return error.ParseError;2953 return error.ParseError;
2925 }2954 }
29262955
2927 var buffer = try std.Buffer.initSize(allocator, 0);2956 var buffer = std.ArrayList(u8).init(allocator);
2928 errdefer buffer.deinit();2957 errdefer buffer.deinit();
29292958
2930 anything_changed.* = try std.zig.render(allocator, buffer.outStream(), tree);2959 anything_changed.* = try std.zig.render(allocator, buffer.outStream(), tree);
lib/std/zig/render.zig+6-2
...@@ -187,12 +187,16 @@ fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *as...@@ -187,12 +187,16 @@ fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *as
187 const first_token = node.firstToken();187 const first_token = node.firstToken();
188 var prev_token = first_token;188 var prev_token = first_token;
189 if (prev_token == 0) return;189 if (prev_token == 0) return;
190 var newline_threshold: usize = 2;
190 while (tree.tokens.at(prev_token - 1).id == .DocComment) {191 while (tree.tokens.at(prev_token - 1).id == .DocComment) {
192 if (tree.tokenLocation(tree.tokens.at(prev_token - 1).end, prev_token).line == 1) {
193 newline_threshold += 1;
194 }
191 prev_token -= 1;195 prev_token -= 1;
192 }196 }
193 const prev_token_end = tree.tokens.at(prev_token - 1).end;197 const prev_token_end = tree.tokens.at(prev_token - 1).end;
194 const loc = tree.tokenLocation(prev_token_end, first_token);198 const loc = tree.tokenLocation(prev_token_end, first_token);
195 if (loc.line >= 2) {199 if (loc.line >= newline_threshold) {
196 try stream.writeByte('\n');200 try stream.writeByte('\n');
197 start_col.* = 0;201 start_col.* = 0;
198 }202 }
...@@ -1527,7 +1531,7 @@ fn renderExpression(...@@ -1527,7 +1531,7 @@ fn renderExpression(
1527 try renderToken(tree, stream, callconv_rparen, indent, start_col, Space.Space); // )1531 try renderToken(tree, stream, callconv_rparen, indent, start_col, Space.Space); // )
1528 } else if (cc_rewrite_str) |str| {1532 } else if (cc_rewrite_str) |str| {
1529 try stream.writeAll("callconv(");1533 try stream.writeAll("callconv(");
1530 try stream.writeAll(mem.toSliceConst(u8, str));1534 try stream.writeAll(mem.spanZ(str));
1531 try stream.writeAll(") ");1535 try stream.writeAll(") ");
1532 }1536 }
15331537
lib/std/zig/system.zig+17-13
...@@ -119,7 +119,7 @@ pub const NativePaths = struct {...@@ -119,7 +119,7 @@ pub const NativePaths = struct {
119 }119 }
120120
121 fn deinitArray(array: *ArrayList([:0]u8)) void {121 fn deinitArray(array: *ArrayList([:0]u8)) void {
122 for (array.toSlice()) |item| {122 for (array.span()) |item| {
123 array.allocator.free(item);123 array.allocator.free(item);
124 }124 }
125 array.deinit();125 array.deinit();
...@@ -201,7 +201,7 @@ pub const NativeTargetInfo = struct {...@@ -201,7 +201,7 @@ pub const NativeTargetInfo = struct {
201 switch (Target.current.os.tag) {201 switch (Target.current.os.tag) {
202 .linux => {202 .linux => {
203 const uts = std.os.uname();203 const uts = std.os.uname();
204 const release = mem.toSliceConst(u8, &uts.release);204 const release = mem.spanZ(&uts.release);
205 // The release field may have several other fields after the205 // The release field may have several other fields after the
206 // kernel version206 // kernel version
207 const kernel_version = if (mem.indexOfScalar(u8, release, '-')) |pos|207 const kernel_version = if (mem.indexOfScalar(u8, release, '-')) |pos|
...@@ -265,7 +265,7 @@ pub const NativeTargetInfo = struct {...@@ -265,7 +265,7 @@ pub const NativeTargetInfo = struct {
265 // The osproductversion sysctl was introduced first with265 // The osproductversion sysctl was introduced first with
266 // High Sierra, thankfully that's also the baseline that Zig266 // High Sierra, thankfully that's also the baseline that Zig
267 // supports267 // supports
268 std.os.sysctlbynameC(268 std.os.sysctlbynameZ(
269 "kern.osproductversion",269 "kern.osproductversion",
270 &product_version,270 &product_version,
271 &size,271 &size,
...@@ -460,7 +460,7 @@ pub const NativeTargetInfo = struct {...@@ -460,7 +460,7 @@ pub const NativeTargetInfo = struct {
460 return result;460 return result;
461 }461 }
462462
463 const env_file = std.fs.openFileAbsoluteC("/usr/bin/env", .{}) catch |err| switch (err) {463 const env_file = std.fs.openFileAbsoluteZ("/usr/bin/env", .{}) catch |err| switch (err) {
464 error.NoSpaceLeft => unreachable,464 error.NoSpaceLeft => unreachable,
465 error.NameTooLong => unreachable,465 error.NameTooLong => unreachable,
466 error.PathAlreadyExists => unreachable,466 error.PathAlreadyExists => unreachable,
...@@ -515,7 +515,7 @@ pub const NativeTargetInfo = struct {...@@ -515,7 +515,7 @@ pub const NativeTargetInfo = struct {
515515
516 fn glibcVerFromSO(so_path: [:0]const u8) !std.builtin.Version {516 fn glibcVerFromSO(so_path: [:0]const u8) !std.builtin.Version {
517 var link_buf: [std.os.PATH_MAX]u8 = undefined;517 var link_buf: [std.os.PATH_MAX]u8 = undefined;
518 const link_name = std.os.readlinkC(so_path.ptr, &link_buf) catch |err| switch (err) {518 const link_name = std.os.readlinkZ(so_path.ptr, &link_buf) catch |err| switch (err) {
519 error.AccessDenied => return error.GnuLibCVersionUnavailable,519 error.AccessDenied => return error.GnuLibCVersionUnavailable,
520 error.FileSystem => return error.FileSystem,520 error.FileSystem => return error.FileSystem,
521 error.SymLinkLoop => return error.SymLinkLoop,521 error.SymLinkLoop => return error.SymLinkLoop,
...@@ -625,9 +625,10 @@ pub const NativeTargetInfo = struct {...@@ -625,9 +625,10 @@ pub const NativeTargetInfo = struct {
625 const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);625 const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);
626 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);626 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);
627 if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong;627 if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong;
628 _ = try preadMin(file, result.dynamic_linker.buffer[0..p_filesz], p_offset, p_filesz);628 const filesz = @intCast(usize, p_filesz);
629 // PT_INTERP includes a null byte in p_filesz.629 _ = try preadMin(file, result.dynamic_linker.buffer[0..filesz], p_offset, filesz);
630 const len = p_filesz - 1;630 // PT_INTERP includes a null byte in filesz.
631 const len = filesz - 1;
631 // dynamic_linker.max_byte is "max", not "len".632 // dynamic_linker.max_byte is "max", not "len".
632 // We know it will fit in u8 because we check against dynamic_linker.buffer.len above.633 // We know it will fit in u8 because we check against dynamic_linker.buffer.len above.
633 result.dynamic_linker.max_byte = @intCast(u8, len - 1);634 result.dynamic_linker.max_byte = @intCast(u8, len - 1);
...@@ -648,7 +649,7 @@ pub const NativeTargetInfo = struct {...@@ -648,7 +649,7 @@ pub const NativeTargetInfo = struct {
648 {649 {
649 var dyn_off = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);650 var dyn_off = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);
650 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);651 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);
651 const dyn_size: u64 = if (is_64) @sizeOf(elf.Elf64_Dyn) else @sizeOf(elf.Elf32_Dyn);652 const dyn_size: usize = if (is_64) @sizeOf(elf.Elf64_Dyn) else @sizeOf(elf.Elf32_Dyn);
652 const dyn_num = p_filesz / dyn_size;653 const dyn_num = p_filesz / dyn_size;
653 var dyn_buf: [16 * @sizeOf(elf.Elf64_Dyn)]u8 align(@alignOf(elf.Elf64_Dyn)) = undefined;654 var dyn_buf: [16 * @sizeOf(elf.Elf64_Dyn)]u8 align(@alignOf(elf.Elf64_Dyn)) = undefined;
654 var dyn_i: usize = 0;655 var dyn_i: usize = 0;
...@@ -739,7 +740,7 @@ pub const NativeTargetInfo = struct {...@@ -739,7 +740,7 @@ pub const NativeTargetInfo = struct {
739 );740 );
740 const sh_name_off = elfInt(is_64, need_bswap, sh32.sh_name, sh64.sh_name);741 const sh_name_off = elfInt(is_64, need_bswap, sh32.sh_name, sh64.sh_name);
741 // TODO this pointer cast should not be necessary742 // TODO this pointer cast should not be necessary
742 const sh_name = mem.toSliceConst(u8, @ptrCast([*:0]u8, shstrtab[sh_name_off..].ptr));743 const sh_name = mem.spanZ(@ptrCast([*:0]u8, shstrtab[sh_name_off..].ptr));
743 if (mem.eql(u8, sh_name, ".dynstr")) {744 if (mem.eql(u8, sh_name, ".dynstr")) {
744 break :find_dyn_str .{745 break :find_dyn_str .{
745 .offset = elfInt(is_64, need_bswap, sh32.sh_offset, sh64.sh_offset),746 .offset = elfInt(is_64, need_bswap, sh32.sh_offset, sh64.sh_offset),
...@@ -754,7 +755,10 @@ pub const NativeTargetInfo = struct {...@@ -754,7 +755,10 @@ pub const NativeTargetInfo = struct {
754 const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, shstrtab_len);755 const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, shstrtab_len);
755 const strtab = strtab_buf[0..strtab_read_len];756 const strtab = strtab_buf[0..strtab_read_len];
756 // TODO this pointer cast should not be necessary757 // TODO this pointer cast should not be necessary
757 const rpath_list = mem.toSliceConst(u8, @ptrCast([*:0]u8, strtab[rpoff..].ptr));758 const rpoff_usize = std.math.cast(usize, rpoff) catch |err| switch (err) {
759 error.Overflow => return error.InvalidElfFile,
760 };
761 const rpath_list = mem.spanZ(@ptrCast([*:0]u8, strtab[rpoff_usize..].ptr));
758 var it = mem.tokenize(rpath_list, ":");762 var it = mem.tokenize(rpath_list, ":");
759 while (it.next()) |rpath| {763 while (it.next()) |rpath| {
760 var dir = fs.cwd().openDir(rpath, .{}) catch |err| switch (err) {764 var dir = fs.cwd().openDir(rpath, .{}) catch |err| switch (err) {
...@@ -779,7 +783,7 @@ pub const NativeTargetInfo = struct {...@@ -779,7 +783,7 @@ pub const NativeTargetInfo = struct {
779 defer dir.close();783 defer dir.close();
780784
781 var link_buf: [std.os.PATH_MAX]u8 = undefined;785 var link_buf: [std.os.PATH_MAX]u8 = undefined;
782 const link_name = std.os.readlinkatC(786 const link_name = std.os.readlinkatZ(
783 dir.fd,787 dir.fd,
784 glibc_so_basename,788 glibc_so_basename,
785 &link_buf,789 &link_buf,
...@@ -814,7 +818,7 @@ pub const NativeTargetInfo = struct {...@@ -814,7 +818,7 @@ pub const NativeTargetInfo = struct {
814 }818 }
815819
816 fn preadMin(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize {820 fn preadMin(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize {
817 var i: u64 = 0;821 var i: usize = 0;
818 while (i < min_read_len) {822 while (i < min_read_len) {
819 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {823 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {
820 error.OperationAborted => unreachable, // Windows-only824 error.OperationAborted => unreachable, // Windows-only
src-self-hosted/clang_options_data.zig+85-50
...@@ -7,7 +7,7 @@ flagpd1("CC"),...@@ -7,7 +7,7 @@ flagpd1("CC"),
7.{7.{
8 .name = "E",8 .name = "E",
9 .syntax = .flag,9 .syntax = .flag,
10 .zig_equivalent = .preprocess,10 .zig_equivalent = .pp_or_asm,
11 .pd1 = true,11 .pd1 = true,
12 .pd2 = false,12 .pd2 = false,
13 .psl = false,13 .psl = false,
...@@ -26,12 +26,26 @@ flagpd1("H"),...@@ -26,12 +26,26 @@ flagpd1("H"),
26},26},
27flagpd1("I-"),27flagpd1("I-"),
28flagpd1("M"),28flagpd1("M"),
29flagpd1("MD"),29.{
30 .name = "MD",
31 .syntax = .flag,
32 .zig_equivalent = .dep_file,
33 .pd1 = true,
34 .pd2 = false,
35 .psl = false,
36},
30flagpd1("MG"),37flagpd1("MG"),
31flagpd1("MM"),38flagpd1("MM"),
32flagpd1("MMD"),39flagpd1("MMD"),
33flagpd1("MP"),40flagpd1("MP"),
34flagpd1("MV"),41.{
42 .name = "MV",
43 .syntax = .flag,
44 .zig_equivalent = .dep_file,
45 .pd1 = true,
46 .pd2 = false,
47 .psl = false,
48},
35flagpd1("Mach"),49flagpd1("Mach"),
36flagpd1("O0"),50flagpd1("O0"),
37flagpd1("O4"),51flagpd1("O4"),
...@@ -53,7 +67,7 @@ flagpd1("Qy"),...@@ -53,7 +67,7 @@ flagpd1("Qy"),
53.{67.{
54 .name = "S",68 .name = "S",
55 .syntax = .flag,69 .syntax = .flag,
56 .zig_equivalent = .driver_punt,70 .zig_equivalent = .pp_or_asm,
57 .pd1 = true,71 .pd1 = true,
58 .pd2 = false,72 .pd2 = false,
59 .psl = false,73 .psl = false,
...@@ -154,7 +168,7 @@ sepd1("Zlinker-input"),...@@ -154,7 +168,7 @@ sepd1("Zlinker-input"),
154.{168.{
155 .name = "E",169 .name = "E",
156 .syntax = .flag,170 .syntax = .flag,
157 .zig_equivalent = .preprocess,171 .zig_equivalent = .pp_or_asm,
158 .pd1 = true,172 .pd1 = true,
159 .pd2 = false,173 .pd2 = false,
160 .psl = true,174 .psl = true,
...@@ -490,7 +504,7 @@ sepd1("Zlinker-input"),...@@ -490,7 +504,7 @@ sepd1("Zlinker-input"),
490.{504.{
491 .name = "MD",505 .name = "MD",
492 .syntax = .flag,506 .syntax = .flag,
493 .zig_equivalent = .other,507 .zig_equivalent = .dep_file,
494 .pd1 = true,508 .pd1 = true,
495 .pd2 = false,509 .pd2 = false,
496 .psl = true,510 .psl = true,
...@@ -1442,7 +1456,7 @@ sepd1("Zlinker-input"),...@@ -1442,7 +1456,7 @@ sepd1("Zlinker-input"),
1442.{1456.{
1443 .name = "assemble",1457 .name = "assemble",
1444 .syntax = .flag,1458 .syntax = .flag,
1445 .zig_equivalent = .driver_punt,1459 .zig_equivalent = .pp_or_asm,
1446 .pd1 = false,1460 .pd1 = false,
1447 .pd2 = true,1461 .pd2 = true,
1448 .psl = false,1462 .psl = false,
...@@ -1658,7 +1672,7 @@ sepd1("Zlinker-input"),...@@ -1658,7 +1672,7 @@ sepd1("Zlinker-input"),
1658.{1672.{
1659 .name = "library-directory",1673 .name = "library-directory",
1660 .syntax = .separate,1674 .syntax = .separate,
1661 .zig_equivalent = .other,1675 .zig_equivalent = .lib_dir,
1662 .pd1 = false,1676 .pd1 = false,
1663 .pd2 = true,1677 .pd2 = true,
1664 .psl = false,1678 .psl = false,
...@@ -1770,7 +1784,7 @@ sepd1("Zlinker-input"),...@@ -1770,7 +1784,7 @@ sepd1("Zlinker-input"),
1770.{1784.{
1771 .name = "preprocess",1785 .name = "preprocess",
1772 .syntax = .flag,1786 .syntax = .flag,
1773 .zig_equivalent = .preprocess,1787 .zig_equivalent = .pp_or_asm,
1774 .pd1 = false,1788 .pd1 = false,
1775 .pd2 = true,1789 .pd2 = true,
1776 .psl = false,1790 .psl = false,
...@@ -2554,14 +2568,7 @@ flagpd1("femulated-tls"),...@@ -2554,14 +2568,7 @@ flagpd1("femulated-tls"),
2554flagpd1("fencode-extended-block-signature"),2568flagpd1("fencode-extended-block-signature"),
2555sepd1("ferror-limit"),2569sepd1("ferror-limit"),
2556flagpd1("fescaping-block-tail-calls"),2570flagpd1("fescaping-block-tail-calls"),
2557.{2571flagpd1("fexceptions"),
2558 .name = "fexceptions",
2559 .syntax = .flag,
2560 .zig_equivalent = .exceptions,
2561 .pd1 = true,
2562 .pd2 = false,
2563 .psl = false,
2564},
2565flagpd1("fexperimental-isel"),2572flagpd1("fexperimental-isel"),
2566flagpd1("fexperimental-new-constant-interpreter"),2573flagpd1("fexperimental-new-constant-interpreter"),
2567flagpd1("fexperimental-new-pass-manager"),2574flagpd1("fexperimental-new-pass-manager"),
...@@ -2765,14 +2772,7 @@ flagpd1("fno-elide-type"),...@@ -2765,14 +2772,7 @@ flagpd1("fno-elide-type"),
2765flagpd1("fno-eliminate-unused-debug-symbols"),2772flagpd1("fno-eliminate-unused-debug-symbols"),
2766flagpd1("fno-emulated-tls"),2773flagpd1("fno-emulated-tls"),
2767flagpd1("fno-escaping-block-tail-calls"),2774flagpd1("fno-escaping-block-tail-calls"),
2768.{2775flagpd1("fno-exceptions"),
2769 .name = "fno-exceptions",
2770 .syntax = .flag,
2771 .zig_equivalent = .no_exceptions,
2772 .pd1 = true,
2773 .pd2 = false,
2774 .psl = false,
2775},
2776flagpd1("fno-experimental-isel"),2776flagpd1("fno-experimental-isel"),
2777flagpd1("fno-experimental-new-pass-manager"),2777flagpd1("fno-experimental-new-pass-manager"),
2778flagpd1("fno-fast-math"),2778flagpd1("fno-fast-math"),
...@@ -2861,14 +2861,7 @@ flagpd1("fno-rewrite-includes"),...@@ -2861,14 +2861,7 @@ flagpd1("fno-rewrite-includes"),
2861flagpd1("fno-ropi"),2861flagpd1("fno-ropi"),
2862flagpd1("fno-rounding-math"),2862flagpd1("fno-rounding-math"),
2863flagpd1("fno-rtlib-add-rpath"),2863flagpd1("fno-rtlib-add-rpath"),
2864.{2864flagpd1("fno-rtti"),
2865 .name = "fno-rtti",
2866 .syntax = .flag,
2867 .zig_equivalent = .no_rtti,
2868 .pd1 = true,
2869 .pd2 = false,
2870 .psl = false,
2871},
2872flagpd1("fno-rtti-data"),2865flagpd1("fno-rtti-data"),
2873flagpd1("fno-rwpi"),2866flagpd1("fno-rwpi"),
2874flagpd1("fno-sanitize-address-poison-custom-array-cookie"),2867flagpd1("fno-sanitize-address-poison-custom-array-cookie"),
...@@ -2996,7 +2989,14 @@ sepd1("fprofile-remapping-file"),...@@ -2996,7 +2989,14 @@ sepd1("fprofile-remapping-file"),
2996flagpd1("fprofile-sample-accurate"),2989flagpd1("fprofile-sample-accurate"),
2997flagpd1("fprofile-sample-use"),2990flagpd1("fprofile-sample-use"),
2998flagpd1("fprofile-use"),2991flagpd1("fprofile-use"),
2999sepd1("framework"),2992.{
2993 .name = "framework",
2994 .syntax = .separate,
2995 .zig_equivalent = .framework,
2996 .pd1 = true,
2997 .pd2 = false,
2998 .psl = false,
2999},
3000flagpd1("freciprocal-math"),3000flagpd1("freciprocal-math"),
3001flagpd1("frecord-command-line"),3001flagpd1("frecord-command-line"),
3002flagpd1("ffree-form"),3002flagpd1("ffree-form"),
...@@ -3016,14 +3016,7 @@ flagpd1("fno-frontend-optimize"),...@@ -3016,14 +3016,7 @@ flagpd1("fno-frontend-optimize"),
3016flagpd1("fropi"),3016flagpd1("fropi"),
3017flagpd1("frounding-math"),3017flagpd1("frounding-math"),
3018flagpd1("frtlib-add-rpath"),3018flagpd1("frtlib-add-rpath"),
3019.{3019flagpd1("frtti"),
3020 .name = "frtti",
3021 .syntax = .flag,
3022 .zig_equivalent = .rtti,
3023 .pd1 = true,
3024 .pd2 = false,
3025 .psl = false,
3026},
3027flagpd1("frwpi"),3020flagpd1("frwpi"),
3028flagpd1("fsanitize-address-globals-dead-stripping"),3021flagpd1("fsanitize-address-globals-dead-stripping"),
3029flagpd1("fsanitize-address-poison-custom-array-cookie"),3022flagpd1("fsanitize-address-poison-custom-array-cookie"),
...@@ -4562,7 +4555,7 @@ joinpd1("target-sdk-version="),...@@ -4562,7 +4555,7 @@ joinpd1("target-sdk-version="),
4562.{4555.{
4563 .name = "library-directory=",4556 .name = "library-directory=",
4564 .syntax = .joined,4557 .syntax = .joined,
4565 .zig_equivalent = .other,4558 .zig_equivalent = .lib_dir,
4566 .pd1 = false,4559 .pd1 = false,
4567 .pd2 = true,4560 .pd2 = true,
4568 .psl = false,4561 .psl = false,
...@@ -5282,8 +5275,22 @@ joinpd1("fixit="),...@@ -5282,8 +5275,22 @@ joinpd1("fixit="),
5282joinpd1("gstabs"),5275joinpd1("gstabs"),
5283joinpd1("gxcoff"),5276joinpd1("gxcoff"),
5284jspd1("iquote"),5277jspd1("iquote"),
5285joinpd1("march="),5278.{
5286joinpd1("mtune="),5279 .name = "march=",
5280 .syntax = .joined,
5281 .zig_equivalent = .mcpu,
5282 .pd1 = true,
5283 .pd2 = false,
5284 .psl = false,
5285},
5286.{
5287 .name = "mtune=",
5288 .syntax = .joined,
5289 .zig_equivalent = .mcpu,
5290 .pd1 = true,
5291 .pd2 = false,
5292 .psl = false,
5293},
5287.{5294.{
5288 .name = "rtlib=",5295 .name = "rtlib=",
5289 .syntax = .joined,5296 .syntax = .joined,
...@@ -5348,7 +5355,14 @@ joinpd1("gcoff"),...@@ -5348,7 +5355,14 @@ joinpd1("gcoff"),
5348joinpd1("mabi="),5355joinpd1("mabi="),
5349joinpd1("mabs="),5356joinpd1("mabs="),
5350joinpd1("masm="),5357joinpd1("masm="),
5351joinpd1("mcpu="),5358.{
5359 .name = "mcpu=",
5360 .syntax = .joined,
5361 .zig_equivalent = .mcpu,
5362 .pd1 = true,
5363 .pd2 = false,
5364 .psl = false,
5365},
5352joinpd1("mfpu="),5366joinpd1("mfpu="),
5353joinpd1("mhvx="),5367joinpd1("mhvx="),
5354joinpd1("mmcu="),5368joinpd1("mmcu="),
...@@ -5441,7 +5455,14 @@ joinpd1("mtp="),...@@ -5441,7 +5455,14 @@ joinpd1("mtp="),
5441joinpd1("gz="),5455joinpd1("gz="),
5442joinpd1("A-"),5456joinpd1("A-"),
5443joinpd1("G="),5457joinpd1("G="),
5444jspd1("MF"),5458.{
5459 .name = "MF",
5460 .syntax = .joined_or_separate,
5461 .zig_equivalent = .dep_file,
5462 .pd1 = true,
5463 .pd2 = false,
5464 .psl = false,
5465},
5445jspd1("MJ"),5466jspd1("MJ"),
5446jspd1("MQ"),5467jspd1("MQ"),
5447jspd1("MT"),5468jspd1("MT"),
...@@ -5656,11 +5677,25 @@ jspd1("MT"),...@@ -5656,11 +5677,25 @@ jspd1("MT"),
5656jspd1("A"),5677jspd1("A"),
5657jspd1("B"),5678jspd1("B"),
5658jspd1("D"),5679jspd1("D"),
5659jspd1("F"),5680.{
5681 .name = "F",
5682 .syntax = .joined_or_separate,
5683 .zig_equivalent = .framework_dir,
5684 .pd1 = true,
5685 .pd2 = false,
5686 .psl = false,
5687},
5660jspd1("G"),5688jspd1("G"),
5661jspd1("I"),5689jspd1("I"),
5662jspd1("J"),5690jspd1("J"),
5663jspd1("L"),5691.{
5692 .name = "L",
5693 .syntax = .joined_or_separate,
5694 .zig_equivalent = .lib_dir,
5695 .pd1 = true,
5696 .pd2 = false,
5697 .psl = false,
5698},
5664.{5699.{
5665 .name = "O",5700 .name = "O",
5666 .syntax = .joined,5701 .syntax = .joined,
...@@ -5694,7 +5729,7 @@ joinpd1("Z"),...@@ -5694,7 +5729,7 @@ joinpd1("Z"),
5694.{5729.{
5695 .name = "F",5730 .name = "F",
5696 .syntax = .joined_or_separate,5731 .syntax = .joined_or_separate,
5697 .zig_equivalent = .other,5732 .zig_equivalent = .framework_dir,
5698 .pd1 = true,5733 .pd1 = true,
5699 .pd2 = false,5734 .pd2 = false,
5700 .psl = true,5735 .psl = true,
src-self-hosted/codegen.zig+14-14
...@@ -25,10 +25,10 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)...@@ -25,10 +25,10 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
2525
26 const context = llvm_handle.node.data;26 const context = llvm_handle.node.data;
2727
28 const module = llvm.ModuleCreateWithNameInContext(comp.name.toSliceConst(), context) orelse return error.OutOfMemory;28 const module = llvm.ModuleCreateWithNameInContext(comp.name.span(), context) orelse return error.OutOfMemory;
29 defer llvm.DisposeModule(module);29 defer llvm.DisposeModule(module);
3030
31 llvm.SetTarget(module, comp.llvm_triple.toSliceConst());31 llvm.SetTarget(module, comp.llvm_triple.span());
32 llvm.SetDataLayout(module, comp.target_layout_str);32 llvm.SetDataLayout(module, comp.target_layout_str);
3333
34 if (comp.target.getObjectFormat() == .coff) {34 if (comp.target.getObjectFormat() == .coff) {
...@@ -45,7 +45,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)...@@ -45,7 +45,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
4545
46 // Don't use ZIG_VERSION_STRING here. LLVM misparses it when it includes46 // Don't use ZIG_VERSION_STRING here. LLVM misparses it when it includes
47 // the git revision.47 // the git revision.
48 const producer = try std.Buffer.allocPrint(&code.arena.allocator, "zig {}.{}.{}", .{48 const producer = try std.fmt.allocPrintZ(&code.arena.allocator, "zig {}.{}.{}", .{
49 @as(u32, c.ZIG_VERSION_MAJOR),49 @as(u32, c.ZIG_VERSION_MAJOR),
50 @as(u32, c.ZIG_VERSION_MINOR),50 @as(u32, c.ZIG_VERSION_MINOR),
51 @as(u32, c.ZIG_VERSION_PATCH),51 @as(u32, c.ZIG_VERSION_PATCH),
...@@ -54,15 +54,15 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)...@@ -54,15 +54,15 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
54 const runtime_version = 0;54 const runtime_version = 0;
55 const compile_unit_file = llvm.CreateFile(55 const compile_unit_file = llvm.CreateFile(
56 dibuilder,56 dibuilder,
57 comp.name.toSliceConst(),57 comp.name.span(),
58 comp.root_package.root_src_dir.toSliceConst(),58 comp.root_package.root_src_dir.span(),
59 ) orelse return error.OutOfMemory;59 ) orelse return error.OutOfMemory;
60 const is_optimized = comp.build_mode != .Debug;60 const is_optimized = comp.build_mode != .Debug;
61 const compile_unit = llvm.CreateCompileUnit(61 const compile_unit = llvm.CreateCompileUnit(
62 dibuilder,62 dibuilder,
63 DW.LANG_C99,63 DW.LANG_C99,
64 compile_unit_file,64 compile_unit_file,
65 producer.toSliceConst(),65 producer,
66 is_optimized,66 is_optimized,
67 flags,67 flags,
68 runtime_version,68 runtime_version,
...@@ -109,14 +109,14 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)...@@ -109,14 +109,14 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
109 if (llvm.TargetMachineEmitToFile(109 if (llvm.TargetMachineEmitToFile(
110 comp.target_machine,110 comp.target_machine,
111 module,111 module,
112 output_path.toSliceConst(),112 output_path.span(),
113 llvm.EmitBinary,113 llvm.EmitBinary,
114 &err_msg,114 &err_msg,
115 is_debug,115 is_debug,
116 is_small,116 is_small,
117 )) {117 )) {
118 if (std.debug.runtime_safety) {118 if (std.debug.runtime_safety) {
119 std.debug.panic("unable to write object file {}: {s}\n", .{ output_path.toSliceConst(), err_msg });119 std.debug.panic("unable to write object file {}: {s}\n", .{ output_path.span(), err_msg });
120 }120 }
121 return error.WritingObjectFileFailed;121 return error.WritingObjectFileFailed;
122 }122 }
...@@ -127,7 +127,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)...@@ -127,7 +127,7 @@ pub async fn renderToLlvm(comp: *Compilation, fn_val: *Value.Fn, code: *ir.Code)
127 llvm.DumpModule(ofile.module);127 llvm.DumpModule(ofile.module);
128 }128 }
129 if (comp.verbose_link) {129 if (comp.verbose_link) {
130 std.debug.warn("created {}\n", .{output_path.toSliceConst()});130 std.debug.warn("created {}\n", .{output_path.span()});
131 }131 }
132}132}
133133
...@@ -150,7 +150,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)...@@ -150,7 +150,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)
150 const llvm_fn_type = try fn_val.base.typ.getLlvmType(ofile.arena, ofile.context);150 const llvm_fn_type = try fn_val.base.typ.getLlvmType(ofile.arena, ofile.context);
151 const llvm_fn = llvm.AddFunction(151 const llvm_fn = llvm.AddFunction(
152 ofile.module,152 ofile.module,
153 fn_val.symbol_name.toSliceConst(),153 fn_val.symbol_name.span(),
154 llvm_fn_type,154 llvm_fn_type,
155 ) orelse return error.OutOfMemory;155 ) orelse return error.OutOfMemory;
156156
...@@ -211,7 +211,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)...@@ -211,7 +211,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)
211 const cur_ret_ptr = if (fn_type_normal.return_type.handleIsPtr()) llvm.GetParam(llvm_fn, 0) else null;211 const cur_ret_ptr = if (fn_type_normal.return_type.handleIsPtr()) llvm.GetParam(llvm_fn, 0) else null;
212212
213 // build all basic blocks213 // build all basic blocks
214 for (code.basic_block_list.toSlice()) |bb| {214 for (code.basic_block_list.span()) |bb| {
215 bb.llvm_block = llvm.AppendBasicBlockInContext(215 bb.llvm_block = llvm.AppendBasicBlockInContext(
216 ofile.context,216 ofile.context,
217 llvm_fn,217 llvm_fn,
...@@ -226,7 +226,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)...@@ -226,7 +226,7 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)
226 // TODO set up error return tracing226 // TODO set up error return tracing
227 // TODO allocate temporary stack values227 // TODO allocate temporary stack values
228228
229 const var_list = fn_type.non_key.Normal.variable_list.toSliceConst();229 const var_list = fn_type.non_key.Normal.variable_list.span();
230 // create debug variable declarations for variables and allocate all local variables230 // create debug variable declarations for variables and allocate all local variables
231 for (var_list) |var_scope, i| {231 for (var_list) |var_scope, i| {
232 const var_type = switch (var_scope.data) {232 const var_type = switch (var_scope.data) {
...@@ -306,9 +306,9 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)...@@ -306,9 +306,9 @@ pub fn renderToLlvmModule(ofile: *ObjectFile, fn_val: *Value.Fn, code: *ir.Code)
306 //}306 //}
307 }307 }
308308
309 for (code.basic_block_list.toSlice()) |current_block| {309 for (code.basic_block_list.span()) |current_block| {
310 llvm.PositionBuilderAtEnd(ofile.builder, current_block.llvm_block);310 llvm.PositionBuilderAtEnd(ofile.builder, current_block.llvm_block);
311 for (current_block.instruction_list.toSlice()) |instruction| {311 for (current_block.instruction_list.span()) |instruction| {
312 if (instruction.ref_count == 0 and !instruction.hasSideEffects()) continue;312 if (instruction.ref_count == 0 and !instruction.hasSideEffects()) continue;
313313
314 instruction.llvm_value = try instruction.render(ofile, fn_val);314 instruction.llvm_value = try instruction.render(ofile, fn_val);
src-self-hosted/compilation.zig+11-11
...@@ -2,7 +2,7 @@ const std = @import("std");...@@ -2,7 +2,7 @@ const std = @import("std");
2const io = std.io;2const io = std.io;
3const mem = std.mem;3const mem = std.mem;
4const Allocator = mem.Allocator;4const Allocator = mem.Allocator;
5const Buffer = std.Buffer;5const ArrayListSentineled = std.ArrayListSentineled;
6const llvm = @import("llvm.zig");6const llvm = @import("llvm.zig");
7const c = @import("c.zig");7const c = @import("c.zig");
8const builtin = std.builtin;8const builtin = std.builtin;
...@@ -123,8 +123,8 @@ pub const LlvmHandle = struct {...@@ -123,8 +123,8 @@ pub const LlvmHandle = struct {
123123
124pub const Compilation = struct {124pub const Compilation = struct {
125 zig_compiler: *ZigCompiler,125 zig_compiler: *ZigCompiler,
126 name: Buffer,126 name: ArrayListSentineled(u8, 0),
127 llvm_triple: Buffer,127 llvm_triple: ArrayListSentineled(u8, 0),
128 root_src_path: ?[]const u8,128 root_src_path: ?[]const u8,
129 target: std.Target,129 target: std.Target,
130 llvm_target: *llvm.Target,130 llvm_target: *llvm.Target,
...@@ -444,7 +444,7 @@ pub const Compilation = struct {...@@ -444,7 +444,7 @@ pub const Compilation = struct {
444 comp.arena_allocator.deinit();444 comp.arena_allocator.deinit();
445 }445 }
446446
447 comp.name = try Buffer.init(comp.arena(), name);447 comp.name = try ArrayListSentineled(u8, 0).init(comp.arena(), name);
448 comp.llvm_triple = try util.getLLVMTriple(comp.arena(), target);448 comp.llvm_triple = try util.getLLVMTriple(comp.arena(), target);
449 comp.llvm_target = try util.llvmTargetFromTriple(comp.llvm_triple);449 comp.llvm_target = try util.llvmTargetFromTriple(comp.llvm_triple);
450 comp.zig_std_dir = try fs.path.join(comp.arena(), &[_][]const u8{ zig_lib_dir, "std" });450 comp.zig_std_dir = try fs.path.join(comp.arena(), &[_][]const u8{ zig_lib_dir, "std" });
...@@ -465,7 +465,7 @@ pub const Compilation = struct {...@@ -465,7 +465,7 @@ pub const Compilation = struct {
465465
466 comp.target_machine = llvm.CreateTargetMachine(466 comp.target_machine = llvm.CreateTargetMachine(
467 comp.llvm_target,467 comp.llvm_target,
468 comp.llvm_triple.toSliceConst(),468 comp.llvm_triple.span(),
469 target_specific_cpu_args orelse "",469 target_specific_cpu_args orelse "",
470 target_specific_cpu_features orelse "",470 target_specific_cpu_features orelse "",
471 opt_level,471 opt_level,
...@@ -1106,7 +1106,7 @@ pub const Compilation = struct {...@@ -1106,7 +1106,7 @@ pub const Compilation = struct {
1106 }1106 }
1107 }1107 }
11081108
1109 for (self.link_libs_list.toSliceConst()) |existing_lib| {1109 for (self.link_libs_list.span()) |existing_lib| {
1110 if (mem.eql(u8, name, existing_lib.name)) {1110 if (mem.eql(u8, name, existing_lib.name)) {
1111 return existing_lib;1111 return existing_lib;
1112 }1112 }
...@@ -1151,7 +1151,7 @@ pub const Compilation = struct {...@@ -1151,7 +1151,7 @@ pub const Compilation = struct {
11511151
1152 /// If the temporary directory for this compilation has not been created, it creates it.1152 /// If the temporary directory for this compilation has not been created, it creates it.
1153 /// Then it creates a random file name in that dir and returns it.1153 /// Then it creates a random file name in that dir and returns it.
1154 pub fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !Buffer {1154 pub fn createRandomOutputPath(self: *Compilation, suffix: []const u8) !ArrayListSentineled(u8, 0) {
1155 const tmp_dir = try self.getTmpDir();1155 const tmp_dir = try self.getTmpDir();
1156 const file_prefix = self.getRandomFileName();1156 const file_prefix = self.getRandomFileName();
11571157
...@@ -1161,7 +1161,7 @@ pub const Compilation = struct {...@@ -1161,7 +1161,7 @@ pub const Compilation = struct {
1161 const full_path = try fs.path.join(self.gpa(), &[_][]const u8{ tmp_dir, file_name[0..] });1161 const full_path = try fs.path.join(self.gpa(), &[_][]const u8{ tmp_dir, file_name[0..] });
1162 errdefer self.gpa().free(full_path);1162 errdefer self.gpa().free(full_path);
11631163
1164 return Buffer.fromOwnedSlice(self.gpa(), full_path);1164 return ArrayListSentineled(u8, 0).fromOwnedSlice(self.gpa(), full_path);
1165 }1165 }
11661166
1167 /// If the temporary directory for this Compilation has not been created, creates it.1167 /// If the temporary directory for this Compilation has not been created, creates it.
...@@ -1279,7 +1279,7 @@ fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {...@@ -1279,7 +1279,7 @@ fn generateDeclFn(comp: *Compilation, fn_decl: *Decl.Fn) !void {
1279 const fn_type = try analyzeFnType(comp, tree_scope, fn_decl.base.parent_scope, fn_decl.fn_proto);1279 const fn_type = try analyzeFnType(comp, tree_scope, fn_decl.base.parent_scope, fn_decl.fn_proto);
1280 defer fn_type.base.base.deref(comp);1280 defer fn_type.base.base.deref(comp);
12811281
1282 var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name);1282 var symbol_name = try std.ArrayListSentineled(u8, 0).init(comp.gpa(), fn_decl.base.name);
1283 var symbol_name_consumed = false;1283 var symbol_name_consumed = false;
1284 errdefer if (!symbol_name_consumed) symbol_name.deinit();1284 errdefer if (!symbol_name_consumed) symbol_name.deinit();
12851285
...@@ -1371,7 +1371,7 @@ fn analyzeFnType(...@@ -1371,7 +1371,7 @@ fn analyzeFnType(
1371 var params = ArrayList(Type.Fn.Param).init(comp.gpa());1371 var params = ArrayList(Type.Fn.Param).init(comp.gpa());
1372 var params_consumed = false;1372 var params_consumed = false;
1373 defer if (!params_consumed) {1373 defer if (!params_consumed) {
1374 for (params.toSliceConst()) |param| {1374 for (params.span()) |param| {
1375 param.typ.base.deref(comp);1375 param.typ.base.deref(comp);
1376 }1376 }
1377 params.deinit();1377 params.deinit();
...@@ -1426,7 +1426,7 @@ fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void {...@@ -1426,7 +1426,7 @@ fn generateDeclFnProto(comp: *Compilation, fn_decl: *Decl.Fn) !void {
1426 );1426 );
1427 defer fn_type.base.base.deref(comp);1427 defer fn_type.base.base.deref(comp);
14281428
1429 var symbol_name = try std.Buffer.init(comp.gpa(), fn_decl.base.name);1429 var symbol_name = try std.ArrayListSentineled(u8, 0).init(comp.gpa(), fn_decl.base.name);
1430 var symbol_name_consumed = false;1430 var symbol_name_consumed = false;
1431 defer if (!symbol_name_consumed) symbol_name.deinit();1431 defer if (!symbol_name_consumed) symbol_name.deinit();
14321432
src-self-hosted/dep_tokenizer.zig+59-59
...@@ -33,7 +33,7 @@ pub const Tokenizer = struct {...@@ -33,7 +33,7 @@ pub const Tokenizer = struct {
33 break; // advance33 break; // advance
34 },34 },
35 else => {35 else => {
36 self.state = State{ .target = try std.Buffer.initSize(&self.arena.allocator, 0) };36 self.state = State{ .target = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0) };
37 },37 },
38 },38 },
39 .target => |*target| switch (char) {39 .target => |*target| switch (char) {
...@@ -53,7 +53,7 @@ pub const Tokenizer = struct {...@@ -53,7 +53,7 @@ pub const Tokenizer = struct {
53 break; // advance53 break; // advance
54 },54 },
55 else => {55 else => {
56 try target.appendByte(char);56 try target.append(char);
57 break; // advance57 break; // advance
58 },58 },
59 },59 },
...@@ -62,24 +62,24 @@ pub const Tokenizer = struct {...@@ -62,24 +62,24 @@ pub const Tokenizer = struct {
62 return self.errorIllegalChar(self.index, char, "bad target escape", .{});62 return self.errorIllegalChar(self.index, char, "bad target escape", .{});
63 },63 },
64 ' ', '#', '\\' => {64 ' ', '#', '\\' => {
65 try target.appendByte(char);65 try target.append(char);
66 self.state = State{ .target = target.* };66 self.state = State{ .target = target.* };
67 break; // advance67 break; // advance
68 },68 },
69 '$' => {69 '$' => {
70 try target.append(self.bytes[self.index - 1 .. self.index]);70 try target.appendSlice(self.bytes[self.index - 1 .. self.index]);
71 self.state = State{ .target_dollar_sign = target.* };71 self.state = State{ .target_dollar_sign = target.* };
72 break; // advance72 break; // advance
73 },73 },
74 else => {74 else => {
75 try target.append(self.bytes[self.index - 1 .. self.index + 1]);75 try target.appendSlice(self.bytes[self.index - 1 .. self.index + 1]);
76 self.state = State{ .target = target.* };76 self.state = State{ .target = target.* };
77 break; // advance77 break; // advance
78 },78 },
79 },79 },
80 .target_dollar_sign => |*target| switch (char) {80 .target_dollar_sign => |*target| switch (char) {
81 '$' => {81 '$' => {
82 try target.appendByte(char);82 try target.append(char);
83 self.state = State{ .target = target.* };83 self.state = State{ .target = target.* };
84 break; // advance84 break; // advance
85 },85 },
...@@ -89,7 +89,7 @@ pub const Tokenizer = struct {...@@ -89,7 +89,7 @@ pub const Tokenizer = struct {
89 },89 },
90 .target_colon => |*target| switch (char) {90 .target_colon => |*target| switch (char) {
91 '\n', '\r' => {91 '\n', '\r' => {
92 const bytes = target.toSlice();92 const bytes = target.span();
93 if (bytes.len != 0) {93 if (bytes.len != 0) {
94 self.state = State{ .lhs = {} };94 self.state = State{ .lhs = {} };
95 return Token{ .id = .target, .bytes = bytes };95 return Token{ .id = .target, .bytes = bytes };
...@@ -103,7 +103,7 @@ pub const Tokenizer = struct {...@@ -103,7 +103,7 @@ pub const Tokenizer = struct {
103 break; // advance103 break; // advance
104 },104 },
105 else => {105 else => {
106 const bytes = target.toSlice();106 const bytes = target.span();
107 if (bytes.len != 0) {107 if (bytes.len != 0) {
108 self.state = State{ .rhs = {} };108 self.state = State{ .rhs = {} };
109 return Token{ .id = .target, .bytes = bytes };109 return Token{ .id = .target, .bytes = bytes };
...@@ -115,7 +115,7 @@ pub const Tokenizer = struct {...@@ -115,7 +115,7 @@ pub const Tokenizer = struct {
115 },115 },
116 .target_colon_reverse_solidus => |*target| switch (char) {116 .target_colon_reverse_solidus => |*target| switch (char) {
117 '\n', '\r' => {117 '\n', '\r' => {
118 const bytes = target.toSlice();118 const bytes = target.span();
119 if (bytes.len != 0) {119 if (bytes.len != 0) {
120 self.state = State{ .lhs = {} };120 self.state = State{ .lhs = {} };
121 return Token{ .id = .target, .bytes = bytes };121 return Token{ .id = .target, .bytes = bytes };
...@@ -125,7 +125,7 @@ pub const Tokenizer = struct {...@@ -125,7 +125,7 @@ pub const Tokenizer = struct {
125 continue;125 continue;
126 },126 },
127 else => {127 else => {
128 try target.append(self.bytes[self.index - 2 .. self.index + 1]);128 try target.appendSlice(self.bytes[self.index - 2 .. self.index + 1]);
129 self.state = State{ .target = target.* };129 self.state = State{ .target = target.* };
130 break;130 break;
131 },131 },
...@@ -144,11 +144,11 @@ pub const Tokenizer = struct {...@@ -144,11 +144,11 @@ pub const Tokenizer = struct {
144 break; // advance144 break; // advance
145 },145 },
146 '"' => {146 '"' => {
147 self.state = State{ .prereq_quote = try std.Buffer.initSize(&self.arena.allocator, 0) };147 self.state = State{ .prereq_quote = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0) };
148 break; // advance148 break; // advance
149 },149 },
150 else => {150 else => {
151 self.state = State{ .prereq = try std.Buffer.initSize(&self.arena.allocator, 0) };151 self.state = State{ .prereq = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0) };
152 },152 },
153 },153 },
154 .rhs_continuation => switch (char) {154 .rhs_continuation => switch (char) {
...@@ -175,24 +175,24 @@ pub const Tokenizer = struct {...@@ -175,24 +175,24 @@ pub const Tokenizer = struct {
175 },175 },
176 .prereq_quote => |*prereq| switch (char) {176 .prereq_quote => |*prereq| switch (char) {
177 '"' => {177 '"' => {
178 const bytes = prereq.toSlice();178 const bytes = prereq.span();
179 self.index += 1;179 self.index += 1;
180 self.state = State{ .rhs = {} };180 self.state = State{ .rhs = {} };
181 return Token{ .id = .prereq, .bytes = bytes };181 return Token{ .id = .prereq, .bytes = bytes };
182 },182 },
183 else => {183 else => {
184 try prereq.appendByte(char);184 try prereq.append(char);
185 break; // advance185 break; // advance
186 },186 },
187 },187 },
188 .prereq => |*prereq| switch (char) {188 .prereq => |*prereq| switch (char) {
189 '\t', ' ' => {189 '\t', ' ' => {
190 const bytes = prereq.toSlice();190 const bytes = prereq.span();
191 self.state = State{ .rhs = {} };191 self.state = State{ .rhs = {} };
192 return Token{ .id = .prereq, .bytes = bytes };192 return Token{ .id = .prereq, .bytes = bytes };
193 },193 },
194 '\n', '\r' => {194 '\n', '\r' => {
195 const bytes = prereq.toSlice();195 const bytes = prereq.span();
196 self.state = State{ .lhs = {} };196 self.state = State{ .lhs = {} };
197 return Token{ .id = .prereq, .bytes = bytes };197 return Token{ .id = .prereq, .bytes = bytes };
198 },198 },
...@@ -201,13 +201,13 @@ pub const Tokenizer = struct {...@@ -201,13 +201,13 @@ pub const Tokenizer = struct {
201 break; // advance201 break; // advance
202 },202 },
203 else => {203 else => {
204 try prereq.appendByte(char);204 try prereq.append(char);
205 break; // advance205 break; // advance
206 },206 },
207 },207 },
208 .prereq_continuation => |*prereq| switch (char) {208 .prereq_continuation => |*prereq| switch (char) {
209 '\n' => {209 '\n' => {
210 const bytes = prereq.toSlice();210 const bytes = prereq.span();
211 self.index += 1;211 self.index += 1;
212 self.state = State{ .rhs = {} };212 self.state = State{ .rhs = {} };
213 return Token{ .id = .prereq, .bytes = bytes };213 return Token{ .id = .prereq, .bytes = bytes };
...@@ -218,14 +218,14 @@ pub const Tokenizer = struct {...@@ -218,14 +218,14 @@ pub const Tokenizer = struct {
218 },218 },
219 else => {219 else => {
220 // not continuation220 // not continuation
221 try prereq.append(self.bytes[self.index - 1 .. self.index + 1]);221 try prereq.appendSlice(self.bytes[self.index - 1 .. self.index + 1]);
222 self.state = State{ .prereq = prereq.* };222 self.state = State{ .prereq = prereq.* };
223 break; // advance223 break; // advance
224 },224 },
225 },225 },
226 .prereq_continuation_linefeed => |prereq| switch (char) {226 .prereq_continuation_linefeed => |prereq| switch (char) {
227 '\n' => {227 '\n' => {
228 const bytes = prereq.toSlice();228 const bytes = prereq.span();
229 self.index += 1;229 self.index += 1;
230 self.state = State{ .rhs = {} };230 self.state = State{ .rhs = {} };
231 return Token{ .id = .prereq, .bytes = bytes };231 return Token{ .id = .prereq, .bytes = bytes };
...@@ -249,7 +249,7 @@ pub const Tokenizer = struct {...@@ -249,7 +249,7 @@ pub const Tokenizer = struct {
249 .rhs_continuation_linefeed,249 .rhs_continuation_linefeed,
250 => {},250 => {},
251 .target => |target| {251 .target => |target| {
252 return self.errorPosition(idx, target.toSlice(), "incomplete target", .{});252 return self.errorPosition(idx, target.span(), "incomplete target", .{});
253 },253 },
254 .target_reverse_solidus,254 .target_reverse_solidus,
255 .target_dollar_sign,255 .target_dollar_sign,
...@@ -258,7 +258,7 @@ pub const Tokenizer = struct {...@@ -258,7 +258,7 @@ pub const Tokenizer = struct {
258 return self.errorIllegalChar(idx, self.bytes[idx], "incomplete escape", .{});258 return self.errorIllegalChar(idx, self.bytes[idx], "incomplete escape", .{});
259 },259 },
260 .target_colon => |target| {260 .target_colon => |target| {
261 const bytes = target.toSlice();261 const bytes = target.span();
262 if (bytes.len != 0) {262 if (bytes.len != 0) {
263 self.index += 1;263 self.index += 1;
264 self.state = State{ .rhs = {} };264 self.state = State{ .rhs = {} };
...@@ -268,7 +268,7 @@ pub const Tokenizer = struct {...@@ -268,7 +268,7 @@ pub const Tokenizer = struct {
268 self.state = State{ .lhs = {} };268 self.state = State{ .lhs = {} };
269 },269 },
270 .target_colon_reverse_solidus => |target| {270 .target_colon_reverse_solidus => |target| {
271 const bytes = target.toSlice();271 const bytes = target.span();
272 if (bytes.len != 0) {272 if (bytes.len != 0) {
273 self.index += 1;273 self.index += 1;
274 self.state = State{ .rhs = {} };274 self.state = State{ .rhs = {} };
...@@ -278,20 +278,20 @@ pub const Tokenizer = struct {...@@ -278,20 +278,20 @@ pub const Tokenizer = struct {
278 self.state = State{ .lhs = {} };278 self.state = State{ .lhs = {} };
279 },279 },
280 .prereq_quote => |prereq| {280 .prereq_quote => |prereq| {
281 return self.errorPosition(idx, prereq.toSlice(), "incomplete quoted prerequisite", .{});281 return self.errorPosition(idx, prereq.span(), "incomplete quoted prerequisite", .{});
282 },282 },
283 .prereq => |prereq| {283 .prereq => |prereq| {
284 const bytes = prereq.toSlice();284 const bytes = prereq.span();
285 self.state = State{ .lhs = {} };285 self.state = State{ .lhs = {} };
286 return Token{ .id = .prereq, .bytes = bytes };286 return Token{ .id = .prereq, .bytes = bytes };
287 },287 },
288 .prereq_continuation => |prereq| {288 .prereq_continuation => |prereq| {
289 const bytes = prereq.toSlice();289 const bytes = prereq.span();
290 self.state = State{ .lhs = {} };290 self.state = State{ .lhs = {} };
291 return Token{ .id = .prereq, .bytes = bytes };291 return Token{ .id = .prereq, .bytes = bytes };
292 },292 },
293 .prereq_continuation_linefeed => |prereq| {293 .prereq_continuation_linefeed => |prereq| {
294 const bytes = prereq.toSlice();294 const bytes = prereq.span();
295 self.state = State{ .lhs = {} };295 self.state = State{ .lhs = {} };
296 return Token{ .id = .prereq, .bytes = bytes };296 return Token{ .id = .prereq, .bytes = bytes };
297 },297 },
...@@ -300,29 +300,29 @@ pub const Tokenizer = struct {...@@ -300,29 +300,29 @@ pub const Tokenizer = struct {
300 }300 }
301301
302 fn errorf(self: *Tokenizer, comptime fmt: []const u8, args: var) Error {302 fn errorf(self: *Tokenizer, comptime fmt: []const u8, args: var) Error {
303 self.error_text = (try std.Buffer.allocPrint(&self.arena.allocator, fmt, args)).toSlice();303 self.error_text = try std.fmt.allocPrintZ(&self.arena.allocator, fmt, args);
304 return Error.InvalidInput;304 return Error.InvalidInput;
305 }305 }
306306
307 fn errorPosition(self: *Tokenizer, position: usize, bytes: []const u8, comptime fmt: []const u8, args: var) Error {307 fn errorPosition(self: *Tokenizer, position: usize, bytes: []const u8, comptime fmt: []const u8, args: var) Error {
308 var buffer = try std.Buffer.initSize(&self.arena.allocator, 0);308 var buffer = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0);
309 try buffer.outStream().print(fmt, args);309 try buffer.outStream().print(fmt, args);
310 try buffer.append(" '");310 try buffer.appendSlice(" '");
311 var out = makeOutput(std.Buffer.append, &buffer);311 var out = makeOutput(std.ArrayListSentineled(u8, 0).appendSlice, &buffer);
312 try printCharValues(&out, bytes);312 try printCharValues(&out, bytes);
313 try buffer.append("'");313 try buffer.appendSlice("'");
314 try buffer.outStream().print(" at position {}", .{position - (bytes.len - 1)});314 try buffer.outStream().print(" at position {}", .{position - (bytes.len - 1)});
315 self.error_text = buffer.toSlice();315 self.error_text = buffer.span();
316 return Error.InvalidInput;316 return Error.InvalidInput;
317 }317 }
318318
319 fn errorIllegalChar(self: *Tokenizer, position: usize, char: u8, comptime fmt: []const u8, args: var) Error {319 fn errorIllegalChar(self: *Tokenizer, position: usize, char: u8, comptime fmt: []const u8, args: var) Error {
320 var buffer = try std.Buffer.initSize(&self.arena.allocator, 0);320 var buffer = try std.ArrayListSentineled(u8, 0).initSize(&self.arena.allocator, 0);
321 try buffer.append("illegal char ");321 try buffer.appendSlice("illegal char ");
322 try printUnderstandableChar(&buffer, char);322 try printUnderstandableChar(&buffer, char);
323 try buffer.outStream().print(" at position {}", .{position});323 try buffer.outStream().print(" at position {}", .{position});
324 if (fmt.len != 0) try buffer.outStream().print(": " ++ fmt, args);324 if (fmt.len != 0) try buffer.outStream().print(": " ++ fmt, args);
325 self.error_text = buffer.toSlice();325 self.error_text = buffer.span();
326 return Error.InvalidInput;326 return Error.InvalidInput;
327 }327 }
328328
...@@ -333,18 +333,18 @@ pub const Tokenizer = struct {...@@ -333,18 +333,18 @@ pub const Tokenizer = struct {
333333
334 const State = union(enum) {334 const State = union(enum) {
335 lhs: void,335 lhs: void,
336 target: std.Buffer,336 target: std.ArrayListSentineled(u8, 0),
337 target_reverse_solidus: std.Buffer,337 target_reverse_solidus: std.ArrayListSentineled(u8, 0),
338 target_dollar_sign: std.Buffer,338 target_dollar_sign: std.ArrayListSentineled(u8, 0),
339 target_colon: std.Buffer,339 target_colon: std.ArrayListSentineled(u8, 0),
340 target_colon_reverse_solidus: std.Buffer,340 target_colon_reverse_solidus: std.ArrayListSentineled(u8, 0),
341 rhs: void,341 rhs: void,
342 rhs_continuation: void,342 rhs_continuation: void,
343 rhs_continuation_linefeed: void,343 rhs_continuation_linefeed: void,
344 prereq_quote: std.Buffer,344 prereq_quote: std.ArrayListSentineled(u8, 0),
345 prereq: std.Buffer,345 prereq: std.ArrayListSentineled(u8, 0),
346 prereq_continuation: std.Buffer,346 prereq_continuation: std.ArrayListSentineled(u8, 0),
347 prereq_continuation_linefeed: std.Buffer,347 prereq_continuation_linefeed: std.ArrayListSentineled(u8, 0),
348 };348 };
349349
350 const Token = struct {350 const Token = struct {
...@@ -841,31 +841,31 @@ fn depTokenizer(input: []const u8, expect: []const u8) !void {...@@ -841,31 +841,31 @@ fn depTokenizer(input: []const u8, expect: []const u8) !void {
841 defer arena_allocator.deinit();841 defer arena_allocator.deinit();
842842
843 var it = Tokenizer.init(arena, input);843 var it = Tokenizer.init(arena, input);
844 var buffer = try std.Buffer.initSize(arena, 0);844 var buffer = try std.ArrayListSentineled(u8, 0).initSize(arena, 0);
845 var i: usize = 0;845 var i: usize = 0;
846 while (true) {846 while (true) {
847 const r = it.next() catch |err| {847 const r = it.next() catch |err| {
848 switch (err) {848 switch (err) {
849 Tokenizer.Error.InvalidInput => {849 Tokenizer.Error.InvalidInput => {
850 if (i != 0) try buffer.append("\n");850 if (i != 0) try buffer.appendSlice("\n");
851 try buffer.append("ERROR: ");851 try buffer.appendSlice("ERROR: ");
852 try buffer.append(it.error_text);852 try buffer.appendSlice(it.error_text);
853 },853 },
854 else => return err,854 else => return err,
855 }855 }
856 break;856 break;
857 };857 };
858 const token = r orelse break;858 const token = r orelse break;
859 if (i != 0) try buffer.append("\n");859 if (i != 0) try buffer.appendSlice("\n");
860 try buffer.append(@tagName(token.id));860 try buffer.appendSlice(@tagName(token.id));
861 try buffer.append(" = {");861 try buffer.appendSlice(" = {");
862 for (token.bytes) |b| {862 for (token.bytes) |b| {
863 try buffer.appendByte(printable_char_tab[b]);863 try buffer.append(printable_char_tab[b]);
864 }864 }
865 try buffer.append("}");865 try buffer.appendSlice("}");
866 i += 1;866 i += 1;
867 }867 }
868 const got: []const u8 = buffer.toSlice();868 const got: []const u8 = buffer.span();
869869
870 if (std.mem.eql(u8, expect, got)) {870 if (std.mem.eql(u8, expect, got)) {
871 testing.expect(true);871 testing.expect(true);
...@@ -995,13 +995,13 @@ fn printCharValues(out: var, bytes: []const u8) !void {...@@ -995,13 +995,13 @@ fn printCharValues(out: var, bytes: []const u8) !void {
995 }995 }
996}996}
997997
998fn printUnderstandableChar(buffer: *std.Buffer, char: u8) !void {998fn printUnderstandableChar(buffer: *std.ArrayListSentineled(u8, 0), char: u8) !void {
999 if (!std.ascii.isPrint(char) or char == ' ') {999 if (!std.ascii.isPrint(char) or char == ' ') {
1000 try buffer.outStream().print("\\x{X:2}", .{char});1000 try buffer.outStream().print("\\x{X:2}", .{char});
1001 } else {1001 } else {
1002 try buffer.append("'");1002 try buffer.appendSlice("'");
1003 try buffer.appendByte(printable_char_tab[char]);1003 try buffer.append(printable_char_tab[char]);
1004 try buffer.append("'");1004 try buffer.appendSlice("'");
1005 }1005 }
1006}1006}
10071007
src-self-hosted/errmsg.zig+2-2
...@@ -158,7 +158,7 @@ pub const Msg = struct {...@@ -158,7 +158,7 @@ pub const Msg = struct {
158 parse_error: *const ast.Error,158 parse_error: *const ast.Error,
159 ) !*Msg {159 ) !*Msg {
160 const loc_token = parse_error.loc();160 const loc_token = parse_error.loc();
161 var text_buf = try std.Buffer.initSize(comp.gpa(), 0);161 var text_buf = std.ArrayList(u8).init(comp.gpa());
162 defer text_buf.deinit();162 defer text_buf.deinit();
163163
164 const realpath_copy = try mem.dupe(comp.gpa(), u8, tree_scope.root().realpath);164 const realpath_copy = try mem.dupe(comp.gpa(), u8, tree_scope.root().realpath);
...@@ -197,7 +197,7 @@ pub const Msg = struct {...@@ -197,7 +197,7 @@ pub const Msg = struct {
197 realpath: []const u8,197 realpath: []const u8,
198 ) !*Msg {198 ) !*Msg {
199 const loc_token = parse_error.loc();199 const loc_token = parse_error.loc();
200 var text_buf = try std.Buffer.initSize(allocator, 0);200 var text_buf = std.ArrayList(u8).init(allocator);
201 defer text_buf.deinit();201 defer text_buf.deinit();
202202
203 const realpath_copy = try mem.dupe(allocator, u8, realpath);203 const realpath_copy = try mem.dupe(allocator, u8, realpath);
src-self-hosted/ir.zig+4-4
...@@ -965,9 +965,9 @@ pub const Code = struct {...@@ -965,9 +965,9 @@ pub const Code = struct {
965965
966 pub fn dump(self: *Code) void {966 pub fn dump(self: *Code) void {
967 var bb_i: usize = 0;967 var bb_i: usize = 0;
968 for (self.basic_block_list.toSliceConst()) |bb| {968 for (self.basic_block_list.span()) |bb| {
969 std.debug.warn("{s}_{}:\n", .{ bb.name_hint, bb.debug_id });969 std.debug.warn("{s}_{}:\n", .{ bb.name_hint, bb.debug_id });
970 for (bb.instruction_list.toSliceConst()) |instr| {970 for (bb.instruction_list.span()) |instr| {
971 std.debug.warn(" ", .{});971 std.debug.warn(" ", .{});
972 instr.dump();972 instr.dump();
973 std.debug.warn("\n", .{});973 std.debug.warn("\n", .{});
...@@ -978,7 +978,7 @@ pub const Code = struct {...@@ -978,7 +978,7 @@ pub const Code = struct {
978 /// returns a ref-incremented value, or adds a compile error978 /// returns a ref-incremented value, or adds a compile error
979 pub fn getCompTimeResult(self: *Code, comp: *Compilation) !*Value {979 pub fn getCompTimeResult(self: *Code, comp: *Compilation) !*Value {
980 const bb = self.basic_block_list.at(0);980 const bb = self.basic_block_list.at(0);
981 for (bb.instruction_list.toSliceConst()) |inst| {981 for (bb.instruction_list.span()) |inst| {
982 if (inst.cast(Inst.Return)) |ret_inst| {982 if (inst.cast(Inst.Return)) |ret_inst| {
983 const ret_value = ret_inst.params.return_value;983 const ret_value = ret_inst.params.return_value;
984 if (ret_value.isCompTime()) {984 if (ret_value.isCompTime()) {
...@@ -2585,6 +2585,6 @@ pub fn analyze(comp: *Compilation, old_code: *Code, expected_type: ?*Type) !*Cod...@@ -2585,6 +2585,6 @@ pub fn analyze(comp: *Compilation, old_code: *Code, expected_type: ?*Type) !*Cod
2585 return ira.irb.finish();2585 return ira.irb.finish();
2586 }2586 }
25872587
2588 ira.irb.code.return_type = try ira.resolvePeerTypes(expected_type, ira.src_implicit_return_type_list.toSliceConst());2588 ira.irb.code.return_type = try ira.resolvePeerTypes(expected_type, ira.src_implicit_return_type_list.span());
2589 return ira.irb.finish();2589 return ira.irb.finish();
2590}2590}
src-self-hosted/libc_installation.zig+20-24
...@@ -14,11 +14,11 @@ usingnamespace @import("windows_sdk.zig");...@@ -14,11 +14,11 @@ usingnamespace @import("windows_sdk.zig");
1414
15/// See the render function implementation for documentation of the fields.15/// See the render function implementation for documentation of the fields.
16pub const LibCInstallation = struct {16pub const LibCInstallation = struct {
17 include_dir: ?[:0]const u8 = null,17 include_dir: ?[]const u8 = null,
18 sys_include_dir: ?[:0]const u8 = null,18 sys_include_dir: ?[]const u8 = null,
19 crt_dir: ?[:0]const u8 = null,19 crt_dir: ?[]const u8 = null,
20 msvc_lib_dir: ?[:0]const u8 = null,20 msvc_lib_dir: ?[]const u8 = null,
21 kernel32_lib_dir: ?[:0]const u8 = null,21 kernel32_lib_dir: ?[]const u8 = null,
2222
23 pub const FindError = error{23 pub const FindError = error{
24 OutOfMemory,24 OutOfMemory,
...@@ -54,7 +54,7 @@ pub const LibCInstallation = struct {...@@ -54,7 +54,7 @@ pub const LibCInstallation = struct {
54 }54 }
55 }55 }
5656
57 const contents = try std.io.readFileAlloc(allocator, libc_file);57 const contents = try std.fs.cwd().readFileAlloc(allocator, libc_file, std.math.maxInt(usize));
58 defer allocator.free(contents);58 defer allocator.free(contents);
5959
60 var it = std.mem.tokenize(contents, "\n");60 var it = std.mem.tokenize(contents, "\n");
...@@ -229,7 +229,7 @@ pub const LibCInstallation = struct {...@@ -229,7 +229,7 @@ pub const LibCInstallation = struct {
229 "-xc",229 "-xc",
230 dev_null,230 dev_null,
231 };231 };
232 const exec_res = std.ChildProcess.exec2(.{232 const exec_res = std.ChildProcess.exec(.{
233 .allocator = allocator,233 .allocator = allocator,
234 .argv = &argv,234 .argv = &argv,
235 .max_output_bytes = 1024 * 1024,235 .max_output_bytes = 1024 * 1024,
...@@ -327,15 +327,14 @@ pub const LibCInstallation = struct {...@@ -327,15 +327,14 @@ pub const LibCInstallation = struct {
327 var search_buf: [2]Search = undefined;327 var search_buf: [2]Search = undefined;
328 const searches = fillSearch(&search_buf, sdk);328 const searches = fillSearch(&search_buf, sdk);
329329
330 var result_buf = try std.Buffer.initSize(allocator, 0);330 var result_buf = std.ArrayList(u8).init(allocator);
331 defer result_buf.deinit();331 defer result_buf.deinit();
332332
333 for (searches) |search| {333 for (searches) |search| {
334 result_buf.shrink(0);334 result_buf.shrink(0);
335 const stream = result_buf.outStream();335 try result_buf.outStream().print("{}\\Include\\{}\\ucrt", .{ search.path, search.version });
336 try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version });
337336
338 var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) {337 var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) {
339 error.FileNotFound,338 error.FileNotFound,
340 error.NotDir,339 error.NotDir,
341 error.NoDevice,340 error.NoDevice,
...@@ -367,7 +366,7 @@ pub const LibCInstallation = struct {...@@ -367,7 +366,7 @@ pub const LibCInstallation = struct {
367 var search_buf: [2]Search = undefined;366 var search_buf: [2]Search = undefined;
368 const searches = fillSearch(&search_buf, sdk);367 const searches = fillSearch(&search_buf, sdk);
369368
370 var result_buf = try std.Buffer.initSize(allocator, 0);369 var result_buf = std.ArrayList(u8).init(allocator);
371 defer result_buf.deinit();370 defer result_buf.deinit();
372371
373 const arch_sub_dir = switch (builtin.arch) {372 const arch_sub_dir = switch (builtin.arch) {
...@@ -379,10 +378,9 @@ pub const LibCInstallation = struct {...@@ -379,10 +378,9 @@ pub const LibCInstallation = struct {
379378
380 for (searches) |search| {379 for (searches) |search| {
381 result_buf.shrink(0);380 result_buf.shrink(0);
382 const stream = result_buf.outStream();381 try result_buf.outStream().print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir });
383 try stream.print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir });
384382
385 var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) {383 var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) {
386 error.FileNotFound,384 error.FileNotFound,
387 error.NotDir,385 error.NotDir,
388 error.NoDevice,386 error.NoDevice,
...@@ -422,7 +420,7 @@ pub const LibCInstallation = struct {...@@ -422,7 +420,7 @@ pub const LibCInstallation = struct {
422 var search_buf: [2]Search = undefined;420 var search_buf: [2]Search = undefined;
423 const searches = fillSearch(&search_buf, sdk);421 const searches = fillSearch(&search_buf, sdk);
424422
425 var result_buf = try std.Buffer.initSize(allocator, 0);423 var result_buf = std.ArrayList(u8).init(allocator);
426 defer result_buf.deinit();424 defer result_buf.deinit();
427425
428 const arch_sub_dir = switch (builtin.arch) {426 const arch_sub_dir = switch (builtin.arch) {
...@@ -437,7 +435,7 @@ pub const LibCInstallation = struct {...@@ -437,7 +435,7 @@ pub const LibCInstallation = struct {
437 const stream = result_buf.outStream();435 const stream = result_buf.outStream();
438 try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir });436 try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir });
439437
440 var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) {438 var dir = fs.cwd().openDir(result_buf.span(), .{}) catch |err| switch (err) {
441 error.FileNotFound,439 error.FileNotFound,
442 error.NotDir,440 error.NotDir,
443 error.NoDevice,441 error.NoDevice,
...@@ -470,12 +468,10 @@ pub const LibCInstallation = struct {...@@ -470,12 +468,10 @@ pub const LibCInstallation = struct {
470 const up1 = fs.path.dirname(msvc_lib_dir) orelse return error.LibCStdLibHeaderNotFound;468 const up1 = fs.path.dirname(msvc_lib_dir) orelse return error.LibCStdLibHeaderNotFound;
471 const up2 = fs.path.dirname(up1) orelse return error.LibCStdLibHeaderNotFound;469 const up2 = fs.path.dirname(up1) orelse return error.LibCStdLibHeaderNotFound;
472470
473 var result_buf = try std.Buffer.init(allocator, up2);471 const dir_path = try fs.path.join(allocator, &[_][]const u8{ up2, "include" });
474 defer result_buf.deinit();472 errdefer allocator.free(dir_path);
475
476 try result_buf.append("\\include");
477473
478 var dir = fs.cwd().openDir(result_buf.toSliceConst(), .{}) catch |err| switch (err) {474 var dir = fs.cwd().openDir(dir_path, .{}) catch |err| switch (err) {
479 error.FileNotFound,475 error.FileNotFound,
480 error.NotDir,476 error.NotDir,
481 error.NoDevice,477 error.NoDevice,
...@@ -490,7 +486,7 @@ pub const LibCInstallation = struct {...@@ -490,7 +486,7 @@ pub const LibCInstallation = struct {
490 else => return error.FileSystem,486 else => return error.FileSystem,
491 };487 };
492488
493 self.sys_include_dir = result_buf.toOwnedSlice();489 self.sys_include_dir = dir_path;
494 }490 }
495491
496 fn findNativeMsvcLibDir(492 fn findNativeMsvcLibDir(
...@@ -522,7 +518,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 {...@@ -522,7 +518,7 @@ fn ccPrintFileName(args: CCPrintFileNameOptions) ![:0]u8 {
522 defer allocator.free(arg1);518 defer allocator.free(arg1);
523 const argv = [_][]const u8{ cc_exe, arg1 };519 const argv = [_][]const u8{ cc_exe, arg1 };
524520
525 const exec_res = std.ChildProcess.exec2(.{521 const exec_res = std.ChildProcess.exec(.{
526 .allocator = allocator,522 .allocator = allocator,
527 .argv = &argv,523 .argv = &argv,
528 .max_output_bytes = 1024 * 1024,524 .max_output_bytes = 1024 * 1024,
src-self-hosted/link.zig+12-12
...@@ -15,10 +15,10 @@ const Context = struct {...@@ -15,10 +15,10 @@ const Context = struct {
15 link_in_crt: bool,15 link_in_crt: bool,
1616
17 link_err: error{OutOfMemory}!void,17 link_err: error{OutOfMemory}!void,
18 link_msg: std.Buffer,18 link_msg: std.ArrayListSentineled(u8, 0),
1919
20 libc: *LibCInstallation,20 libc: *LibCInstallation,
21 out_file_path: std.Buffer,21 out_file_path: std.ArrayListSentineled(u8, 0),
22};22};
2323
24pub fn link(comp: *Compilation) !void {24pub fn link(comp: *Compilation) !void {
...@@ -34,9 +34,9 @@ pub fn link(comp: *Compilation) !void {...@@ -34,9 +34,9 @@ pub fn link(comp: *Compilation) !void {
34 };34 };
35 defer ctx.arena.deinit();35 defer ctx.arena.deinit();
36 ctx.args = std.ArrayList([*:0]const u8).init(&ctx.arena.allocator);36 ctx.args = std.ArrayList([*:0]const u8).init(&ctx.arena.allocator);
37 ctx.link_msg = std.Buffer.initNull(&ctx.arena.allocator);37 ctx.link_msg = std.ArrayListSentineled(u8, 0).initNull(&ctx.arena.allocator);
3838
39 ctx.out_file_path = try std.Buffer.init(&ctx.arena.allocator, comp.name.toSliceConst());39 ctx.out_file_path = try std.ArrayListSentineled(u8, 0).init(&ctx.arena.allocator, comp.name.span());
40 switch (comp.kind) {40 switch (comp.kind) {
41 .Exe => {41 .Exe => {
42 try ctx.out_file_path.append(comp.target.exeFileExt());42 try ctx.out_file_path.append(comp.target.exeFileExt());
...@@ -70,7 +70,7 @@ pub fn link(comp: *Compilation) !void {...@@ -70,7 +70,7 @@ pub fn link(comp: *Compilation) !void {
70 try constructLinkerArgs(&ctx);70 try constructLinkerArgs(&ctx);
7171
72 if (comp.verbose_link) {72 if (comp.verbose_link) {
73 for (ctx.args.toSliceConst()) |arg, i| {73 for (ctx.args.span()) |arg, i| {
74 const space = if (i == 0) "" else " ";74 const space = if (i == 0) "" else " ";
75 std.debug.warn("{}{s}", .{ space, arg });75 std.debug.warn("{}{s}", .{ space, arg });
76 }76 }
...@@ -78,7 +78,7 @@ pub fn link(comp: *Compilation) !void {...@@ -78,7 +78,7 @@ pub fn link(comp: *Compilation) !void {
78 }78 }
7979
80 const extern_ofmt = toExternObjectFormatType(comp.target.getObjectFormat());80 const extern_ofmt = toExternObjectFormatType(comp.target.getObjectFormat());
81 const args_slice = ctx.args.toSlice();81 const args_slice = ctx.args.span();
8282
83 {83 {
84 // LLD is not thread-safe, so we grab a global lock.84 // LLD is not thread-safe, so we grab a global lock.
...@@ -91,7 +91,7 @@ pub fn link(comp: *Compilation) !void {...@@ -91,7 +91,7 @@ pub fn link(comp: *Compilation) !void {
91 // TODO capture these messages and pass them through the system, reporting them through the91 // TODO capture these messages and pass them through the system, reporting them through the
92 // event system instead of printing them directly here.92 // event system instead of printing them directly here.
93 // perhaps try to parse and understand them.93 // perhaps try to parse and understand them.
94 std.debug.warn("{}\n", .{ctx.link_msg.toSliceConst()});94 std.debug.warn("{}\n", .{ctx.link_msg.span()});
95 }95 }
96 return error.LinkFailed;96 return error.LinkFailed;
97 }97 }
...@@ -173,7 +173,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void {...@@ -173,7 +173,7 @@ fn constructLinkerArgsElf(ctx: *Context) !void {
173 //}173 //}
174174
175 try ctx.args.append("-o");175 try ctx.args.append("-o");
176 try ctx.args.append(ctx.out_file_path.toSliceConst());176 try ctx.args.append(ctx.out_file_path.span());
177177
178 if (ctx.link_in_crt) {178 if (ctx.link_in_crt) {
179 const crt1o = if (ctx.comp.is_static) "crt1.o" else "Scrt1.o";179 const crt1o = if (ctx.comp.is_static) "crt1.o" else "Scrt1.o";
...@@ -291,7 +291,7 @@ fn constructLinkerArgsCoff(ctx: *Context) !void {...@@ -291,7 +291,7 @@ fn constructLinkerArgsCoff(ctx: *Context) !void {
291291
292 const is_library = ctx.comp.kind == .Lib;292 const is_library = ctx.comp.kind == .Lib;
293293
294 const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", .{ctx.out_file_path.toSliceConst()});294 const out_arg = try std.fmt.allocPrint(&ctx.arena.allocator, "-OUT:{}\x00", .{ctx.out_file_path.span()});
295 try ctx.args.append(@ptrCast([*:0]const u8, out_arg.ptr));295 try ctx.args.append(@ptrCast([*:0]const u8, out_arg.ptr));
296296
297 if (ctx.comp.haveLibC()) {297 if (ctx.comp.haveLibC()) {
...@@ -394,7 +394,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {...@@ -394,7 +394,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
394 }394 }
395395
396 try ctx.args.append("-o");396 try ctx.args.append("-o");
397 try ctx.args.append(ctx.out_file_path.toSliceConst());397 try ctx.args.append(ctx.out_file_path.span());
398398
399 if (shared) {399 if (shared) {
400 try ctx.args.append("-headerpad_max_install_names");400 try ctx.args.append("-headerpad_max_install_names");
...@@ -432,7 +432,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {...@@ -432,7 +432,7 @@ fn constructLinkerArgsMachO(ctx: *Context) !void {
432432
433 // TODO433 // TODO
434 //if (ctx.comp.target == Target.Native) {434 //if (ctx.comp.target == Target.Native) {
435 // for (ctx.comp.link_libs_list.toSliceConst()) |lib| {435 // for (ctx.comp.link_libs_list.span()) |lib| {
436 // if (mem.eql(u8, lib.name, "c")) {436 // if (mem.eql(u8, lib.name, "c")) {
437 // // on Darwin, libSystem has libc in it, but also you have to use it437 // // on Darwin, libSystem has libc in it, but also you have to use it
438 // // to make syscalls because the syscall numbers are not documented438 // // to make syscalls because the syscall numbers are not documented
...@@ -482,7 +482,7 @@ fn addFnObjects(ctx: *Context) !void {...@@ -482,7 +482,7 @@ fn addFnObjects(ctx: *Context) !void {
482 ctx.comp.gpa().destroy(node);482 ctx.comp.gpa().destroy(node);
483 continue;483 continue;
484 };484 };
485 try ctx.args.append(fn_val.containing_object.toSliceConst());485 try ctx.args.append(fn_val.containing_object.span());
486 it = node.next;486 it = node.next;
487 }487 }
488}488}
src-self-hosted/main.zig+7-7
...@@ -421,7 +421,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co...@@ -421,7 +421,7 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
421 process.exit(1);421 process.exit(1);
422 }422 }
423423
424 try ZigCompiler.setLlvmArgv(allocator, mllvm_flags.toSliceConst());424 try ZigCompiler.setLlvmArgv(allocator, mllvm_flags.span());
425425
426 const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch process.exit(1);426 const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch process.exit(1);
427 defer allocator.free(zig_lib_dir);427 defer allocator.free(zig_lib_dir);
...@@ -448,14 +448,14 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co...@@ -448,14 +448,14 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
448 comp.override_libc = &override_libc;448 comp.override_libc = &override_libc;
449 }449 }
450450
451 for (system_libs.toSliceConst()) |lib| {451 for (system_libs.span()) |lib| {
452 _ = try comp.addLinkLib(lib, true);452 _ = try comp.addLinkLib(lib, true);
453 }453 }
454454
455 comp.version = version;455 comp.version = version;
456 comp.is_test = false;456 comp.is_test = false;
457 comp.linker_script = linker_script;457 comp.linker_script = linker_script;
458 comp.clang_argv = clang_argv_buf.toSliceConst();458 comp.clang_argv = clang_argv_buf.span();
459 comp.strip = strip;459 comp.strip = strip;
460460
461 comp.verbose_tokenize = verbose_tokenize;461 comp.verbose_tokenize = verbose_tokenize;
...@@ -488,8 +488,8 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co...@@ -488,8 +488,8 @@ fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Co
488 comp.emit_asm = emit_asm;488 comp.emit_asm = emit_asm;
489 comp.emit_llvm_ir = emit_llvm_ir;489 comp.emit_llvm_ir = emit_llvm_ir;
490 comp.emit_h = emit_h;490 comp.emit_h = emit_h;
491 comp.assembly_files = assembly_files.toSliceConst();491 comp.assembly_files = assembly_files.span();
492 comp.link_objects = link_objects.toSliceConst();492 comp.link_objects = link_objects.span();
493493
494 comp.start();494 comp.start();
495 processBuildEvents(comp, color);495 processBuildEvents(comp, color);
...@@ -683,7 +683,7 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {...@@ -683,7 +683,7 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
683 };683 };
684684
685 var group = event.Group(FmtError!void).init(allocator);685 var group = event.Group(FmtError!void).init(allocator);
686 for (input_files.toSliceConst()) |file_path| {686 for (input_files.span()) |file_path| {
687 try group.call(fmtPath, .{ &fmt, file_path, check_flag });687 try group.call(fmtPath, .{ &fmt, file_path, check_flag });
688 }688 }
689 try group.wait();689 try group.wait();
...@@ -898,7 +898,7 @@ const CliPkg = struct {...@@ -898,7 +898,7 @@ const CliPkg = struct {
898 }898 }
899899
900 pub fn deinit(self: *CliPkg) void {900 pub fn deinit(self: *CliPkg) void {
901 for (self.children.toSliceConst()) |child| {901 for (self.children.span()) |child| {
902 child.deinit();902 child.deinit();
903 }903 }
904 self.children.deinit();904 self.children.deinit();
src-self-hosted/package.zig+5-5
...@@ -1,11 +1,11 @@...@@ -1,11 +1,11 @@
1const std = @import("std");1const std = @import("std");
2const mem = std.mem;2const mem = std.mem;
3const assert = std.debug.assert;3const assert = std.debug.assert;
4const Buffer = std.Buffer;4const ArrayListSentineled = std.ArrayListSentineled;
55
6pub const Package = struct {6pub const Package = struct {
7 root_src_dir: Buffer,7 root_src_dir: ArrayListSentineled(u8, 0),
8 root_src_path: Buffer,8 root_src_path: ArrayListSentineled(u8, 0),
99
10 /// relative to root_src_dir10 /// relative to root_src_dir
11 table: Table,11 table: Table,
...@@ -17,8 +17,8 @@ pub const Package = struct {...@@ -17,8 +17,8 @@ pub const Package = struct {
17 pub fn create(allocator: *mem.Allocator, root_src_dir: []const u8, root_src_path: []const u8) !*Package {17 pub fn create(allocator: *mem.Allocator, root_src_dir: []const u8, root_src_path: []const u8) !*Package {
18 const ptr = try allocator.create(Package);18 const ptr = try allocator.create(Package);
19 ptr.* = Package{19 ptr.* = Package{
20 .root_src_dir = try Buffer.init(allocator, root_src_dir),20 .root_src_dir = try ArrayListSentineled(u8, 0).init(allocator, root_src_dir),
21 .root_src_path = try Buffer.init(allocator, root_src_path),21 .root_src_path = try ArrayListSentineled(u8, 0).init(allocator, root_src_path),
22 .table = Table.init(allocator),22 .table = Table.init(allocator),
23 };23 };
24 return ptr;24 return ptr;
src-self-hosted/stage2.zig+57-55
...@@ -8,7 +8,7 @@ const fs = std.fs;...@@ -8,7 +8,7 @@ const fs = std.fs;
8const process = std.process;8const process = std.process;
9const Allocator = mem.Allocator;9const Allocator = mem.Allocator;
10const ArrayList = std.ArrayList;10const ArrayList = std.ArrayList;
11const Buffer = std.Buffer;11const ArrayListSentineled = std.ArrayListSentineled;
12const Target = std.Target;12const Target = std.Target;
13const CrossTarget = std.zig.CrossTarget;13const CrossTarget = std.zig.CrossTarget;
14const self_hosted_main = @import("main.zig");14const self_hosted_main = @import("main.zig");
...@@ -188,14 +188,14 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {...@@ -188,14 +188,14 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
188 const argc_usize = @intCast(usize, argc);188 const argc_usize = @intCast(usize, argc);
189 var arg_i: usize = 0;189 var arg_i: usize = 0;
190 while (arg_i < argc_usize) : (arg_i += 1) {190 while (arg_i < argc_usize) : (arg_i += 1) {
191 try args_list.append(mem.toSliceConst(u8, argv[arg_i]));191 try args_list.append(mem.spanZ(argv[arg_i]));
192 }192 }
193193
194 stdout = std.io.getStdOut().outStream();194 stdout = std.io.getStdOut().outStream();
195 stderr_file = std.io.getStdErr();195 stderr_file = std.io.getStdErr();
196 stderr = stderr_file.outStream();196 stderr = stderr_file.outStream();
197197
198 const args = args_list.toSliceConst()[2..];198 const args = args_list.span()[2..];
199199
200 var color: errmsg.Color = .Auto;200 var color: errmsg.Color = .Auto;
201 var stdin_flag: bool = false;201 var stdin_flag: bool = false;
...@@ -288,7 +288,7 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {...@@ -288,7 +288,7 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
288 .allocator = allocator,288 .allocator = allocator,
289 };289 };
290290
291 for (input_files.toSliceConst()) |file_path| {291 for (input_files.span()) |file_path| {
292 try fmtPath(&fmt, file_path, check_flag);292 try fmtPath(&fmt, file_path, check_flag);
293 }293 }
294 if (fmt.any_error) {294 if (fmt.any_error) {
...@@ -321,7 +321,8 @@ fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool) FmtError!void {...@@ -321,7 +321,8 @@ fn fmtPath(fmt: *Fmt, file_path: []const u8, check_mode: bool) FmtError!void {
321 if (fmt.seen.exists(file_path)) return;321 if (fmt.seen.exists(file_path)) return;
322 try fmt.seen.put(file_path);322 try fmt.seen.put(file_path);
323323
324 const source_code = io.readFileAlloc(fmt.allocator, file_path) catch |err| switch (err) {324 const max = std.math.maxInt(usize);
325 const source_code = fs.cwd().readFileAlloc(fmt.allocator, file_path, max) catch |err| switch (err) {
325 error.IsDir, error.AccessDenied => {326 error.IsDir, error.AccessDenied => {
326 // TODO make event based (and dir.next())327 // TODO make event based (and dir.next())
327 var dir = try fs.cwd().openDir(file_path, .{ .iterate = true });328 var dir = try fs.cwd().openDir(file_path, .{ .iterate = true });
...@@ -413,12 +414,13 @@ fn printErrMsgToFile(...@@ -413,12 +414,13 @@ fn printErrMsgToFile(
413 const start_loc = tree.tokenLocationPtr(0, first_token);414 const start_loc = tree.tokenLocationPtr(0, first_token);
414 const end_loc = tree.tokenLocationPtr(first_token.end, last_token);415 const end_loc = tree.tokenLocationPtr(first_token.end, last_token);
415416
416 var text_buf = try std.Buffer.initSize(allocator, 0);417 var text_buf = std.ArrayList(u8).init(allocator);
417 const out_stream = &text_buf.outStream();418 defer text_buf.deinit();
419 const out_stream = text_buf.outStream();
418 try parse_error.render(&tree.tokens, out_stream);420 try parse_error.render(&tree.tokens, out_stream);
419 const text = text_buf.toOwnedSlice();421 const text = text_buf.span();
420422
421 const stream = &file.outStream();423 const stream = file.outStream();
422 try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text });424 try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text });
423425
424 if (!color_on) return;426 if (!color_on) return;
...@@ -450,10 +452,10 @@ export fn stage2_DepTokenizer_deinit(self: *stage2_DepTokenizer) void {...@@ -450,10 +452,10 @@ export fn stage2_DepTokenizer_deinit(self: *stage2_DepTokenizer) void {
450452
451export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextResult {453export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextResult {
452 const otoken = self.handle.next() catch {454 const otoken = self.handle.next() catch {
453 const textz = std.Buffer.init(&self.handle.arena.allocator, self.handle.error_text) catch @panic("failed to create .d tokenizer error text");455 const textz = std.ArrayListSentineled(u8, 0).init(&self.handle.arena.allocator, self.handle.error_text) catch @panic("failed to create .d tokenizer error text");
454 return stage2_DepNextResult{456 return stage2_DepNextResult{
455 .type_id = .error_,457 .type_id = .error_,
456 .textz = textz.toSlice().ptr,458 .textz = textz.span().ptr,
457 };459 };
458 };460 };
459 const token = otoken orelse {461 const token = otoken orelse {
...@@ -462,13 +464,13 @@ export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextRes...@@ -462,13 +464,13 @@ export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextRes
462 .textz = undefined,464 .textz = undefined,
463 };465 };
464 };466 };
465 const textz = std.Buffer.init(&self.handle.arena.allocator, token.bytes) catch @panic("failed to create .d tokenizer token text");467 const textz = std.ArrayListSentineled(u8, 0).init(&self.handle.arena.allocator, token.bytes) catch @panic("failed to create .d tokenizer token text");
466 return stage2_DepNextResult{468 return stage2_DepNextResult{
467 .type_id = switch (token.id) {469 .type_id = switch (token.id) {
468 .target => .target,470 .target => .target,
469 .prereq => .prereq,471 .prereq => .prereq,
470 },472 },
471 .textz = textz.toSlice().ptr,473 .textz = textz.span().ptr,
472 };474 };
473}475}
474476
...@@ -575,7 +577,7 @@ fn detectNativeCpuWithLLVM(...@@ -575,7 +577,7 @@ fn detectNativeCpuWithLLVM(
575 var result = Target.Cpu.baseline(arch);577 var result = Target.Cpu.baseline(arch);
576578
577 if (llvm_cpu_name_z) |cpu_name_z| {579 if (llvm_cpu_name_z) |cpu_name_z| {
578 const llvm_cpu_name = mem.toSliceConst(u8, cpu_name_z);580 const llvm_cpu_name = mem.spanZ(cpu_name_z);
579581
580 for (arch.allCpuModels()) |model| {582 for (arch.allCpuModels()) |model| {
581 const this_llvm_name = model.llvm_name orelse continue;583 const this_llvm_name = model.llvm_name orelse continue;
...@@ -596,7 +598,7 @@ fn detectNativeCpuWithLLVM(...@@ -596,7 +598,7 @@ fn detectNativeCpuWithLLVM(
596 const all_features = arch.allFeaturesList();598 const all_features = arch.allFeaturesList();
597599
598 if (llvm_cpu_features_opt) |llvm_cpu_features| {600 if (llvm_cpu_features_opt) |llvm_cpu_features| {
599 var it = mem.tokenize(mem.toSliceConst(u8, llvm_cpu_features), ",");601 var it = mem.tokenize(mem.spanZ(llvm_cpu_features), ",");
600 while (it.next()) |decorated_llvm_feat| {602 while (it.next()) |decorated_llvm_feat| {
601 var op: enum {603 var op: enum {
602 add,604 add,
...@@ -691,12 +693,11 @@ fn stage2CrossTarget(...@@ -691,12 +693,11 @@ fn stage2CrossTarget(
691 mcpu_oz: ?[*:0]const u8,693 mcpu_oz: ?[*:0]const u8,
692 dynamic_linker_oz: ?[*:0]const u8,694 dynamic_linker_oz: ?[*:0]const u8,
693) !CrossTarget {695) !CrossTarget {
694 const zig_triple = if (zig_triple_oz) |zig_triple_z| mem.toSliceConst(u8, zig_triple_z) else "native";696 const mcpu = mem.spanZ(mcpu_oz);
695 const mcpu = if (mcpu_oz) |mcpu_z| mem.toSliceConst(u8, mcpu_z) else null;697 const dynamic_linker = mem.spanZ(dynamic_linker_oz);
696 const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.toSliceConst(u8, dl_z) else null;
697 var diags: CrossTarget.ParseOptions.Diagnostics = .{};698 var diags: CrossTarget.ParseOptions.Diagnostics = .{};
698 const target: CrossTarget = CrossTarget.parse(.{699 const target: CrossTarget = CrossTarget.parse(.{
699 .arch_os_abi = zig_triple,700 .arch_os_abi = mem.spanZ(zig_triple_oz) orelse "native",
700 .cpu_features = mcpu,701 .cpu_features = mcpu,
701 .dynamic_linker = dynamic_linker,702 .dynamic_linker = dynamic_linker,
702 .diagnostics = &diags,703 .diagnostics = &diags,
...@@ -743,15 +744,15 @@ fn stage2TargetParse(...@@ -743,15 +744,15 @@ fn stage2TargetParse(
743744
744// ABI warning745// ABI warning
745const Stage2LibCInstallation = extern struct {746const Stage2LibCInstallation = extern struct {
746 include_dir: [*:0]const u8,747 include_dir: [*]const u8,
747 include_dir_len: usize,748 include_dir_len: usize,
748 sys_include_dir: [*:0]const u8,749 sys_include_dir: [*]const u8,
749 sys_include_dir_len: usize,750 sys_include_dir_len: usize,
750 crt_dir: [*:0]const u8,751 crt_dir: [*]const u8,
751 crt_dir_len: usize,752 crt_dir_len: usize,
752 msvc_lib_dir: [*:0]const u8,753 msvc_lib_dir: [*]const u8,
753 msvc_lib_dir_len: usize,754 msvc_lib_dir_len: usize,
754 kernel32_lib_dir: [*:0]const u8,755 kernel32_lib_dir: [*]const u8,
755 kernel32_lib_dir_len: usize,756 kernel32_lib_dir_len: usize,
756757
757 fn initFromStage2(self: *Stage2LibCInstallation, libc: LibCInstallation) void {758 fn initFromStage2(self: *Stage2LibCInstallation, libc: LibCInstallation) void {
...@@ -795,19 +796,19 @@ const Stage2LibCInstallation = extern struct {...@@ -795,19 +796,19 @@ const Stage2LibCInstallation = extern struct {
795 fn toStage2(self: Stage2LibCInstallation) LibCInstallation {796 fn toStage2(self: Stage2LibCInstallation) LibCInstallation {
796 var libc: LibCInstallation = .{};797 var libc: LibCInstallation = .{};
797 if (self.include_dir_len != 0) {798 if (self.include_dir_len != 0) {
798 libc.include_dir = self.include_dir[0..self.include_dir_len :0];799 libc.include_dir = self.include_dir[0..self.include_dir_len];
799 }800 }
800 if (self.sys_include_dir_len != 0) {801 if (self.sys_include_dir_len != 0) {
801 libc.sys_include_dir = self.sys_include_dir[0..self.sys_include_dir_len :0];802 libc.sys_include_dir = self.sys_include_dir[0..self.sys_include_dir_len];
802 }803 }
803 if (self.crt_dir_len != 0) {804 if (self.crt_dir_len != 0) {
804 libc.crt_dir = self.crt_dir[0..self.crt_dir_len :0];805 libc.crt_dir = self.crt_dir[0..self.crt_dir_len];
805 }806 }
806 if (self.msvc_lib_dir_len != 0) {807 if (self.msvc_lib_dir_len != 0) {
807 libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len :0];808 libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len];
808 }809 }
809 if (self.kernel32_lib_dir_len != 0) {810 if (self.kernel32_lib_dir_len != 0) {
810 libc.kernel32_lib_dir = self.kernel32_lib_dir[0..self.kernel32_lib_dir_len :0];811 libc.kernel32_lib_dir = self.kernel32_lib_dir[0..self.kernel32_lib_dir_len];
811 }812 }
812 return libc;813 return libc;
813 }814 }
...@@ -817,7 +818,7 @@ const Stage2LibCInstallation = extern struct {...@@ -817,7 +818,7 @@ const Stage2LibCInstallation = extern struct {
817export fn stage2_libc_parse(stage1_libc: *Stage2LibCInstallation, libc_file_z: [*:0]const u8) Error {818export fn stage2_libc_parse(stage1_libc: *Stage2LibCInstallation, libc_file_z: [*:0]const u8) Error {
818 stderr_file = std.io.getStdErr();819 stderr_file = std.io.getStdErr();
819 stderr = stderr_file.outStream();820 stderr = stderr_file.outStream();
820 const libc_file = mem.toSliceConst(u8, libc_file_z);821 const libc_file = mem.spanZ(libc_file_z);
821 var libc = LibCInstallation.parse(std.heap.c_allocator, libc_file, stderr) catch |err| switch (err) {822 var libc = LibCInstallation.parse(std.heap.c_allocator, libc_file, stderr) catch |err| switch (err) {
822 error.ParseError => return .SemanticAnalyzeFail,823 error.ParseError => return .SemanticAnalyzeFail,
823 error.DiskQuota => return .DiskQuota,824 error.DiskQuota => return .DiskQuota,
...@@ -929,14 +930,14 @@ const Stage2Target = extern struct {...@@ -929,14 +930,14 @@ const Stage2Target = extern struct {
929 var dynamic_linker: ?[*:0]u8 = null;930 var dynamic_linker: ?[*:0]u8 = null;
930 const target = try crossTargetToTarget(cross_target, &dynamic_linker);931 const target = try crossTargetToTarget(cross_target, &dynamic_linker);
931932
932 var cache_hash = try std.Buffer.allocPrint(allocator, "{}\n{}\n", .{933 var cache_hash = try std.ArrayListSentineled(u8, 0).allocPrint(allocator, "{}\n{}\n", .{
933 target.cpu.model.name,934 target.cpu.model.name,
934 target.cpu.features.asBytes(),935 target.cpu.features.asBytes(),
935 });936 });
936 defer cache_hash.deinit();937 defer cache_hash.deinit();
937938
938 const generic_arch_name = target.cpu.arch.genericName();939 const generic_arch_name = target.cpu.arch.genericName();
939 var cpu_builtin_str_buffer = try std.Buffer.allocPrint(allocator,940 var cpu_builtin_str_buffer = try std.ArrayListSentineled(u8, 0).allocPrint(allocator,
940 \\Cpu{{941 \\Cpu{{
941 \\ .arch = .{},942 \\ .arch = .{},
942 \\ .model = &Target.{}.cpu.{},943 \\ .model = &Target.{}.cpu.{},
...@@ -951,7 +952,7 @@ const Stage2Target = extern struct {...@@ -951,7 +952,7 @@ const Stage2Target = extern struct {
951 });952 });
952 defer cpu_builtin_str_buffer.deinit();953 defer cpu_builtin_str_buffer.deinit();
953954
954 var llvm_features_buffer = try std.Buffer.initSize(allocator, 0);955 var llvm_features_buffer = try std.ArrayListSentineled(u8, 0).initSize(allocator, 0);
955 defer llvm_features_buffer.deinit();956 defer llvm_features_buffer.deinit();
956957
957 // Unfortunately we have to do the work twice, because Clang does not support958 // Unfortunately we have to do the work twice, because Clang does not support
...@@ -966,17 +967,17 @@ const Stage2Target = extern struct {...@@ -966,17 +967,17 @@ const Stage2Target = extern struct {
966967
967 if (feature.llvm_name) |llvm_name| {968 if (feature.llvm_name) |llvm_name| {
968 const plus_or_minus = "-+"[@boolToInt(is_enabled)];969 const plus_or_minus = "-+"[@boolToInt(is_enabled)];
969 try llvm_features_buffer.appendByte(plus_or_minus);970 try llvm_features_buffer.append(plus_or_minus);
970 try llvm_features_buffer.append(llvm_name);971 try llvm_features_buffer.appendSlice(llvm_name);
971 try llvm_features_buffer.append(",");972 try llvm_features_buffer.appendSlice(",");
972 }973 }
973974
974 if (is_enabled) {975 if (is_enabled) {
975 // TODO some kind of "zig identifier escape" function rather than976 // TODO some kind of "zig identifier escape" function rather than
976 // unconditionally using @"" syntax977 // unconditionally using @"" syntax
977 try cpu_builtin_str_buffer.append(" .@\"");978 try cpu_builtin_str_buffer.appendSlice(" .@\"");
978 try cpu_builtin_str_buffer.append(feature.name);979 try cpu_builtin_str_buffer.appendSlice(feature.name);
979 try cpu_builtin_str_buffer.append("\",\n");980 try cpu_builtin_str_buffer.appendSlice("\",\n");
980 }981 }
981 }982 }
982983
...@@ -995,16 +996,16 @@ const Stage2Target = extern struct {...@@ -995,16 +996,16 @@ const Stage2Target = extern struct {
995 },996 },
996 }997 }
997998
998 try cpu_builtin_str_buffer.append(999 try cpu_builtin_str_buffer.appendSlice(
999 \\ }),1000 \\ }),
1000 \\};1001 \\};
1001 \\1002 \\
1002 );1003 );
10031004
1004 assert(mem.endsWith(u8, llvm_features_buffer.toSliceConst(), ","));1005 assert(mem.endsWith(u8, llvm_features_buffer.span(), ","));
1005 llvm_features_buffer.shrink(llvm_features_buffer.len() - 1);1006 llvm_features_buffer.shrink(llvm_features_buffer.len() - 1);
10061007
1007 var os_builtin_str_buffer = try std.Buffer.allocPrint(allocator,1008 var os_builtin_str_buffer = try std.ArrayListSentineled(u8, 0).allocPrint(allocator,
1008 \\Os{{1009 \\Os{{
1009 \\ .tag = .{},1010 \\ .tag = .{},
1010 \\ .version_range = .{{1011 \\ .version_range = .{{
...@@ -1047,7 +1048,7 @@ const Stage2Target = extern struct {...@@ -1047,7 +1048,7 @@ const Stage2Target = extern struct {
1047 .emscripten,1048 .emscripten,
1048 .uefi,1049 .uefi,
1049 .other,1050 .other,
1050 => try os_builtin_str_buffer.append(" .none = {} }\n"),1051 => try os_builtin_str_buffer.appendSlice(" .none = {} }\n"),
10511052
1052 .freebsd,1053 .freebsd,
1053 .macosx,1054 .macosx,
...@@ -1123,10 +1124,10 @@ const Stage2Target = extern struct {...@@ -1123,10 +1124,10 @@ const Stage2Target = extern struct {
1123 @tagName(target.os.version_range.windows.max),1124 @tagName(target.os.version_range.windows.max),
1124 }),1125 }),
1125 }1126 }
1126 try os_builtin_str_buffer.append("};\n");1127 try os_builtin_str_buffer.appendSlice("};\n");
11271128
1128 try cache_hash.append(1129 try cache_hash.appendSlice(
1129 os_builtin_str_buffer.toSlice()[os_builtin_str_ver_start_index..os_builtin_str_buffer.len()],1130 os_builtin_str_buffer.span()[os_builtin_str_ver_start_index..os_builtin_str_buffer.len()],
1130 );1131 );
11311132
1132 const glibc_or_darwin_version = blk: {1133 const glibc_or_darwin_version = blk: {
...@@ -1238,10 +1239,10 @@ fn stage2DetectNativePaths(stage1_paths: *Stage2NativePaths) !void {...@@ -1238,10 +1239,10 @@ fn stage2DetectNativePaths(stage1_paths: *Stage2NativePaths) !void {
1238 var paths = try std.zig.system.NativePaths.detect(std.heap.c_allocator);1239 var paths = try std.zig.system.NativePaths.detect(std.heap.c_allocator);
1239 errdefer paths.deinit();1240 errdefer paths.deinit();
12401241
1241 try convertSlice(paths.include_dirs.toSlice(), &stage1_paths.include_dirs_ptr, &stage1_paths.include_dirs_len);1242 try convertSlice(paths.include_dirs.span(), &stage1_paths.include_dirs_ptr, &stage1_paths.include_dirs_len);
1242 try convertSlice(paths.lib_dirs.toSlice(), &stage1_paths.lib_dirs_ptr, &stage1_paths.lib_dirs_len);1243 try convertSlice(paths.lib_dirs.span(), &stage1_paths.lib_dirs_ptr, &stage1_paths.lib_dirs_len);
1243 try convertSlice(paths.rpaths.toSlice(), &stage1_paths.rpaths_ptr, &stage1_paths.rpaths_len);1244 try convertSlice(paths.rpaths.span(), &stage1_paths.rpaths_ptr, &stage1_paths.rpaths_len);
1244 try convertSlice(paths.warnings.toSlice(), &stage1_paths.warnings_ptr, &stage1_paths.warnings_len);1245 try convertSlice(paths.warnings.span(), &stage1_paths.warnings_ptr, &stage1_paths.warnings_len);
1245}1246}
12461247
1247fn convertSlice(slice: [][:0]u8, ptr: *[*][*:0]u8, len: *usize) !void {1248fn convertSlice(slice: [][:0]u8, ptr: *[*][*:0]u8, len: *usize) !void {
...@@ -1285,18 +1286,19 @@ pub const ClangArgIterator = extern struct {...@@ -1285,18 +1286,19 @@ pub const ClangArgIterator = extern struct {
1285 shared,1286 shared,
1286 rdynamic,1287 rdynamic,
1287 wl,1288 wl,
1288 preprocess,1289 pp_or_asm,
1289 optimize,1290 optimize,
1290 debug,1291 debug,
1291 sanitize,1292 sanitize,
1292 linker_script,1293 linker_script,
1293 verbose_cmds,1294 verbose_cmds,
1294 exceptions,
1295 no_exceptions,
1296 rtti,
1297 no_rtti,
1298 for_linker,1295 for_linker,
1299 linker_input_z,1296 linker_input_z,
1297 lib_dir,
1298 mcpu,
1299 dep_file,
1300 framework_dir,
1301 framework,
1300 };1302 };
13011303
1302 const Args = struct {1304 const Args = struct {
src-self-hosted/test.zig+7-5
...@@ -88,8 +88,7 @@ pub const TestContext = struct {...@@ -88,8 +88,7 @@ pub const TestContext = struct {
88 try std.fs.cwd().makePath(dirname);88 try std.fs.cwd().makePath(dirname);
89 }89 }
9090
91 // TODO async I/O91 try std.fs.cwd().writeFile(file1_path, source);
92 try std.io.writeFile(file1_path, source);
9392
94 var comp = try Compilation.create(93 var comp = try Compilation.create(
95 &self.zig_compiler,94 &self.zig_compiler,
...@@ -122,8 +121,7 @@ pub const TestContext = struct {...@@ -122,8 +121,7 @@ pub const TestContext = struct {
122 try std.fs.cwd().makePath(dirname);121 try std.fs.cwd().makePath(dirname);
123 }122 }
124123
125 // TODO async I/O124 try std.fs.cwd().writeFile(file1_path, source);
126 try std.io.writeFile(file1_path, source);
127125
128 var comp = try Compilation.create(126 var comp = try Compilation.create(
129 &self.zig_compiler,127 &self.zig_compiler,
...@@ -156,7 +154,11 @@ pub const TestContext = struct {...@@ -156,7 +154,11 @@ pub const TestContext = struct {
156 .Ok => {154 .Ok => {
157 const argv = [_][]const u8{exe_file};155 const argv = [_][]const u8{exe_file};
158 // TODO use event loop156 // TODO use event loop
159 const child = try std.ChildProcess.exec(allocator, argv, null, null, 1024 * 1024);157 const child = try std.ChildProcess.exec(.{
158 .allocator = allocator,
159 .argv = argv,
160 .max_output_bytes = 1024 * 1024,
161 });
160 switch (child.term) {162 switch (child.term) {
161 .Exited => |code| {163 .Exited => |code| {
162 if (code != 0) {164 if (code != 0) {
src-self-hosted/translate_c.zig+44-12
...@@ -209,7 +209,7 @@ const Scope = struct {...@@ -209,7 +209,7 @@ const Scope = struct {
209209
210pub const Context = struct {210pub const Context = struct {
211 tree: *ast.Tree,211 tree: *ast.Tree,
212 source_buffer: *std.Buffer,212 source_buffer: *std.ArrayList(u8),
213 err: Error,213 err: Error,
214 source_manager: *ZigClangSourceManager,214 source_manager: *ZigClangSourceManager,
215 decl_table: DeclTable,215 decl_table: DeclTable,
...@@ -235,7 +235,7 @@ pub const Context = struct {...@@ -235,7 +235,7 @@ pub const Context = struct {
235235
236 /// Convert a null-terminated C string to a slice allocated in the arena236 /// Convert a null-terminated C string to a slice allocated in the arena
237 fn str(c: *Context, s: [*:0]const u8) ![]u8 {237 fn str(c: *Context, s: [*:0]const u8) ![]u8 {
238 return mem.dupe(c.a(), u8, mem.toSliceConst(u8, s));238 return mem.dupe(c.a(), u8, mem.spanZ(s));
239 }239 }
240240
241 /// Convert a clang source location to a file:line:column string241 /// Convert a clang source location to a file:line:column string
...@@ -275,7 +275,7 @@ pub fn translate(...@@ -275,7 +275,7 @@ pub fn translate(
275275
276 const tree = try tree_arena.allocator.create(ast.Tree);276 const tree = try tree_arena.allocator.create(ast.Tree);
277 tree.* = ast.Tree{277 tree.* = ast.Tree{
278 .source = undefined, // need to use Buffer.toOwnedSlice later278 .source = undefined, // need to use toOwnedSlice later
279 .root_node = undefined,279 .root_node = undefined,
280 .arena_allocator = tree_arena,280 .arena_allocator = tree_arena,
281 .tokens = undefined, // can't reference the allocator yet281 .tokens = undefined, // can't reference the allocator yet
...@@ -296,7 +296,7 @@ pub fn translate(...@@ -296,7 +296,7 @@ pub fn translate(
296 .eof_token = undefined,296 .eof_token = undefined,
297 };297 };
298298
299 var source_buffer = try std.Buffer.initSize(arena, 0);299 var source_buffer = std.ArrayList(u8).init(arena);
300300
301 var context = Context{301 var context = Context{
302 .tree = tree,302 .tree = tree,
...@@ -3845,7 +3845,9 @@ fn transCreateNodePtrType(...@@ -3845,7 +3845,9 @@ fn transCreateNodePtrType(
3845}3845}
38463846
3847fn transCreateNodeAPInt(c: *Context, int: *const ZigClangAPSInt) !*ast.Node {3847fn transCreateNodeAPInt(c: *Context, int: *const ZigClangAPSInt) !*ast.Node {
3848 const num_limbs = ZigClangAPSInt_getNumWords(int);3848 const num_limbs = math.cast(usize, ZigClangAPSInt_getNumWords(int)) catch |err| switch (err) {
3849 error.Overflow => return error.OutOfMemory,
3850 };
3849 var aps_int = int;3851 var aps_int = int;
3850 const is_negative = ZigClangAPSInt_isSigned(int) and ZigClangAPSInt_isNegative(int);3852 const is_negative = ZigClangAPSInt_isSigned(int) and ZigClangAPSInt_isNegative(int);
3851 if (is_negative)3853 if (is_negative)
...@@ -3855,8 +3857,26 @@ fn transCreateNodeAPInt(c: *Context, int: *const ZigClangAPSInt) !*ast.Node {...@@ -3855,8 +3857,26 @@ fn transCreateNodeAPInt(c: *Context, int: *const ZigClangAPSInt) !*ast.Node {
3855 big.negate();3857 big.negate();
3856 defer big.deinit();3858 defer big.deinit();
3857 const data = ZigClangAPSInt_getRawData(aps_int);3859 const data = ZigClangAPSInt_getRawData(aps_int);
3858 var i: @TypeOf(num_limbs) = 0;3860 switch (@sizeOf(std.math.big.Limb)) {
3859 while (i < num_limbs) : (i += 1) big.limbs[i] = data[i];3861 8 => {
3862 var i: usize = 0;
3863 while (i < num_limbs) : (i += 1) {
3864 big.limbs[i] = data[i];
3865 }
3866 },
3867 4 => {
3868 var limb_i: usize = 0;
3869 var data_i: usize = 0;
3870 while (limb_i < num_limbs) : ({
3871 limb_i += 2;
3872 data_i += 1;
3873 }) {
3874 big.limbs[limb_i] = @truncate(u32, data[data_i]);
3875 big.limbs[limb_i + 1] = @truncate(u32, data[data_i] >> 32);
3876 }
3877 },
3878 else => @compileError("unimplemented"),
3879 }
3860 const str = big.toString(c.a(), 10) catch |err| switch (err) {3880 const str = big.toString(c.a(), 10) catch |err| switch (err) {
3861 error.OutOfMemory => return error.OutOfMemory,3881 error.OutOfMemory => return error.OutOfMemory,
3862 else => unreachable,3882 else => unreachable,
...@@ -4289,7 +4309,7 @@ fn makeRestorePoint(c: *Context) RestorePoint {...@@ -4289,7 +4309,7 @@ fn makeRestorePoint(c: *Context) RestorePoint {
4289 return RestorePoint{4309 return RestorePoint{
4290 .c = c,4310 .c = c,
4291 .token_index = c.tree.tokens.len,4311 .token_index = c.tree.tokens.len,
4292 .src_buf_index = c.source_buffer.len(),4312 .src_buf_index = c.source_buffer.len,
4293 };4313 };
4294}4314}
42954315
...@@ -4751,11 +4771,11 @@ fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenInd...@@ -4751,11 +4771,11 @@ fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenInd
47514771
4752fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex {4772fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex {
4753 assert(token_id != .Invalid);4773 assert(token_id != .Invalid);
4754 const start_index = c.source_buffer.len();4774 const start_index = c.source_buffer.len;
4755 errdefer c.source_buffer.shrink(start_index);4775 errdefer c.source_buffer.shrink(start_index);
47564776
4757 try c.source_buffer.outStream().print(format, args);4777 try c.source_buffer.outStream().print(format, args);
4758 const end_index = c.source_buffer.len();4778 const end_index = c.source_buffer.len;
4759 const token_index = c.tree.tokens.len;4779 const token_index = c.tree.tokens.len;
4760 const new_token = try c.tree.tokens.addOne();4780 const new_token = try c.tree.tokens.addOne();
4761 errdefer c.tree.tokens.shrink(token_index);4781 errdefer c.tree.tokens.shrink(token_index);
...@@ -4765,7 +4785,7 @@ fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8,...@@ -4765,7 +4785,7 @@ fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8,
4765 .start = start_index,4785 .start = start_index,
4766 .end = end_index,4786 .end = end_index,
4767 };4787 };
4768 try c.source_buffer.appendByte(' ');4788 try c.source_buffer.append(' ');
47694789
4770 return token_index;4790 return token_index;
4771}4791}
...@@ -5782,6 +5802,18 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5782,6 +5802,18 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5782 op_id = .Mod;5802 op_id = .Mod;
5783 op_token = try appendToken(c, .Percent, "%");5803 op_token = try appendToken(c, .Percent, "%");
5784 },5804 },
5805 .StringLiteral => {
5806 op_id = .ArrayCat;
5807 op_token = try appendToken(c, .PlusPlus, "++");
5808
5809 _ = it.prev();
5810 },
5811 .Identifier => {
5812 op_id = .ArrayCat;
5813 op_token = try appendToken(c, .PlusPlus, "++");
5814
5815 _ = it.prev();
5816 },
5785 else => {5817 else => {
5786 _ = it.prev();5818 _ = it.prev();
5787 return node;5819 return node;
...@@ -5839,7 +5871,7 @@ fn parseCPrefixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5839,7 +5871,7 @@ fn parseCPrefixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
58395871
5840fn tokenSlice(c: *Context, token: ast.TokenIndex) []u8 {5872fn tokenSlice(c: *Context, token: ast.TokenIndex) []u8 {
5841 const tok = c.tree.tokens.at(token);5873 const tok = c.tree.tokens.at(token);
5842 const slice = c.source_buffer.toSlice()[tok.start..tok.end];5874 const slice = c.source_buffer.span()[tok.start..tok.end];
5843 return if (mem.startsWith(u8, slice, "@\""))5875 return if (mem.startsWith(u8, slice, "@\""))
5844 slice[2 .. slice.len - 1]5876 slice[2 .. slice.len - 1]
5845 else5877 else
src-self-hosted/type.zig+2-2
...@@ -387,10 +387,10 @@ pub const Type = struct {...@@ -387,10 +387,10 @@ pub const Type = struct {
387 };387 };
388 errdefer comp.gpa().destroy(self);388 errdefer comp.gpa().destroy(self);
389389
390 var name_buf = try std.Buffer.initSize(comp.gpa(), 0);390 var name_buf = std.ArrayList(u8).init(comp.gpa());
391 defer name_buf.deinit();391 defer name_buf.deinit();
392392
393 const name_stream = &std.io.BufferOutStream.init(&name_buf).stream;393 const name_stream = name_buf.outStream();
394394
395 switch (key.data) {395 switch (key.data) {
396 .Generic => |generic| {396 .Generic => |generic| {
src-self-hosted/util.zig+7-7
...@@ -16,11 +16,11 @@ pub fn getDarwinArchString(self: Target) [:0]const u8 {...@@ -16,11 +16,11 @@ pub fn getDarwinArchString(self: Target) [:0]const u8 {
16 }16 }
17}17}
1818
19pub fn llvmTargetFromTriple(triple: std.Buffer) !*llvm.Target {19pub fn llvmTargetFromTriple(triple: [:0]const u8) !*llvm.Target {
20 var result: *llvm.Target = undefined;20 var result: *llvm.Target = undefined;
21 var err_msg: [*:0]u8 = undefined;21 var err_msg: [*:0]u8 = undefined;
22 if (llvm.GetTargetFromTriple(triple.toSlice(), &result, &err_msg) != 0) {22 if (llvm.GetTargetFromTriple(triple, &result, &err_msg) != 0) {
23 std.debug.warn("triple: {s} error: {s}\n", .{ triple.toSlice(), err_msg });23 std.debug.warn("triple: {s} error: {s}\n", .{ triple, err_msg });
24 return error.UnsupportedTarget;24 return error.UnsupportedTarget;
25 }25 }
26 return result;26 return result;
...@@ -34,14 +34,14 @@ pub fn initializeAllTargets() void {...@@ -34,14 +34,14 @@ pub fn initializeAllTargets() void {
34 llvm.InitializeAllAsmParsers();34 llvm.InitializeAllAsmParsers();
35}35}
3636
37pub fn getLLVMTriple(allocator: *std.mem.Allocator, target: std.Target) !std.Buffer {37pub fn getLLVMTriple(allocator: *std.mem.Allocator, target: std.Target) ![:0]u8 {
38 var result = try std.Buffer.initSize(allocator, 0);38 var result = try std.ArrayListSentineled(u8, 0).initSize(allocator, 0);
39 errdefer result.deinit();39 defer result.deinit();
4040
41 try result.outStream().print(41 try result.outStream().print(
42 "{}-unknown-{}-{}",42 "{}-unknown-{}-{}",
43 .{ @tagName(target.cpu.arch), @tagName(target.os.tag), @tagName(target.abi) },43 .{ @tagName(target.cpu.arch), @tagName(target.os.tag), @tagName(target.abi) },
44 );44 );
4545
46 return result;46 return result.toOwnedSlice();
47}47}
src-self-hosted/value.zig+9-9
...@@ -3,7 +3,7 @@ const Scope = @import("scope.zig").Scope;...@@ -3,7 +3,7 @@ const Scope = @import("scope.zig").Scope;
3const Compilation = @import("compilation.zig").Compilation;3const Compilation = @import("compilation.zig").Compilation;
4const ObjectFile = @import("codegen.zig").ObjectFile;4const ObjectFile = @import("codegen.zig").ObjectFile;
5const llvm = @import("llvm.zig");5const llvm = @import("llvm.zig");
6const Buffer = std.Buffer;6const ArrayListSentineled = std.ArrayListSentineled;
7const assert = std.debug.assert;7const assert = std.debug.assert;
88
9/// Values are ref-counted, heap-allocated, and copy-on-write9/// Values are ref-counted, heap-allocated, and copy-on-write
...@@ -131,9 +131,9 @@ pub const Value = struct {...@@ -131,9 +131,9 @@ pub const Value = struct {
131131
132 /// The main external name that is used in the .o file.132 /// The main external name that is used in the .o file.
133 /// TODO https://github.com/ziglang/zig/issues/265133 /// TODO https://github.com/ziglang/zig/issues/265
134 symbol_name: Buffer,134 symbol_name: ArrayListSentineled(u8, 0),
135135
136 pub fn create(comp: *Compilation, fn_type: *Type.Fn, symbol_name: Buffer) !*FnProto {136 pub fn create(comp: *Compilation, fn_type: *Type.Fn, symbol_name: ArrayListSentineled(u8, 0)) !*FnProto {
137 const self = try comp.gpa().create(FnProto);137 const self = try comp.gpa().create(FnProto);
138 self.* = FnProto{138 self.* = FnProto{
139 .base = Value{139 .base = Value{
...@@ -156,7 +156,7 @@ pub const Value = struct {...@@ -156,7 +156,7 @@ pub const Value = struct {
156 const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);156 const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
157 const llvm_fn = llvm.AddFunction(157 const llvm_fn = llvm.AddFunction(
158 ofile.module,158 ofile.module,
159 self.symbol_name.toSliceConst(),159 self.symbol_name.span(),
160 llvm_fn_type,160 llvm_fn_type,
161 ) orelse return error.OutOfMemory;161 ) orelse return error.OutOfMemory;
162162
...@@ -171,7 +171,7 @@ pub const Value = struct {...@@ -171,7 +171,7 @@ pub const Value = struct {
171171
172 /// The main external name that is used in the .o file.172 /// The main external name that is used in the .o file.
173 /// TODO https://github.com/ziglang/zig/issues/265173 /// TODO https://github.com/ziglang/zig/issues/265
174 symbol_name: Buffer,174 symbol_name: ArrayListSentineled(u8, 0),
175175
176 /// parent should be the top level decls or container decls176 /// parent should be the top level decls or container decls
177 fndef_scope: *Scope.FnDef,177 fndef_scope: *Scope.FnDef,
...@@ -183,13 +183,13 @@ pub const Value = struct {...@@ -183,13 +183,13 @@ pub const Value = struct {
183 block_scope: ?*Scope.Block,183 block_scope: ?*Scope.Block,
184184
185 /// Path to the object file that contains this function185 /// Path to the object file that contains this function
186 containing_object: Buffer,186 containing_object: ArrayListSentineled(u8, 0),
187187
188 link_set_node: *std.TailQueue(?*Value.Fn).Node,188 link_set_node: *std.TailQueue(?*Value.Fn).Node,
189189
190 /// Creates a Fn value with 1 ref190 /// Creates a Fn value with 1 ref
191 /// Takes ownership of symbol_name191 /// Takes ownership of symbol_name
192 pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: Buffer) !*Fn {192 pub fn create(comp: *Compilation, fn_type: *Type.Fn, fndef_scope: *Scope.FnDef, symbol_name: ArrayListSentineled(u8, 0)) !*Fn {
193 const link_set_node = try comp.gpa().create(Compilation.FnLinkSet.Node);193 const link_set_node = try comp.gpa().create(Compilation.FnLinkSet.Node);
194 link_set_node.* = Compilation.FnLinkSet.Node{194 link_set_node.* = Compilation.FnLinkSet.Node{
195 .data = null,195 .data = null,
...@@ -209,7 +209,7 @@ pub const Value = struct {...@@ -209,7 +209,7 @@ pub const Value = struct {
209 .child_scope = &fndef_scope.base,209 .child_scope = &fndef_scope.base,
210 .block_scope = null,210 .block_scope = null,
211 .symbol_name = symbol_name,211 .symbol_name = symbol_name,
212 .containing_object = Buffer.initNull(comp.gpa()),212 .containing_object = ArrayListSentineled(u8, 0).initNull(comp.gpa()),
213 .link_set_node = link_set_node,213 .link_set_node = link_set_node,
214 };214 };
215 fn_type.base.base.ref();215 fn_type.base.base.ref();
...@@ -241,7 +241,7 @@ pub const Value = struct {...@@ -241,7 +241,7 @@ pub const Value = struct {
241 const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);241 const llvm_fn_type = try self.base.typ.getLlvmType(ofile.arena, ofile.context);
242 const llvm_fn = llvm.AddFunction(242 const llvm_fn = llvm.AddFunction(
243 ofile.module,243 ofile.module,
244 self.symbol_name.toSliceConst(),244 self.symbol_name.span(),
245 llvm_fn_type,245 llvm_fn_type,
246 ) orelse return error.OutOfMemory;246 ) orelse return error.OutOfMemory;
247247
src/all_types.hpp+30-4
...@@ -54,6 +54,16 @@ struct ResultLocCast;...@@ -54,6 +54,16 @@ struct ResultLocCast;
54struct ResultLocReturn;54struct ResultLocReturn;
55struct IrExecutableGen;55struct IrExecutableGen;
5656
57enum FileExt {
58 FileExtUnknown,
59 FileExtAsm,
60 FileExtC,
61 FileExtCpp,
62 FileExtHeader,
63 FileExtLLVMIr,
64 FileExtLLVMBitCode,
65};
66
57enum PtrLen {67enum PtrLen {
58 PtrLenUnknown,68 PtrLenUnknown,
59 PtrLenSingle,69 PtrLenSingle,
...@@ -1324,6 +1334,7 @@ struct ZigTypeFloat {...@@ -1324,6 +1334,7 @@ struct ZigTypeFloat {
1324 size_t bit_count;1334 size_t bit_count;
1325};1335};
13261336
1337// Needs to have the same memory layout as ZigTypeVector
1327struct ZigTypeArray {1338struct ZigTypeArray {
1328 ZigType *child_type;1339 ZigType *child_type;
1329 uint64_t len;1340 uint64_t len;
...@@ -1512,12 +1523,17 @@ struct ZigTypeBoundFn {...@@ -1512,12 +1523,17 @@ struct ZigTypeBoundFn {
1512 ZigType *fn_type;1523 ZigType *fn_type;
1513};1524};
15141525
1526// Needs to have the same memory layout as ZigTypeArray
1515struct ZigTypeVector {1527struct ZigTypeVector {
1516 // The type must be a pointer, integer, bool, or float1528 // The type must be a pointer, integer, bool, or float
1517 ZigType *elem_type;1529 ZigType *elem_type;
1518 uint32_t len;1530 uint64_t len;
1531 size_t padding;
1519};1532};
15201533
1534// A lot of code is relying on ZigTypeArray and ZigTypeVector having the same layout/size
1535static_assert(sizeof(ZigTypeVector) == sizeof(ZigTypeArray), "Size of ZigTypeVector and ZigTypeArray do not match!");
1536
1521enum ZigTypeId {1537enum ZigTypeId {
1522 ZigTypeIdInvalid,1538 ZigTypeIdInvalid,
1523 ZigTypeIdMetaType,1539 ZigTypeIdMetaType,
...@@ -1999,6 +2015,12 @@ enum WantCSanitize {...@@ -1999,6 +2015,12 @@ enum WantCSanitize {
1999 WantCSanitizeEnabled,2015 WantCSanitizeEnabled,
2000};2016};
20012017
2018enum OptionalBool {
2019 OptionalBoolNull,
2020 OptionalBoolFalse,
2021 OptionalBoolTrue,
2022};
2023
2002struct CFile {2024struct CFile {
2003 ZigList<const char *> args;2025 ZigList<const char *> args;
2004 const char *source_path;2026 const char *source_path;
...@@ -2214,6 +2236,7 @@ struct CodeGen {...@@ -2214,6 +2236,7 @@ struct CodeGen {
2214 bool reported_bad_link_libc_error;2236 bool reported_bad_link_libc_error;
2215 bool is_dynamic; // shared library rather than static library. dynamic musl rather than static musl.2237 bool is_dynamic; // shared library rather than static library. dynamic musl rather than static musl.
2216 bool need_frame_size_prefix_data;2238 bool need_frame_size_prefix_data;
2239 bool disable_c_depfile;
22172240
2218 //////////////////////////// Participates in Input Parameter Cache Hash2241 //////////////////////////// Participates in Input Parameter Cache Hash
2219 /////// Note: there is a separate cache hash for builtin.zig, when adding fields,2242 /////// Note: there is a separate cache hash for builtin.zig, when adding fields,
...@@ -2242,6 +2265,9 @@ struct CodeGen {...@@ -2242,6 +2265,9 @@ struct CodeGen {
2242 const ZigTarget *zig_target;2265 const ZigTarget *zig_target;
2243 TargetSubsystem subsystem; // careful using this directly; see detect_subsystem2266 TargetSubsystem subsystem; // careful using this directly; see detect_subsystem
2244 ValgrindSupport valgrind_support;2267 ValgrindSupport valgrind_support;
2268 CodeModel code_model;
2269 OptionalBool linker_gc_sections;
2270 OptionalBool linker_allow_shlib_undefined;
2245 bool strip_debug_symbols;2271 bool strip_debug_symbols;
2246 bool is_test_build;2272 bool is_test_build;
2247 bool is_single_threaded;2273 bool is_single_threaded;
...@@ -2262,9 +2288,8 @@ struct CodeGen {...@@ -2262,9 +2288,8 @@ struct CodeGen {
2262 bool emit_asm;2288 bool emit_asm;
2263 bool emit_llvm_ir;2289 bool emit_llvm_ir;
2264 bool test_is_evented;2290 bool test_is_evented;
2265 bool cpp_rtti;2291 bool linker_z_nodelete;
2266 bool cpp_exceptions;2292 bool linker_z_defs;
2267 CodeModel code_model;
22682293
2269 Buf *root_out_name;2294 Buf *root_out_name;
2270 Buf *test_filter;2295 Buf *test_filter;
...@@ -2273,6 +2298,7 @@ struct CodeGen {...@@ -2273,6 +2298,7 @@ struct CodeGen {
2273 Buf *zig_std_dir;2298 Buf *zig_std_dir;
2274 Buf *version_script_path;2299 Buf *version_script_path;
2275 Buf *override_soname;2300 Buf *override_soname;
2301 Buf *linker_optimization;
22762302
2277 const char **llvm_argv;2303 const char **llvm_argv;
2278 size_t llvm_argv_len;2304 size_t llvm_argv_len;
src/analyze.cpp+7-4
...@@ -363,6 +363,7 @@ bool type_is_resolved(ZigType *type_entry, ResolveStatus status) {...@@ -363,6 +363,7 @@ bool type_is_resolved(ZigType *type_entry, ResolveStatus status) {
363 case ResolveStatusLLVMFull:363 case ResolveStatusLLVMFull:
364 return type_entry->llvm_type != nullptr;364 return type_entry->llvm_type != nullptr;
365 }365 }
366 zig_unreachable();
366 case ZigTypeIdOpaque:367 case ZigTypeIdOpaque:
367 return status < ResolveStatusSizeKnown;368 return status < ResolveStatusSizeKnown;
368 case ZigTypeIdPointer:369 case ZigTypeIdPointer:
...@@ -381,6 +382,7 @@ bool type_is_resolved(ZigType *type_entry, ResolveStatus status) {...@@ -381,6 +382,7 @@ bool type_is_resolved(ZigType *type_entry, ResolveStatus status) {
381 case ResolveStatusLLVMFull:382 case ResolveStatusLLVMFull:
382 return type_entry->llvm_type != nullptr;383 return type_entry->llvm_type != nullptr;
383 }384 }
385 zig_unreachable();
384 case ZigTypeIdMetaType:386 case ZigTypeIdMetaType:
385 case ZigTypeIdVoid:387 case ZigTypeIdVoid:
386 case ZigTypeIdBool:388 case ZigTypeIdBool:
...@@ -5156,6 +5158,7 @@ ZigType *get_vector_type(CodeGen *g, uint32_t len, ZigType *elem_type) {...@@ -5156,6 +5158,7 @@ ZigType *get_vector_type(CodeGen *g, uint32_t len, ZigType *elem_type) {
5156 }5158 }
5157 entry->data.vector.len = len;5159 entry->data.vector.len = len;
5158 entry->data.vector.elem_type = elem_type;5160 entry->data.vector.elem_type = elem_type;
5161 entry->data.vector.padding = 0;
51595162
5160 buf_resize(&entry->name, 0);5163 buf_resize(&entry->name, 0);
5161 buf_appendf(&entry->name, "@Vector(%u, %s)", len, buf_ptr(&elem_type->name));5164 buf_appendf(&entry->name, "@Vector(%u, %s)", len, buf_ptr(&elem_type->name));
...@@ -5358,7 +5361,7 @@ static uint32_t hash_const_val(ZigValue *const_val) {...@@ -5358,7 +5361,7 @@ static uint32_t hash_const_val(ZigValue *const_val) {
5358 return result;5361 return result;
5359 }5362 }
5360 case ZigTypeIdEnumLiteral:5363 case ZigTypeIdEnumLiteral:
5361 return buf_hash(const_val->data.x_enum_literal) * 2691276464;5364 return buf_hash(const_val->data.x_enum_literal) * (uint32_t)2691276464;
5362 case ZigTypeIdEnum:5365 case ZigTypeIdEnum:
5363 {5366 {
5364 uint32_t result = 31643936;5367 uint32_t result = 31643936;
...@@ -5426,12 +5429,12 @@ static uint32_t hash_const_val(ZigValue *const_val) {...@@ -5426,12 +5429,12 @@ static uint32_t hash_const_val(ZigValue *const_val) {
5426 return 2709806591;5429 return 2709806591;
5427 case ZigTypeIdOptional:5430 case ZigTypeIdOptional:
5428 if (get_src_ptr_type(const_val->type) != nullptr) {5431 if (get_src_ptr_type(const_val->type) != nullptr) {
5429 return hash_const_val_ptr(const_val) * 1992916303;5432 return hash_const_val_ptr(const_val) * (uint32_t)1992916303;
5430 } else if (const_val->type->data.maybe.child_type->id == ZigTypeIdErrorSet) {5433 } else if (const_val->type->data.maybe.child_type->id == ZigTypeIdErrorSet) {
5431 return hash_const_val_error_set(const_val) * 3147031929;5434 return hash_const_val_error_set(const_val) * (uint32_t)3147031929;
5432 } else {5435 } else {
5433 if (const_val->data.x_optional) {5436 if (const_val->data.x_optional) {
5434 return hash_const_val(const_val->data.x_optional) * 1992916303;5437 return hash_const_val(const_val->data.x_optional) * (uint32_t)1992916303;
5435 } else {5438 } else {
5436 return 4016830364;5439 return 4016830364;
5437 }5440 }
src/analyze.hpp+1-7
...@@ -257,14 +257,8 @@ Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose...@@ -257,14 +257,8 @@ Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose
257LLVMTypeRef get_llvm_type(CodeGen *g, ZigType *type);257LLVMTypeRef get_llvm_type(CodeGen *g, ZigType *type);
258ZigLLVMDIType *get_llvm_di_type(CodeGen *g, ZigType *type);258ZigLLVMDIType *get_llvm_di_type(CodeGen *g, ZigType *type);
259259
260enum CSourceKind {
261 CSourceKindAsm,
262 CSourceKindC,
263 CSourceKindCpp,
264};
265
266void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_path, bool translate_c,260void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_path, bool translate_c,
267 CSourceKind source_kind);261 FileExt source_kind);
268262
269void src_assert(bool ok, AstNode *source_node);263void src_assert(bool ok, AstNode *source_node);
270bool is_container(ZigType *type_entry);264bool is_container(ZigType *type_entry);
src/bigint.cpp+1-1
...@@ -1430,7 +1430,7 @@ void bigint_shr(BigInt *dest, const BigInt *op1, const BigInt *op2) {...@@ -1430,7 +1430,7 @@ void bigint_shr(BigInt *dest, const BigInt *op1, const BigInt *op2) {
1430 uint64_t digit = op1_digits[op_digit_index];1430 uint64_t digit = op1_digits[op_digit_index];
1431 size_t dest_digit_index = op_digit_index - digit_shift_count;1431 size_t dest_digit_index = op_digit_index - digit_shift_count;
1432 digits[dest_digit_index] = carry | (digit >> leftover_shift_count);1432 digits[dest_digit_index] = carry | (digit >> leftover_shift_count);
1433 carry = digit << (64 - leftover_shift_count);1433 carry = (leftover_shift_count != 0) ? (digit << (64 - leftover_shift_count)) : 0;
14341434
1435 if (dest_digit_index == 0) { break; }1435 if (dest_digit_index == 0) { break; }
1436 op_digit_index -= 1;1436 op_digit_index -= 1;
src/buffer.hpp+1-4
...@@ -178,10 +178,7 @@ static inline bool buf_starts_with_str(Buf *buf, const char *str) {...@@ -178,10 +178,7 @@ static inline bool buf_starts_with_str(Buf *buf, const char *str) {
178}178}
179179
180static inline bool buf_ends_with_mem(Buf *buf, const char *mem, size_t mem_len) {180static inline bool buf_ends_with_mem(Buf *buf, const char *mem, size_t mem_len) {
181 if (buf_len(buf) < mem_len) {181 return mem_ends_with_mem(buf_ptr(buf), buf_len(buf), mem, mem_len);
182 return false;
183 }
184 return memcmp(buf_ptr(buf) + buf_len(buf) - mem_len, mem, mem_len) == 0;
185}182}
186183
187static inline bool buf_ends_with_str(Buf *buf, const char *str) {184static inline bool buf_ends_with_str(Buf *buf, const char *str) {
src/cache_hash.cpp+7-1
...@@ -27,11 +27,17 @@ void cache_init(CacheHash *ch, Buf *manifest_dir) {...@@ -27,11 +27,17 @@ void cache_init(CacheHash *ch, Buf *manifest_dir) {
27void cache_mem(CacheHash *ch, const char *ptr, size_t len) {27void cache_mem(CacheHash *ch, const char *ptr, size_t len) {
28 assert(ch->manifest_file_path == nullptr);28 assert(ch->manifest_file_path == nullptr);
29 assert(ptr != nullptr);29 assert(ptr != nullptr);
30 // + 1 to include the null byte
31 blake2b_update(&ch->blake, ptr, len);30 blake2b_update(&ch->blake, ptr, len);
32}31}
3332
33void cache_slice(CacheHash *ch, Slice<const char> slice) {
34 // mix the length into the hash so that two juxtaposed cached slices can't collide
35 cache_usize(ch, slice.len);
36 cache_mem(ch, slice.ptr, slice.len);
37}
38
34void cache_str(CacheHash *ch, const char *ptr) {39void cache_str(CacheHash *ch, const char *ptr) {
40 // + 1 to include the null byte
35 cache_mem(ch, ptr, strlen(ptr) + 1);41 cache_mem(ch, ptr, strlen(ptr) + 1);
36}42}
3743
src/cache_hash.hpp+1
...@@ -36,6 +36,7 @@ void cache_init(CacheHash *ch, Buf *manifest_dir);...@@ -36,6 +36,7 @@ void cache_init(CacheHash *ch, Buf *manifest_dir);
3636
37// Next, use the hash population functions to add the initial parameters.37// Next, use the hash population functions to add the initial parameters.
38void cache_mem(CacheHash *ch, const char *ptr, size_t len);38void cache_mem(CacheHash *ch, const char *ptr, size_t len);
39void cache_slice(CacheHash *ch, Slice<const char> slice);
39void cache_str(CacheHash *ch, const char *ptr);40void cache_str(CacheHash *ch, const char *ptr);
40void cache_int(CacheHash *ch, int x);41void cache_int(CacheHash *ch, int x);
41void cache_bool(CacheHash *ch, bool x);42void cache_bool(CacheHash *ch, bool x);
src/codegen.cpp+82-89
...@@ -714,7 +714,7 @@ static LLVMValueRef get_arithmetic_overflow_fn(CodeGen *g, ZigType *operand_type...@@ -714,7 +714,7 @@ static LLVMValueRef get_arithmetic_overflow_fn(CodeGen *g, ZigType *operand_type
714 };714 };
715715
716 if (operand_type->id == ZigTypeIdVector) {716 if (operand_type->id == ZigTypeIdVector) {
717 sprintf(fn_name, "llvm.%s.with.overflow.v%" PRIu32 "i%" PRIu32, signed_str,717 sprintf(fn_name, "llvm.%s.with.overflow.v%" PRIu64 "i%" PRIu32, signed_str,
718 operand_type->data.vector.len, int_type->data.integral.bit_count);718 operand_type->data.vector.len, int_type->data.integral.bit_count);
719719
720 LLVMTypeRef return_elem_types[] = {720 LLVMTypeRef return_elem_types[] = {
...@@ -3954,8 +3954,9 @@ static void render_async_var_decls(CodeGen *g, Scope *scope) {...@@ -3954,8 +3954,9 @@ static void render_async_var_decls(CodeGen *g, Scope *scope) {
3954 if (var->did_the_decl_codegen) {3954 if (var->did_the_decl_codegen) {
3955 render_decl_var(g, var);3955 render_decl_var(g, var);
3956 }3956 }
3957 // fallthrough
3958 }3957 }
3958 ZIG_FALLTHROUGH;
3959
3959 case ScopeIdDecls:3960 case ScopeIdDecls:
3960 case ScopeIdBlock:3961 case ScopeIdBlock:
3961 case ScopeIdDefer:3962 case ScopeIdDefer:
...@@ -8784,8 +8785,6 @@ static Error define_builtin_compile_vars(CodeGen *g) {...@@ -8784,8 +8785,6 @@ static Error define_builtin_compile_vars(CodeGen *g) {
8784 cache_bool(&cache_hash, g->is_test_build);8785 cache_bool(&cache_hash, g->is_test_build);
8785 cache_bool(&cache_hash, g->is_single_threaded);8786 cache_bool(&cache_hash, g->is_single_threaded);
8786 cache_bool(&cache_hash, g->test_is_evented);8787 cache_bool(&cache_hash, g->test_is_evented);
8787 cache_bool(&cache_hash, g->cpp_rtti);
8788 cache_bool(&cache_hash, g->cpp_exceptions);
8789 cache_int(&cache_hash, g->code_model);8788 cache_int(&cache_hash, g->code_model);
8790 cache_int(&cache_hash, g->zig_target->is_native_os);8789 cache_int(&cache_hash, g->zig_target->is_native_os);
8791 cache_int(&cache_hash, g->zig_target->is_native_cpu);8790 cache_int(&cache_hash, g->zig_target->is_native_cpu);
...@@ -9125,21 +9124,29 @@ static void detect_libc(CodeGen *g) {...@@ -9125,21 +9124,29 @@ static void detect_libc(CodeGen *g) {
9125 g->libc_include_dir_len = 0;9124 g->libc_include_dir_len = 0;
9126 g->libc_include_dir_list = heap::c_allocator.allocate<const char *>(dir_count);9125 g->libc_include_dir_list = heap::c_allocator.allocate<const char *>(dir_count);
91279126
9128 g->libc_include_dir_list[g->libc_include_dir_len] = g->libc->include_dir;9127 g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem(
9128 g->libc->include_dir, g->libc->include_dir_len));
9129 g->libc_include_dir_len += 1;9129 g->libc_include_dir_len += 1;
91309130
9131 if (want_sys_dir) {9131 if (want_sys_dir) {
9132 g->libc_include_dir_list[g->libc_include_dir_len] = g->libc->sys_include_dir;9132 g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_create_from_mem(
9133 g->libc->sys_include_dir, g->libc->sys_include_dir_len));
9133 g->libc_include_dir_len += 1;9134 g->libc_include_dir_len += 1;
9134 }9135 }
91359136
9136 if (want_um_and_shared_dirs != 0) {9137 if (want_um_and_shared_dirs != 0) {
9137 g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_sprintf(9138 Buf *include_dir_parent = buf_alloc();
9138 "%s" OS_SEP ".." OS_SEP "um", g->libc->include_dir));9139 os_path_join(buf_create_from_mem(g->libc->include_dir, g->libc->include_dir_len),
9140 buf_create_from_str(".."), include_dir_parent);
9141
9142 Buf *buff1 = buf_alloc();
9143 os_path_join(include_dir_parent, buf_create_from_str("um"), buff1);
9144 g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buff1);
9139 g->libc_include_dir_len += 1;9145 g->libc_include_dir_len += 1;
91409146
9141 g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buf_sprintf(9147 Buf *buff2 = buf_alloc();
9142 "%s" OS_SEP ".." OS_SEP "shared", g->libc->include_dir));9148 os_path_join(include_dir_parent, buf_create_from_str("shared"), buff2);
9149 g->libc_include_dir_list[g->libc_include_dir_len] = buf_ptr(buff2);
9143 g->libc_include_dir_len += 1;9150 g->libc_include_dir_len += 1;
9144 }9151 }
9145 assert(g->libc_include_dir_len == dir_count);9152 assert(g->libc_include_dir_len == dir_count);
...@@ -9163,20 +9170,13 @@ static void detect_libc(CodeGen *g) {...@@ -9163,20 +9170,13 @@ static void detect_libc(CodeGen *g) {
91639170
9164// does not add the "cc" arg9171// does not add the "cc" arg
9165void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_path,9172void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_path,
9166 bool translate_c, CSourceKind source_kind)9173 bool translate_c, FileExt source_kind)
9167{9174{
9168 if (translate_c) {9175 if (translate_c) {
9169 args.append("-x");9176 args.append("-x");
9170 args.append("c");9177 args.append("c");
9171 }9178 }
91729179
9173 if (source_kind != CSourceKindAsm && out_dep_path != nullptr) {
9174 args.append("-MD");
9175 args.append("-MV");
9176 args.append("-MF");
9177 args.append(out_dep_path);
9178 }
9179
9180 args.append("-nostdinc");9180 args.append("-nostdinc");
9181 args.append("-fno-spell-checking");9181 args.append("-fno-spell-checking");
91829182
...@@ -9184,14 +9184,7 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa...@@ -9184,14 +9184,7 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa
9184 args.append("-ffunction-sections");9184 args.append("-ffunction-sections");
9185 }9185 }
91869186
9187 if (translate_c) {9187 if (!translate_c) {
9188 if (source_kind != CSourceKindAsm) {
9189 // this gives us access to preprocessing entities, presumably at
9190 // the cost of performance
9191 args.append("-Xclang");
9192 args.append("-detailed-preprocessing-record");
9193 }
9194 } else {
9195 switch (g->err_color) {9188 switch (g->err_color) {
9196 case ErrColorAuto:9189 case ErrColorAuto:
9197 break;9190 break;
...@@ -9225,24 +9218,25 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa...@@ -9225,24 +9218,25 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa
9225 args.append("-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS");9218 args.append("-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS");
9226 }9219 }
92279220
9228 // According to Rich Felker libc headers are supposed to go before C language headers.
9229 // However as noted by @dimenus, appending libc headers before c_headers breaks intrinsics
9230 // and other compiler specific items.
9231 args.append("-isystem");
9232 args.append(buf_ptr(g->zig_c_headers_dir));
9233
9234 for (size_t i = 0; i < g->libc_include_dir_len; i += 1) {
9235 const char *include_dir = g->libc_include_dir_list[i];
9236 args.append("-isystem");
9237 args.append(include_dir);
9238 }
9239
9240 args.append("-target");9221 args.append("-target");
9241 args.append(buf_ptr(&g->llvm_triple_str));9222 args.append(buf_ptr(&g->llvm_triple_str));
92429223
9243 switch (source_kind) {9224 switch (source_kind) {
9244 case CSourceKindC:9225 case FileExtC:
9245 case CSourceKindCpp:9226 case FileExtCpp:
9227 case FileExtHeader:
9228 // According to Rich Felker libc headers are supposed to go before C language headers.
9229 // However as noted by @dimenus, appending libc headers before c_headers breaks intrinsics
9230 // and other compiler specific items.
9231 args.append("-isystem");
9232 args.append(buf_ptr(g->zig_c_headers_dir));
9233
9234 for (size_t i = 0; i < g->libc_include_dir_len; i += 1) {
9235 const char *include_dir = g->libc_include_dir_list[i];
9236 args.append("-isystem");
9237 args.append(include_dir);
9238 }
9239
9246 if (g->zig_target->llvm_cpu_name != nullptr) {9240 if (g->zig_target->llvm_cpu_name != nullptr) {
9247 args.append("-Xclang");9241 args.append("-Xclang");
9248 args.append("-target-cpu");9242 args.append("-target-cpu");
...@@ -9255,18 +9249,25 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa...@@ -9255,18 +9249,25 @@ void add_cc_args(CodeGen *g, ZigList<const char *> &args, const char *out_dep_pa
9255 args.append("-Xclang");9249 args.append("-Xclang");
9256 args.append(g->zig_target->llvm_cpu_features);9250 args.append(g->zig_target->llvm_cpu_features);
9257 }9251 }
9252 if (translate_c) {
9253 // this gives us access to preprocessing entities, presumably at
9254 // the cost of performance
9255 args.append("-Xclang");
9256 args.append("-detailed-preprocessing-record");
9257 }
9258 if (out_dep_path != nullptr) {
9259 args.append("-MD");
9260 args.append("-MV");
9261 args.append("-MF");
9262 args.append(out_dep_path);
9263 }
9258 break;9264 break;
9259 case CSourceKindAsm:9265 case FileExtAsm:
9266 case FileExtLLVMIr:
9267 case FileExtLLVMBitCode:
9268 case FileExtUnknown:
9260 break;9269 break;
9261 }9270 }
9262 if (source_kind == CSourceKindCpp) {
9263 if (!g->cpp_rtti) {
9264 args.append("-fno-rtti");
9265 }
9266 if (!g->cpp_exceptions) {
9267 args.append("-fno-exceptions");
9268 }
9269 }
9270 for (size_t i = 0; i < g->zig_target->llvm_cpu_features_asm_len; i += 1) {9271 for (size_t i = 0; i < g->zig_target->llvm_cpu_features_asm_len; i += 1) {
9271 args.append(g->zig_target->llvm_cpu_features_asm_ptr[i]);9272 args.append(g->zig_target->llvm_cpu_features_asm_ptr[i]);
9272 }9273 }
...@@ -9414,7 +9415,7 @@ void codegen_translate_c(CodeGen *g, Buf *full_path) {...@@ -9414,7 +9415,7 @@ void codegen_translate_c(CodeGen *g, Buf *full_path) {
9414 }9415 }
94159416
9416 ZigList<const char *> clang_argv = {0};9417 ZigList<const char *> clang_argv = {0};
9417 add_cc_args(g, clang_argv, out_dep_path_cstr, true, CSourceKindC);9418 add_cc_args(g, clang_argv, out_dep_path_cstr, true, FileExtC);
94189419
9419 clang_argv.append(buf_ptr(full_path));9420 clang_argv.append(buf_ptr(full_path));
94209421
...@@ -9714,8 +9715,6 @@ Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose...@@ -9714,8 +9715,6 @@ Error create_c_object_cache(CodeGen *g, CacheHash **out_cache_hash, bool verbose
9714 cache_bool(cache_hash, g->have_sanitize_c);9715 cache_bool(cache_hash, g->have_sanitize_c);
9715 cache_bool(cache_hash, want_valgrind_support(g));9716 cache_bool(cache_hash, want_valgrind_support(g));
9716 cache_bool(cache_hash, g->function_sections);9717 cache_bool(cache_hash, g->function_sections);
9717 cache_bool(cache_hash, g->cpp_rtti);
9718 cache_bool(cache_hash, g->cpp_exceptions);
9719 cache_int(cache_hash, g->code_model);9718 cache_int(cache_hash, g->code_model);
97209719
9721 for (size_t arg_i = 0; arg_i < g->clang_argv_len; arg_i += 1) {9720 for (size_t arg_i = 0; arg_i < g->clang_argv_len; arg_i += 1) {
...@@ -9754,15 +9753,6 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {...@@ -9754,15 +9753,6 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {
9754 Buf *c_source_basename = buf_alloc();9753 Buf *c_source_basename = buf_alloc();
9755 os_path_split(c_source_file, nullptr, c_source_basename);9754 os_path_split(c_source_file, nullptr, c_source_basename);
97569755
9757 CSourceKind c_source_kind;
9758 if (buf_ends_with_str(c_source_basename, ".s") ||
9759 buf_ends_with_str(c_source_basename, ".S"))
9760 {
9761 c_source_kind = CSourceKindAsm;
9762 } else {
9763 c_source_kind = CSourceKindC;
9764 }
9765
9766 Stage2ProgressNode *child_prog_node = stage2_progress_start(g->sub_progress_node, buf_ptr(c_source_basename),9756 Stage2ProgressNode *child_prog_node = stage2_progress_start(g->sub_progress_node, buf_ptr(c_source_basename),
9767 buf_len(c_source_basename), 0);9757 buf_len(c_source_basename), 0);
97689758
...@@ -9813,7 +9803,7 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {...@@ -9813,7 +9803,7 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {
9813 exit(1);9803 exit(1);
9814 }9804 }
9815 }9805 }
9816 bool is_cache_miss = (buf_len(&digest) == 0);9806 bool is_cache_miss = g->disable_c_depfile || (buf_len(&digest) == 0);
9817 if (is_cache_miss) {9807 if (is_cache_miss) {
9818 // we can't know the digest until we do the C compiler invocation, so we9808 // we can't know the digest until we do the C compiler invocation, so we
9819 // need a tmp filename.9809 // need a tmp filename.
...@@ -9828,14 +9818,14 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {...@@ -9828,14 +9818,14 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {
9828 args.append(buf_ptr(self_exe_path));9818 args.append(buf_ptr(self_exe_path));
9829 args.append("clang");9819 args.append("clang");
98309820
9831 if (c_file->preprocessor_only_basename != nullptr) {9821 if (c_file->preprocessor_only_basename == nullptr) {
9832 args.append("-E");
9833 } else {
9834 args.append("-c");9822 args.append("-c");
9835 }9823 }
98369824
9837 Buf *out_dep_path = buf_sprintf("%s.d", buf_ptr(out_obj_path));9825 Buf *out_dep_path = g->disable_c_depfile ? nullptr : buf_sprintf("%s.d", buf_ptr(out_obj_path));
9838 add_cc_args(g, args, buf_ptr(out_dep_path), false, c_source_kind);9826 const char *out_dep_path_cstr = (out_dep_path == nullptr) ? nullptr : buf_ptr(out_dep_path);
9827 FileExt ext = classify_file_ext(buf_ptr(c_source_basename), buf_len(c_source_basename));
9828 add_cc_args(g, args, out_dep_path_cstr, false, ext);
98399829
9840 args.append("-o");9830 args.append("-o");
9841 args.append(buf_ptr(out_obj_path));9831 args.append(buf_ptr(out_obj_path));
...@@ -9856,22 +9846,24 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {...@@ -9856,22 +9846,24 @@ static void gen_c_object(CodeGen *g, Buf *self_exe_path, CFile *c_file) {
9856 exit(1);9846 exit(1);
9857 }9847 }
98589848
9859 // add the files depended on to the cache system9849 if (out_dep_path != nullptr) {
9860 if ((err = cache_add_dep_file(cache_hash, out_dep_path, true))) {9850 // add the files depended on to the cache system
9861 // Don't treat the absence of the .d file as a fatal error, the9851 if ((err = cache_add_dep_file(cache_hash, out_dep_path, true))) {
9862 // compiler may not produce one eg. when compiling .s files9852 // Don't treat the absence of the .d file as a fatal error, the
9853 // compiler may not produce one eg. when compiling .s files
9854 if (err != ErrorFileNotFound) {
9855 fprintf(stderr, "Failed to add C source dependencies to cache: %s\n", err_str(err));
9856 exit(1);
9857 }
9858 }
9863 if (err != ErrorFileNotFound) {9859 if (err != ErrorFileNotFound) {
9864 fprintf(stderr, "Failed to add C source dependencies to cache: %s\n", err_str(err));9860 os_delete_file(out_dep_path);
9865 exit(1);
9866 }9861 }
9867 }
9868 if (err != ErrorFileNotFound) {
9869 os_delete_file(out_dep_path);
9870 }
98719862
9872 if ((err = cache_final(cache_hash, &digest))) {9863 if ((err = cache_final(cache_hash, &digest))) {
9873 fprintf(stderr, "Unable to finalize cache hash: %s\n", err_str(err));9864 fprintf(stderr, "Unable to finalize cache hash: %s\n", err_str(err));
9874 exit(1);9865 exit(1);
9866 }
9875 }9867 }
9876 artifact_dir = buf_alloc();9868 artifact_dir = buf_alloc();
9877 os_path_join(o_dir, &digest, artifact_dir);9869 os_path_join(o_dir, &digest, artifact_dir);
...@@ -10550,8 +10542,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {...@@ -10550,8 +10542,6 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
10550 cache_bool(ch, g->emit_bin);10542 cache_bool(ch, g->emit_bin);
10551 cache_bool(ch, g->emit_llvm_ir);10543 cache_bool(ch, g->emit_llvm_ir);
10552 cache_bool(ch, g->emit_asm);10544 cache_bool(ch, g->emit_asm);
10553 cache_bool(ch, g->cpp_rtti);
10554 cache_bool(ch, g->cpp_exceptions);
10555 cache_usize(ch, g->version_major);10545 cache_usize(ch, g->version_major);
10556 cache_usize(ch, g->version_minor);10546 cache_usize(ch, g->version_minor);
10557 cache_usize(ch, g->version_patch);10547 cache_usize(ch, g->version_patch);
...@@ -10560,14 +10550,19 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {...@@ -10560,14 +10550,19 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
10560 cache_list_of_str(ch, g->lib_dirs.items, g->lib_dirs.length);10550 cache_list_of_str(ch, g->lib_dirs.items, g->lib_dirs.length);
10561 cache_list_of_str(ch, g->framework_dirs.items, g->framework_dirs.length);10551 cache_list_of_str(ch, g->framework_dirs.items, g->framework_dirs.length);
10562 if (g->libc) {10552 if (g->libc) {
10563 cache_str(ch, g->libc->include_dir);10553 cache_slice(ch, Slice<const char>{g->libc->include_dir, g->libc->include_dir_len});
10564 cache_str(ch, g->libc->sys_include_dir);10554 cache_slice(ch, Slice<const char>{g->libc->sys_include_dir, g->libc->sys_include_dir_len});
10565 cache_str(ch, g->libc->crt_dir);10555 cache_slice(ch, Slice<const char>{g->libc->crt_dir, g->libc->crt_dir_len});
10566 cache_str(ch, g->libc->msvc_lib_dir);10556 cache_slice(ch, Slice<const char>{g->libc->msvc_lib_dir, g->libc->msvc_lib_dir_len});
10567 cache_str(ch, g->libc->kernel32_lib_dir);10557 cache_slice(ch, Slice<const char>{g->libc->kernel32_lib_dir, g->libc->kernel32_lib_dir_len});
10568 }10558 }
10569 cache_buf_opt(ch, g->version_script_path);10559 cache_buf_opt(ch, g->version_script_path);
10570 cache_buf_opt(ch, g->override_soname);10560 cache_buf_opt(ch, g->override_soname);
10561 cache_buf_opt(ch, g->linker_optimization);
10562 cache_int(ch, g->linker_gc_sections);
10563 cache_int(ch, g->linker_allow_shlib_undefined);
10564 cache_bool(ch, g->linker_z_nodelete);
10565 cache_bool(ch, g->linker_z_defs);
1057110566
10572 // gen_c_objects appends objects to g->link_objects which we want to include in the hash10567 // gen_c_objects appends objects to g->link_objects which we want to include in the hash
10573 gen_c_objects(g);10568 gen_c_objects(g);
...@@ -10856,8 +10851,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o...@@ -10856,8 +10851,6 @@ CodeGen *create_child_codegen(CodeGen *parent_gen, Buf *root_src_path, OutType o
10856 parent_gen->build_mode, parent_gen->zig_lib_dir, libc, get_global_cache_dir(), false, child_progress_node);10851 parent_gen->build_mode, parent_gen->zig_lib_dir, libc, get_global_cache_dir(), false, child_progress_node);
10857 child_gen->root_out_name = buf_create_from_str(name);10852 child_gen->root_out_name = buf_create_from_str(name);
10858 child_gen->disable_gen_h = true;10853 child_gen->disable_gen_h = true;
10859 child_gen->cpp_rtti = parent_gen->cpp_rtti;
10860 child_gen->cpp_exceptions = parent_gen->cpp_exceptions;
10861 child_gen->want_stack_check = WantStackCheckDisabled;10854 child_gen->want_stack_check = WantStackCheckDisabled;
10862 child_gen->want_sanitize_c = WantCSanitizeDisabled;10855 child_gen->want_sanitize_c = WantCSanitizeDisabled;
10863 child_gen->verbose_tokenize = parent_gen->verbose_tokenize;10856 child_gen->verbose_tokenize = parent_gen->verbose_tokenize;
src/compiler.cpp+22
...@@ -164,3 +164,25 @@ Buf *get_global_cache_dir(void) {...@@ -164,3 +164,25 @@ Buf *get_global_cache_dir(void) {
164 buf_deinit(&app_data_dir);164 buf_deinit(&app_data_dir);
165 return &saved_global_cache_dir;165 return &saved_global_cache_dir;
166}166}
167
168FileExt classify_file_ext(const char *filename_ptr, size_t filename_len) {
169 if (mem_ends_with_str(filename_ptr, filename_len, ".c")) {
170 return FileExtC;
171 } else if (mem_ends_with_str(filename_ptr, filename_len, ".C") ||
172 mem_ends_with_str(filename_ptr, filename_len, ".cc") ||
173 mem_ends_with_str(filename_ptr, filename_len, ".cpp") ||
174 mem_ends_with_str(filename_ptr, filename_len, ".cxx"))
175 {
176 return FileExtCpp;
177 } else if (mem_ends_with_str(filename_ptr, filename_len, ".ll")) {
178 return FileExtLLVMIr;
179 } else if (mem_ends_with_str(filename_ptr, filename_len, ".bc")) {
180 return FileExtLLVMBitCode;
181 } else if (mem_ends_with_str(filename_ptr, filename_len, ".s") ||
182 mem_ends_with_str(filename_ptr, filename_len, ".S"))
183 {
184 return FileExtAsm;
185 }
186 // TODO look for .so, .so.X, .so.X.Y, .so.X.Y.Z
187 return FileExtUnknown;
188}
src/compiler.hpp+4-2
...@@ -8,8 +8,7 @@...@@ -8,8 +8,7 @@
8#ifndef ZIG_COMPILER_HPP8#ifndef ZIG_COMPILER_HPP
9#define ZIG_COMPILER_HPP9#define ZIG_COMPILER_HPP
1010
11#include "buffer.hpp"11#include "all_types.hpp"
12#include "error.hpp"
1312
14Error get_compiler_id(Buf **result);13Error get_compiler_id(Buf **result);
1514
...@@ -19,4 +18,7 @@ Buf *get_zig_std_dir(Buf *zig_lib_dir);...@@ -19,4 +18,7 @@ Buf *get_zig_std_dir(Buf *zig_lib_dir);
1918
20Buf *get_global_cache_dir(void);19Buf *get_global_cache_dir(void);
2120
21
22FileExt classify_file_ext(const char *filename_ptr, size_t filename_len);
23
22#endif24#endif
src/dump_analysis.cpp+2-2
...@@ -80,7 +80,7 @@ static void jw_array_elem(JsonWriter *jw) {...@@ -80,7 +80,7 @@ static void jw_array_elem(JsonWriter *jw) {
80 zig_unreachable();80 zig_unreachable();
81 case JsonWriterStateArray:81 case JsonWriterStateArray:
82 fprintf(jw->f, ",");82 fprintf(jw->f, ",");
83 // fallthrough83 ZIG_FALLTHROUGH;
84 case JsonWriterStateArrayStart:84 case JsonWriterStateArrayStart:
85 jw->state[jw->state_index] = JsonWriterStateArray;85 jw->state[jw->state_index] = JsonWriterStateArray;
86 jw_push_state(jw, JsonWriterStateValue);86 jw_push_state(jw, JsonWriterStateValue);
...@@ -134,7 +134,7 @@ static void jw_object_field(JsonWriter *jw, const char *name) {...@@ -134,7 +134,7 @@ static void jw_object_field(JsonWriter *jw, const char *name) {
134 zig_unreachable();134 zig_unreachable();
135 case JsonWriterStateObject:135 case JsonWriterStateObject:
136 fprintf(jw->f, ",");136 fprintf(jw->f, ",");
137 // fallthrough137 ZIG_FALLTHROUGH;
138 case JsonWriterStateObjectStart:138 case JsonWriterStateObjectStart:
139 jw->state[jw->state_index] = JsonWriterStateObject;139 jw->state[jw->state_index] = JsonWriterStateObject;
140 jw_push_state(jw, JsonWriterStateValue);140 jw_push_state(jw, JsonWriterStateValue);
src/ir.cpp+73-32
...@@ -231,6 +231,7 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op);...@@ -231,6 +231,7 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op);
231static IrInstSrc *ir_lval_wrap(IrBuilderSrc *irb, Scope *scope, IrInstSrc *value, LVal lval, ResultLoc *result_loc);231static IrInstSrc *ir_lval_wrap(IrBuilderSrc *irb, Scope *scope, IrInstSrc *value, LVal lval, ResultLoc *result_loc);
232static IrInstSrc *ir_expr_wrap(IrBuilderSrc *irb, Scope *scope, IrInstSrc *inst, ResultLoc *result_loc);232static IrInstSrc *ir_expr_wrap(IrBuilderSrc *irb, Scope *scope, IrInstSrc *inst, ResultLoc *result_loc);
233static ZigType *adjust_ptr_align(CodeGen *g, ZigType *ptr_type, uint32_t new_align);233static ZigType *adjust_ptr_align(CodeGen *g, ZigType *ptr_type, uint32_t new_align);
234static ZigType *adjust_ptr_const(CodeGen *g, ZigType *ptr_type, bool is_const);
234static ZigType *adjust_slice_align(CodeGen *g, ZigType *slice_type, uint32_t new_align);235static ZigType *adjust_slice_align(CodeGen *g, ZigType *slice_type, uint32_t new_align);
235static Error buf_read_value_bytes(IrAnalyze *ira, CodeGen *codegen, AstNode *source_node, uint8_t *buf, ZigValue *val);236static Error buf_read_value_bytes(IrAnalyze *ira, CodeGen *codegen, AstNode *source_node, uint8_t *buf, ZigValue *val);
236static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ZigValue *val);237static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ZigValue *val);
...@@ -11453,10 +11454,8 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, ZigType *wanted...@@ -11453,10 +11454,8 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, ZigType *wanted
11453 bool actual_allows_zero = ptr_allows_addr_zero(actual_type);11454 bool actual_allows_zero = ptr_allows_addr_zero(actual_type);
11454 bool wanted_is_c_ptr = wanted_type->id == ZigTypeIdPointer && wanted_type->data.pointer.ptr_len == PtrLenC;11455 bool wanted_is_c_ptr = wanted_type->id == ZigTypeIdPointer && wanted_type->data.pointer.ptr_len == PtrLenC;
11455 bool actual_is_c_ptr = actual_type->id == ZigTypeIdPointer && actual_type->data.pointer.ptr_len == PtrLenC;11456 bool actual_is_c_ptr = actual_type->id == ZigTypeIdPointer && actual_type->data.pointer.ptr_len == PtrLenC;
11456 bool wanted_opt_or_ptr = wanted_ptr_type != nullptr &&11457 bool wanted_opt_or_ptr = wanted_ptr_type != nullptr && wanted_ptr_type->id == ZigTypeIdPointer;
11457 (wanted_type->id == ZigTypeIdPointer || wanted_type->id == ZigTypeIdOptional);11458 bool actual_opt_or_ptr = actual_ptr_type != nullptr && actual_ptr_type->id == ZigTypeIdPointer;
11458 bool actual_opt_or_ptr = actual_ptr_type != nullptr &&
11459 (actual_type->id == ZigTypeIdPointer || actual_type->id == ZigTypeIdOptional);
11460 if (wanted_opt_or_ptr && actual_opt_or_ptr) {11459 if (wanted_opt_or_ptr && actual_opt_or_ptr) {
11461 bool ok_null_term_ptrs =11460 bool ok_null_term_ptrs =
11462 wanted_ptr_type->data.pointer.sentinel == nullptr ||11461 wanted_ptr_type->data.pointer.sentinel == nullptr ||
...@@ -11844,6 +11843,7 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -11844,6 +11843,7 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
1184411843
11845 bool any_are_null = (prev_inst->value->type->id == ZigTypeIdNull);11844 bool any_are_null = (prev_inst->value->type->id == ZigTypeIdNull);
11846 bool convert_to_const_slice = false;11845 bool convert_to_const_slice = false;
11846 bool make_the_slice_const = false;
11847 for (; i < instruction_count; i += 1) {11847 for (; i < instruction_count; i += 1) {
11848 IrInstGen *cur_inst = instructions[i];11848 IrInstGen *cur_inst = instructions[i];
11849 ZigType *cur_type = cur_inst->value->type;11849 ZigType *cur_type = cur_inst->value->type;
...@@ -12357,12 +12357,12 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12357,12 +12357,12 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12357 ZigType *slice_type = (prev_type->id == ZigTypeIdErrorUnion) ?12357 ZigType *slice_type = (prev_type->id == ZigTypeIdErrorUnion) ?
12358 prev_type->data.error_union.payload_type : prev_type;12358 prev_type->data.error_union.payload_type : prev_type;
12359 ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry;12359 ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry;
12360 if ((slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 ||12360 if (types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type,
12361 !cur_type->data.pointer.is_const) &&
12362 types_match_const_cast_only(ira,
12363 slice_ptr_type->data.pointer.child_type,
12364 array_type->data.array.child_type, source_node, false).id == ConstCastResultIdOk)12361 array_type->data.array.child_type, source_node, false).id == ConstCastResultIdOk)
12365 {12362 {
12363 bool const_ok = (slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 ||
12364 !cur_type->data.pointer.is_const);
12365 if (!const_ok) make_the_slice_const = true;
12366 convert_to_const_slice = false;12366 convert_to_const_slice = false;
12367 continue;12367 continue;
12368 }12368 }
...@@ -12391,12 +12391,12 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12391,12 +12391,12 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12391 break;12391 break;
12392 }12392 }
12393 ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry;12393 ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry;
12394 if ((slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 ||12394 if (types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type,
12395 !prev_type->data.pointer.is_const) &&
12396 types_match_const_cast_only(ira,
12397 slice_ptr_type->data.pointer.child_type,
12398 array_type->data.array.child_type, source_node, false).id == ConstCastResultIdOk)12395 array_type->data.array.child_type, source_node, false).id == ConstCastResultIdOk)
12399 {12396 {
12397 bool const_ok = (slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0 ||
12398 !prev_type->data.pointer.is_const);
12399 if (!const_ok) make_the_slice_const = true;
12400 prev_inst = cur_inst;12400 prev_inst = cur_inst;
12401 convert_to_const_slice = false;12401 convert_to_const_slice = false;
12402 continue;12402 continue;
...@@ -12408,8 +12408,6 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12408,8 +12408,6 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12408 cur_type->data.pointer.child_type->id == ZigTypeIdArray &&12408 cur_type->data.pointer.child_type->id == ZigTypeIdArray &&
12409 prev_type->id == ZigTypeIdPointer && prev_type->data.pointer.ptr_len == PtrLenSingle &&12409 prev_type->id == ZigTypeIdPointer && prev_type->data.pointer.ptr_len == PtrLenSingle &&
12410 prev_type->data.pointer.child_type->id == ZigTypeIdArray &&12410 prev_type->data.pointer.child_type->id == ZigTypeIdArray &&
12411 (cur_type->data.pointer.is_const || !prev_type->data.pointer.is_const ||
12412 prev_type->data.pointer.child_type->data.array.len == 0) &&
12413 (12411 (
12414 prev_type->data.pointer.child_type->data.array.sentinel == nullptr ||12412 prev_type->data.pointer.child_type->data.array.sentinel == nullptr ||
12415 (cur_type->data.pointer.child_type->data.array.sentinel != nullptr &&12413 (cur_type->data.pointer.child_type->data.array.sentinel != nullptr &&
...@@ -12421,6 +12419,9 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12421,6 +12419,9 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12421 prev_type->data.pointer.child_type->data.array.child_type,12419 prev_type->data.pointer.child_type->data.array.child_type,
12422 source_node, !cur_type->data.pointer.is_const).id == ConstCastResultIdOk)12420 source_node, !cur_type->data.pointer.is_const).id == ConstCastResultIdOk)
12423 {12421 {
12422 bool const_ok = (cur_type->data.pointer.is_const || !prev_type->data.pointer.is_const ||
12423 prev_type->data.pointer.child_type->data.array.len == 0);
12424 if (!const_ok) make_the_slice_const = true;
12424 prev_inst = cur_inst;12425 prev_inst = cur_inst;
12425 convert_to_const_slice = true;12426 convert_to_const_slice = true;
12426 continue;12427 continue;
...@@ -12429,8 +12430,6 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12429,8 +12430,6 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12429 prev_type->data.pointer.child_type->id == ZigTypeIdArray &&12430 prev_type->data.pointer.child_type->id == ZigTypeIdArray &&
12430 cur_type->id == ZigTypeIdPointer && cur_type->data.pointer.ptr_len == PtrLenSingle &&12431 cur_type->id == ZigTypeIdPointer && cur_type->data.pointer.ptr_len == PtrLenSingle &&
12431 cur_type->data.pointer.child_type->id == ZigTypeIdArray &&12432 cur_type->data.pointer.child_type->id == ZigTypeIdArray &&
12432 (prev_type->data.pointer.is_const || !cur_type->data.pointer.is_const ||
12433 cur_type->data.pointer.child_type->data.array.len == 0) &&
12434 (12433 (
12435 cur_type->data.pointer.child_type->data.array.sentinel == nullptr ||12434 cur_type->data.pointer.child_type->data.array.sentinel == nullptr ||
12436 (prev_type->data.pointer.child_type->data.array.sentinel != nullptr &&12435 (prev_type->data.pointer.child_type->data.array.sentinel != nullptr &&
...@@ -12442,6 +12441,9 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12442,6 +12441,9 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12442 cur_type->data.pointer.child_type->data.array.child_type,12441 cur_type->data.pointer.child_type->data.array.child_type,
12443 source_node, !prev_type->data.pointer.is_const).id == ConstCastResultIdOk)12442 source_node, !prev_type->data.pointer.is_const).id == ConstCastResultIdOk)
12444 {12443 {
12444 bool const_ok = (prev_type->data.pointer.is_const || !cur_type->data.pointer.is_const ||
12445 cur_type->data.pointer.child_type->data.array.len == 0);
12446 if (!const_ok) make_the_slice_const = true;
12445 convert_to_const_slice = true;12447 convert_to_const_slice = true;
12446 continue;12448 continue;
12447 }12449 }
...@@ -12486,7 +12488,7 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12486,7 +12488,7 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12486 src_assert(array_type->id == ZigTypeIdArray, source_node);12488 src_assert(array_type->id == ZigTypeIdArray, source_node);
12487 ZigType *ptr_type = get_pointer_to_type_extra2(12489 ZigType *ptr_type = get_pointer_to_type_extra2(
12488 ira->codegen, array_type->data.array.child_type,12490 ira->codegen, array_type->data.array.child_type,
12489 prev_inst->value->type->data.pointer.is_const, false,12491 prev_inst->value->type->data.pointer.is_const || make_the_slice_const, false,
12490 PtrLenUnknown,12492 PtrLenUnknown,
12491 0, 0, 0, false,12493 0, 0, 0, false,
12492 VECTOR_INDEX_NONE, nullptr, array_type->data.array.sentinel);12494 VECTOR_INDEX_NONE, nullptr, array_type->data.array.sentinel);
...@@ -12537,6 +12539,26 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT...@@ -12537,6 +12539,26 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT
12537 return ira->codegen->builtin_types.entry_invalid;12539 return ira->codegen->builtin_types.entry_invalid;
12538 return get_optional_type(ira->codegen, prev_inst->value->type);12540 return get_optional_type(ira->codegen, prev_inst->value->type);
12539 }12541 }
12542 } else if (make_the_slice_const) {
12543 ZigType *slice_type;
12544 if (prev_inst->value->type->id == ZigTypeIdErrorUnion) {
12545 slice_type = prev_inst->value->type->data.error_union.payload_type;
12546 } else if (is_slice(prev_inst->value->type)) {
12547 slice_type = prev_inst->value->type;
12548 } else {
12549 zig_unreachable();
12550 }
12551 ZigType *slice_ptr_type = slice_type->data.structure.fields[slice_ptr_index]->type_entry;
12552 ZigType *adjusted_ptr_type = adjust_ptr_const(ira->codegen, slice_ptr_type, make_the_slice_const);
12553 ZigType *adjusted_slice_type = get_slice_type(ira->codegen, adjusted_ptr_type);
12554 if (prev_inst->value->type->id == ZigTypeIdErrorUnion) {
12555 return get_error_union_type(ira->codegen, prev_inst->value->type->data.error_union.err_set_type,
12556 adjusted_slice_type);
12557 } else if (is_slice(prev_inst->value->type)) {
12558 return adjusted_slice_type;
12559 } else {
12560 zig_unreachable();
12561 }
12540 } else {12562 } else {
12541 return prev_inst->value->type;12563 return prev_inst->value->type;
12542 }12564 }
...@@ -15929,7 +15951,7 @@ static IrInstGen *ir_analyze_bin_op_cmp_numeric(IrAnalyze *ira, IrInst *source_i...@@ -15929,7 +15951,7 @@ static IrInstGen *ir_analyze_bin_op_cmp_numeric(IrAnalyze *ira, IrInst *source_i
15929 if (op1->value->type->id == ZigTypeIdVector && op2->value->type->id == ZigTypeIdVector) {15951 if (op1->value->type->id == ZigTypeIdVector && op2->value->type->id == ZigTypeIdVector) {
15930 if (op1->value->type->data.vector.len != op2->value->type->data.vector.len) {15952 if (op1->value->type->data.vector.len != op2->value->type->data.vector.len) {
15931 ir_add_error(ira, source_instr,15953 ir_add_error(ira, source_instr,
15932 buf_sprintf("vector length mismatch: %" PRIu32 " and %" PRIu32,15954 buf_sprintf("vector length mismatch: %" PRIu64 " and %" PRIu64,
15933 op1->value->type->data.vector.len, op2->value->type->data.vector.len));15955 op1->value->type->data.vector.len, op2->value->type->data.vector.len));
15934 return ira->codegen->invalid_inst_gen;15956 return ira->codegen->invalid_inst_gen;
15935 }15957 }
...@@ -18958,7 +18980,7 @@ static IrInstGen *ir_analyze_async_call(IrAnalyze *ira, IrInst* source_instr, Zi...@@ -18958,7 +18980,7 @@ static IrInstGen *ir_analyze_async_call(IrAnalyze *ira, IrInst* source_instr, Zi
18958 if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) {18980 if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) {
18959 return result_loc;18981 return result_loc;
18960 }18982 }
18961 result_loc = ir_implicit_cast2(ira, &call_result_loc->source_instruction->base, result_loc,18983 result_loc = ir_implicit_cast2(ira, source_instr, result_loc,
18962 get_pointer_to_type(ira->codegen, frame_type, false));18984 get_pointer_to_type(ira->codegen, frame_type, false));
18963 if (type_is_invalid(result_loc->value->type))18985 if (type_is_invalid(result_loc->value->type))
18964 return ira->codegen->invalid_inst_gen;18986 return ira->codegen->invalid_inst_gen;
...@@ -19925,6 +19947,7 @@ static IrInstGen *ir_analyze_call_extra(IrAnalyze *ira, IrInst* source_instr,...@@ -19925,6 +19947,7 @@ static IrInstGen *ir_analyze_call_extra(IrAnalyze *ira, IrInst* source_instr,
19925 buf_sprintf("the specified modifier requires a comptime-known function"));19947 buf_sprintf("the specified modifier requires a comptime-known function"));
19926 return ira->codegen->invalid_inst_gen;19948 return ira->codegen->invalid_inst_gen;
19927 }19949 }
19950 ZIG_FALLTHROUGH;
19928 default:19951 default:
19929 break;19952 break;
19930 }19953 }
...@@ -19943,14 +19966,16 @@ static IrInstGen *ir_analyze_call_extra(IrAnalyze *ira, IrInst* source_instr,...@@ -19943,14 +19966,16 @@ static IrInstGen *ir_analyze_call_extra(IrAnalyze *ira, IrInst* source_instr,
19943 return ira->codegen->invalid_inst_gen;19966 return ira->codegen->invalid_inst_gen;
1994419967
19945 IrInstGen *stack = nullptr;19968 IrInstGen *stack = nullptr;
19969 IrInst *stack_src = nullptr;
19946 if (stack_is_non_null) {19970 if (stack_is_non_null) {
19947 stack = ir_analyze_optional_value_payload_value(ira, source_instr, opt_stack, false);19971 stack = ir_analyze_optional_value_payload_value(ira, source_instr, opt_stack, false);
19948 if (type_is_invalid(stack->value->type))19972 if (type_is_invalid(stack->value->type))
19949 return ira->codegen->invalid_inst_gen;19973 return ira->codegen->invalid_inst_gen;
19974 stack_src = &stack->base;
19950 }19975 }
1995119976
19952 return ir_analyze_fn_call(ira, source_instr, fn, fn_type, fn_ref, first_arg_ptr, first_arg_ptr_src,19977 return ir_analyze_fn_call(ira, source_instr, fn, fn_type, fn_ref, first_arg_ptr, first_arg_ptr_src,
19953 modifier, stack, &stack->base, false, args_ptr, args_len, nullptr, result_loc);19978 modifier, stack, stack_src, false, args_ptr, args_len, nullptr, result_loc);
19954}19979}
1995519980
19956static IrInstGen *ir_analyze_instruction_call_extra(IrAnalyze *ira, IrInstSrcCallExtra *instruction) {19981static IrInstGen *ir_analyze_instruction_call_extra(IrAnalyze *ira, IrInstSrcCallExtra *instruction) {
...@@ -20708,24 +20733,44 @@ static ZigType *adjust_slice_align(CodeGen *g, ZigType *slice_type, uint32_t new...@@ -20708,24 +20733,44 @@ static ZigType *adjust_slice_align(CodeGen *g, ZigType *slice_type, uint32_t new
2070820733
20709static ZigType *adjust_ptr_len(CodeGen *g, ZigType *ptr_type, PtrLen ptr_len) {20734static ZigType *adjust_ptr_len(CodeGen *g, ZigType *ptr_type, PtrLen ptr_len) {
20710 assert(ptr_type->id == ZigTypeIdPointer);20735 assert(ptr_type->id == ZigTypeIdPointer);
20711 return get_pointer_to_type_extra(g,20736 return get_pointer_to_type_extra2(g,
20712 ptr_type->data.pointer.child_type,20737 ptr_type->data.pointer.child_type,
20713 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,20738 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
20714 ptr_len,20739 ptr_len,
20715 ptr_type->data.pointer.explicit_alignment,20740 ptr_type->data.pointer.explicit_alignment,
20716 ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes,20741 ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes,
20717 ptr_type->data.pointer.allow_zero);20742 ptr_type->data.pointer.allow_zero,
20743 ptr_type->data.pointer.vector_index,
20744 ptr_type->data.pointer.inferred_struct_field,
20745 ptr_type->data.pointer.sentinel);
20718}20746}
2071920747
20720static ZigType *adjust_ptr_allow_zero(CodeGen *g, ZigType *ptr_type, bool allow_zero) {20748static ZigType *adjust_ptr_allow_zero(CodeGen *g, ZigType *ptr_type, bool allow_zero) {
20721 assert(ptr_type->id == ZigTypeIdPointer);20749 assert(ptr_type->id == ZigTypeIdPointer);
20722 return get_pointer_to_type_extra(g,20750 return get_pointer_to_type_extra2(g,
20723 ptr_type->data.pointer.child_type,20751 ptr_type->data.pointer.child_type,
20724 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,20752 ptr_type->data.pointer.is_const, ptr_type->data.pointer.is_volatile,
20725 ptr_type->data.pointer.ptr_len,20753 ptr_type->data.pointer.ptr_len,
20726 ptr_type->data.pointer.explicit_alignment,20754 ptr_type->data.pointer.explicit_alignment,
20727 ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes,20755 ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes,
20728 allow_zero);20756 allow_zero,
20757 ptr_type->data.pointer.vector_index,
20758 ptr_type->data.pointer.inferred_struct_field,
20759 ptr_type->data.pointer.sentinel);
20760}
20761
20762static ZigType *adjust_ptr_const(CodeGen *g, ZigType *ptr_type, bool is_const) {
20763 assert(ptr_type->id == ZigTypeIdPointer);
20764 return get_pointer_to_type_extra2(g,
20765 ptr_type->data.pointer.child_type,
20766 is_const, ptr_type->data.pointer.is_volatile,
20767 ptr_type->data.pointer.ptr_len,
20768 ptr_type->data.pointer.explicit_alignment,
20769 ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes,
20770 ptr_type->data.pointer.allow_zero,
20771 ptr_type->data.pointer.vector_index,
20772 ptr_type->data.pointer.inferred_struct_field,
20773 ptr_type->data.pointer.sentinel);
20729}20774}
2073020775
20731static Error compute_elem_align(IrAnalyze *ira, ZigType *elem_type, uint32_t base_ptr_align,20776static Error compute_elem_align(IrAnalyze *ira, ZigType *elem_type, uint32_t base_ptr_align,
...@@ -20880,13 +20925,8 @@ static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemP...@@ -20880,13 +20925,8 @@ static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemP
20880 if (instr_is_comptime(casted_elem_index)) {20925 if (instr_is_comptime(casted_elem_index)) {
20881 uint64_t index = bigint_as_u64(&casted_elem_index->value->data.x_bigint);20926 uint64_t index = bigint_as_u64(&casted_elem_index->value->data.x_bigint);
20882 if (array_type->id == ZigTypeIdArray) {20927 if (array_type->id == ZigTypeIdArray) {
20883 uint64_t array_len = array_type->data.array.len;20928 uint64_t array_len = array_type->data.array.len +
20884 if (index == array_len && array_type->data.array.sentinel != nullptr) {20929 (array_type->data.array.sentinel != nullptr);
20885 ZigType *elem_type = array_type->data.array.child_type;
20886 IrInstGen *sentinel_elem = ir_const(ira, &elem_ptr_instruction->base.base, elem_type);
20887 copy_const_val(ira->codegen, sentinel_elem->value, array_type->data.array.sentinel);
20888 return ir_get_ref(ira, &elem_ptr_instruction->base.base, sentinel_elem, true, false);
20889 }
20890 if (index >= array_len) {20930 if (index >= array_len) {
20891 ir_add_error_node(ira, elem_ptr_instruction->base.base.source_node,20931 ir_add_error_node(ira, elem_ptr_instruction->base.base.source_node,
20892 buf_sprintf("index %" ZIG_PRI_u64 " outside array of size %" ZIG_PRI_u64,20932 buf_sprintf("index %" ZIG_PRI_u64 " outside array of size %" ZIG_PRI_u64,
...@@ -25131,7 +25171,7 @@ static IrInstGen *ir_analyze_instruction_c_import(IrAnalyze *ira, IrInstSrcCImpo...@@ -25131,7 +25171,7 @@ static IrInstGen *ir_analyze_instruction_c_import(IrAnalyze *ira, IrInstSrcCImpo
2513125171
25132 ZigList<const char *> clang_argv = {0};25172 ZigList<const char *> clang_argv = {0};
2513325173
25134 add_cc_args(ira->codegen, clang_argv, buf_ptr(tmp_dep_file), true, CSourceKindC);25174 add_cc_args(ira->codegen, clang_argv, buf_ptr(tmp_dep_file), true, FileExtC);
2513525175
25136 clang_argv.append(buf_ptr(&tmp_c_file_path));25176 clang_argv.append(buf_ptr(&tmp_c_file_path));
2513725177
...@@ -28128,6 +28168,7 @@ static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ZigValue *val)...@@ -28128,6 +28168,7 @@ static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ZigValue *val)
28128 return;28168 return;
28129 }28169 }
28130 }28170 }
28171 zig_unreachable();
28131 case ZigTypeIdOptional:28172 case ZigTypeIdOptional:
28132 zig_panic("TODO buf_write_value_bytes maybe type");28173 zig_panic("TODO buf_write_value_bytes maybe type");
28133 case ZigTypeIdFn:28174 case ZigTypeIdFn:
src/link.cpp+103-22
...@@ -651,6 +651,7 @@ static const char *build_libunwind(CodeGen *parent, Stage2ProgressNode *progress...@@ -651,6 +651,7 @@ static const char *build_libunwind(CodeGen *parent, Stage2ProgressNode *progress
651 if (parent->is_single_threaded) {651 if (parent->is_single_threaded) {
652 c_file->args.append("-D_LIBUNWIND_HAS_NO_THREADS");652 c_file->args.append("-D_LIBUNWIND_HAS_NO_THREADS");
653 }653 }
654 c_file->args.append("-Wno-bitwise-conditional-parentheses");
654 c_source_files.append(c_file);655 c_source_files.append(c_file);
655 }656 }
656 child_gen->c_source_files = c_source_files;657 child_gen->c_source_files = c_source_files;
...@@ -1594,7 +1595,8 @@ static const char *get_libc_crt_file(CodeGen *parent, const char *file, Stage2Pr...@@ -1594,7 +1595,8 @@ static const char *get_libc_crt_file(CodeGen *parent, const char *file, Stage2Pr
1594 } else {1595 } else {
1595 assert(parent->libc != nullptr);1596 assert(parent->libc != nullptr);
1596 Buf *out_buf = buf_alloc();1597 Buf *out_buf = buf_alloc();
1597 os_path_join(buf_create_from_str(parent->libc->crt_dir), buf_create_from_str(file), out_buf);1598 os_path_join(buf_create_from_mem(parent->libc->crt_dir, parent->libc->crt_dir_len),
1599 buf_create_from_str(file), out_buf);
1598 return buf_ptr(out_buf);1600 return buf_ptr(out_buf);
1599 }1601 }
1600}1602}
...@@ -1767,8 +1769,17 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1767,8 +1769,17 @@ static void construct_linker_job_elf(LinkJob *lj) {
1767 lj->args.append(g->linker_script);1769 lj->args.append(g->linker_script);
1768 }1770 }
17691771
1770 if (g->out_type != OutTypeObj) {1772 switch (g->linker_gc_sections) {
1771 lj->args.append("--gc-sections");1773 case OptionalBoolNull:
1774 if (g->out_type != OutTypeObj) {
1775 lj->args.append("--gc-sections");
1776 }
1777 break;
1778 case OptionalBoolTrue:
1779 lj->args.append("--gc-sections");
1780 break;
1781 case OptionalBoolFalse:
1782 break;
1772 }1783 }
17731784
1774 if (g->link_eh_frame_hdr) {1785 if (g->link_eh_frame_hdr) {
...@@ -1779,6 +1790,19 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1779,6 +1790,19 @@ static void construct_linker_job_elf(LinkJob *lj) {
1779 lj->args.append("--export-dynamic");1790 lj->args.append("--export-dynamic");
1780 }1791 }
17811792
1793 if (g->linker_optimization != nullptr) {
1794 lj->args.append(buf_ptr(g->linker_optimization));
1795 }
1796
1797 if (g->linker_z_nodelete) {
1798 lj->args.append("-z");
1799 lj->args.append("nodelete");
1800 }
1801 if (g->linker_z_defs) {
1802 lj->args.append("-z");
1803 lj->args.append("defs");
1804 }
1805
1782 lj->args.append("-m");1806 lj->args.append("-m");
1783 lj->args.append(getLDMOption(g->zig_target));1807 lj->args.append(getLDMOption(g->zig_target));
17841808
...@@ -1859,7 +1883,7 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1859,7 +1883,7 @@ static void construct_linker_job_elf(LinkJob *lj) {
1859 if (g->libc_link_lib != nullptr) {1883 if (g->libc_link_lib != nullptr) {
1860 if (g->libc != nullptr) {1884 if (g->libc != nullptr) {
1861 lj->args.append("-L");1885 lj->args.append("-L");
1862 lj->args.append(g->libc->crt_dir);1886 lj->args.append(buf_ptr(buf_create_from_mem(g->libc->crt_dir, g->libc->crt_dir_len)));
1863 }1887 }
18641888
1865 if (g->have_dynamic_link && (is_dyn_lib || g->out_type == OutTypeExe)) {1889 if (g->have_dynamic_link && (is_dyn_lib || g->out_type == OutTypeExe)) {
...@@ -1903,7 +1927,7 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1903,7 +1927,7 @@ static void construct_linker_job_elf(LinkJob *lj) {
1903 // libc is linked specially1927 // libc is linked specially
1904 continue;1928 continue;
1905 }1929 }
1906 if (buf_eql_str(link_lib->name, "c++") || buf_eql_str(link_lib->name, "c++abi")) {1930 if (target_is_libcpp_lib_name(g->zig_target, buf_ptr(link_lib->name))) {
1907 // libc++ is linked specially1931 // libc++ is linked specially
1908 continue;1932 continue;
1909 }1933 }
...@@ -1947,15 +1971,11 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1947,15 +1971,11 @@ static void construct_linker_job_elf(LinkJob *lj) {
1947 lj->args.append("-lpthread");1971 lj->args.append("-lpthread");
1948 }1972 }
1949 } else if (target_is_glibc(g->zig_target)) {1973 } else if (target_is_glibc(g->zig_target)) {
1950 if (target_supports_libunwind(g->zig_target)) {1974 lj->args.append(build_libunwind(g, lj->build_dep_prog_node));
1951 lj->args.append(build_libunwind(g, lj->build_dep_prog_node));
1952 }
1953 add_glibc_libs(lj);1975 add_glibc_libs(lj);
1954 lj->args.append(get_libc_crt_file(g, "libc_nonshared.a", lj->build_dep_prog_node));1976 lj->args.append(get_libc_crt_file(g, "libc_nonshared.a", lj->build_dep_prog_node));
1955 } else if (target_is_musl(g->zig_target)) {1977 } else if (target_is_musl(g->zig_target)) {
1956 if (target_supports_libunwind(g->zig_target)) {1978 lj->args.append(build_libunwind(g, lj->build_dep_prog_node));
1957 lj->args.append(build_libunwind(g, lj->build_dep_prog_node));
1958 }
1959 lj->args.append(build_musl(g, lj->build_dep_prog_node));1979 lj->args.append(build_musl(g, lj->build_dep_prog_node));
1960 } else if (g->libcpp_link_lib != nullptr) {1980 } else if (g->libcpp_link_lib != nullptr) {
1961 lj->args.append(build_libunwind(g, lj->build_dep_prog_node));1981 lj->args.append(build_libunwind(g, lj->build_dep_prog_node));
...@@ -1973,8 +1993,17 @@ static void construct_linker_job_elf(LinkJob *lj) {...@@ -1973,8 +1993,17 @@ static void construct_linker_job_elf(LinkJob *lj) {
1973 }1993 }
1974 }1994 }
19751995
1976 if (!g->zig_target->is_native_os) {1996 switch (g->linker_allow_shlib_undefined) {
1977 lj->args.append("--allow-shlib-undefined");1997 case OptionalBoolNull:
1998 if (!g->zig_target->is_native_os) {
1999 lj->args.append("--allow-shlib-undefined");
2000 }
2001 break;
2002 case OptionalBoolFalse:
2003 break;
2004 case OptionalBoolTrue:
2005 lj->args.append("--allow-shlib-undefined");
2006 break;
1978 }2007 }
1979}2008}
19802009
...@@ -2384,14 +2413,26 @@ static void construct_linker_job_coff(LinkJob *lj) {...@@ -2384,14 +2413,26 @@ static void construct_linker_job_coff(LinkJob *lj) {
2384 lj->args.append(buf_ptr(buf_sprintf("-OUT:%s", buf_ptr(&g->bin_file_output_path))));2413 lj->args.append(buf_ptr(buf_sprintf("-OUT:%s", buf_ptr(&g->bin_file_output_path))));
23852414
2386 if (g->libc_link_lib != nullptr && g->libc != nullptr) {2415 if (g->libc_link_lib != nullptr && g->libc != nullptr) {
2387 lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->crt_dir)));2416 Buf *buff0 = buf_create_from_str("-LIBPATH:");
2417 buf_append_mem(buff0, g->libc->crt_dir, g->libc->crt_dir_len);
2418 lj->args.append(buf_ptr(buff0));
23882419
2389 if (target_abi_is_gnu(g->zig_target->abi)) {2420 if (target_abi_is_gnu(g->zig_target->abi)) {
2390 lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->sys_include_dir)));2421 Buf *buff1 = buf_create_from_str("-LIBPATH:");
2391 lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->include_dir)));2422 buf_append_mem(buff1, g->libc->sys_include_dir, g->libc->sys_include_dir_len);
2423 lj->args.append(buf_ptr(buff1));
2424
2425 Buf *buff2 = buf_create_from_str("-LIBPATH:");
2426 buf_append_mem(buff2, g->libc->include_dir, g->libc->include_dir_len);
2427 lj->args.append(buf_ptr(buff2));
2392 } else {2428 } else {
2393 lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->msvc_lib_dir)));2429 Buf *buff1 = buf_create_from_str("-LIBPATH:");
2394 lj->args.append(buf_ptr(buf_sprintf("-LIBPATH:%s", g->libc->kernel32_lib_dir)));2430 buf_append_mem(buff1, g->libc->msvc_lib_dir, g->libc->msvc_lib_dir_len);
2431 lj->args.append(buf_ptr(buff1));
2432
2433 Buf *buff2 = buf_create_from_str("-LIBPATH:");
2434 buf_append_mem(buff2, g->libc->kernel32_lib_dir, g->libc->kernel32_lib_dir_len);
2435 lj->args.append(buf_ptr(buff2));
2395 }2436 }
2396 }2437 }
23972438
...@@ -2470,7 +2511,12 @@ static void construct_linker_job_coff(LinkJob *lj) {...@@ -2470,7 +2511,12 @@ static void construct_linker_job_coff(LinkJob *lj) {
2470 if (buf_eql_str(link_lib->name, "c")) {2511 if (buf_eql_str(link_lib->name, "c")) {
2471 continue;2512 continue;
2472 }2513 }
2473 if (buf_eql_str(link_lib->name, "c++") || buf_eql_str(link_lib->name, "c++abi")) {2514 if (target_is_libcpp_lib_name(g->zig_target, buf_ptr(link_lib->name))) {
2515 // libc++ is linked specially
2516 continue;
2517 }
2518 if (g->libc == nullptr && target_is_libc_lib_name(g->zig_target, buf_ptr(link_lib->name))) {
2519 // these libraries are always linked below when targeting glibc
2474 continue;2520 continue;
2475 }2521 }
2476 bool is_sys_lib = is_mingw_link_lib(link_lib->name);2522 bool is_sys_lib = is_mingw_link_lib(link_lib->name);
...@@ -2521,10 +2567,34 @@ static void construct_linker_job_macho(LinkJob *lj) {...@@ -2521,10 +2567,34 @@ static void construct_linker_job_macho(LinkJob *lj) {
2521 //lj->args.append("-error-limit=0");2567 //lj->args.append("-error-limit=0");
2522 lj->args.append("-demangle");2568 lj->args.append("-demangle");
25232569
2570 switch (g->linker_gc_sections) {
2571 case OptionalBoolNull:
2572 // TODO why do we not follow the same logic of elf here?
2573 break;
2574 case OptionalBoolTrue:
2575 lj->args.append("--gc-sections");
2576 break;
2577 case OptionalBoolFalse:
2578 break;
2579 }
2580
2524 if (g->linker_rdynamic) {2581 if (g->linker_rdynamic) {
2525 lj->args.append("-export_dynamic");2582 lj->args.append("-export_dynamic");
2526 }2583 }
25272584
2585 if (g->linker_optimization != nullptr) {
2586 lj->args.append(buf_ptr(g->linker_optimization));
2587 }
2588
2589 if (g->linker_z_nodelete) {
2590 lj->args.append("-z");
2591 lj->args.append("nodelete");
2592 }
2593 if (g->linker_z_defs) {
2594 lj->args.append("-z");
2595 lj->args.append("defs");
2596 }
2597
2528 bool is_lib = g->out_type == OutTypeLib;2598 bool is_lib = g->out_type == OutTypeLib;
2529 bool is_dyn_lib = g->is_dynamic && is_lib;2599 bool is_dyn_lib = g->is_dynamic && is_lib;
2530 if (is_lib && !g->is_dynamic) {2600 if (is_lib && !g->is_dynamic) {
...@@ -2639,9 +2709,20 @@ static void construct_linker_job_macho(LinkJob *lj) {...@@ -2639,9 +2709,20 @@ static void construct_linker_job_macho(LinkJob *lj) {
2639 // and change between versions.2709 // and change between versions.
2640 // so we always link against libSystem2710 // so we always link against libSystem
2641 lj->args.append("-lSystem");2711 lj->args.append("-lSystem");
2642 } else {2712 }
2643 lj->args.append("-undefined");2713 switch (g->linker_allow_shlib_undefined) {
2644 lj->args.append("dynamic_lookup");2714 case OptionalBoolNull:
2715 if (!g->zig_target->is_native_os) {
2716 lj->args.append("-undefined");
2717 lj->args.append("dynamic_lookup");
2718 }
2719 break;
2720 case OptionalBoolFalse:
2721 break;
2722 case OptionalBoolTrue:
2723 lj->args.append("-undefined");
2724 lj->args.append("dynamic_lookup");
2725 break;
2645 }2726 }
26462727
2647 for (size_t i = 0; i < g->framework_dirs.length; i += 1) {2728 for (size_t i = 0; i < g->framework_dirs.length; i += 1) {
src/main.cpp+97-43
...@@ -455,11 +455,15 @@ static int main0(int argc, char **argv) {...@@ -455,11 +455,15 @@ static int main0(int argc, char **argv) {
455 const char *mcpu = nullptr;455 const char *mcpu = nullptr;
456 CodeModel code_model = CodeModelDefault;456 CodeModel code_model = CodeModelDefault;
457 const char *override_soname = nullptr;457 const char *override_soname = nullptr;
458 bool only_preprocess = false;458 bool only_pp_or_asm = false;
459 bool ensure_libc_on_non_freestanding = false;459 bool ensure_libc_on_non_freestanding = false;
460 bool ensure_libcpp_on_non_freestanding = false;460 bool ensure_libcpp_on_non_freestanding = false;
461 bool cpp_rtti = true;461 bool disable_c_depfile = false;
462 bool cpp_exceptions = true;462 Buf *linker_optimization = nullptr;
463 OptionalBool linker_gc_sections = OptionalBoolNull;
464 OptionalBool linker_allow_shlib_undefined = OptionalBoolNull;
465 bool linker_z_nodelete = false;
466 bool linker_z_defs = false;
463467
464 ZigList<const char *> llvm_argv = {0};468 ZigList<const char *> llvm_argv = {0};
465 llvm_argv.append("zig (LLVM option parsing)");469 llvm_argv.append("zig (LLVM option parsing)");
...@@ -617,20 +621,22 @@ static int main0(int argc, char **argv) {...@@ -617,20 +621,22 @@ static int main0(int argc, char **argv) {
617 }621 }
618 break;622 break;
619 case Stage2ClangArgPositional: {623 case Stage2ClangArgPositional: {
620 Buf *arg_buf = buf_create_from_str(it.only_arg);624 FileExt file_ext = classify_file_ext(it.only_arg, strlen(it.only_arg));
621 if (buf_ends_with_str(arg_buf, ".c") ||625 switch (file_ext) {
622 buf_ends_with_str(arg_buf, ".C") ||626 case FileExtAsm:
623 buf_ends_with_str(arg_buf, ".cc") ||627 case FileExtC:
624 buf_ends_with_str(arg_buf, ".cpp") ||628 case FileExtCpp:
625 buf_ends_with_str(arg_buf, ".cxx") ||629 case FileExtLLVMIr:
626 buf_ends_with_str(arg_buf, ".s") ||630 case FileExtLLVMBitCode:
627 buf_ends_with_str(arg_buf, ".S"))631 case FileExtHeader: {
628 {632 CFile *c_file = heap::c_allocator.create<CFile>();
629 CFile *c_file = heap::c_allocator.create<CFile>();633 c_file->source_path = it.only_arg;
630 c_file->source_path = it.only_arg;634 c_source_files.append(c_file);
631 c_source_files.append(c_file);635 break;
632 } else {636 }
633 objects.append(it.only_arg);637 case FileExtUnknown:
638 objects.append(it.only_arg);
639 break;
634 }640 }
635 break;641 break;
636 }642 }
...@@ -676,8 +682,12 @@ static int main0(int argc, char **argv) {...@@ -676,8 +682,12 @@ static int main0(int argc, char **argv) {
676 }682 }
677 break;683 break;
678 }684 }
679 case Stage2ClangArgPreprocess:685 case Stage2ClangArgPreprocessOrAsm:
680 only_preprocess = true;686 // this handles both -E and -S
687 only_pp_or_asm = true;
688 for (size_t i = 0; i < it.other_args_len; i += 1) {
689 clang_argv.append(it.other_args_ptr[i]);
690 }
681 break;691 break;
682 case Stage2ClangArgOptimize:692 case Stage2ClangArgOptimize:
683 // alright what release mode do they want?693 // alright what release mode do they want?
...@@ -688,7 +698,9 @@ static int main0(int argc, char **argv) {...@@ -688,7 +698,9 @@ static int main0(int argc, char **argv) {
688 strcmp(it.only_arg, "O4") == 0)698 strcmp(it.only_arg, "O4") == 0)
689 {699 {
690 build_mode = BuildModeFastRelease;700 build_mode = BuildModeFastRelease;
691 } else if (strcmp(it.only_arg, "Og") == 0) {701 } else if (strcmp(it.only_arg, "Og") == 0 ||
702 strcmp(it.only_arg, "O0") == 0)
703 {
692 build_mode = BuildModeDebug;704 build_mode = BuildModeDebug;
693 } else {705 } else {
694 for (size_t i = 0; i < it.other_args_len; i += 1) {706 for (size_t i = 0; i < it.other_args_len; i += 1) {
...@@ -722,18 +734,6 @@ static int main0(int argc, char **argv) {...@@ -722,18 +734,6 @@ static int main0(int argc, char **argv) {
722 verbose_cc = true;734 verbose_cc = true;
723 verbose_link = true;735 verbose_link = true;
724 break;736 break;
725 case Stage2ClangArgExceptions:
726 cpp_exceptions = true;
727 break;
728 case Stage2ClangArgNoExceptions:
729 cpp_exceptions = false;
730 break;
731 case Stage2ClangArgRtti:
732 cpp_rtti = true;
733 break;
734 case Stage2ClangArgNoRtti:
735 cpp_rtti = false;
736 break;
737 case Stage2ClangArgForLinker:737 case Stage2ClangArgForLinker:
738 linker_args.append(buf_create_from_str(it.only_arg));738 linker_args.append(buf_create_from_str(it.only_arg));
739 break;739 break;
...@@ -741,6 +741,24 @@ static int main0(int argc, char **argv) {...@@ -741,6 +741,24 @@ static int main0(int argc, char **argv) {
741 linker_args.append(buf_create_from_str("-z"));741 linker_args.append(buf_create_from_str("-z"));
742 linker_args.append(buf_create_from_str(it.only_arg));742 linker_args.append(buf_create_from_str(it.only_arg));
743 break;743 break;
744 case Stage2ClangArgLibDir:
745 lib_dirs.append(it.only_arg);
746 break;
747 case Stage2ClangArgMCpu:
748 mcpu = it.only_arg;
749 break;
750 case Stage2ClangArgDepFile:
751 disable_c_depfile = true;
752 for (size_t i = 0; i < it.other_args_len; i += 1) {
753 clang_argv.append(it.other_args_ptr[i]);
754 }
755 break;
756 case Stage2ClangArgFrameworkDir:
757 framework_dirs.append(it.only_arg);
758 break;
759 case Stage2ClangArgFramework:
760 frameworks.append(it.only_arg);
761 break;
744 }762 }
745 }763 }
746 // Parse linker args764 // Parse linker args
...@@ -802,6 +820,37 @@ static int main0(int argc, char **argv) {...@@ -802,6 +820,37 @@ static int main0(int argc, char **argv) {
802 buf_eql_str(arg, "-export-dynamic"))820 buf_eql_str(arg, "-export-dynamic"))
803 {821 {
804 rdynamic = true;822 rdynamic = true;
823 } else if (buf_eql_str(arg, "--version-script")) {
824 i += 1;
825 if (i >= linker_args.length) {
826 fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg));
827 return EXIT_FAILURE;
828 }
829 version_script = linker_args.at(i);
830 } else if (buf_starts_with_str(arg, "-O")) {
831 linker_optimization = arg;
832 } else if (buf_eql_str(arg, "--gc-sections")) {
833 linker_gc_sections = OptionalBoolTrue;
834 } else if (buf_eql_str(arg, "--no-gc-sections")) {
835 linker_gc_sections = OptionalBoolFalse;
836 } else if (buf_eql_str(arg, "--allow-shlib-undefined")) {
837 linker_allow_shlib_undefined = OptionalBoolTrue;
838 } else if (buf_eql_str(arg, "--no-allow-shlib-undefined")) {
839 linker_allow_shlib_undefined = OptionalBoolFalse;
840 } else if (buf_eql_str(arg, "-z")) {
841 i += 1;
842 if (i >= linker_args.length) {
843 fprintf(stderr, "expected linker arg after '%s'\n", buf_ptr(arg));
844 return EXIT_FAILURE;
845 }
846 Buf *z_arg = linker_args.at(i);
847 if (buf_eql_str(z_arg, "nodelete")) {
848 linker_z_nodelete = true;
849 } else if (buf_eql_str(z_arg, "defs")) {
850 linker_z_defs = true;
851 } else {
852 fprintf(stderr, "warning: unsupported linker arg: -z %s\n", buf_ptr(z_arg));
853 }
805 } else {854 } else {
806 fprintf(stderr, "warning: unsupported linker arg: %s\n", buf_ptr(arg));855 fprintf(stderr, "warning: unsupported linker arg: %s\n", buf_ptr(arg));
807 }856 }
...@@ -811,7 +860,7 @@ static int main0(int argc, char **argv) {...@@ -811,7 +860,7 @@ static int main0(int argc, char **argv) {
811 build_mode = BuildModeSafeRelease;860 build_mode = BuildModeSafeRelease;
812 }861 }
813862
814 if (only_preprocess) {863 if (only_pp_or_asm) {
815 cmd = CmdBuild;864 cmd = CmdBuild;
816 out_type = OutTypeObj;865 out_type = OutTypeObj;
817 emit_bin = false;866 emit_bin = false;
...@@ -1329,8 +1378,6 @@ static int main0(int argc, char **argv) {...@@ -1329,8 +1378,6 @@ static int main0(int argc, char **argv) {
1329 LinkLib *link_lib = codegen_add_link_lib(g, buf_create_from_str(link_libs.at(i)));1378 LinkLib *link_lib = codegen_add_link_lib(g, buf_create_from_str(link_libs.at(i)));
1330 link_lib->provided_explicitly = true;1379 link_lib->provided_explicitly = true;
1331 }1380 }
1332 g->cpp_rtti = cpp_rtti;
1333 g->cpp_exceptions = cpp_exceptions;
1334 g->subsystem = subsystem;1381 g->subsystem = subsystem;
1335 g->valgrind_support = valgrind_support;1382 g->valgrind_support = valgrind_support;
1336 g->want_pic = want_pic;1383 g->want_pic = want_pic;
...@@ -1369,15 +1416,17 @@ static int main0(int argc, char **argv) {...@@ -1369,15 +1416,17 @@ static int main0(int argc, char **argv) {
1369 return print_error_usage(arg0);1416 return print_error_usage(arg0);
1370 }1417 }
13711418
1372 bool any_non_c_link_libs = false;1419 bool any_system_lib_dependencies = false;
1373 for (size_t i = 0; i < link_libs.length; i += 1) {1420 for (size_t i = 0; i < link_libs.length; i += 1) {
1374 if (!target_is_libc_lib_name(&target, link_libs.at(i))) {1421 if (!target_is_libc_lib_name(&target, link_libs.at(i)) &&
1375 any_non_c_link_libs = true;1422 !target_is_libcpp_lib_name(&target, link_libs.at(i)))
1423 {
1424 any_system_lib_dependencies = true;
1376 break;1425 break;
1377 }1426 }
1378 }1427 }
13791428
1380 if (target.is_native_os && any_non_c_link_libs) {1429 if (target.is_native_os && any_system_lib_dependencies) {
1381 Error err;1430 Error err;
1382 Stage2NativePaths paths;1431 Stage2NativePaths paths;
1383 if ((err = stage2_detect_native_paths(&paths))) {1432 if ((err = stage2_detect_native_paths(&paths))) {
...@@ -1477,8 +1526,6 @@ static int main0(int argc, char **argv) {...@@ -1477,8 +1526,6 @@ static int main0(int argc, char **argv) {
1477 }1526 }
1478 CodeGen *g = codegen_create(main_pkg_path, zig_root_source_file, &target, out_type, build_mode,1527 CodeGen *g = codegen_create(main_pkg_path, zig_root_source_file, &target, out_type, build_mode,
1479 override_lib_dir, libc, cache_dir_buf, cmd == CmdTest, root_progress_node);1528 override_lib_dir, libc, cache_dir_buf, cmd == CmdTest, root_progress_node);
1480 g->cpp_rtti = cpp_rtti;
1481 g->cpp_exceptions = cpp_exceptions;
1482 if (llvm_argv.length >= 2) codegen_set_llvm_argv(g, llvm_argv.items + 1, llvm_argv.length - 2);1529 if (llvm_argv.length >= 2) codegen_set_llvm_argv(g, llvm_argv.items + 1, llvm_argv.length - 2);
1483 g->valgrind_support = valgrind_support;1530 g->valgrind_support = valgrind_support;
1484 g->link_eh_frame_hdr = link_eh_frame_hdr;1531 g->link_eh_frame_hdr = link_eh_frame_hdr;
...@@ -1522,6 +1569,13 @@ static int main0(int argc, char **argv) {...@@ -1522,6 +1569,13 @@ static int main0(int argc, char **argv) {
1522 g->system_linker_hack = system_linker_hack;1569 g->system_linker_hack = system_linker_hack;
1523 g->function_sections = function_sections;1570 g->function_sections = function_sections;
1524 g->code_model = code_model;1571 g->code_model = code_model;
1572 g->disable_c_depfile = disable_c_depfile;
1573
1574 g->linker_optimization = linker_optimization;
1575 g->linker_gc_sections = linker_gc_sections;
1576 g->linker_allow_shlib_undefined = linker_allow_shlib_undefined;
1577 g->linker_z_nodelete = linker_z_nodelete;
1578 g->linker_z_defs = linker_z_defs;
15251579
1526 if (override_soname) {1580 if (override_soname) {
1527 g->override_soname = buf_create_from_str(override_soname);1581 g->override_soname = buf_create_from_str(override_soname);
...@@ -1611,7 +1665,7 @@ static int main0(int argc, char **argv) {...@@ -1611,7 +1665,7 @@ static int main0(int argc, char **argv) {
1611#endif1665#endif
1612 Buf *dest_path = buf_create_from_str(emit_bin_override_path);1666 Buf *dest_path = buf_create_from_str(emit_bin_override_path);
1613 Buf *source_path;1667 Buf *source_path;
1614 if (only_preprocess) {1668 if (only_pp_or_asm) {
1615 source_path = buf_alloc();1669 source_path = buf_alloc();
1616 Buf *pp_only_basename = buf_create_from_str(1670 Buf *pp_only_basename = buf_create_from_str(
1617 c_source_files.at(0)->preprocessor_only_basename);1671 c_source_files.at(0)->preprocessor_only_basename);
...@@ -1625,7 +1679,7 @@ static int main0(int argc, char **argv) {...@@ -1625,7 +1679,7 @@ static int main0(int argc, char **argv) {
1625 buf_ptr(dest_path), err_str(err));1679 buf_ptr(dest_path), err_str(err));
1626 return main_exit(root_progress_node, EXIT_FAILURE);1680 return main_exit(root_progress_node, EXIT_FAILURE);
1627 }1681 }
1628 } else if (only_preprocess) {1682 } else if (only_pp_or_asm) {
1629#if defined(ZIG_OS_WINDOWS)1683#if defined(ZIG_OS_WINDOWS)
1630 buf_replace(g->c_artifact_dir, '/', '\\');1684 buf_replace(g->c_artifact_dir, '/', '\\');
1631#endif1685#endif
src/os.cpp+6-3
...@@ -1097,8 +1097,8 @@ static Error set_file_times(OsFile file, OsTimeStamp ts) {...@@ -1097,8 +1097,8 @@ static Error set_file_times(OsFile file, OsTimeStamp ts) {
1097 return ErrorNone;1097 return ErrorNone;
1098#else1098#else
1099 struct timespec times[2] = {1099 struct timespec times[2] = {
1100 { (time_t)ts.sec, (time_t)ts.nsec },1100 { (time_t)ts.sec, (long)ts.nsec },
1101 { (time_t)ts.sec, (time_t)ts.nsec },1101 { (time_t)ts.sec, (long)ts.nsec },
1102 };1102 };
1103 if (futimens(file, times) == -1) {1103 if (futimens(file, times) == -1) {
1104 switch (errno) {1104 switch (errno) {
...@@ -1456,7 +1456,10 @@ static void init_rand() {...@@ -1456,7 +1456,10 @@ static void init_rand() {
1456 memcpy(&seed, bytes, sizeof(unsigned));1456 memcpy(&seed, bytes, sizeof(unsigned));
1457 srand(seed);1457 srand(seed);
1458#elif defined(ZIG_OS_LINUX)1458#elif defined(ZIG_OS_LINUX)
1459 srand(*((unsigned*)getauxval(AT_RANDOM)));1459 unsigned char *ptr_random = (unsigned char*)getauxval(AT_RANDOM);
1460 unsigned seed;
1461 memcpy(&seed, ptr_random, sizeof(seed));
1462 srand(seed);
1460#else1463#else
1461 int fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);1464 int fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC);
1462 if (fd == -1) {1465 if (fd == -1) {
src/stage2.h+6-5
...@@ -342,18 +342,19 @@ enum Stage2ClangArg {...@@ -342,18 +342,19 @@ enum Stage2ClangArg {
342 Stage2ClangArgShared,342 Stage2ClangArgShared,
343 Stage2ClangArgRDynamic,343 Stage2ClangArgRDynamic,
344 Stage2ClangArgWL,344 Stage2ClangArgWL,
345 Stage2ClangArgPreprocess,345 Stage2ClangArgPreprocessOrAsm,
346 Stage2ClangArgOptimize,346 Stage2ClangArgOptimize,
347 Stage2ClangArgDebug,347 Stage2ClangArgDebug,
348 Stage2ClangArgSanitize,348 Stage2ClangArgSanitize,
349 Stage2ClangArgLinkerScript,349 Stage2ClangArgLinkerScript,
350 Stage2ClangArgVerboseCmds,350 Stage2ClangArgVerboseCmds,
351 Stage2ClangArgExceptions,
352 Stage2ClangArgNoExceptions,
353 Stage2ClangArgRtti,
354 Stage2ClangArgNoRtti,
355 Stage2ClangArgForLinker,351 Stage2ClangArgForLinker,
356 Stage2ClangArgLinkerInputZ,352 Stage2ClangArgLinkerInputZ,
353 Stage2ClangArgLibDir,
354 Stage2ClangArgMCpu,
355 Stage2ClangArgDepFile,
356 Stage2ClangArgFrameworkDir,
357 Stage2ClangArgFramework,
357};358};
358359
359// ABI warning360// ABI warning
src/target.cpp+14-13
...@@ -624,6 +624,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {...@@ -624,6 +624,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
624 case CIntTypeCount:624 case CIntTypeCount:
625 zig_unreachable();625 zig_unreachable();
626 }626 }
627 zig_unreachable();
627 default:628 default:
628 switch (id) {629 switch (id) {
629 case CIntTypeShort:630 case CIntTypeShort:
...@@ -642,6 +643,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {...@@ -642,6 +643,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
642 zig_unreachable();643 zig_unreachable();
643 }644 }
644 }645 }
646 zig_unreachable();
645 case OsLinux:647 case OsLinux:
646 case OsMacOSX:648 case OsMacOSX:
647 case OsFreeBSD:649 case OsFreeBSD:
...@@ -666,6 +668,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {...@@ -666,6 +668,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
666 case CIntTypeCount:668 case CIntTypeCount:
667 zig_unreachable();669 zig_unreachable();
668 }670 }
671 zig_unreachable();
669 case OsUefi:672 case OsUefi:
670 case OsWindows:673 case OsWindows:
671 switch (id) {674 switch (id) {
...@@ -683,6 +686,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {...@@ -683,6 +686,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
683 case CIntTypeCount:686 case CIntTypeCount:
684 zig_unreachable();687 zig_unreachable();
685 }688 }
689 zig_unreachable();
686 case OsIOS:690 case OsIOS:
687 switch (id) {691 switch (id) {
688 case CIntTypeShort:692 case CIntTypeShort:
...@@ -699,6 +703,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {...@@ -699,6 +703,7 @@ uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
699 case CIntTypeCount:703 case CIntTypeCount:
700 zig_unreachable();704 zig_unreachable();
701 }705 }
706 zig_unreachable();
702 case OsAnanas:707 case OsAnanas:
703 case OsCloudABI:708 case OsCloudABI:
704 case OsKFreeBSD:709 case OsKFreeBSD:
...@@ -1207,6 +1212,15 @@ bool target_is_libc_lib_name(const ZigTarget *target, const char *name) {...@@ -1207,6 +1212,15 @@ bool target_is_libc_lib_name(const ZigTarget *target, const char *name) {
1207 if (strcmp(name, "c") == 0)1212 if (strcmp(name, "c") == 0)
1208 return true;1213 return true;
12091214
1215 if (target_abi_is_gnu(target->abi) && target->os == OsWindows) {
1216 // mingw-w64
1217
1218 if (strcmp(name, "m") == 0)
1219 return true;
1220
1221 return false;
1222 }
1223
1210 if (target_abi_is_gnu(target->abi) || target_abi_is_musl(target->abi) || target_os_is_darwin(target->os)) {1224 if (target_abi_is_gnu(target->abi) || target_abi_is_musl(target->abi) || target_os_is_darwin(target->os)) {
1211 if (strcmp(name, "m") == 0)1225 if (strcmp(name, "m") == 0)
1212 return true;1226 return true;
...@@ -1286,19 +1300,6 @@ const char *target_arch_musl_name(ZigLLVM_ArchType arch) {...@@ -1286,19 +1300,6 @@ const char *target_arch_musl_name(ZigLLVM_ArchType arch) {
1286 }1300 }
1287}1301}
12881302
1289bool target_supports_libunwind(const ZigTarget *target) {
1290 switch (target->arch) {
1291 case ZigLLVM_arm:
1292 case ZigLLVM_armeb:
1293 case ZigLLVM_riscv32:
1294 case ZigLLVM_riscv64:
1295 return false;
1296 default:
1297 return true;
1298 }
1299 return true;
1300}
1301
1302bool target_libc_needs_crti_crtn(const ZigTarget *target) {1303bool target_libc_needs_crti_crtn(const ZigTarget *target) {
1303 if (target->arch == ZigLLVM_riscv32 || target->arch == ZigLLVM_riscv64 || target_is_android(target)) {1304 if (target->arch == ZigLLVM_riscv32 || target->arch == ZigLLVM_riscv64 || target_is_android(target)) {
1304 return false;1305 return false;
src/target.hpp-1
...@@ -119,7 +119,6 @@ bool target_supports_stack_probing(const ZigTarget *target);...@@ -119,7 +119,6 @@ bool target_supports_stack_probing(const ZigTarget *target);
119bool target_supports_sanitize_c(const ZigTarget *target);119bool target_supports_sanitize_c(const ZigTarget *target);
120bool target_has_debug_info(const ZigTarget *target);120bool target_has_debug_info(const ZigTarget *target);
121const char *target_arch_musl_name(ZigLLVM_ArchType arch);121const char *target_arch_musl_name(ZigLLVM_ArchType arch);
122bool target_supports_libunwind(const ZigTarget *target);
123122
124uint32_t target_arch_pointer_bit_width(ZigLLVM_ArchType arch);123uint32_t target_arch_pointer_bit_width(ZigLLVM_ArchType arch);
125uint32_t target_arch_largest_atomic_bits(ZigLLVM_ArchType arch);124uint32_t target_arch_largest_atomic_bits(ZigLLVM_ArchType arch);
src/tokenizer.cpp+12-3
...@@ -840,6 +840,7 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -840,6 +840,7 @@ void tokenize(Buf *buf, Tokenization *out) {
840 t.state = TokenizeStateStart;840 t.state = TokenizeStateStart;
841 continue;841 continue;
842 }842 }
843 break;
843 case TokenizeStateSawSlash:844 case TokenizeStateSawSlash:
844 switch (c) {845 switch (c) {
845 case '/':846 case '/':
...@@ -1209,7 +1210,7 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -1209,7 +1210,7 @@ void tokenize(Buf *buf, Tokenization *out) {
1209 t.is_trailing_underscore = false;1210 t.is_trailing_underscore = false;
1210 t.state = TokenizeStateNumber;1211 t.state = TokenizeStateNumber;
1211 }1212 }
1212 // fall through1213 ZIG_FALLTHROUGH;
1213 case TokenizeStateNumber:1214 case TokenizeStateNumber:
1214 {1215 {
1215 if (c == '_') {1216 if (c == '_') {
...@@ -1291,7 +1292,7 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -1291,7 +1292,7 @@ void tokenize(Buf *buf, Tokenization *out) {
1291 t.is_trailing_underscore = false;1292 t.is_trailing_underscore = false;
1292 t.state = TokenizeStateFloatFraction;1293 t.state = TokenizeStateFloatFraction;
1293 }1294 }
1294 // fall through1295 ZIG_FALLTHROUGH;
1295 case TokenizeStateFloatFraction:1296 case TokenizeStateFloatFraction:
1296 {1297 {
1297 if (c == '_') {1298 if (c == '_') {
...@@ -1350,7 +1351,7 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -1350,7 +1351,7 @@ void tokenize(Buf *buf, Tokenization *out) {
1350 t.is_trailing_underscore = false;1351 t.is_trailing_underscore = false;
1351 t.state = TokenizeStateFloatExponentNumber;1352 t.state = TokenizeStateFloatExponentNumber;
1352 }1353 }
1353 // fall through1354 ZIG_FALLTHROUGH;
1354 case TokenizeStateFloatExponentNumber:1355 case TokenizeStateFloatExponentNumber:
1355 {1356 {
1356 if (c == '_') {1357 if (c == '_') {
...@@ -1494,9 +1495,17 @@ void tokenize(Buf *buf, Tokenization *out) {...@@ -1494,9 +1495,17 @@ void tokenize(Buf *buf, Tokenization *out) {
1494 tokenize_error(&t, "unexpected EOF");1495 tokenize_error(&t, "unexpected EOF");
1495 break;1496 break;
1496 case TokenizeStateLineComment:1497 case TokenizeStateLineComment:
1498 break;
1497 case TokenizeStateSawSlash2:1499 case TokenizeStateSawSlash2:
1500 cancel_token(&t);
1501 break;
1498 case TokenizeStateSawSlash3:1502 case TokenizeStateSawSlash3:
1503 set_token_id(&t, t.cur_tok, TokenIdDocComment);
1504 end_token(&t);
1505 break;
1499 case TokenizeStateSawSlashBang:1506 case TokenizeStateSawSlashBang:
1507 set_token_id(&t, t.cur_tok, TokenIdContainerDocComment);
1508 end_token(&t);
1500 break;1509 break;
1501 }1510 }
1502 if (t.state != TokenizeStateError) {1511 if (t.state != TokenizeStateError) {
src/util.hpp+9
...@@ -100,6 +100,15 @@ static inline bool is_power_of_2(uint64_t x) {...@@ -100,6 +100,15 @@ static inline bool is_power_of_2(uint64_t x) {
100 return x != 0 && ((x & (~x + 1)) == x);100 return x != 0 && ((x & (~x + 1)) == x);
101}101}
102102
103static inline bool mem_ends_with_mem(const char *mem, size_t mem_len, const char *end, size_t end_len) {
104 if (mem_len < end_len) return false;
105 return memcmp(mem + mem_len - end_len, end, end_len) == 0;
106}
107
108static inline bool mem_ends_with_str(const char *mem, size_t mem_len, const char *str) {
109 return mem_ends_with_mem(mem, mem_len, str, strlen(str));
110}
111
103static inline uint64_t round_to_next_power_of_2(uint64_t x) {112static inline uint64_t round_to_next_power_of_2(uint64_t x) {
104 --x;113 --x;
105 x |= x >> 1;114 x |= x >> 1;
src/util_base.hpp+10
...@@ -64,4 +64,14 @@ static inline void zig_assert(bool ok, const char *file, int line, const char *f...@@ -64,4 +64,14 @@ static inline void zig_assert(bool ok, const char *file, int line, const char *f
64#undef assert64#undef assert
65#define assert(ok) zig_assert(ok, __FILE__, __LINE__, __func__)65#define assert(ok) zig_assert(ok, __FILE__, __LINE__, __func__)
6666
67#if defined(_MSC_VER)
68#define ZIG_FALLTHROUGH
69#elif defined(__clang__)
70#define ZIG_FALLTHROUGH [[clang::fallthrough]]
71#elif defined(__GNUC__)
72#define ZIG_FALLTHROUGH __attribute__((fallthrough))
73#else
74#define ZIG_FALLTHROUGH
75#endif
76
67#endif77#endif
src/zig_clang.h+2
...@@ -52,6 +52,8 @@ struct ZigClangAPValue {...@@ -52,6 +52,8 @@ struct ZigClangAPValue {
52 // experimentally-derived size of clang::APValue::DataType52 // experimentally-derived size of clang::APValue::DataType
53#if defined(_WIN32) && defined(_MSC_VER)53#if defined(_WIN32) && defined(_MSC_VER)
54 char Data[52];54 char Data[52];
55#elif defined(__i386__)
56 char Data[48];
55#else57#else
56 char Data[68];58 char Data[68];
57#endif59#endif
test/cli.zig+8-3
...@@ -59,7 +59,12 @@ fn printCmd(cwd: []const u8, argv: []const []const u8) void {...@@ -59,7 +59,12 @@ fn printCmd(cwd: []const u8, argv: []const []const u8) void {
5959
60fn exec(cwd: []const u8, argv: []const []const u8) !ChildProcess.ExecResult {60fn exec(cwd: []const u8, argv: []const []const u8) !ChildProcess.ExecResult {
61 const max_output_size = 100 * 1024;61 const max_output_size = 100 * 1024;
62 const result = ChildProcess.exec(a, argv, cwd, null, max_output_size) catch |err| {62 const result = ChildProcess.exec(.{
63 .allocator = a,
64 .argv = argv,
65 .cwd = cwd,
66 .max_output_bytes = max_output_size,
67 }) catch |err| {
63 std.debug.warn("The following command failed:\n", .{});68 std.debug.warn("The following command failed:\n", .{});
64 printCmd(cwd, argv);69 printCmd(cwd, argv);
65 return err;70 return err;
...@@ -101,7 +106,7 @@ fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {...@@ -101,7 +106,7 @@ fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {
101 const example_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.zig" });106 const example_zig_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.zig" });
102 const example_s_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.s" });107 const example_s_path = try fs.path.join(a, &[_][]const u8{ dir_path, "example.s" });
103108
104 try std.io.writeFile(example_zig_path,109 try fs.cwd().writeFile(example_zig_path,
105 \\// Type your code here, or load an example.110 \\// Type your code here, or load an example.
106 \\export fn square(num: i32) i32 {111 \\export fn square(num: i32) i32 {
107 \\ return num * num;112 \\ return num * num;
...@@ -124,7 +129,7 @@ fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {...@@ -124,7 +129,7 @@ fn testGodboltApi(zig_exe: []const u8, dir_path: []const u8) anyerror!void {
124 };129 };
125 _ = try exec(dir_path, &args);130 _ = try exec(dir_path, &args);
126131
127 const out_asm = try std.io.readFileAlloc(a, example_s_path);132 const out_asm = try std.fs.cwd().readFileAlloc(a, example_s_path, std.math.maxInt(usize));
128 testing.expect(std.mem.indexOf(u8, out_asm, "square:") != null);133 testing.expect(std.mem.indexOf(u8, out_asm, "square:") != null);
129 testing.expect(std.mem.indexOf(u8, out_asm, "mov\teax, edi") != null);134 testing.expect(std.mem.indexOf(u8, out_asm, "mov\teax, edi") != null);
130 testing.expect(std.mem.indexOf(u8, out_asm, "imul\teax, edi") != null);135 testing.expect(std.mem.indexOf(u8, out_asm, "imul\teax, edi") != null);
test/compile_errors.zig+52-1
...@@ -2,6 +2,19 @@ const tests = @import("tests.zig");...@@ -2,6 +2,19 @@ const tests = @import("tests.zig");
2const std = @import("std");2const std = @import("std");
33
4pub fn addCases(cases: *tests.CompileErrorContext) void {4pub fn addCases(cases: *tests.CompileErrorContext) void {
5 cases.addTest("cast between ?T where T is not a pointer",
6 \\pub const fnty1 = ?fn (i8) void;
7 \\pub const fnty2 = ?fn (u64) void;
8 \\export fn entry() void {
9 \\ var a: fnty1 = undefined;
10 \\ var b: fnty2 = undefined;
11 \\ a = b;
12 \\}
13 , &[_][]const u8{
14 "tmp.zig:6:9: error: expected type '?fn(i8) void', found '?fn(u64) void'",
15 "tmp.zig:6:9: note: optional type child 'fn(u64) void' cannot cast into optional type child 'fn(i8) void'",
16 });
17
5 cases.addTest("unused variable error on errdefer",18 cases.addTest("unused variable error on errdefer",
6 \\fn foo() !void {19 \\fn foo() !void {
7 \\ errdefer |a| unreachable;20 \\ errdefer |a| unreachable;
...@@ -1188,7 +1201,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -1188,7 +1201,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
1188 \\ suspend;1201 \\ suspend;
1189 \\}1202 \\}
1190 , &[_][]const u8{1203 , &[_][]const u8{
1191 "tmp.zig:3:5: error: expected type '*@Frame(bar)', found '*@Frame(foo)'",1204 "tmp.zig:3:13: error: expected type '*@Frame(bar)', found '*@Frame(foo)'",
1192 });1205 });
11931206
1194 cases.add("@Frame() of generic function",1207 cases.add("@Frame() of generic function",
...@@ -6806,4 +6819,42 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -6806,4 +6819,42 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
6806 , &[_][]const u8{6819 , &[_][]const u8{
6807 "tmp.zig:2:27: error: type 'u32' does not support array initialization",6820 "tmp.zig:2:27: error: type 'u32' does not support array initialization",
6808 });6821 });
6822
6823 cases.add("issue #2687: coerce from undefined array pointer to slice",
6824 \\export fn foo1() void {
6825 \\ const a: *[1]u8 = undefined;
6826 \\ var b: []u8 = a;
6827 \\}
6828 \\export fn foo2() void {
6829 \\ comptime {
6830 \\ var a: *[1]u8 = undefined;
6831 \\ var b: []u8 = a;
6832 \\ }
6833 \\}
6834 \\export fn foo3() void {
6835 \\ comptime {
6836 \\ const a: *[1]u8 = undefined;
6837 \\ var b: []u8 = a;
6838 \\ }
6839 \\}
6840 , &[_][]const u8{
6841 "tmp.zig:3:19: error: use of undefined value here causes undefined behavior",
6842 "tmp.zig:8:23: error: use of undefined value here causes undefined behavior",
6843 "tmp.zig:14:23: error: use of undefined value here causes undefined behavior",
6844 });
6845
6846 cases.add("issue #3818: bitcast from parray/slice to u16",
6847 \\export fn foo1() void {
6848 \\ var bytes = [_]u8{1, 2};
6849 \\ const word: u16 = @bitCast(u16, bytes[0..]);
6850 \\}
6851 \\export fn foo2() void {
6852 \\ var bytes: []u8 = &[_]u8{1, 2};
6853 \\ const word: u16 = @bitCast(u16, bytes);
6854 \\}
6855 , &[_][]const u8{
6856 "tmp.zig:3:42: error: unable to @bitCast from pointer type '*[2]u8'",
6857 "tmp.zig:7:32: error: destination type 'u16' has size 2 but source type '[]u8' has size 16",
6858 "tmp.zig:7:37: note: referenced here",
6859 });
6809}6860}
test/src/compare_output.zig+4-4
...@@ -91,7 +91,7 @@ pub const CompareOutputContext = struct {...@@ -91,7 +91,7 @@ pub const CompareOutputContext = struct {
91 const b = self.b;91 const b = self.b;
9292
93 const write_src = b.addWriteFiles();93 const write_src = b.addWriteFiles();
94 for (case.sources.toSliceConst()) |src_file| {94 for (case.sources.span()) |src_file| {
95 write_src.add(src_file.filename, src_file.source);95 write_src.add(src_file.filename, src_file.source);
96 }96 }
9797
...@@ -105,7 +105,7 @@ pub const CompareOutputContext = struct {...@@ -105,7 +105,7 @@ pub const CompareOutputContext = struct {
105 }105 }
106106
107 const exe = b.addExecutable("test", null);107 const exe = b.addExecutable("test", null);
108 exe.addAssemblyFileFromWriteFileStep(write_src, case.sources.toSliceConst()[0].filename);108 exe.addAssemblyFileFromWriteFileStep(write_src, case.sources.span()[0].filename);
109109
110 const run = exe.run();110 const run = exe.run();
111 run.addArgs(case.cli_args);111 run.addArgs(case.cli_args);
...@@ -125,7 +125,7 @@ pub const CompareOutputContext = struct {...@@ -125,7 +125,7 @@ pub const CompareOutputContext = struct {
125 if (mem.indexOf(u8, annotated_case_name, filter) == null) continue;125 if (mem.indexOf(u8, annotated_case_name, filter) == null) continue;
126 }126 }
127127
128 const basename = case.sources.toSliceConst()[0].filename;128 const basename = case.sources.span()[0].filename;
129 const exe = b.addExecutableFromWriteFileStep("test", write_src, basename);129 const exe = b.addExecutableFromWriteFileStep("test", write_src, basename);
130 exe.setBuildMode(mode);130 exe.setBuildMode(mode);
131 if (case.link_libc) {131 if (case.link_libc) {
...@@ -146,7 +146,7 @@ pub const CompareOutputContext = struct {...@@ -146,7 +146,7 @@ pub const CompareOutputContext = struct {
146 if (mem.indexOf(u8, annotated_case_name, filter) == null) return;146 if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
147 }147 }
148148
149 const basename = case.sources.toSliceConst()[0].filename;149 const basename = case.sources.span()[0].filename;
150 const exe = b.addExecutableFromWriteFileStep("test", write_src, basename);150 const exe = b.addExecutableFromWriteFileStep("test", write_src, basename);
151 if (case.link_libc) {151 if (case.link_libc) {
152 exe.linkSystemLibrary("c");152 exe.linkSystemLibrary("c");
test/src/run_translated_c.zig+2-2
...@@ -82,13 +82,13 @@ pub const RunTranslatedCContext = struct {...@@ -82,13 +82,13 @@ pub const RunTranslatedCContext = struct {
82 }82 }
8383
84 const write_src = b.addWriteFiles();84 const write_src = b.addWriteFiles();
85 for (case.sources.toSliceConst()) |src_file| {85 for (case.sources.span()) |src_file| {
86 write_src.add(src_file.filename, src_file.source);86 write_src.add(src_file.filename, src_file.source);
87 }87 }
88 const translate_c = b.addTranslateC(.{88 const translate_c = b.addTranslateC(.{
89 .write_file = .{89 .write_file = .{
90 .step = write_src,90 .step = write_src,
91 .basename = case.sources.toSliceConst()[0].filename,91 .basename = case.sources.span()[0].filename,
92 },92 },
93 });93 });
94 translate_c.step.name = b.fmt("{} translate-c", .{annotated_case_name});94 translate_c.step.name = b.fmt("{} translate-c", .{annotated_case_name});
test/src/translate_c.zig+3-3
...@@ -105,20 +105,20 @@ pub const TranslateCContext = struct {...@@ -105,20 +105,20 @@ pub const TranslateCContext = struct {
105 }105 }
106106
107 const write_src = b.addWriteFiles();107 const write_src = b.addWriteFiles();
108 for (case.sources.toSliceConst()) |src_file| {108 for (case.sources.span()) |src_file| {
109 write_src.add(src_file.filename, src_file.source);109 write_src.add(src_file.filename, src_file.source);
110 }110 }
111111
112 const translate_c = b.addTranslateC(.{112 const translate_c = b.addTranslateC(.{
113 .write_file = .{113 .write_file = .{
114 .step = write_src,114 .step = write_src,
115 .basename = case.sources.toSliceConst()[0].filename,115 .basename = case.sources.span()[0].filename,
116 },116 },
117 });117 });
118 translate_c.step.name = annotated_case_name;118 translate_c.step.name = annotated_case_name;
119 translate_c.setTarget(case.target);119 translate_c.setTarget(case.target);
120120
121 const check_file = translate_c.addCheckFile(case.expected_lines.toSliceConst());121 const check_file = translate_c.addCheckFile(case.expected_lines.span());
122122
123 self.step.dependOn(&check_file.step);123 self.step.dependOn(&check_file.step);
124 }124 }
test/stage1/behavior.zig+3
...@@ -41,6 +41,9 @@ comptime {...@@ -41,6 +41,9 @@ comptime {
41 _ = @import("behavior/bugs/3586.zig");41 _ = @import("behavior/bugs/3586.zig");
42 _ = @import("behavior/bugs/3742.zig");42 _ = @import("behavior/bugs/3742.zig");
43 _ = @import("behavior/bugs/4560.zig");43 _ = @import("behavior/bugs/4560.zig");
44 _ = @import("behavior/bugs/4769_a.zig");
45 _ = @import("behavior/bugs/4769_b.zig");
46 _ = @import("behavior/bugs/4769_c.zig");
44 _ = @import("behavior/bugs/394.zig");47 _ = @import("behavior/bugs/394.zig");
45 _ = @import("behavior/bugs/421.zig");48 _ = @import("behavior/bugs/421.zig");
46 _ = @import("behavior/bugs/529.zig");49 _ = @import("behavior/bugs/529.zig");
test/stage1/behavior/array.zig+14-5
...@@ -31,14 +31,23 @@ fn getArrayLen(a: []const u32) usize {...@@ -31,14 +31,23 @@ fn getArrayLen(a: []const u32) usize {
31test "array with sentinels" {31test "array with sentinels" {
32 const S = struct {32 const S = struct {
33 fn doTheTest(is_ct: bool) void {33 fn doTheTest(is_ct: bool) void {
34 var zero_sized: [0:0xde]u8 = [_:0xde]u8{};
35 expectEqual(@as(u8, 0xde), zero_sized[0]);
36 // Disabled at runtime because of
37 // https://github.com/ziglang/zig/issues/4372
38 if (is_ct) {34 if (is_ct) {
35 var zero_sized: [0:0xde]u8 = [_:0xde]u8{};
36 // Disabled at runtime because of
37 // https://github.com/ziglang/zig/issues/4372
38 expectEqual(@as(u8, 0xde), zero_sized[0]);
39 var reinterpreted = @ptrCast(*[1]u8, &zero_sized);39 var reinterpreted = @ptrCast(*[1]u8, &zero_sized);
40 expectEqual(@as(u8, 0xde), reinterpreted[0]);40 expectEqual(@as(u8, 0xde), reinterpreted[0]);
41 }41 }
42 var arr: [3:0x55]u8 = undefined;
43 // Make sure the sentinel pointer is pointing after the last element
44 if (!is_ct) {
45 const sentinel_ptr = @ptrToInt(&arr[3]);
46 const last_elem_ptr = @ptrToInt(&arr[2]);
47 expectEqual(@as(usize, 1), sentinel_ptr - last_elem_ptr);
48 }
49 // Make sure the sentinel is writeable
50 arr[3] = 0x55;
42 }51 }
43 };52 };
4453
...@@ -372,7 +381,7 @@ test "access the null element of a null terminated array" {...@@ -372,7 +381,7 @@ test "access the null element of a null terminated array" {
372 const S = struct {381 const S = struct {
373 fn doTheTest() void {382 fn doTheTest() void {
374 var array: [4:0]u8 = .{ 'a', 'o', 'e', 'u' };383 var array: [4:0]u8 = .{ 'a', 'o', 'e', 'u' };
375 comptime expect(array[4] == 0);384 expect(array[4] == 0);
376 var len: usize = 4;385 var len: usize = 4;
377 expect(array[len] == 0);386 expect(array[len] == 0);
378 }387 }
test/stage1/behavior/atomics.zig-2
...@@ -190,8 +190,6 @@ fn testAtomicRmwInt() void {...@@ -190,8 +190,6 @@ fn testAtomicRmwInt() void {
190 _ = @atomicRmw(u8, &x, .Xor, 2, .SeqCst);190 _ = @atomicRmw(u8, &x, .Xor, 2, .SeqCst);
191 expect(x == 0xfd);191 expect(x == 0xfd);
192192
193 // TODO https://github.com/ziglang/zig/issues/4724
194 if (builtin.arch == .mipsel) return;
195 _ = @atomicRmw(u8, &x, .Max, 1, .SeqCst);193 _ = @atomicRmw(u8, &x, .Max, 1, .SeqCst);
196 expect(x == 0xfd);194 expect(x == 0xfd);
197 _ = @atomicRmw(u8, &x, .Min, 1, .SeqCst);195 _ = @atomicRmw(u8, &x, .Min, 1, .SeqCst);
test/stage1/behavior/bugs/4769_a.zig created+1
...@@ -0,0 +1 @@
1//
\ No newline at end of file
test/stage1/behavior/bugs/4769_b.zig created+1
...@@ -0,0 +1 @@
1//!
\ No newline at end of file
test/stage1/behavior/bugs/4769_c.zig created+1
...@@ -0,0 +1 @@
1///
\ No newline at end of file
test/stage1/behavior/cast.zig+16-1
...@@ -329,7 +329,7 @@ fn testCastPtrOfArrayToSliceAndPtr() void {...@@ -329,7 +329,7 @@ fn testCastPtrOfArrayToSliceAndPtr() void {
329test "cast *[1][*]const u8 to [*]const ?[*]const u8" {329test "cast *[1][*]const u8 to [*]const ?[*]const u8" {
330 const window_name = [1][*]const u8{"window name"};330 const window_name = [1][*]const u8{"window name"};
331 const x: [*]const ?[*]const u8 = &window_name;331 const x: [*]const ?[*]const u8 = &window_name;
332 expect(mem.eql(u8, std.mem.toSliceConst(u8, @ptrCast([*:0]const u8, x[0].?)), "window name"));332 expect(mem.eql(u8, std.mem.spanZ(@ptrCast([*:0]const u8, x[0].?)), "window name"));
333}333}
334334
335test "@intCast comptime_int" {335test "@intCast comptime_int" {
...@@ -790,3 +790,18 @@ test "assignment to optional pointer result loc" {...@@ -790,3 +790,18 @@ test "assignment to optional pointer result loc" {
790 var foo: struct { ptr: ?*c_void } = .{ .ptr = &global_struct };790 var foo: struct { ptr: ?*c_void } = .{ .ptr = &global_struct };
791 expect(foo.ptr.? == @ptrCast(*c_void, &global_struct));791 expect(foo.ptr.? == @ptrCast(*c_void, &global_struct));
792}792}
793
794test "peer type resolve string lit with sentinel-terminated mutable slice" {
795 var array: [4:0]u8 = undefined;
796 array[4] = 0; // TODO remove this when #4372 is solved
797 var slice: [:0]u8 = array[0..4 :0];
798 comptime expect(@TypeOf(slice, "hi") == [:0]const u8);
799 comptime expect(@TypeOf("hi", slice) == [:0]const u8);
800}
801
802test "peer type resolve array pointers, one of them const" {
803 var array1: [4]u8 = undefined;
804 const array2: [5]u8 = undefined;
805 comptime expect(@TypeOf(&array1, &array2) == []const u8);
806 comptime expect(@TypeOf(&array2, &array1) == []const u8);
807}
test/stage1/behavior/pointers.zig+1-1
...@@ -225,7 +225,7 @@ test "null terminated pointer" {...@@ -225,7 +225,7 @@ test "null terminated pointer" {
225 var zero_ptr: [*:0]const u8 = @ptrCast([*:0]const u8, &array_with_zero);225 var zero_ptr: [*:0]const u8 = @ptrCast([*:0]const u8, &array_with_zero);
226 var no_zero_ptr: [*]const u8 = zero_ptr;226 var no_zero_ptr: [*]const u8 = zero_ptr;
227 var zero_ptr_again = @ptrCast([*:0]const u8, no_zero_ptr);227 var zero_ptr_again = @ptrCast([*:0]const u8, no_zero_ptr);
228 expect(std.mem.eql(u8, std.mem.toSliceConst(u8, zero_ptr_again), "hello"));228 expect(std.mem.eql(u8, std.mem.spanZ(zero_ptr_again), "hello"));
229 }229 }
230 };230 };
231 S.doTheTest();231 S.doTheTest();
test/standalone/brace_expansion/main.zig+24-24
...@@ -4,7 +4,7 @@ const mem = std.mem;...@@ -4,7 +4,7 @@ const mem = std.mem;
4const debug = std.debug;4const debug = std.debug;
5const assert = debug.assert;5const assert = debug.assert;
6const testing = std.testing;6const testing = std.testing;
7const Buffer = std.Buffer;7const ArrayListSentineled = std.ArrayListSentineled;
8const ArrayList = std.ArrayList;8const ArrayList = std.ArrayList;
9const maxInt = std.math.maxInt;9const maxInt = std.math.maxInt;
1010
...@@ -111,7 +111,7 @@ fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node {...@@ -111,7 +111,7 @@ fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node {
111 }111 }
112}112}
113113
114fn expandString(input: []const u8, output: *Buffer) !void {114fn expandString(input: []const u8, output: *ArrayListSentineled(u8, 0)) !void {
115 const tokens = try tokenize(input);115 const tokens = try tokenize(input);
116 if (tokens.len == 1) {116 if (tokens.len == 1) {
117 return output.resize(0);117 return output.resize(0);
...@@ -125,52 +125,52 @@ fn expandString(input: []const u8, output: *Buffer) !void {...@@ -125,52 +125,52 @@ fn expandString(input: []const u8, output: *Buffer) !void {
125 else => return error.InvalidInput,125 else => return error.InvalidInput,
126 }126 }
127127
128 var result_list = ArrayList(Buffer).init(global_allocator);128 var result_list = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator);
129 defer result_list.deinit();129 defer result_list.deinit();
130130
131 try expandNode(root, &result_list);131 try expandNode(root, &result_list);
132132
133 try output.resize(0);133 try output.resize(0);
134 for (result_list.toSliceConst()) |buf, i| {134 for (result_list.span()) |buf, i| {
135 if (i != 0) {135 if (i != 0) {
136 try output.appendByte(' ');136 try output.append(' ');
137 }137 }
138 try output.append(buf.toSliceConst());138 try output.appendSlice(buf.span());
139 }139 }
140}140}
141141
142const ExpandNodeError = error{OutOfMemory};142const ExpandNodeError = error{OutOfMemory};
143143
144fn expandNode(node: Node, output: *ArrayList(Buffer)) ExpandNodeError!void {144fn expandNode(node: Node, output: *ArrayList(ArrayListSentineled(u8, 0))) ExpandNodeError!void {
145 assert(output.len == 0);145 assert(output.len == 0);
146 switch (node) {146 switch (node) {
147 Node.Scalar => |scalar| {147 Node.Scalar => |scalar| {
148 try output.append(try Buffer.init(global_allocator, scalar));148 try output.append(try ArrayListSentineled(u8, 0).init(global_allocator, scalar));
149 },149 },
150 Node.Combine => |pair| {150 Node.Combine => |pair| {
151 const a_node = pair[0];151 const a_node = pair[0];
152 const b_node = pair[1];152 const b_node = pair[1];
153153
154 var child_list_a = ArrayList(Buffer).init(global_allocator);154 var child_list_a = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator);
155 try expandNode(a_node, &child_list_a);155 try expandNode(a_node, &child_list_a);
156156
157 var child_list_b = ArrayList(Buffer).init(global_allocator);157 var child_list_b = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator);
158 try expandNode(b_node, &child_list_b);158 try expandNode(b_node, &child_list_b);
159159
160 for (child_list_a.toSliceConst()) |buf_a| {160 for (child_list_a.span()) |buf_a| {
161 for (child_list_b.toSliceConst()) |buf_b| {161 for (child_list_b.span()) |buf_b| {
162 var combined_buf = try Buffer.initFromBuffer(buf_a);162 var combined_buf = try ArrayListSentineled(u8, 0).initFromBuffer(buf_a);
163 try combined_buf.append(buf_b.toSliceConst());163 try combined_buf.appendSlice(buf_b.span());
164 try output.append(combined_buf);164 try output.append(combined_buf);
165 }165 }
166 }166 }
167 },167 },
168 Node.List => |list| {168 Node.List => |list| {
169 for (list.toSliceConst()) |child_node| {169 for (list.span()) |child_node| {
170 var child_list = ArrayList(Buffer).init(global_allocator);170 var child_list = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator);
171 try expandNode(child_node, &child_list);171 try expandNode(child_node, &child_list);
172172
173 for (child_list.toSliceConst()) |buf| {173 for (child_list.span()) |buf| {
174 try output.append(buf);174 try output.append(buf);
175 }175 }
176 }176 }
...@@ -187,17 +187,17 @@ pub fn main() !void {...@@ -187,17 +187,17 @@ pub fn main() !void {
187187
188 global_allocator = &arena.allocator;188 global_allocator = &arena.allocator;
189189
190 var stdin_buf = try Buffer.initSize(global_allocator, 0);190 var stdin_buf = try ArrayListSentineled(u8, 0).initSize(global_allocator, 0);
191 defer stdin_buf.deinit();191 defer stdin_buf.deinit();
192192
193 var stdin_adapter = stdin_file.inStream();193 var stdin_adapter = stdin_file.inStream();
194 try stdin_adapter.stream.readAllBuffer(&stdin_buf, maxInt(usize));194 try stdin_adapter.stream.readAllBuffer(&stdin_buf, maxInt(usize));
195195
196 var result_buf = try Buffer.initSize(global_allocator, 0);196 var result_buf = try ArrayListSentineled(u8, 0).initSize(global_allocator, 0);
197 defer result_buf.deinit();197 defer result_buf.deinit();
198198
199 try expandString(stdin_buf.toSlice(), &result_buf);199 try expandString(stdin_buf.span(), &result_buf);
200 try stdout_file.write(result_buf.toSliceConst());200 try stdout_file.write(result_buf.span());
201}201}
202202
203test "invalid inputs" {203test "invalid inputs" {
...@@ -218,7 +218,7 @@ test "invalid inputs" {...@@ -218,7 +218,7 @@ test "invalid inputs" {
218}218}
219219
220fn expectError(test_input: []const u8, expected_err: anyerror) void {220fn expectError(test_input: []const u8, expected_err: anyerror) void {
221 var output_buf = Buffer.initSize(global_allocator, 0) catch unreachable;221 var output_buf = ArrayListSentineled(u8, 0).initSize(global_allocator, 0) catch unreachable;
222 defer output_buf.deinit();222 defer output_buf.deinit();
223223
224 testing.expectError(expected_err, expandString(test_input, &output_buf));224 testing.expectError(expected_err, expandString(test_input, &output_buf));
...@@ -251,10 +251,10 @@ test "valid inputs" {...@@ -251,10 +251,10 @@ test "valid inputs" {
251}251}
252252
253fn expectExpansion(test_input: []const u8, expected_result: []const u8) void {253fn expectExpansion(test_input: []const u8, expected_result: []const u8) void {
254 var result = Buffer.initSize(global_allocator, 0) catch unreachable;254 var result = ArrayListSentineled(u8, 0).initSize(global_allocator, 0) catch unreachable;
255 defer result.deinit();255 defer result.deinit();
256256
257 expandString(test_input, &result) catch unreachable;257 expandString(test_input, &result) catch unreachable;
258258
259 testing.expectEqualSlices(u8, expected_result, result.toSlice());259 testing.expectEqualSlices(u8, expected_result, result.span());
260}260}
test/standalone/guess_number/main.zig+1-1
...@@ -17,7 +17,7 @@ pub fn main() !void {...@@ -17,7 +17,7 @@ pub fn main() !void {
17 const seed = std.mem.readIntNative(u64, &seed_bytes);17 const seed = std.mem.readIntNative(u64, &seed_bytes);
18 var prng = std.rand.DefaultPrng.init(seed);18 var prng = std.rand.DefaultPrng.init(seed);
1919
20 const answer = prng.random.range(u8, 0, 100) + 1;20 const answer = prng.random.intRangeLessThan(u8, 0, 100) + 1;
2121
22 while (true) {22 while (true) {
23 try stdout.print("\nGuess a number between 1 and 100: ", .{});23 try stdout.print("\nGuess a number between 1 and 100: ", .{});
test/tests.zig+32-33
...@@ -4,7 +4,6 @@ const debug = std.debug;...@@ -4,7 +4,6 @@ const debug = std.debug;
4const warn = debug.warn;4const warn = debug.warn;
5const build = std.build;5const build = std.build;
6const CrossTarget = std.zig.CrossTarget;6const CrossTarget = std.zig.CrossTarget;
7const Buffer = std.Buffer;
8const io = std.io;7const io = std.io;
9const fs = std.fs;8const fs = std.fs;
10const mem = std.mem;9const mem = std.mem;
...@@ -583,7 +582,7 @@ pub const StackTracesContext = struct {...@@ -583,7 +582,7 @@ pub const StackTracesContext = struct {
583582
584 warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });583 warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });
585584
586 const child = std.ChildProcess.init(args.toSliceConst(), b.allocator) catch unreachable;585 const child = std.ChildProcess.init(args.span(), b.allocator) catch unreachable;
587 defer child.deinit();586 defer child.deinit();
588587
589 child.stdin_behavior = .Ignore;588 child.stdin_behavior = .Ignore;
...@@ -592,7 +591,7 @@ pub const StackTracesContext = struct {...@@ -592,7 +591,7 @@ pub const StackTracesContext = struct {
592 child.env_map = b.env_map;591 child.env_map = b.env_map;
593592
594 if (b.verbose) {593 if (b.verbose) {
595 printInvocation(args.toSliceConst());594 printInvocation(args.span());
596 }595 }
597 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) });596 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) });
598597
...@@ -614,23 +613,23 @@ pub const StackTracesContext = struct {...@@ -614,23 +613,23 @@ pub const StackTracesContext = struct {
614 code,613 code,
615 expect_code,614 expect_code,
616 });615 });
617 printInvocation(args.toSliceConst());616 printInvocation(args.span());
618 return error.TestFailed;617 return error.TestFailed;
619 }618 }
620 },619 },
621 .Signal => |signum| {620 .Signal => |signum| {
622 warn("Process {} terminated on signal {}\n", .{ full_exe_path, signum });621 warn("Process {} terminated on signal {}\n", .{ full_exe_path, signum });
623 printInvocation(args.toSliceConst());622 printInvocation(args.span());
624 return error.TestFailed;623 return error.TestFailed;
625 },624 },
626 .Stopped => |signum| {625 .Stopped => |signum| {
627 warn("Process {} stopped on signal {}\n", .{ full_exe_path, signum });626 warn("Process {} stopped on signal {}\n", .{ full_exe_path, signum });
628 printInvocation(args.toSliceConst());627 printInvocation(args.span());
629 return error.TestFailed;628 return error.TestFailed;
630 },629 },
631 .Unknown => |code| {630 .Unknown => |code| {
632 warn("Process {} terminated unexpectedly with error code {}\n", .{ full_exe_path, code });631 warn("Process {} terminated unexpectedly with error code {}\n", .{ full_exe_path, code });
633 printInvocation(args.toSliceConst());632 printInvocation(args.span());
634 return error.TestFailed;633 return error.TestFailed;
635 },634 },
636 }635 }
...@@ -640,7 +639,7 @@ pub const StackTracesContext = struct {...@@ -640,7 +639,7 @@ pub const StackTracesContext = struct {
640 // - replace address with symbolic string639 // - replace address with symbolic string
641 // - skip empty lines640 // - skip empty lines
642 const got: []const u8 = got_result: {641 const got: []const u8 = got_result: {
643 var buf = try Buffer.initSize(b.allocator, 0);642 var buf = ArrayList(u8).init(b.allocator);
644 defer buf.deinit();643 defer buf.deinit();
645 if (stderr.len != 0 and stderr[stderr.len - 1] == '\n') stderr = stderr[0 .. stderr.len - 1];644 if (stderr.len != 0 and stderr[stderr.len - 1] == '\n') stderr = stderr[0 .. stderr.len - 1];
646 var it = mem.separate(stderr, "\n");645 var it = mem.separate(stderr, "\n");
...@@ -652,21 +651,21 @@ pub const StackTracesContext = struct {...@@ -652,21 +651,21 @@ pub const StackTracesContext = struct {
652 var pos: usize = if (std.Target.current.os.tag == .windows) 2 else 0;651 var pos: usize = if (std.Target.current.os.tag == .windows) 2 else 0;
653 for (delims) |delim, i| {652 for (delims) |delim, i| {
654 marks[i] = mem.indexOfPos(u8, line, pos, delim) orelse {653 marks[i] = mem.indexOfPos(u8, line, pos, delim) orelse {
655 try buf.append(line);654 try buf.appendSlice(line);
656 try buf.append("\n");655 try buf.appendSlice("\n");
657 continue :process_lines;656 continue :process_lines;
658 };657 };
659 pos = marks[i] + delim.len;658 pos = marks[i] + delim.len;
660 }659 }
661 pos = mem.lastIndexOfScalar(u8, line[0..marks[0]], fs.path.sep) orelse {660 pos = mem.lastIndexOfScalar(u8, line[0..marks[0]], fs.path.sep) orelse {
662 try buf.append(line);661 try buf.appendSlice(line);
663 try buf.append("\n");662 try buf.appendSlice("\n");
664 continue :process_lines;663 continue :process_lines;
665 };664 };
666 try buf.append(line[pos + 1 .. marks[2] + delims[2].len]);665 try buf.appendSlice(line[pos + 1 .. marks[2] + delims[2].len]);
667 try buf.append(" [address]");666 try buf.appendSlice(" [address]");
668 try buf.append(line[marks[3]..]);667 try buf.appendSlice(line[marks[3]..]);
669 try buf.append("\n");668 try buf.appendSlice("\n");
670 }669 }
671 break :got_result buf.toOwnedSlice();670 break :got_result buf.toOwnedSlice();
672 };671 };
...@@ -785,7 +784,7 @@ pub const CompileErrorContext = struct {...@@ -785,7 +784,7 @@ pub const CompileErrorContext = struct {
785 } else {784 } else {
786 try zig_args.append("build-obj");785 try zig_args.append("build-obj");
787 }786 }
788 const root_src_basename = self.case.sources.toSliceConst()[0].filename;787 const root_src_basename = self.case.sources.span()[0].filename;
789 try zig_args.append(self.write_src.getOutputPath(root_src_basename));788 try zig_args.append(self.write_src.getOutputPath(root_src_basename));
790789
791 zig_args.append("--name") catch unreachable;790 zig_args.append("--name") catch unreachable;
...@@ -809,10 +808,10 @@ pub const CompileErrorContext = struct {...@@ -809,10 +808,10 @@ pub const CompileErrorContext = struct {
809 warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });808 warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });
810809
811 if (b.verbose) {810 if (b.verbose) {
812 printInvocation(zig_args.toSliceConst());811 printInvocation(zig_args.span());
813 }812 }
814813
815 const child = std.ChildProcess.init(zig_args.toSliceConst(), b.allocator) catch unreachable;814 const child = std.ChildProcess.init(zig_args.span(), b.allocator) catch unreachable;
816 defer child.deinit();815 defer child.deinit();
817816
818 child.env_map = b.env_map;817 child.env_map = b.env_map;
...@@ -822,11 +821,11 @@ pub const CompileErrorContext = struct {...@@ -822,11 +821,11 @@ pub const CompileErrorContext = struct {
822821
823 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });822 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });
824823
825 var stdout_buf = Buffer.initNull(b.allocator);824 var stdout_buf = ArrayList(u8).init(b.allocator);
826 var stderr_buf = Buffer.initNull(b.allocator);825 var stderr_buf = ArrayList(u8).init(b.allocator);
827826
828 child.stdout.?.inStream().readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable;827 child.stdout.?.inStream().readAllArrayList(&stdout_buf, max_stdout_size) catch unreachable;
829 child.stderr.?.inStream().readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable;828 child.stderr.?.inStream().readAllArrayList(&stderr_buf, max_stdout_size) catch unreachable;
830829
831 const term = child.wait() catch |err| {830 const term = child.wait() catch |err| {
832 debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });831 debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });
...@@ -834,19 +833,19 @@ pub const CompileErrorContext = struct {...@@ -834,19 +833,19 @@ pub const CompileErrorContext = struct {
834 switch (term) {833 switch (term) {
835 .Exited => |code| {834 .Exited => |code| {
836 if (code == 0) {835 if (code == 0) {
837 printInvocation(zig_args.toSliceConst());836 printInvocation(zig_args.span());
838 return error.CompilationIncorrectlySucceeded;837 return error.CompilationIncorrectlySucceeded;
839 }838 }
840 },839 },
841 else => {840 else => {
842 warn("Process {} terminated unexpectedly\n", .{b.zig_exe});841 warn("Process {} terminated unexpectedly\n", .{b.zig_exe});
843 printInvocation(zig_args.toSliceConst());842 printInvocation(zig_args.span());
844 return error.TestFailed;843 return error.TestFailed;
845 },844 },
846 }845 }
847846
848 const stdout = stdout_buf.toSliceConst();847 const stdout = stdout_buf.span();
849 const stderr = stderr_buf.toSliceConst();848 const stderr = stderr_buf.span();
850849
851 if (stdout.len != 0) {850 if (stdout.len != 0) {
852 warn(851 warn(
...@@ -875,12 +874,12 @@ pub const CompileErrorContext = struct {...@@ -875,12 +874,12 @@ pub const CompileErrorContext = struct {
875874
876 if (!ok) {875 if (!ok) {
877 warn("\n======== Expected these compile errors: ========\n", .{});876 warn("\n======== Expected these compile errors: ========\n", .{});
878 for (self.case.expected_errors.toSliceConst()) |expected| {877 for (self.case.expected_errors.span()) |expected| {
879 warn("{}\n", .{expected});878 warn("{}\n", .{expected});
880 }879 }
881 }880 }
882 } else {881 } else {
883 for (self.case.expected_errors.toSliceConst()) |expected| {882 for (self.case.expected_errors.span()) |expected| {
884 if (mem.indexOf(u8, stderr, expected) == null) {883 if (mem.indexOf(u8, stderr, expected) == null) {
885 warn(884 warn(
886 \\885 \\
...@@ -980,7 +979,7 @@ pub const CompileErrorContext = struct {...@@ -980,7 +979,7 @@ pub const CompileErrorContext = struct {
980 if (mem.indexOf(u8, annotated_case_name, filter) == null) return;979 if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
981 }980 }
982 const write_src = b.addWriteFiles();981 const write_src = b.addWriteFiles();
983 for (case.sources.toSliceConst()) |src_file| {982 for (case.sources.span()) |src_file| {
984 write_src.add(src_file.filename, src_file.source);983 write_src.add(src_file.filename, src_file.source);
985 }984 }
986985
...@@ -1027,7 +1026,7 @@ pub const StandaloneContext = struct {...@@ -1027,7 +1026,7 @@ pub const StandaloneContext = struct {
1027 zig_args.append("--verbose") catch unreachable;1026 zig_args.append("--verbose") catch unreachable;
1028 }1027 }
10291028
1030 const run_cmd = b.addSystemCommand(zig_args.toSliceConst());1029 const run_cmd = b.addSystemCommand(zig_args.span());
10311030
1032 const log_step = b.addLog("PASS {}\n", .{annotated_case_name});1031 const log_step = b.addLog("PASS {}\n", .{annotated_case_name});
1033 log_step.step.dependOn(&run_cmd.step);1032 log_step.step.dependOn(&run_cmd.step);
...@@ -1127,7 +1126,7 @@ pub const GenHContext = struct {...@@ -1127,7 +1126,7 @@ pub const GenHContext = struct {
1127 const full_h_path = self.obj.getOutputHPath();1126 const full_h_path = self.obj.getOutputHPath();
1128 const actual_h = try io.readFileAlloc(b.allocator, full_h_path);1127 const actual_h = try io.readFileAlloc(b.allocator, full_h_path);
11291128
1130 for (self.case.expected_lines.toSliceConst()) |expected_line| {1129 for (self.case.expected_lines.span()) |expected_line| {
1131 if (mem.indexOf(u8, actual_h, expected_line) == null) {1130 if (mem.indexOf(u8, actual_h, expected_line) == null) {
1132 warn(1131 warn(
1133 \\1132 \\
...@@ -1188,7 +1187,7 @@ pub const GenHContext = struct {...@@ -1188,7 +1187,7 @@ pub const GenHContext = struct {
1188 }1187 }
11891188
1190 const write_src = b.addWriteFiles();1189 const write_src = b.addWriteFiles();
1191 for (case.sources.toSliceConst()) |src_file| {1190 for (case.sources.span()) |src_file| {
1192 write_src.add(src_file.filename, src_file.source);1191 write_src.add(src_file.filename, src_file.source);
1193 }1192 }
11941193
test/translate_c.zig+39
...@@ -2808,4 +2808,43 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -2808,4 +2808,43 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
2808 \\ return if (x > y) x else y;2808 \\ return if (x > y) x else y;
2809 \\}2809 \\}
2810 });2810 });
2811
2812 cases.add("string concatenation in macros",
2813 \\#define FOO "hello"
2814 \\#define BAR FOO " world"
2815 \\#define BAZ "oh, " FOO
2816 , &[_][]const u8{
2817 \\pub const FOO = "hello";
2818 ,
2819 \\pub const BAR = FOO ++ " world";
2820 ,
2821 \\pub const BAZ = "oh, " ++ FOO;
2822 });
2823
2824 cases.add("string concatenation in macros: two defines",
2825 \\#define FOO "hello"
2826 \\#define BAZ " world"
2827 \\#define BAR FOO BAZ
2828 , &[_][]const u8{
2829 \\pub const FOO = "hello";
2830 ,
2831 \\pub const BAZ = " world";
2832 ,
2833 \\pub const BAR = FOO ++ BAZ;
2834 });
2835
2836 cases.add("string concatenation in macros: two strings",
2837 \\#define FOO "a" "b"
2838 \\#define BAR FOO "c"
2839 , &[_][]const u8{
2840 \\pub const FOO = "a" ++ "b";
2841 ,
2842 \\pub const BAR = FOO ++ "c";
2843 });
2844
2845 cases.add("string concatenation in macros: three strings",
2846 \\#define FOO "a" "b" "c"
2847 , &[_][]const u8{
2848 \\pub const FOO = "a" ++ ("b" ++ "c");
2849 });
2811}2850}
tools/merge_anal_dumps.zig+12-12
...@@ -183,13 +183,13 @@ const Dump = struct {...@@ -183,13 +183,13 @@ const Dump = struct {
183 try mergeSameStrings(&self.zig_version, zig_version);183 try mergeSameStrings(&self.zig_version, zig_version);
184 try mergeSameStrings(&self.root_name, root_name);184 try mergeSameStrings(&self.root_name, root_name);
185185
186 for (params.get("builds").?.value.Array.toSliceConst()) |json_build| {186 for (params.get("builds").?.value.Array.span()) |json_build| {
187 const target = json_build.Object.get("target").?.value.String;187 const target = json_build.Object.get("target").?.value.String;
188 try self.targets.append(target);188 try self.targets.append(target);
189 }189 }
190190
191 // Merge files. If the string matches, it's the same file.191 // Merge files. If the string matches, it's the same file.
192 const other_files = root.Object.get("files").?.value.Array.toSliceConst();192 const other_files = root.Object.get("files").?.value.Array.span();
193 var other_file_to_mine = std.AutoHashMap(usize, usize).init(self.a());193 var other_file_to_mine = std.AutoHashMap(usize, usize).init(self.a());
194 for (other_files) |other_file, i| {194 for (other_files) |other_file, i| {
195 const gop = try self.file_map.getOrPut(other_file.String);195 const gop = try self.file_map.getOrPut(other_file.String);
...@@ -201,7 +201,7 @@ const Dump = struct {...@@ -201,7 +201,7 @@ const Dump = struct {
201 }201 }
202202
203 // Merge AST nodes. If the file id, line, and column all match, it's the same AST node.203 // Merge AST nodes. If the file id, line, and column all match, it's the same AST node.
204 const other_ast_nodes = root.Object.get("astNodes").?.value.Array.toSliceConst();204 const other_ast_nodes = root.Object.get("astNodes").?.value.Array.span();
205 var other_ast_node_to_mine = std.AutoHashMap(usize, usize).init(self.a());205 var other_ast_node_to_mine = std.AutoHashMap(usize, usize).init(self.a());
206 for (other_ast_nodes) |other_ast_node_json, i| {206 for (other_ast_nodes) |other_ast_node_json, i| {
207 const other_file_id = jsonObjInt(other_ast_node_json, "file");207 const other_file_id = jsonObjInt(other_ast_node_json, "file");
...@@ -221,9 +221,9 @@ const Dump = struct {...@@ -221,9 +221,9 @@ const Dump = struct {
221 // convert fields lists221 // convert fields lists
222 for (other_ast_nodes) |other_ast_node_json, i| {222 for (other_ast_nodes) |other_ast_node_json, i| {
223 const my_node_index = other_ast_node_to_mine.get(i).?.value;223 const my_node_index = other_ast_node_to_mine.get(i).?.value;
224 const my_node = &self.node_list.toSlice()[my_node_index];224 const my_node = &self.node_list.span()[my_node_index];
225 if (other_ast_node_json.Object.get("fields")) |fields_json_kv| {225 if (other_ast_node_json.Object.get("fields")) |fields_json_kv| {
226 const other_fields = fields_json_kv.value.Array.toSliceConst();226 const other_fields = fields_json_kv.value.Array.span();
227 my_node.fields = try self.a().alloc(usize, other_fields.len);227 my_node.fields = try self.a().alloc(usize, other_fields.len);
228 for (other_fields) |other_field_index, field_i| {228 for (other_fields) |other_field_index, field_i| {
229 const other_index = @intCast(usize, other_field_index.Integer);229 const other_index = @intCast(usize, other_field_index.Integer);
...@@ -233,7 +233,7 @@ const Dump = struct {...@@ -233,7 +233,7 @@ const Dump = struct {
233 }233 }
234234
235 // Merge errors. If the AST Node matches, it's the same error value.235 // Merge errors. If the AST Node matches, it's the same error value.
236 const other_errors = root.Object.get("errors").?.value.Array.toSliceConst();236 const other_errors = root.Object.get("errors").?.value.Array.span();
237 var other_error_to_mine = std.AutoHashMap(usize, usize).init(self.a());237 var other_error_to_mine = std.AutoHashMap(usize, usize).init(self.a());
238 for (other_errors) |other_error_json, i| {238 for (other_errors) |other_error_json, i| {
239 const other_src_id = jsonObjInt(other_error_json, "src");239 const other_src_id = jsonObjInt(other_error_json, "src");
...@@ -253,7 +253,7 @@ const Dump = struct {...@@ -253,7 +253,7 @@ const Dump = struct {
253 // First we identify all the simple types and merge those.253 // First we identify all the simple types and merge those.
254 // Example: void, type, noreturn254 // Example: void, type, noreturn
255 // We can also do integers and floats.255 // We can also do integers and floats.
256 const other_types = root.Object.get("types").?.value.Array.toSliceConst();256 const other_types = root.Object.get("types").?.value.Array.span();
257 var other_types_to_mine = std.AutoHashMap(usize, usize).init(self.a());257 var other_types_to_mine = std.AutoHashMap(usize, usize).init(self.a());
258 for (other_types) |other_type_json, i| {258 for (other_types) |other_type_json, i| {
259 const type_kind = jsonObjInt(other_type_json, "kind");259 const type_kind = jsonObjInt(other_type_json, "kind");
...@@ -336,7 +336,7 @@ const Dump = struct {...@@ -336,7 +336,7 @@ const Dump = struct {
336336
337 try jw.objectField("builds");337 try jw.objectField("builds");
338 try jw.beginArray();338 try jw.beginArray();
339 for (self.targets.toSliceConst()) |target| {339 for (self.targets.span()) |target| {
340 try jw.arrayElem();340 try jw.arrayElem();
341 try jw.beginObject();341 try jw.beginObject();
342 try jw.objectField("target");342 try jw.objectField("target");
...@@ -349,7 +349,7 @@ const Dump = struct {...@@ -349,7 +349,7 @@ const Dump = struct {
349349
350 try jw.objectField("types");350 try jw.objectField("types");
351 try jw.beginArray();351 try jw.beginArray();
352 for (self.type_list.toSliceConst()) |t| {352 for (self.type_list.span()) |t| {
353 try jw.arrayElem();353 try jw.arrayElem();
354 try jw.beginObject();354 try jw.beginObject();
355355
...@@ -379,7 +379,7 @@ const Dump = struct {...@@ -379,7 +379,7 @@ const Dump = struct {
379379
380 try jw.objectField("errors");380 try jw.objectField("errors");
381 try jw.beginArray();381 try jw.beginArray();
382 for (self.error_list.toSliceConst()) |zig_error| {382 for (self.error_list.span()) |zig_error| {
383 try jw.arrayElem();383 try jw.arrayElem();
384 try jw.beginObject();384 try jw.beginObject();
385385
...@@ -395,7 +395,7 @@ const Dump = struct {...@@ -395,7 +395,7 @@ const Dump = struct {
395395
396 try jw.objectField("astNodes");396 try jw.objectField("astNodes");
397 try jw.beginArray();397 try jw.beginArray();
398 for (self.node_list.toSliceConst()) |node| {398 for (self.node_list.span()) |node| {
399 try jw.arrayElem();399 try jw.arrayElem();
400 try jw.beginObject();400 try jw.beginObject();
401401
...@@ -425,7 +425,7 @@ const Dump = struct {...@@ -425,7 +425,7 @@ const Dump = struct {
425425
426 try jw.objectField("files");426 try jw.objectField("files");
427 try jw.beginArray();427 try jw.beginArray();
428 for (self.file_list.toSliceConst()) |file| {428 for (self.file_list.span()) |file| {
429 try jw.arrayElem();429 try jw.arrayElem();
430 try jw.emitString(file);430 try jw.emitString(file);
431 }431 }
tools/process_headers.zig+4-4
...@@ -324,7 +324,7 @@ pub fn main() !void {...@@ -324,7 +324,7 @@ pub fn main() !void {
324 },324 },
325 .os = .linux,325 .os = .linux,
326 };326 };
327 search: for (search_paths.toSliceConst()) |search_path| {327 search: for (search_paths.span()) |search_path| {
328 var sub_path: []const []const u8 = undefined;328 var sub_path: []const []const u8 = undefined;
329 switch (vendor) {329 switch (vendor) {
330 .musl => {330 .musl => {
...@@ -414,13 +414,13 @@ pub fn main() !void {...@@ -414,13 +414,13 @@ pub fn main() !void {
414 try contents_list.append(contents);414 try contents_list.append(contents);
415 }415 }
416 }416 }
417 std.sort.sort(*Contents, contents_list.toSlice(), Contents.hitCountLessThan);417 std.sort.sort(*Contents, contents_list.span(), Contents.hitCountLessThan);
418 var best_contents = contents_list.popOrNull().?;418 var best_contents = contents_list.popOrNull().?;
419 if (best_contents.hit_count > 1) {419 if (best_contents.hit_count > 1) {
420 // worth it to make it generic420 // worth it to make it generic
421 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, generic_name, path_kv.key });421 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, generic_name, path_kv.key });
422 try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?);422 try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?);
423 try std.io.writeFile(full_path, best_contents.bytes);423 try std.fs.cwd().writeFile(full_path, best_contents.bytes);
424 best_contents.is_generic = true;424 best_contents.is_generic = true;
425 while (contents_list.popOrNull()) |contender| {425 while (contents_list.popOrNull()) |contender| {
426 if (contender.hit_count > 1) {426 if (contender.hit_count > 1) {
...@@ -447,7 +447,7 @@ pub fn main() !void {...@@ -447,7 +447,7 @@ pub fn main() !void {
447 });447 });
448 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, out_subpath, path_kv.key });448 const full_path = try std.fs.path.join(allocator, &[_][]const u8{ out_dir, out_subpath, path_kv.key });
449 try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?);449 try std.fs.cwd().makePath(std.fs.path.dirname(full_path).?);
450 try std.io.writeFile(full_path, contents.bytes);450 try std.fs.cwd().writeFile(full_path, contents.bytes);
451 }451 }
452 }452 }
453}453}
tools/update_clang_options.zig+37-13
...@@ -96,19 +96,19 @@ const known_options = [_]KnownOpt{...@@ -96,19 +96,19 @@ const known_options = [_]KnownOpt{
96 },96 },
97 .{97 .{
98 .name = "E",98 .name = "E",
99 .ident = "preprocess",99 .ident = "pp_or_asm",
100 },100 },
101 .{101 .{
102 .name = "preprocess",102 .name = "preprocess",
103 .ident = "preprocess",103 .ident = "pp_or_asm",
104 },104 },
105 .{105 .{
106 .name = "S",106 .name = "S",
107 .ident = "driver_punt",107 .ident = "pp_or_asm",
108 },108 },
109 .{109 .{
110 .name = "assemble",110 .name = "assemble",
111 .ident = "driver_punt",111 .ident = "pp_or_asm",
112 },112 },
113 .{113 .{
114 .name = "O1",114 .name = "O1",
...@@ -175,20 +175,44 @@ const known_options = [_]KnownOpt{...@@ -175,20 +175,44 @@ const known_options = [_]KnownOpt{
175 .ident = "verbose_cmds",175 .ident = "verbose_cmds",
176 },176 },
177 .{177 .{
178 .name = "fexceptions",178 .name = "L",
179 .ident = "exceptions",179 .ident = "lib_dir",
180 },
181 .{
182 .name = "library-directory",
183 .ident = "lib_dir",
184 },
185 .{
186 .name = "mcpu",
187 .ident = "mcpu",
188 },
189 .{
190 .name = "march",
191 .ident = "mcpu",
192 },
193 .{
194 .name = "mtune",
195 .ident = "mcpu",
196 },
197 .{
198 .name = "MD",
199 .ident = "dep_file",
200 },
201 .{
202 .name = "MV",
203 .ident = "dep_file",
180 },204 },
181 .{205 .{
182 .name = "fno-exceptions",206 .name = "MF",
183 .ident = "no_exceptions",207 .ident = "dep_file",
184 },208 },
185 .{209 .{
186 .name = "frtti",210 .name = "F",
187 .ident = "rtti",211 .ident = "framework_dir",
188 },212 },
189 .{213 .{
190 .name = "fno-rtti",214 .name = "framework",
191 .ident = "no_rtti",215 .ident = "framework",
192 },216 },
193};217};
194218
...@@ -239,7 +263,7 @@ pub fn main() anyerror!void {...@@ -239,7 +263,7 @@ pub fn main() anyerror!void {
239 try std.fmt.allocPrint(allocator, "-I={}/clang/include/clang/Driver", .{llvm_src_root}),263 try std.fmt.allocPrint(allocator, "-I={}/clang/include/clang/Driver", .{llvm_src_root}),
240 };264 };
241265
242 const child_result = try std.ChildProcess.exec2(.{266 const child_result = try std.ChildProcess.exec(.{
243 .allocator = allocator,267 .allocator = allocator,
244 .argv = &child_args,268 .argv = &child_args,
245 .max_output_bytes = 100 * 1024 * 1024,269 .max_output_bytes = 100 * 1024 * 1024,
tools/update_glibc.zig+7-7
...@@ -223,15 +223,15 @@ pub fn main() !void {...@@ -223,15 +223,15 @@ pub fn main() !void {
223 var list = std.ArrayList([]const u8).init(allocator);223 var list = std.ArrayList([]const u8).init(allocator);
224 var it = global_fn_set.iterator();224 var it = global_fn_set.iterator();
225 while (it.next()) |kv| try list.append(kv.key);225 while (it.next()) |kv| try list.append(kv.key);
226 std.sort.sort([]const u8, list.toSlice(), strCmpLessThan);226 std.sort.sort([]const u8, list.span(), strCmpLessThan);
227 break :blk list.toSliceConst();227 break :blk list.span();
228 };228 };
229 const global_ver_list = blk: {229 const global_ver_list = blk: {
230 var list = std.ArrayList([]const u8).init(allocator);230 var list = std.ArrayList([]const u8).init(allocator);
231 var it = global_ver_set.iterator();231 var it = global_ver_set.iterator();
232 while (it.next()) |kv| try list.append(kv.key);232 while (it.next()) |kv| try list.append(kv.key);
233 std.sort.sort([]const u8, list.toSlice(), versionLessThan);233 std.sort.sort([]const u8, list.span(), versionLessThan);
234 break :blk list.toSliceConst();234 break :blk list.span();
235 };235 };
236 {236 {
237 const vers_txt_path = try fs.path.join(allocator, &[_][]const u8{ glibc_out_dir, "vers.txt" });237 const vers_txt_path = try fs.path.join(allocator, &[_][]const u8{ glibc_out_dir, "vers.txt" });
...@@ -264,13 +264,13 @@ pub fn main() !void {...@@ -264,13 +264,13 @@ pub fn main() !void {
264 for (abi_lists) |*abi_list, abi_index| {264 for (abi_lists) |*abi_list, abi_index| {
265 const kv = target_functions.get(@ptrToInt(abi_list)).?;265 const kv = target_functions.get(@ptrToInt(abi_list)).?;
266 const fn_vers_list = &kv.value.fn_vers_list;266 const fn_vers_list = &kv.value.fn_vers_list;
267 for (kv.value.list.toSliceConst()) |*ver_fn| {267 for (kv.value.list.span()) |*ver_fn| {
268 const gop = try fn_vers_list.getOrPut(ver_fn.name);268 const gop = try fn_vers_list.getOrPut(ver_fn.name);
269 if (!gop.found_existing) {269 if (!gop.found_existing) {
270 gop.kv.value = std.ArrayList(usize).init(allocator);270 gop.kv.value = std.ArrayList(usize).init(allocator);
271 }271 }
272 const ver_index = global_ver_set.get(ver_fn.ver).?.value;272 const ver_index = global_ver_set.get(ver_fn.ver).?.value;
273 if (std.mem.indexOfScalar(usize, gop.kv.value.toSliceConst(), ver_index) == null) {273 if (std.mem.indexOfScalar(usize, gop.kv.value.span(), ver_index) == null) {
274 try gop.kv.value.append(ver_index);274 try gop.kv.value.append(ver_index);
275 }275 }
276 }276 }
...@@ -297,7 +297,7 @@ pub fn main() !void {...@@ -297,7 +297,7 @@ pub fn main() !void {
297 try abilist_txt.writeByte('\n');297 try abilist_txt.writeByte('\n');
298 continue;298 continue;
299 };299 };
300 for (kv.value.toSliceConst()) |ver_index, it_i| {300 for (kv.value.span()) |ver_index, it_i| {
301 if (it_i != 0) try abilist_txt.writeByte(' ');301 if (it_i != 0) try abilist_txt.writeByte(' ');
302 try abilist_txt.print("{d}", .{ver_index});302 try abilist_txt.print("{d}", .{ver_index});
303 }303 }