authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-03-13 15:17:53-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-03-13 15:17:53-04:00
log656ba530d80e67bc7bb9c40e5c2db26a40743a15
tree767f4d57000922cf122ae965dc825f87c62ec64e
parent96c07674fc2293fa040212ab797c05436dc515b1
parent3eff77bfb52accbc16eb831753ff4917fc2b4873
signaturelock-open Commit is signed but in an unrecognized format.

Merge remote-tracking branch 'origin/master' into llvm10


543 files changed, 10643 insertions(+), 6766 deletions(-)

ci/srht/freebsd_script-7
...@@ -3,13 +3,6 @@...@@ -3,13 +3,6 @@
3set -x3set -x
4set -e4set -e
55
6# The following line can be removed as soon as FreeBSD fixes
7# their packaging glitch. If not fixed by March 15, 2020
8# there is something wrong. Should be fixed much sooner.
9# note: this will cause some complaints when running
10# pkg commands but let's ignore them.
11sudo rm /usr/local/etc/pkg/repos/FreeBSD.conf
12
13sudo pkg update -fq6sudo pkg update -fq
14sudo pkg install -y cmake py27-s3cmd wget curl jq7sudo pkg install -y cmake py27-s3cmd wget curl jq
158
doc/docgen.zig+44-51
...@@ -40,12 +40,9 @@ pub fn main() !void {...@@ -40,12 +40,9 @@ pub fn main() !void {
40 var out_file = try fs.cwd().createFile(out_file_name, .{});40 var out_file = try fs.cwd().createFile(out_file_name, .{});
41 defer out_file.close();41 defer out_file.close();
4242
43 var file_in_stream = in_file.inStream();43 const input_file_bytes = try in_file.inStream().readAllAlloc(allocator, max_doc_file_size);
4444
45 const input_file_bytes = try file_in_stream.stream.readAllAlloc(allocator, max_doc_file_size);45 var buffered_out_stream = io.bufferedOutStream(out_file.outStream());
46
47 var file_out_stream = out_file.outStream();
48 var buffered_out_stream = io.BufferedOutStream(fs.File.WriteError).init(&file_out_stream.stream);
4946
50 var tokenizer = Tokenizer.init(in_file_name, input_file_bytes);47 var tokenizer = Tokenizer.init(in_file_name, input_file_bytes);
51 var toc = try genToc(allocator, &tokenizer);48 var toc = try genToc(allocator, &tokenizer);
...@@ -53,7 +50,7 @@ pub fn main() !void {...@@ -53,7 +50,7 @@ pub fn main() !void {
53 try fs.cwd().makePath(tmp_dir_name);50 try fs.cwd().makePath(tmp_dir_name);
54 defer fs.deleteTree(tmp_dir_name) catch {};51 defer fs.deleteTree(tmp_dir_name) catch {};
5552
56 try genHtml(allocator, &tokenizer, &toc, &buffered_out_stream.stream, zig_exe);53 try genHtml(allocator, &tokenizer, &toc, buffered_out_stream.outStream(), zig_exe);
57 try buffered_out_stream.flush();54 try buffered_out_stream.flush();
58}55}
5956
...@@ -327,8 +324,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -327,8 +324,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
327 var toc_buf = try std.Buffer.initSize(allocator, 0);324 var toc_buf = try std.Buffer.initSize(allocator, 0);
328 defer toc_buf.deinit();325 defer toc_buf.deinit();
329326
330 var toc_buf_adapter = io.BufferOutStream.init(&toc_buf);327 var toc = toc_buf.outStream();
331 var toc = &toc_buf_adapter.stream;
332328
333 var nodes = std.ArrayList(Node).init(allocator);329 var nodes = std.ArrayList(Node).init(allocator);
334 defer nodes.deinit();330 defer nodes.deinit();
...@@ -342,7 +338,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -342,7 +338,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
342 if (header_stack_size != 0) {338 if (header_stack_size != 0) {
343 return parseError(tokenizer, token, "unbalanced headers", .{});339 return parseError(tokenizer, token, "unbalanced headers", .{});
344 }340 }
345 try toc.write(" </ul>\n");341 try toc.writeAll(" </ul>\n");
346 break;342 break;
347 },343 },
348 Token.Id.Content => {344 Token.Id.Content => {
...@@ -407,7 +403,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -407,7 +403,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
407 if (last_columns) |n| {403 if (last_columns) |n| {
408 try toc.print("<ul style=\"columns: {}\">\n", .{n});404 try toc.print("<ul style=\"columns: {}\">\n", .{n});
409 } else {405 } else {
410 try toc.write("<ul>\n");406 try toc.writeAll("<ul>\n");
411 }407 }
412 } else {408 } else {
413 last_action = Action.Open;409 last_action = Action.Open;
...@@ -424,9 +420,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {...@@ -424,9 +420,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
424420
425 if (last_action == Action.Close) {421 if (last_action == Action.Close) {
426 try toc.writeByteNTimes(' ', 8 + header_stack_size * 4);422 try toc.writeByteNTimes(' ', 8 + header_stack_size * 4);
427 try toc.write("</ul></li>\n");423 try toc.writeAll("</ul></li>\n");
428 } else {424 } else {
429 try toc.write("</li>\n");425 try toc.writeAll("</li>\n");
430 last_action = Action.Close;426 last_action = Action.Close;
431 }427 }
432 } else if (mem.eql(u8, tag_name, "see_also")) {428 } else if (mem.eql(u8, tag_name, "see_also")) {
...@@ -614,8 +610,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {...@@ -614,8 +610,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
614 var buf = try std.Buffer.initSize(allocator, 0);610 var buf = try std.Buffer.initSize(allocator, 0);
615 defer buf.deinit();611 defer buf.deinit();
616612
617 var buf_adapter = io.BufferOutStream.init(&buf);613 const out = buf.outStream();
618 var out = &buf_adapter.stream;
619 for (input) |c| {614 for (input) |c| {
620 switch (c) {615 switch (c) {
621 'a'...'z', 'A'...'Z', '_', '-', '0'...'9' => {616 'a'...'z', 'A'...'Z', '_', '-', '0'...'9' => {
...@@ -634,8 +629,7 @@ fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {...@@ -634,8 +629,7 @@ fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
634 var buf = try std.Buffer.initSize(allocator, 0);629 var buf = try std.Buffer.initSize(allocator, 0);
635 defer buf.deinit();630 defer buf.deinit();
636631
637 var buf_adapter = io.BufferOutStream.init(&buf);632 const out = buf.outStream();
638 var out = &buf_adapter.stream;
639 try writeEscaped(out, input);633 try writeEscaped(out, input);
640 return buf.toOwnedSlice();634 return buf.toOwnedSlice();
641}635}
...@@ -643,10 +637,10 @@ fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {...@@ -643,10 +637,10 @@ fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
643fn writeEscaped(out: var, input: []const u8) !void {637fn writeEscaped(out: var, input: []const u8) !void {
644 for (input) |c| {638 for (input) |c| {
645 try switch (c) {639 try switch (c) {
646 '&' => out.write("&amp;"),640 '&' => out.writeAll("&amp;"),
647 '<' => out.write("&lt;"),641 '<' => out.writeAll("&lt;"),
648 '>' => out.write("&gt;"),642 '>' => out.writeAll("&gt;"),
649 '"' => out.write("&quot;"),643 '"' => out.writeAll("&quot;"),
650 else => out.writeByte(c),644 else => out.writeByte(c),
651 };645 };
652 }646 }
...@@ -681,8 +675,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {...@@ -681,8 +675,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
681 var buf = try std.Buffer.initSize(allocator, 0);675 var buf = try std.Buffer.initSize(allocator, 0);
682 defer buf.deinit();676 defer buf.deinit();
683677
684 var buf_adapter = io.BufferOutStream.init(&buf);678 var out = buf.outStream();
685 var out = &buf_adapter.stream;
686 var number_start_index: usize = undefined;679 var number_start_index: usize = undefined;
687 var first_number: usize = undefined;680 var first_number: usize = undefined;
688 var second_number: usize = undefined;681 var second_number: usize = undefined;
...@@ -743,7 +736,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {...@@ -743,7 +736,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
743 'm' => {736 'm' => {
744 state = TermState.Start;737 state = TermState.Start;
745 while (open_span_count != 0) : (open_span_count -= 1) {738 while (open_span_count != 0) : (open_span_count -= 1) {
746 try out.write("</span>");739 try out.writeAll("</span>");
747 }740 }
748 if (first_number != 0 or second_number != 0) {741 if (first_number != 0 or second_number != 0) {
749 try out.print("<span class=\"t{}_{}\">", .{ first_number, second_number });742 try out.print("<span class=\"t{}_{}\">", .{ first_number, second_number });
...@@ -774,7 +767,7 @@ fn isType(name: []const u8) bool {...@@ -774,7 +767,7 @@ fn isType(name: []const u8) bool {
774767
775fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Token, raw_src: []const u8) !void {768fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Token, raw_src: []const u8) !void {
776 const src = mem.trim(u8, raw_src, " \n");769 const src = mem.trim(u8, raw_src, " \n");
777 try out.write("<code class=\"zig\">");770 try out.writeAll("<code class=\"zig\">");
778 var tokenizer = std.zig.Tokenizer.init(src);771 var tokenizer = std.zig.Tokenizer.init(src);
779 var index: usize = 0;772 var index: usize = 0;
780 var next_tok_is_fn = false;773 var next_tok_is_fn = false;
...@@ -835,15 +828,15 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok...@@ -835,15 +828,15 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
835 .Keyword_allowzero,828 .Keyword_allowzero,
836 .Keyword_while,829 .Keyword_while,
837 => {830 => {
838 try out.write("<span class=\"tok-kw\">");831 try out.writeAll("<span class=\"tok-kw\">");
839 try writeEscaped(out, src[token.start..token.end]);832 try writeEscaped(out, src[token.start..token.end]);
840 try out.write("</span>");833 try out.writeAll("</span>");
841 },834 },
842835
843 .Keyword_fn => {836 .Keyword_fn => {
844 try out.write("<span class=\"tok-kw\">");837 try out.writeAll("<span class=\"tok-kw\">");
845 try writeEscaped(out, src[token.start..token.end]);838 try writeEscaped(out, src[token.start..token.end]);
846 try out.write("</span>");839 try out.writeAll("</span>");
847 next_tok_is_fn = true;840 next_tok_is_fn = true;
848 },841 },
849842
...@@ -852,24 +845,24 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok...@@ -852,24 +845,24 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
852 .Keyword_true,845 .Keyword_true,
853 .Keyword_false,846 .Keyword_false,
854 => {847 => {
855 try out.write("<span class=\"tok-null\">");848 try out.writeAll("<span class=\"tok-null\">");
856 try writeEscaped(out, src[token.start..token.end]);849 try writeEscaped(out, src[token.start..token.end]);
857 try out.write("</span>");850 try out.writeAll("</span>");
858 },851 },
859852
860 .StringLiteral,853 .StringLiteral,
861 .MultilineStringLiteralLine,854 .MultilineStringLiteralLine,
862 .CharLiteral,855 .CharLiteral,
863 => {856 => {
864 try out.write("<span class=\"tok-str\">");857 try out.writeAll("<span class=\"tok-str\">");
865 try writeEscaped(out, src[token.start..token.end]);858 try writeEscaped(out, src[token.start..token.end]);
866 try out.write("</span>");859 try out.writeAll("</span>");
867 },860 },
868861
869 .Builtin => {862 .Builtin => {
870 try out.write("<span class=\"tok-builtin\">");863 try out.writeAll("<span class=\"tok-builtin\">");
871 try writeEscaped(out, src[token.start..token.end]);864 try writeEscaped(out, src[token.start..token.end]);
872 try out.write("</span>");865 try out.writeAll("</span>");
873 },866 },
874867
875 .LineComment,868 .LineComment,
...@@ -877,16 +870,16 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok...@@ -877,16 +870,16 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
877 .ContainerDocComment,870 .ContainerDocComment,
878 .ShebangLine,871 .ShebangLine,
879 => {872 => {
880 try out.write("<span class=\"tok-comment\">");873 try out.writeAll("<span class=\"tok-comment\">");
881 try writeEscaped(out, src[token.start..token.end]);874 try writeEscaped(out, src[token.start..token.end]);
882 try out.write("</span>");875 try out.writeAll("</span>");
883 },876 },
884877
885 .Identifier => {878 .Identifier => {
886 if (prev_tok_was_fn) {879 if (prev_tok_was_fn) {
887 try out.write("<span class=\"tok-fn\">");880 try out.writeAll("<span class=\"tok-fn\">");
888 try writeEscaped(out, src[token.start..token.end]);881 try writeEscaped(out, src[token.start..token.end]);
889 try out.write("</span>");882 try out.writeAll("</span>");
890 } else {883 } else {
891 const is_int = blk: {884 const is_int = blk: {
892 if (src[token.start] != 'i' and src[token.start] != 'u')885 if (src[token.start] != 'i' and src[token.start] != 'u')
...@@ -901,9 +894,9 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok...@@ -901,9 +894,9 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
901 break :blk true;894 break :blk true;
902 };895 };
903 if (is_int or isType(src[token.start..token.end])) {896 if (is_int or isType(src[token.start..token.end])) {
904 try out.write("<span class=\"tok-type\">");897 try out.writeAll("<span class=\"tok-type\">");
905 try writeEscaped(out, src[token.start..token.end]);898 try writeEscaped(out, src[token.start..token.end]);
906 try out.write("</span>");899 try out.writeAll("</span>");
907 } else {900 } else {
908 try writeEscaped(out, src[token.start..token.end]);901 try writeEscaped(out, src[token.start..token.end]);
909 }902 }
...@@ -913,9 +906,9 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok...@@ -913,9 +906,9 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
913 .IntegerLiteral,906 .IntegerLiteral,
914 .FloatLiteral,907 .FloatLiteral,
915 => {908 => {
916 try out.write("<span class=\"tok-number\">");909 try out.writeAll("<span class=\"tok-number\">");
917 try writeEscaped(out, src[token.start..token.end]);910 try writeEscaped(out, src[token.start..token.end]);
918 try out.write("</span>");911 try out.writeAll("</span>");
919 },912 },
920913
921 .Bang,914 .Bang,
...@@ -983,7 +976,7 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok...@@ -983,7 +976,7 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
983 }976 }
984 index = token.end;977 index = token.end;
985 }978 }
986 try out.write("</code>");979 try out.writeAll("</code>");
987}980}
988981
989fn tokenizeAndPrint(docgen_tokenizer: *Tokenizer, out: var, source_token: Token) !void {982fn tokenizeAndPrint(docgen_tokenizer: *Tokenizer, out: var, source_token: Token) !void {
...@@ -1002,7 +995,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1002,7 +995,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1002 for (toc.nodes) |node| {995 for (toc.nodes) |node| {
1003 switch (node) {996 switch (node) {
1004 .Content => |data| {997 .Content => |data| {
1005 try out.write(data);998 try out.writeAll(data);
1006 },999 },
1007 .Link => |info| {1000 .Link => |info| {
1008 if (!toc.urls.contains(info.url)) {1001 if (!toc.urls.contains(info.url)) {
...@@ -1011,12 +1004,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1011,12 +1004,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1011 try out.print("<a href=\"#{}\">{}</a>", .{ info.url, info.name });1004 try out.print("<a href=\"#{}\">{}</a>", .{ info.url, info.name });
1012 },1005 },
1013 .Nav => {1006 .Nav => {
1014 try out.write(toc.toc);1007 try out.writeAll(toc.toc);
1015 },1008 },
1016 .Builtin => |tok| {1009 .Builtin => |tok| {
1017 try out.write("<pre>");1010 try out.writeAll("<pre>");
1018 try tokenizeAndPrintRaw(tokenizer, out, tok, builtin_code);1011 try tokenizeAndPrintRaw(tokenizer, out, tok, builtin_code);
1019 try out.write("</pre>");1012 try out.writeAll("</pre>");
1020 },1013 },
1021 .HeaderOpen => |info| {1014 .HeaderOpen => |info| {
1022 try out.print(1015 try out.print(
...@@ -1025,7 +1018,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1025,7 +1018,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1025 );1018 );
1026 },1019 },
1027 .SeeAlso => |items| {1020 .SeeAlso => |items| {
1028 try out.write("<p>See also:</p><ul>\n");1021 try out.writeAll("<p>See also:</p><ul>\n");
1029 for (items) |item| {1022 for (items) |item| {
1030 const url = try urlize(allocator, item.name);1023 const url = try urlize(allocator, item.name);
1031 if (!toc.urls.contains(url)) {1024 if (!toc.urls.contains(url)) {
...@@ -1033,7 +1026,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1033,7 +1026,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1033 }1026 }
1034 try out.print("<li><a href=\"#{}\">{}</a></li>\n", .{ url, item.name });1027 try out.print("<li><a href=\"#{}\">{}</a></li>\n", .{ url, item.name });
1035 }1028 }
1036 try out.write("</ul>\n");1029 try out.writeAll("</ul>\n");
1037 },1030 },
1038 .Syntax => |content_tok| {1031 .Syntax => |content_tok| {
1039 try tokenizeAndPrint(tokenizer, out, content_tok);1032 try tokenizeAndPrint(tokenizer, out, content_tok);
...@@ -1047,9 +1040,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var...@@ -1047,9 +1040,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
1047 if (!code.is_inline) {1040 if (!code.is_inline) {
1048 try out.print("<p class=\"file\">{}.zig</p>", .{code.name});1041 try out.print("<p class=\"file\">{}.zig</p>", .{code.name});
1049 }1042 }
1050 try out.write("<pre>");1043 try out.writeAll("<pre>");
1051 try tokenizeAndPrint(tokenizer, out, code.source_token);1044 try tokenizeAndPrint(tokenizer, out, code.source_token);
1052 try out.write("</pre>");1045 try out.writeAll("</pre>");
1053 const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", .{code.name});1046 const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", .{code.name});
1054 const tmp_source_file_name = try fs.path.join(1047 const tmp_source_file_name = try fs.path.join(
1055 allocator,1048 allocator,
doc/langref.html.in+11-36
...@@ -230,7 +230,7 @@...@@ -230,7 +230,7 @@
230const std = @import("std");230const std = @import("std");
231231
232pub fn main() !void {232pub fn main() !void {
233 const stdout = &std.io.getStdOut().outStream().stream;233 const stdout = std.io.getStdOut().outStream();
234 try stdout.print("Hello, {}!\n", .{"world"});234 try stdout.print("Hello, {}!\n", .{"world"});
235}235}
236 {#code_end#}236 {#code_end#}
...@@ -6728,17 +6728,8 @@ async fn func(y: *i32) void {...@@ -6728,17 +6728,8 @@ async fn func(y: *i32) void {
6728 This builtin function atomically dereferences a pointer and returns the value.6728 This builtin function atomically dereferences a pointer and returns the value.
6729 </p>6729 </p>
6730 <p>6730 <p>
6731 {#syntax#}T{#endsyntax#} must be a pointer type, a {#syntax#}bool{#endsyntax#}, a float,6731 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
6732 an integer whose bit count meets these requirements:6732 an integer or an enum.
6733 </p>
6734 <ul>
6735 <li>At least 8</li>
6736 <li>At most the same as usize</li>
6737 <li>Power of 2</li>
6738 </ul> or an enum with a valid integer tag type.
6739 <p>
6740 TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe
6741 we can remove this restriction
6742 </p>6733 </p>
6743 {#header_close#}6734 {#header_close#}
6744 {#header_open|@atomicRmw#}6735 {#header_open|@atomicRmw#}
...@@ -6747,17 +6738,8 @@ async fn func(y: *i32) void {...@@ -6747,17 +6738,8 @@ async fn func(y: *i32) void {
6747 This builtin function atomically modifies memory and then returns the previous value.6738 This builtin function atomically modifies memory and then returns the previous value.
6748 </p>6739 </p>
6749 <p>6740 <p>
6750 {#syntax#}T{#endsyntax#} must be a pointer type, a {#syntax#}bool{#endsyntax#},6741 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
6751 or an integer whose bit count meets these requirements:6742 an integer or an enum.
6752 </p>
6753 <ul>
6754 <li>At least 8</li>
6755 <li>At most the same as usize</li>
6756 <li>Power of 2</li>
6757 </ul>
6758 <p>
6759 TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe
6760 we can remove this restriction
6761 </p>6743 </p>
6762 <p>6744 <p>
6763 Supported operations:6745 Supported operations:
...@@ -6782,17 +6764,8 @@ async fn func(y: *i32) void {...@@ -6782,17 +6764,8 @@ async fn func(y: *i32) void {
6782 This builtin function atomically stores a value.6764 This builtin function atomically stores a value.
6783 </p>6765 </p>
6784 <p>6766 <p>
6785 {#syntax#}T{#endsyntax#} must be a pointer type, a {#syntax#}bool{#endsyntax#}, a float,6767 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
6786 an integer whose bit count meets these requirements:6768 an integer or an enum.
6787 </p>
6788 <ul>
6789 <li>At least 8</li>
6790 <li>At most the same as usize</li>
6791 <li>Power of 2</li>
6792 </ul> or an enum with a valid integer tag type.
6793 <p>
6794 TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe
6795 we can remove this restriction
6796 </p>6769 </p>
6797 {#header_close#}6770 {#header_close#}
6798 {#header_open|@bitCast#}6771 {#header_open|@bitCast#}
...@@ -7074,7 +7047,8 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_v...@@ -7074,7 +7047,8 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_v
7074 more efficiently in machine instructions.7047 more efficiently in machine instructions.
7075 </p>7048 </p>
7076 <p>7049 <p>
7077 {#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("builtin").AtomicOrder{#endsyntax#}.7050 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
7051 an integer or an enum.
7078 </p>7052 </p>
7079 <p>{#syntax#}@TypeOf(ptr).alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>7053 <p>{#syntax#}@TypeOf(ptr).alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>
7080 {#see_also|Compile Variables|cmpxchgWeak#}7054 {#see_also|Compile Variables|cmpxchgWeak#}
...@@ -7102,7 +7076,8 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val...@@ -7102,7 +7076,8 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val
7102 However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.7076 However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.
7103 </p>7077 </p>
7104 <p>7078 <p>
7105 {#syntax#}AtomicOrder{#endsyntax#} can be found with {#syntax#}@import("builtin").AtomicOrder{#endsyntax#}.7079 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
7080 an integer or an enum.
7106 </p>7081 </p>
7107 <p>{#syntax#}@TypeOf(ptr).alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>7082 <p>{#syntax#}@TypeOf(ptr).alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>
7108 {#see_also|Compile Variables|cmpxchgStrong#}7083 {#see_also|Compile Variables|cmpxchgStrong#}
lib/libc/include/aarch64-linux-musl/bits/alltypes.h+66-55
...@@ -2,16 +2,13 @@...@@ -2,16 +2,13 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)5#if __AARCH64EB__
6typedef __builtin_va_list va_list;6#define __BYTE_ORDER 4321
7#define __DEFINED_va_list7#else
8#endif8#define __BYTE_ORDER 1234
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif9#endif
1410
11#define __LONG_MAX 0x7fffffffffffffffL
1512
16#ifndef __cplusplus13#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)14#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -53,52 +50,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -53,52 +50,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
53#define __DEFINED_max_align_t50#define __DEFINED_max_align_t
54#endif51#endif
5552
5653#define __LITTLE_ENDIAN 1234
57#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)54#define __BIG_ENDIAN 4321
58typedef long time_t;55#define __USE_TIME_BITS64 1
59#define __DEFINED_time_t
60#endif
61
62#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
63typedef long suseconds_t;
64#define __DEFINED_suseconds_t
65#endif
66
67
68#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
69typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
70#define __DEFINED_pthread_attr_t
71#endif
72
73#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
74typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
75#define __DEFINED_pthread_mutex_t
76#endif
77
78#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
79typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
80#define __DEFINED_mtx_t
81#endif
82
83#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
84typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
85#define __DEFINED_pthread_cond_t
86#endif
87
88#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
89typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
90#define __DEFINED_cnd_t
91#endif
92
93#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
94typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
95#define __DEFINED_pthread_rwlock_t
96#endif
97
98#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
99typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
100#define __DEFINED_pthread_barrier_t
101#endif
10256
103#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)57#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
104typedef unsigned _Addr size_t;58typedef unsigned _Addr size_t;
...@@ -135,6 +89,16 @@ typedef _Reg register_t;...@@ -135,6 +89,16 @@ typedef _Reg register_t;
135#define __DEFINED_register_t89#define __DEFINED_register_t
136#endif90#endif
13791
92#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
93typedef _Int64 time_t;
94#define __DEFINED_time_t
95#endif
96
97#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
98typedef _Int64 suseconds_t;
99#define __DEFINED_suseconds_t
100#endif
101
138102
139#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)103#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
140typedef signed char int8_t;104typedef signed char int8_t;
...@@ -270,7 +234,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -270,7 +234,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
270#endif234#endif
271235
272#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)236#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
273struct timespec { time_t tv_sec; long tv_nsec; };237struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
274#define __DEFINED_struct_timespec238#define __DEFINED_struct_timespec
275#endif239#endif
276240
...@@ -366,6 +330,17 @@ typedef struct _IO_FILE FILE;...@@ -366,6 +330,17 @@ typedef struct _IO_FILE FILE;
366#endif330#endif
367331
368332
333#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
334typedef __builtin_va_list va_list;
335#define __DEFINED_va_list
336#endif
337
338#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
339typedef __builtin_va_list __isoc_va_list;
340#define __DEFINED___isoc_va_list
341#endif
342
343
369#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)344#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
370typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;345typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
371#define __DEFINED_mbstate_t346#define __DEFINED_mbstate_t
...@@ -401,6 +376,42 @@ typedef unsigned short sa_family_t;...@@ -401,6 +376,42 @@ typedef unsigned short sa_family_t;
401#endif376#endif
402377
403378
379#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
380typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
381#define __DEFINED_pthread_attr_t
382#endif
383
384#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
385typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
386#define __DEFINED_pthread_mutex_t
387#endif
388
389#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
390typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
391#define __DEFINED_mtx_t
392#endif
393
394#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
395typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
396#define __DEFINED_pthread_cond_t
397#endif
398
399#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
400typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
401#define __DEFINED_cnd_t
402#endif
403
404#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
405typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
406#define __DEFINED_pthread_rwlock_t
407#endif
408
409#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
410typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
411#define __DEFINED_pthread_barrier_t
412#endif
413
414
404#undef _Addr415#undef _Addr
405#undef _Int64416#undef _Int64
406#undef _Reg417#undef _Reg
\ No newline at end of file
lib/libc/include/aarch64-linux-musl/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if __AARCH64EB__
2#define __BYTE_ORDER __BIG_ENDIAN
3#else
4#define __BYTE_ORDER __LITTLE_ENDIAN
5#endif
\ No newline at end of file
lib/libc/include/aarch64-linux-musl/bits/socket.h deleted-33
...@@ -1,33 +0,0 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7#if __BYTE_ORDER == __BIG_ENDIAN
8 int __pad1, msg_iovlen;
9#else
10 int msg_iovlen, __pad1;
11#endif
12 void *msg_control;
13#if __BYTE_ORDER == __BIG_ENDIAN
14 int __pad2;
15 socklen_t msg_controllen;
16#else
17 socklen_t msg_controllen;
18 int __pad2;
19#endif
20 int msg_flags;
21};
22
23struct cmsghdr {
24#if __BYTE_ORDER == __BIG_ENDIAN
25 int __pad1;
26 socklen_t cmsg_len;
27#else
28 socklen_t cmsg_len;
29 int __pad1;
30#endif
31 int cmsg_level;
32 int cmsg_type;
33};
\ No newline at end of file
lib/libc/include/aarch64-linux-musl/bits/syscall.h+5-1
...@@ -287,6 +287,8 @@...@@ -287,6 +287,8 @@
287#define __NR_fsconfig 431287#define __NR_fsconfig 431
288#define __NR_fsmount 432288#define __NR_fsmount 432
289#define __NR_fspick 433289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
291#define SYS_io_setup 0293#define SYS_io_setup 0
292#define SYS_io_destroy 1294#define SYS_io_destroy 1
...@@ -576,4 +578,6 @@...@@ -576,4 +578,6 @@
576#define SYS_fsopen 430578#define SYS_fsopen 430
577#define SYS_fsconfig 431579#define SYS_fsconfig 431
578#define SYS_fsmount 432580#define SYS_fsmount 432
579#define SYS_fspick 433
\ No newline at end of file
581#define SYS_fspick 433
582#define SYS_pidfd_open 434
583#define SYS_clone3 435
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/alltypes.h+67-55
...@@ -1,17 +1,15 @@...@@ -1,17 +1,15 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)6#if __ARMEB__
6typedef __builtin_va_list va_list;7#define __BYTE_ORDER 4321
7#define __DEFINED_va_list8#else
8#endif9#define __BYTE_ORDER 1234
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif10#endif
1411
12#define __LONG_MAX 0x7fffffffL
1513
16#ifndef __cplusplus14#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)15#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -37,52 +35,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -37,52 +35,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
37#define __DEFINED_max_align_t35#define __DEFINED_max_align_t
38#endif36#endif
3937
4038#define __LITTLE_ENDIAN 1234
41#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)39#define __BIG_ENDIAN 4321
42typedef long time_t;40#define __USE_TIME_BITS64 1
43#define __DEFINED_time_t
44#endif
45
46#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
47typedef long suseconds_t;
48#define __DEFINED_suseconds_t
49#endif
50
51
52#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
53typedef struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
54#define __DEFINED_pthread_attr_t
55#endif
56
57#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
58typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
59#define __DEFINED_pthread_mutex_t
60#endif
61
62#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
63typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
64#define __DEFINED_mtx_t
65#endif
66
67#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
68typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
69#define __DEFINED_pthread_cond_t
70#endif
71
72#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
73typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
74#define __DEFINED_cnd_t
75#endif
76
77#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
78typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
79#define __DEFINED_pthread_rwlock_t
80#endif
81
82#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
83typedef struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
84#define __DEFINED_pthread_barrier_t
85#endif
8641
87#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)42#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
88typedef unsigned _Addr size_t;43typedef unsigned _Addr size_t;
...@@ -119,6 +74,16 @@ typedef _Reg register_t;...@@ -119,6 +74,16 @@ typedef _Reg register_t;
119#define __DEFINED_register_t74#define __DEFINED_register_t
120#endif75#endif
12176
77#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
78typedef _Int64 time_t;
79#define __DEFINED_time_t
80#endif
81
82#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
83typedef _Int64 suseconds_t;
84#define __DEFINED_suseconds_t
85#endif
86
12287
123#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)88#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
124typedef signed char int8_t;89typedef signed char int8_t;
...@@ -254,7 +219,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -254,7 +219,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254#endif219#endif
255220
256#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)221#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
257struct timespec { time_t tv_sec; long tv_nsec; };222struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
258#define __DEFINED_struct_timespec223#define __DEFINED_struct_timespec
259#endif224#endif
260225
...@@ -350,6 +315,17 @@ typedef struct _IO_FILE FILE;...@@ -350,6 +315,17 @@ typedef struct _IO_FILE FILE;
350#endif315#endif
351316
352317
318#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
319typedef __builtin_va_list va_list;
320#define __DEFINED_va_list
321#endif
322
323#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
324typedef __builtin_va_list __isoc_va_list;
325#define __DEFINED___isoc_va_list
326#endif
327
328
353#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)329#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;330typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355#define __DEFINED_mbstate_t331#define __DEFINED_mbstate_t
...@@ -385,6 +361,42 @@ typedef unsigned short sa_family_t;...@@ -385,6 +361,42 @@ typedef unsigned short sa_family_t;
385#endif361#endif
386362
387363
364#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
365typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
366#define __DEFINED_pthread_attr_t
367#endif
368
369#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
370typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
371#define __DEFINED_pthread_mutex_t
372#endif
373
374#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
375typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
376#define __DEFINED_mtx_t
377#endif
378
379#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
380typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
381#define __DEFINED_pthread_cond_t
382#endif
383
384#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
385typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
386#define __DEFINED_cnd_t
387#endif
388
389#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
390typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
391#define __DEFINED_pthread_rwlock_t
392#endif
393
394#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
395typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
396#define __DEFINED_pthread_barrier_t
397#endif
398
399
388#undef _Addr400#undef _Addr
389#undef _Int64401#undef _Int64
390#undef _Reg402#undef _Reg
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if __ARMEB__
2#define __BYTE_ORDER __BIG_ENDIAN
3#else
4#define __BYTE_ORDER __LITTLE_ENDIAN
5#endif
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/ipcstat.h created+1
...@@ -0,0 +1 @@
1#define IPC_STAT 0x102
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 32
4#endif
5
6#define LONG_MAX 0x7fffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/msg.h+9-6
...@@ -1,15 +1,18 @@...@@ -1,15 +1,18 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3 time_t msg_stime;3 unsigned long __msg_stime_lo;
4 int __unused1;4 unsigned long __msg_stime_hi;
5 time_t msg_rtime;5 unsigned long __msg_rtime_lo;
6 int __unused2;6 unsigned long __msg_rtime_hi;
7 time_t msg_ctime;7 unsigned long __msg_ctime_lo;
8 int __unused3;8 unsigned long __msg_ctime_hi;
9 unsigned long msg_cbytes;9 unsigned long msg_cbytes;
10 msgqnum_t msg_qnum;10 msgqnum_t msg_qnum;
11 msglen_t msg_qbytes;11 msglen_t msg_qbytes;
12 pid_t msg_lspid;12 pid_t msg_lspid;
13 pid_t msg_lrpid;13 pid_t msg_lrpid;
14 unsigned long __unused[2];14 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
15};18};
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/sem.h+6-4
...@@ -1,9 +1,9 @@...@@ -1,9 +1,9 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 time_t sem_otime;3 unsigned long __sem_otime_lo;
4 long __unused1;4 unsigned long __sem_otime_hi;
5 time_t sem_ctime;5 unsigned long __sem_ctime_lo;
6 long __unused2;6 unsigned long __sem_ctime_hi;
7#if __BYTE_ORDER == __LITTLE_ENDIAN7#if __BYTE_ORDER == __LITTLE_ENDIAN
8 unsigned short sem_nsems;8 unsigned short sem_nsems;
9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
...@@ -13,4 +13,6 @@ struct semid_ds {...@@ -13,4 +13,6 @@ struct semid_ds {
13#endif13#endif
14 long __unused3;14 long __unused3;
15 long __unused4;15 long __unused4;
16 time_t sem_otime;
17 time_t sem_ctime;
16};18};
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/shm.h+10-6
...@@ -3,17 +3,21 @@...@@ -3,17 +3,21 @@
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 size_t shm_segsz;5 size_t shm_segsz;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 int __unused1;7 unsigned long __shm_atime_hi;
8 time_t shm_dtime;8 unsigned long __shm_dtime_lo;
9 int __unused2;9 unsigned long __shm_dtime_hi;
10 time_t shm_ctime;10 unsigned long __shm_ctime_lo;
11 int __unused3;11 unsigned long __shm_ctime_hi;
12 pid_t shm_cpid;12 pid_t shm_cpid;
13 pid_t shm_lpid;13 pid_t shm_lpid;
14 unsigned long shm_nattch;14 unsigned long shm_nattch;
15 unsigned long __pad1;15 unsigned long __pad1;
16 unsigned long __pad2;16 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
17};21};
1822
19struct shminfo {23struct shminfo {
lib/libc/include/arm-linux-musl/bits/stat.h+5-1
...@@ -14,8 +14,12 @@ struct stat {...@@ -14,8 +14,12 @@ struct stat {
14 off_t st_size;14 off_t st_size;
15 blksize_t st_blksize;15 blksize_t st_blksize;
16 blkcnt_t st_blocks;16 blkcnt_t st_blocks;
17 struct {
18 long tv_sec;
19 long tv_nsec;
20 } __st_atim32, __st_mtim32, __st_ctim32;
21 ino_t st_ino;
17 struct timespec st_atim;22 struct timespec st_atim;
18 struct timespec st_mtim;23 struct timespec st_mtim;
19 struct timespec st_ctim;24 struct timespec st_ctim;
20 ino_t st_ino;
21};25};
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/syscall.h+25-21
...@@ -55,8 +55,8 @@...@@ -55,8 +55,8 @@
55#define __NR_sethostname 7455#define __NR_sethostname 74
56#define __NR_setrlimit 7556#define __NR_setrlimit 75
57#define __NR_getrusage 7757#define __NR_getrusage 77
58#define __NR_gettimeofday 7858#define __NR_gettimeofday_time32 78
59#define __NR_settimeofday 7959#define __NR_settimeofday_time32 79
60#define __NR_getgroups 8060#define __NR_getgroups 80
61#define __NR_setgroups 8161#define __NR_setgroups 81
62#define __NR_symlink 8362#define __NR_symlink 83
...@@ -211,14 +211,14 @@...@@ -211,14 +211,14 @@
211#define __NR_remap_file_pages 253211#define __NR_remap_file_pages 253
212#define __NR_set_tid_address 256212#define __NR_set_tid_address 256
213#define __NR_timer_create 257213#define __NR_timer_create 257
214#define __NR_timer_settime 258214#define __NR_timer_settime32 258
215#define __NR_timer_gettime 259215#define __NR_timer_gettime32 259
216#define __NR_timer_getoverrun 260216#define __NR_timer_getoverrun 260
217#define __NR_timer_delete 261217#define __NR_timer_delete 261
218#define __NR_clock_settime 262218#define __NR_clock_settime32 262
219#define __NR_clock_gettime 263219#define __NR_clock_gettime32 263
220#define __NR_clock_getres 264220#define __NR_clock_getres_time32 264
221#define __NR_clock_nanosleep 265221#define __NR_clock_nanosleep_time32 265
222#define __NR_statfs64 266222#define __NR_statfs64 266
223#define __NR_fstatfs64 267223#define __NR_fstatfs64 267
224#define __NR_tgkill 268224#define __NR_tgkill 268
...@@ -308,8 +308,8 @@...@@ -308,8 +308,8 @@
308#define __NR_timerfd_create 350308#define __NR_timerfd_create 350
309#define __NR_eventfd 351309#define __NR_eventfd 351
310#define __NR_fallocate 352310#define __NR_fallocate 352
311#define __NR_timerfd_settime 353311#define __NR_timerfd_settime32 353
312#define __NR_timerfd_gettime 354312#define __NR_timerfd_gettime32 354
313#define __NR_signalfd4 355313#define __NR_signalfd4 355
314#define __NR_eventfd2 356314#define __NR_eventfd2 356
315#define __NR_epoll_create1 357315#define __NR_epoll_create1 357
...@@ -387,6 +387,8 @@...@@ -387,6 +387,8 @@
387#define __NR_fsconfig 431387#define __NR_fsconfig 431
388#define __NR_fsmount 432388#define __NR_fsmount 432
389#define __NR_fspick 433389#define __NR_fspick 433
390#define __NR_pidfd_open 434
391#define __NR_clone3 435
390392
391#define __ARM_NR_breakpoint 0x0f0001393#define __ARM_NR_breakpoint 0x0f0001
392#define __ARM_NR_cacheflush 0x0f0002394#define __ARM_NR_cacheflush 0x0f0002
...@@ -452,8 +454,8 @@...@@ -452,8 +454,8 @@
452#define SYS_sethostname 74454#define SYS_sethostname 74
453#define SYS_setrlimit 75455#define SYS_setrlimit 75
454#define SYS_getrusage 77456#define SYS_getrusage 77
455#define SYS_gettimeofday 78457#define SYS_gettimeofday_time32 78
456#define SYS_settimeofday 79458#define SYS_settimeofday_time32 79
457#define SYS_getgroups 80459#define SYS_getgroups 80
458#define SYS_setgroups 81460#define SYS_setgroups 81
459#define SYS_symlink 83461#define SYS_symlink 83
...@@ -608,14 +610,14 @@...@@ -608,14 +610,14 @@
608#define SYS_remap_file_pages 253610#define SYS_remap_file_pages 253
609#define SYS_set_tid_address 256611#define SYS_set_tid_address 256
610#define SYS_timer_create 257612#define SYS_timer_create 257
611#define SYS_timer_settime 258613#define SYS_timer_settime32 258
612#define SYS_timer_gettime 259614#define SYS_timer_gettime32 259
613#define SYS_timer_getoverrun 260615#define SYS_timer_getoverrun 260
614#define SYS_timer_delete 261616#define SYS_timer_delete 261
615#define SYS_clock_settime 262617#define SYS_clock_settime32 262
616#define SYS_clock_gettime 263618#define SYS_clock_gettime32 263
617#define SYS_clock_getres 264619#define SYS_clock_getres_time32 264
618#define SYS_clock_nanosleep 265620#define SYS_clock_nanosleep_time32 265
619#define SYS_statfs64 266621#define SYS_statfs64 266
620#define SYS_fstatfs64 267622#define SYS_fstatfs64 267
621#define SYS_tgkill 268623#define SYS_tgkill 268
...@@ -705,8 +707,8 @@...@@ -705,8 +707,8 @@
705#define SYS_timerfd_create 350707#define SYS_timerfd_create 350
706#define SYS_eventfd 351708#define SYS_eventfd 351
707#define SYS_fallocate 352709#define SYS_fallocate 352
708#define SYS_timerfd_settime 353710#define SYS_timerfd_settime32 353
709#define SYS_timerfd_gettime 354711#define SYS_timerfd_gettime32 354
710#define SYS_signalfd4 355712#define SYS_signalfd4 355
711#define SYS_eventfd2 356713#define SYS_eventfd2 356
712#define SYS_epoll_create1 357714#define SYS_epoll_create1 357
...@@ -783,4 +785,6 @@...@@ -783,4 +785,6 @@
783#define SYS_fsopen 430785#define SYS_fsopen 430
784#define SYS_fsconfig 431786#define SYS_fsconfig 431
785#define SYS_fsmount 432787#define SYS_fsmount 432
786#define SYS_fspick 433
\ No newline at end of file
788#define SYS_fspick 433
789#define SYS_pidfd_open 434
790#define SYS_clone3 435
\ No newline at end of file
lib/libc/include/generic-musl/aio.h+4
...@@ -62,6 +62,10 @@ int lio_listio(int, struct aiocb *__restrict const *__restrict, int, struct sige...@@ -62,6 +62,10 @@ int lio_listio(int, struct aiocb *__restrict const *__restrict, int, struct sige
62#define off64_t off_t62#define off64_t off_t
63#endif63#endif
6464
65#if _REDIR_TIME64
66__REDIR(aio_suspend, __aio_suspend_time64);
67#endif
68
65#ifdef __cplusplus69#ifdef __cplusplus
66}70}
67#endif71#endif
lib/libc/include/generic-musl/alloca.h-2
...@@ -10,9 +10,7 @@ extern "C" {...@@ -10,9 +10,7 @@ extern "C" {
1010
11void *alloca(size_t);11void *alloca(size_t);
1212
13#ifdef __GNUC__
14#define alloca __builtin_alloca13#define alloca __builtin_alloca
15#endif
1614
17#ifdef __cplusplus15#ifdef __cplusplus
18}16}
lib/libc/include/generic-musl/arpa/nameser.h-1
...@@ -7,7 +7,6 @@ extern "C" {...@@ -7,7 +7,6 @@ extern "C" {
77
8#include <stddef.h>8#include <stddef.h>
9#include <stdint.h>9#include <stdint.h>
10#include <endian.h>
1110
12#define __NAMESER 1999100611#define __NAMESER 19991006
13#define NS_PACKETSZ 51212#define NS_PACKETSZ 512
lib/libc/include/generic-musl/bits/dirent.h created+11
...@@ -0,0 +1,11 @@
1#define _DIRENT_HAVE_D_RECLEN
2#define _DIRENT_HAVE_D_OFF
3#define _DIRENT_HAVE_D_TYPE
4
5struct dirent {
6 ino_t d_ino;
7 off_t d_off;
8 unsigned short d_reclen;
9 unsigned char d_type;
10 char d_name[256];
11};
\ No newline at end of file
lib/libc/include/generic-musl/bits/endian.h deleted-1
...@@ -1 +0,0 @@
1#define __BYTE_ORDER __LITTLE_ENDIAN
\ No newline at end of file
lib/libc/include/generic-musl/bits/ioctl.h+5
...@@ -104,7 +104,12 @@...@@ -104,7 +104,12 @@
104#define FIOGETOWN 0x8903104#define FIOGETOWN 0x8903
105#define SIOCGPGRP 0x8904105#define SIOCGPGRP 0x8904
106#define SIOCATMARK 0x8905106#define SIOCATMARK 0x8905
107#if __LONG_MAX == 0x7fffffff
108#define SIOCGSTAMP _IOR(0x89, 6, char[16])
109#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
110#else
107#define SIOCGSTAMP 0x8906111#define SIOCGSTAMP 0x8906
108#define SIOCGSTAMPNS 0x8907112#define SIOCGSTAMPNS 0x8907
113#endif
109114
110#include <bits/ioctl_fix.h>115#include <bits/ioctl_fix.h>
\ No newline at end of file
lib/libc/include/generic-musl/bits/limits.h-7
...@@ -1,7 +0,0 @@...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 64
4#endif
5
6#define LONG_MAX 0x7fffffffffffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
lib/libc/include/generic-musl/bits/socket.h-15
...@@ -1,15 +0,0 @@...@@ -1,15 +0,0 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen;
6 void *msg_control;
7 socklen_t msg_controllen;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int cmsg_level;
14 int cmsg_type;
15};
\ No newline at end of file
lib/libc/include/generic-musl/dirent.h+2-12
...@@ -15,19 +15,9 @@ extern "C" {...@@ -15,19 +15,9 @@ extern "C" {
1515
16#include <bits/alltypes.h>16#include <bits/alltypes.h>
1717
18typedef struct __dirstream DIR;18#include <bits/dirent.h>
19
20#define _DIRENT_HAVE_D_RECLEN
21#define _DIRENT_HAVE_D_OFF
22#define _DIRENT_HAVE_D_TYPE
2319
24struct dirent {20typedef struct __dirstream DIR;
25 ino_t d_ino;
26 off_t d_off;
27 unsigned short d_reclen;
28 unsigned char d_type;
29 char d_name[256];
30};
3121
32#define d_fileno d_ino22#define d_fileno d_ino
3323
lib/libc/include/generic-musl/dlfcn.h+4
...@@ -35,6 +35,10 @@ int dladdr(const void *, Dl_info *);...@@ -35,6 +35,10 @@ int dladdr(const void *, Dl_info *);
35int dlinfo(void *, int, void *);35int dlinfo(void *, int, void *);
36#endif36#endif
3737
38#if _REDIR_TIME64
39__REDIR(dlsym, __dlsym_time64);
40#endif
41
38#ifdef __cplusplus42#ifdef __cplusplus
39}43}
40#endif44#endif
lib/libc/include/generic-musl/endian.h+21-23
...@@ -3,25 +3,19 @@...@@ -3,25 +3,19 @@
33
4#include <features.h>4#include <features.h>
55
6#define __LITTLE_ENDIAN 12346#define __NEED_uint16_t
7#define __BIG_ENDIAN 43217#define __NEED_uint32_t
8#define __PDP_ENDIAN 34128#define __NEED_uint64_t
99
10#if defined(__GNUC__) && defined(__BYTE_ORDER__)10#include <bits/alltypes.h>
11#define __BYTE_ORDER __BYTE_ORDER__
12#else
13#include <bits/endian.h>
14#endif
1511
16#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)12#define __PDP_ENDIAN 3412
1713
18#define BIG_ENDIAN __BIG_ENDIAN14#define BIG_ENDIAN __BIG_ENDIAN
19#define LITTLE_ENDIAN __LITTLE_ENDIAN15#define LITTLE_ENDIAN __LITTLE_ENDIAN
20#define PDP_ENDIAN __PDP_ENDIAN16#define PDP_ENDIAN __PDP_ENDIAN
21#define BYTE_ORDER __BYTE_ORDER17#define BYTE_ORDER __BYTE_ORDER
2218
23#include <stdint.h>
24
25static __inline uint16_t __bswap16(uint16_t __x)19static __inline uint16_t __bswap16(uint16_t __x)
26{20{
27 return __x<<8 | __x>>8;21 return __x<<8 | __x>>8;
...@@ -40,43 +34,47 @@ static __inline uint64_t __bswap64(uint64_t __x)...@@ -40,43 +34,47 @@ static __inline uint64_t __bswap64(uint64_t __x)
40#if __BYTE_ORDER == __LITTLE_ENDIAN34#if __BYTE_ORDER == __LITTLE_ENDIAN
41#define htobe16(x) __bswap16(x)35#define htobe16(x) __bswap16(x)
42#define be16toh(x) __bswap16(x)36#define be16toh(x) __bswap16(x)
43#define betoh16(x) __bswap16(x)
44#define htobe32(x) __bswap32(x)37#define htobe32(x) __bswap32(x)
45#define be32toh(x) __bswap32(x)38#define be32toh(x) __bswap32(x)
46#define betoh32(x) __bswap32(x)
47#define htobe64(x) __bswap64(x)39#define htobe64(x) __bswap64(x)
48#define be64toh(x) __bswap64(x)40#define be64toh(x) __bswap64(x)
49#define betoh64(x) __bswap64(x)
50#define htole16(x) (uint16_t)(x)41#define htole16(x) (uint16_t)(x)
51#define le16toh(x) (uint16_t)(x)42#define le16toh(x) (uint16_t)(x)
52#define letoh16(x) (uint16_t)(x)
53#define htole32(x) (uint32_t)(x)43#define htole32(x) (uint32_t)(x)
54#define le32toh(x) (uint32_t)(x)44#define le32toh(x) (uint32_t)(x)
55#define letoh32(x) (uint32_t)(x)
56#define htole64(x) (uint64_t)(x)45#define htole64(x) (uint64_t)(x)
57#define le64toh(x) (uint64_t)(x)46#define le64toh(x) (uint64_t)(x)
58#define letoh64(x) (uint64_t)(x)
59#else47#else
60#define htobe16(x) (uint16_t)(x)48#define htobe16(x) (uint16_t)(x)
61#define be16toh(x) (uint16_t)(x)49#define be16toh(x) (uint16_t)(x)
62#define betoh16(x) (uint16_t)(x)
63#define htobe32(x) (uint32_t)(x)50#define htobe32(x) (uint32_t)(x)
64#define be32toh(x) (uint32_t)(x)51#define be32toh(x) (uint32_t)(x)
65#define betoh32(x) (uint32_t)(x)
66#define htobe64(x) (uint64_t)(x)52#define htobe64(x) (uint64_t)(x)
67#define be64toh(x) (uint64_t)(x)53#define be64toh(x) (uint64_t)(x)
68#define betoh64(x) (uint64_t)(x)
69#define htole16(x) __bswap16(x)54#define htole16(x) __bswap16(x)
70#define le16toh(x) __bswap16(x)55#define le16toh(x) __bswap16(x)
71#define letoh16(x) __bswap16(x)
72#define htole32(x) __bswap32(x)56#define htole32(x) __bswap32(x)
73#define le32toh(x) __bswap32(x)57#define le32toh(x) __bswap32(x)
74#define letoh32(x) __bswap32(x)
75#define htole64(x) __bswap64(x)58#define htole64(x) __bswap64(x)
76#define le64toh(x) __bswap64(x)59#define le64toh(x) __bswap64(x)
77#define letoh64(x) __bswap64(x)
78#endif60#endif
7961
62#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
63#if __BYTE_ORDER == __LITTLE_ENDIAN
64#define betoh16(x) __bswap16(x)
65#define betoh32(x) __bswap32(x)
66#define betoh64(x) __bswap64(x)
67#define letoh16(x) (uint16_t)(x)
68#define letoh32(x) (uint32_t)(x)
69#define letoh64(x) (uint64_t)(x)
70#else
71#define betoh16(x) (uint16_t)(x)
72#define betoh32(x) (uint32_t)(x)
73#define betoh64(x) (uint64_t)(x)
74#define letoh16(x) __bswap16(x)
75#define letoh32(x) __bswap32(x)
76#define letoh64(x) __bswap64(x)
77#endif
80#endif78#endif
8179
82#endif80#endif
\ No newline at end of file
lib/libc/include/generic-musl/features.h+2
...@@ -35,4 +35,6 @@...@@ -35,4 +35,6 @@
35#define _Noreturn35#define _Noreturn
36#endif36#endif
3737
38#define __REDIR(x,y) __typeof__(x) x __asm__(#y)
39
38#endif40#endif
\ No newline at end of file
lib/libc/include/generic-musl/limits.h+13-5
...@@ -3,9 +3,7 @@...@@ -3,9 +3,7 @@
33
4#include <features.h>4#include <features.h>
55
6/* Most limits are system-specific */6#include <bits/alltypes.h> /* __LONG_MAX */
7
8#include <bits/limits.h>
97
10/* Support signed or unsigned plain-char */8/* Support signed or unsigned plain-char */
119
...@@ -17,8 +15,6 @@...@@ -17,8 +15,6 @@
17#define CHAR_MAX 12715#define CHAR_MAX 127
18#endif16#endif
1917
20/* Some universal constants... */
21
22#define CHAR_BIT 818#define CHAR_BIT 8
23#define SCHAR_MIN (-128)19#define SCHAR_MIN (-128)
24#define SCHAR_MAX 12720#define SCHAR_MAX 127
...@@ -30,8 +26,10 @@...@@ -30,8 +26,10 @@
30#define INT_MAX 0x7fffffff26#define INT_MAX 0x7fffffff
31#define UINT_MAX 0xffffffffU27#define UINT_MAX 0xffffffffU
32#define LONG_MIN (-LONG_MAX-1)28#define LONG_MIN (-LONG_MAX-1)
29#define LONG_MAX __LONG_MAX
33#define ULONG_MAX (2UL*LONG_MAX+1)30#define ULONG_MAX (2UL*LONG_MAX+1)
34#define LLONG_MIN (-LLONG_MAX-1)31#define LLONG_MIN (-LLONG_MAX-1)
32#define LLONG_MAX 0x7fffffffffffffffLL
35#define ULLONG_MAX (2ULL*LLONG_MAX+1)33#define ULLONG_MAX (2ULL*LLONG_MAX+1)
3634
37#define MB_LEN_MAX 435#define MB_LEN_MAX 4
...@@ -39,9 +37,13 @@...@@ -39,9 +37,13 @@
39#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \37#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
40 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)38 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
4139
40#include <bits/limits.h>
41
42#define PIPE_BUF 409642#define PIPE_BUF 4096
43#define FILESIZEBITS 6443#define FILESIZEBITS 64
44#ifndef NAME_MAX
44#define NAME_MAX 25545#define NAME_MAX 255
46#endif
45#define PATH_MAX 409647#define PATH_MAX 4096
46#define NGROUPS_MAX 3248#define NGROUPS_MAX 32
47#define ARG_MAX 13107249#define ARG_MAX 131072
...@@ -53,6 +55,12 @@...@@ -53,6 +55,12 @@
53#define TTY_NAME_MAX 3255#define TTY_NAME_MAX 32
54#define HOST_NAME_MAX 25556#define HOST_NAME_MAX 255
5557
58#if LONG_MAX == 0x7fffffffL
59#define LONG_BIT 32
60#else
61#define LONG_BIT 64
62#endif
63
56/* Implementation choices... */64/* Implementation choices... */
5765
58#define PTHREAD_KEYS_MAX 12866#define PTHREAD_KEYS_MAX 128
lib/libc/include/generic-musl/mqueue.h+5
...@@ -30,6 +30,11 @@ ssize_t mq_timedreceive(mqd_t, char *__restrict, size_t, unsigned *__restrict, c...@@ -30,6 +30,11 @@ ssize_t mq_timedreceive(mqd_t, char *__restrict, size_t, unsigned *__restrict, c
30int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *);30int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *);
31int mq_unlink(const char *);31int mq_unlink(const char *);
3232
33#if _REDIR_TIME64
34__REDIR(mq_timedreceive, __mq_timedreceive_time64);
35__REDIR(mq_timedsend, __mq_timedsend_time64);
36#endif
37
33#ifdef __cplusplus38#ifdef __cplusplus
34}39}
35#endif40#endif
lib/libc/include/generic-musl/netinet/icmp6.h-1
...@@ -9,7 +9,6 @@ extern "C" {...@@ -9,7 +9,6 @@ extern "C" {
9#include <string.h>9#include <string.h>
10#include <sys/types.h>10#include <sys/types.h>
11#include <netinet/in.h>11#include <netinet/in.h>
12#include <endian.h>
1312
14#define ICMP6_FILTER 113#define ICMP6_FILTER 1
1514
lib/libc/include/generic-musl/netinet/if_ether.h+1
...@@ -58,6 +58,7 @@...@@ -58,6 +58,7 @@
58#define ETH_P_ERSPAN 0x88BE58#define ETH_P_ERSPAN 0x88BE
59#define ETH_P_PREAUTH 0x88C759#define ETH_P_PREAUTH 0x88C7
60#define ETH_P_TIPC 0x88CA60#define ETH_P_TIPC 0x88CA
61#define ETH_P_LLDP 0x88CC
61#define ETH_P_MACSEC 0x88E562#define ETH_P_MACSEC 0x88E5
62#define ETH_P_8021AH 0x88E763#define ETH_P_8021AH 0x88E7
63#define ETH_P_MVRP 0x88F564#define ETH_P_MVRP 0x88F5
lib/libc/include/generic-musl/netinet/ip.h+2-1
...@@ -7,7 +7,6 @@ extern "C" {...@@ -7,7 +7,6 @@ extern "C" {
77
8#include <stdint.h>8#include <stdint.h>
9#include <netinet/in.h>9#include <netinet/in.h>
10#include <endian.h>
1110
12struct timestamp {11struct timestamp {
13 uint8_t len;12 uint8_t len;
...@@ -191,6 +190,8 @@ struct ip_timestamp {...@@ -191,6 +190,8 @@ struct ip_timestamp {
191190
192#define IP_MSS 576191#define IP_MSS 576
193192
193#define __UAPI_DEF_IPHDR 0
194
194#ifdef __cplusplus195#ifdef __cplusplus
195}196}
196#endif197#endif
lib/libc/include/generic-musl/netinet/ip6.h-1
...@@ -7,7 +7,6 @@ extern "C" {...@@ -7,7 +7,6 @@ extern "C" {
77
8#include <stdint.h>8#include <stdint.h>
9#include <netinet/in.h>9#include <netinet/in.h>
10#include <endian.h>
1110
12struct ip6_hdr {11struct ip6_hdr {
13 union {12 union {
lib/libc/include/generic-musl/netinet/tcp.h+3-1
...@@ -38,6 +38,7 @@...@@ -38,6 +38,7 @@
38#define TCP_FASTOPEN_NO_COOKIE 3438#define TCP_FASTOPEN_NO_COOKIE 34
39#define TCP_ZEROCOPY_RECEIVE 3539#define TCP_ZEROCOPY_RECEIVE 35
40#define TCP_INQ 3640#define TCP_INQ 36
41#define TCP_TX_DELAY 37
4142
42#define TCP_CM_INQ TCP_INQ43#define TCP_CM_INQ TCP_INQ
4344
...@@ -97,7 +98,6 @@ enum {...@@ -97,7 +98,6 @@ enum {
97#include <sys/types.h>98#include <sys/types.h>
98#include <sys/socket.h>99#include <sys/socket.h>
99#include <stdint.h>100#include <stdint.h>
100#include <endian.h>
101101
102typedef uint32_t tcp_seq;102typedef uint32_t tcp_seq;
103103
...@@ -234,6 +234,8 @@ struct tcp_info {...@@ -234,6 +234,8 @@ struct tcp_info {
234 uint64_t tcpi_bytes_retrans;234 uint64_t tcpi_bytes_retrans;
235 uint32_t tcpi_dsack_dups;235 uint32_t tcpi_dsack_dups;
236 uint32_t tcpi_reord_seen;236 uint32_t tcpi_reord_seen;
237 uint32_t tcpi_rcv_ooopack;
238 uint32_t tcpi_snd_wnd;
237};239};
238240
239#define TCP_MD5SIG_MAXKEYLEN 80241#define TCP_MD5SIG_MAXKEYLEN 80
lib/libc/include/generic-musl/poll.h+6
...@@ -44,6 +44,12 @@ int poll (struct pollfd *, nfds_t, int);...@@ -44,6 +44,12 @@ int poll (struct pollfd *, nfds_t, int);
44int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);44int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);
45#endif45#endif
4646
47#if _REDIR_TIME64
48#ifdef _GNU_SOURCE
49__REDIR(ppoll, __ppoll_time64);
50#endif
51#endif
52
47#ifdef __cplusplus53#ifdef __cplusplus
48}54}
49#endif55#endif
lib/libc/include/generic-musl/pthread.h+10
...@@ -224,6 +224,16 @@ int pthread_tryjoin_np(pthread_t, void **);...@@ -224,6 +224,16 @@ int pthread_tryjoin_np(pthread_t, void **);
224int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);224int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);
225#endif225#endif
226226
227#if _REDIR_TIME64
228__REDIR(pthread_mutex_timedlock, __pthread_mutex_timedlock_time64);
229__REDIR(pthread_cond_timedwait, __pthread_cond_timedwait_time64);
230__REDIR(pthread_rwlock_timedrdlock, __pthread_rwlock_timedrdlock_time64);
231__REDIR(pthread_rwlock_timedwrlock, __pthread_rwlock_timedwrlock_time64);
232#ifdef _GNU_SOURCE
233__REDIR(pthread_timedjoin_np, __pthread_timedjoin_np_time64);
234#endif
235#endif
236
227#ifdef __cplusplus237#ifdef __cplusplus
228}238}
229#endif239#endif
lib/libc/include/generic-musl/sched.h+8
...@@ -19,10 +19,14 @@ extern "C" {...@@ -19,10 +19,14 @@ extern "C" {
19struct sched_param {19struct sched_param {
20 int sched_priority;20 int sched_priority;
21 int __reserved1;21 int __reserved1;
22#if _REDIR_TIME64
23 long __reserved2[4];
24#else
22 struct {25 struct {
23 time_t __reserved1;26 time_t __reserved1;
24 long __reserved2;27 long __reserved2;
25 } __reserved2[2];28 } __reserved2[2];
29#endif
26 int __reserved3;30 int __reserved3;
27};31};
2832
...@@ -133,6 +137,10 @@ __CPU_op_func_S(XOR, ^)...@@ -133,6 +137,10 @@ __CPU_op_func_S(XOR, ^)
133137
134#endif138#endif
135139
140#if _REDIR_TIME64
141__REDIR(sched_rr_get_interval, __sched_rr_get_interval_time64);
142#endif
143
136#ifdef __cplusplus144#ifdef __cplusplus
137}145}
138#endif146#endif
lib/libc/include/generic-musl/semaphore.h+4
...@@ -29,6 +29,10 @@ int sem_trywait(sem_t *);...@@ -29,6 +29,10 @@ int sem_trywait(sem_t *);
29int sem_unlink(const char *);29int sem_unlink(const char *);
30int sem_wait(sem_t *);30int sem_wait(sem_t *);
3131
32#if _REDIR_TIME64
33__REDIR(sem_timedwait, __sem_timedwait_time64);
34#endif
35
32#ifdef __cplusplus36#ifdef __cplusplus
33}37}
34#endif38#endif
lib/libc/include/generic-musl/signal.h+8
...@@ -271,6 +271,14 @@ typedef int sig_atomic_t;...@@ -271,6 +271,14 @@ typedef int sig_atomic_t;
271void (*signal(int, void (*)(int)))(int);271void (*signal(int, void (*)(int)))(int);
272int raise(int);272int raise(int);
273273
274#if _REDIR_TIME64
275#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
276 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
277 || defined(_BSD_SOURCE)
278__REDIR(sigtimedwait, __sigtimedwait_time64);
279#endif
280#endif
281
274#ifdef __cplusplus282#ifdef __cplusplus
275}283}
276#endif284#endif
lib/libc/include/generic-musl/sys/acct.h-1
...@@ -6,7 +6,6 @@ extern "C" {...@@ -6,7 +6,6 @@ extern "C" {
6#endif6#endif
77
8#include <features.h>8#include <features.h>
9#include <endian.h>
10#include <time.h>9#include <time.h>
11#include <stdint.h>10#include <stdint.h>
1211
lib/libc/include/generic-musl/sys/ioctl.h+1
...@@ -4,6 +4,7 @@...@@ -4,6 +4,7 @@
4extern "C" {4extern "C" {
5#endif5#endif
66
7#include <bits/alltypes.h>
7#include <bits/ioctl.h>8#include <bits/ioctl.h>
89
9#define N_TTY 010#define N_TTY 0
lib/libc/include/generic-musl/sys/mman.h+2
...@@ -92,6 +92,8 @@ extern "C" {...@@ -92,6 +92,8 @@ extern "C" {
92#define MADV_DODUMP 1792#define MADV_DODUMP 17
93#define MADV_WIPEONFORK 1893#define MADV_WIPEONFORK 18
94#define MADV_KEEPONFORK 1994#define MADV_KEEPONFORK 19
95#define MADV_COLD 20
96#define MADV_PAGEOUT 21
95#define MADV_HWPOISON 10097#define MADV_HWPOISON 100
96#define MADV_SOFT_OFFLINE 10198#define MADV_SOFT_OFFLINE 101
97#endif99#endif
lib/libc/include/generic-musl/sys/prctl.h+4
...@@ -154,6 +154,10 @@ struct prctl_mm_map {...@@ -154,6 +154,10 @@ struct prctl_mm_map {
154#define PR_PAC_APDBKEY (1UL << 3)154#define PR_PAC_APDBKEY (1UL << 3)
155#define PR_PAC_APGAKEY (1UL << 4)155#define PR_PAC_APGAKEY (1UL << 4)
156156
157#define PR_SET_TAGGED_ADDR_CTRL 55
158#define PR_GET_TAGGED_ADDR_CTRL 56
159#define PR_TAGGED_ADDR_ENABLE (1UL << 0)
160
157int prctl (int, ...);161int prctl (int, ...);
158162
159#ifdef __cplusplus163#ifdef __cplusplus
lib/libc/include/generic-musl/sys/procfs.h+3-4
...@@ -23,10 +23,9 @@ struct elf_prstatus {...@@ -23,10 +23,9 @@ struct elf_prstatus {
23 pid_t pr_ppid;23 pid_t pr_ppid;
24 pid_t pr_pgrp;24 pid_t pr_pgrp;
25 pid_t pr_sid;25 pid_t pr_sid;
26 struct timeval pr_utime;26 struct {
27 struct timeval pr_stime;27 long tv_sec, tv_usec;
28 struct timeval pr_cutime;28 } pr_utime, pr_stime, pr_cutime, pr_cstime;
29 struct timeval pr_cstime;
30 elf_gregset_t pr_reg;29 elf_gregset_t pr_reg;
31 int pr_fpvalid;30 int pr_fpvalid;
32};31};
lib/libc/include/generic-musl/sys/ptrace.h+29
...@@ -41,6 +41,7 @@ extern "C" {...@@ -41,6 +41,7 @@ extern "C" {
41#define PTRACE_SETSIGMASK 0x420b41#define PTRACE_SETSIGMASK 0x420b
42#define PTRACE_SECCOMP_GET_FILTER 0x420c42#define PTRACE_SECCOMP_GET_FILTER 0x420c
43#define PTRACE_SECCOMP_GET_METADATA 0x420d43#define PTRACE_SECCOMP_GET_METADATA 0x420d
44#define PTRACE_GET_SYSCALL_INFO 0x420e
4445
45#define PT_READ_I PTRACE_PEEKTEXT46#define PT_READ_I PTRACE_PEEKTEXT
46#define PT_READ_D PTRACE_PEEKDATA47#define PT_READ_D PTRACE_PEEKDATA
...@@ -88,6 +89,11 @@ extern "C" {...@@ -88,6 +89,11 @@ extern "C" {
8889
89#define PTRACE_PEEKSIGINFO_SHARED 190#define PTRACE_PEEKSIGINFO_SHARED 1
9091
92#define PTRACE_SYSCALL_INFO_NONE 0
93#define PTRACE_SYSCALL_INFO_ENTRY 1
94#define PTRACE_SYSCALL_INFO_EXIT 2
95#define PTRACE_SYSCALL_INFO_SECCOMP 3
96
91#include <bits/ptrace.h>97#include <bits/ptrace.h>
9298
93struct __ptrace_peeksiginfo_args {99struct __ptrace_peeksiginfo_args {
...@@ -101,6 +107,29 @@ struct __ptrace_seccomp_metadata {...@@ -101,6 +107,29 @@ struct __ptrace_seccomp_metadata {
101 uint64_t flags;107 uint64_t flags;
102};108};
103109
110struct __ptrace_syscall_info {
111 uint8_t op;
112 uint8_t __pad[3];
113 uint32_t arch;
114 uint64_t instruction_pointer;
115 uint64_t stack_pointer;
116 union {
117 struct {
118 uint64_t nr;
119 uint64_t args[6];
120 } entry;
121 struct {
122 int64_t rval;
123 uint8_t is_error;
124 } exit;
125 struct {
126 uint64_t nr;
127 uint64_t args[6];
128 uint32_t ret_data;
129 } seccomp;
130 };
131};
132
104long ptrace(int, ...);133long ptrace(int, ...);
105134
106#ifdef __cplusplus135#ifdef __cplusplus
lib/libc/include/generic-musl/sys/resource.h+6-1
...@@ -90,7 +90,8 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);...@@ -90,7 +90,8 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);
90#define RLIMIT_MSGQUEUE 1290#define RLIMIT_MSGQUEUE 12
91#define RLIMIT_NICE 1391#define RLIMIT_NICE 13
92#define RLIMIT_RTPRIO 1492#define RLIMIT_RTPRIO 14
93#define RLIMIT_NLIMITS 1593#define RLIMIT_RTTIME 15
94#define RLIMIT_NLIMITS 16
9495
95#define RLIM_NLIMITS RLIMIT_NLIMITS96#define RLIM_NLIMITS RLIMIT_NLIMITS
9697
...@@ -104,6 +105,10 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);...@@ -104,6 +105,10 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);
104#define rlim64_t rlim_t105#define rlim64_t rlim_t
105#endif106#endif
106107
108#if _REDIR_TIME64
109__REDIR(getrusage, __getrusage_time64);
110#endif
111
107#ifdef __cplusplus112#ifdef __cplusplus
108}113}
109#endif114#endif
lib/libc/include/generic-musl/sys/select.h+5
...@@ -35,6 +35,11 @@ int pselect (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, co...@@ -35,6 +35,11 @@ int pselect (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, co
35#define NFDBITS (8*(int)sizeof(long))35#define NFDBITS (8*(int)sizeof(long))
36#endif36#endif
3737
38#if _REDIR_TIME64
39__REDIR(select, __select_time64);
40__REDIR(pselect, __pselect_time64);
41#endif
42
38#ifdef __cplusplus43#ifdef __cplusplus
39}44}
40#endif45#endif
lib/libc/include/generic-musl/sys/sem.h+6-2
...@@ -25,8 +25,6 @@ extern "C" {...@@ -25,8 +25,6 @@ extern "C" {
25#define SETVAL 1625#define SETVAL 16
26#define SETALL 1726#define SETALL 17
2727
28#include <endian.h>
29
30#include <bits/sem.h>28#include <bits/sem.h>
3129
32#define _SEM_SEMUN_UNDEFINED 130#define _SEM_SEMUN_UNDEFINED 1
...@@ -62,6 +60,12 @@ int semop(int, struct sembuf *, size_t);...@@ -62,6 +60,12 @@ int semop(int, struct sembuf *, size_t);
62int semtimedop(int, struct sembuf *, size_t, const struct timespec *);60int semtimedop(int, struct sembuf *, size_t, const struct timespec *);
63#endif61#endif
6462
63#if _REDIR_TIME64
64#ifdef _GNU_SOURCE
65__REDIR(semtimedop, __semtimedop_time64);
66#endif
67#endif
68
65#ifdef __cplusplus69#ifdef __cplusplus
66}70}
67#endif71#endif
lib/libc/include/generic-musl/sys/socket.h+63-6
...@@ -19,6 +19,40 @@ extern "C" {...@@ -19,6 +19,40 @@ extern "C" {
1919
20#include <bits/socket.h>20#include <bits/socket.h>
2121
22struct msghdr {
23 void *msg_name;
24 socklen_t msg_namelen;
25 struct iovec *msg_iov;
26#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN
27 int __pad1;
28#endif
29 int msg_iovlen;
30#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN
31 int __pad1;
32#endif
33 void *msg_control;
34#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN
35 int __pad2;
36#endif
37 socklen_t msg_controllen;
38#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN
39 int __pad2;
40#endif
41 int msg_flags;
42};
43
44struct cmsghdr {
45#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN
46 int __pad1;
47#endif
48 socklen_t cmsg_len;
49#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN
50 int __pad1;
51#endif
52 int cmsg_level;
53 int cmsg_type;
54};
55
22#ifdef _GNU_SOURCE56#ifdef _GNU_SOURCE
23struct ucred {57struct ucred {
24 pid_t pid;58 pid_t pid;
...@@ -182,8 +216,6 @@ struct linger {...@@ -182,8 +216,6 @@ struct linger {
182#define SO_PEERCRED 17216#define SO_PEERCRED 17
183#define SO_RCVLOWAT 18217#define SO_RCVLOWAT 18
184#define SO_SNDLOWAT 19218#define SO_SNDLOWAT 19
185#define SO_RCVTIMEO 20
186#define SO_SNDTIMEO 21
187#define SO_ACCEPTCONN 30219#define SO_ACCEPTCONN 30
188#define SO_PEERSEC 31220#define SO_PEERSEC 31
189#define SO_SNDBUFFORCE 32221#define SO_SNDBUFFORCE 32
...@@ -192,6 +224,28 @@ struct linger {...@@ -192,6 +224,28 @@ struct linger {
192#define SO_DOMAIN 39224#define SO_DOMAIN 39
193#endif225#endif
194226
227#ifndef SO_RCVTIMEO
228#if __LONG_MAX == 0x7fffffff
229#define SO_RCVTIMEO 66
230#define SO_SNDTIMEO 67
231#else
232#define SO_RCVTIMEO 20
233#define SO_SNDTIMEO 21
234#endif
235#endif
236
237#ifndef SO_TIMESTAMP
238#if __LONG_MAX == 0x7fffffff
239#define SO_TIMESTAMP 63
240#define SO_TIMESTAMPNS 64
241#define SO_TIMESTAMPING 65
242#else
243#define SO_TIMESTAMP 29
244#define SO_TIMESTAMPNS 35
245#define SO_TIMESTAMPING 37
246#endif
247#endif
248
195#define SO_SECURITY_AUTHENTICATION 22249#define SO_SECURITY_AUTHENTICATION 22
196#define SO_SECURITY_ENCRYPTION_TRANSPORT 23250#define SO_SECURITY_ENCRYPTION_TRANSPORT 23
197#define SO_SECURITY_ENCRYPTION_NETWORK 24251#define SO_SECURITY_ENCRYPTION_NETWORK 24
...@@ -203,14 +257,10 @@ struct linger {...@@ -203,14 +257,10 @@ struct linger {
203#define SO_GET_FILTER SO_ATTACH_FILTER257#define SO_GET_FILTER SO_ATTACH_FILTER
204258
205#define SO_PEERNAME 28259#define SO_PEERNAME 28
206#define SO_TIMESTAMP 29
207#define SCM_TIMESTAMP SO_TIMESTAMP260#define SCM_TIMESTAMP SO_TIMESTAMP
208
209#define SO_PASSSEC 34261#define SO_PASSSEC 34
210#define SO_TIMESTAMPNS 35
211#define SCM_TIMESTAMPNS SO_TIMESTAMPNS262#define SCM_TIMESTAMPNS SO_TIMESTAMPNS
212#define SO_MARK 36263#define SO_MARK 36
213#define SO_TIMESTAMPING 37
214#define SCM_TIMESTAMPING SO_TIMESTAMPING264#define SCM_TIMESTAMPING SO_TIMESTAMPING
215#define SO_RXQ_OVFL 40265#define SO_RXQ_OVFL 40
216#define SO_WIFI_STATUS 41266#define SO_WIFI_STATUS 41
...@@ -238,6 +288,7 @@ struct linger {...@@ -238,6 +288,7 @@ struct linger {
238#define SO_TXTIME 61288#define SO_TXTIME 61
239#define SCM_TXTIME SO_TXTIME289#define SCM_TXTIME SO_TXTIME
240#define SO_BINDTOIFINDEX 62290#define SO_BINDTOIFINDEX 62
291#define SO_DETACH_REUSEPORT_BPF 68
241292
242#ifndef SOL_SOCKET293#ifndef SOL_SOCKET
243#define SOL_SOCKET 1294#define SOL_SOCKET 1
...@@ -350,6 +401,12 @@ int setsockopt (int, int, int, const void *, socklen_t);...@@ -350,6 +401,12 @@ int setsockopt (int, int, int, const void *, socklen_t);
350401
351int sockatmark (int);402int sockatmark (int);
352403
404#if _REDIR_TIME64
405#ifdef _GNU_SOURCE
406__REDIR(recvmmsg, __recvmmsg_time64);
407#endif
408#endif
409
353#ifdef __cplusplus410#ifdef __cplusplus
354}411}
355#endif412#endif
lib/libc/include/generic-musl/sys/stat.h+9
...@@ -110,6 +110,15 @@ int lchmod(const char *, mode_t);...@@ -110,6 +110,15 @@ int lchmod(const char *, mode_t);
110#define off64_t off_t110#define off64_t off_t
111#endif111#endif
112112
113#if _REDIR_TIME64
114__REDIR(stat, __stat_time64);
115__REDIR(fstat, __fstat_time64);
116__REDIR(lstat, __lstat_time64);
117__REDIR(fstatat, __fstatat_time64);
118__REDIR(futimens, __futimens_time64);
119__REDIR(utimensat, __utimensat_time64);
120#endif
121
113#ifdef __cplusplus122#ifdef __cplusplus
114}123}
115#endif124#endif
lib/libc/include/generic-musl/sys/statvfs.h-2
...@@ -11,8 +11,6 @@ extern "C" {...@@ -11,8 +11,6 @@ extern "C" {
11#define __NEED_fsfilcnt_t11#define __NEED_fsfilcnt_t
12#include <bits/alltypes.h>12#include <bits/alltypes.h>
1313
14#include <endian.h>
15
16struct statvfs {14struct statvfs {
17 unsigned long f_bsize, f_frsize;15 unsigned long f_bsize, f_frsize;
18 fsblkcnt_t f_blocks, f_bfree, f_bavail;16 fsblkcnt_t f_blocks, f_bfree, f_bavail;
lib/libc/include/generic-musl/sys/time.h+14
...@@ -56,6 +56,20 @@ int adjtime (const struct timeval *, struct timeval *);...@@ -56,6 +56,20 @@ int adjtime (const struct timeval *, struct timeval *);
56 (void)0 )56 (void)0 )
57#endif57#endif
5858
59#if _REDIR_TIME64
60__REDIR(gettimeofday, __gettimeofday_time64);
61__REDIR(getitimer, __getitimer_time64);
62__REDIR(setitimer, __setitimer_time64);
63__REDIR(utimes, __utimes_time64);
64#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
65__REDIR(futimes, __futimes_time64);
66__REDIR(futimesat, __futimesat_time64);
67__REDIR(lutimes, __lutimes_time64);
68__REDIR(settimeofday, __settimeofday_time64);
69__REDIR(adjtime, __adjtime64);
70#endif
71#endif
72
59#ifdef __cplusplus73#ifdef __cplusplus
60}74}
61#endif75#endif
lib/libc/include/generic-musl/sys/timeb.h+6
...@@ -4,6 +4,8 @@...@@ -4,6 +4,8 @@
4extern "C" {4extern "C" {
5#endif5#endif
66
7#include <features.h>
8
7#define __NEED_time_t9#define __NEED_time_t
810
9#include <bits/alltypes.h>11#include <bits/alltypes.h>
...@@ -16,6 +18,10 @@ struct timeb {...@@ -16,6 +18,10 @@ struct timeb {
1618
17int ftime(struct timeb *);19int ftime(struct timeb *);
1820
21#if _REDIR_TIME64
22__REDIR(ftime, __ftime64);
23#endif
24
19#ifdef __cplusplus25#ifdef __cplusplus
20}26}
21#endif27#endif
lib/libc/include/generic-musl/sys/timerfd.h+5
...@@ -20,6 +20,11 @@ int timerfd_create(int, int);...@@ -20,6 +20,11 @@ int timerfd_create(int, int);
20int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *);20int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *);
21int timerfd_gettime(int, struct itimerspec *);21int timerfd_gettime(int, struct itimerspec *);
2222
23#if _REDIR_TIME64
24__REDIR(timerfd_settime, __timerfd_settime64);
25__REDIR(timerfd_gettime, __timerfd_gettime64);
26#endif
27
23#ifdef __cplusplus28#ifdef __cplusplus
24}29}
25#endif30#endif
lib/libc/include/generic-musl/sys/timex.h+5
...@@ -91,6 +91,11 @@ struct timex {...@@ -91,6 +91,11 @@ struct timex {
91int adjtimex(struct timex *);91int adjtimex(struct timex *);
92int clock_adjtime(clockid_t, struct timex *);92int clock_adjtime(clockid_t, struct timex *);
9393
94#if _REDIR_TIME64
95__REDIR(adjtimex, __adjtimex_time64);
96__REDIR(clock_adjtime, __clock_adjtime64);
97#endif
98
94#ifdef __cplusplus99#ifdef __cplusplus
95}100}
96#endif101#endif
lib/libc/include/generic-musl/sys/ttydefaults.h+1-6
...@@ -6,16 +6,11 @@...@@ -6,16 +6,11 @@
6#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL)6#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL)
7#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL)7#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL)
8#define TTYDEF_SPEED (B9600)8#define TTYDEF_SPEED (B9600)
9#define CTRL(x) (x&037)9#define CTRL(x) ((x)&037)
10#define CEOF CTRL('d')10#define CEOF CTRL('d')
1111
12#ifdef _POSIX_VDISABLE
13#define CEOL _POSIX_VDISABLE
14#define CSTATUS _POSIX_VDISABLE
15#else
16#define CEOL '\0'12#define CEOL '\0'
17#define CSTATUS '\0'13#define CSTATUS '\0'
18#endif
1914
20#define CERASE 017715#define CERASE 0177
21#define CINTR CTRL('c')16#define CINTR CTRL('c')
lib/libc/include/generic-musl/sys/wait.h+9-1
...@@ -13,7 +13,8 @@ extern "C" {...@@ -13,7 +13,8 @@ extern "C" {
13typedef enum {13typedef enum {
14 P_ALL = 0,14 P_ALL = 0,
15 P_PID = 1,15 P_PID = 1,
16 P_PGID = 216 P_PGID = 2,
17 P_PIDFD = 3
17} idtype_t;18} idtype_t;
1819
19pid_t wait (int *);20pid_t wait (int *);
...@@ -53,6 +54,13 @@ pid_t wait4 (pid_t, int *, int, struct rusage *);...@@ -53,6 +54,13 @@ pid_t wait4 (pid_t, int *, int, struct rusage *);
53#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu)54#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu)
54#define WIFCONTINUED(s) ((s) == 0xffff)55#define WIFCONTINUED(s) ((s) == 0xffff)
5556
57#if _REDIR_TIME64
58#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
59__REDIR(wait3, __wait3_time64);
60__REDIR(wait4, __wait4_time64);
61#endif
62#endif
63
56#ifdef __cplusplus64#ifdef __cplusplus
57}65}
58#endif66#endif
lib/libc/include/generic-musl/threads.h+6
...@@ -80,6 +80,12 @@ void tss_delete(tss_t);...@@ -80,6 +80,12 @@ void tss_delete(tss_t);
80int tss_set(tss_t, void *);80int tss_set(tss_t, void *);
81void *tss_get(tss_t);81void *tss_get(tss_t);
8282
83#if _REDIR_TIME64
84__REDIR(thrd_sleep, __thrd_sleep_time64);
85__REDIR(mtx_timedlock, __mtx_timedlock_time64);
86__REDIR(cnd_timedwait, __cnd_timedwait_time64);
87#endif
88
83#ifdef __cplusplus89#ifdef __cplusplus
84}90}
85#endif91#endif
lib/libc/include/generic-musl/time.h+28
...@@ -130,6 +130,34 @@ int stime(const time_t *);...@@ -130,6 +130,34 @@ int stime(const time_t *);
130time_t timegm(struct tm *);130time_t timegm(struct tm *);
131#endif131#endif
132132
133#if _REDIR_TIME64
134__REDIR(time, __time64);
135__REDIR(difftime, __difftime64);
136__REDIR(mktime, __mktime64);
137__REDIR(gmtime, __gmtime64);
138__REDIR(localtime, __localtime64);
139__REDIR(ctime, __ctime64);
140__REDIR(timespec_get, __timespec_get_time64);
141#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
142 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
143 || defined(_BSD_SOURCE)
144__REDIR(gmtime_r, __gmtime64_r);
145__REDIR(localtime_r, __localtime64_r);
146__REDIR(ctime_r, __ctime64_r);
147__REDIR(nanosleep, __nanosleep_time64);
148__REDIR(clock_getres, __clock_getres_time64);
149__REDIR(clock_gettime, __clock_gettime64);
150__REDIR(clock_settime, __clock_settime64);
151__REDIR(clock_nanosleep, __clock_nanosleep_time64);
152__REDIR(timer_settime, __timer_settime64);
153__REDIR(timer_gettime, __timer_gettime64);
154#endif
155#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
156__REDIR(stime, __stime64);
157__REDIR(timegm, __timegm_time64);
158#endif
159#endif
160
133#ifdef __cplusplus161#ifdef __cplusplus
134}162}
135#endif163#endif
lib/libc/include/generic-musl/utime.h+6
...@@ -5,6 +5,8 @@...@@ -5,6 +5,8 @@
5extern "C" {5extern "C" {
6#endif6#endif
77
8#include <features.h>
9
8#define __NEED_time_t10#define __NEED_time_t
911
10#include <bits/alltypes.h>12#include <bits/alltypes.h>
...@@ -16,6 +18,10 @@ struct utimbuf {...@@ -16,6 +18,10 @@ struct utimbuf {
1618
17int utime (const char *, const struct utimbuf *);19int utime (const char *, const struct utimbuf *);
1820
21#if _REDIR_TIME64
22__REDIR(utime, __utime64);
23#endif
24
19#ifdef __cplusplus25#ifdef __cplusplus
20}26}
21#endif27#endif
lib/libc/include/generic-musl/utmpx.h+6-1
...@@ -16,6 +16,7 @@ extern "C" {...@@ -16,6 +16,7 @@ extern "C" {
1616
17struct utmpx {17struct utmpx {
18 short ut_type;18 short ut_type;
19 short __ut_pad1;
19 pid_t ut_pid;20 pid_t ut_pid;
20 char ut_line[32];21 char ut_line[32];
21 char ut_id[4];22 char ut_id[4];
...@@ -25,7 +26,11 @@ struct utmpx {...@@ -25,7 +26,11 @@ struct utmpx {
25 short __e_termination;26 short __e_termination;
26 short __e_exit;27 short __e_exit;
27 } ut_exit;28 } ut_exit;
28 long ut_session;29#if __BYTE_ORDER == 1234
30 int ut_session, __ut_pad2;
31#else
32 int __ut_pad2, ut_session;
33#endif
29 struct timeval ut_tv;34 struct timeval ut_tv;
30 unsigned ut_addr_v6[4];35 unsigned ut_addr_v6[4];
31 char __unused[20];36 char __unused[20];
lib/libc/include/i386-linux-musl/bits/alltypes.h+64-70
...@@ -1,30 +1,10 @@...@@ -1,30 +1,10 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5#if __GNUC__ >= 36#define __BYTE_ORDER 1234
6#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)7#define __LONG_MAX 0x7fffffffL
7typedef __builtin_va_list va_list;
8#define __DEFINED_va_list
9#endif
10
11#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
12typedef __builtin_va_list __isoc_va_list;
13#define __DEFINED___isoc_va_list
14#endif
15
16#else
17#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
18typedef struct __va_list * va_list;
19#define __DEFINED_va_list
20#endif
21
22#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
23typedef struct __va_list * __isoc_va_list;
24#define __DEFINED___isoc_va_list
25#endif
26
27#endif
288
29#ifndef __cplusplus9#ifndef __cplusplus
30#ifdef __WCHAR_TYPE__10#ifdef __WCHAR_TYPE__
...@@ -85,52 +65,9 @@ typedef struct { alignas(8) long long __ll; long double __ld; } max_align_t;...@@ -85,52 +65,9 @@ typedef struct { alignas(8) long long __ll; long double __ld; } max_align_t;
85#endif65#endif
8666
87#endif67#endif
8868#define __LITTLE_ENDIAN 1234
89#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)69#define __BIG_ENDIAN 4321
90typedef long time_t;70#define __USE_TIME_BITS64 1
91#define __DEFINED_time_t
92#endif
93
94#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
95typedef long suseconds_t;
96#define __DEFINED_suseconds_t
97#endif
98
99
100#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
101typedef struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
102#define __DEFINED_pthread_attr_t
103#endif
104
105#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
106typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
107#define __DEFINED_pthread_mutex_t
108#endif
109
110#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
111typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
112#define __DEFINED_mtx_t
113#endif
114
115#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
116typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
117#define __DEFINED_pthread_cond_t
118#endif
119
120#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
121typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
122#define __DEFINED_cnd_t
123#endif
124
125#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
126typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
127#define __DEFINED_pthread_rwlock_t
128#endif
129
130#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
131typedef struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
132#define __DEFINED_pthread_barrier_t
133#endif
13471
135#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)72#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
136typedef unsigned _Addr size_t;73typedef unsigned _Addr size_t;
...@@ -167,6 +104,16 @@ typedef _Reg register_t;...@@ -167,6 +104,16 @@ typedef _Reg register_t;
167#define __DEFINED_register_t104#define __DEFINED_register_t
168#endif105#endif
169106
107#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
108typedef _Int64 time_t;
109#define __DEFINED_time_t
110#endif
111
112#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
113typedef _Int64 suseconds_t;
114#define __DEFINED_suseconds_t
115#endif
116
170117
171#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)118#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
172typedef signed char int8_t;119typedef signed char int8_t;
...@@ -302,7 +249,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -302,7 +249,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
302#endif249#endif
303250
304#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)251#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
305struct timespec { time_t tv_sec; long tv_nsec; };252struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
306#define __DEFINED_struct_timespec253#define __DEFINED_struct_timespec
307#endif254#endif
308255
...@@ -398,6 +345,17 @@ typedef struct _IO_FILE FILE;...@@ -398,6 +345,17 @@ typedef struct _IO_FILE FILE;
398#endif345#endif
399346
400347
348#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
349typedef __builtin_va_list va_list;
350#define __DEFINED_va_list
351#endif
352
353#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
354typedef __builtin_va_list __isoc_va_list;
355#define __DEFINED___isoc_va_list
356#endif
357
358
401#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)359#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
402typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;360typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
403#define __DEFINED_mbstate_t361#define __DEFINED_mbstate_t
...@@ -433,6 +391,42 @@ typedef unsigned short sa_family_t;...@@ -433,6 +391,42 @@ typedef unsigned short sa_family_t;
433#endif391#endif
434392
435393
394#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
395typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
396#define __DEFINED_pthread_attr_t
397#endif
398
399#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
400typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
401#define __DEFINED_pthread_mutex_t
402#endif
403
404#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
405typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
406#define __DEFINED_mtx_t
407#endif
408
409#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
410typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
411#define __DEFINED_pthread_cond_t
412#endif
413
414#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
415typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
416#define __DEFINED_cnd_t
417#endif
418
419#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
420typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
421#define __DEFINED_pthread_rwlock_t
422#endif
423
424#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
425typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
426#define __DEFINED_pthread_barrier_t
427#endif
428
429
436#undef _Addr430#undef _Addr
437#undef _Int64431#undef _Int64
438#undef _Reg432#undef _Reg
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/ipcstat.h created+1
...@@ -0,0 +1 @@
1#define IPC_STAT 0x102
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/limits.h+1-8
...@@ -1,8 +1 @@...@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define PAGESIZE 4096
4#define LONG_BIT 32
5#endif
6
7#define LONG_MAX 0x7fffffffL
8#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
1#define PAGESIZE 4096
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/msg.h+9-6
...@@ -1,15 +1,18 @@...@@ -1,15 +1,18 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3 time_t msg_stime;3 unsigned long __msg_stime_lo;
4 int __unused1;4 unsigned long __msg_stime_hi;
5 time_t msg_rtime;5 unsigned long __msg_rtime_lo;
6 int __unused2;6 unsigned long __msg_rtime_hi;
7 time_t msg_ctime;7 unsigned long __msg_ctime_lo;
8 int __unused3;8 unsigned long __msg_ctime_hi;
9 unsigned long msg_cbytes;9 unsigned long msg_cbytes;
10 msgqnum_t msg_qnum;10 msgqnum_t msg_qnum;
11 msglen_t msg_qbytes;11 msglen_t msg_qbytes;
12 pid_t msg_lspid;12 pid_t msg_lspid;
13 pid_t msg_lrpid;13 pid_t msg_lrpid;
14 unsigned long __unused[2];14 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
15};18};
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/sem.h+6-4
...@@ -1,11 +1,13 @@...@@ -1,11 +1,13 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 time_t sem_otime;3 unsigned long __sem_otime_lo;
4 long __unused1;4 unsigned long __sem_otime_hi;
5 time_t sem_ctime;5 unsigned long __sem_ctime_lo;
6 long __unused2;6 unsigned long __sem_ctime_hi;
7 unsigned short sem_nsems;7 unsigned short sem_nsems;
8 char __sem_nsems_pad[sizeof(long)-sizeof(short)];8 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
9 long __unused3;9 long __unused3;
10 long __unused4;10 long __unused4;
11 time_t sem_otime;
12 time_t sem_ctime;
11};13};
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/shm.h+10-6
...@@ -3,17 +3,21 @@...@@ -3,17 +3,21 @@
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 size_t shm_segsz;5 size_t shm_segsz;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 int __unused1;7 unsigned long __shm_atime_hi;
8 time_t shm_dtime;8 unsigned long __shm_dtime_lo;
9 int __unused2;9 unsigned long __shm_dtime_hi;
10 time_t shm_ctime;10 unsigned long __shm_ctime_lo;
11 int __unused3;11 unsigned long __shm_ctime_hi;
12 pid_t shm_cpid;12 pid_t shm_cpid;
13 pid_t shm_lpid;13 pid_t shm_lpid;
14 unsigned long shm_nattch;14 unsigned long shm_nattch;
15 unsigned long __pad1;15 unsigned long __pad1;
16 unsigned long __pad2;16 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
17};21};
1822
19struct shminfo {23struct shminfo {
lib/libc/include/i386-linux-musl/bits/stat.h+5-1
...@@ -14,8 +14,12 @@ struct stat {...@@ -14,8 +14,12 @@ struct stat {
14 off_t st_size;14 off_t st_size;
15 blksize_t st_blksize;15 blksize_t st_blksize;
16 blkcnt_t st_blocks;16 blkcnt_t st_blocks;
17 struct {
18 long tv_sec;
19 long tv_nsec;
20 } __st_atim32, __st_mtim32, __st_ctim32;
21 ino_t st_ino;
17 struct timespec st_atim;22 struct timespec st_atim;
18 struct timespec st_mtim;23 struct timespec st_mtim;
19 struct timespec st_ctim;24 struct timespec st_ctim;
20 ino_t st_ino;
21};25};
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/syscall.h+25-21
...@@ -76,8 +76,8 @@...@@ -76,8 +76,8 @@
76#define __NR_setrlimit 7576#define __NR_setrlimit 75
77#define __NR_getrlimit 76 /* Back compatible 2Gig limited rlimit */77#define __NR_getrlimit 76 /* Back compatible 2Gig limited rlimit */
78#define __NR_getrusage 7778#define __NR_getrusage 77
79#define __NR_gettimeofday 7879#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday 7980#define __NR_settimeofday_time32 79
81#define __NR_getgroups 8081#define __NR_getgroups 80
82#define __NR_setgroups 8182#define __NR_setgroups 81
83#define __NR_select 8283#define __NR_select 82
...@@ -257,14 +257,14 @@...@@ -257,14 +257,14 @@
257#define __NR_remap_file_pages 257257#define __NR_remap_file_pages 257
258#define __NR_set_tid_address 258258#define __NR_set_tid_address 258
259#define __NR_timer_create 259259#define __NR_timer_create 259
260#define __NR_timer_settime (__NR_timer_create+1)260#define __NR_timer_settime32 (__NR_timer_create+1)
261#define __NR_timer_gettime (__NR_timer_create+2)261#define __NR_timer_gettime32 (__NR_timer_create+2)
262#define __NR_timer_getoverrun (__NR_timer_create+3)262#define __NR_timer_getoverrun (__NR_timer_create+3)
263#define __NR_timer_delete (__NR_timer_create+4)263#define __NR_timer_delete (__NR_timer_create+4)
264#define __NR_clock_settime (__NR_timer_create+5)264#define __NR_clock_settime32 (__NR_timer_create+5)
265#define __NR_clock_gettime (__NR_timer_create+6)265#define __NR_clock_gettime32 (__NR_timer_create+6)
266#define __NR_clock_getres (__NR_timer_create+7)266#define __NR_clock_getres_time32 (__NR_timer_create+7)
267#define __NR_clock_nanosleep (__NR_timer_create+8)267#define __NR_clock_nanosleep_time32 (__NR_timer_create+8)
268#define __NR_statfs64 268268#define __NR_statfs64 268
269#define __NR_fstatfs64 269269#define __NR_fstatfs64 269
270#define __NR_tgkill 270270#define __NR_tgkill 270
...@@ -322,8 +322,8 @@...@@ -322,8 +322,8 @@
322#define __NR_timerfd_create 322322#define __NR_timerfd_create 322
323#define __NR_eventfd 323323#define __NR_eventfd 323
324#define __NR_fallocate 324324#define __NR_fallocate 324
325#define __NR_timerfd_settime 325325#define __NR_timerfd_settime32 325
326#define __NR_timerfd_gettime 326326#define __NR_timerfd_gettime32 326
327#define __NR_signalfd4 327327#define __NR_signalfd4 327
328#define __NR_eventfd2 328328#define __NR_eventfd2 328
329#define __NR_epoll_create1 329329#define __NR_epoll_create1 329
...@@ -424,6 +424,8 @@...@@ -424,6 +424,8 @@
424#define __NR_fsconfig 431424#define __NR_fsconfig 431
425#define __NR_fsmount 432425#define __NR_fsmount 432
426#define __NR_fspick 433426#define __NR_fspick 433
427#define __NR_pidfd_open 434
428#define __NR_clone3 435
427429
428#define SYS_restart_syscall 0430#define SYS_restart_syscall 0
429#define SYS_exit 1431#define SYS_exit 1
...@@ -503,8 +505,8 @@...@@ -503,8 +505,8 @@
503#define SYS_setrlimit 75505#define SYS_setrlimit 75
504#define SYS_getrlimit 76 /* Back compatible 2Gig limited rlimit */506#define SYS_getrlimit 76 /* Back compatible 2Gig limited rlimit */
505#define SYS_getrusage 77507#define SYS_getrusage 77
506#define SYS_gettimeofday 78508#define SYS_gettimeofday_time32 78
507#define SYS_settimeofday 79509#define SYS_settimeofday_time32 79
508#define SYS_getgroups 80510#define SYS_getgroups 80
509#define SYS_setgroups 81511#define SYS_setgroups 81
510#define SYS_select 82512#define SYS_select 82
...@@ -682,14 +684,14 @@...@@ -682,14 +684,14 @@
682#define SYS_remap_file_pages 257684#define SYS_remap_file_pages 257
683#define SYS_set_tid_address 258685#define SYS_set_tid_address 258
684#define SYS_timer_create 259686#define SYS_timer_create 259
685#define SYS_timer_settime (__NR_timer_create+1)687#define SYS_timer_settime32 (__NR_timer_create+1)
686#define SYS_timer_gettime (__NR_timer_create+2)688#define SYS_timer_gettime32 (__NR_timer_create+2)
687#define SYS_timer_getoverrun (__NR_timer_create+3)689#define SYS_timer_getoverrun (__NR_timer_create+3)
688#define SYS_timer_delete (__NR_timer_create+4)690#define SYS_timer_delete (__NR_timer_create+4)
689#define SYS_clock_settime (__NR_timer_create+5)691#define SYS_clock_settime32 (__NR_timer_create+5)
690#define SYS_clock_gettime (__NR_timer_create+6)692#define SYS_clock_gettime32 (__NR_timer_create+6)
691#define SYS_clock_getres (__NR_timer_create+7)693#define SYS_clock_getres_time32 (__NR_timer_create+7)
692#define SYS_clock_nanosleep (__NR_timer_create+8)694#define SYS_clock_nanosleep_time32 (__NR_timer_create+8)
693#define SYS_statfs64 268695#define SYS_statfs64 268
694#define SYS_fstatfs64 269696#define SYS_fstatfs64 269
695#define SYS_tgkill 270697#define SYS_tgkill 270
...@@ -747,8 +749,8 @@...@@ -747,8 +749,8 @@
747#define SYS_timerfd_create 322749#define SYS_timerfd_create 322
748#define SYS_eventfd 323750#define SYS_eventfd 323
749#define SYS_fallocate 324751#define SYS_fallocate 324
750#define SYS_timerfd_settime 325752#define SYS_timerfd_settime32 325
751#define SYS_timerfd_gettime 326753#define SYS_timerfd_gettime32 326
752#define SYS_signalfd4 327754#define SYS_signalfd4 327
753#define SYS_eventfd2 328755#define SYS_eventfd2 328
754#define SYS_epoll_create1 329756#define SYS_epoll_create1 329
...@@ -848,4 +850,6 @@...@@ -848,4 +850,6 @@
848#define SYS_fsopen 430850#define SYS_fsopen 430
849#define SYS_fsconfig 431851#define SYS_fsconfig 431
850#define SYS_fsmount 432852#define SYS_fsmount 432
851#define SYS_fspick 433
\ No newline at end of file
853#define SYS_fspick 433
854#define SYS_pidfd_open 434
855#define SYS_clone3 435
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/alltypes.h+67-55
...@@ -1,17 +1,15 @@...@@ -1,17 +1,15 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)6#if _MIPSEL || __MIPSEL || __MIPSEL__
6typedef __builtin_va_list va_list;7#define __BYTE_ORDER 1234
7#define __DEFINED_va_list8#else
8#endif9#define __BYTE_ORDER 4321
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif10#endif
1411
12#define __LONG_MAX 0x7fffffffL
1513
16#ifndef __cplusplus14#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)15#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -37,52 +35,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -37,52 +35,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
37#define __DEFINED_max_align_t35#define __DEFINED_max_align_t
38#endif36#endif
3937
4038#define __LITTLE_ENDIAN 1234
41#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)39#define __BIG_ENDIAN 4321
42typedef long time_t;40#define __USE_TIME_BITS64 1
43#define __DEFINED_time_t
44#endif
45
46#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
47typedef long suseconds_t;
48#define __DEFINED_suseconds_t
49#endif
50
51
52#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
53typedef struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
54#define __DEFINED_pthread_attr_t
55#endif
56
57#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
58typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
59#define __DEFINED_pthread_mutex_t
60#endif
61
62#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
63typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
64#define __DEFINED_mtx_t
65#endif
66
67#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
68typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
69#define __DEFINED_pthread_cond_t
70#endif
71
72#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
73typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
74#define __DEFINED_cnd_t
75#endif
76
77#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
78typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
79#define __DEFINED_pthread_rwlock_t
80#endif
81
82#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
83typedef struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
84#define __DEFINED_pthread_barrier_t
85#endif
8641
87#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)42#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
88typedef unsigned _Addr size_t;43typedef unsigned _Addr size_t;
...@@ -119,6 +74,16 @@ typedef _Reg register_t;...@@ -119,6 +74,16 @@ typedef _Reg register_t;
119#define __DEFINED_register_t74#define __DEFINED_register_t
120#endif75#endif
12176
77#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
78typedef _Int64 time_t;
79#define __DEFINED_time_t
80#endif
81
82#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
83typedef _Int64 suseconds_t;
84#define __DEFINED_suseconds_t
85#endif
86
12287
123#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)88#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
124typedef signed char int8_t;89typedef signed char int8_t;
...@@ -254,7 +219,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -254,7 +219,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254#endif219#endif
255220
256#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)221#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
257struct timespec { time_t tv_sec; long tv_nsec; };222struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
258#define __DEFINED_struct_timespec223#define __DEFINED_struct_timespec
259#endif224#endif
260225
...@@ -350,6 +315,17 @@ typedef struct _IO_FILE FILE;...@@ -350,6 +315,17 @@ typedef struct _IO_FILE FILE;
350#endif315#endif
351316
352317
318#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
319typedef __builtin_va_list va_list;
320#define __DEFINED_va_list
321#endif
322
323#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
324typedef __builtin_va_list __isoc_va_list;
325#define __DEFINED___isoc_va_list
326#endif
327
328
353#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)329#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;330typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355#define __DEFINED_mbstate_t331#define __DEFINED_mbstate_t
...@@ -385,6 +361,42 @@ typedef unsigned short sa_family_t;...@@ -385,6 +361,42 @@ typedef unsigned short sa_family_t;
385#endif361#endif
386362
387363
364#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
365typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
366#define __DEFINED_pthread_attr_t
367#endif
368
369#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
370typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
371#define __DEFINED_pthread_mutex_t
372#endif
373
374#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
375typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
376#define __DEFINED_mtx_t
377#endif
378
379#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
380typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
381#define __DEFINED_pthread_cond_t
382#endif
383
384#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
385typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
386#define __DEFINED_cnd_t
387#endif
388
389#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
390typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
391#define __DEFINED_pthread_rwlock_t
392#endif
393
394#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
395typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
396#define __DEFINED_pthread_barrier_t
397#endif
398
399
388#undef _Addr400#undef _Addr
389#undef _Int64401#undef _Int64
390#undef _Reg402#undef _Reg
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if _MIPSEL || __MIPSEL || __MIPSEL__
2#define __BYTE_ORDER __LITTLE_ENDIAN
3#else
4#define __BYTE_ORDER __BIG_ENDIAN
5#endif
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/hwcap.h+12-1
...@@ -1,3 +1,14 @@...@@ -1,3 +1,14 @@
1#define HWCAP_MIPS_R6 (1 << 0)1#define HWCAP_MIPS_R6 (1 << 0)
2#define HWCAP_MIPS_MSA (1 << 1)2#define HWCAP_MIPS_MSA (1 << 1)
3#define HWCAP_MIPS_CRC32 (1 << 2)
\ No newline at end of file
3#define HWCAP_MIPS_CRC32 (1 << 2)
4#define HWCAP_MIPS_MIPS16 (1 << 3)
5#define HWCAP_MIPS_MDMX (1 << 4)
6#define HWCAP_MIPS_MIPS3D (1 << 5)
7#define HWCAP_MIPS_SMARTMIPS (1 << 6)
8#define HWCAP_MIPS_DSP (1 << 7)
9#define HWCAP_MIPS_DSP2 (1 << 8)
10#define HWCAP_MIPS_DSP3 (1 << 9)
11#define HWCAP_MIPS_MIPS16E2 (1 << 10)
12#define HWCAP_LOONGSON_MMI (1 << 11)
13#define HWCAP_LOONGSON_EXT (1 << 12)
14#define HWCAP_LOONGSON_EXT2 (1 << 13)
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/ioctl.h+2-2
...@@ -110,5 +110,5 @@...@@ -110,5 +110,5 @@
110#define SIOCATMARK _IOR('s', 7, int)110#define SIOCATMARK _IOR('s', 7, int)
111#define SIOCSPGRP _IOW('s', 8, pid_t)111#define SIOCSPGRP _IOW('s', 8, pid_t)
112#define SIOCGPGRP _IOR('s', 9, pid_t)112#define SIOCGPGRP _IOR('s', 9, pid_t)
113#define SIOCGSTAMP 0x8906
114#define SIOCGSTAMPNS 0x8907
\ No newline at end of file
113#define SIOCGSTAMP _IOR(0x89, 6, char[16])
114#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/ipcstat.h created+1
...@@ -0,0 +1 @@
1#define IPC_STAT 0x102
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 32
4#endif
5
6#define LONG_MAX 0x7fffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/msg.h+15-12
...@@ -1,19 +1,19 @@...@@ -1,19 +1,19 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3#if _MIPSEL || __MIPSEL || __MIPSEL__3#if _MIPSEL || __MIPSEL || __MIPSEL__
4 time_t msg_stime;4 unsigned long __msg_stime_lo;
5 int __unused1;5 unsigned long __msg_stime_hi;
6 time_t msg_rtime;6 unsigned long __msg_rtime_lo;
7 int __unused2;7 unsigned long __msg_rtime_hi;
8 time_t msg_ctime;8 unsigned long __msg_ctime_lo;
9 int __unused3;9 unsigned long __msg_ctime_hi;
10#else10#else
11 int __unused1;11 unsigned long __msg_stime_hi;
12 time_t msg_stime;12 unsigned long __msg_stime_lo;
13 int __unused2;13 unsigned long __msg_rtime_hi;
14 time_t msg_rtime;14 unsigned long __msg_rtime_lo;
15 int __unused3;15 unsigned long __msg_ctime_hi;
16 time_t msg_ctime;16 unsigned long __msg_ctime_lo;
17#endif17#endif
18 unsigned long msg_cbytes;18 unsigned long msg_cbytes;
19 msgqnum_t msg_qnum;19 msgqnum_t msg_qnum;
...@@ -21,4 +21,7 @@ struct msqid_ds {...@@ -21,4 +21,7 @@ struct msqid_ds {
21 pid_t msg_lspid;21 pid_t msg_lspid;
22 pid_t msg_lrpid;22 pid_t msg_lrpid;
23 unsigned long __unused[2];23 unsigned long __unused[2];
24 time_t msg_stime;
25 time_t msg_rtime;
26 time_t msg_ctime;
24};27};
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/sem.h created+16
...@@ -0,0 +1,16 @@
1struct semid_ds {
2 struct ipc_perm sem_perm;
3 unsigned long __sem_otime_lo;
4 unsigned long __sem_ctime_lo;
5#if __BYTE_ORDER == __LITTLE_ENDIAN
6 unsigned short sem_nsems;
7 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
8#else
9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
10 unsigned short sem_nsems;
11#endif
12 unsigned long __sem_otime_hi;
13 unsigned long __sem_ctime_hi;
14 time_t sem_otime;
15 time_t sem_ctime;
16};
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/shm.h created+29
...@@ -0,0 +1,29 @@
1#define SHMLBA 4096
2
3struct shmid_ds {
4 struct ipc_perm shm_perm;
5 size_t shm_segsz;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_dtime_lo;
8 unsigned long __shm_ctime_lo;
9 pid_t shm_cpid;
10 pid_t shm_lpid;
11 unsigned long shm_nattch;
12 unsigned short __shm_atime_hi;
13 unsigned short __shm_dtime_hi;
14 unsigned short __shm_ctime_hi;
15 unsigned short __pad1;
16 time_t shm_atime;
17 time_t shm_dtime;
18 time_t shm_ctime;
19};
20
21struct shminfo {
22 unsigned long shmmax, shmmin, shmmni, shmseg, shmall, __unused[4];
23};
24
25struct shm_info {
26 int __used_ids;
27 unsigned long shm_tot, shm_rss, shm_swp;
28 unsigned long __swap_attempts, __swap_successes;
29};
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/signal.h+6-2
...@@ -19,14 +19,18 @@ typedef struct {...@@ -19,14 +19,18 @@ typedef struct {
19} fpregset_t;19} fpregset_t;
20struct sigcontext {20struct sigcontext {
21 unsigned sc_regmask, sc_status;21 unsigned sc_regmask, sc_status;
22 unsigned long long sc_pc, sc_regs[32], sc_fpregs[32];22 unsigned long long sc_pc;
23 gregset_t sc_regs;
24 fpregset_t sc_fpregs;
23 unsigned sc_ownedfp, sc_fpc_csr, sc_fpc_eir, sc_used_math, sc_dsp;25 unsigned sc_ownedfp, sc_fpc_csr, sc_fpc_eir, sc_used_math, sc_dsp;
24 unsigned long long sc_mdhi, sc_mdlo;26 unsigned long long sc_mdhi, sc_mdlo;
25 unsigned long sc_hi1, sc_lo1, sc_hi2, sc_lo2, sc_hi3, sc_lo3;27 unsigned long sc_hi1, sc_lo1, sc_hi2, sc_lo2, sc_hi3, sc_lo3;
26};28};
27typedef struct {29typedef struct {
28 unsigned regmask, status;30 unsigned regmask, status;
29 unsigned long long pc, gregs[32], fpregs[32];31 unsigned long long pc;
32 gregset_t gregs;
33 fpregset_t fpregs;
30 unsigned ownedfp, fpc_csr, fpc_eir, used_math, dsp;34 unsigned ownedfp, fpc_csr, fpc_eir, used_math, dsp;
31 unsigned long long mdhi, mdlo;35 unsigned long long mdhi, mdlo;
32 unsigned long hi1, lo1, hi2, lo2, hi3, lo3;36 unsigned long hi1, lo1, hi2, lo2, hi3, lo3;
lib/libc/include/mips-linux-musl/bits/socket.h-18
...@@ -1,19 +1,3 @@...@@ -1,19 +1,3 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen;
6 void *msg_control;
7 socklen_t msg_controllen;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int cmsg_level;
14 int cmsg_type;
15};
16
17#define SOCK_STREAM 21#define SOCK_STREAM 2
18#define SOCK_DGRAM 12#define SOCK_DGRAM 1
193
...@@ -32,8 +16,6 @@ struct cmsghdr {...@@ -32,8 +16,6 @@ struct cmsghdr {
32#define SO_RCVBUF 0x100216#define SO_RCVBUF 0x1002
33#define SO_SNDLOWAT 0x100317#define SO_SNDLOWAT 0x1003
34#define SO_RCVLOWAT 0x100418#define SO_RCVLOWAT 0x1004
35#define SO_RCVTIMEO 0x1006
36#define SO_SNDTIMEO 0x1005
37#define SO_ERROR 0x100719#define SO_ERROR 0x1007
38#define SO_TYPE 0x100820#define SO_TYPE 0x1008
39#define SO_ACCEPTCONN 0x100921#define SO_ACCEPTCONN 0x1009
lib/libc/include/mips-linux-musl/bits/stat.h+8-4
...@@ -12,11 +12,15 @@ struct stat {...@@ -12,11 +12,15 @@ struct stat {
12 dev_t st_rdev;12 dev_t st_rdev;
13 long __st_padding2[2];13 long __st_padding2[2];
14 off_t st_size;14 off_t st_size;
15 struct timespec st_atim;15 struct {
16 struct timespec st_mtim;16 long tv_sec;
17 struct timespec st_ctim;17 long tv_nsec;
18 } __st_atim32, __st_mtim32, __st_ctim32;
18 blksize_t st_blksize;19 blksize_t st_blksize;
19 long __st_padding3;20 long __st_padding3;
20 blkcnt_t st_blocks;21 blkcnt_t st_blocks;
21 long __st_padding4[14];22 struct timespec st_atim;
23 struct timespec st_mtim;
24 struct timespec st_ctim;
25 long __st_padding4[2];
22};26};
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/syscall.h+25-21
...@@ -76,8 +76,8 @@...@@ -76,8 +76,8 @@
76#define __NR_setrlimit 407576#define __NR_setrlimit 4075
77#define __NR_getrlimit 407677#define __NR_getrlimit 4076
78#define __NR_getrusage 407778#define __NR_getrusage 4077
79#define __NR_gettimeofday 407879#define __NR_gettimeofday_time32 4078
80#define __NR_settimeofday 407980#define __NR_settimeofday_time32 4079
81#define __NR_getgroups 408081#define __NR_getgroups 4080
82#define __NR_setgroups 408182#define __NR_setgroups 4081
83#define __NR_reserved82 408283#define __NR_reserved82 4082
...@@ -256,14 +256,14 @@...@@ -256,14 +256,14 @@
256#define __NR_statfs64 4255256#define __NR_statfs64 4255
257#define __NR_fstatfs64 4256257#define __NR_fstatfs64 4256
258#define __NR_timer_create 4257258#define __NR_timer_create 4257
259#define __NR_timer_settime 4258259#define __NR_timer_settime32 4258
260#define __NR_timer_gettime 4259260#define __NR_timer_gettime32 4259
261#define __NR_timer_getoverrun 4260261#define __NR_timer_getoverrun 4260
262#define __NR_timer_delete 4261262#define __NR_timer_delete 4261
263#define __NR_clock_settime 4262263#define __NR_clock_settime32 4262
264#define __NR_clock_gettime 4263264#define __NR_clock_gettime32 4263
265#define __NR_clock_getres 4264265#define __NR_clock_getres_time32 4264
266#define __NR_clock_nanosleep 4265266#define __NR_clock_nanosleep_time32 4265
267#define __NR_tgkill 4266267#define __NR_tgkill 4266
268#define __NR_utimes 4267268#define __NR_utimes 4267
269#define __NR_mbind 4268269#define __NR_mbind 4268
...@@ -319,8 +319,8 @@...@@ -319,8 +319,8 @@
319#define __NR_eventfd 4319319#define __NR_eventfd 4319
320#define __NR_fallocate 4320320#define __NR_fallocate 4320
321#define __NR_timerfd_create 4321321#define __NR_timerfd_create 4321
322#define __NR_timerfd_gettime 4322322#define __NR_timerfd_gettime32 4322
323#define __NR_timerfd_settime 4323323#define __NR_timerfd_settime32 4323
324#define __NR_signalfd4 4324324#define __NR_signalfd4 4324
325#define __NR_eventfd2 4325325#define __NR_eventfd2 4325
326#define __NR_epoll_create1 4326326#define __NR_epoll_create1 4326
...@@ -406,6 +406,8 @@...@@ -406,6 +406,8 @@
406#define __NR_fsconfig 4431406#define __NR_fsconfig 4431
407#define __NR_fsmount 4432407#define __NR_fsmount 4432
408#define __NR_fspick 4433408#define __NR_fspick 4433
409#define __NR_pidfd_open 4434
410#define __NR_clone3 4435
409411
410#define SYS_syscall 4000412#define SYS_syscall 4000
411#define SYS_exit 4001413#define SYS_exit 4001
...@@ -485,8 +487,8 @@...@@ -485,8 +487,8 @@
485#define SYS_setrlimit 4075487#define SYS_setrlimit 4075
486#define SYS_getrlimit 4076488#define SYS_getrlimit 4076
487#define SYS_getrusage 4077489#define SYS_getrusage 4077
488#define SYS_gettimeofday 4078490#define SYS_gettimeofday_time32 4078
489#define SYS_settimeofday 4079491#define SYS_settimeofday_time32 4079
490#define SYS_getgroups 4080492#define SYS_getgroups 4080
491#define SYS_setgroups 4081493#define SYS_setgroups 4081
492#define SYS_reserved82 4082494#define SYS_reserved82 4082
...@@ -665,14 +667,14 @@...@@ -665,14 +667,14 @@
665#define SYS_statfs64 4255667#define SYS_statfs64 4255
666#define SYS_fstatfs64 4256668#define SYS_fstatfs64 4256
667#define SYS_timer_create 4257669#define SYS_timer_create 4257
668#define SYS_timer_settime 4258670#define SYS_timer_settime32 4258
669#define SYS_timer_gettime 4259671#define SYS_timer_gettime32 4259
670#define SYS_timer_getoverrun 4260672#define SYS_timer_getoverrun 4260
671#define SYS_timer_delete 4261673#define SYS_timer_delete 4261
672#define SYS_clock_settime 4262674#define SYS_clock_settime32 4262
673#define SYS_clock_gettime 4263675#define SYS_clock_gettime32 4263
674#define SYS_clock_getres 4264676#define SYS_clock_getres_time32 4264
675#define SYS_clock_nanosleep 4265677#define SYS_clock_nanosleep_time32 4265
676#define SYS_tgkill 4266678#define SYS_tgkill 4266
677#define SYS_utimes 4267679#define SYS_utimes 4267
678#define SYS_mbind 4268680#define SYS_mbind 4268
...@@ -728,8 +730,8 @@...@@ -728,8 +730,8 @@
728#define SYS_eventfd 4319730#define SYS_eventfd 4319
729#define SYS_fallocate 4320731#define SYS_fallocate 4320
730#define SYS_timerfd_create 4321732#define SYS_timerfd_create 4321
731#define SYS_timerfd_gettime 4322733#define SYS_timerfd_gettime32 4322
732#define SYS_timerfd_settime 4323734#define SYS_timerfd_settime32 4323
733#define SYS_signalfd4 4324735#define SYS_signalfd4 4324
734#define SYS_eventfd2 4325736#define SYS_eventfd2 4325
735#define SYS_epoll_create1 4326737#define SYS_epoll_create1 4326
...@@ -814,4 +816,6 @@...@@ -814,4 +816,6 @@
814#define SYS_fsopen 4430816#define SYS_fsopen 4430
815#define SYS_fsconfig 4431817#define SYS_fsconfig 4431
816#define SYS_fsmount 4432818#define SYS_fsmount 4432
817#define SYS_fspick 4433
\ No newline at end of file
819#define SYS_fspick 4433
820#define SYS_pidfd_open 4434
821#define SYS_clone3 4435
\ No newline at end of file
lib/libc/include/mips64-linux-musl/bits/alltypes.h+66-55
...@@ -2,16 +2,13 @@...@@ -2,16 +2,13 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)5#if _MIPSEL || __MIPSEL || __MIPSEL__
6typedef __builtin_va_list va_list;6#define __BYTE_ORDER 1234
7#define __DEFINED_va_list7#else
8#endif8#define __BYTE_ORDER 4321
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif9#endif
1410
11#define __LONG_MAX 0x7fffffffffffffffL
1512
16#ifndef __cplusplus13#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)14#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -38,57 +35,14 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -38,57 +35,14 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
38#endif35#endif
3936
4037
41#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
42typedef long time_t;
43#define __DEFINED_time_t
44#endif
45
46#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
47typedef long suseconds_t;
48#define __DEFINED_suseconds_t
49#endif
50
51
52#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t)38#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t)
53typedef unsigned nlink_t;39typedef unsigned nlink_t;
54#define __DEFINED_nlink_t40#define __DEFINED_nlink_t
55#endif41#endif
5642
5743#define __LITTLE_ENDIAN 1234
58#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)44#define __BIG_ENDIAN 4321
59typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;45#define __USE_TIME_BITS64 1
60#define __DEFINED_pthread_attr_t
61#endif
62
63#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
64typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
65#define __DEFINED_pthread_mutex_t
66#endif
67
68#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
69typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
70#define __DEFINED_mtx_t
71#endif
72
73#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
74typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
75#define __DEFINED_pthread_cond_t
76#endif
77
78#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
79typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
80#define __DEFINED_cnd_t
81#endif
82
83#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
84typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
85#define __DEFINED_pthread_rwlock_t
86#endif
87
88#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
89typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
90#define __DEFINED_pthread_barrier_t
91#endif
9246
93#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)47#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
94typedef unsigned _Addr size_t;48typedef unsigned _Addr size_t;
...@@ -125,6 +79,16 @@ typedef _Reg register_t;...@@ -125,6 +79,16 @@ typedef _Reg register_t;
125#define __DEFINED_register_t79#define __DEFINED_register_t
126#endif80#endif
12781
82#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
83typedef _Int64 time_t;
84#define __DEFINED_time_t
85#endif
86
87#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
88typedef _Int64 suseconds_t;
89#define __DEFINED_suseconds_t
90#endif
91
12892
129#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)93#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
130typedef signed char int8_t;94typedef signed char int8_t;
...@@ -260,7 +224,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -260,7 +224,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
260#endif224#endif
261225
262#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)226#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
263struct timespec { time_t tv_sec; long tv_nsec; };227struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
264#define __DEFINED_struct_timespec228#define __DEFINED_struct_timespec
265#endif229#endif
266230
...@@ -356,6 +320,17 @@ typedef struct _IO_FILE FILE;...@@ -356,6 +320,17 @@ typedef struct _IO_FILE FILE;
356#endif320#endif
357321
358322
323#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
324typedef __builtin_va_list va_list;
325#define __DEFINED_va_list
326#endif
327
328#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
329typedef __builtin_va_list __isoc_va_list;
330#define __DEFINED___isoc_va_list
331#endif
332
333
359#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)334#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
360typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;335typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
361#define __DEFINED_mbstate_t336#define __DEFINED_mbstate_t
...@@ -391,6 +366,42 @@ typedef unsigned short sa_family_t;...@@ -391,6 +366,42 @@ typedef unsigned short sa_family_t;
391#endif366#endif
392367
393368
369#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
370typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
371#define __DEFINED_pthread_attr_t
372#endif
373
374#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
375typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
376#define __DEFINED_pthread_mutex_t
377#endif
378
379#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
380typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
381#define __DEFINED_mtx_t
382#endif
383
384#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
385typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
386#define __DEFINED_pthread_cond_t
387#endif
388
389#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
390typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
391#define __DEFINED_cnd_t
392#endif
393
394#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
395typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
396#define __DEFINED_pthread_rwlock_t
397#endif
398
399#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
400typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
401#define __DEFINED_pthread_barrier_t
402#endif
403
404
394#undef _Addr405#undef _Addr
395#undef _Int64406#undef _Int64
396#undef _Reg407#undef _Reg
\ No newline at end of file
lib/libc/include/mips64-linux-musl/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if _MIPSEL || __MIPSEL || __MIPSEL__
2#define __BYTE_ORDER __LITTLE_ENDIAN
3#else
4#define __BYTE_ORDER __BIG_ENDIAN
5#endif
\ No newline at end of file
lib/libc/include/mips64-linux-musl/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 64
4#endif
5
6#define LONG_MAX 0x7fffffffffffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
lib/libc/include/mips64-linux-musl/bits/socket.h-34
...@@ -1,37 +1,3 @@...@@ -1,37 +1,3 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7#if __BYTE_ORDER == __BIG_ENDIAN
8 int __pad1, msg_iovlen;
9#else
10 int msg_iovlen, __pad1;
11#endif
12 void *msg_control;
13#if __BYTE_ORDER == __BIG_ENDIAN
14 int __pad2;
15 socklen_t msg_controllen;
16#else
17 socklen_t msg_controllen;
18 int __pad2;
19#endif
20 int msg_flags;
21};
22
23struct cmsghdr {
24#if __BYTE_ORDER == __BIG_ENDIAN
25 int __pad1;
26 socklen_t cmsg_len;
27#else
28 socklen_t cmsg_len;
29 int __pad1;
30#endif
31 int cmsg_level;
32 int cmsg_type;
33};
34
35#define SOCK_STREAM 21#define SOCK_STREAM 2
36#define SOCK_DGRAM 12#define SOCK_DGRAM 1
37#define SOL_SOCKET 655353#define SOL_SOCKET 65535
lib/libc/include/mips64-linux-musl/bits/syscall.h+5-1
...@@ -336,6 +336,8 @@...@@ -336,6 +336,8 @@
336#define __NR_fsconfig 5431336#define __NR_fsconfig 5431
337#define __NR_fsmount 5432337#define __NR_fsmount 5432
338#define __NR_fspick 5433338#define __NR_fspick 5433
339#define __NR_pidfd_open 5434
340#define __NR_clone3 5435
339341
340#define SYS_read 5000342#define SYS_read 5000
341#define SYS_write 5001343#define SYS_write 5001
...@@ -674,4 +676,6 @@...@@ -674,4 +676,6 @@
674#define SYS_fsopen 5430676#define SYS_fsopen 5430
675#define SYS_fsconfig 5431677#define SYS_fsconfig 5431
676#define SYS_fsmount 5432678#define SYS_fsmount 5432
677#define SYS_fspick 5433
\ No newline at end of file
679#define SYS_fspick 5433
680#define SYS_pidfd_open 5434
681#define SYS_clone3 5435
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/alltypes.h+64-57
...@@ -1,17 +1,10 @@...@@ -1,17 +1,10 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)6#define __BYTE_ORDER 4321
6typedef __builtin_va_list va_list;7#define __LONG_MAX 0x7fffffffL
7#define __DEFINED_va_list
8#endif
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif
14
158
16#ifndef __cplusplus9#ifndef __cplusplus
17#ifdef __WCHAR_TYPE__10#ifdef __WCHAR_TYPE__
...@@ -45,52 +38,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -45,52 +38,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
45#define __DEFINED_max_align_t38#define __DEFINED_max_align_t
46#endif39#endif
4740
4841#define __LITTLE_ENDIAN 1234
49#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)42#define __BIG_ENDIAN 4321
50typedef long time_t;43#define __USE_TIME_BITS64 1
51#define __DEFINED_time_t
52#endif
53
54#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
55typedef long suseconds_t;
56#define __DEFINED_suseconds_t
57#endif
58
59
60#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
61typedef struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
62#define __DEFINED_pthread_attr_t
63#endif
64
65#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
66typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
67#define __DEFINED_pthread_mutex_t
68#endif
69
70#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
71typedef struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
72#define __DEFINED_mtx_t
73#endif
74
75#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
76typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
77#define __DEFINED_pthread_cond_t
78#endif
79
80#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
81typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
82#define __DEFINED_cnd_t
83#endif
84
85#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
86typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
87#define __DEFINED_pthread_rwlock_t
88#endif
89
90#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
91typedef struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
92#define __DEFINED_pthread_barrier_t
93#endif
9444
95#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)45#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
96typedef unsigned _Addr size_t;46typedef unsigned _Addr size_t;
...@@ -127,6 +77,16 @@ typedef _Reg register_t;...@@ -127,6 +77,16 @@ typedef _Reg register_t;
127#define __DEFINED_register_t77#define __DEFINED_register_t
128#endif78#endif
12979
80#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
81typedef _Int64 time_t;
82#define __DEFINED_time_t
83#endif
84
85#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
86typedef _Int64 suseconds_t;
87#define __DEFINED_suseconds_t
88#endif
89
13090
131#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)91#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
132typedef signed char int8_t;92typedef signed char int8_t;
...@@ -262,7 +222,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -262,7 +222,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
262#endif222#endif
263223
264#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)224#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
265struct timespec { time_t tv_sec; long tv_nsec; };225struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
266#define __DEFINED_struct_timespec226#define __DEFINED_struct_timespec
267#endif227#endif
268228
...@@ -358,6 +318,17 @@ typedef struct _IO_FILE FILE;...@@ -358,6 +318,17 @@ typedef struct _IO_FILE FILE;
358#endif318#endif
359319
360320
321#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
322typedef __builtin_va_list va_list;
323#define __DEFINED_va_list
324#endif
325
326#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
327typedef __builtin_va_list __isoc_va_list;
328#define __DEFINED___isoc_va_list
329#endif
330
331
361#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)332#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
362typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;333typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
363#define __DEFINED_mbstate_t334#define __DEFINED_mbstate_t
...@@ -393,6 +364,42 @@ typedef unsigned short sa_family_t;...@@ -393,6 +364,42 @@ typedef unsigned short sa_family_t;
393#endif364#endif
394365
395366
367#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
368typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
369#define __DEFINED_pthread_attr_t
370#endif
371
372#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
373typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
374#define __DEFINED_pthread_mutex_t
375#endif
376
377#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
378typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
379#define __DEFINED_mtx_t
380#endif
381
382#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
383typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
384#define __DEFINED_pthread_cond_t
385#endif
386
387#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
388typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
389#define __DEFINED_cnd_t
390#endif
391
392#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
393typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
394#define __DEFINED_pthread_rwlock_t
395#endif
396
397#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
398typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
399#define __DEFINED_pthread_barrier_t
400#endif
401
402
396#undef _Addr403#undef _Addr
397#undef _Int64404#undef _Int64
398#undef _Reg405#undef _Reg
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/endian.h deleted-15
...@@ -1,15 +0,0 @@
1#ifdef __BIG_ENDIAN__
2 #if __BIG_ENDIAN__
3 #define __BYTE_ORDER __BIG_ENDIAN
4 #endif
5#endif /* __BIG_ENDIAN__ */
6
7#ifdef __LITTLE_ENDIAN__
8 #if __LITTLE_ENDIAN__
9 #define __BYTE_ORDER __LITTLE_ENDIAN
10 #endif
11#endif /* __LITTLE_ENDIAN__ */
12
13#ifndef __BYTE_ORDER
14 #define __BYTE_ORDER __BIG_ENDIAN
15#endif
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/ioctl.h+2-2
...@@ -116,5 +116,5 @@...@@ -116,5 +116,5 @@
116#define FIOGETOWN 0x8903116#define FIOGETOWN 0x8903
117#define SIOCGPGRP 0x8904117#define SIOCGPGRP 0x8904
118#define SIOCATMARK 0x8905118#define SIOCATMARK 0x8905
119#define SIOCGSTAMP 0x8906
120#define SIOCGSTAMPNS 0x8907
\ No newline at end of file
119#define SIOCGSTAMP _IOR(0x89, 6, char[16])
120#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/ipcstat.h created+1
...@@ -0,0 +1 @@
1#define IPC_STAT 0x102
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 32
4#endif
5
6#define LONG_MAX 0x7fffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/msg.h+9-6
...@@ -1,15 +1,18 @@...@@ -1,15 +1,18 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3 int __unused1;3 unsigned long __msg_stime_hi;
4 time_t msg_stime;4 unsigned long __msg_stime_lo;
5 int __unused2;5 unsigned long __msg_rtime_hi;
6 time_t msg_rtime;6 unsigned long __msg_rtime_lo;
7 int __unused3;7 unsigned long __msg_ctime_hi;
8 time_t msg_ctime;8 unsigned long __msg_ctime_lo;
9 unsigned long msg_cbytes;9 unsigned long msg_cbytes;
10 msgqnum_t msg_qnum;10 msgqnum_t msg_qnum;
11 msglen_t msg_qbytes;11 msglen_t msg_qbytes;
12 pid_t msg_lspid;12 pid_t msg_lspid;
13 pid_t msg_lrpid;13 pid_t msg_lrpid;
14 unsigned long __unused[2];14 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
15};18};
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/sem.h+6-4
...@@ -1,10 +1,12 @@...@@ -1,10 +1,12 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 int __unused1;3 unsigned long __sem_otime_hi;
4 time_t sem_otime;4 unsigned long __sem_otime_lo;
5 int __unused2;5 unsigned long __sem_ctime_hi;
6 time_t sem_ctime;6 unsigned long __sem_ctime_lo;
7 unsigned short __sem_nsems_pad, sem_nsems;7 unsigned short __sem_nsems_pad, sem_nsems;
8 long __unused3;8 long __unused3;
9 long __unused4;9 long __unused4;
10 time_t sem_otime;
11 time_t sem_ctime;
10};12};
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/shm.h+9-7
...@@ -2,19 +2,21 @@...@@ -2,19 +2,21 @@
22
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 int __unused1;5 unsigned long __shm_atime_hi;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 int __unused2;7 unsigned long __shm_dtime_hi;
8 time_t shm_dtime;8 unsigned long __shm_dtime_lo;
9 int __unused3;9 unsigned long __shm_ctime_hi;
10 time_t shm_ctime;10 unsigned long __shm_ctime_lo;
11 int __unused4;
12 size_t shm_segsz;11 size_t shm_segsz;
13 pid_t shm_cpid;12 pid_t shm_cpid;
14 pid_t shm_lpid;13 pid_t shm_lpid;
15 unsigned long shm_nattch;14 unsigned long shm_nattch;
16 unsigned long __pad1;15 unsigned long __pad1;
17 unsigned long __pad2;16 unsigned long __pad2;
17 time_t shm_atime;
18 time_t shm_dtime;
19 time_t shm_ctime;
18};20};
1921
20struct shminfo {22struct shminfo {
lib/libc/include/powerpc-linux-musl/bits/signal.h+1-1
...@@ -28,7 +28,7 @@ struct sigcontext {...@@ -28,7 +28,7 @@ struct sigcontext {
28 int signal;28 int signal;
29 unsigned long handler;29 unsigned long handler;
30 unsigned long oldmask;30 unsigned long oldmask;
31 void *regs;31 struct pt_regs *regs;
32};32};
3333
34typedef struct {34typedef struct {
lib/libc/include/powerpc-linux-musl/bits/socket.h-18
...@@ -1,19 +1,3 @@...@@ -1,19 +1,3 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen;
6 void *msg_control;
7 socklen_t msg_controllen;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int cmsg_level;
14 int cmsg_type;
15};
16
17#define SO_DEBUG 11#define SO_DEBUG 1
18#define SO_REUSEADDR 22#define SO_REUSEADDR 2
19#define SO_TYPE 33#define SO_TYPE 3
...@@ -31,8 +15,6 @@ struct cmsghdr {...@@ -31,8 +15,6 @@ struct cmsghdr {
31#define SO_REUSEPORT 1515#define SO_REUSEPORT 15
32#define SO_RCVLOWAT 1616#define SO_RCVLOWAT 16
33#define SO_SNDLOWAT 1717#define SO_SNDLOWAT 17
34#define SO_RCVTIMEO 18
35#define SO_SNDTIMEO 19
36#define SO_PASSCRED 2018#define SO_PASSCRED 20
37#define SO_PEERCRED 2119#define SO_PEERCRED 21
38#define SO_ACCEPTCONN 3020#define SO_ACCEPTCONN 30
lib/libc/include/powerpc-linux-musl/bits/stat.h+5-1
...@@ -13,8 +13,12 @@ struct stat {...@@ -13,8 +13,12 @@ struct stat {
13 off_t st_size;13 off_t st_size;
14 blksize_t st_blksize;14 blksize_t st_blksize;
15 blkcnt_t st_blocks;15 blkcnt_t st_blocks;
16 struct {
17 long tv_sec;
18 long tv_nsec;
19 } __st_atim32, __st_mtim32, __st_ctim32;
20 unsigned __unused[2];
16 struct timespec st_atim;21 struct timespec st_atim;
17 struct timespec st_mtim;22 struct timespec st_mtim;
18 struct timespec st_ctim;23 struct timespec st_ctim;
19 unsigned __unused[2];
20};24};
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/syscall.h+25-21
...@@ -76,8 +76,8 @@...@@ -76,8 +76,8 @@
76#define __NR_setrlimit 7576#define __NR_setrlimit 75
77#define __NR_getrlimit 7677#define __NR_getrlimit 76
78#define __NR_getrusage 7778#define __NR_getrusage 77
79#define __NR_gettimeofday 7879#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday 7980#define __NR_settimeofday_time32 79
81#define __NR_getgroups 8081#define __NR_getgroups 80
82#define __NR_setgroups 8182#define __NR_setgroups 81
83#define __NR_select 8283#define __NR_select 82
...@@ -238,14 +238,14 @@...@@ -238,14 +238,14 @@
238#define __NR_epoll_wait 238238#define __NR_epoll_wait 238
239#define __NR_remap_file_pages 239239#define __NR_remap_file_pages 239
240#define __NR_timer_create 240240#define __NR_timer_create 240
241#define __NR_timer_settime 241241#define __NR_timer_settime32 241
242#define __NR_timer_gettime 242242#define __NR_timer_gettime32 242
243#define __NR_timer_getoverrun 243243#define __NR_timer_getoverrun 243
244#define __NR_timer_delete 244244#define __NR_timer_delete 244
245#define __NR_clock_settime 245245#define __NR_clock_settime32 245
246#define __NR_clock_gettime 246246#define __NR_clock_gettime32 246
247#define __NR_clock_getres 247247#define __NR_clock_getres_time32 247
248#define __NR_clock_nanosleep 248248#define __NR_clock_nanosleep_time32 248
249#define __NR_swapcontext 249249#define __NR_swapcontext 249
250#define __NR_tgkill 250250#define __NR_tgkill 250
251#define __NR_utimes 251251#define __NR_utimes 251
...@@ -307,8 +307,8 @@...@@ -307,8 +307,8 @@
307#define __NR_sync_file_range2 308307#define __NR_sync_file_range2 308
308#define __NR_fallocate 309308#define __NR_fallocate 309
309#define __NR_subpage_prot 310309#define __NR_subpage_prot 310
310#define __NR_timerfd_settime 311310#define __NR_timerfd_settime32 311
311#define __NR_timerfd_gettime 312311#define __NR_timerfd_gettime32 312
312#define __NR_signalfd4 313312#define __NR_signalfd4 313
313#define __NR_eventfd2 314313#define __NR_eventfd2 314
314#define __NR_epoll_create1 315314#define __NR_epoll_create1 315
...@@ -413,6 +413,8 @@...@@ -413,6 +413,8 @@
413#define __NR_fsconfig 431413#define __NR_fsconfig 431
414#define __NR_fsmount 432414#define __NR_fsmount 432
415#define __NR_fspick 433415#define __NR_fspick 433
416#define __NR_pidfd_open 434
417#define __NR_clone3 435
416418
417#define SYS_restart_syscall 0419#define SYS_restart_syscall 0
418#define SYS_exit 1420#define SYS_exit 1
...@@ -492,8 +494,8 @@...@@ -492,8 +494,8 @@
492#define SYS_setrlimit 75494#define SYS_setrlimit 75
493#define SYS_getrlimit 76495#define SYS_getrlimit 76
494#define SYS_getrusage 77496#define SYS_getrusage 77
495#define SYS_gettimeofday 78497#define SYS_gettimeofday_time32 78
496#define SYS_settimeofday 79498#define SYS_settimeofday_time32 79
497#define SYS_getgroups 80499#define SYS_getgroups 80
498#define SYS_setgroups 81500#define SYS_setgroups 81
499#define SYS_select 82501#define SYS_select 82
...@@ -654,14 +656,14 @@...@@ -654,14 +656,14 @@
654#define SYS_epoll_wait 238656#define SYS_epoll_wait 238
655#define SYS_remap_file_pages 239657#define SYS_remap_file_pages 239
656#define SYS_timer_create 240658#define SYS_timer_create 240
657#define SYS_timer_settime 241659#define SYS_timer_settime32 241
658#define SYS_timer_gettime 242660#define SYS_timer_gettime32 242
659#define SYS_timer_getoverrun 243661#define SYS_timer_getoverrun 243
660#define SYS_timer_delete 244662#define SYS_timer_delete 244
661#define SYS_clock_settime 245663#define SYS_clock_settime32 245
662#define SYS_clock_gettime 246664#define SYS_clock_gettime32 246
663#define SYS_clock_getres 247665#define SYS_clock_getres_time32 247
664#define SYS_clock_nanosleep 248666#define SYS_clock_nanosleep_time32 248
665#define SYS_swapcontext 249667#define SYS_swapcontext 249
666#define SYS_tgkill 250668#define SYS_tgkill 250
667#define SYS_utimes 251669#define SYS_utimes 251
...@@ -723,8 +725,8 @@...@@ -723,8 +725,8 @@
723#define SYS_sync_file_range2 308725#define SYS_sync_file_range2 308
724#define SYS_fallocate 309726#define SYS_fallocate 309
725#define SYS_subpage_prot 310727#define SYS_subpage_prot 310
726#define SYS_timerfd_settime 311728#define SYS_timerfd_settime32 311
727#define SYS_timerfd_gettime 312729#define SYS_timerfd_gettime32 312
728#define SYS_signalfd4 313730#define SYS_signalfd4 313
729#define SYS_eventfd2 314731#define SYS_eventfd2 314
730#define SYS_epoll_create1 315732#define SYS_epoll_create1 315
...@@ -828,4 +830,6 @@...@@ -828,4 +830,6 @@
828#define SYS_fsopen 430830#define SYS_fsopen 430
829#define SYS_fsconfig 431831#define SYS_fsconfig 431
830#define SYS_fsmount 432832#define SYS_fsmount 432
831#define SYS_fspick 433
\ No newline at end of file
833#define SYS_fspick 433
834#define SYS_pidfd_open 434
835#define SYS_clone3 435
\ No newline at end of file
lib/libc/include/powerpc64-linux-musl/bits/alltypes.h+66-55
...@@ -2,16 +2,13 @@...@@ -2,16 +2,13 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)5#if __BIG_ENDIAN__
6typedef __builtin_va_list va_list;6#define __BYTE_ORDER 4321
7#define __DEFINED_va_list7#else
8#endif8#define __BYTE_ORDER 1234
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif9#endif
1410
11#define __LONG_MAX 0x7fffffffffffffffL
1512
16#ifndef __cplusplus13#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)14#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -37,52 +34,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -37,52 +34,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
37#define __DEFINED_max_align_t34#define __DEFINED_max_align_t
38#endif35#endif
3936
4037#define __LITTLE_ENDIAN 1234
41#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)38#define __BIG_ENDIAN 4321
42typedef long time_t;39#define __USE_TIME_BITS64 1
43#define __DEFINED_time_t
44#endif
45
46#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
47typedef long suseconds_t;
48#define __DEFINED_suseconds_t
49#endif
50
51
52#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
53typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
54#define __DEFINED_pthread_attr_t
55#endif
56
57#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
58typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
59#define __DEFINED_pthread_mutex_t
60#endif
61
62#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
63typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
64#define __DEFINED_mtx_t
65#endif
66
67#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
68typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
69#define __DEFINED_pthread_cond_t
70#endif
71
72#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
73typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
74#define __DEFINED_cnd_t
75#endif
76
77#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
78typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
79#define __DEFINED_pthread_rwlock_t
80#endif
81
82#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
83typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
84#define __DEFINED_pthread_barrier_t
85#endif
8640
87#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)41#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
88typedef unsigned _Addr size_t;42typedef unsigned _Addr size_t;
...@@ -119,6 +73,16 @@ typedef _Reg register_t;...@@ -119,6 +73,16 @@ typedef _Reg register_t;
119#define __DEFINED_register_t73#define __DEFINED_register_t
120#endif74#endif
12175
76#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
77typedef _Int64 time_t;
78#define __DEFINED_time_t
79#endif
80
81#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
82typedef _Int64 suseconds_t;
83#define __DEFINED_suseconds_t
84#endif
85
12286
123#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)87#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
124typedef signed char int8_t;88typedef signed char int8_t;
...@@ -254,7 +218,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -254,7 +218,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254#endif218#endif
255219
256#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)220#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
257struct timespec { time_t tv_sec; long tv_nsec; };221struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
258#define __DEFINED_struct_timespec222#define __DEFINED_struct_timespec
259#endif223#endif
260224
...@@ -350,6 +314,17 @@ typedef struct _IO_FILE FILE;...@@ -350,6 +314,17 @@ typedef struct _IO_FILE FILE;
350#endif314#endif
351315
352316
317#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
318typedef __builtin_va_list va_list;
319#define __DEFINED_va_list
320#endif
321
322#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
323typedef __builtin_va_list __isoc_va_list;
324#define __DEFINED___isoc_va_list
325#endif
326
327
353#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)328#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;329typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355#define __DEFINED_mbstate_t330#define __DEFINED_mbstate_t
...@@ -385,6 +360,42 @@ typedef unsigned short sa_family_t;...@@ -385,6 +360,42 @@ typedef unsigned short sa_family_t;
385#endif360#endif
386361
387362
363#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
364typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
365#define __DEFINED_pthread_attr_t
366#endif
367
368#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
369typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
370#define __DEFINED_pthread_mutex_t
371#endif
372
373#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
374typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
375#define __DEFINED_mtx_t
376#endif
377
378#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
379typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
380#define __DEFINED_pthread_cond_t
381#endif
382
383#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
384typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
385#define __DEFINED_cnd_t
386#endif
387
388#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
389typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
390#define __DEFINED_pthread_rwlock_t
391#endif
392
393#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
394typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
395#define __DEFINED_pthread_barrier_t
396#endif
397
398
388#undef _Addr399#undef _Addr
389#undef _Int64400#undef _Int64
390#undef _Reg401#undef _Reg
\ No newline at end of file
lib/libc/include/powerpc64-linux-musl/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if __BIG_ENDIAN__
2#define __BYTE_ORDER __BIG_ENDIAN
3#else
4#define __BYTE_ORDER __LITTLE_ENDIAN
5#endif
\ No newline at end of file
lib/libc/include/powerpc64-linux-musl/bits/signal.h+2-6
...@@ -9,11 +9,7 @@...@@ -9,11 +9,7 @@
9#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)9#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
1010
11typedef unsigned long greg_t, gregset_t[48];11typedef unsigned long greg_t, gregset_t[48];
1212typedef double fpregset_t[33];
13typedef struct {
14 double fpregs[32];
15 double fpscr;
16} fpregset_t;
1713
18typedef struct {14typedef struct {
19#ifdef __GNUC__15#ifdef __GNUC__
...@@ -36,7 +32,7 @@ typedef struct sigcontext {...@@ -36,7 +32,7 @@ typedef struct sigcontext {
36 int _pad0;32 int _pad0;
37 unsigned long handler;33 unsigned long handler;
38 unsigned long oldmask;34 unsigned long oldmask;
39 void *regs;35 struct pt_regs *regs;
40 gregset_t gp_regs;36 gregset_t gp_regs;
41 fpregset_t fp_regs;37 fpregset_t fp_regs;
42 vrregset_t *v_regs;38 vrregset_t *v_regs;
lib/libc/include/powerpc64-linux-musl/bits/socket.h-34
...@@ -1,37 +1,3 @@...@@ -1,37 +1,3 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7#if __BYTE_ORDER == __BIG_ENDIAN
8 int __pad1, msg_iovlen;
9#else
10 int msg_iovlen, __pad1;
11#endif
12 void *msg_control;
13#if __BYTE_ORDER == __BIG_ENDIAN
14 int __pad2;
15 socklen_t msg_controllen;
16#else
17 socklen_t msg_controllen;
18 int __pad2;
19#endif
20 int msg_flags;
21};
22
23struct cmsghdr {
24#if __BYTE_ORDER == __BIG_ENDIAN
25 int __pad1;
26 socklen_t cmsg_len;
27#else
28 socklen_t cmsg_len;
29 int __pad1;
30#endif
31 int cmsg_level;
32 int cmsg_type;
33};
34
35#define SO_DEBUG 11#define SO_DEBUG 1
36#define SO_REUSEADDR 22#define SO_REUSEADDR 2
37#define SO_TYPE 33#define SO_TYPE 3
lib/libc/include/powerpc64-linux-musl/bits/syscall.h+5-1
...@@ -385,6 +385,8 @@...@@ -385,6 +385,8 @@
385#define __NR_fsconfig 431385#define __NR_fsconfig 431
386#define __NR_fsmount 432386#define __NR_fsmount 432
387#define __NR_fspick 433387#define __NR_fspick 433
388#define __NR_pidfd_open 434
389#define __NR_clone3 435
388390
389#define SYS_restart_syscall 0391#define SYS_restart_syscall 0
390#define SYS_exit 1392#define SYS_exit 1
...@@ -772,4 +774,6 @@...@@ -772,4 +774,6 @@
772#define SYS_fsopen 430774#define SYS_fsopen 430
773#define SYS_fsconfig 431775#define SYS_fsconfig 431
774#define SYS_fsmount 432776#define SYS_fsmount 432
775#define SYS_fspick 433
\ No newline at end of file
777#define SYS_fspick 433
778#define SYS_pidfd_open 434
779#define SYS_clone3 435
\ No newline at end of file
lib/libc/include/riscv64-linux-musl/bits/alltypes.h+63-57
...@@ -2,16 +2,8 @@...@@ -2,16 +2,8 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)5#define __BYTE_ORDER 1234
6typedef __builtin_va_list va_list;6#define __LONG_MAX 0x7fffffffffffffffL
7#define __DEFINED_va_list
8#endif
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif
14
157
16#ifndef __cplusplus8#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)9#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -48,52 +40,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -48,52 +40,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
48#define __DEFINED_max_align_t40#define __DEFINED_max_align_t
49#endif41#endif
5042
5143#define __LITTLE_ENDIAN 1234
52#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)44#define __BIG_ENDIAN 4321
53typedef long time_t;45#define __USE_TIME_BITS64 1
54#define __DEFINED_time_t
55#endif
56
57#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
58typedef long suseconds_t;
59#define __DEFINED_suseconds_t
60#endif
61
62
63#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
64typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
65#define __DEFINED_pthread_attr_t
66#endif
67
68#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
69typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
70#define __DEFINED_pthread_mutex_t
71#endif
72
73#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
74typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
75#define __DEFINED_mtx_t
76#endif
77
78#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
79typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
80#define __DEFINED_pthread_cond_t
81#endif
82
83#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
84typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
85#define __DEFINED_cnd_t
86#endif
87
88#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
89typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
90#define __DEFINED_pthread_rwlock_t
91#endif
92
93#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
94typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
95#define __DEFINED_pthread_barrier_t
96#endif
9746
98#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)47#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
99typedef unsigned _Addr size_t;48typedef unsigned _Addr size_t;
...@@ -130,6 +79,16 @@ typedef _Reg register_t;...@@ -130,6 +79,16 @@ typedef _Reg register_t;
130#define __DEFINED_register_t79#define __DEFINED_register_t
131#endif80#endif
13281
82#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
83typedef _Int64 time_t;
84#define __DEFINED_time_t
85#endif
86
87#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
88typedef _Int64 suseconds_t;
89#define __DEFINED_suseconds_t
90#endif
91
13392
134#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)93#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
135typedef signed char int8_t;94typedef signed char int8_t;
...@@ -265,7 +224,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -265,7 +224,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
265#endif224#endif
266225
267#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)226#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
268struct timespec { time_t tv_sec; long tv_nsec; };227struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
269#define __DEFINED_struct_timespec228#define __DEFINED_struct_timespec
270#endif229#endif
271230
...@@ -361,6 +320,17 @@ typedef struct _IO_FILE FILE;...@@ -361,6 +320,17 @@ typedef struct _IO_FILE FILE;
361#endif320#endif
362321
363322
323#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
324typedef __builtin_va_list va_list;
325#define __DEFINED_va_list
326#endif
327
328#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
329typedef __builtin_va_list __isoc_va_list;
330#define __DEFINED___isoc_va_list
331#endif
332
333
364#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)334#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
365typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;335typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
366#define __DEFINED_mbstate_t336#define __DEFINED_mbstate_t
...@@ -396,6 +366,42 @@ typedef unsigned short sa_family_t;...@@ -396,6 +366,42 @@ typedef unsigned short sa_family_t;
396#endif366#endif
397367
398368
369#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
370typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
371#define __DEFINED_pthread_attr_t
372#endif
373
374#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
375typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
376#define __DEFINED_pthread_mutex_t
377#endif
378
379#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
380typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
381#define __DEFINED_mtx_t
382#endif
383
384#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
385typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
386#define __DEFINED_pthread_cond_t
387#endif
388
389#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
390typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
391#define __DEFINED_cnd_t
392#endif
393
394#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
395typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
396#define __DEFINED_pthread_rwlock_t
397#endif
398
399#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
400typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
401#define __DEFINED_pthread_barrier_t
402#endif
403
404
399#undef _Addr405#undef _Addr
400#undef _Int64406#undef _Int64
401#undef _Reg407#undef _Reg
\ No newline at end of file
lib/libc/include/riscv64-linux-musl/bits/reg.h deleted-8
...@@ -1,8 +0,0 @@
1#undef __WORDSIZE
2#define __WORDSIZE 64
3#define REG_PC 0
4#define REG_RA 1
5#define REG_SP 2
6#define REG_TP 4
7#define REG_S0 8
8#define REG_A0 10
\ No newline at end of file
lib/libc/include/riscv64-linux-musl/bits/signal.h+9
...@@ -35,6 +35,15 @@ typedef struct mcontext_t {...@@ -35,6 +35,15 @@ typedef struct mcontext_t {
35 union __riscv_mc_fp_state __fpregs;35 union __riscv_mc_fp_state __fpregs;
36} mcontext_t;36} mcontext_t;
3737
38#if defined(_GNU_SOURCE)
39#define REG_PC 0
40#define REG_RA 1
41#define REG_SP 2
42#define REG_TP 4
43#define REG_S0 8
44#define REG_A0 10
45#endif
46
38#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)47#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
39typedef unsigned long greg_t;48typedef unsigned long greg_t;
40typedef unsigned long gregset_t[32];49typedef unsigned long gregset_t[32];
lib/libc/include/riscv64-linux-musl/bits/socket.h deleted-19
...@@ -1,19 +0,0 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7 int msg_iovlen, __pad1;
8 void *msg_control;
9 socklen_t msg_controllen;
10 int __pad2;
11 int msg_flags;
12};
13
14struct cmsghdr {
15 socklen_t cmsg_len;
16 int __pad1;
17 int cmsg_level;
18 int cmsg_type;
19};
\ No newline at end of file
lib/libc/include/riscv64-linux-musl/bits/syscall.h+4
...@@ -287,6 +287,8 @@...@@ -287,6 +287,8 @@
287#define __NR_fsconfig 431287#define __NR_fsconfig 431
288#define __NR_fsmount 432288#define __NR_fsmount 432
289#define __NR_fspick 433289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
291#define __NR_sysriscv __NR_arch_specific_syscall293#define __NR_sysriscv __NR_arch_specific_syscall
292#define __NR_riscv_flush_icache (__NR_sysriscv + 15)294#define __NR_riscv_flush_icache (__NR_sysriscv + 15)
...@@ -579,5 +581,7 @@...@@ -579,5 +581,7 @@
579#define SYS_fsconfig 431581#define SYS_fsconfig 431
580#define SYS_fsmount 432582#define SYS_fsmount 432
581#define SYS_fspick 433583#define SYS_fspick 433
584#define SYS_pidfd_open 434
585#define SYS_clone3 435
582#define SYS_sysriscv __NR_arch_specific_syscall586#define SYS_sysriscv __NR_arch_specific_syscall
583#define SYS_riscv_flush_icache (__NR_sysriscv + 15)587#define SYS_riscv_flush_icache (__NR_sysriscv + 15)
\ No newline at end of file
lib/libc/include/s390x-linux-musl/bits/alltypes.h+63-57
...@@ -2,16 +2,8 @@...@@ -2,16 +2,8 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)5#define __BYTE_ORDER 4321
6typedef __builtin_va_list va_list;6#define __LONG_MAX 0x7fffffffffffffffL
7#define __DEFINED_va_list
8#endif
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif
14
157
16#ifndef __cplusplus8#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)9#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -37,52 +29,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -37,52 +29,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
37#define __DEFINED_max_align_t29#define __DEFINED_max_align_t
38#endif30#endif
3931
4032#define __LITTLE_ENDIAN 1234
41#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)33#define __BIG_ENDIAN 4321
42typedef long time_t;34#define __USE_TIME_BITS64 1
43#define __DEFINED_time_t
44#endif
45
46#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
47typedef long suseconds_t;
48#define __DEFINED_suseconds_t
49#endif
50
51
52#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
53typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
54#define __DEFINED_pthread_attr_t
55#endif
56
57#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
58typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
59#define __DEFINED_pthread_mutex_t
60#endif
61
62#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
63typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
64#define __DEFINED_mtx_t
65#endif
66
67#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
68typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
69#define __DEFINED_pthread_cond_t
70#endif
71
72#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
73typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
74#define __DEFINED_cnd_t
75#endif
76
77#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
78typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
79#define __DEFINED_pthread_rwlock_t
80#endif
81
82#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
83typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
84#define __DEFINED_pthread_barrier_t
85#endif
8635
87#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)36#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
88typedef unsigned _Addr size_t;37typedef unsigned _Addr size_t;
...@@ -119,6 +68,16 @@ typedef _Reg register_t;...@@ -119,6 +68,16 @@ typedef _Reg register_t;
119#define __DEFINED_register_t68#define __DEFINED_register_t
120#endif69#endif
12170
71#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
72typedef _Int64 time_t;
73#define __DEFINED_time_t
74#endif
75
76#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
77typedef _Int64 suseconds_t;
78#define __DEFINED_suseconds_t
79#endif
80
12281
123#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)82#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
124typedef signed char int8_t;83typedef signed char int8_t;
...@@ -254,7 +213,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -254,7 +213,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254#endif213#endif
255214
256#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)215#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
257struct timespec { time_t tv_sec; long tv_nsec; };216struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
258#define __DEFINED_struct_timespec217#define __DEFINED_struct_timespec
259#endif218#endif
260219
...@@ -350,6 +309,17 @@ typedef struct _IO_FILE FILE;...@@ -350,6 +309,17 @@ typedef struct _IO_FILE FILE;
350#endif309#endif
351310
352311
312#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
313typedef __builtin_va_list va_list;
314#define __DEFINED_va_list
315#endif
316
317#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
318typedef __builtin_va_list __isoc_va_list;
319#define __DEFINED___isoc_va_list
320#endif
321
322
353#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)323#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;324typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355#define __DEFINED_mbstate_t325#define __DEFINED_mbstate_t
...@@ -385,6 +355,42 @@ typedef unsigned short sa_family_t;...@@ -385,6 +355,42 @@ typedef unsigned short sa_family_t;
385#endif355#endif
386356
387357
358#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
359typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
360#define __DEFINED_pthread_attr_t
361#endif
362
363#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
364typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
365#define __DEFINED_pthread_mutex_t
366#endif
367
368#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
369typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
370#define __DEFINED_mtx_t
371#endif
372
373#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
374typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
375#define __DEFINED_pthread_cond_t
376#endif
377
378#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
379typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
380#define __DEFINED_cnd_t
381#endif
382
383#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
384typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
385#define __DEFINED_pthread_rwlock_t
386#endif
387
388#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
389typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
390#define __DEFINED_pthread_barrier_t
391#endif
392
393
388#undef _Addr394#undef _Addr
389#undef _Int64395#undef _Int64
390#undef _Reg396#undef _Reg
\ No newline at end of file
lib/libc/include/s390x-linux-musl/bits/endian.h deleted-1
...@@ -1 +0,0 @@
1#define __BYTE_ORDER __BIG_ENDIAN
\ No newline at end of file
lib/libc/include/s390x-linux-musl/bits/limits.h+1-8
...@@ -1,8 +1 @@...@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define PAGESIZE 4096
4#define LONG_BIT 64
5#endif
6
7#define LONG_MAX 0x7fffffffffffffffL
8#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
1#define PAGESIZE 4096
\ No newline at end of file
lib/libc/include/s390x-linux-musl/bits/socket.h deleted-17
...@@ -1,17 +0,0 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int __pad1, msg_iovlen;
6 void *msg_control;
7 int __pad2;
8 socklen_t msg_controllen;
9 int msg_flags;
10};
11
12struct cmsghdr {
13 int __pad1;
14 socklen_t cmsg_len;
15 int cmsg_level;
16 int cmsg_type;
17};
\ No newline at end of file
lib/libc/include/s390x-linux-musl/bits/syscall.h+5-1
...@@ -350,6 +350,8 @@...@@ -350,6 +350,8 @@
350#define __NR_fsconfig 431350#define __NR_fsconfig 431
351#define __NR_fsmount 432351#define __NR_fsmount 432
352#define __NR_fspick 433352#define __NR_fspick 433
353#define __NR_pidfd_open 434
354#define __NR_clone3 435
353355
354#define SYS_exit 1356#define SYS_exit 1
355#define SYS_fork 2357#define SYS_fork 2
...@@ -702,4 +704,6 @@...@@ -702,4 +704,6 @@
702#define SYS_fsopen 430704#define SYS_fsopen 430
703#define SYS_fsconfig 431705#define SYS_fsconfig 431
704#define SYS_fsmount 432706#define SYS_fsmount 432
705#define SYS_fspick 433
\ No newline at end of file
707#define SYS_fspick 433
708#define SYS_pidfd_open 434
709#define SYS_clone3 435
\ No newline at end of file
lib/libc/include/x86_64-linux-musl/bits/alltypes.h+63-57
...@@ -2,16 +2,8 @@...@@ -2,16 +2,8 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)5#define __BYTE_ORDER 1234
6typedef __builtin_va_list va_list;6#define __LONG_MAX 0x7fffffffffffffffL
7#define __DEFINED_va_list
8#endif
9
10#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
11typedef __builtin_va_list __isoc_va_list;
12#define __DEFINED___isoc_va_list
13#endif
14
157
16#ifndef __cplusplus8#ifndef __cplusplus
17#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)9#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
...@@ -50,52 +42,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;...@@ -50,52 +42,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
50#define __DEFINED_max_align_t42#define __DEFINED_max_align_t
51#endif43#endif
5244
5345#define __LITTLE_ENDIAN 1234
54#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)46#define __BIG_ENDIAN 4321
55typedef long time_t;47#define __USE_TIME_BITS64 1
56#define __DEFINED_time_t
57#endif
58
59#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
60typedef long suseconds_t;
61#define __DEFINED_suseconds_t
62#endif
63
64
65#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
66typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
67#define __DEFINED_pthread_attr_t
68#endif
69
70#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
71typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
72#define __DEFINED_pthread_mutex_t
73#endif
74
75#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
76typedef struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
77#define __DEFINED_mtx_t
78#endif
79
80#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
81typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
82#define __DEFINED_pthread_cond_t
83#endif
84
85#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
86typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
87#define __DEFINED_cnd_t
88#endif
89
90#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
91typedef struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
92#define __DEFINED_pthread_rwlock_t
93#endif
94
95#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
96typedef struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
97#define __DEFINED_pthread_barrier_t
98#endif
9948
100#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)49#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
101typedef unsigned _Addr size_t;50typedef unsigned _Addr size_t;
...@@ -132,6 +81,16 @@ typedef _Reg register_t;...@@ -132,6 +81,16 @@ typedef _Reg register_t;
132#define __DEFINED_register_t81#define __DEFINED_register_t
133#endif82#endif
13483
84#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
85typedef _Int64 time_t;
86#define __DEFINED_time_t
87#endif
88
89#if defined(__NEED_suseconds_t) && !defined(__DEFINED_suseconds_t)
90typedef _Int64 suseconds_t;
91#define __DEFINED_suseconds_t
92#endif
93
13594
136#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)95#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
137typedef signed char int8_t;96typedef signed char int8_t;
...@@ -267,7 +226,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };...@@ -267,7 +226,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
267#endif226#endif
268227
269#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)228#if defined(__NEED_struct_timespec) && !defined(__DEFINED_struct_timespec)
270struct timespec { time_t tv_sec; long tv_nsec; };229struct timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
271#define __DEFINED_struct_timespec230#define __DEFINED_struct_timespec
272#endif231#endif
273232
...@@ -363,6 +322,17 @@ typedef struct _IO_FILE FILE;...@@ -363,6 +322,17 @@ typedef struct _IO_FILE FILE;
363#endif322#endif
364323
365324
325#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
326typedef __builtin_va_list va_list;
327#define __DEFINED_va_list
328#endif
329
330#if defined(__NEED___isoc_va_list) && !defined(__DEFINED___isoc_va_list)
331typedef __builtin_va_list __isoc_va_list;
332#define __DEFINED___isoc_va_list
333#endif
334
335
366#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)336#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
367typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;337typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
368#define __DEFINED_mbstate_t338#define __DEFINED_mbstate_t
...@@ -398,6 +368,42 @@ typedef unsigned short sa_family_t;...@@ -398,6 +368,42 @@ typedef unsigned short sa_family_t;
398#endif368#endif
399369
400370
371#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
372typedef struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
373#define __DEFINED_pthread_attr_t
374#endif
375
376#if defined(__NEED_pthread_mutex_t) && !defined(__DEFINED_pthread_mutex_t)
377typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
378#define __DEFINED_pthread_mutex_t
379#endif
380
381#if defined(__NEED_mtx_t) && !defined(__DEFINED_mtx_t)
382typedef struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
383#define __DEFINED_mtx_t
384#endif
385
386#if defined(__NEED_pthread_cond_t) && !defined(__DEFINED_pthread_cond_t)
387typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
388#define __DEFINED_pthread_cond_t
389#endif
390
391#if defined(__NEED_cnd_t) && !defined(__DEFINED_cnd_t)
392typedef struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
393#define __DEFINED_cnd_t
394#endif
395
396#if defined(__NEED_pthread_rwlock_t) && !defined(__DEFINED_pthread_rwlock_t)
397typedef struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
398#define __DEFINED_pthread_rwlock_t
399#endif
400
401#if defined(__NEED_pthread_barrier_t) && !defined(__DEFINED_pthread_barrier_t)
402typedef struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
403#define __DEFINED_pthread_barrier_t
404#endif
405
406
401#undef _Addr407#undef _Addr
402#undef _Int64408#undef _Int64
403#undef _Reg409#undef _Reg
\ No newline at end of file
lib/libc/include/x86_64-linux-musl/bits/limits.h+1-8
...@@ -1,8 +1 @@...@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define PAGESIZE 4096
4#define LONG_BIT 64
5#endif
6
7#define LONG_MAX 0x7fffffffffffffffL
8#define LLONG_MAX 0x7fffffffffffffffLL
\ No newline at end of file
1#define PAGESIZE 4096
\ No newline at end of file
lib/libc/include/x86_64-linux-musl/bits/socket.h deleted-16
...@@ -1,16 +0,0 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen, __pad1;
6 void *msg_control;
7 socklen_t msg_controllen, __pad2;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int __pad1;
14 int cmsg_level;
15 int cmsg_type;
16};
\ No newline at end of file
lib/libc/include/x86_64-linux-musl/bits/syscall.h+5-1
...@@ -343,6 +343,8 @@...@@ -343,6 +343,8 @@
343#define __NR_fsconfig 431343#define __NR_fsconfig 431
344#define __NR_fsmount 432344#define __NR_fsmount 432
345#define __NR_fspick 433345#define __NR_fspick 433
346#define __NR_pidfd_open 434
347#define __NR_clone3 435
346348
347#define SYS_read 0349#define SYS_read 0
348#define SYS_write 1350#define SYS_write 1
...@@ -688,4 +690,6 @@...@@ -688,4 +690,6 @@
688#define SYS_fsopen 430690#define SYS_fsopen 430
689#define SYS_fsconfig 431691#define SYS_fsconfig 431
690#define SYS_fsmount 432692#define SYS_fsmount 432
691#define SYS_fspick 433
\ No newline at end of file
693#define SYS_fspick 433
694#define SYS_pidfd_open 434
695#define SYS_clone3 435
\ No newline at end of file
lib/libc/musl/COPYRIGHT+2-2
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1musl as a whole is licensed under the following standard MIT license:1musl as a whole is licensed under the following standard MIT license:
22
3----------------------------------------------------------------------3----------------------------------------------------------------------
4Copyright © 2005-2019 Rich Felker, et al.4Copyright © 2005-2020 Rich Felker, et al.
55
6Permission is hereby granted, free of charge, to any person obtaining6Permission is hereby granted, free of charge, to any person obtaining
7a copy of this software and associated documentation files (the7a copy of this software and associated documentation files (the
...@@ -26,6 +26,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE....@@ -26,6 +26,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26Authors/contributors include:26Authors/contributors include:
2727
28A. Wilcox28A. Wilcox
29Ada Worcester
29Alex Dowad30Alex Dowad
30Alex Suykov31Alex Suykov
31Alexander Monakov32Alexander Monakov
...@@ -65,7 +66,6 @@ Jeremy Huntwork...@@ -65,7 +66,6 @@ Jeremy Huntwork
65Jo-Philipp Wich66Jo-Philipp Wich
66Joakim Sindholt67Joakim Sindholt
67John Spencer68John Spencer
68Josiah Worcester
69Julien Ramseier69Julien Ramseier
70Justin Cormack70Justin Cormack
71Kaarle Ritvanen71Kaarle Ritvanen
lib/libc/musl/arch/aarch64/bits/alltypes.h.in+7-13
...@@ -2,8 +2,13 @@...@@ -2,8 +2,13 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;5#if __AARCH64EB__
6TYPEDEF __builtin_va_list __isoc_va_list;6#define __BYTE_ORDER 4321
7#else
8#define __BYTE_ORDER 1234
9#endif
10
11#define __LONG_MAX 0x7fffffffffffffffL
712
8#ifndef __cplusplus13#ifndef __cplusplus
9TYPEDEF unsigned wchar_t;14TYPEDEF unsigned wchar_t;
...@@ -17,14 +22,3 @@ TYPEDEF float float_t;...@@ -17,14 +22,3 @@ TYPEDEF float float_t;
17TYPEDEF double double_t;22TYPEDEF double double_t;
1823
19TYPEDEF struct { long long __ll; long double __ld; } max_align_t;24TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
20
21TYPEDEF long time_t;
22TYPEDEF long suseconds_t;
23
24TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
25TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
26TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
27TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
28TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
29TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
30TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/aarch64/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if __AARCH64EB__
2#define __BYTE_ORDER __BIG_ENDIAN
3#else
4#define __BYTE_ORDER __LITTLE_ENDIAN
5#endif
lib/libc/musl/arch/aarch64/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 64
4#endif
5
6#define LONG_MAX 0x7fffffffffffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/aarch64/bits/socket.h deleted-33
...@@ -1,33 +0,0 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7#if __BYTE_ORDER == __BIG_ENDIAN
8 int __pad1, msg_iovlen;
9#else
10 int msg_iovlen, __pad1;
11#endif
12 void *msg_control;
13#if __BYTE_ORDER == __BIG_ENDIAN
14 int __pad2;
15 socklen_t msg_controllen;
16#else
17 socklen_t msg_controllen;
18 int __pad2;
19#endif
20 int msg_flags;
21};
22
23struct cmsghdr {
24#if __BYTE_ORDER == __BIG_ENDIAN
25 int __pad1;
26 socklen_t cmsg_len;
27#else
28 socklen_t cmsg_len;
29 int __pad1;
30#endif
31 int cmsg_level;
32 int cmsg_type;
33};
lib/libc/musl/arch/aarch64/bits/syscall.h.in+2
...@@ -287,4 +287,6 @@...@@ -287,4 +287,6 @@
287#define __NR_fsconfig 431287#define __NR_fsconfig 431
288#define __NR_fsmount 432288#define __NR_fsmount 432
289#define __NR_fspick 433289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
lib/libc/musl/arch/aarch64/reloc.h-2
...@@ -1,5 +1,3 @@...@@ -1,5 +1,3 @@
1#include <endian.h>
2
3#if __BYTE_ORDER == __BIG_ENDIAN1#if __BYTE_ORDER == __BIG_ENDIAN
4#define ENDIAN_SUFFIX "_be"2#define ENDIAN_SUFFIX "_be"
5#else3#else
lib/libc/musl/arch/arm/bits/alltypes.h.in+8-13
...@@ -1,9 +1,15 @@...@@ -1,9 +1,15 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5TYPEDEF __builtin_va_list va_list;6#if __ARMEB__
6TYPEDEF __builtin_va_list __isoc_va_list;7#define __BYTE_ORDER 4321
8#else
9#define __BYTE_ORDER 1234
10#endif
11
12#define __LONG_MAX 0x7fffffffL
713
8#ifndef __cplusplus14#ifndef __cplusplus
9TYPEDEF unsigned wchar_t;15TYPEDEF unsigned wchar_t;
...@@ -13,14 +19,3 @@ TYPEDEF float float_t;...@@ -13,14 +19,3 @@ TYPEDEF float float_t;
13TYPEDEF double double_t;19TYPEDEF double double_t;
1420
15TYPEDEF struct { long long __ll; long double __ld; } max_align_t;21TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
16
17TYPEDEF long time_t;
18TYPEDEF long suseconds_t;
19
20TYPEDEF struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
21TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
22TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
23TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
24TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
25TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
26TYPEDEF struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/arm/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if __ARMEB__
2#define __BYTE_ORDER __BIG_ENDIAN
3#else
4#define __BYTE_ORDER __LITTLE_ENDIAN
5#endif
lib/libc/musl/arch/arm/bits/ipcstat.h+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1#define IPC_STAT 21#define IPC_STAT 0x102
lib/libc/musl/arch/arm/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 32
4#endif
5
6#define LONG_MAX 0x7fffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/arm/bits/msg.h+9-6
...@@ -1,15 +1,18 @@...@@ -1,15 +1,18 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3 time_t msg_stime;3 unsigned long __msg_stime_lo;
4 int __unused1;4 unsigned long __msg_stime_hi;
5 time_t msg_rtime;5 unsigned long __msg_rtime_lo;
6 int __unused2;6 unsigned long __msg_rtime_hi;
7 time_t msg_ctime;7 unsigned long __msg_ctime_lo;
8 int __unused3;8 unsigned long __msg_ctime_hi;
9 unsigned long msg_cbytes;9 unsigned long msg_cbytes;
10 msgqnum_t msg_qnum;10 msgqnum_t msg_qnum;
11 msglen_t msg_qbytes;11 msglen_t msg_qbytes;
12 pid_t msg_lspid;12 pid_t msg_lspid;
13 pid_t msg_lrpid;13 pid_t msg_lrpid;
14 unsigned long __unused[2];14 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
15};18};
lib/libc/musl/arch/arm/bits/sem.h+6-4
...@@ -1,9 +1,9 @@...@@ -1,9 +1,9 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 time_t sem_otime;3 unsigned long __sem_otime_lo;
4 long __unused1;4 unsigned long __sem_otime_hi;
5 time_t sem_ctime;5 unsigned long __sem_ctime_lo;
6 long __unused2;6 unsigned long __sem_ctime_hi;
7#if __BYTE_ORDER == __LITTLE_ENDIAN7#if __BYTE_ORDER == __LITTLE_ENDIAN
8 unsigned short sem_nsems;8 unsigned short sem_nsems;
9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
...@@ -13,4 +13,6 @@ struct semid_ds {...@@ -13,4 +13,6 @@ struct semid_ds {
13#endif13#endif
14 long __unused3;14 long __unused3;
15 long __unused4;15 long __unused4;
16 time_t sem_otime;
17 time_t sem_ctime;
16};18};
lib/libc/musl/arch/arm/bits/shm.h+10-6
...@@ -3,17 +3,21 @@...@@ -3,17 +3,21 @@
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 size_t shm_segsz;5 size_t shm_segsz;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 int __unused1;7 unsigned long __shm_atime_hi;
8 time_t shm_dtime;8 unsigned long __shm_dtime_lo;
9 int __unused2;9 unsigned long __shm_dtime_hi;
10 time_t shm_ctime;10 unsigned long __shm_ctime_lo;
11 int __unused3;11 unsigned long __shm_ctime_hi;
12 pid_t shm_cpid;12 pid_t shm_cpid;
13 pid_t shm_lpid;13 pid_t shm_lpid;
14 unsigned long shm_nattch;14 unsigned long shm_nattch;
15 unsigned long __pad1;15 unsigned long __pad1;
16 unsigned long __pad2;16 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
17};21};
1822
19struct shminfo {23struct shminfo {
lib/libc/musl/arch/arm/bits/stat.h+5-1
...@@ -14,8 +14,12 @@ struct stat {...@@ -14,8 +14,12 @@ struct stat {
14 off_t st_size;14 off_t st_size;
15 blksize_t st_blksize;15 blksize_t st_blksize;
16 blkcnt_t st_blocks;16 blkcnt_t st_blocks;
17 struct {
18 long tv_sec;
19 long tv_nsec;
20 } __st_atim32, __st_mtim32, __st_ctim32;
21 ino_t st_ino;
17 struct timespec st_atim;22 struct timespec st_atim;
18 struct timespec st_mtim;23 struct timespec st_mtim;
19 struct timespec st_ctim;24 struct timespec st_ctim;
20 ino_t st_ino;
21};25};
lib/libc/musl/arch/arm/bits/syscall.h.in+12-10
...@@ -55,8 +55,8 @@...@@ -55,8 +55,8 @@
55#define __NR_sethostname 7455#define __NR_sethostname 74
56#define __NR_setrlimit 7556#define __NR_setrlimit 75
57#define __NR_getrusage 7757#define __NR_getrusage 77
58#define __NR_gettimeofday 7858#define __NR_gettimeofday_time32 78
59#define __NR_settimeofday 7959#define __NR_settimeofday_time32 79
60#define __NR_getgroups 8060#define __NR_getgroups 80
61#define __NR_setgroups 8161#define __NR_setgroups 81
62#define __NR_symlink 8362#define __NR_symlink 83
...@@ -211,14 +211,14 @@...@@ -211,14 +211,14 @@
211#define __NR_remap_file_pages 253211#define __NR_remap_file_pages 253
212#define __NR_set_tid_address 256212#define __NR_set_tid_address 256
213#define __NR_timer_create 257213#define __NR_timer_create 257
214#define __NR_timer_settime 258214#define __NR_timer_settime32 258
215#define __NR_timer_gettime 259215#define __NR_timer_gettime32 259
216#define __NR_timer_getoverrun 260216#define __NR_timer_getoverrun 260
217#define __NR_timer_delete 261217#define __NR_timer_delete 261
218#define __NR_clock_settime 262218#define __NR_clock_settime32 262
219#define __NR_clock_gettime 263219#define __NR_clock_gettime32 263
220#define __NR_clock_getres 264220#define __NR_clock_getres_time32 264
221#define __NR_clock_nanosleep 265221#define __NR_clock_nanosleep_time32 265
222#define __NR_statfs64 266222#define __NR_statfs64 266
223#define __NR_fstatfs64 267223#define __NR_fstatfs64 267
224#define __NR_tgkill 268224#define __NR_tgkill 268
...@@ -308,8 +308,8 @@...@@ -308,8 +308,8 @@
308#define __NR_timerfd_create 350308#define __NR_timerfd_create 350
309#define __NR_eventfd 351309#define __NR_eventfd 351
310#define __NR_fallocate 352310#define __NR_fallocate 352
311#define __NR_timerfd_settime 353311#define __NR_timerfd_settime32 353
312#define __NR_timerfd_gettime 354312#define __NR_timerfd_gettime32 354
313#define __NR_signalfd4 355313#define __NR_signalfd4 355
314#define __NR_eventfd2 356314#define __NR_eventfd2 356
315#define __NR_epoll_create1 357315#define __NR_epoll_create1 357
...@@ -387,6 +387,8 @@...@@ -387,6 +387,8 @@
387#define __NR_fsconfig 431387#define __NR_fsconfig 431
388#define __NR_fsmount 432388#define __NR_fsmount 432
389#define __NR_fspick 433389#define __NR_fspick 433
390#define __NR_pidfd_open 434
391#define __NR_clone3 435
390392
391#define __ARM_NR_breakpoint 0x0f0001393#define __ARM_NR_breakpoint 0x0f0001
392#define __ARM_NR_cacheflush 0x0f0002394#define __ARM_NR_cacheflush 0x0f0002
lib/libc/musl/arch/arm/reloc.h-2
...@@ -1,5 +1,3 @@...@@ -1,5 +1,3 @@
1#include <endian.h>
2
3#if __BYTE_ORDER == __BIG_ENDIAN1#if __BYTE_ORDER == __BIG_ENDIAN
4#define ENDIAN_SUFFIX "eb"2#define ENDIAN_SUFFIX "eb"
5#else3#else
lib/libc/musl/arch/arm/syscall_arch.h+3-1
...@@ -99,7 +99,9 @@ static inline long __syscall6(long n, long a, long b, long c, long d, long e, lo...@@ -99,7 +99,9 @@ static inline long __syscall6(long n, long a, long b, long c, long d, long e, lo
99}99}
100100
101#define VDSO_USEFUL101#define VDSO_USEFUL
102#define VDSO_CGT_SYM "__vdso_clock_gettime"102#define VDSO_CGT32_SYM "__vdso_clock_gettime"
103#define VDSO_CGT32_VER "LINUX_2.6"
104#define VDSO_CGT_SYM "__vdso_clock_gettime64"
103#define VDSO_CGT_VER "LINUX_2.6"105#define VDSO_CGT_VER "LINUX_2.6"
104106
105#define SYSCALL_FADVISE_6_ARG107#define SYSCALL_FADVISE_6_ARG
lib/libc/musl/arch/generic/bits/dirent.h created+11
...@@ -0,0 +1,11 @@
1#define _DIRENT_HAVE_D_RECLEN
2#define _DIRENT_HAVE_D_OFF
3#define _DIRENT_HAVE_D_TYPE
4
5struct dirent {
6 ino_t d_ino;
7 off_t d_off;
8 unsigned short d_reclen;
9 unsigned char d_type;
10 char d_name[256];
11};
lib/libc/musl/arch/generic/bits/ioctl.h+5
...@@ -104,7 +104,12 @@...@@ -104,7 +104,12 @@
104#define FIOGETOWN 0x8903104#define FIOGETOWN 0x8903
105#define SIOCGPGRP 0x8904105#define SIOCGPGRP 0x8904
106#define SIOCATMARK 0x8905106#define SIOCATMARK 0x8905
107#if __LONG_MAX == 0x7fffffff
108#define SIOCGSTAMP _IOR(0x89, 6, char[16])
109#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
110#else
107#define SIOCGSTAMP 0x8906111#define SIOCGSTAMP 0x8906
108#define SIOCGSTAMPNS 0x8907112#define SIOCGSTAMPNS 0x8907
113#endif
109114
110#include <bits/ioctl_fix.h>115#include <bits/ioctl_fix.h>
lib/libc/musl/arch/generic/bits/limits.h created
lib/libc/musl/arch/generic/bits/socket.h-15
...@@ -1,15 +0,0 @@...@@ -1,15 +0,0 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen;
6 void *msg_control;
7 socklen_t msg_controllen;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int cmsg_level;
14 int cmsg_type;
15};
lib/libc/musl/arch/i386/bits/alltypes.h.in+3-18
...@@ -1,14 +1,10 @@...@@ -1,14 +1,10 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5#if __GNUC__ >= 36#define __BYTE_ORDER 1234
6TYPEDEF __builtin_va_list va_list;7#define __LONG_MAX 0x7fffffffL
7TYPEDEF __builtin_va_list __isoc_va_list;
8#else
9TYPEDEF struct __va_list * va_list;
10TYPEDEF struct __va_list * __isoc_va_list;
11#endif
128
13#ifndef __cplusplus9#ifndef __cplusplus
14#ifdef __WCHAR_TYPE__10#ifdef __WCHAR_TYPE__
...@@ -33,14 +29,3 @@ TYPEDEF struct { __attribute__((__aligned__(8))) long long __ll; long double __l...@@ -33,14 +29,3 @@ TYPEDEF struct { __attribute__((__aligned__(8))) long long __ll; long double __l
33#else29#else
34TYPEDEF struct { alignas(8) long long __ll; long double __ld; } max_align_t;30TYPEDEF struct { alignas(8) long long __ll; long double __ld; } max_align_t;
35#endif31#endif
36
37TYPEDEF long time_t;
38TYPEDEF long suseconds_t;
39
40TYPEDEF struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
41TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
42TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
43TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
44TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
45TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
46TYPEDEF struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/i386/bits/endian.h deleted-1
...@@ -1 +0,0 @@
1#define __BYTE_ORDER __LITTLE_ENDIAN
lib/libc/musl/arch/i386/bits/ipcstat.h+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1#define IPC_STAT 21#define IPC_STAT 0x102
lib/libc/musl/arch/i386/bits/limits.h-7
...@@ -1,8 +1 @@...@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define PAGESIZE 40961#define PAGESIZE 4096
4#define LONG_BIT 32
5#endif
6
7#define LONG_MAX 0x7fffffffL
8#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/i386/bits/msg.h+9-6
...@@ -1,15 +1,18 @@...@@ -1,15 +1,18 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3 time_t msg_stime;3 unsigned long __msg_stime_lo;
4 int __unused1;4 unsigned long __msg_stime_hi;
5 time_t msg_rtime;5 unsigned long __msg_rtime_lo;
6 int __unused2;6 unsigned long __msg_rtime_hi;
7 time_t msg_ctime;7 unsigned long __msg_ctime_lo;
8 int __unused3;8 unsigned long __msg_ctime_hi;
9 unsigned long msg_cbytes;9 unsigned long msg_cbytes;
10 msgqnum_t msg_qnum;10 msgqnum_t msg_qnum;
11 msglen_t msg_qbytes;11 msglen_t msg_qbytes;
12 pid_t msg_lspid;12 pid_t msg_lspid;
13 pid_t msg_lrpid;13 pid_t msg_lrpid;
14 unsigned long __unused[2];14 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
15};18};
lib/libc/musl/arch/i386/bits/sem.h+6-4
...@@ -1,11 +1,13 @@...@@ -1,11 +1,13 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 time_t sem_otime;3 unsigned long __sem_otime_lo;
4 long __unused1;4 unsigned long __sem_otime_hi;
5 time_t sem_ctime;5 unsigned long __sem_ctime_lo;
6 long __unused2;6 unsigned long __sem_ctime_hi;
7 unsigned short sem_nsems;7 unsigned short sem_nsems;
8 char __sem_nsems_pad[sizeof(long)-sizeof(short)];8 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
9 long __unused3;9 long __unused3;
10 long __unused4;10 long __unused4;
11 time_t sem_otime;
12 time_t sem_ctime;
11};13};
lib/libc/musl/arch/i386/bits/shm.h+10-6
...@@ -3,17 +3,21 @@...@@ -3,17 +3,21 @@
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 size_t shm_segsz;5 size_t shm_segsz;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 int __unused1;7 unsigned long __shm_atime_hi;
8 time_t shm_dtime;8 unsigned long __shm_dtime_lo;
9 int __unused2;9 unsigned long __shm_dtime_hi;
10 time_t shm_ctime;10 unsigned long __shm_ctime_lo;
11 int __unused3;11 unsigned long __shm_ctime_hi;
12 pid_t shm_cpid;12 pid_t shm_cpid;
13 pid_t shm_lpid;13 pid_t shm_lpid;
14 unsigned long shm_nattch;14 unsigned long shm_nattch;
15 unsigned long __pad1;15 unsigned long __pad1;
16 unsigned long __pad2;16 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
17};21};
1822
19struct shminfo {23struct shminfo {
lib/libc/musl/arch/i386/bits/stat.h+5-1
...@@ -14,8 +14,12 @@ struct stat {...@@ -14,8 +14,12 @@ struct stat {
14 off_t st_size;14 off_t st_size;
15 blksize_t st_blksize;15 blksize_t st_blksize;
16 blkcnt_t st_blocks;16 blkcnt_t st_blocks;
17 struct {
18 long tv_sec;
19 long tv_nsec;
20 } __st_atim32, __st_mtim32, __st_ctim32;
21 ino_t st_ino;
17 struct timespec st_atim;22 struct timespec st_atim;
18 struct timespec st_mtim;23 struct timespec st_mtim;
19 struct timespec st_ctim;24 struct timespec st_ctim;
20 ino_t st_ino;
21};25};
lib/libc/musl/arch/i386/bits/syscall.h.in+12-10
...@@ -76,8 +76,8 @@...@@ -76,8 +76,8 @@
76#define __NR_setrlimit 7576#define __NR_setrlimit 75
77#define __NR_getrlimit 76 /* Back compatible 2Gig limited rlimit */77#define __NR_getrlimit 76 /* Back compatible 2Gig limited rlimit */
78#define __NR_getrusage 7778#define __NR_getrusage 77
79#define __NR_gettimeofday 7879#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday 7980#define __NR_settimeofday_time32 79
81#define __NR_getgroups 8081#define __NR_getgroups 80
82#define __NR_setgroups 8182#define __NR_setgroups 81
83#define __NR_select 8283#define __NR_select 82
...@@ -257,14 +257,14 @@...@@ -257,14 +257,14 @@
257#define __NR_remap_file_pages 257257#define __NR_remap_file_pages 257
258#define __NR_set_tid_address 258258#define __NR_set_tid_address 258
259#define __NR_timer_create 259259#define __NR_timer_create 259
260#define __NR_timer_settime (__NR_timer_create+1)260#define __NR_timer_settime32 (__NR_timer_create+1)
261#define __NR_timer_gettime (__NR_timer_create+2)261#define __NR_timer_gettime32 (__NR_timer_create+2)
262#define __NR_timer_getoverrun (__NR_timer_create+3)262#define __NR_timer_getoverrun (__NR_timer_create+3)
263#define __NR_timer_delete (__NR_timer_create+4)263#define __NR_timer_delete (__NR_timer_create+4)
264#define __NR_clock_settime (__NR_timer_create+5)264#define __NR_clock_settime32 (__NR_timer_create+5)
265#define __NR_clock_gettime (__NR_timer_create+6)265#define __NR_clock_gettime32 (__NR_timer_create+6)
266#define __NR_clock_getres (__NR_timer_create+7)266#define __NR_clock_getres_time32 (__NR_timer_create+7)
267#define __NR_clock_nanosleep (__NR_timer_create+8)267#define __NR_clock_nanosleep_time32 (__NR_timer_create+8)
268#define __NR_statfs64 268268#define __NR_statfs64 268
269#define __NR_fstatfs64 269269#define __NR_fstatfs64 269
270#define __NR_tgkill 270270#define __NR_tgkill 270
...@@ -322,8 +322,8 @@...@@ -322,8 +322,8 @@
322#define __NR_timerfd_create 322322#define __NR_timerfd_create 322
323#define __NR_eventfd 323323#define __NR_eventfd 323
324#define __NR_fallocate 324324#define __NR_fallocate 324
325#define __NR_timerfd_settime 325325#define __NR_timerfd_settime32 325
326#define __NR_timerfd_gettime 326326#define __NR_timerfd_gettime32 326
327#define __NR_signalfd4 327327#define __NR_signalfd4 327
328#define __NR_eventfd2 328328#define __NR_eventfd2 328
329#define __NR_epoll_create1 329329#define __NR_epoll_create1 329
...@@ -424,4 +424,6 @@...@@ -424,4 +424,6 @@
424#define __NR_fsconfig 431424#define __NR_fsconfig 431
425#define __NR_fsmount 432425#define __NR_fsmount 432
426#define __NR_fspick 433426#define __NR_fspick 433
427#define __NR_pidfd_open 434
428#define __NR_clone3 435
427429
lib/libc/musl/arch/i386/syscall_arch.h+3-1
...@@ -83,7 +83,9 @@ static inline long __syscall6(long n, long a1, long a2, long a3, long a4, long a...@@ -83,7 +83,9 @@ static inline long __syscall6(long n, long a1, long a2, long a3, long a4, long a
83}83}
8484
85#define VDSO_USEFUL85#define VDSO_USEFUL
86#define VDSO_CGT_SYM "__vdso_clock_gettime"86#define VDSO_CGT32_SYM "__vdso_clock_gettime"
87#define VDSO_CGT32_VER "LINUX_2.6"
88#define VDSO_CGT_SYM "__vdso_clock_gettime64"
87#define VDSO_CGT_VER "LINUX_2.6"89#define VDSO_CGT_VER "LINUX_2.6"
8890
89#define SYSCALL_USE_SOCKETCALL91#define SYSCALL_USE_SOCKETCALL
lib/libc/musl/arch/mips/bits/alltypes.h.in+8-13
...@@ -1,9 +1,15 @@...@@ -1,9 +1,15 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5TYPEDEF __builtin_va_list va_list;6#if _MIPSEL || __MIPSEL || __MIPSEL__
6TYPEDEF __builtin_va_list __isoc_va_list;7#define __BYTE_ORDER 1234
8#else
9#define __BYTE_ORDER 4321
10#endif
11
12#define __LONG_MAX 0x7fffffffL
713
8#ifndef __cplusplus14#ifndef __cplusplus
9TYPEDEF int wchar_t;15TYPEDEF int wchar_t;
...@@ -13,14 +19,3 @@ TYPEDEF float float_t;...@@ -13,14 +19,3 @@ TYPEDEF float float_t;
13TYPEDEF double double_t;19TYPEDEF double double_t;
1420
15TYPEDEF struct { long long __ll; long double __ld; } max_align_t;21TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
16
17TYPEDEF long time_t;
18TYPEDEF long suseconds_t;
19
20TYPEDEF struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
21TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
22TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
23TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
24TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
25TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
26TYPEDEF struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/mips/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if _MIPSEL || __MIPSEL || __MIPSEL__
2#define __BYTE_ORDER __LITTLE_ENDIAN
3#else
4#define __BYTE_ORDER __BIG_ENDIAN
5#endif
lib/libc/musl/arch/mips/bits/hwcap.h+11
...@@ -1,3 +1,14 @@...@@ -1,3 +1,14 @@
1#define HWCAP_MIPS_R6 (1 << 0)1#define HWCAP_MIPS_R6 (1 << 0)
2#define HWCAP_MIPS_MSA (1 << 1)2#define HWCAP_MIPS_MSA (1 << 1)
3#define HWCAP_MIPS_CRC32 (1 << 2)3#define HWCAP_MIPS_CRC32 (1 << 2)
4#define HWCAP_MIPS_MIPS16 (1 << 3)
5#define HWCAP_MIPS_MDMX (1 << 4)
6#define HWCAP_MIPS_MIPS3D (1 << 5)
7#define HWCAP_MIPS_SMARTMIPS (1 << 6)
8#define HWCAP_MIPS_DSP (1 << 7)
9#define HWCAP_MIPS_DSP2 (1 << 8)
10#define HWCAP_MIPS_DSP3 (1 << 9)
11#define HWCAP_MIPS_MIPS16E2 (1 << 10)
12#define HWCAP_LOONGSON_MMI (1 << 11)
13#define HWCAP_LOONGSON_EXT (1 << 12)
14#define HWCAP_LOONGSON_EXT2 (1 << 13)
lib/libc/musl/arch/mips/bits/ioctl.h+2-2
...@@ -110,5 +110,5 @@...@@ -110,5 +110,5 @@
110#define SIOCATMARK _IOR('s', 7, int)110#define SIOCATMARK _IOR('s', 7, int)
111#define SIOCSPGRP _IOW('s', 8, pid_t)111#define SIOCSPGRP _IOW('s', 8, pid_t)
112#define SIOCGPGRP _IOR('s', 9, pid_t)112#define SIOCGPGRP _IOR('s', 9, pid_t)
113#define SIOCGSTAMP 0x8906113#define SIOCGSTAMP _IOR(0x89, 6, char[16])
114#define SIOCGSTAMPNS 0x8907114#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
lib/libc/musl/arch/mips/bits/ipcstat.h+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1#define IPC_STAT 21#define IPC_STAT 0x102
lib/libc/musl/arch/mips/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 32
4#endif
5
6#define LONG_MAX 0x7fffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/mips/bits/msg.h+15-12
...@@ -1,19 +1,19 @@...@@ -1,19 +1,19 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3#if _MIPSEL || __MIPSEL || __MIPSEL__3#if _MIPSEL || __MIPSEL || __MIPSEL__
4 time_t msg_stime;4 unsigned long __msg_stime_lo;
5 int __unused1;5 unsigned long __msg_stime_hi;
6 time_t msg_rtime;6 unsigned long __msg_rtime_lo;
7 int __unused2;7 unsigned long __msg_rtime_hi;
8 time_t msg_ctime;8 unsigned long __msg_ctime_lo;
9 int __unused3;9 unsigned long __msg_ctime_hi;
10#else10#else
11 int __unused1;11 unsigned long __msg_stime_hi;
12 time_t msg_stime;12 unsigned long __msg_stime_lo;
13 int __unused2;13 unsigned long __msg_rtime_hi;
14 time_t msg_rtime;14 unsigned long __msg_rtime_lo;
15 int __unused3;15 unsigned long __msg_ctime_hi;
16 time_t msg_ctime;16 unsigned long __msg_ctime_lo;
17#endif17#endif
18 unsigned long msg_cbytes;18 unsigned long msg_cbytes;
19 msgqnum_t msg_qnum;19 msgqnum_t msg_qnum;
...@@ -21,4 +21,7 @@ struct msqid_ds {...@@ -21,4 +21,7 @@ struct msqid_ds {
21 pid_t msg_lspid;21 pid_t msg_lspid;
22 pid_t msg_lrpid;22 pid_t msg_lrpid;
23 unsigned long __unused[2];23 unsigned long __unused[2];
24 time_t msg_stime;
25 time_t msg_rtime;
26 time_t msg_ctime;
24};27};
lib/libc/musl/arch/mips/bits/sem.h+6-4
...@@ -1,7 +1,7 @@...@@ -1,7 +1,7 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 time_t sem_otime;3 unsigned long __sem_otime_lo;
4 time_t sem_ctime;4 unsigned long __sem_ctime_lo;
5#if __BYTE_ORDER == __LITTLE_ENDIAN5#if __BYTE_ORDER == __LITTLE_ENDIAN
6 unsigned short sem_nsems;6 unsigned short sem_nsems;
7 char __sem_nsems_pad[sizeof(long)-sizeof(short)];7 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
...@@ -9,6 +9,8 @@ struct semid_ds {...@@ -9,6 +9,8 @@ struct semid_ds {
9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];9 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
10 unsigned short sem_nsems;10 unsigned short sem_nsems;
11#endif11#endif
12 long __unused3;12 unsigned long __sem_otime_hi;
13 long __unused4;13 unsigned long __sem_ctime_hi;
14 time_t sem_otime;
15 time_t sem_ctime;
14};16};
lib/libc/musl/arch/mips/bits/shm.h+10-5
...@@ -3,14 +3,19 @@...@@ -3,14 +3,19 @@
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 size_t shm_segsz;5 size_t shm_segsz;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 time_t shm_dtime;7 unsigned long __shm_dtime_lo;
8 time_t shm_ctime;8 unsigned long __shm_ctime_lo;
9 pid_t shm_cpid;9 pid_t shm_cpid;
10 pid_t shm_lpid;10 pid_t shm_lpid;
11 unsigned long shm_nattch;11 unsigned long shm_nattch;
12 unsigned long __pad1;12 unsigned short __shm_atime_hi;
13 unsigned long __pad2;13 unsigned short __shm_dtime_hi;
14 unsigned short __shm_ctime_hi;
15 unsigned short __pad1;
16 time_t shm_atime;
17 time_t shm_dtime;
18 time_t shm_ctime;
14};19};
1520
16struct shminfo {21struct shminfo {
lib/libc/musl/arch/mips/bits/signal.h+6-2
...@@ -19,14 +19,18 @@ typedef struct {...@@ -19,14 +19,18 @@ typedef struct {
19} fpregset_t;19} fpregset_t;
20struct sigcontext {20struct sigcontext {
21 unsigned sc_regmask, sc_status;21 unsigned sc_regmask, sc_status;
22 unsigned long long sc_pc, sc_regs[32], sc_fpregs[32];22 unsigned long long sc_pc;
23 gregset_t sc_regs;
24 fpregset_t sc_fpregs;
23 unsigned sc_ownedfp, sc_fpc_csr, sc_fpc_eir, sc_used_math, sc_dsp;25 unsigned sc_ownedfp, sc_fpc_csr, sc_fpc_eir, sc_used_math, sc_dsp;
24 unsigned long long sc_mdhi, sc_mdlo;26 unsigned long long sc_mdhi, sc_mdlo;
25 unsigned long sc_hi1, sc_lo1, sc_hi2, sc_lo2, sc_hi3, sc_lo3;27 unsigned long sc_hi1, sc_lo1, sc_hi2, sc_lo2, sc_hi3, sc_lo3;
26};28};
27typedef struct {29typedef struct {
28 unsigned regmask, status;30 unsigned regmask, status;
29 unsigned long long pc, gregs[32], fpregs[32];31 unsigned long long pc;
32 gregset_t gregs;
33 fpregset_t fpregs;
30 unsigned ownedfp, fpc_csr, fpc_eir, used_math, dsp;34 unsigned ownedfp, fpc_csr, fpc_eir, used_math, dsp;
31 unsigned long long mdhi, mdlo;35 unsigned long long mdhi, mdlo;
32 unsigned long hi1, lo1, hi2, lo2, hi3, lo3;36 unsigned long hi1, lo1, hi2, lo2, hi3, lo3;
lib/libc/musl/arch/mips/bits/socket.h-18
...@@ -1,19 +1,3 @@...@@ -1,19 +1,3 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen;
6 void *msg_control;
7 socklen_t msg_controllen;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int cmsg_level;
14 int cmsg_type;
15};
16
17#define SOCK_STREAM 21#define SOCK_STREAM 2
18#define SOCK_DGRAM 12#define SOCK_DGRAM 1
193
...@@ -32,8 +16,6 @@ struct cmsghdr {...@@ -32,8 +16,6 @@ struct cmsghdr {
32#define SO_RCVBUF 0x100216#define SO_RCVBUF 0x1002
33#define SO_SNDLOWAT 0x100317#define SO_SNDLOWAT 0x1003
34#define SO_RCVLOWAT 0x100418#define SO_RCVLOWAT 0x1004
35#define SO_RCVTIMEO 0x1006
36#define SO_SNDTIMEO 0x1005
37#define SO_ERROR 0x100719#define SO_ERROR 0x1007
38#define SO_TYPE 0x100820#define SO_TYPE 0x1008
39#define SO_ACCEPTCONN 0x100921#define SO_ACCEPTCONN 0x1009
lib/libc/musl/arch/mips/bits/stat.h+8-4
...@@ -12,11 +12,15 @@ struct stat {...@@ -12,11 +12,15 @@ struct stat {
12 dev_t st_rdev;12 dev_t st_rdev;
13 long __st_padding2[2];13 long __st_padding2[2];
14 off_t st_size;14 off_t st_size;
15 struct timespec st_atim;15 struct {
16 struct timespec st_mtim;16 long tv_sec;
17 struct timespec st_ctim;17 long tv_nsec;
18 } __st_atim32, __st_mtim32, __st_ctim32;
18 blksize_t st_blksize;19 blksize_t st_blksize;
19 long __st_padding3;20 long __st_padding3;
20 blkcnt_t st_blocks;21 blkcnt_t st_blocks;
21 long __st_padding4[14];22 struct timespec st_atim;
23 struct timespec st_mtim;
24 struct timespec st_ctim;
25 long __st_padding4[2];
22};26};
lib/libc/musl/arch/mips/bits/syscall.h.in+12-10
...@@ -76,8 +76,8 @@...@@ -76,8 +76,8 @@
76#define __NR_setrlimit 407576#define __NR_setrlimit 4075
77#define __NR_getrlimit 407677#define __NR_getrlimit 4076
78#define __NR_getrusage 407778#define __NR_getrusage 4077
79#define __NR_gettimeofday 407879#define __NR_gettimeofday_time32 4078
80#define __NR_settimeofday 407980#define __NR_settimeofday_time32 4079
81#define __NR_getgroups 408081#define __NR_getgroups 4080
82#define __NR_setgroups 408182#define __NR_setgroups 4081
83#define __NR_reserved82 408283#define __NR_reserved82 4082
...@@ -256,14 +256,14 @@...@@ -256,14 +256,14 @@
256#define __NR_statfs64 4255256#define __NR_statfs64 4255
257#define __NR_fstatfs64 4256257#define __NR_fstatfs64 4256
258#define __NR_timer_create 4257258#define __NR_timer_create 4257
259#define __NR_timer_settime 4258259#define __NR_timer_settime32 4258
260#define __NR_timer_gettime 4259260#define __NR_timer_gettime32 4259
261#define __NR_timer_getoverrun 4260261#define __NR_timer_getoverrun 4260
262#define __NR_timer_delete 4261262#define __NR_timer_delete 4261
263#define __NR_clock_settime 4262263#define __NR_clock_settime32 4262
264#define __NR_clock_gettime 4263264#define __NR_clock_gettime32 4263
265#define __NR_clock_getres 4264265#define __NR_clock_getres_time32 4264
266#define __NR_clock_nanosleep 4265266#define __NR_clock_nanosleep_time32 4265
267#define __NR_tgkill 4266267#define __NR_tgkill 4266
268#define __NR_utimes 4267268#define __NR_utimes 4267
269#define __NR_mbind 4268269#define __NR_mbind 4268
...@@ -319,8 +319,8 @@...@@ -319,8 +319,8 @@
319#define __NR_eventfd 4319319#define __NR_eventfd 4319
320#define __NR_fallocate 4320320#define __NR_fallocate 4320
321#define __NR_timerfd_create 4321321#define __NR_timerfd_create 4321
322#define __NR_timerfd_gettime 4322322#define __NR_timerfd_gettime32 4322
323#define __NR_timerfd_settime 4323323#define __NR_timerfd_settime32 4323
324#define __NR_signalfd4 4324324#define __NR_signalfd4 4324
325#define __NR_eventfd2 4325325#define __NR_eventfd2 4325
326#define __NR_epoll_create1 4326326#define __NR_epoll_create1 4326
...@@ -406,4 +406,6 @@...@@ -406,4 +406,6 @@
406#define __NR_fsconfig 4431406#define __NR_fsconfig 4431
407#define __NR_fsmount 4432407#define __NR_fsmount 4432
408#define __NR_fspick 4433408#define __NR_fspick 4433
409#define __NR_pidfd_open 4434
410#define __NR_clone3 4435
409411
lib/libc/musl/arch/mips/reloc.h-2
...@@ -1,5 +1,3 @@...@@ -1,5 +1,3 @@
1#include <endian.h>
2
3#if __mips_isa_rev >= 61#if __mips_isa_rev >= 6
4#define ISA_SUFFIX "r6"2#define ISA_SUFFIX "r6"
5#else3#else
lib/libc/musl/arch/mips/syscall_arch.h+3-1
...@@ -142,7 +142,9 @@ static inline long __syscall7(long n, long a, long b, long c, long d, long e, lo...@@ -142,7 +142,9 @@ static inline long __syscall7(long n, long a, long b, long c, long d, long e, lo
142}142}
143143
144#define VDSO_USEFUL144#define VDSO_USEFUL
145#define VDSO_CGT_SYM "__vdso_clock_gettime"145#define VDSO_CGT32_SYM "__vdso_clock_gettime"
146#define VDSO_CGT32_VER "LINUX_2.6"
147#define VDSO_CGT_SYM "__vdso_clock_gettime64"
146#define VDSO_CGT_VER "LINUX_2.6"148#define VDSO_CGT_VER "LINUX_2.6"
147149
148#define SO_SNDTIMEO_OLD 0x1005150#define SO_SNDTIMEO_OLD 0x1005
lib/libc/musl/arch/mips64/bits/alltypes.h.in+7-13
...@@ -2,8 +2,13 @@...@@ -2,8 +2,13 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;5#if _MIPSEL || __MIPSEL || __MIPSEL__
6TYPEDEF __builtin_va_list __isoc_va_list;6#define __BYTE_ORDER 1234
7#else
8#define __BYTE_ORDER 4321
9#endif
10
11#define __LONG_MAX 0x7fffffffffffffffL
712
8#ifndef __cplusplus13#ifndef __cplusplus
9TYPEDEF int wchar_t;14TYPEDEF int wchar_t;
...@@ -14,15 +19,4 @@ TYPEDEF double double_t;...@@ -14,15 +19,4 @@ TYPEDEF double double_t;
1419
15TYPEDEF struct { long long __ll; long double __ld; } max_align_t;20TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
1621
17TYPEDEF long time_t;
18TYPEDEF long suseconds_t;
19
20TYPEDEF unsigned nlink_t;22TYPEDEF unsigned nlink_t;
21
22TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
23TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
24TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
25TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
26TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
27TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
28TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/mips64/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if _MIPSEL || __MIPSEL || __MIPSEL__
2#define __BYTE_ORDER __LITTLE_ENDIAN
3#else
4#define __BYTE_ORDER __BIG_ENDIAN
5#endif
lib/libc/musl/arch/mips64/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 64
4#endif
5
6#define LONG_MAX 0x7fffffffffffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/mips64/bits/socket.h-34
...@@ -1,37 +1,3 @@...@@ -1,37 +1,3 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7#if __BYTE_ORDER == __BIG_ENDIAN
8 int __pad1, msg_iovlen;
9#else
10 int msg_iovlen, __pad1;
11#endif
12 void *msg_control;
13#if __BYTE_ORDER == __BIG_ENDIAN
14 int __pad2;
15 socklen_t msg_controllen;
16#else
17 socklen_t msg_controllen;
18 int __pad2;
19#endif
20 int msg_flags;
21};
22
23struct cmsghdr {
24#if __BYTE_ORDER == __BIG_ENDIAN
25 int __pad1;
26 socklen_t cmsg_len;
27#else
28 socklen_t cmsg_len;
29 int __pad1;
30#endif
31 int cmsg_level;
32 int cmsg_type;
33};
34
35#define SOCK_STREAM 21#define SOCK_STREAM 2
36#define SOCK_DGRAM 12#define SOCK_DGRAM 1
37#define SOL_SOCKET 655353#define SOL_SOCKET 65535
lib/libc/musl/arch/mips64/bits/syscall.h.in+2
...@@ -336,4 +336,6 @@...@@ -336,4 +336,6 @@
336#define __NR_fsconfig 5431336#define __NR_fsconfig 5431
337#define __NR_fsmount 5432337#define __NR_fsmount 5432
338#define __NR_fspick 5433338#define __NR_fspick 5433
339#define __NR_pidfd_open 5434
340#define __NR_clone3 5435
339341
lib/libc/musl/arch/mips64/reloc.h+2-8
...@@ -1,9 +1,3 @@...@@ -1,9 +1,3 @@
1#ifndef __RELOC_H__
2#define __RELOC_H__
3
4#define _GNU_SOURCE
5#include <endian.h>
6
7#if __mips_isa_rev >= 61#if __mips_isa_rev >= 6
8#define ISA_SUFFIX "r6"2#define ISA_SUFFIX "r6"
9#else3#else
...@@ -33,6 +27,8 @@...@@ -33,6 +27,8 @@
33#define REL_DTPOFF R_MIPS_TLS_DTPREL6427#define REL_DTPOFF R_MIPS_TLS_DTPREL64
34#define REL_TPOFF R_MIPS_TLS_TPREL6428#define REL_TPOFF R_MIPS_TLS_TPREL64
3529
30#include <endian.h>
31
36#undef R_TYPE32#undef R_TYPE
37#undef R_SYM33#undef R_SYM
38#undef R_INFO34#undef R_INFO
...@@ -62,5 +58,3 @@...@@ -62,5 +58,3 @@
62 " daddu %0, %0, $ra \n" \58 " daddu %0, %0, $ra \n" \
63 ".set pop \n" \59 ".set pop \n" \
64 : "=r"(*(fp)) : : "memory", "ra" )60 : "=r"(*(fp)) : : "memory", "ra" )
65
66#endif
lib/libc/musl/arch/powerpc/bits/alltypes.h.in+3-13
...@@ -1,9 +1,10 @@...@@ -1,9 +1,10 @@
1#define _REDIR_TIME64 1
1#define _Addr int2#define _Addr int
2#define _Int64 long long3#define _Int64 long long
3#define _Reg int4#define _Reg int
45
5TYPEDEF __builtin_va_list va_list;6#define __BYTE_ORDER 4321
6TYPEDEF __builtin_va_list __isoc_va_list;7#define __LONG_MAX 0x7fffffffL
78
8#ifndef __cplusplus9#ifndef __cplusplus
9#ifdef __WCHAR_TYPE__10#ifdef __WCHAR_TYPE__
...@@ -17,14 +18,3 @@ TYPEDEF float float_t;...@@ -17,14 +18,3 @@ TYPEDEF float float_t;
17TYPEDEF double double_t;18TYPEDEF double double_t;
1819
19TYPEDEF struct { long long __ll; long double __ld; } max_align_t;20TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
20
21TYPEDEF long time_t;
22TYPEDEF long suseconds_t;
23
24TYPEDEF struct { union { int __i[9]; volatile int __vi[9]; unsigned __s[9]; } __u; } pthread_attr_t;
25TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } pthread_mutex_t;
26TYPEDEF struct { union { int __i[6]; volatile int __vi[6]; volatile void *volatile __p[6]; } __u; } mtx_t;
27TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } pthread_cond_t;
28TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12]; } __u; } cnd_t;
29TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[8]; } __u; } pthread_rwlock_t;
30TYPEDEF struct { union { int __i[5]; volatile int __vi[5]; void *__p[5]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/powerpc/bits/endian.h deleted-15
...@@ -1,15 +0,0 @@
1#ifdef __BIG_ENDIAN__
2 #if __BIG_ENDIAN__
3 #define __BYTE_ORDER __BIG_ENDIAN
4 #endif
5#endif /* __BIG_ENDIAN__ */
6
7#ifdef __LITTLE_ENDIAN__
8 #if __LITTLE_ENDIAN__
9 #define __BYTE_ORDER __LITTLE_ENDIAN
10 #endif
11#endif /* __LITTLE_ENDIAN__ */
12
13#ifndef __BYTE_ORDER
14 #define __BYTE_ORDER __BIG_ENDIAN
15#endif
lib/libc/musl/arch/powerpc/bits/ioctl.h+2-2
...@@ -116,5 +116,5 @@...@@ -116,5 +116,5 @@
116#define FIOGETOWN 0x8903116#define FIOGETOWN 0x8903
117#define SIOCGPGRP 0x8904117#define SIOCGPGRP 0x8904
118#define SIOCATMARK 0x8905118#define SIOCATMARK 0x8905
119#define SIOCGSTAMP 0x8906119#define SIOCGSTAMP _IOR(0x89, 6, char[16])
120#define SIOCGSTAMPNS 0x8907120#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
lib/libc/musl/arch/powerpc/bits/ipcstat.h+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1#define IPC_STAT 21#define IPC_STAT 0x102
lib/libc/musl/arch/powerpc/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 32
4#endif
5
6#define LONG_MAX 0x7fffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/powerpc/bits/msg.h+9-6
...@@ -1,15 +1,18 @@...@@ -1,15 +1,18 @@
1struct msqid_ds {1struct msqid_ds {
2 struct ipc_perm msg_perm;2 struct ipc_perm msg_perm;
3 int __unused1;3 unsigned long __msg_stime_hi;
4 time_t msg_stime;4 unsigned long __msg_stime_lo;
5 int __unused2;5 unsigned long __msg_rtime_hi;
6 time_t msg_rtime;6 unsigned long __msg_rtime_lo;
7 int __unused3;7 unsigned long __msg_ctime_hi;
8 time_t msg_ctime;8 unsigned long __msg_ctime_lo;
9 unsigned long msg_cbytes;9 unsigned long msg_cbytes;
10 msgqnum_t msg_qnum;10 msgqnum_t msg_qnum;
11 msglen_t msg_qbytes;11 msglen_t msg_qbytes;
12 pid_t msg_lspid;12 pid_t msg_lspid;
13 pid_t msg_lrpid;13 pid_t msg_lrpid;
14 unsigned long __unused[2];14 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
15};18};
lib/libc/musl/arch/powerpc/bits/sem.h+6-4
...@@ -1,10 +1,12 @@...@@ -1,10 +1,12 @@
1struct semid_ds {1struct semid_ds {
2 struct ipc_perm sem_perm;2 struct ipc_perm sem_perm;
3 int __unused1;3 unsigned long __sem_otime_hi;
4 time_t sem_otime;4 unsigned long __sem_otime_lo;
5 int __unused2;5 unsigned long __sem_ctime_hi;
6 time_t sem_ctime;6 unsigned long __sem_ctime_lo;
7 unsigned short __sem_nsems_pad, sem_nsems;7 unsigned short __sem_nsems_pad, sem_nsems;
8 long __unused3;8 long __unused3;
9 long __unused4;9 long __unused4;
10 time_t sem_otime;
11 time_t sem_ctime;
10};12};
lib/libc/musl/arch/powerpc/bits/shm.h+9-7
...@@ -2,19 +2,21 @@...@@ -2,19 +2,21 @@
22
3struct shmid_ds {3struct shmid_ds {
4 struct ipc_perm shm_perm;4 struct ipc_perm shm_perm;
5 int __unused1;5 unsigned long __shm_atime_hi;
6 time_t shm_atime;6 unsigned long __shm_atime_lo;
7 int __unused2;7 unsigned long __shm_dtime_hi;
8 time_t shm_dtime;8 unsigned long __shm_dtime_lo;
9 int __unused3;9 unsigned long __shm_ctime_hi;
10 time_t shm_ctime;10 unsigned long __shm_ctime_lo;
11 int __unused4;
12 size_t shm_segsz;11 size_t shm_segsz;
13 pid_t shm_cpid;12 pid_t shm_cpid;
14 pid_t shm_lpid;13 pid_t shm_lpid;
15 unsigned long shm_nattch;14 unsigned long shm_nattch;
16 unsigned long __pad1;15 unsigned long __pad1;
17 unsigned long __pad2;16 unsigned long __pad2;
17 time_t shm_atime;
18 time_t shm_dtime;
19 time_t shm_ctime;
18};20};
1921
20struct shminfo {22struct shminfo {
lib/libc/musl/arch/powerpc/bits/signal.h+1-1
...@@ -28,7 +28,7 @@ struct sigcontext {...@@ -28,7 +28,7 @@ struct sigcontext {
28 int signal;28 int signal;
29 unsigned long handler;29 unsigned long handler;
30 unsigned long oldmask;30 unsigned long oldmask;
31 void *regs;31 struct pt_regs *regs;
32};32};
3333
34typedef struct {34typedef struct {
lib/libc/musl/arch/powerpc/bits/socket.h-18
...@@ -1,19 +1,3 @@...@@ -1,19 +1,3 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen;
6 void *msg_control;
7 socklen_t msg_controllen;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int cmsg_level;
14 int cmsg_type;
15};
16
17#define SO_DEBUG 11#define SO_DEBUG 1
18#define SO_REUSEADDR 22#define SO_REUSEADDR 2
19#define SO_TYPE 33#define SO_TYPE 3
...@@ -31,8 +15,6 @@ struct cmsghdr {...@@ -31,8 +15,6 @@ struct cmsghdr {
31#define SO_REUSEPORT 1515#define SO_REUSEPORT 15
32#define SO_RCVLOWAT 1616#define SO_RCVLOWAT 16
33#define SO_SNDLOWAT 1717#define SO_SNDLOWAT 17
34#define SO_RCVTIMEO 18
35#define SO_SNDTIMEO 19
36#define SO_PASSCRED 2018#define SO_PASSCRED 20
37#define SO_PEERCRED 2119#define SO_PEERCRED 21
38#define SO_ACCEPTCONN 3020#define SO_ACCEPTCONN 30
lib/libc/musl/arch/powerpc/bits/stat.h+5-1
...@@ -13,8 +13,12 @@ struct stat {...@@ -13,8 +13,12 @@ struct stat {
13 off_t st_size;13 off_t st_size;
14 blksize_t st_blksize;14 blksize_t st_blksize;
15 blkcnt_t st_blocks;15 blkcnt_t st_blocks;
16 struct {
17 long tv_sec;
18 long tv_nsec;
19 } __st_atim32, __st_mtim32, __st_ctim32;
20 unsigned __unused[2];
16 struct timespec st_atim;21 struct timespec st_atim;
17 struct timespec st_mtim;22 struct timespec st_mtim;
18 struct timespec st_ctim;23 struct timespec st_ctim;
19 unsigned __unused[2];
20};24};
lib/libc/musl/arch/powerpc/bits/syscall.h.in+12-10
...@@ -76,8 +76,8 @@...@@ -76,8 +76,8 @@
76#define __NR_setrlimit 7576#define __NR_setrlimit 75
77#define __NR_getrlimit 7677#define __NR_getrlimit 76
78#define __NR_getrusage 7778#define __NR_getrusage 77
79#define __NR_gettimeofday 7879#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday 7980#define __NR_settimeofday_time32 79
81#define __NR_getgroups 8081#define __NR_getgroups 80
82#define __NR_setgroups 8182#define __NR_setgroups 81
83#define __NR_select 8283#define __NR_select 82
...@@ -238,14 +238,14 @@...@@ -238,14 +238,14 @@
238#define __NR_epoll_wait 238238#define __NR_epoll_wait 238
239#define __NR_remap_file_pages 239239#define __NR_remap_file_pages 239
240#define __NR_timer_create 240240#define __NR_timer_create 240
241#define __NR_timer_settime 241241#define __NR_timer_settime32 241
242#define __NR_timer_gettime 242242#define __NR_timer_gettime32 242
243#define __NR_timer_getoverrun 243243#define __NR_timer_getoverrun 243
244#define __NR_timer_delete 244244#define __NR_timer_delete 244
245#define __NR_clock_settime 245245#define __NR_clock_settime32 245
246#define __NR_clock_gettime 246246#define __NR_clock_gettime32 246
247#define __NR_clock_getres 247247#define __NR_clock_getres_time32 247
248#define __NR_clock_nanosleep 248248#define __NR_clock_nanosleep_time32 248
249#define __NR_swapcontext 249249#define __NR_swapcontext 249
250#define __NR_tgkill 250250#define __NR_tgkill 250
251#define __NR_utimes 251251#define __NR_utimes 251
...@@ -307,8 +307,8 @@...@@ -307,8 +307,8 @@
307#define __NR_sync_file_range2 308307#define __NR_sync_file_range2 308
308#define __NR_fallocate 309308#define __NR_fallocate 309
309#define __NR_subpage_prot 310309#define __NR_subpage_prot 310
310#define __NR_timerfd_settime 311310#define __NR_timerfd_settime32 311
311#define __NR_timerfd_gettime 312311#define __NR_timerfd_gettime32 312
312#define __NR_signalfd4 313312#define __NR_signalfd4 313
313#define __NR_eventfd2 314313#define __NR_eventfd2 314
314#define __NR_epoll_create1 315314#define __NR_epoll_create1 315
...@@ -413,4 +413,6 @@...@@ -413,4 +413,6 @@
413#define __NR_fsconfig 431413#define __NR_fsconfig 431
414#define __NR_fsmount 432414#define __NR_fsmount 432
415#define __NR_fspick 433415#define __NR_fspick 433
416#define __NR_pidfd_open 434
417#define __NR_clone3 435
416418
lib/libc/musl/arch/powerpc64/bits/alltypes.h.in+7-13
...@@ -2,8 +2,13 @@...@@ -2,8 +2,13 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;5#if __BIG_ENDIAN__
6TYPEDEF __builtin_va_list __isoc_va_list;6#define __BYTE_ORDER 4321
7#else
8#define __BYTE_ORDER 1234
9#endif
10
11#define __LONG_MAX 0x7fffffffffffffffL
712
8#ifndef __cplusplus13#ifndef __cplusplus
9TYPEDEF int wchar_t;14TYPEDEF int wchar_t;
...@@ -13,14 +18,3 @@ TYPEDEF float float_t;...@@ -13,14 +18,3 @@ TYPEDEF float float_t;
13TYPEDEF double double_t;18TYPEDEF double double_t;
1419
15TYPEDEF struct { long long __ll; long double __ld; } max_align_t;20TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
16
17TYPEDEF long time_t;
18TYPEDEF long suseconds_t;
19
20TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
21TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
22TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
23TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
24TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
25TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
26TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/powerpc64/bits/endian.h deleted-5
...@@ -1,5 +0,0 @@
1#if __BIG_ENDIAN__
2#define __BYTE_ORDER __BIG_ENDIAN
3#else
4#define __BYTE_ORDER __LITTLE_ENDIAN
5#endif
lib/libc/musl/arch/powerpc64/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 64
4#endif
5
6#define LONG_MAX 0x7fffffffffffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/powerpc64/bits/signal.h+2-6
...@@ -9,11 +9,7 @@...@@ -9,11 +9,7 @@
9#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)9#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
1010
11typedef unsigned long greg_t, gregset_t[48];11typedef unsigned long greg_t, gregset_t[48];
1212typedef double fpregset_t[33];
13typedef struct {
14 double fpregs[32];
15 double fpscr;
16} fpregset_t;
1713
18typedef struct {14typedef struct {
19#ifdef __GNUC__15#ifdef __GNUC__
...@@ -36,7 +32,7 @@ typedef struct sigcontext {...@@ -36,7 +32,7 @@ typedef struct sigcontext {
36 int _pad0;32 int _pad0;
37 unsigned long handler;33 unsigned long handler;
38 unsigned long oldmask;34 unsigned long oldmask;
39 void *regs;35 struct pt_regs *regs;
40 gregset_t gp_regs;36 gregset_t gp_regs;
41 fpregset_t fp_regs;37 fpregset_t fp_regs;
42 vrregset_t *v_regs;38 vrregset_t *v_regs;
lib/libc/musl/arch/powerpc64/bits/socket.h-34
...@@ -1,37 +1,3 @@...@@ -1,37 +1,3 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7#if __BYTE_ORDER == __BIG_ENDIAN
8 int __pad1, msg_iovlen;
9#else
10 int msg_iovlen, __pad1;
11#endif
12 void *msg_control;
13#if __BYTE_ORDER == __BIG_ENDIAN
14 int __pad2;
15 socklen_t msg_controllen;
16#else
17 socklen_t msg_controllen;
18 int __pad2;
19#endif
20 int msg_flags;
21};
22
23struct cmsghdr {
24#if __BYTE_ORDER == __BIG_ENDIAN
25 int __pad1;
26 socklen_t cmsg_len;
27#else
28 socklen_t cmsg_len;
29 int __pad1;
30#endif
31 int cmsg_level;
32 int cmsg_type;
33};
34
35#define SO_DEBUG 11#define SO_DEBUG 1
36#define SO_REUSEADDR 22#define SO_REUSEADDR 2
37#define SO_TYPE 33#define SO_TYPE 3
lib/libc/musl/arch/powerpc64/bits/syscall.h.in+2
...@@ -385,4 +385,6 @@...@@ -385,4 +385,6 @@
385#define __NR_fsconfig 431385#define __NR_fsconfig 431
386#define __NR_fsmount 432386#define __NR_fsmount 432
387#define __NR_fspick 433387#define __NR_fspick 433
388#define __NR_pidfd_open 434
389#define __NR_clone3 435
388390
lib/libc/musl/arch/powerpc64/reloc.h-2
...@@ -1,5 +1,3 @@...@@ -1,5 +1,3 @@
1#include <endian.h>
2
3#if __BYTE_ORDER == __LITTLE_ENDIAN1#if __BYTE_ORDER == __LITTLE_ENDIAN
4#define ENDIAN_SUFFIX "le"2#define ENDIAN_SUFFIX "le"
5#else3#else
lib/libc/musl/arch/riscv64/atomic_arch.h+1-1
...@@ -15,7 +15,7 @@ static inline int a_cas(volatile int *p, int t, int s)...@@ -15,7 +15,7 @@ static inline int a_cas(volatile int *p, int t, int s)
15 " bnez %1, 1b\n"15 " bnez %1, 1b\n"
16 "1:"16 "1:"
17 : "=&r"(old), "=&r"(tmp)17 : "=&r"(old), "=&r"(tmp)
18 : "r"(p), "r"(t), "r"(s)18 : "r"(p), "r"((long)t), "r"((long)s)
19 : "memory");19 : "memory");
20 return old;20 return old;
21}21}
lib/libc/musl/arch/riscv64/bits/alltypes.h.in+2-13
...@@ -2,8 +2,8 @@...@@ -2,8 +2,8 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;5#define __BYTE_ORDER 1234
6TYPEDEF __builtin_va_list __isoc_va_list;6#define __LONG_MAX 0x7fffffffffffffffL
77
8#ifndef __cplusplus8#ifndef __cplusplus
9TYPEDEF int wchar_t;9TYPEDEF int wchar_t;
...@@ -16,14 +16,3 @@ TYPEDEF float float_t;...@@ -16,14 +16,3 @@ TYPEDEF float float_t;
16TYPEDEF double double_t;16TYPEDEF double double_t;
1717
18TYPEDEF struct { long long __ll; long double __ld; } max_align_t;18TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
19
20TYPEDEF long time_t;
21TYPEDEF long suseconds_t;
22
23TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
24TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
25TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
26TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
27TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
28TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
29TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/riscv64/bits/endian.h deleted-1
...@@ -1 +0,0 @@
1#define __BYTE_ORDER __LITTLE_ENDIAN
lib/libc/musl/arch/riscv64/bits/limits.h deleted-7
...@@ -1,7 +0,0 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define LONG_BIT 64
4#endif
5
6#define LONG_MAX 0x7fffffffffffffffL
7#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/riscv64/bits/reg.h-6
...@@ -1,8 +1,2 @@...@@ -1,8 +1,2 @@
1#undef __WORDSIZE1#undef __WORDSIZE
2#define __WORDSIZE 642#define __WORDSIZE 64
3#define REG_PC 0
4#define REG_RA 1
5#define REG_SP 2
6#define REG_TP 4
7#define REG_S0 8
8#define REG_A0 10
lib/libc/musl/arch/riscv64/bits/signal.h+9
...@@ -35,6 +35,15 @@ typedef struct mcontext_t {...@@ -35,6 +35,15 @@ typedef struct mcontext_t {
35 union __riscv_mc_fp_state __fpregs;35 union __riscv_mc_fp_state __fpregs;
36} mcontext_t;36} mcontext_t;
3737
38#if defined(_GNU_SOURCE)
39#define REG_PC 0
40#define REG_RA 1
41#define REG_SP 2
42#define REG_TP 4
43#define REG_S0 8
44#define REG_A0 10
45#endif
46
38#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)47#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
39typedef unsigned long greg_t;48typedef unsigned long greg_t;
40typedef unsigned long gregset_t[32];49typedef unsigned long gregset_t[32];
lib/libc/musl/arch/riscv64/bits/socket.h deleted-19
...@@ -1,19 +0,0 @@
1#include <endian.h>
2
3struct msghdr {
4 void *msg_name;
5 socklen_t msg_namelen;
6 struct iovec *msg_iov;
7 int msg_iovlen, __pad1;
8 void *msg_control;
9 socklen_t msg_controllen;
10 int __pad2;
11 int msg_flags;
12};
13
14struct cmsghdr {
15 socklen_t cmsg_len;
16 int __pad1;
17 int cmsg_level;
18 int cmsg_type;
19};
lib/libc/musl/arch/riscv64/bits/syscall.h.in+2
...@@ -287,6 +287,8 @@...@@ -287,6 +287,8 @@
287#define __NR_fsconfig 431287#define __NR_fsconfig 431
288#define __NR_fsmount 432288#define __NR_fsmount 432
289#define __NR_fspick 433289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
291#define __NR_sysriscv __NR_arch_specific_syscall293#define __NR_sysriscv __NR_arch_specific_syscall
292#define __NR_riscv_flush_icache (__NR_sysriscv + 15)294#define __NR_riscv_flush_icache (__NR_sysriscv + 15)
lib/libc/musl/arch/s390x/bits/alltypes.h.in+2-13
...@@ -2,8 +2,8 @@...@@ -2,8 +2,8 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;5#define __BYTE_ORDER 4321
6TYPEDEF __builtin_va_list __isoc_va_list;6#define __LONG_MAX 0x7fffffffffffffffL
77
8#ifndef __cplusplus8#ifndef __cplusplus
9TYPEDEF int wchar_t;9TYPEDEF int wchar_t;
...@@ -13,14 +13,3 @@ TYPEDEF double float_t;...@@ -13,14 +13,3 @@ TYPEDEF double float_t;
13TYPEDEF double double_t;13TYPEDEF double double_t;
1414
15TYPEDEF struct { long long __ll; long double __ld; } max_align_t;15TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
16
17TYPEDEF long time_t;
18TYPEDEF long suseconds_t;
19
20TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
21TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
22TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
23TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
24TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
25TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
26TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/s390x/bits/endian.h deleted-1
...@@ -1 +0,0 @@
1#define __BYTE_ORDER __BIG_ENDIAN
lib/libc/musl/arch/s390x/bits/limits.h-7
...@@ -1,8 +1 @@...@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define PAGESIZE 40961#define PAGESIZE 4096
4#define LONG_BIT 64
5#endif
6
7#define LONG_MAX 0x7fffffffffffffffL
8#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/s390x/bits/socket.h deleted-17
...@@ -1,17 +0,0 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int __pad1, msg_iovlen;
6 void *msg_control;
7 int __pad2;
8 socklen_t msg_controllen;
9 int msg_flags;
10};
11
12struct cmsghdr {
13 int __pad1;
14 socklen_t cmsg_len;
15 int cmsg_level;
16 int cmsg_type;
17};
lib/libc/musl/arch/s390x/bits/syscall.h.in+2
...@@ -350,4 +350,6 @@...@@ -350,4 +350,6 @@
350#define __NR_fsconfig 431350#define __NR_fsconfig 431
351#define __NR_fsmount 432351#define __NR_fsmount 432
352#define __NR_fspick 433352#define __NR_fspick 433
353#define __NR_pidfd_open 434
354#define __NR_clone3 435
353355
lib/libc/musl/arch/s390x/reloc.h-2
...@@ -1,5 +1,3 @@...@@ -1,5 +1,3 @@
1#include <endian.h>
2
3#define LDSO_ARCH "s390x"1#define LDSO_ARCH "s390x"
42
5#define REL_SYMBOLIC R_390_643#define REL_SYMBOLIC R_390_64
lib/libc/musl/arch/x86_64/bits/alltypes.h.in+2-13
...@@ -2,8 +2,8 @@...@@ -2,8 +2,8 @@
2#define _Int64 long2#define _Int64 long
3#define _Reg long3#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;5#define __BYTE_ORDER 1234
6TYPEDEF __builtin_va_list __isoc_va_list;6#define __LONG_MAX 0x7fffffffffffffffL
77
8#ifndef __cplusplus8#ifndef __cplusplus
9TYPEDEF int wchar_t;9TYPEDEF int wchar_t;
...@@ -18,14 +18,3 @@ TYPEDEF double double_t;...@@ -18,14 +18,3 @@ TYPEDEF double double_t;
18#endif18#endif
1919
20TYPEDEF struct { long long __ll; long double __ld; } max_align_t;20TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
21
22TYPEDEF long time_t;
23TYPEDEF long suseconds_t;
24
25TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
26TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } pthread_mutex_t;
27TYPEDEF struct { union { int __i[10]; volatile int __vi[10]; volatile void *volatile __p[5]; } __u; } mtx_t;
28TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } pthread_cond_t;
29TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[6]; } __u; } cnd_t;
30TYPEDEF struct { union { int __i[14]; volatile int __vi[14]; void *__p[7]; } __u; } pthread_rwlock_t;
31TYPEDEF struct { union { int __i[8]; volatile int __vi[8]; void *__p[4]; } __u; } pthread_barrier_t;
lib/libc/musl/arch/x86_64/bits/endian.h deleted-1
...@@ -1 +0,0 @@
1#define __BYTE_ORDER __LITTLE_ENDIAN
lib/libc/musl/arch/x86_64/bits/limits.h-7
...@@ -1,8 +1 @@...@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3#define PAGESIZE 40961#define PAGESIZE 4096
4#define LONG_BIT 64
5#endif
6
7#define LONG_MAX 0x7fffffffffffffffL
8#define LLONG_MAX 0x7fffffffffffffffLL
lib/libc/musl/arch/x86_64/bits/socket.h deleted-16
...@@ -1,16 +0,0 @@
1struct msghdr {
2 void *msg_name;
3 socklen_t msg_namelen;
4 struct iovec *msg_iov;
5 int msg_iovlen, __pad1;
6 void *msg_control;
7 socklen_t msg_controllen, __pad2;
8 int msg_flags;
9};
10
11struct cmsghdr {
12 socklen_t cmsg_len;
13 int __pad1;
14 int cmsg_level;
15 int cmsg_type;
16};
lib/libc/musl/arch/x86_64/bits/syscall.h.in+2
...@@ -343,4 +343,6 @@...@@ -343,4 +343,6 @@
343#define __NR_fsconfig 431343#define __NR_fsconfig 431
344#define __NR_fsmount 432344#define __NR_fsmount 432
345#define __NR_fspick 433345#define __NR_fspick 433
346#define __NR_pidfd_open 434
347#define __NR_clone3 435
346348
lib/libc/musl/compat/time32/__xstat.c created+24
...@@ -0,0 +1,24 @@
1#include "time32.h"
2#include <sys/stat.h>
3
4struct stat32;
5
6int __fxstat64(int ver, int fd, struct stat32 *buf)
7{
8 return __fstat_time32(fd, buf);
9}
10
11int __fxstatat64(int ver, int fd, const char *path, struct stat32 *buf, int flag)
12{
13 return __fstatat_time32(fd, path, buf, flag);
14}
15
16int __lxstat64(int ver, const char *path, struct stat32 *buf)
17{
18 return __lstat_time32(path, buf);
19}
20
21int __xstat64(int ver, const char *path, struct stat32 *buf)
22{
23 return __stat_time32(path, buf);
24}
lib/libc/musl/compat/time32/adjtime32.c created+21
...@@ -0,0 +1,21 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4#include <sys/time.h>
5#include <sys/timex.h>
6
7int __adjtime32(const struct timeval32 *in32, struct timeval32 *out32)
8{
9 struct timeval out;
10 int r = adjtime((&(struct timeval){
11 .tv_sec = in32->tv_sec,
12 .tv_usec = in32->tv_usec}), &out);
13 if (r) return r;
14 /* We can't range-check the result because success was already
15 * committed by the above call. */
16 if (out32) {
17 out32->tv_sec = out.tv_sec;
18 out32->tv_usec = out.tv_usec;
19 }
20 return r;
21}
lib/libc/musl/compat/time32/adjtimex_time32.c created+10
...@@ -0,0 +1,10 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/timex.h>
4
5struct timex32;
6
7int __adjtimex_time32(struct timex32 *tx32)
8{
9 return __clock_adjtime32(CLOCK_REALTIME, tx32);
10}
lib/libc/musl/compat/time32/aio_suspend_time32.c created+11
...@@ -0,0 +1,11 @@
1#include "time32.h"
2#include <time.h>
3#include <aio.h>
4
5int __aio_suspend_time32(const struct aiocb *const cbs[], int cnt, const struct timespec32 *ts32)
6{
7 return aio_suspend(cbs, cnt, ts32 ? (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}) : 0);
9}
10
11weak_alias(aio_suspend, aio_suspend64);
lib/libc/musl/compat/time32/clock_adjtime32.c created+70
...@@ -0,0 +1,70 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/time.h>
4#include <sys/timex.h>
5#include <string.h>
6#include <stddef.h>
7
8struct timex32 {
9 unsigned modes;
10 long offset, freq, maxerror, esterror;
11 int status;
12 long constant, precision, tolerance;
13 struct timeval32 time;
14 long tick, ppsfreq, jitter;
15 int shift;
16 long stabil, jitcnt, calcnt, errcnt, stbcnt;
17 int tai;
18 int __padding[11];
19};
20
21int __clock_adjtime32(clockid_t clock_id, struct timex32 *tx32)
22{
23 struct timex utx = {
24 .modes = tx32->modes,
25 .offset = tx32->offset,
26 .freq = tx32->freq,
27 .maxerror = tx32->maxerror,
28 .esterror = tx32->esterror,
29 .status = tx32->status,
30 .constant = tx32->constant,
31 .precision = tx32->precision,
32 .tolerance = tx32->tolerance,
33 .time.tv_sec = tx32->time.tv_sec,
34 .time.tv_usec = tx32->time.tv_usec,
35 .tick = tx32->tick,
36 .ppsfreq = tx32->ppsfreq,
37 .jitter = tx32->jitter,
38 .shift = tx32->shift,
39 .stabil = tx32->stabil,
40 .jitcnt = tx32->jitcnt,
41 .calcnt = tx32->calcnt,
42 .errcnt = tx32->errcnt,
43 .stbcnt = tx32->stbcnt,
44 .tai = tx32->tai,
45 };
46 int r = clock_adjtime(clock_id, &utx);
47 if (r<0) return r;
48 tx32->modes = utx.modes;
49 tx32->offset = utx.offset;
50 tx32->freq = utx.freq;
51 tx32->maxerror = utx.maxerror;
52 tx32->esterror = utx.esterror;
53 tx32->status = utx.status;
54 tx32->constant = utx.constant;
55 tx32->precision = utx.precision;
56 tx32->tolerance = utx.tolerance;
57 tx32->time.tv_sec = utx.time.tv_sec;
58 tx32->time.tv_usec = utx.time.tv_usec;
59 tx32->tick = utx.tick;
60 tx32->ppsfreq = utx.ppsfreq;
61 tx32->jitter = utx.jitter;
62 tx32->shift = utx.shift;
63 tx32->stabil = utx.stabil;
64 tx32->jitcnt = utx.jitcnt;
65 tx32->calcnt = utx.calcnt;
66 tx32->errcnt = utx.errcnt;
67 tx32->stbcnt = utx.stbcnt;
68 tx32->tai = utx.tai;
69 return r;
70}
lib/libc/musl/compat/time32/clock_getres_time32.c created+13
...@@ -0,0 +1,13 @@
1#include "time32.h"
2#include <time.h>
3
4int __clock_getres_time32(clockid_t clk, struct timespec32 *ts32)
5{
6 struct timespec ts;
7 int r = clock_getres(clk, &ts);
8 if (!r && ts32) {
9 ts32->tv_sec = ts.tv_sec;
10 ts32->tv_nsec = ts.tv_nsec;
11 }
12 return r;
13}
lib/libc/musl/compat/time32/clock_gettime32.c created+18
...@@ -0,0 +1,18 @@
1#include "time32.h"
2#include <time.h>
3#include <errno.h>
4#include <stdint.h>
5
6int __clock_gettime32(clockid_t clk, struct timespec32 *ts32)
7{
8 struct timespec ts;
9 int r = clock_gettime(clk, &ts);
10 if (r) return r;
11 if (ts.tv_sec < INT32_MIN || ts.tv_sec > INT32_MAX) {
12 errno = EOVERFLOW;
13 return -1;
14 }
15 ts32->tv_sec = ts.tv_sec;
16 ts32->tv_nsec = ts.tv_nsec;
17 return 0;
18}
lib/libc/musl/compat/time32/clock_nanosleep_time32.c created+15
...@@ -0,0 +1,15 @@
1#include "time32.h"
2#include <time.h>
3#include <errno.h>
4
5int __clock_nanosleep_time32(clockid_t clk, int flags, const struct timespec32 *req32, struct timespec32 *rem32)
6{
7 struct timespec rem;
8 int ret = clock_nanosleep(clk, flags, (&(struct timespec){
9 .tv_sec = req32->tv_sec, .tv_nsec = req32->tv_nsec}), &rem);
10 if (ret==EINTR && rem32 && !(flags & TIMER_ABSTIME)) {
11 rem32->tv_sec = rem.tv_sec;
12 rem32->tv_nsec = rem.tv_nsec;
13 }
14 return ret;
15}
lib/libc/musl/compat/time32/clock_settime32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3
4int __clock_settime32(clockid_t clk, const struct timespec32 *ts32)
5{
6 return clock_settime(clk, (&(struct timespec){
7 .tv_sec = ts32->tv_sec,
8 .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/cnd_timedwait_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <threads.h>
4
5int __cnd_timedwait_time32(cnd_t *restrict c, mtx_t *restrict m, const struct timespec32 *restrict ts32)
6{
7 return cnd_timedwait(c, m, ts32 ? (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}) : 0);
9}
lib/libc/musl/compat/time32/ctime32.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4char *__ctime32(time32_t *t)
5{
6 return ctime(&(time_t){*t});
7}
lib/libc/musl/compat/time32/ctime32_r.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4char *__ctime32_r(time32_t *t, char *buf)
5{
6 return ctime_r(&(time_t){*t}, buf);
7}
lib/libc/musl/compat/time32/difftime32.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4double __difftime32(time32_t t1, time32_t t2)
5{
6 return difftime(t1, t2);
7}
lib/libc/musl/compat/time32/fstat_time32.c created+17
...@@ -0,0 +1,17 @@
1#include "time32.h"
2#include <time.h>
3#include <string.h>
4#include <sys/stat.h>
5#include <stddef.h>
6
7struct stat32;
8
9int __fstat_time32(int fd, struct stat32 *restrict st32)
10{
11 struct stat st;
12 int r = fstat(fd, &st);
13 if (!r) memcpy(st32, &st, offsetof(struct stat, st_atim));
14 return r;
15}
16
17weak_alias(fstat, fstat64);
lib/libc/musl/compat/time32/fstatat_time32.c created+17
...@@ -0,0 +1,17 @@
1#include "time32.h"
2#include <time.h>
3#include <string.h>
4#include <sys/stat.h>
5#include <stddef.h>
6
7struct stat32;
8
9int __fstatat_time32(int fd, const char *restrict path, struct stat32 *restrict st32, int flag)
10{
11 struct stat st;
12 int r = fstatat(fd, path, &st, flag);
13 if (!r) memcpy(st32, &st, offsetof(struct stat, st_atim));
14 return r;
15}
16
17weak_alias(fstatat, fstatat64);
lib/libc/musl/compat/time32/ftime32.c created+25
...@@ -0,0 +1,25 @@
1#include "time32.h"
2#include <sys/timeb.h>
3#include <errno.h>
4#include <stdint.h>
5
6struct timeb32 {
7 int32_t time;
8 unsigned short millitm;
9 short timezone, dstflag;
10};
11
12int __ftime32(struct timeb32 *tp)
13{
14 struct timeb tb;
15 if (ftime(&tb) < 0) return -1;
16 if (tb.time < INT32_MIN || tb.time > INT32_MAX) {
17 errno = EOVERFLOW;
18 return -1;
19 }
20 tp->time = tb.time;
21 tp->millitm = tb.millitm;
22 tp->timezone = tb.timezone;
23 tp->dstflag = tb.dstflag;
24 return 0;
25}
lib/libc/musl/compat/time32/futimens_time32.c created+10
...@@ -0,0 +1,10 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/stat.h>
4
5int __futimens_time32(int fd, const struct timespec32 *times32)
6{
7 return futimens(fd, !times32 ? 0 : ((struct timespec[2]){
8 {.tv_sec = times32[0].tv_sec,.tv_nsec = times32[0].tv_nsec},
9 {.tv_sec = times32[1].tv_sec,.tv_nsec = times32[1].tv_nsec}}));
10}
lib/libc/musl/compat/time32/futimes_time32.c created+12
...@@ -0,0 +1,12 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4#include <sys/time.h>
5#include <sys/stat.h>
6
7int __futimes_time32(int fd, const struct timeval32 times32[2])
8{
9 return futimes(fd, !times32 ? 0 : ((struct timeval[2]){
10 {.tv_sec = times32[0].tv_sec,.tv_usec = times32[0].tv_usec},
11 {.tv_sec = times32[1].tv_sec,.tv_usec = times32[1].tv_usec}}));
12}
lib/libc/musl/compat/time32/futimesat_time32.c created+12
...@@ -0,0 +1,12 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4#include <sys/time.h>
5#include <sys/stat.h>
6
7int __futimesat_time32(int dirfd, const char *pathname, const struct timeval32 times32[2])
8{
9 return futimesat(dirfd, pathname, !times32 ? 0 : ((struct timeval[2]){
10 {.tv_sec = times32[0].tv_sec,.tv_usec = times32[0].tv_usec},
11 {.tv_sec = times32[1].tv_sec,.tv_usec = times32[1].tv_usec}}));
12}
lib/libc/musl/compat/time32/getitimer_time32.c created+15
...@@ -0,0 +1,15 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/time.h>
4
5int __getitimer_time32(int which, struct itimerval32 *old32)
6{
7 struct itimerval old;
8 int r = getitimer(which, &old);
9 if (r) return r;
10 old32->it_interval.tv_sec = old.it_interval.tv_sec;
11 old32->it_interval.tv_usec = old.it_interval.tv_usec;
12 old32->it_value.tv_sec = old.it_value.tv_sec;
13 old32->it_value.tv_usec = old.it_value.tv_usec;
14 return 0;
15}
lib/libc/musl/compat/time32/getrusage_time32.c created+39
...@@ -0,0 +1,39 @@
1#include "time32.h"
2#include <string.h>
3#include <stddef.h>
4#include <sys/resource.h>
5
6struct compat_rusage {
7 struct timeval32 ru_utime;
8 struct timeval32 ru_stime;
9 long ru_maxrss;
10 long ru_ixrss;
11 long ru_idrss;
12 long ru_isrss;
13 long ru_minflt;
14 long ru_majflt;
15 long ru_nswap;
16 long ru_inblock;
17 long ru_oublock;
18 long ru_msgsnd;
19 long ru_msgrcv;
20 long ru_nsignals;
21 long ru_nvcsw;
22 long ru_nivcsw;
23};
24
25int __getrusage_time32(int who, struct compat_rusage *usage)
26{
27 struct rusage ru;
28 int r = getrusage(who, &ru);
29 if (!r) {
30 usage->ru_utime.tv_sec = ru.ru_utime.tv_sec;
31 usage->ru_utime.tv_usec = ru.ru_utime.tv_usec;
32 usage->ru_stime.tv_sec = ru.ru_stime.tv_sec;
33 usage->ru_stime.tv_usec = ru.ru_stime.tv_usec;
34 memcpy(&usage->ru_maxrss, &ru.ru_maxrss,
35 sizeof(struct compat_rusage) -
36 offsetof(struct compat_rusage, ru_maxrss));
37 }
38 return r;
39}
lib/libc/musl/compat/time32/gettimeofday_time32.c created+19
...@@ -0,0 +1,19 @@
1#include "time32.h"
2#include <sys/time.h>
3#include <errno.h>
4#include <stdint.h>
5
6int __gettimeofday_time32(struct timeval32 *tv32, void *tz)
7{
8 struct timeval tv;
9 if (!tv32) return 0;
10 int r = gettimeofday(&tv, 0);
11 if (r) return r;
12 if (tv.tv_sec < INT32_MIN || tv.tv_sec > INT32_MAX) {
13 errno = EOVERFLOW;
14 return -1;
15 }
16 tv32->tv_sec = tv.tv_sec;
17 tv32->tv_usec = tv.tv_usec;
18 return 0;
19}
lib/libc/musl/compat/time32/gmtime32.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4struct tm *__gmtime32(time32_t *t)
5{
6 return gmtime(&(time_t){*t});
7}
lib/libc/musl/compat/time32/gmtime32_r.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4struct tm *__gmtime32_r(time32_t *t, struct tm *tm)
5{
6 return gmtime_r(&(time_t){*t}, tm);
7}
lib/libc/musl/compat/time32/localtime32.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4struct tm *__localtime32(time32_t *t)
5{
6 return localtime(&(time_t){*t});
7}
lib/libc/musl/compat/time32/localtime32_r.c created+7
...@@ -0,0 +1,7 @@
1#include "time32.h"
2#include <time.h>
3
4struct tm *__localtime32_r(time32_t *t, struct tm *tm)
5{
6 return localtime_r(&(time_t){*t}, tm);
7}
lib/libc/musl/compat/time32/lstat_time32.c created+17
...@@ -0,0 +1,17 @@
1#include "time32.h"
2#include <time.h>
3#include <string.h>
4#include <sys/stat.h>
5#include <stddef.h>
6
7struct stat32;
8
9int __lstat_time32(const char *restrict path, struct stat32 *restrict st32)
10{
11 struct stat st;
12 int r = lstat(path, &st);
13 if (!r) memcpy(st32, &st, offsetof(struct stat, st_atim));
14 return r;
15}
16
17weak_alias(lstat, lstat64);
lib/libc/musl/compat/time32/lutimes_time32.c created+12
...@@ -0,0 +1,12 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4#include <sys/time.h>
5#include <sys/stat.h>
6
7int __lutimes_time32(const char *path, const struct timeval32 times32[2])
8{
9 return lutimes(path, !times32 ? 0 : ((struct timeval[2]){
10 {.tv_sec = times32[0].tv_sec,.tv_usec = times32[0].tv_usec},
11 {.tv_sec = times32[1].tv_sec,.tv_usec = times32[1].tv_usec}}));
12}
lib/libc/musl/compat/time32/mktime32.c created+16
...@@ -0,0 +1,16 @@
1#include "time32.h"
2#include <time.h>
3#include <errno.h>
4#include <stdint.h>
5
6time32_t __mktime32(struct tm *tm)
7{
8 struct tm tmp = *tm;
9 time_t t = mktime(&tmp);
10 if (t < INT32_MIN || t > INT32_MAX) {
11 errno = EOVERFLOW;
12 return -1;
13 }
14 *tm = tmp;
15 return t;
16}
lib/libc/musl/compat/time32/mq_timedreceive_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <mqueue.h>
3#include <time.h>
4
5ssize_t __mq_timedreceive_time32(mqd_t mqd, char *restrict msg, size_t len, unsigned *restrict prio, const struct timespec32 *restrict ts32)
6{
7 return mq_timedreceive(mqd, msg, len, prio, ts32 ? (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}) : 0);
9}
lib/libc/musl/compat/time32/mq_timedsend_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <mqueue.h>
3#include <time.h>
4
5int __mq_timedsend_time32(mqd_t mqd, const char *msg, size_t len, unsigned prio, const struct timespec32 *ts32)
6{
7 return mq_timedsend(mqd, msg, len, prio, ts32 ? (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}) : 0);
9}
lib/libc/musl/compat/time32/mtx_timedlock_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <threads.h>
4
5int __mtx_timedlock_time32(mtx_t *restrict m, const struct timespec32 *restrict ts32)
6{
7 return mtx_timedlock(m, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/nanosleep_time32.c created+15
...@@ -0,0 +1,15 @@
1#include "time32.h"
2#include <time.h>
3#include <errno.h>
4
5int __nanosleep_time32(const struct timespec32 *req32, struct timespec32 *rem32)
6{
7 struct timespec rem;
8 int ret = nanosleep((&(struct timespec){
9 .tv_sec = req32->tv_sec, .tv_nsec = req32->tv_nsec}), &rem);
10 if (ret<0 && errno==EINTR && rem32) {
11 rem32->tv_sec = rem.tv_sec;
12 rem32->tv_nsec = rem.tv_nsec;
13 }
14 return ret;
15}
lib/libc/musl/compat/time32/ppoll_time32.c created+10
...@@ -0,0 +1,10 @@
1#include "time32.h"
2#define _GNU_SOURCE
3#include <time.h>
4#include <poll.h>
5
6int __ppoll_time32(struct pollfd *fds, nfds_t n, const struct timespec32 *ts32, const sigset_t *mask)
7{
8 return ppoll(fds, n, !ts32 ? 0 : (&(struct timespec){
9 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}), mask);
10}
lib/libc/musl/compat/time32/pselect_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/select.h>
4
5int __pselect_time32(int n, fd_set *restrict rfds, fd_set *restrict wfds, fd_set *restrict efds, const struct timespec32 *restrict ts32, const sigset_t *restrict mask)
6{
7 return pselect(n, rfds, wfds, efds, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}), mask);
9}
lib/libc/musl/compat/time32/pthread_cond_timedwait_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <pthread.h>
4
5int __pthread_cond_timedwait_time32(pthread_cond_t *restrict c, pthread_mutex_t *restrict m, const struct timespec32 *restrict ts32)
6{
7 return pthread_cond_timedwait(c, m, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/pthread_mutex_timedlock_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <pthread.h>
4
5int __pthread_mutex_timedlock_time32(pthread_mutex_t *restrict m, const struct timespec32 *restrict ts32)
6{
7 return pthread_mutex_timedlock(m, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/pthread_rwlock_timedrdlock_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <pthread.h>
4
5int __pthread_rwlock_timedrdlock_time32(pthread_rwlock_t *restrict rw, const struct timespec32 *restrict ts32)
6{
7 return pthread_rwlock_timedrdlock(rw, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/pthread_rwlock_timedwrlock_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <pthread.h>
4
5int __pthread_rwlock_timedwrlock_time32(pthread_rwlock_t *restrict rw, const struct timespec32 *restrict ts32)
6{
7 return pthread_rwlock_timedwrlock(rw, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/pthread_timedjoin_np_time32.c created+10
...@@ -0,0 +1,10 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4#include <pthread.h>
5
6int __pthread_timedjoin_np_time32(pthread_t t, void **res, const struct timespec32 *at32)
7{
8 return pthread_timedjoin_np(t, res, !at32 ? 0 : (&(struct timespec){
9 .tv_sec = at32->tv_sec, .tv_nsec = at32->tv_nsec}));
10}
lib/libc/musl/compat/time32/recvmmsg_time32.c created+10
...@@ -0,0 +1,10 @@
1#include "time32.h"
2#define _GNU_SOURCE
3#include <time.h>
4#include <sys/socket.h>
5
6int __recvmmsg_time32(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags, struct timespec32 *ts32)
7{
8 return recvmmsg(fd, msgvec, vlen, flags, ts32 ? (&(struct timespec){
9 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}) : 0);
10}
lib/libc/musl/compat/time32/sched_rr_get_interval_time32.c created+13
...@@ -0,0 +1,13 @@
1#include "time32.h"
2#include <time.h>
3#include <sched.h>
4
5int __sched_rr_get_interval_time32(pid_t pid, struct timespec32 *ts32)
6{
7 struct timespec ts;
8 int r = sched_rr_get_interval(pid, &ts);
9 if (r) return r;
10 ts32->tv_sec = ts.tv_sec;
11 ts32->tv_nsec = ts.tv_nsec;
12 return r;
13}
lib/libc/musl/compat/time32/select_time32.c created+10
...@@ -0,0 +1,10 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/time.h>
4#include <sys/select.h>
5
6int __select_time32(int n, fd_set *restrict rfds, fd_set *restrict wfds, fd_set *restrict efds, struct timeval32 *restrict tv32)
7{
8 return select(n, rfds, wfds, efds, !tv32 ? 0 : (&(struct timeval){
9 .tv_sec = tv32->tv_sec, .tv_usec = tv32->tv_usec}));
10}
lib/libc/musl/compat/time32/sem_timedwait_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <semaphore.h>
4
5int __sem_timedwait_time32(sem_t *sem, const struct timespec32 *restrict ts32)
6{
7 return sem_timedwait(sem, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/semtimedop_time32.c created+10
...@@ -0,0 +1,10 @@
1#include "time32.h"
2#define _GNU_SOURCE
3#include <sys/sem.h>
4#include <time.h>
5
6int __semtimedop_time32(int id, struct sembuf *buf, size_t n, const struct timespec32 *ts32)
7{
8 return semtimedop(id, buf, n, !ts32 ? 0 : (&(struct timespec){
9 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
10}
lib/libc/musl/compat/time32/setitimer_time32.c created+25
...@@ -0,0 +1,25 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/time.h>
4
5int __setitimer_time32(int which, const struct itimerval32 *restrict new32, struct itimerval32 *restrict old32)
6{
7 struct itimerval old;
8 int r = setitimer(which, (&(struct itimerval){
9 .it_interval.tv_sec = new32->it_interval.tv_sec,
10 .it_interval.tv_usec = new32->it_interval.tv_usec,
11 .it_value.tv_sec = new32->it_value.tv_sec,
12 .it_value.tv_usec = new32->it_value.tv_usec}), &old);
13 if (r) return r;
14 /* The above call has already committed to success by changing the
15 * timer setting, so we can't fail on out-of-range old value.
16 * Since these are relative times, values large enough to overflow
17 * don't make sense anyway. */
18 if (old32) {
19 old32->it_interval.tv_sec = old.it_interval.tv_sec;
20 old32->it_interval.tv_usec = old.it_interval.tv_usec;
21 old32->it_value.tv_sec = old.it_value.tv_sec;
22 old32->it_value.tv_usec = old.it_value.tv_usec;
23 }
24 return 0;
25}
lib/libc/musl/compat/time32/settimeofday_time32.c created+10
...@@ -0,0 +1,10 @@
1#define _BSD_SOURCE
2#include "time32.h"
3#include <sys/time.h>
4
5int __settimeofday_time32(const struct timeval32 *tv32, const void *tz)
6{
7 return settimeofday(!tv32 ? 0 : (&(struct timeval){
8 .tv_sec = tv32->tv_sec,
9 .tv_usec = tv32->tv_usec}), 0);
10}
lib/libc/musl/compat/time32/sigtimedwait_time32.c created+9
...@@ -0,0 +1,9 @@
1#include "time32.h"
2#include <time.h>
3#include <signal.h>
4
5int __sigtimedwait_time32(const sigset_t *restrict set, siginfo_t *restrict si, const struct timespec32 *restrict ts32)
6{
7 return sigtimedwait(set, si, !ts32 ? 0 : (&(struct timespec){
8 .tv_sec = ts32->tv_sec, .tv_nsec = ts32->tv_nsec}));
9}
lib/libc/musl/compat/time32/stat_time32.c created+17
...@@ -0,0 +1,17 @@
1#include "time32.h"
2#include <time.h>
3#include <string.h>
4#include <sys/stat.h>
5#include <stddef.h>
6
7struct stat32;
8
9int __stat_time32(const char *restrict path, struct stat32 *restrict st32)
10{
11 struct stat st;
12 int r = stat(path, &st);
13 if (!r) memcpy(st32, &st, offsetof(struct stat, st_atim));
14 return r;
15}
16
17weak_alias(stat, stat64);
lib/libc/musl/compat/time32/stime32.c created+8
...@@ -0,0 +1,8 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4
5int __stime32(const time32_t *t)
6{
7 return stime(&(time_t){*t});
8}
lib/libc/musl/compat/time32/thrd_sleep_time32.c created+16
...@@ -0,0 +1,16 @@
1#include "time32.h"
2#include <time.h>
3#include <threads.h>
4#include <errno.h>
5
6int __thrd_sleep_time32(const struct timespec32 *req32, struct timespec32 *rem32)
7{
8 struct timespec rem;
9 int ret = thrd_sleep((&(struct timespec){
10 .tv_sec = req32->tv_sec, .tv_nsec = req32->tv_nsec}), &rem);
11 if (ret<0 && errno==EINTR && rem32) {
12 rem32->tv_sec = rem.tv_sec;
13 rem32->tv_nsec = rem.tv_nsec;
14 }
15 return ret;
16}
lib/libc/musl/compat/time32/time32.c created+15
...@@ -0,0 +1,15 @@
1#include "time32.h"
2#include <time.h>
3#include <errno.h>
4#include <stdint.h>
5
6time32_t __time32(time32_t *p)
7{
8 time_t t = time(0);
9 if (t < INT32_MIN || t > INT32_MAX) {
10 errno = EOVERFLOW;
11 return -1;
12 }
13 if (p) *p = t;
14 return t;
15}
lib/libc/musl/compat/time32/time32.h created+91
...@@ -0,0 +1,91 @@
1#ifndef TIME32_H
2#define TIME32_H
3
4#include <sys/types.h>
5
6typedef long time32_t;
7
8struct timeval32 {
9 long tv_sec;
10 long tv_usec;
11};
12
13struct itimerval32 {
14 struct timeval32 it_interval;
15 struct timeval32 it_value;
16};
17
18struct timespec32 {
19 long tv_sec;
20 long tv_nsec;
21};
22
23struct itimerspec32 {
24 struct timespec32 it_interval;
25 struct timespec32 it_value;
26};
27
28int __adjtime32() __asm__("adjtime");
29int __adjtimex_time32() __asm__("adjtimex");
30int __aio_suspend_time32() __asm__("aio_suspend");
31int __clock_adjtime32() __asm__("clock_adjtime");
32int __clock_getres_time32() __asm__("clock_getres");
33int __clock_gettime32() __asm__("clock_gettime");
34int __clock_nanosleep_time32() __asm__("clock_nanosleep");
35int __clock_settime32() __asm__("clock_settime");
36int __cnd_timedwait_time32() __asm__("cnd_timedwait");
37char *__ctime32() __asm__("ctime");
38char *__ctime32_r() __asm__("ctime_r");
39double __difftime32() __asm__("difftime");
40int __fstat_time32() __asm__("fstat");
41int __fstatat_time32() __asm__("fstatat");
42int __ftime32() __asm__("ftime");
43int __futimens_time32() __asm__("futimens");
44int __futimes_time32() __asm__("futimes");
45int __futimesat_time32() __asm__("futimesat");
46int __getitimer_time32() __asm__("getitimer");
47int __getrusage_time32() __asm__("getrusage");
48int __gettimeofday_time32() __asm__("gettimeofday");
49struct tm *__gmtime32() __asm__("gmtime");
50struct tm *__gmtime32_r() __asm__("gmtime_r");
51struct tm *__localtime32() __asm__("localtime");
52struct tm *__localtime32_r() __asm__("localtime_r");
53int __lstat_time32() __asm__("lstat");
54int __lutimes_time32() __asm__("lutimes");
55time32_t __mktime32() __asm__("mktime");
56ssize_t __mq_timedreceive_time32() __asm__("mq_timedreceive");
57int __mq_timedsend_time32() __asm__("mq_timedsend");
58int __mtx_timedlock_time32() __asm__("mtx_timedlock");
59int __nanosleep_time32() __asm__("nanosleep");
60int __ppoll_time32() __asm__("ppoll");
61int __pselect_time32() __asm__("pselect");
62int __pthread_cond_timedwait_time32() __asm__("pthread_cond_timedwait");
63int __pthread_mutex_timedlock_time32() __asm__("pthread_mutex_timedlock");
64int __pthread_rwlock_timedrdlock_time32() __asm__("pthread_rwlock_timedrdlock");
65int __pthread_rwlock_timedwrlock_time32() __asm__("pthread_rwlock_timedwrlock");
66int __pthread_timedjoin_np_time32() __asm__("pthread_timedjoin_np");
67int __recvmmsg_time32() __asm__("recvmmsg");
68int __sched_rr_get_interval_time32() __asm__("sched_rr_get_interval");
69int __select_time32() __asm__("select");
70int __sem_timedwait_time32() __asm__("sem_timedwait");
71int __semtimedop_time32() __asm__("semtimedop");
72int __setitimer_time32() __asm__("setitimer");
73int __settimeofday_time32() __asm__("settimeofday");
74int __sigtimedwait_time32() __asm__("sigtimedwait");
75int __stat_time32() __asm__("stat");
76int __stime32() __asm__("stime");
77int __thrd_sleep_time32() __asm__("thrd_sleep");
78time32_t __time32() __asm__("time");
79time32_t __time32gm() __asm__("timegm");
80int __timer_gettime32() __asm__("timer_gettime");
81int __timer_settime32() __asm__("timer_settime");
82int __timerfd_gettime32() __asm__("timerfd_gettime");
83int __timerfd_settime32() __asm__("timerfd_settime");
84int __timespec_get_time32() __asm__("timespec_get");
85int __utime_time32() __asm__("utime");
86int __utimensat_time32() __asm__("utimensat");
87int __utimes_time32() __asm__("utimes");
88pid_t __wait3_time32() __asm__("wait3");
89pid_t __wait4_time32() __asm__("wait4");
90
91#endif
lib/libc/musl/compat/time32/time32gm.c created+15
...@@ -0,0 +1,15 @@
1#define _GNU_SOURCE
2#include "time32.h"
3#include <time.h>
4#include <errno.h>
5#include <stdint.h>
6
7time32_t __time32gm(struct tm *tm)
8{
9 time_t t = timegm(tm);
10 if (t < INT32_MIN || t > INT32_MAX) {
11 errno = EOVERFLOW;
12 return -1;
13 }
14 return t;
15}
lib/libc/musl/compat/time32/timer_gettime32.c created+15
...@@ -0,0 +1,15 @@
1#include "time32.h"
2#include <time.h>
3
4int __timer_gettime32(timer_t t, struct itimerspec32 *val32)
5{
6 struct itimerspec old;
7 int r = timer_gettime(t, &old);
8 if (r) return r;
9 /* No range checking for consistency with settime */
10 val32->it_interval.tv_sec = old.it_interval.tv_sec;
11 val32->it_interval.tv_nsec = old.it_interval.tv_nsec;
12 val32->it_value.tv_sec = old.it_value.tv_sec;
13 val32->it_value.tv_nsec = old.it_value.tv_nsec;
14 return 0;
15}
lib/libc/musl/compat/time32/timer_settime32.c created+25
...@@ -0,0 +1,25 @@
1#include "time32.h"
2#include <time.h>
3
4int __timer_settime32(timer_t t, int flags, const struct itimerspec32 *restrict val32, struct itimerspec32 *restrict old32)
5{
6 struct itimerspec old;
7 int r = timer_settime(t, flags, (&(struct itimerspec){
8 .it_interval.tv_sec = val32->it_interval.tv_sec,
9 .it_interval.tv_nsec = val32->it_interval.tv_nsec,
10 .it_value.tv_sec = val32->it_value.tv_sec,
11 .it_value.tv_nsec = val32->it_value.tv_nsec}),
12 old32 ? &old : 0);
13 if (r) return r;
14 /* The above call has already committed to success by changing the
15 * timer setting, so we can't fail on out-of-range old value.
16 * Since these are relative times, values large enough to overflow
17 * don't make sense anyway. */
18 if (old32) {
19 old32->it_interval.tv_sec = old.it_interval.tv_sec;
20 old32->it_interval.tv_nsec = old.it_interval.tv_nsec;
21 old32->it_value.tv_sec = old.it_value.tv_sec;
22 old32->it_value.tv_nsec = old.it_value.tv_nsec;
23 }
24 return 0;
25}
lib/libc/musl/compat/time32/timerfd_gettime32.c created+16
...@@ -0,0 +1,16 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/timerfd.h>
4
5int __timerfd_gettime32(int t, struct itimerspec32 *val32)
6{
7 struct itimerspec old;
8 int r = timerfd_gettime(t, &old);
9 if (r) return r;
10 /* No range checking for consistency with settime */
11 val32->it_interval.tv_sec = old.it_interval.tv_sec;
12 val32->it_interval.tv_nsec = old.it_interval.tv_nsec;
13 val32->it_value.tv_sec = old.it_value.tv_sec;
14 val32->it_value.tv_nsec = old.it_value.tv_nsec;
15 return 0;
16}
lib/libc/musl/compat/time32/timerfd_settime32.c created+26
...@@ -0,0 +1,26 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/timerfd.h>
4
5int __timerfd_settime32(int t, int flags, const struct itimerspec32 *restrict val32, struct itimerspec32 *restrict old32)
6{
7 struct itimerspec old;
8 int r = timerfd_settime(t, flags, (&(struct itimerspec){
9 .it_interval.tv_sec = val32->it_interval.tv_sec,
10 .it_interval.tv_nsec = val32->it_interval.tv_nsec,
11 .it_value.tv_sec = val32->it_value.tv_sec,
12 .it_value.tv_nsec = val32->it_value.tv_nsec}),
13 old32 ? &old : 0);
14 if (r) return r;
15 /* The above call has already committed to success by changing the
16 * timer setting, so we can't fail on out-of-range old value.
17 * Since these are relative times, values large enough to overflow
18 * don't make sense anyway. */
19 if (old32) {
20 old32->it_interval.tv_sec = old.it_interval.tv_sec;
21 old32->it_interval.tv_nsec = old.it_interval.tv_nsec;
22 old32->it_value.tv_sec = old.it_value.tv_sec;
23 old32->it_value.tv_nsec = old.it_value.tv_nsec;
24 }
25 return 0;
26}
lib/libc/musl/compat/time32/timespec_get_time32.c created+18
...@@ -0,0 +1,18 @@
1#include "time32.h"
2#include <time.h>
3#include <errno.h>
4#include <stdint.h>
5
6int __timespec_get_time32(struct timespec32 *ts32, int base)
7{
8 struct timespec ts;
9 int r = timespec_get(&ts, base);
10 if (!r) return r;
11 if (ts.tv_sec < INT32_MIN || ts.tv_sec > INT32_MAX) {
12 errno = EOVERFLOW;
13 return 0;
14 }
15 ts32->tv_sec = ts.tv_sec;
16 ts32->tv_nsec = ts.tv_nsec;
17 return r;
18}
lib/libc/musl/compat/time32/utime_time32.c created+14
...@@ -0,0 +1,14 @@
1#include "time32.h"
2#include <time.h>
3#include <utime.h>
4
5struct utimbuf32 {
6 time32_t actime;
7 time32_t modtime;
8};
9
10int __utime_time32(const char *path, const struct utimbuf32 *times32)
11{
12 return utime(path, !times32 ? 0 : (&(struct utimbuf){
13 .actime = times32->actime, .modtime = times32->modtime}));
14}
lib/libc/musl/compat/time32/utimensat_time32.c created+11
...@@ -0,0 +1,11 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/stat.h>
4
5int __utimensat_time32(int fd, const char *path, const struct timespec32 times32[2], int flags)
6{
7 return utimensat(fd, path, !times32 ? 0 : ((struct timespec[2]){
8 {.tv_sec = times32[0].tv_sec,.tv_nsec = times32[0].tv_nsec},
9 {.tv_sec = times32[1].tv_sec,.tv_nsec = times32[1].tv_nsec}}),
10 flags);
11}
lib/libc/musl/compat/time32/utimes_time32.c created+11
...@@ -0,0 +1,11 @@
1#include "time32.h"
2#include <time.h>
3#include <sys/time.h>
4#include <sys/stat.h>
5
6int __utimes_time32(const char *path, const struct timeval32 times32[2])
7{
8 return utimes(path, !times32 ? 0 : ((struct timeval[2]){
9 {.tv_sec = times32[0].tv_sec,.tv_usec = times32[0].tv_usec},
10 {.tv_sec = times32[1].tv_sec,.tv_usec = times32[1].tv_usec}}));
11}
lib/libc/musl/compat/time32/wait3_time32.c created+40
...@@ -0,0 +1,40 @@
1#define _BSD_SOURCE
2#include "time32.h"
3#include <string.h>
4#include <stddef.h>
5#include <sys/wait.h>
6
7struct compat_rusage {
8 struct timeval32 ru_utime;
9 struct timeval32 ru_stime;
10 long ru_maxrss;
11 long ru_ixrss;
12 long ru_idrss;
13 long ru_isrss;
14 long ru_minflt;
15 long ru_majflt;
16 long ru_nswap;
17 long ru_inblock;
18 long ru_oublock;
19 long ru_msgsnd;
20 long ru_msgrcv;
21 long ru_nsignals;
22 long ru_nvcsw;
23 long ru_nivcsw;
24};
25
26pid_t __wait3_time32(int *status, int options, struct compat_rusage *usage)
27{
28 struct rusage ru;
29 int r = wait3(status, options, usage ? &ru : 0);
30 if (!r && usage) {
31 usage->ru_utime.tv_sec = ru.ru_utime.tv_sec;
32 usage->ru_utime.tv_usec = ru.ru_utime.tv_usec;
33 usage->ru_stime.tv_sec = ru.ru_stime.tv_sec;
34 usage->ru_stime.tv_usec = ru.ru_stime.tv_usec;
35 memcpy(&usage->ru_maxrss, &ru.ru_maxrss,
36 sizeof(struct compat_rusage) -
37 offsetof(struct compat_rusage, ru_maxrss));
38 }
39 return r;
40}
lib/libc/musl/compat/time32/wait4_time32.c created+40
...@@ -0,0 +1,40 @@
1#define _BSD_SOURCE
2#include "time32.h"
3#include <string.h>
4#include <stddef.h>
5#include <sys/wait.h>
6
7struct compat_rusage {
8 struct timeval32 ru_utime;
9 struct timeval32 ru_stime;
10 long ru_maxrss;
11 long ru_ixrss;
12 long ru_idrss;
13 long ru_isrss;
14 long ru_minflt;
15 long ru_majflt;
16 long ru_nswap;
17 long ru_inblock;
18 long ru_oublock;
19 long ru_msgsnd;
20 long ru_msgrcv;
21 long ru_nsignals;
22 long ru_nvcsw;
23 long ru_nivcsw;
24};
25
26pid_t __wait4_time32(pid_t pid, int *status, int options, struct compat_rusage *usage)
27{
28 struct rusage ru;
29 int r = wait4(pid, status, options, usage ? &ru : 0);
30 if (!r && usage) {
31 usage->ru_utime.tv_sec = ru.ru_utime.tv_sec;
32 usage->ru_utime.tv_usec = ru.ru_utime.tv_usec;
33 usage->ru_stime.tv_sec = ru.ru_stime.tv_sec;
34 usage->ru_stime.tv_usec = ru.ru_stime.tv_usec;
35 memcpy(&usage->ru_maxrss, &ru.ru_maxrss,
36 sizeof(struct compat_rusage) -
37 offsetof(struct compat_rusage, ru_maxrss));
38 }
39 return r;
40}
lib/libc/musl/include/aio.h+4
...@@ -62,6 +62,10 @@ int lio_listio(int, struct aiocb *__restrict const *__restrict, int, struct sige...@@ -62,6 +62,10 @@ int lio_listio(int, struct aiocb *__restrict const *__restrict, int, struct sige
62#define off64_t off_t62#define off64_t off_t
63#endif63#endif
6464
65#if _REDIR_TIME64
66__REDIR(aio_suspend, __aio_suspend_time64);
67#endif
68
65#ifdef __cplusplus69#ifdef __cplusplus
66}70}
67#endif71#endif
lib/libc/musl/include/alloca.h-2
...@@ -10,9 +10,7 @@ extern "C" {...@@ -10,9 +10,7 @@ extern "C" {
1010
11void *alloca(size_t);11void *alloca(size_t);
1212
13#ifdef __GNUC__
14#define alloca __builtin_alloca13#define alloca __builtin_alloca
15#endif
1614
17#ifdef __cplusplus15#ifdef __cplusplus
18}16}
lib/libc/musl/include/alltypes.h.in+18-1
...@@ -1,3 +1,7 @@...@@ -1,3 +1,7 @@
1#define __LITTLE_ENDIAN 1234
2#define __BIG_ENDIAN 4321
3#define __USE_TIME_BITS64 1
4
1TYPEDEF unsigned _Addr size_t;5TYPEDEF unsigned _Addr size_t;
2TYPEDEF unsigned _Addr uintptr_t;6TYPEDEF unsigned _Addr uintptr_t;
3TYPEDEF _Addr ptrdiff_t;7TYPEDEF _Addr ptrdiff_t;
...@@ -5,6 +9,8 @@ TYPEDEF _Addr ssize_t;...@@ -5,6 +9,8 @@ TYPEDEF _Addr ssize_t;
5TYPEDEF _Addr intptr_t;9TYPEDEF _Addr intptr_t;
6TYPEDEF _Addr regoff_t;10TYPEDEF _Addr regoff_t;
7TYPEDEF _Reg register_t;11TYPEDEF _Reg register_t;
12TYPEDEF _Int64 time_t;
13TYPEDEF _Int64 suseconds_t;
814
9TYPEDEF signed char int8_t;15TYPEDEF signed char int8_t;
10TYPEDEF signed short int16_t;16TYPEDEF signed short int16_t;
...@@ -35,7 +41,7 @@ TYPEDEF void * timer_t;...@@ -35,7 +41,7 @@ TYPEDEF void * timer_t;
35TYPEDEF int clockid_t;41TYPEDEF int clockid_t;
36TYPEDEF long clock_t;42TYPEDEF long clock_t;
37STRUCT timeval { time_t tv_sec; suseconds_t tv_usec; };43STRUCT timeval { time_t tv_sec; suseconds_t tv_usec; };
38STRUCT timespec { time_t tv_sec; long tv_nsec; };44STRUCT timespec { time_t tv_sec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER==4321); long tv_nsec; int :8*(sizeof(time_t)-sizeof(long))*(__BYTE_ORDER!=4321); };
3945
40TYPEDEF int pid_t;46TYPEDEF int pid_t;
41TYPEDEF unsigned id_t;47TYPEDEF unsigned id_t;
...@@ -60,6 +66,9 @@ TYPEDEF struct { unsigned __attr[2]; } pthread_rwlockattr_t;...@@ -60,6 +66,9 @@ TYPEDEF struct { unsigned __attr[2]; } pthread_rwlockattr_t;
60STRUCT _IO_FILE { char __x; };66STRUCT _IO_FILE { char __x; };
61TYPEDEF struct _IO_FILE FILE;67TYPEDEF struct _IO_FILE FILE;
6268
69TYPEDEF __builtin_va_list va_list;
70TYPEDEF __builtin_va_list __isoc_va_list;
71
63TYPEDEF struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;72TYPEDEF struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
6473
65TYPEDEF struct __locale_struct * locale_t;74TYPEDEF struct __locale_struct * locale_t;
...@@ -71,6 +80,14 @@ STRUCT iovec { void *iov_base; size_t iov_len; };...@@ -71,6 +80,14 @@ STRUCT iovec { void *iov_base; size_t iov_len; };
71TYPEDEF unsigned socklen_t;80TYPEDEF unsigned socklen_t;
72TYPEDEF unsigned short sa_family_t;81TYPEDEF unsigned short sa_family_t;
7382
83TYPEDEF struct { union { int __i[sizeof(long)==8?14:9]; volatile int __vi[sizeof(long)==8?14:9]; unsigned long __s[sizeof(long)==8?7:9]; } __u; } pthread_attr_t;
84TYPEDEF struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } pthread_mutex_t;
85TYPEDEF struct { union { int __i[sizeof(long)==8?10:6]; volatile int __vi[sizeof(long)==8?10:6]; volatile void *volatile __p[sizeof(long)==8?5:6]; } __u; } mtx_t;
86TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } pthread_cond_t;
87TYPEDEF struct { union { int __i[12]; volatile int __vi[12]; void *__p[12*sizeof(int)/sizeof(void*)]; } __u; } cnd_t;
88TYPEDEF struct { union { int __i[sizeof(long)==8?14:8]; volatile int __vi[sizeof(long)==8?14:8]; void *__p[sizeof(long)==8?7:8]; } __u; } pthread_rwlock_t;
89TYPEDEF struct { union { int __i[sizeof(long)==8?8:5]; volatile int __vi[sizeof(long)==8?8:5]; void *__p[sizeof(long)==8?4:5]; } __u; } pthread_barrier_t;
90
74#undef _Addr91#undef _Addr
75#undef _Int6492#undef _Int64
76#undef _Reg93#undef _Reg
lib/libc/musl/include/arpa/nameser.h-1
...@@ -7,7 +7,6 @@ extern "C" {...@@ -7,7 +7,6 @@ extern "C" {
77
8#include <stddef.h>8#include <stddef.h>
9#include <stdint.h>9#include <stdint.h>
10#include <endian.h>
1110
12#define __NAMESER 1999100611#define __NAMESER 19991006
13#define NS_PACKETSZ 51212#define NS_PACKETSZ 512
lib/libc/musl/include/dirent.h+2-12
...@@ -15,19 +15,9 @@ extern "C" {...@@ -15,19 +15,9 @@ extern "C" {
1515
16#include <bits/alltypes.h>16#include <bits/alltypes.h>
1717
18typedef struct __dirstream DIR;18#include <bits/dirent.h>
19
20#define _DIRENT_HAVE_D_RECLEN
21#define _DIRENT_HAVE_D_OFF
22#define _DIRENT_HAVE_D_TYPE
2319
24struct dirent {20typedef struct __dirstream DIR;
25 ino_t d_ino;
26 off_t d_off;
27 unsigned short d_reclen;
28 unsigned char d_type;
29 char d_name[256];
30};
3121
32#define d_fileno d_ino22#define d_fileno d_ino
3323
lib/libc/musl/include/dlfcn.h+4
...@@ -35,6 +35,10 @@ int dladdr(const void *, Dl_info *);...@@ -35,6 +35,10 @@ int dladdr(const void *, Dl_info *);
35int dlinfo(void *, int, void *);35int dlinfo(void *, int, void *);
36#endif36#endif
3737
38#if _REDIR_TIME64
39__REDIR(dlsym, __dlsym_time64);
40#endif
41
38#ifdef __cplusplus42#ifdef __cplusplus
39}43}
40#endif44#endif
lib/libc/musl/include/endian.h+21-23
...@@ -3,25 +3,19 @@...@@ -3,25 +3,19 @@
33
4#include <features.h>4#include <features.h>
55
6#define __LITTLE_ENDIAN 12346#define __NEED_uint16_t
7#define __BIG_ENDIAN 43217#define __NEED_uint32_t
8#define __PDP_ENDIAN 34128#define __NEED_uint64_t
99
10#if defined(__GNUC__) && defined(__BYTE_ORDER__)10#include <bits/alltypes.h>
11#define __BYTE_ORDER __BYTE_ORDER__
12#else
13#include <bits/endian.h>
14#endif
1511
16#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)12#define __PDP_ENDIAN 3412
1713
18#define BIG_ENDIAN __BIG_ENDIAN14#define BIG_ENDIAN __BIG_ENDIAN
19#define LITTLE_ENDIAN __LITTLE_ENDIAN15#define LITTLE_ENDIAN __LITTLE_ENDIAN
20#define PDP_ENDIAN __PDP_ENDIAN16#define PDP_ENDIAN __PDP_ENDIAN
21#define BYTE_ORDER __BYTE_ORDER17#define BYTE_ORDER __BYTE_ORDER
2218
23#include <stdint.h>
24
25static __inline uint16_t __bswap16(uint16_t __x)19static __inline uint16_t __bswap16(uint16_t __x)
26{20{
27 return __x<<8 | __x>>8;21 return __x<<8 | __x>>8;
...@@ -40,43 +34,47 @@ static __inline uint64_t __bswap64(uint64_t __x)...@@ -40,43 +34,47 @@ static __inline uint64_t __bswap64(uint64_t __x)
40#if __BYTE_ORDER == __LITTLE_ENDIAN34#if __BYTE_ORDER == __LITTLE_ENDIAN
41#define htobe16(x) __bswap16(x)35#define htobe16(x) __bswap16(x)
42#define be16toh(x) __bswap16(x)36#define be16toh(x) __bswap16(x)
43#define betoh16(x) __bswap16(x)
44#define htobe32(x) __bswap32(x)37#define htobe32(x) __bswap32(x)
45#define be32toh(x) __bswap32(x)38#define be32toh(x) __bswap32(x)
46#define betoh32(x) __bswap32(x)
47#define htobe64(x) __bswap64(x)39#define htobe64(x) __bswap64(x)
48#define be64toh(x) __bswap64(x)40#define be64toh(x) __bswap64(x)
49#define betoh64(x) __bswap64(x)
50#define htole16(x) (uint16_t)(x)41#define htole16(x) (uint16_t)(x)
51#define le16toh(x) (uint16_t)(x)42#define le16toh(x) (uint16_t)(x)
52#define letoh16(x) (uint16_t)(x)
53#define htole32(x) (uint32_t)(x)43#define htole32(x) (uint32_t)(x)
54#define le32toh(x) (uint32_t)(x)44#define le32toh(x) (uint32_t)(x)
55#define letoh32(x) (uint32_t)(x)
56#define htole64(x) (uint64_t)(x)45#define htole64(x) (uint64_t)(x)
57#define le64toh(x) (uint64_t)(x)46#define le64toh(x) (uint64_t)(x)
58#define letoh64(x) (uint64_t)(x)
59#else47#else
60#define htobe16(x) (uint16_t)(x)48#define htobe16(x) (uint16_t)(x)
61#define be16toh(x) (uint16_t)(x)49#define be16toh(x) (uint16_t)(x)
62#define betoh16(x) (uint16_t)(x)
63#define htobe32(x) (uint32_t)(x)50#define htobe32(x) (uint32_t)(x)
64#define be32toh(x) (uint32_t)(x)51#define be32toh(x) (uint32_t)(x)
65#define betoh32(x) (uint32_t)(x)
66#define htobe64(x) (uint64_t)(x)52#define htobe64(x) (uint64_t)(x)
67#define be64toh(x) (uint64_t)(x)53#define be64toh(x) (uint64_t)(x)
68#define betoh64(x) (uint64_t)(x)
69#define htole16(x) __bswap16(x)54#define htole16(x) __bswap16(x)
70#define le16toh(x) __bswap16(x)55#define le16toh(x) __bswap16(x)
71#define letoh16(x) __bswap16(x)
72#define htole32(x) __bswap32(x)56#define htole32(x) __bswap32(x)
73#define le32toh(x) __bswap32(x)57#define le32toh(x) __bswap32(x)
74#define letoh32(x) __bswap32(x)
75#define htole64(x) __bswap64(x)58#define htole64(x) __bswap64(x)
76#define le64toh(x) __bswap64(x)59#define le64toh(x) __bswap64(x)
77#define letoh64(x) __bswap64(x)
78#endif60#endif
7961
62#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
63#if __BYTE_ORDER == __LITTLE_ENDIAN
64#define betoh16(x) __bswap16(x)
65#define betoh32(x) __bswap32(x)
66#define betoh64(x) __bswap64(x)
67#define letoh16(x) (uint16_t)(x)
68#define letoh32(x) (uint32_t)(x)
69#define letoh64(x) (uint64_t)(x)
70#else
71#define betoh16(x) (uint16_t)(x)
72#define betoh32(x) (uint32_t)(x)
73#define betoh64(x) (uint64_t)(x)
74#define letoh16(x) __bswap16(x)
75#define letoh32(x) __bswap32(x)
76#define letoh64(x) __bswap64(x)
77#endif
80#endif78#endif
8179
82#endif80#endif
lib/libc/musl/include/features.h+2
...@@ -35,4 +35,6 @@...@@ -35,4 +35,6 @@
35#define _Noreturn35#define _Noreturn
36#endif36#endif
3737
38#define __REDIR(x,y) __typeof__(x) x __asm__(#y)
39
38#endif40#endif
lib/libc/musl/include/limits.h+13-5
...@@ -3,9 +3,7 @@...@@ -3,9 +3,7 @@
33
4#include <features.h>4#include <features.h>
55
6/* Most limits are system-specific */6#include <bits/alltypes.h> /* __LONG_MAX */
7
8#include <bits/limits.h>
97
10/* Support signed or unsigned plain-char */8/* Support signed or unsigned plain-char */
119
...@@ -17,8 +15,6 @@...@@ -17,8 +15,6 @@
17#define CHAR_MAX 12715#define CHAR_MAX 127
18#endif16#endif
1917
20/* Some universal constants... */
21
22#define CHAR_BIT 818#define CHAR_BIT 8
23#define SCHAR_MIN (-128)19#define SCHAR_MIN (-128)
24#define SCHAR_MAX 12720#define SCHAR_MAX 127
...@@ -30,8 +26,10 @@...@@ -30,8 +26,10 @@
30#define INT_MAX 0x7fffffff26#define INT_MAX 0x7fffffff
31#define UINT_MAX 0xffffffffU27#define UINT_MAX 0xffffffffU
32#define LONG_MIN (-LONG_MAX-1)28#define LONG_MIN (-LONG_MAX-1)
29#define LONG_MAX __LONG_MAX
33#define ULONG_MAX (2UL*LONG_MAX+1)30#define ULONG_MAX (2UL*LONG_MAX+1)
34#define LLONG_MIN (-LLONG_MAX-1)31#define LLONG_MIN (-LLONG_MAX-1)
32#define LLONG_MAX 0x7fffffffffffffffLL
35#define ULLONG_MAX (2ULL*LLONG_MAX+1)33#define ULLONG_MAX (2ULL*LLONG_MAX+1)
3634
37#define MB_LEN_MAX 435#define MB_LEN_MAX 4
...@@ -39,9 +37,13 @@...@@ -39,9 +37,13 @@
39#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \37#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
40 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)38 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
4139
40#include <bits/limits.h>
41
42#define PIPE_BUF 409642#define PIPE_BUF 4096
43#define FILESIZEBITS 6443#define FILESIZEBITS 64
44#ifndef NAME_MAX
44#define NAME_MAX 25545#define NAME_MAX 255
46#endif
45#define PATH_MAX 409647#define PATH_MAX 4096
46#define NGROUPS_MAX 3248#define NGROUPS_MAX 32
47#define ARG_MAX 13107249#define ARG_MAX 131072
...@@ -53,6 +55,12 @@...@@ -53,6 +55,12 @@
53#define TTY_NAME_MAX 3255#define TTY_NAME_MAX 32
54#define HOST_NAME_MAX 25556#define HOST_NAME_MAX 255
5557
58#if LONG_MAX == 0x7fffffffL
59#define LONG_BIT 32
60#else
61#define LONG_BIT 64
62#endif
63
56/* Implementation choices... */64/* Implementation choices... */
5765
58#define PTHREAD_KEYS_MAX 12866#define PTHREAD_KEYS_MAX 128
lib/libc/musl/include/mqueue.h+5
...@@ -30,6 +30,11 @@ ssize_t mq_timedreceive(mqd_t, char *__restrict, size_t, unsigned *__restrict, c...@@ -30,6 +30,11 @@ ssize_t mq_timedreceive(mqd_t, char *__restrict, size_t, unsigned *__restrict, c
30int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *);30int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *);
31int mq_unlink(const char *);31int mq_unlink(const char *);
3232
33#if _REDIR_TIME64
34__REDIR(mq_timedreceive, __mq_timedreceive_time64);
35__REDIR(mq_timedsend, __mq_timedsend_time64);
36#endif
37
33#ifdef __cplusplus38#ifdef __cplusplus
34}39}
35#endif40#endif
lib/libc/musl/include/netinet/icmp6.h-1
...@@ -9,7 +9,6 @@ extern "C" {...@@ -9,7 +9,6 @@ extern "C" {
9#include <string.h>9#include <string.h>
10#include <sys/types.h>10#include <sys/types.h>
11#include <netinet/in.h>11#include <netinet/in.h>
12#include <endian.h>
1312
14#define ICMP6_FILTER 113#define ICMP6_FILTER 1
1514
lib/libc/musl/include/netinet/if_ether.h+1
...@@ -58,6 +58,7 @@...@@ -58,6 +58,7 @@
58#define ETH_P_ERSPAN 0x88BE58#define ETH_P_ERSPAN 0x88BE
59#define ETH_P_PREAUTH 0x88C759#define ETH_P_PREAUTH 0x88C7
60#define ETH_P_TIPC 0x88CA60#define ETH_P_TIPC 0x88CA
61#define ETH_P_LLDP 0x88CC
61#define ETH_P_MACSEC 0x88E562#define ETH_P_MACSEC 0x88E5
62#define ETH_P_8021AH 0x88E763#define ETH_P_8021AH 0x88E7
63#define ETH_P_MVRP 0x88F564#define ETH_P_MVRP 0x88F5
lib/libc/musl/include/netinet/ip.h+2-1
...@@ -7,7 +7,6 @@ extern "C" {...@@ -7,7 +7,6 @@ extern "C" {
77
8#include <stdint.h>8#include <stdint.h>
9#include <netinet/in.h>9#include <netinet/in.h>
10#include <endian.h>
1110
12struct timestamp {11struct timestamp {
13 uint8_t len;12 uint8_t len;
...@@ -191,6 +190,8 @@ struct ip_timestamp {...@@ -191,6 +190,8 @@ struct ip_timestamp {
191190
192#define IP_MSS 576191#define IP_MSS 576
193192
193#define __UAPI_DEF_IPHDR 0
194
194#ifdef __cplusplus195#ifdef __cplusplus
195}196}
196#endif197#endif
lib/libc/musl/include/netinet/ip6.h-1
...@@ -7,7 +7,6 @@ extern "C" {...@@ -7,7 +7,6 @@ extern "C" {
77
8#include <stdint.h>8#include <stdint.h>
9#include <netinet/in.h>9#include <netinet/in.h>
10#include <endian.h>
1110
12struct ip6_hdr {11struct ip6_hdr {
13 union {12 union {
lib/libc/musl/include/netinet/tcp.h+3-1
...@@ -38,6 +38,7 @@...@@ -38,6 +38,7 @@
38#define TCP_FASTOPEN_NO_COOKIE 3438#define TCP_FASTOPEN_NO_COOKIE 34
39#define TCP_ZEROCOPY_RECEIVE 3539#define TCP_ZEROCOPY_RECEIVE 35
40#define TCP_INQ 3640#define TCP_INQ 36
41#define TCP_TX_DELAY 37
4142
42#define TCP_CM_INQ TCP_INQ43#define TCP_CM_INQ TCP_INQ
4344
...@@ -97,7 +98,6 @@ enum {...@@ -97,7 +98,6 @@ enum {
97#include <sys/types.h>98#include <sys/types.h>
98#include <sys/socket.h>99#include <sys/socket.h>
99#include <stdint.h>100#include <stdint.h>
100#include <endian.h>
101101
102typedef uint32_t tcp_seq;102typedef uint32_t tcp_seq;
103103
...@@ -234,6 +234,8 @@ struct tcp_info {...@@ -234,6 +234,8 @@ struct tcp_info {
234 uint64_t tcpi_bytes_retrans;234 uint64_t tcpi_bytes_retrans;
235 uint32_t tcpi_dsack_dups;235 uint32_t tcpi_dsack_dups;
236 uint32_t tcpi_reord_seen;236 uint32_t tcpi_reord_seen;
237 uint32_t tcpi_rcv_ooopack;
238 uint32_t tcpi_snd_wnd;
237};239};
238240
239#define TCP_MD5SIG_MAXKEYLEN 80241#define TCP_MD5SIG_MAXKEYLEN 80
lib/libc/musl/include/poll.h+6
...@@ -44,6 +44,12 @@ int poll (struct pollfd *, nfds_t, int);...@@ -44,6 +44,12 @@ int poll (struct pollfd *, nfds_t, int);
44int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);44int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);
45#endif45#endif
4646
47#if _REDIR_TIME64
48#ifdef _GNU_SOURCE
49__REDIR(ppoll, __ppoll_time64);
50#endif
51#endif
52
47#ifdef __cplusplus53#ifdef __cplusplus
48}54}
49#endif55#endif
lib/libc/musl/include/pthread.h+10
...@@ -224,6 +224,16 @@ int pthread_tryjoin_np(pthread_t, void **);...@@ -224,6 +224,16 @@ int pthread_tryjoin_np(pthread_t, void **);
224int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);224int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);
225#endif225#endif
226226
227#if _REDIR_TIME64
228__REDIR(pthread_mutex_timedlock, __pthread_mutex_timedlock_time64);
229__REDIR(pthread_cond_timedwait, __pthread_cond_timedwait_time64);
230__REDIR(pthread_rwlock_timedrdlock, __pthread_rwlock_timedrdlock_time64);
231__REDIR(pthread_rwlock_timedwrlock, __pthread_rwlock_timedwrlock_time64);
232#ifdef _GNU_SOURCE
233__REDIR(pthread_timedjoin_np, __pthread_timedjoin_np_time64);
234#endif
235#endif
236
227#ifdef __cplusplus237#ifdef __cplusplus
228}238}
229#endif239#endif
lib/libc/musl/include/sched.h+8
...@@ -19,10 +19,14 @@ extern "C" {...@@ -19,10 +19,14 @@ extern "C" {
19struct sched_param {19struct sched_param {
20 int sched_priority;20 int sched_priority;
21 int __reserved1;21 int __reserved1;
22#if _REDIR_TIME64
23 long __reserved2[4];
24#else
22 struct {25 struct {
23 time_t __reserved1;26 time_t __reserved1;
24 long __reserved2;27 long __reserved2;
25 } __reserved2[2];28 } __reserved2[2];
29#endif
26 int __reserved3;30 int __reserved3;
27};31};
2832
...@@ -133,6 +137,10 @@ __CPU_op_func_S(XOR, ^)...@@ -133,6 +137,10 @@ __CPU_op_func_S(XOR, ^)
133137
134#endif138#endif
135139
140#if _REDIR_TIME64
141__REDIR(sched_rr_get_interval, __sched_rr_get_interval_time64);
142#endif
143
136#ifdef __cplusplus144#ifdef __cplusplus
137}145}
138#endif146#endif
lib/libc/musl/include/semaphore.h+4
...@@ -29,6 +29,10 @@ int sem_trywait(sem_t *);...@@ -29,6 +29,10 @@ int sem_trywait(sem_t *);
29int sem_unlink(const char *);29int sem_unlink(const char *);
30int sem_wait(sem_t *);30int sem_wait(sem_t *);
3131
32#if _REDIR_TIME64
33__REDIR(sem_timedwait, __sem_timedwait_time64);
34#endif
35
32#ifdef __cplusplus36#ifdef __cplusplus
33}37}
34#endif38#endif
lib/libc/musl/include/signal.h+8
...@@ -271,6 +271,14 @@ typedef int sig_atomic_t;...@@ -271,6 +271,14 @@ typedef int sig_atomic_t;
271void (*signal(int, void (*)(int)))(int);271void (*signal(int, void (*)(int)))(int);
272int raise(int);272int raise(int);
273273
274#if _REDIR_TIME64
275#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
276 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
277 || defined(_BSD_SOURCE)
278__REDIR(sigtimedwait, __sigtimedwait_time64);
279#endif
280#endif
281
274#ifdef __cplusplus282#ifdef __cplusplus
275}283}
276#endif284#endif
lib/libc/musl/include/sys/acct.h-1
...@@ -6,7 +6,6 @@ extern "C" {...@@ -6,7 +6,6 @@ extern "C" {
6#endif6#endif
77
8#include <features.h>8#include <features.h>
9#include <endian.h>
10#include <time.h>9#include <time.h>
11#include <stdint.h>10#include <stdint.h>
1211
lib/libc/musl/include/sys/ioctl.h+1
...@@ -4,6 +4,7 @@...@@ -4,6 +4,7 @@
4extern "C" {4extern "C" {
5#endif5#endif
66
7#include <bits/alltypes.h>
7#include <bits/ioctl.h>8#include <bits/ioctl.h>
89
9#define N_TTY 010#define N_TTY 0
lib/libc/musl/include/sys/mman.h+2
...@@ -92,6 +92,8 @@ extern "C" {...@@ -92,6 +92,8 @@ extern "C" {
92#define MADV_DODUMP 1792#define MADV_DODUMP 17
93#define MADV_WIPEONFORK 1893#define MADV_WIPEONFORK 18
94#define MADV_KEEPONFORK 1994#define MADV_KEEPONFORK 19
95#define MADV_COLD 20
96#define MADV_PAGEOUT 21
95#define MADV_HWPOISON 10097#define MADV_HWPOISON 100
96#define MADV_SOFT_OFFLINE 10198#define MADV_SOFT_OFFLINE 101
97#endif99#endif
lib/libc/musl/include/sys/prctl.h+4
...@@ -154,6 +154,10 @@ struct prctl_mm_map {...@@ -154,6 +154,10 @@ struct prctl_mm_map {
154#define PR_PAC_APDBKEY (1UL << 3)154#define PR_PAC_APDBKEY (1UL << 3)
155#define PR_PAC_APGAKEY (1UL << 4)155#define PR_PAC_APGAKEY (1UL << 4)
156156
157#define PR_SET_TAGGED_ADDR_CTRL 55
158#define PR_GET_TAGGED_ADDR_CTRL 56
159#define PR_TAGGED_ADDR_ENABLE (1UL << 0)
160
157int prctl (int, ...);161int prctl (int, ...);
158162
159#ifdef __cplusplus163#ifdef __cplusplus
lib/libc/musl/include/sys/procfs.h+3-4
...@@ -23,10 +23,9 @@ struct elf_prstatus {...@@ -23,10 +23,9 @@ struct elf_prstatus {
23 pid_t pr_ppid;23 pid_t pr_ppid;
24 pid_t pr_pgrp;24 pid_t pr_pgrp;
25 pid_t pr_sid;25 pid_t pr_sid;
26 struct timeval pr_utime;26 struct {
27 struct timeval pr_stime;27 long tv_sec, tv_usec;
28 struct timeval pr_cutime;28 } pr_utime, pr_stime, pr_cutime, pr_cstime;
29 struct timeval pr_cstime;
30 elf_gregset_t pr_reg;29 elf_gregset_t pr_reg;
31 int pr_fpvalid;30 int pr_fpvalid;
32};31};
lib/libc/musl/include/sys/ptrace.h+29
...@@ -41,6 +41,7 @@ extern "C" {...@@ -41,6 +41,7 @@ extern "C" {
41#define PTRACE_SETSIGMASK 0x420b41#define PTRACE_SETSIGMASK 0x420b
42#define PTRACE_SECCOMP_GET_FILTER 0x420c42#define PTRACE_SECCOMP_GET_FILTER 0x420c
43#define PTRACE_SECCOMP_GET_METADATA 0x420d43#define PTRACE_SECCOMP_GET_METADATA 0x420d
44#define PTRACE_GET_SYSCALL_INFO 0x420e
4445
45#define PT_READ_I PTRACE_PEEKTEXT46#define PT_READ_I PTRACE_PEEKTEXT
46#define PT_READ_D PTRACE_PEEKDATA47#define PT_READ_D PTRACE_PEEKDATA
...@@ -88,6 +89,11 @@ extern "C" {...@@ -88,6 +89,11 @@ extern "C" {
8889
89#define PTRACE_PEEKSIGINFO_SHARED 190#define PTRACE_PEEKSIGINFO_SHARED 1
9091
92#define PTRACE_SYSCALL_INFO_NONE 0
93#define PTRACE_SYSCALL_INFO_ENTRY 1
94#define PTRACE_SYSCALL_INFO_EXIT 2
95#define PTRACE_SYSCALL_INFO_SECCOMP 3
96
91#include <bits/ptrace.h>97#include <bits/ptrace.h>
9298
93struct __ptrace_peeksiginfo_args {99struct __ptrace_peeksiginfo_args {
...@@ -101,6 +107,29 @@ struct __ptrace_seccomp_metadata {...@@ -101,6 +107,29 @@ struct __ptrace_seccomp_metadata {
101 uint64_t flags;107 uint64_t flags;
102};108};
103109
110struct __ptrace_syscall_info {
111 uint8_t op;
112 uint8_t __pad[3];
113 uint32_t arch;
114 uint64_t instruction_pointer;
115 uint64_t stack_pointer;
116 union {
117 struct {
118 uint64_t nr;
119 uint64_t args[6];
120 } entry;
121 struct {
122 int64_t rval;
123 uint8_t is_error;
124 } exit;
125 struct {
126 uint64_t nr;
127 uint64_t args[6];
128 uint32_t ret_data;
129 } seccomp;
130 };
131};
132
104long ptrace(int, ...);133long ptrace(int, ...);
105134
106#ifdef __cplusplus135#ifdef __cplusplus
lib/libc/musl/include/sys/resource.h+6-1
...@@ -90,7 +90,8 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);...@@ -90,7 +90,8 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);
90#define RLIMIT_MSGQUEUE 1290#define RLIMIT_MSGQUEUE 12
91#define RLIMIT_NICE 1391#define RLIMIT_NICE 13
92#define RLIMIT_RTPRIO 1492#define RLIMIT_RTPRIO 14
93#define RLIMIT_NLIMITS 1593#define RLIMIT_RTTIME 15
94#define RLIMIT_NLIMITS 16
9495
95#define RLIM_NLIMITS RLIMIT_NLIMITS96#define RLIM_NLIMITS RLIMIT_NLIMITS
9697
...@@ -104,6 +105,10 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);...@@ -104,6 +105,10 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);
104#define rlim64_t rlim_t105#define rlim64_t rlim_t
105#endif106#endif
106107
108#if _REDIR_TIME64
109__REDIR(getrusage, __getrusage_time64);
110#endif
111
107#ifdef __cplusplus112#ifdef __cplusplus
108}113}
109#endif114#endif
lib/libc/musl/include/sys/select.h+5
...@@ -35,6 +35,11 @@ int pselect (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, co...@@ -35,6 +35,11 @@ int pselect (int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, co
35#define NFDBITS (8*(int)sizeof(long))35#define NFDBITS (8*(int)sizeof(long))
36#endif36#endif
3737
38#if _REDIR_TIME64
39__REDIR(select, __select_time64);
40__REDIR(pselect, __pselect_time64);
41#endif
42
38#ifdef __cplusplus43#ifdef __cplusplus
39}44}
40#endif45#endif
lib/libc/musl/include/sys/sem.h+6-2
...@@ -25,8 +25,6 @@ extern "C" {...@@ -25,8 +25,6 @@ extern "C" {
25#define SETVAL 1625#define SETVAL 16
26#define SETALL 1726#define SETALL 17
2727
28#include <endian.h>
29
30#include <bits/sem.h>28#include <bits/sem.h>
3129
32#define _SEM_SEMUN_UNDEFINED 130#define _SEM_SEMUN_UNDEFINED 1
...@@ -62,6 +60,12 @@ int semop(int, struct sembuf *, size_t);...@@ -62,6 +60,12 @@ int semop(int, struct sembuf *, size_t);
62int semtimedop(int, struct sembuf *, size_t, const struct timespec *);60int semtimedop(int, struct sembuf *, size_t, const struct timespec *);
63#endif61#endif
6462
63#if _REDIR_TIME64
64#ifdef _GNU_SOURCE
65__REDIR(semtimedop, __semtimedop_time64);
66#endif
67#endif
68
65#ifdef __cplusplus69#ifdef __cplusplus
66}70}
67#endif71#endif
lib/libc/musl/include/sys/socket.h+63-6
...@@ -19,6 +19,40 @@ extern "C" {...@@ -19,6 +19,40 @@ extern "C" {
1919
20#include <bits/socket.h>20#include <bits/socket.h>
2121
22struct msghdr {
23 void *msg_name;
24 socklen_t msg_namelen;
25 struct iovec *msg_iov;
26#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN
27 int __pad1;
28#endif
29 int msg_iovlen;
30#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN
31 int __pad1;
32#endif
33 void *msg_control;
34#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN
35 int __pad2;
36#endif
37 socklen_t msg_controllen;
38#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN
39 int __pad2;
40#endif
41 int msg_flags;
42};
43
44struct cmsghdr {
45#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __BIG_ENDIAN
46 int __pad1;
47#endif
48 socklen_t cmsg_len;
49#if __LONG_MAX > 0x7fffffff && __BYTE_ORDER == __LITTLE_ENDIAN
50 int __pad1;
51#endif
52 int cmsg_level;
53 int cmsg_type;
54};
55
22#ifdef _GNU_SOURCE56#ifdef _GNU_SOURCE
23struct ucred {57struct ucred {
24 pid_t pid;58 pid_t pid;
...@@ -182,8 +216,6 @@ struct linger {...@@ -182,8 +216,6 @@ struct linger {
182#define SO_PEERCRED 17216#define SO_PEERCRED 17
183#define SO_RCVLOWAT 18217#define SO_RCVLOWAT 18
184#define SO_SNDLOWAT 19218#define SO_SNDLOWAT 19
185#define SO_RCVTIMEO 20
186#define SO_SNDTIMEO 21
187#define SO_ACCEPTCONN 30219#define SO_ACCEPTCONN 30
188#define SO_PEERSEC 31220#define SO_PEERSEC 31
189#define SO_SNDBUFFORCE 32221#define SO_SNDBUFFORCE 32
...@@ -192,6 +224,28 @@ struct linger {...@@ -192,6 +224,28 @@ struct linger {
192#define SO_DOMAIN 39224#define SO_DOMAIN 39
193#endif225#endif
194226
227#ifndef SO_RCVTIMEO
228#if __LONG_MAX == 0x7fffffff
229#define SO_RCVTIMEO 66
230#define SO_SNDTIMEO 67
231#else
232#define SO_RCVTIMEO 20
233#define SO_SNDTIMEO 21
234#endif
235#endif
236
237#ifndef SO_TIMESTAMP
238#if __LONG_MAX == 0x7fffffff
239#define SO_TIMESTAMP 63
240#define SO_TIMESTAMPNS 64
241#define SO_TIMESTAMPING 65
242#else
243#define SO_TIMESTAMP 29
244#define SO_TIMESTAMPNS 35
245#define SO_TIMESTAMPING 37
246#endif
247#endif
248
195#define SO_SECURITY_AUTHENTICATION 22249#define SO_SECURITY_AUTHENTICATION 22
196#define SO_SECURITY_ENCRYPTION_TRANSPORT 23250#define SO_SECURITY_ENCRYPTION_TRANSPORT 23
197#define SO_SECURITY_ENCRYPTION_NETWORK 24251#define SO_SECURITY_ENCRYPTION_NETWORK 24
...@@ -203,14 +257,10 @@ struct linger {...@@ -203,14 +257,10 @@ struct linger {
203#define SO_GET_FILTER SO_ATTACH_FILTER257#define SO_GET_FILTER SO_ATTACH_FILTER
204258
205#define SO_PEERNAME 28259#define SO_PEERNAME 28
206#define SO_TIMESTAMP 29
207#define SCM_TIMESTAMP SO_TIMESTAMP260#define SCM_TIMESTAMP SO_TIMESTAMP
208
209#define SO_PASSSEC 34261#define SO_PASSSEC 34
210#define SO_TIMESTAMPNS 35
211#define SCM_TIMESTAMPNS SO_TIMESTAMPNS262#define SCM_TIMESTAMPNS SO_TIMESTAMPNS
212#define SO_MARK 36263#define SO_MARK 36
213#define SO_TIMESTAMPING 37
214#define SCM_TIMESTAMPING SO_TIMESTAMPING264#define SCM_TIMESTAMPING SO_TIMESTAMPING
215#define SO_RXQ_OVFL 40265#define SO_RXQ_OVFL 40
216#define SO_WIFI_STATUS 41266#define SO_WIFI_STATUS 41
...@@ -238,6 +288,7 @@ struct linger {...@@ -238,6 +288,7 @@ struct linger {
238#define SO_TXTIME 61288#define SO_TXTIME 61
239#define SCM_TXTIME SO_TXTIME289#define SCM_TXTIME SO_TXTIME
240#define SO_BINDTOIFINDEX 62290#define SO_BINDTOIFINDEX 62
291#define SO_DETACH_REUSEPORT_BPF 68
241292
242#ifndef SOL_SOCKET293#ifndef SOL_SOCKET
243#define SOL_SOCKET 1294#define SOL_SOCKET 1
...@@ -350,6 +401,12 @@ int setsockopt (int, int, int, const void *, socklen_t);...@@ -350,6 +401,12 @@ int setsockopt (int, int, int, const void *, socklen_t);
350401
351int sockatmark (int);402int sockatmark (int);
352403
404#if _REDIR_TIME64
405#ifdef _GNU_SOURCE
406__REDIR(recvmmsg, __recvmmsg_time64);
407#endif
408#endif
409
353#ifdef __cplusplus410#ifdef __cplusplus
354}411}
355#endif412#endif
lib/libc/musl/include/sys/stat.h+9
...@@ -110,6 +110,15 @@ int lchmod(const char *, mode_t);...@@ -110,6 +110,15 @@ int lchmod(const char *, mode_t);
110#define off64_t off_t110#define off64_t off_t
111#endif111#endif
112112
113#if _REDIR_TIME64
114__REDIR(stat, __stat_time64);
115__REDIR(fstat, __fstat_time64);
116__REDIR(lstat, __lstat_time64);
117__REDIR(fstatat, __fstatat_time64);
118__REDIR(futimens, __futimens_time64);
119__REDIR(utimensat, __utimensat_time64);
120#endif
121
113#ifdef __cplusplus122#ifdef __cplusplus
114}123}
115#endif124#endif
lib/libc/musl/include/sys/statvfs.h-2
...@@ -11,8 +11,6 @@ extern "C" {...@@ -11,8 +11,6 @@ extern "C" {
11#define __NEED_fsfilcnt_t11#define __NEED_fsfilcnt_t
12#include <bits/alltypes.h>12#include <bits/alltypes.h>
1313
14#include <endian.h>
15
16struct statvfs {14struct statvfs {
17 unsigned long f_bsize, f_frsize;15 unsigned long f_bsize, f_frsize;
18 fsblkcnt_t f_blocks, f_bfree, f_bavail;16 fsblkcnt_t f_blocks, f_bfree, f_bavail;
lib/libc/musl/include/sys/time.h+14
...@@ -56,6 +56,20 @@ int adjtime (const struct timeval *, struct timeval *);...@@ -56,6 +56,20 @@ int adjtime (const struct timeval *, struct timeval *);
56 (void)0 )56 (void)0 )
57#endif57#endif
5858
59#if _REDIR_TIME64
60__REDIR(gettimeofday, __gettimeofday_time64);
61__REDIR(getitimer, __getitimer_time64);
62__REDIR(setitimer, __setitimer_time64);
63__REDIR(utimes, __utimes_time64);
64#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
65__REDIR(futimes, __futimes_time64);
66__REDIR(futimesat, __futimesat_time64);
67__REDIR(lutimes, __lutimes_time64);
68__REDIR(settimeofday, __settimeofday_time64);
69__REDIR(adjtime, __adjtime64);
70#endif
71#endif
72
59#ifdef __cplusplus73#ifdef __cplusplus
60}74}
61#endif75#endif
lib/libc/musl/include/sys/timeb.h+6
...@@ -4,6 +4,8 @@...@@ -4,6 +4,8 @@
4extern "C" {4extern "C" {
5#endif5#endif
66
7#include <features.h>
8
7#define __NEED_time_t9#define __NEED_time_t
810
9#include <bits/alltypes.h>11#include <bits/alltypes.h>
...@@ -16,6 +18,10 @@ struct timeb {...@@ -16,6 +18,10 @@ struct timeb {
1618
17int ftime(struct timeb *);19int ftime(struct timeb *);
1820
21#if _REDIR_TIME64
22__REDIR(ftime, __ftime64);
23#endif
24
19#ifdef __cplusplus25#ifdef __cplusplus
20}26}
21#endif27#endif
lib/libc/musl/include/sys/timerfd.h+5
...@@ -20,6 +20,11 @@ int timerfd_create(int, int);...@@ -20,6 +20,11 @@ int timerfd_create(int, int);
20int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *);20int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *);
21int timerfd_gettime(int, struct itimerspec *);21int timerfd_gettime(int, struct itimerspec *);
2222
23#if _REDIR_TIME64
24__REDIR(timerfd_settime, __timerfd_settime64);
25__REDIR(timerfd_gettime, __timerfd_gettime64);
26#endif
27
23#ifdef __cplusplus28#ifdef __cplusplus
24}29}
25#endif30#endif
lib/libc/musl/include/sys/timex.h+5
...@@ -91,6 +91,11 @@ struct timex {...@@ -91,6 +91,11 @@ struct timex {
91int adjtimex(struct timex *);91int adjtimex(struct timex *);
92int clock_adjtime(clockid_t, struct timex *);92int clock_adjtime(clockid_t, struct timex *);
9393
94#if _REDIR_TIME64
95__REDIR(adjtimex, __adjtimex_time64);
96__REDIR(clock_adjtime, __clock_adjtime64);
97#endif
98
94#ifdef __cplusplus99#ifdef __cplusplus
95}100}
96#endif101#endif
lib/libc/musl/include/sys/ttydefaults.h+1-6
...@@ -6,16 +6,11 @@...@@ -6,16 +6,11 @@
6#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL)6#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL)
7#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL)7#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL)
8#define TTYDEF_SPEED (B9600)8#define TTYDEF_SPEED (B9600)
9#define CTRL(x) (x&037)9#define CTRL(x) ((x)&037)
10#define CEOF CTRL('d')10#define CEOF CTRL('d')
1111
12#ifdef _POSIX_VDISABLE
13#define CEOL _POSIX_VDISABLE
14#define CSTATUS _POSIX_VDISABLE
15#else
16#define CEOL '\0'12#define CEOL '\0'
17#define CSTATUS '\0'13#define CSTATUS '\0'
18#endif
1914
20#define CERASE 017715#define CERASE 0177
21#define CINTR CTRL('c')16#define CINTR CTRL('c')
lib/libc/musl/include/sys/wait.h+9-1
...@@ -13,7 +13,8 @@ extern "C" {...@@ -13,7 +13,8 @@ extern "C" {
13typedef enum {13typedef enum {
14 P_ALL = 0,14 P_ALL = 0,
15 P_PID = 1,15 P_PID = 1,
16 P_PGID = 216 P_PGID = 2,
17 P_PIDFD = 3
17} idtype_t;18} idtype_t;
1819
19pid_t wait (int *);20pid_t wait (int *);
...@@ -53,6 +54,13 @@ pid_t wait4 (pid_t, int *, int, struct rusage *);...@@ -53,6 +54,13 @@ pid_t wait4 (pid_t, int *, int, struct rusage *);
53#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu)54#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu)
54#define WIFCONTINUED(s) ((s) == 0xffff)55#define WIFCONTINUED(s) ((s) == 0xffff)
5556
57#if _REDIR_TIME64
58#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
59__REDIR(wait3, __wait3_time64);
60__REDIR(wait4, __wait4_time64);
61#endif
62#endif
63
56#ifdef __cplusplus64#ifdef __cplusplus
57}65}
58#endif66#endif
lib/libc/musl/include/threads.h+6
...@@ -80,6 +80,12 @@ void tss_delete(tss_t);...@@ -80,6 +80,12 @@ void tss_delete(tss_t);
80int tss_set(tss_t, void *);80int tss_set(tss_t, void *);
81void *tss_get(tss_t);81void *tss_get(tss_t);
8282
83#if _REDIR_TIME64
84__REDIR(thrd_sleep, __thrd_sleep_time64);
85__REDIR(mtx_timedlock, __mtx_timedlock_time64);
86__REDIR(cnd_timedwait, __cnd_timedwait_time64);
87#endif
88
83#ifdef __cplusplus89#ifdef __cplusplus
84}90}
85#endif91#endif
lib/libc/musl/include/time.h+28
...@@ -130,6 +130,34 @@ int stime(const time_t *);...@@ -130,6 +130,34 @@ int stime(const time_t *);
130time_t timegm(struct tm *);130time_t timegm(struct tm *);
131#endif131#endif
132132
133#if _REDIR_TIME64
134__REDIR(time, __time64);
135__REDIR(difftime, __difftime64);
136__REDIR(mktime, __mktime64);
137__REDIR(gmtime, __gmtime64);
138__REDIR(localtime, __localtime64);
139__REDIR(ctime, __ctime64);
140__REDIR(timespec_get, __timespec_get_time64);
141#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
142 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
143 || defined(_BSD_SOURCE)
144__REDIR(gmtime_r, __gmtime64_r);
145__REDIR(localtime_r, __localtime64_r);
146__REDIR(ctime_r, __ctime64_r);
147__REDIR(nanosleep, __nanosleep_time64);
148__REDIR(clock_getres, __clock_getres_time64);
149__REDIR(clock_gettime, __clock_gettime64);
150__REDIR(clock_settime, __clock_settime64);
151__REDIR(clock_nanosleep, __clock_nanosleep_time64);
152__REDIR(timer_settime, __timer_settime64);
153__REDIR(timer_gettime, __timer_gettime64);
154#endif
155#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
156__REDIR(stime, __stime64);
157__REDIR(timegm, __timegm_time64);
158#endif
159#endif
160
133#ifdef __cplusplus161#ifdef __cplusplus
134}162}
135#endif163#endif
lib/libc/musl/include/utime.h+6
...@@ -5,6 +5,8 @@...@@ -5,6 +5,8 @@
5extern "C" {5extern "C" {
6#endif6#endif
77
8#include <features.h>
9
8#define __NEED_time_t10#define __NEED_time_t
911
10#include <bits/alltypes.h>12#include <bits/alltypes.h>
...@@ -16,6 +18,10 @@ struct utimbuf {...@@ -16,6 +18,10 @@ struct utimbuf {
1618
17int utime (const char *, const struct utimbuf *);19int utime (const char *, const struct utimbuf *);
1820
21#if _REDIR_TIME64
22__REDIR(utime, __utime64);
23#endif
24
19#ifdef __cplusplus25#ifdef __cplusplus
20}26}
21#endif27#endif
lib/libc/musl/include/utmpx.h+6-1
...@@ -16,6 +16,7 @@ extern "C" {...@@ -16,6 +16,7 @@ extern "C" {
1616
17struct utmpx {17struct utmpx {
18 short ut_type;18 short ut_type;
19 short __ut_pad1;
19 pid_t ut_pid;20 pid_t ut_pid;
20 char ut_line[32];21 char ut_line[32];
21 char ut_id[4];22 char ut_id[4];
...@@ -25,7 +26,11 @@ struct utmpx {...@@ -25,7 +26,11 @@ struct utmpx {
25 short __e_termination;26 short __e_termination;
26 short __e_exit;27 short __e_exit;
27 } ut_exit;28 } ut_exit;
28 long ut_session;29#if __BYTE_ORDER == 1234
30 int ut_session, __ut_pad2;
31#else
32 int __ut_pad2, ut_session;
33#endif
29 struct timeval ut_tv;34 struct timeval ut_tv;
30 unsigned ut_addr_v6[4];35 unsigned ut_addr_v6[4];
31 char __unused[20];36 char __unused[20];
lib/libc/musl/src/aio/aio_suspend.c+2
...@@ -73,4 +73,6 @@ int aio_suspend(const struct aiocb *const cbs[], int cnt, const struct timespec...@@ -73,4 +73,6 @@ int aio_suspend(const struct aiocb *const cbs[], int cnt, const struct timespec
73 }73 }
74}74}
7575
76#if !_REDIR_TIME64
76weak_alias(aio_suspend, aio_suspend64);77weak_alias(aio_suspend, aio_suspend64);
78#endif
lib/libc/musl/src/complex/cacosh.c+4-1
...@@ -4,6 +4,9 @@...@@ -4,6 +4,9 @@
44
5double complex cacosh(double complex z)5double complex cacosh(double complex z)
6{6{
7 int zineg = signbit(cimag(z));
8
7 z = cacos(z);9 z = cacos(z);
8 return CMPLX(-cimag(z), creal(z));10 if (zineg) return CMPLX(cimag(z), -creal(z));
11 else return CMPLX(-cimag(z), creal(z));
9}12}
lib/libc/musl/src/complex/cacoshf.c+4-1
...@@ -2,6 +2,9 @@...@@ -2,6 +2,9 @@
22
3float complex cacoshf(float complex z)3float complex cacoshf(float complex z)
4{4{
5 int zineg = signbit(cimagf(z));
6
5 z = cacosf(z);7 z = cacosf(z);
6 return CMPLXF(-cimagf(z), crealf(z));8 if (zineg) return CMPLXF(cimagf(z), -crealf(z));
9 else return CMPLXF(-cimagf(z), crealf(z));
7}10}
lib/libc/musl/src/complex/cacoshl.c+4-1
...@@ -8,7 +8,10 @@ long double complex cacoshl(long double complex z)...@@ -8,7 +8,10 @@ long double complex cacoshl(long double complex z)
8#else8#else
9long double complex cacoshl(long double complex z)9long double complex cacoshl(long double complex z)
10{10{
11 int zineg = signbit(cimagl(z));
12
11 z = cacosl(z);13 z = cacosl(z);
12 return CMPLXL(-cimagl(z), creall(z));14 if (zineg) return CMPLXL(cimagl(z), -creall(z));
15 else return CMPLXL(-cimagl(z), creall(z));
13}16}
14#endif17#endif
lib/libc/musl/src/complex/catanf.c+1-13
...@@ -87,29 +87,17 @@ float complex catanf(float complex z)...@@ -87,29 +87,17 @@ float complex catanf(float complex z)
87 x = crealf(z);87 x = crealf(z);
88 y = cimagf(z);88 y = cimagf(z);
8989
90 if ((x == 0.0f) && (y > 1.0f))
91 goto ovrf;
92
93 x2 = x * x;90 x2 = x * x;
94 a = 1.0f - x2 - (y * y);91 a = 1.0f - x2 - (y * y);
95 if (a == 0.0f)
96 goto ovrf;
9792
98 t = 0.5f * atan2f(2.0f * x, a);93 t = 0.5f * atan2f(2.0f * x, a);
99 w = _redupif(t);94 w = _redupif(t);
10095
101 t = y - 1.0f;96 t = y - 1.0f;
102 a = x2 + (t * t);97 a = x2 + (t * t);
103 if (a == 0.0f)
104 goto ovrf;
10598
106 t = y + 1.0f;99 t = y + 1.0f;
107 a = (x2 + (t * t))/a;100 a = (x2 + (t * t))/a;
108 w = w + (0.25f * logf (a)) * I;101 w = CMPLXF(w, 0.25f * logf(a));
109 return w;
110
111ovrf:
112 // FIXME
113 w = MAXNUMF + MAXNUMF * I;
114 return w;102 return w;
115}103}
lib/libc/musl/src/complex/catanl.c+1-13
...@@ -97,30 +97,18 @@ long double complex catanl(long double complex z)...@@ -97,30 +97,18 @@ long double complex catanl(long double complex z)
97 x = creall(z);97 x = creall(z);
98 y = cimagl(z);98 y = cimagl(z);
9999
100 if ((x == 0.0L) && (y > 1.0L))
101 goto ovrf;
102
103 x2 = x * x;100 x2 = x * x;
104 a = 1.0L - x2 - (y * y);101 a = 1.0L - x2 - (y * y);
105 if (a == 0.0L)
106 goto ovrf;
107102
108 t = atan2l(2.0L * x, a) * 0.5L;103 t = atan2l(2.0L * x, a) * 0.5L;
109 w = redupil(t);104 w = redupil(t);
110105
111 t = y - 1.0L;106 t = y - 1.0L;
112 a = x2 + (t * t);107 a = x2 + (t * t);
113 if (a == 0.0L)
114 goto ovrf;
115108
116 t = y + 1.0L;109 t = y + 1.0L;
117 a = (x2 + (t * t)) / a;110 a = (x2 + (t * t)) / a;
118 w = w + (0.25L * logl(a)) * I;111 w = CMPLXF(w, 0.25L * logl(a));
119 return w;
120
121ovrf:
122 // FIXME
123 w = LDBL_MAX + LDBL_MAX * I;
124 return w;112 return w;
125}113}
126#endif114#endif
lib/libc/musl/src/ctype/alpha.h+84-75
...@@ -8,17 +8,17 @@...@@ -8,17 +8,17 @@
817,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,817,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
917,17,17,17,17,17,17,63,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,917,17,17,17,17,17,17,63,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1016,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,64,65,17,66,67,1016,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,64,65,17,66,67,
1168,69,70,71,72,73,74,17,75,76,77,78,79,80,16,16,16,81,82,83,84,85,86,87,88,89,1168,69,70,71,72,73,74,17,75,76,77,78,79,80,81,16,82,83,84,85,86,87,88,89,90,91,
1216,90,16,91,92,16,16,17,17,17,93,94,95,16,16,16,16,16,16,16,16,16,16,17,17,17,1292,93,16,94,95,96,16,17,17,17,97,98,99,16,16,16,16,16,16,16,16,16,16,17,17,17,
1317,96,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,97,16,16,16,16,16,16,1317,100,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,101,16,16,16,16,16,
1416,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1416,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1516,17,17,98,99,16,16,16,100,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,1516,16,17,17,102,103,16,16,104,105,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
1617,17,17,17,17,17,17,101,17,17,102,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1617,17,17,17,17,17,17,17,17,106,17,17,107,16,16,16,16,16,16,16,16,16,16,16,16,
1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,103,1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,
18104,16,16,16,16,16,16,16,16,16,105,16,16,16,16,16,16,16,16,16,16,16,16,16,16,18108,109,16,16,16,16,16,16,16,16,16,110,16,16,16,16,16,16,16,16,16,16,16,16,16,
1916,16,16,16,16,16,16,16,16,106,107,108,109,16,16,16,16,16,16,16,16,110,16,16,1916,16,16,16,16,16,16,16,16,16,111,112,113,114,16,16,16,16,16,16,16,16,115,116,
2016,16,16,16,16,111,112,16,16,16,16,113,16,16,114,16,16,16,16,16,16,16,16,16,20117,16,16,16,16,16,118,119,16,16,16,16,120,16,16,121,16,16,16,16,16,16,16,16,
2116,16,16,16,2116,16,16,16,16,
2216,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,2216,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,
23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
24255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,254,255,255,7,254,24255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,254,255,255,7,254,
...@@ -27,8 +27,8 @@...@@ -27,8 +27,8 @@
27255,195,255,3,0,31,80,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,223,188,64,215,255,255,27255,195,255,3,0,31,80,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,223,188,64,215,255,255,
28251,255,255,255,255,255,255,255,255,255,191,255,255,255,255,255,255,255,255,28251,255,255,255,255,255,255,255,255,255,191,255,255,255,255,255,255,255,255,
29255,255,255,255,255,255,255,255,255,3,252,255,255,255,255,255,255,255,255,255,29255,255,255,255,255,255,255,255,255,3,252,255,255,255,255,255,255,255,255,255,
30255,255,255,255,255,255,255,255,255,255,255,254,255,255,255,127,2,254,255,255,30255,255,255,255,255,255,255,255,255,255,255,254,255,255,255,127,2,255,255,255,
31255,255,0,0,0,0,0,255,191,182,0,255,255,255,7,7,0,0,0,255,7,255,255,255,255,31255,255,1,0,0,0,0,255,191,182,0,255,255,255,135,7,0,0,0,255,7,255,255,255,255,
32255,255,255,254,255,195,255,255,255,255,255,255,255,255,255,255,255,255,239,32255,255,255,254,255,195,255,255,255,255,255,255,255,255,255,255,255,255,239,
3331,254,225,255,3331,254,225,255,
34159,0,0,255,255,255,255,255,255,0,224,255,255,255,255,255,255,255,255,255,255,34159,0,0,255,255,255,255,255,255,0,224,255,255,255,255,255,255,255,255,255,255,
...@@ -42,54 +42,55 @@...@@ -42,54 +42,55 @@
42255,0,0,239,223,253,255,255,253,239,227,223,29,96,64,207,255,6,0,239,223,253,42255,0,0,239,223,253,255,255,253,239,227,223,29,96,64,207,255,6,0,239,223,253,
43255,255,255,255,231,223,93,240,128,207,255,0,252,236,255,127,252,255,255,251,43255,255,255,255,231,223,93,240,128,207,255,0,252,236,255,127,252,255,255,251,
4447,127,128,95,255,192,255,12,0,254,255,255,255,255,127,255,7,63,32,255,3,0,0,4447,127,128,95,255,192,255,12,0,254,255,255,255,255,127,255,7,63,32,255,3,0,0,
450,0,150,37,240,254,174,236,255,59,95,32,255,243,0,0,0,450,0,214,247,255,255,175,255,255,59,95,32,255,243,0,0,0,
460,1,0,0,0,255,3,0,0,255,254,255,255,255,31,254,255,3,255,255,254,255,255,255,460,1,0,0,0,255,3,0,0,255,254,255,255,255,31,254,255,3,255,255,254,255,255,255,
4731,0,0,0,0,0,0,0,0,255,255,255,255,255,255,127,249,255,3,255,255,231,193,255,4731,0,0,0,0,0,0,0,0,255,255,255,255,255,255,127,249,255,3,255,255,255,255,255,
48255,127,64,255,51,255,255,255,255,191,32,255,255,255,255,255,247,255,255,255,48255,255,255,255,63,255,255,255,255,191,32,255,255,255,255,255,247,255,255,255,
49255,255,255,255,255,255,61,127,61,255,255,255,255,255,61,255,255,255,255,61,49255,255,255,255,255,255,61,127,61,255,255,255,255,255,61,255,255,255,255,61,
50127,61,255,127,255,255,255,255,255,255,255,61,255,255,255,255,255,255,255,255,50127,61,255,127,255,255,255,255,255,255,255,61,255,255,255,255,255,255,255,255,
51135,0,0,0,0,255,255,0,0,255,255,255,255,255,255,255,255,255,255,63,63,254,255,517,0,0,0,0,255,255,0,0,255,255,255,255,255,255,255,255,255,255,63,63,254,255,
52255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,52255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
53255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,53255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
54255,255,255,255,255,159,255,255,254,255,255,7,255,255,255,255,255,255,255,255,54255,255,255,255,255,159,255,255,254,255,255,7,255,255,255,255,255,255,255,255,
55255,199,255,1,255,223,15,0,255,255,15,0,255,255,15,0,255,223,13,0,255,255,255,55255,199,255,1,255,223,15,0,255,255,15,0,255,255,15,0,255,223,13,0,255,255,255,
56255,255,255,207,255,255,1,128,16,255,3,0,0,0,0,255,3,255,255,255,255,255,255,56255,255,255,207,255,255,1,128,16,255,3,0,0,0,0,255,3,255,255,255,255,255,255,
57255,255,255,255,255,0,255,255,255,255,255,7,255,255,255,255,255,255,255,255,57255,255,255,255,255,1,255,255,255,255,255,7,255,255,255,255,255,255,255,255,
5863,5863,
590,255,255,255,127,255,15,255,1,192,255,255,255,255,63,31,0,255,255,255,255,590,255,255,255,127,255,15,255,1,192,255,255,255,255,63,31,0,255,255,255,255,
60255,15,255,255,255,3,255,3,0,0,0,0,255,255,255,15,255,255,255,255,255,255,255,60255,15,255,255,255,3,255,3,0,0,0,0,255,255,255,15,255,255,255,255,255,255,255,
61127,254,255,31,0,255,3,255,3,128,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,61127,254,255,31,0,255,3,255,3,128,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,
62255,239,255,239,15,255,3,0,0,0,0,255,255,255,255,255,243,255,255,255,255,255,62255,239,255,239,15,255,3,0,0,0,0,255,255,255,255,255,243,255,255,255,255,255,
63255,191,255,3,0,255,255,255,255,255,255,63,0,255,227,255,255,255,255,255,63,63255,191,255,3,0,255,255,255,255,255,255,127,0,255,227,255,255,255,255,255,63,
64255,1,0,0,0,0,0,0,0,0,0,0,0,222,111,0,255,255,255,255,255,255,255,255,255,255,64255,1,255,255,255,255,255,231,0,0,0,0,0,222,111,4,255,255,255,255,255,255,255,
65255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,128,255,31,0,65255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,
66255,255,63,63,255,255,255,255,63,63,255,170,255,255,255,63,255,255,255,255,66128,255,31,0,255,255,63,63,255,255,255,255,63,63,255,170,255,255,255,63,255,
67255,255,223,95,220,31,207,15,255,31,220,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,128,67255,255,255,255,255,223,95,220,31,207,15,255,31,220,31,0,0,0,0,0,0,0,0,0,0,0,
680,0,255,31,0,0,0,0,0,0,0,0,0,0,0,0,132,252,47,62,80,189,255,243,224,67,0,0,680,0,0,2,128,0,0,255,31,0,0,0,0,0,0,0,0,0,0,0,0,132,252,47,62,80,189,255,243,
69255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,69224,67,0,0,255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
700,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,255,255,255,255,255,255,3,0,700,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,255,255,255,255,255,255,3,0,
710,255,255,255,255,255,127,255,255,255,255,255,127,255,255,255,255,255,255,255,710,255,255,255,255,255,127,255,255,255,255,255,127,255,255,255,255,255,255,255,
72255,255,255,255,255,255,255,255,255,31,120,12,0,255,255,255,255,191,32,255,72255,255,255,255,255,255,255,255,255,31,120,12,0,255,255,255,255,191,32,255,
73255,255,255,255,255,255,128,0,0,255,255,127,0,127,127,127,127,127,127,127,127,73255,255,255,255,255,255,128,0,0,255,255,127,0,127,127,127,127,127,127,127,127,
74255,255,255,255,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,74255,255,255,255,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
750,0,224,0,0,0,254,3,62,31,254,255,255,255,255,255,255,255,255,255,127,224,254,750,0,224,0,0,0,254,3,62,31,254,255,255,255,255,255,255,255,255,255,127,224,254,
76255,255,255,255,255,255,255,255,255,255,247,224,255,255,255,255,127,254,255,76255,255,255,255,255,255,255,255,255,255,247,224,255,255,255,255,255,254,255,
77255,255,255,255,255,255,255,255,255,127,0,0,255,255,255,7,0,0,0,0,0,0,255,255,77255,255,255,255,255,255,255,255,255,127,0,0,255,255,255,7,0,0,0,0,0,0,255,255,
78255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,78255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
79255,255,255,63,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,79255,255,255,63,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,
80255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7,0,80255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,
810,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,0,810,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,0,
820,0,0,0,0,0,255,255,255,255,255,63,255,31,255,255,255,15,0,0,255,255,255,255,820,0,0,0,0,0,255,255,255,255,255,63,255,31,255,255,255,15,0,0,255,255,255,255,
83255,127,240,143,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,83255,127,240,143,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,
840,128,255,252,255,255,255,255,255,255,255,255,255,255,255,255,249,255,255,255,840,128,255,252,255,255,255,255,255,255,255,255,255,255,255,255,249,255,255,255,
85127,255,0,0,0,0,0,0,0,128,255,187,247,255,255,255,0,0,0,255,255,255,255,255,85255,255,255,124,0,0,0,0,0,128,255,191,255,255,255,255,0,0,0,255,255,255,255,
86255,15,0,255,255,255,255,255,255,255,255,47,0,255,3,0,0,252,40,255,255,255,86255,255,15,0,255,255,255,255,255,255,255,255,47,0,255,3,0,0,252,232,255,255,
87255,255,7,255,255,255,255,7,0,255,255,255,31,255,255,255,255,255,255,247,255,87255,255,255,7,255,255,255,255,7,0,255,255,255,31,255,255,255,255,255,255,247,
880,128,255,3,223,255,255,127,255,255,255,255,255,255,127,0,255,63,255,3,255,88255,0,128,255,3,255,255,255,127,255,255,255,255,255,255,127,0,255,63,255,3,
89255,127,196,255,255,255,255,255,255,255,127,5,0,0,56,255,255,60,0,126,126,126,89255,255,127,252,255,255,255,255,255,255,255,127,5,0,0,56,255,255,60,0,126,126,
900,127,127,255,255,255,255,255,247,63,0,255,255,255,255,255,255,255,255,255,90126,0,127,127,255,255,255,255,255,247,255,0,255,255,255,255,255,255,255,255,
91255,255,255,255,255,255,7,255,3,255,255,255,255,255,255,255,255,255,255,255,91255,255,255,255,255,255,255,7,255,3,255,255,255,255,255,255,255,255,255,255,
92255,255,255,255,255,255,255,255,255,15,0,255,255,127,248,255,255,255,255,255,92255,255,255,255,255,255,255,255,255,255,15,0,255,255,127,248,255,255,255,255,
93255,
9315,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255,255,255,9415,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255,255,255,
94255,255,255,255,255,255,255,255,3,0,0,0,0,127,0,248,224,255,253,127,95,219,95255,255,255,255,255,255,255,255,3,0,0,0,0,127,0,248,224,255,253,127,95,219,
95255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,0,248,255,255,255,96255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,0,248,255,255,255,
...@@ -109,55 +110,63 @@...@@ -109,55 +110,63 @@
1090,0,0,0,0,0,0,0,0,0,0,0,63,253,255,255,255,255,191,145,255,255,63,0,255,255,1100,0,0,0,0,0,0,0,0,0,0,0,63,253,255,255,255,255,191,145,255,255,63,0,255,255,
110127,0,255,255,255,127,0,0,0,0,0,0,0,0,255,255,55,0,255,255,63,0,255,255,255,3,111127,0,255,255,255,127,0,0,0,0,0,0,0,0,255,255,55,0,255,255,63,0,255,255,255,3,
1110,0,0,0,0,0,0,0,255,255,255,255,255,255,255,192,0,0,0,0,0,0,0,0,111,240,239,1120,0,0,0,0,0,0,0,255,255,255,255,255,255,255,192,0,0,0,0,0,0,0,0,111,240,239,
112254,255,255,15,0,0,0,0,0,255,255,255,31,255,255,255,31,0,0,0,0,255,254,255,113254,255,255,63,0,0,0,0,0,255,255,255,31,255,255,255,31,0,0,0,0,255,254,255,
113255,31,0,0,0,255,255,255,255,255,255,63,0,255,255,63,0,255,255,7,0,255,255,3,114255,31,0,0,0,255,255,255,255,255,255,63,0,255,255,63,0,255,255,7,0,255,255,3,
1140,0,0,0,0,0,0,0,0,0,0,0,1150,0,0,0,0,0,0,0,0,0,0,0,
1150,255,255,255,255,255,255,255,255,255,1,0,0,0,0,0,0,255,255,255,255,255,255,7,1160,255,255,255,255,255,255,255,255,255,1,0,0,0,0,0,0,255,255,255,255,255,255,7,
1160,255,255,255,255,255,255,7,0,255,255,255,255,255,255,255,255,63,0,0,0,192,1170,255,255,255,255,255,255,7,0,255,255,255,255,255,0,255,3,0,0,0,0,0,0,0,0,0,0,
117255,0,0,252,255,255,255,255,255,255,1,0,0,255,255,255,1,255,3,255,255,255,255,1180,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,31,128,0,255,255,63,0,0,0,0,0,0,0,0,0,
118255,255,199,255,0,0,255,255,255,255,71,0,255,255,255,255,255,255,255,255,30,0,1190,0,0,0,0,0,0,0,0,0,255,255,127,0,255,255,255,255,255,255,255,255,63,0,0,0,
119255,23,0,0,0,0,255,255,251,255,255,255,159,64,0,0,0,0,0,0,0,0,127,189,255,191,120192,255,0,0,252,255,255,255,255,255,255,1,0,0,255,255,255,1,255,3,255,255,255,
120255,1,255,255,255,255,255,255,255,1,255,3,239,159,249,255,255,253,237,227,159,121255,255,255,199,255,112,0,255,255,255,255,71,0,255,255,255,255,255,255,255,
12125,129,224,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,122255,30,0,255,23,0,0,0,0,255,255,251,255,255,255,159,64,0,0,0,0,0,0,0,0,127,
122255,255,187,7,255,3,0,0,0,0,255,255,255,255,255,255,255,255,179,0,255,3,0,0,0,123189,255,191,255,1,255,255,255,255,255,255,255,1,255,3,239,159,249,255,255,253,
124237,227,159,25,129,224,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,
125255,255,255,255,255,187,7,255,131,0,0,0,0,255,255,255,255,255,255,255,255,179,
1260,255,3,0,0,0,
1230,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,63,127,0,0,0,63,0,0,1270,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,63,127,0,0,0,63,0,0,
1240,0,255,255,255,255,255,255,255,127,17,0,255,3,0,0,0,0,255,255,255,255,255,1280,0,255,255,255,255,255,255,255,127,17,0,255,3,0,0,0,0,255,255,255,255,255,
125255,63,0,255,3,0,0,0,0,0,129255,63,1,255,3,0,0,0,0,0,0,255,255,255,231,255,7,255,3,0,0,0,0,0,0,0,0,0,0,0,
1260,255,255,255,227,255,7,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1300,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,
1270,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,3,1310,255,255,255,255,255,255,255,255,255,3,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1280,128,255,255,255,255,255,255,231,127,0,0,255,255,255,255,255,255,207,255,255,1320,0,0,0,255,252,255,255,255,255,255,252,26,0,0,0,255,255,255,255,255,255,231,
1290,0,0,0,0,255,255,255,255,255,255,255,1,255,253,255,255,255,255,127,127,1,0,133127,0,0,255,255,255,255,255,255,255,255,255,32,0,0,0,0,255,255,255,255,255,
130255,3,0,0,252,255,255,255,252,255,255,254,127,0,0,0,0,0,0,0,0,0,127,251,255,134255,255,1,255,253,255,255,255,255,127,127,1,0,255,3,0,0,252,255,255,255,252,
131255,255,255,127,180,203,0,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,135255,255,254,127,0,0,0,0,0,0,0,0,0,127,251,255,255,255,255,127,180,203,0,255,3,
136191,253,255,255,255,127,123,1,255,3,0,0,0,0,0,0,0,0,0,
1370,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,127,0,255,
132255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,138255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,
1330,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,127,0,1390,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,127,0,
1340,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,1400,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
135255,255,255,255,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,141255,255,255,255,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,
1360,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,142255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,
137255,255,255,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,143255,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,
1380,0,255,255,255,255,255,255,255,1,255,255,255,127,255,3,0,0,0,0,0,0,0,0,0,0,0,144255,255,255,255,255,255,1,255,255,255,127,255,3,0,0,0,0,0,0,0,0,0,0,0,0,255,
1390,255,255,255,63,0,0,255,255,255,255,255,255,127,0,15,0,255,3,248,255,255,224,145255,255,63,0,0,255,255,255,255,255,255,0,0,15,0,255,3,248,255,255,224,255,255,
140255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,31,0,255,1460,0,0,0,0,0,0,0,0,0,0,0,0,
141255,255,255,255,127,0,0,248,255,0,0,0,0,0,0,0,0,3,0,0,0,255,255,255,255,255,1470,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1480,0,255,255,255,255,255,255,255,255,255,135,255,255,255,255,255,255,255,128,
149255,255,0,0,0,0,0,0,0,0,11,0,0,0,255,255,255,255,255,255,255,255,255,255,255,
142255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,150255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
143255,255,255,255,255,31,0,0,255,255,255,255,255,255,255,255,255,255,255,255,151255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
144255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7,0,152255,255,255,255,255,255,255,255,255,255,255,255,7,0,255,255,255,127,0,0,0,0,0,
145255,255,255,127,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,1530,7,0,240,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
146255,255,255,255,255,255,255,
147255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,154255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
148255,255,255,255,255,255,255,255,255,255,255,255,255,15,255,255,255,255,255,155255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,255,255,255,255,
149255,255,255,255,255,255,255,255,7,255,31,255,1,255,67,0,0,0,0,0,0,0,0,0,0,0,0,156255,255,255,255,255,255,255,255,255,7,255,31,255,1,255,67,0,0,0,0,0,0,0,0,0,0,
150255,255,255,255,255,255,255,255,255,255,223,255,255,255,255,255,255,255,255,1570,0,255,255,255,255,255,255,255,255,255,255,223,255,255,255,255,255,255,255,
151223,100,222,255,235,239,255,255,255,255,255,255,255,191,231,223,223,255,255,158255,223,100,222,255,235,239,255,255,255,255,255,255,
152255,123,95,252,253,255,255,255,255,255,255,255,255,255,255,255,255,255,255,159255,191,231,223,223,255,255,255,123,95,252,253,255,255,255,255,255,255,255,
153255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,160255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
154255,255,255,255,255,255,255,255,63,255,255,255,253,255,255,247,255,255,255,161255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255,
155247,255,255,223,255,255,255,223,255,255,127,255,255,255,127,255,255,255,253,162253,255,255,247,255,255,255,247,255,255,223,255,255,255,223,255,255,127,255,
156255,255,255,253,255,255,247,207,255,255,255,255,255,255,127,255,255,249,219,7,163255,255,127,255,255,255,253,255,255,255,253,255,255,247,207,255,255,255,255,
1570,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,164255,255,127,255,255,249,219,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
158255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,1650,0,255,255,255,255,255,31,128,63,255,67,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1590,0,0,0,0,1660,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,
1600,255,255,255,255,255,255,255,255,143,0,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16715,255,3,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
1610,0,0,0,239,255,255,255,150,254,247,10,132,234,150,170,150,247,247,94,255,251,168255,255,255,255,255,255,255,31,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,
162255,15,238,251,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,3,255,255,255,3,169143,8,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
163255,255,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1700,239,255,255,255,150,254,247,10,132,234,150,170,150,247,247,94,255,251,255,
17115,238,251,255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,3,255,255,255,3,255,
172255,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
lib/libc/musl/src/ctype/casemap.h created+297
...@@ -0,0 +1,297 @@
1static const unsigned char tab[] = {
2 7, 8, 9, 10, 11, 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
3 13, 6, 6, 14, 6, 6, 6, 6, 6, 6, 6, 6, 15, 16, 17, 18,
4 6, 19, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 20, 21, 6, 6,
5 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
8 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
9 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
10 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
11 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
12 6, 6, 6, 6, 6, 6, 22, 23, 6, 6, 6, 24, 6, 6, 6, 6,
13 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
14 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
15 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
16 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
17 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 25,
18 6, 6, 6, 6, 26, 6, 6, 6, 6, 6, 6, 6, 27, 6, 6, 6,
19 6, 6, 6, 6, 6, 6, 6, 6, 28, 6, 6, 6, 6, 6, 6, 6,
20 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
21 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
22 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
23 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
24 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 29, 6,
25 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
26 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
27 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
28 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
29 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
30 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
31 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
32 6, 6, 6, 6, 6, 6, 6, 6, 6, 30, 6, 6, 6, 6, 6, 6,
33 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
35 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
36 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
37 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
38 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
39 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
40 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36,
41 43, 43, 43, 43, 43, 43, 43, 43, 1, 0, 84, 86, 86, 86, 86, 86,
42 86, 86, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
43 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 43, 43, 43, 43, 43, 43,
44 43, 7, 43, 43, 91, 86, 86, 86, 86, 86, 86, 86, 74, 86, 86, 5,
45 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80,
46 36, 80, 121, 49, 80, 49, 80, 49, 56, 80, 49, 80, 49, 80, 49, 80,
47 49, 80, 49, 80, 49, 80, 49, 80, 78, 49, 2, 78, 13, 13, 78, 3,
48 78, 0, 36, 110, 0, 78, 49, 38, 110, 81, 78, 36, 80, 78, 57, 20,
49 129, 27, 29, 29, 83, 49, 80, 49, 80, 13, 49, 80, 49, 80, 49, 80,
50 27, 83, 36, 80, 49, 2, 92, 123, 92, 123, 92, 123, 92, 123, 92, 123,
51 20, 121, 92, 123, 92, 123, 92, 45, 43, 73, 3, 72, 3, 120, 92, 123,
52 20, 0, 150, 10, 1, 43, 40, 6, 6, 0, 42, 6, 42, 42, 43, 7,
53 187, 181, 43, 30, 0, 43, 7, 43, 43, 43, 1, 43, 43, 43, 43, 43,
54 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
55 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 1, 43, 43, 43, 43,
56 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
57 43, 43, 43, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
58 43, 205, 70, 205, 43, 0, 37, 43, 7, 1, 6, 1, 85, 86, 86, 86,
59 86, 86, 85, 86, 86, 2, 36, 129, 129, 129, 129, 129, 21, 129, 129, 129,
60 0, 0, 43, 0, 178, 209, 178, 209, 178, 209, 178, 209, 0, 0, 205, 204,
61 1, 0, 215, 215, 215, 215, 215, 131, 129, 129, 129, 129, 129, 129, 129, 129,
62 129, 129, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 28, 0, 0, 0,
63 0, 0, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 2, 0, 0,
64 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80,
65 49, 80, 78, 49, 80, 49, 80, 78, 49, 80, 49, 80, 49, 80, 49, 80,
66 49, 80, 49, 80, 49, 80, 49, 2, 135, 166, 135, 166, 135, 166, 135, 166,
67 135, 166, 135, 166, 135, 166, 135, 166, 42, 43, 43, 43, 43, 43, 43, 43,
68 43, 43, 43, 43, 43, 0, 0, 0, 84, 86, 86, 86, 86, 86, 86, 86,
69 86, 86, 86, 86, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
70 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
71 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
74 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
75 0, 0, 0, 84, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86,
76 12, 0, 12, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
77 43, 7, 42, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 43, 43, 43, 43, 43,
81 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
82 43, 43, 43, 43, 86, 86, 108, 129, 21, 0, 43, 43, 43, 43, 43, 43,
83 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
84 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
85 43, 43, 43, 43, 7, 108, 3, 65, 43, 43, 86, 86, 86, 86, 86, 86,
86 86, 86, 86, 86, 86, 86, 86, 86, 44, 86, 43, 43, 43, 43, 43, 43,
87 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 1,
88 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
89 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
90 0, 0, 0, 0, 0, 0, 0, 0, 12, 108, 0, 0, 0, 0, 0, 6,
91 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
92 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
93 0, 0, 0, 0, 0, 0, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37,
94 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37,
95 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37,
96 6, 37, 6, 37, 6, 37, 6, 37, 86, 122, 158, 38, 6, 37, 6, 37,
97 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 37,
98 6, 37, 6, 37, 6, 37, 6, 37, 6, 37, 6, 1, 43, 43, 79, 86,
99 86, 44, 43, 127, 86, 86, 57, 43, 43, 85, 86, 86, 43, 43, 79, 86,
100 86, 44, 43, 127, 86, 86, 129, 55, 117, 91, 123, 92, 43, 43, 79, 86,
101 86, 2, 172, 4, 0, 0, 57, 43, 43, 85, 86, 86, 43, 43, 79, 86,
102 86, 44, 43, 43, 86, 86, 50, 19, 129, 87, 0, 111, 129, 126, 201, 215,
103 126, 45, 129, 129, 14, 126, 57, 127, 111, 87, 0, 129, 129, 126, 21, 0,
104 126, 3, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 7, 43,
105 36, 43, 151, 43, 43, 43, 43, 43, 43, 43, 43, 43, 42, 43, 43, 43,
106 43, 43, 86, 86, 86, 86, 86, 128, 129, 129, 129, 129, 57, 187, 42, 43,
107 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
108 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
109 43, 43, 43, 43, 43, 43, 43, 1, 129, 129, 129, 129, 129, 129, 129, 129,
110 129, 129, 129, 129, 129, 129, 129, 201, 172, 172, 172, 172, 172, 172, 172, 172,
111 172, 172, 172, 172, 172, 172, 172, 208, 13, 0, 78, 49, 2, 180, 193, 193,
112 215, 215, 36, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80,
113 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80, 49, 80,
114 49, 80, 49, 80, 215, 215, 83, 193, 71, 212, 215, 215, 215, 5, 43, 43,
115 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 7, 1, 0, 1, 0, 0,
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
121 0, 0, 0, 0, 0, 0, 0, 0, 0, 78, 49, 80, 49, 80, 49, 80,
122 49, 80, 49, 80, 49, 80, 49, 80, 13, 0, 0, 0, 0, 0, 36, 80,
123 49, 80, 49, 80, 49, 80, 49, 80, 0, 0, 0, 0, 0, 0, 0, 0,
124 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
125 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 43, 43, 43, 43, 43,
126 43, 43, 43, 43, 43, 121, 92, 123, 92, 123, 79, 123, 92, 123, 92, 123,
127 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, 92, 123, 92, 45,
128 43, 43, 121, 20, 92, 123, 92, 45, 121, 42, 92, 39, 92, 123, 92, 123,
129 92, 123, 164, 0, 10, 180, 92, 123, 92, 123, 79, 3, 42, 43, 43, 43,
130 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 1,
131 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
132 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, 0, 0, 0,
133 0, 0, 0, 0, 0, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
134 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43,
135 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
136 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
137 0, 43, 43, 43, 43, 43, 43, 43, 43, 7, 0, 72, 86, 86, 86, 86,
138 86, 86, 86, 86, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
139 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
140 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
141 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 43, 43, 43, 43,
142 43, 43, 43, 43, 43, 43, 43, 43, 43, 85, 86, 86, 86, 86, 86, 86,
143 86, 86, 86, 86, 86, 86, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0,
144 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
145 0, 0, 0, 0, 0, 0, 36, 43, 43, 43, 43, 43, 43, 43, 43, 43,
146 43, 43, 7, 0, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86,
147 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
148 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
149 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 43, 43, 43,
150 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 7, 0, 0,
151 0, 0, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86,
152 86, 86, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
153 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
154 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
155 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 43,
156 43, 43, 43, 43, 43, 43, 43, 43, 86, 86, 86, 86, 86, 86, 86, 86,
157 86, 86, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159 0, 0, 0, 42, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 86, 86,
160 86, 86, 86, 86, 86, 86, 86, 86, 14, 0, 0, 0, 0, 0, 0, 0,
161 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
162 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
163 0, 0, 0, 0, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 43, 85,
164 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 14, 0, 0, 0, 0, 0,
165 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
166 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
167 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
169};
170static const int rules[] = {
171 0x0, 0x2001, -0x2000, 0x1dbf00, 0x2e700, 0x7900,
172 0x2402, 0x101, -0x100, 0x0, 0x201, -0x200,
173 -0xc6ff, -0xe800, -0x78ff, -0x12c00, 0xc300, 0xd201,
174 0xce01, 0xcd01, 0x4f01, 0xca01, 0xcb01, 0xcf01,
175 0x6100, 0xd301, 0xd101, 0xa300, 0xd501, 0x8200,
176 0xd601, 0xda01, 0xd901, 0xdb01, 0x3800, 0x3,
177 -0x4f00, -0x60ff, -0x37ff, 0x242802, 0x0, 0x101,
178 -0x100, -0xcd00, -0xda00, -0x81ff, 0x2a2b01, -0xa2ff,
179 0x2a2801, 0x2a3f00, -0xc2ff, 0x4501, 0x4701, 0x2a1f00,
180 0x2a1c00, 0x2a1e00, -0xd200, -0xce00, -0xca00, -0xcb00,
181 0xa54f00, 0xa54b00, -0xcf00, 0xa52800, 0xa54400, -0xd100,
182 -0xd300, 0x29f700, 0xa54100, 0x29fd00, -0xd500, -0xd600,
183 0x29e700, 0xa54300, 0xa52a00, -0x4500, -0xd900, -0x4700,
184 -0xdb00, 0xa51500, 0xa51200, 0x4c2402, 0x0, 0x2001,
185 -0x2000, 0x101, -0x100, 0x5400, 0x7401, 0x2601,
186 0x2501, 0x4001, 0x3f01, -0x2600, -0x2500, -0x1f00,
187 -0x4000, -0x3f00, 0x801, -0x3e00, -0x3900, -0x2f00,
188 -0x3600, -0x800, -0x5600, -0x5000, 0x700, -0x7400,
189 -0x3bff, -0x6000, -0x6ff, 0x701a02, 0x101, -0x100,
190 0x2001, -0x2000, 0x5001, 0xf01, -0xf00, 0x0,
191 0x3001, -0x3000, 0x101, -0x100, 0x0, 0xbc000,
192 0x1c6001, 0x0, 0x97d001, 0x801, -0x800, 0x8a0502,
193 0x0, -0xbbfff, -0x186200, 0x89c200, -0x182500, -0x186e00,
194 -0x186d00, -0x186400, -0x186300, -0x185c00, 0x0, 0x8a3800,
195 0x8a0400, 0xee600, 0x101, -0x100, 0x0, -0x3b00,
196 -0x1dbeff, 0x8f1d02, 0x800, -0x7ff, 0x0, 0x5600,
197 -0x55ff, 0x4a00, 0x6400, 0x8000, 0x7000, 0x7e00,
198 0x900, -0x49ff, -0x8ff, -0x1c2500, -0x63ff, -0x6fff,
199 -0x7fff, -0x7dff, 0xac0502, 0x0, 0x1001, -0x1000,
200 0x1c01, 0x101, -0x1d5cff, -0x20beff, -0x2045ff, -0x1c00,
201 0xb10b02, 0x101, -0x100, 0x3001, -0x3000, 0x0,
202 -0x29f6ff, -0xee5ff, -0x29e6ff, -0x2a2b00, -0x2a2800, -0x2a1bff,
203 -0x29fcff, -0x2a1eff, -0x2a1dff, -0x2a3eff, 0x0, -0x1c6000,
204 0x0, 0x101, -0x100, 0xbc0c02, 0x0, 0x101,
205 -0x100, -0xa543ff, 0x3a001, -0x8a03ff, -0xa527ff, 0x3000,
206 -0xa54eff, -0xa54aff, -0xa540ff, -0xa511ff, -0xa529ff, -0xa514ff,
207 -0x2fff, -0xa542ff, -0x8a37ff, 0x0, -0x97d000, -0x3a000,
208 0x0, 0x2001, -0x2000, 0x0, 0x2801, -0x2800,
209 0x0, 0x4001, -0x4000, 0x0, 0x2001, -0x2000,
210 0x0, 0x2001, -0x2000, 0x0, 0x2201, -0x2200,
211};
212static const unsigned char rulebases[] = {
213 0, 6, 39, 81, 111, 119, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
214 124, 0, 0, 127, 0, 0, 0, 0, 0, 0, 0, 0, 131, 142, 146, 151,
215 0, 170, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 180, 196, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
217 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 198, 201, 0, 0, 0, 219, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
228 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 222,
229 0, 0, 0, 0, 225, 0, 0, 0, 0, 0, 0, 0, 228, 0, 0, 0,
230 0, 0, 0, 0, 0, 0, 0, 0, 231, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
234 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
235 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 234, 0,
236 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
237 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
238 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
239 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
240 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
241 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
242 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
243 0, 0, 0, 0, 0, 0, 0, 0, 0, 237, 0, 0, 0, 0, 0, 0,
244 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
245};
246static const unsigned char exceptions[][2] = {
247 { 48, 12 }, { 49, 13 }, { 120, 14 }, { 127, 15 },
248 { 128, 16 }, { 129, 17 }, { 134, 18 }, { 137, 19 },
249 { 138, 19 }, { 142, 20 }, { 143, 21 }, { 144, 22 },
250 { 147, 19 }, { 148, 23 }, { 149, 24 }, { 150, 25 },
251 { 151, 26 }, { 154, 27 }, { 156, 25 }, { 157, 28 },
252 { 158, 29 }, { 159, 30 }, { 166, 31 }, { 169, 31 },
253 { 174, 31 }, { 177, 32 }, { 178, 32 }, { 183, 33 },
254 { 191, 34 }, { 197, 35 }, { 200, 35 }, { 203, 35 },
255 { 221, 36 }, { 242, 35 }, { 246, 37 }, { 247, 38 },
256 { 32, 45 }, { 58, 46 }, { 61, 47 }, { 62, 48 },
257 { 63, 49 }, { 64, 49 }, { 67, 50 }, { 68, 51 },
258 { 69, 52 }, { 80, 53 }, { 81, 54 }, { 82, 55 },
259 { 83, 56 }, { 84, 57 }, { 89, 58 }, { 91, 59 },
260 { 92, 60 }, { 97, 61 }, { 99, 62 }, { 101, 63 },
261 { 102, 64 }, { 104, 65 }, { 105, 66 }, { 106, 64 },
262 { 107, 67 }, { 108, 68 }, { 111, 66 }, { 113, 69 },
263 { 114, 70 }, { 117, 71 }, { 125, 72 }, { 130, 73 },
264 { 135, 74 }, { 137, 75 }, { 138, 76 }, { 139, 76 },
265 { 140, 77 }, { 146, 78 }, { 157, 79 }, { 158, 80 },
266 { 69, 87 }, { 123, 29 }, { 124, 29 }, { 125, 29 },
267 { 127, 88 }, { 134, 89 }, { 136, 90 }, { 137, 90 },
268 { 138, 90 }, { 140, 91 }, { 142, 92 }, { 143, 92 },
269 { 172, 93 }, { 173, 94 }, { 174, 94 }, { 175, 94 },
270 { 194, 95 }, { 204, 96 }, { 205, 97 }, { 206, 97 },
271 { 207, 98 }, { 208, 99 }, { 209, 100 }, { 213, 101 },
272 { 214, 102 }, { 215, 103 }, { 240, 104 }, { 241, 105 },
273 { 242, 106 }, { 243, 107 }, { 244, 108 }, { 245, 109 },
274 { 249, 110 }, { 253, 45 }, { 254, 45 }, { 255, 45 },
275 { 80, 105 }, { 81, 105 }, { 82, 105 }, { 83, 105 },
276 { 84, 105 }, { 85, 105 }, { 86, 105 }, { 87, 105 },
277 { 88, 105 }, { 89, 105 }, { 90, 105 }, { 91, 105 },
278 { 92, 105 }, { 93, 105 }, { 94, 105 }, { 95, 105 },
279 { 130, 0 }, { 131, 0 }, { 132, 0 }, { 133, 0 },
280 { 134, 0 }, { 135, 0 }, { 136, 0 }, { 137, 0 },
281 { 192, 117 }, { 207, 118 }, { 128, 137 }, { 129, 138 },
282 { 130, 139 }, { 133, 140 }, { 134, 141 }, { 112, 157 },
283 { 113, 157 }, { 118, 158 }, { 119, 158 }, { 120, 159 },
284 { 121, 159 }, { 122, 160 }, { 123, 160 }, { 124, 161 },
285 { 125, 161 }, { 179, 162 }, { 186, 163 }, { 187, 163 },
286 { 188, 164 }, { 190, 165 }, { 195, 162 }, { 204, 164 },
287 { 218, 166 }, { 219, 166 }, { 229, 106 }, { 234, 167 },
288 { 235, 167 }, { 236, 110 }, { 243, 162 }, { 248, 168 },
289 { 249, 168 }, { 250, 169 }, { 251, 169 }, { 252, 164 },
290 { 38, 176 }, { 42, 177 }, { 43, 178 }, { 78, 179 },
291 { 132, 8 }, { 98, 186 }, { 99, 187 }, { 100, 188 },
292 { 101, 189 }, { 102, 190 }, { 109, 191 }, { 110, 192 },
293 { 111, 193 }, { 112, 194 }, { 126, 195 }, { 127, 195 },
294 { 125, 207 }, { 141, 208 }, { 148, 209 }, { 171, 210 },
295 { 172, 211 }, { 173, 212 }, { 176, 213 }, { 177, 214 },
296 { 178, 215 }, { 196, 216 }, { 197, 217 }, { 198, 218 },
297};
lib/libc/musl/src/ctype/nonspacing.h+48-40
...@@ -8,16 +8,16 @@...@@ -8,16 +8,16 @@
816,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,816,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
916,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,916,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1016,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,49,16,16,50,1016,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,49,16,16,50,
1151,16,52,53,54,16,16,16,16,16,16,55,16,16,16,16,16,56,57,58,59,60,61,62,63,16,1151,16,52,53,54,16,16,16,16,16,16,55,16,16,56,16,57,58,59,60,61,62,63,64,65,66,
1216,64,16,65,66,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1267,68,16,69,70,71,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1316,72,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1316,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1416,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1516,16,16,73,74,16,16,16,75,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1416,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1616,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1516,16,16,67,68,16,16,16,69,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1616,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1816,16,16,16,16,16,16,76,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1816,16,16,16,16,16,16,70,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1916,16,77,78,16,16,16,16,16,16,16,79,16,16,16,16,16,80,81,82,16,16,16,16,16,83,
1916,16,71,72,16,16,16,16,16,16,16,73,16,16,16,16,16,74,16,16,16,16,16,16,16,75,2084,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
2076,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
2116,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,2116,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,
22255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,22255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
...@@ -25,16 +25,16 @@...@@ -25,16 +25,16 @@
250,0,0,0,0,0,0,248,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,250,0,0,0,0,0,0,248,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
260,0,0,254,255,255,255,255,191,182,0,0,0,0,0,0,0,63,0,255,23,0,0,0,0,0,248,255,260,0,0,254,255,255,255,255,191,182,0,0,0,0,0,0,0,63,0,255,23,0,0,0,0,0,248,255,
27255,0,0,1,0,0,0,0,0,0,0,0,0,0,0,192,191,159,61,0,0,0,128,2,0,0,0,255,255,255,27255,0,0,1,0,0,0,0,0,0,0,0,0,0,0,192,191,159,61,0,0,0,128,2,0,0,0,255,255,255,
287,0,0,0,0,0,0,0,0,0,0,192,255,1,0,0,0,0,0,0,248,15,0,0,0,192,251,239,62,0,0,0,287,0,0,0,0,0,0,0,0,0,0,192,255,1,0,0,0,0,0,0,248,15,32,0,0,192,251,239,62,0,0,
290,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,255,255,255,255,290,0,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,248,255,255,255,255,
30255,7,0,0,0,0,0,0,20,254,33,254,0,12,0,0,0,2,0,0,0,0,0,0,16,30,32,0,0,12,0,0,30255,7,0,0,0,0,0,0,20,254,33,254,0,12,0,0,0,2,0,0,0,0,0,0,16,30,32,0,0,12,0,0,
310,6,0,0,0,0,0,0,16,134,57,2,0,0,0,35,0,6,0,0,0,0,0,0,16,190,33,0,0,12,0,0,252,3164,6,0,0,0,0,0,0,16,134,57,2,0,0,0,35,0,6,0,0,0,0,0,0,16,190,33,0,0,12,0,0,
322,0,0,0,0,0,0,144,30,32,64,0,12,0,0,0,4,0,0,0,0,0,0,0,1,32,0,0,0,0,0,0,1,0,0,32252,2,0,0,0,0,0,0,144,30,32,64,0,12,0,0,0,4,0,0,0,0,0,0,0,1,32,0,0,0,0,0,0,17,
330,0,0,0,192,193,61,96,0,12,0,0,0,2,0,0,0,0,0,0,144,64,48,0,0,12,0,0,0,3,0,0,0,330,0,0,0,0,0,192,193,61,96,0,12,0,0,0,2,0,0,0,0,0,0,144,64,48,0,0,12,0,0,0,3,0,
340,0,0,24,30,32,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,4,92,0,0,0,0,0,0,0,0,0,0,0,242,340,0,0,0,0,24,30,32,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,4,92,0,0,0,0,0,0,0,0,0,0,0,
357,128,127,0,0,0,0,0,0,0,0,0,0,0,0,242,27,0,63,0,0,0,0,0,0,0,0,0,3,0,0,160,2,0,35242,7,128,127,0,0,0,0,0,0,0,0,0,0,0,0,242,31,0,63,0,0,0,0,0,0,0,0,0,3,0,0,160,
360,0,0,0,0,254,127,223,224,255,254,255,255,255,31,64,0,0,0,0,0,0,0,0,0,0,0,0,362,0,0,0,0,0,0,254,127,223,224,255,254,255,255,255,31,64,0,0,0,0,0,0,0,0,0,0,0,
37224,253,102,0,0,0,195,1,0,30,0,100,32,0,32,0,0,0,0,0,0,0,0,0,0,0,370,224,253,102,0,0,0,195,1,0,30,0,100,32,0,32,0,0,0,0,0,0,0,0,0,0,0,
380,0,0,0,0,0,0,0,0,0,0,0,224,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,0,380,0,0,0,0,0,0,0,0,0,0,0,224,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,0,
390,0,28,0,0,0,12,0,0,0,12,0,0,0,0,0,0,0,176,63,64,254,15,32,0,0,0,0,0,120,0,0,390,0,28,0,0,0,12,0,0,0,12,0,0,0,0,0,0,0,176,63,64,254,15,32,0,0,0,0,0,120,0,0,
400,0,0,0,0,0,0,0,0,0,0,0,96,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135,1,4,14,0,400,0,0,0,0,0,0,0,0,0,0,0,96,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,135,1,4,14,0,
...@@ -48,9 +48,9 @@...@@ -48,9 +48,9 @@
480,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,480,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,
490,60,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,490,60,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
500,0,0,128,247,63,0,0,0,192,0,0,0,0,0,0,0,0,0,0,3,0,68,8,0,0,96,0,0,0,0,0,0,0,500,0,0,128,247,63,0,0,0,192,0,0,0,0,0,0,0,0,0,0,3,0,68,8,0,0,96,0,0,0,0,0,0,0,
510,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0,255,255,3,0,0,0,0,0,192,63,0,0,128,255,3,0,0,510,0,0,0,0,0,0,0,0,0,0,0,48,0,0,0,255,255,3,128,0,0,0,0,192,63,0,0,128,255,3,0,
520,0,0,7,0,0,0,0,0,200,19,0,0,0,0,32,0,0,0,0,0,0,0,0,126,102,0,8,16,0,0,0,0,0,520,0,0,0,7,0,0,0,0,0,200,51,0,0,0,0,32,0,0,0,0,0,0,0,0,126,102,0,8,16,0,0,0,0,
5316,0,0,0,0,0,0,157,193,2,0,0,0,0,48,64,530,16,0,0,0,0,0,0,157,193,2,0,0,0,0,48,64,
540,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,33,0,0,0,0,0,64,540,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,33,0,0,0,0,0,64,
550,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,255,255,0,550,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,255,255,0,
560,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,560,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,
...@@ -58,24 +58,32 @@...@@ -58,24 +58,32 @@
580,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,580,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
590,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,590,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
600,110,240,0,0,0,0,0,135,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,96,0,0,600,110,240,0,0,0,0,0,135,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,96,0,0,
610,2,0,0,0,0,0,0,255,127,0,0,0,0,0,0,128,3,0,0,0,0,0,120,38,0,0,0,0,0,0,0,0,7,610,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
620,0,0,128,239,31,0,0,0,0,0,0,0,8,0,3,0,0,0,0,0,192,127,0,28,0,0,0,0,0,0,0,0,0,620,0,0,192,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,255,
630,0,128,211,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,248,7,0,0,3,0,0,0,0,63127,0,0,0,0,0,0,128,3,0,0,0,0,0,120,38,0,32,0,0,0,0,0,0,7,0,0,0,128,239,31,0,
640,0,16,1,0,0,0,192,31,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,640,0,0,0,0,0,8,0,3,0,0,0,0,0,192,127,0,30,0,0,0,0,0,0,0,0,0,0,0,128,211,64,0,0,
6592,0,0,0,0,0,0,0,0,0,0,0,0,0,248,133,13,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,650,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,248,7,0,0,3,0,0,0,0,0,0,24,1,0,0,0,192,
660,0,0,0,0,0,0,0,0,0,60,176,1,0,0,48,0,0,0,0,0,0,0,0,0,0,248,167,1,0,0,0,0,0,0,6631,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,92,0,0,64,0,0,0,0,0,
670,0,0,0,0,0,40,191,0,0,0,0,0,0,0,0,0,0,0,0,224,188,15,0,0,0,0,0,0,0,0,0,0,0,0,670,0,0,0,0,248,133,13,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
680,0,0,0,0,0,0,0,0,0,0,0,0,680,60,176,1,0,0,48,0,0,0,
690,126,6,0,0,0,0,248,121,128,0,126,14,0,0,0,0,0,252,127,3,0,0,0,0,0,0,0,0,0,0,690,0,0,0,0,0,0,248,167,1,0,0,0,0,0,0,0,0,0,0,0,0,40,191,0,0,0,0,0,0,0,0,0,0,0,
700,0,0,0,0,0,0,0,127,191,0,0,0,0,0,0,0,0,0,0,252,255,255,252,109,0,0,0,0,0,0,0,700,224,188,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
710,0,0,0,0,0,0,0,126,180,191,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,71128,255,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
720,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31,0,0,0,0,0,0,0,127,720,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,12,1,0,0,0,254,7,0,0,0,0,248,121,128,0,
730,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,73126,14,0,0,0,0,0,252,127,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,191,0,0,0,
740,0,0,128,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,740,0,0,0,0,0,0,252,255,255,252,109,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,126,180,191,0,
7596,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,3,248,255,231,15,0,0,750,0,0,0,0,0,0,0,163,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
760,60,0,0,0,0,0,0,0,0,0,760,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
770,0,0,0,0,0,0,0,0,28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,770,0,0,0,0,0,0,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
78255,255,255,255,127,248,255,255,255,255,255,31,32,0,16,0,0,248,254,255,0,0,0,780,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31,0,0,0,0,0,0,0,127,0,0,0,
790,0,0,0,0,0,0,127,255,255,249,219,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,790,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,
800,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,0,0,0,0,0,0,800,128,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,96,15,
810,0,0,0,0,0,0,240,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,810,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,3,248,255,231,15,0,0,0,60,0,
820,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
830,0,0,255,255,255,255,255,255,127,248,255,255,255,255,255,31,32,0,16,0,0,248,
84254,255,0,0,0,0,0,0,0,0,0,
850,127,255,255,249,219,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
860,0,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
870,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
880,0,0,0,0,0,0,0,0,0,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,240,7,0,0,0,0,0,0,0,0,
890,0,0,0,0,0,0,0,0,0,0,0,0,0,
lib/libc/musl/src/ctype/punct.h+86-74
...@@ -8,17 +8,17 @@...@@ -8,17 +8,17 @@
816,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,816,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
916,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,64,16,16,16,16,16,16,16,16,16,916,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,64,16,16,16,16,16,16,16,16,16,
1016,16,16,16,16,16,16,16,16,16,16,16,16,16,65,16,16,66,16,67,68,1016,16,16,16,16,16,16,16,16,16,16,16,16,16,65,16,16,66,16,67,68,
1169,16,70,71,72,16,73,16,16,74,75,76,77,78,16,79,16,80,81,82,83,84,85,86,87,88,1169,16,70,71,72,16,73,16,16,74,75,76,77,78,16,79,80,81,82,83,84,85,86,87,88,89,
1216,89,16,90,91,16,16,16,16,16,16,92,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1290,91,16,92,93,94,95,16,16,16,16,96,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1316,97,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1316,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1416,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1516,16,16,98,99,16,16,100,101,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1416,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1616,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1516,16,16,93,94,16,16,16,95,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1616,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1816,16,16,16,16,16,16,16,102,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1816,16,16,16,16,16,16,96,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1916,16,16,103,104,105,106,16,16,107,108,17,17,109,16,16,16,16,16,16,110,111,16,
1916,97,98,99,100,16,16,101,102,17,17,103,16,16,16,16,16,16,16,16,16,16,16,16,2016,16,16,16,112,113,16,16,114,115,116,16,117,118,119,17,17,17,120,121,122,123,
2016,104,105,16,16,16,16,106,16,107,108,109,17,17,17,110,111,112,113,16,16,16,21124,16,16,16,16,
2116,16,
2216,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,2216,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,
23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
24255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,254,255,0,252,1,0,0,248,1,24255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,254,255,0,252,1,0,0,248,1,
...@@ -28,25 +28,25 @@...@@ -28,25 +28,25 @@
280,0,0,0,0,0,0,0,0,0,0,0,0,0,252,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,280,0,0,0,0,0,0,0,0,0,0,0,0,0,252,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
290,0,0,252,0,0,0,0,0,230,254,255,255,255,0,64,73,0,0,0,0,0,24,0,255,255,0,216,290,0,0,252,0,0,0,0,0,230,254,255,255,255,0,64,73,0,0,0,0,0,24,0,255,255,0,216,
300,0,0,0,0,0,0,1,0,60,0,0,0,0,0,0,0,0,0,0,0,0,16,224,1,30,0,300,0,0,0,0,0,0,1,0,60,0,0,0,0,0,0,0,0,0,0,0,0,16,224,1,30,0,
3196,255,191,0,0,0,0,0,0,255,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,248,207,3,3196,255,191,0,0,0,0,0,0,255,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,248,207,
320,0,0,3,0,32,255,127,0,0,0,78,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,252,0,0,0,0,0,32227,0,0,0,3,0,32,255,127,0,0,0,78,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,7,252,0,0,0,
330,0,0,0,16,0,32,30,0,48,0,1,0,0,0,0,0,0,0,0,16,0,32,0,0,0,0,252,47,0,0,0,0,0,330,0,0,0,0,0,16,0,32,30,0,48,0,1,0,0,0,0,0,0,0,0,16,0,32,0,0,0,0,252,111,0,0,0,
340,0,16,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,32,0,0,0,0,3,224,0,0,0,0,0,0,0,16,340,0,0,0,16,0,32,0,0,0,0,64,0,0,0,0,0,0,0,0,16,0,32,0,0,0,0,3,224,0,0,0,0,0,0,
350,32,0,0,0,0,253,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,255,7,0,0,0,0,0,0,0,0,0,32,0,350,16,0,32,0,0,0,0,253,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,255,7,16,0,0,0,0,0,0,0,0,
360,0,0,0,255,0,0,0,0,0,0,0,16,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0,160,0,127,0,3632,0,0,0,0,128,255,16,0,0,0,0,0,0,16,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,24,0,160,
370,255,3,0,0,0,0,0,0,0,0,0,4,0,0,0,0,16,0,0,0,0,0,0,128,0,128,192,223,0,12,0,0,370,127,0,0,255,3,0,0,0,0,0,0,0,0,0,4,0,0,0,0,16,0,0,0,0,0,0,128,0,128,192,223,
380,0,0,0,0,0,0,0,0,0,0,31,0,0,0,0,0,380,12,0,0,0,0,0,0,0,0,0,0,0,4,0,31,0,0,0,0,0,
390,254,255,255,255,0,252,255,255,0,0,0,0,0,0,0,0,252,0,0,0,0,0,0,192,255,223,390,254,255,255,255,0,252,255,255,0,0,0,0,0,0,0,0,252,0,0,0,0,0,0,192,255,223,
40255,7,0,0,0,0,0,0,0,0,0,0,128,6,0,252,0,0,24,62,0,0,128,191,0,204,0,0,0,0,0,0,40255,7,0,0,0,0,0,0,0,0,0,0,128,6,0,252,0,0,0,0,0,0,0,0,0,192,0,0,0,0,0,0,0,0,0,
410,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,96,255,255,255,31,0,0,255,3,0,0,0,0,0,0,0,0,410,0,8,0,0,0,0,0,0,0,0,0,0,0,224,255,255,255,31,0,0,255,3,0,0,0,0,0,0,0,0,0,0,
420,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,420,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
430,0,0,0,0,0,0,0,0,0,96,0,0,1,0,0,24,0,0,0,0,0,0,0,0,0,56,0,0,0,0,16,0,0,0,112,430,0,0,0,0,0,0,0,96,0,0,1,0,0,24,0,0,0,0,0,0,0,0,0,56,0,0,0,0,16,0,0,0,112,0,0,
440,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,254,127,47,0,0,255,3,255,127,0,0,0,0,0,0,440,0,0,0,0,0,0,0,0,0,0,0,0,48,0,0,254,127,47,0,0,255,3,255,127,0,0,0,0,0,0,0,0,
450,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,49,0,0,0,0,0,450,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,49,0,0,0,0,0,0,0,
460,0,0,0,0,0,0,0,0,0,0,0,0,196,255,255,255,460,0,0,0,0,0,0,0,0,0,0,196,255,255,255,
47255,0,0,0,192,0,0,0,0,0,0,0,0,1,0,224,159,0,0,0,0,127,63,255,127,0,0,0,0,0,0,47255,0,0,0,192,0,0,0,0,0,0,0,0,1,0,224,159,0,0,0,0,127,63,255,127,0,0,0,0,0,0,
480,0,0,0,0,0,0,0,16,0,16,0,0,252,255,255,255,31,0,0,0,0,0,12,0,0,0,0,0,0,64,0,480,0,0,0,0,0,0,0,16,0,16,0,0,252,255,255,255,31,0,0,0,0,0,12,0,0,0,0,0,0,64,0,
4912,240,0,0,0,0,0,0,192,248,0,0,0,0,0,0,0,192,0,0,0,0,0,0,0,0,255,0,255,255,4912,240,0,0,0,0,0,0,128,248,0,0,0,0,0,0,0,192,0,0,0,0,0,0,0,0,255,0,255,255,
50255,33,144,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,50255,33,144,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,
51127,0,224,251,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,3,224,0,224,0,51127,0,224,251,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,160,3,224,0,224,0,
52224,0,96,128,248,255,255,255,252,255,255,255,255,255,127,223,255,241,127,255,52224,0,96,128,248,255,255,255,252,255,255,255,255,255,127,223,255,241,127,255,
...@@ -55,22 +55,23 @@...@@ -55,22 +55,23 @@
55255,255,255,255,255,127,0,0,0,255,7,0,0,255,255,255,255,255,255,255,255,255,55255,255,255,255,255,127,0,0,0,255,7,0,0,255,255,255,255,255,255,255,255,255,
56255,63,0,0,0,0,0,0,252,255,56255,63,0,0,0,0,0,0,252,255,
57255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,207,255,255,255,57255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,207,255,255,255,
5863,255,255,255,255,227,255,253,7,0,0,240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5863,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,
590,0,0,0,0,0,0,0,0,0,0,0,224,135,3,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,128,0,0,0,590,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,135,3,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
600,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,127,255,255,255,3,0,0,0,0,0,0,60128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,127,255,255,255,255,0,
61255,255,255,251,255,255,255,255,255,255,255,255,255,255,15,0,255,255,255,255,610,0,0,0,0,255,255,255,251,255,255,255,255,255,255,255,255,255,255,15,0,255,
62255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,62255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
63255,255,255,63,0,0,0,255,15,30,255,255,255,1,252,193,224,0,0,0,0,0,0,0,0,0,0,63255,255,255,255,255,255,63,0,0,0,255,15,30,255,255,255,1,252,193,224,0,0,0,0,
640,30,1,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,640,0,0,0,0,0,0,30,1,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
650,0,255,255,255,255,15,0,0,0,255,255,255,127,255,255,255,255,255,255,255,255,65255,255,0,0,0,0,255,255,255,255,15,0,0,0,255,255,255,127,255,255,255,255,255,
66255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,66255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
67127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,67255,255,255,
68255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,
68255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,127,0,0,0,69255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,127,0,0,0,
690,0,0,192,0,224,0,0,0,0,0,0,0,0,0,0,0,128,15,112,0,0,0,0,0,0,0,0,0,0,0,0,0,0,700,0,0,192,0,224,0,0,0,0,0,0,0,0,0,0,0,128,15,112,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
70255,0,255,255,127,0,3,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,71255,0,255,255,127,0,3,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
7168,8,0,0,0,15,255,3,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,16,192,0,0,255,255,3,23,7264,0,0,0,0,15,255,3,0,0,0,0,0,0,240,0,0,0,0,0,0,0,0,0,16,192,0,0,255,255,3,23,
720,0,0,0,0,248,0,0,0,0,8,128,0,0,0,0,0,0,0,0,0,0,8,0,255,63,0,192,32,0,0,0,0,0,730,0,0,0,0,248,0,0,0,0,8,128,0,0,0,0,0,0,0,0,0,0,8,0,255,63,0,192,0,0,0,0,0,0,
730,0,0,0,0,0,0,0,0,240,0,0,128,59,0,0,0,0,0,0,0,128,2,0,0,192,0,0,67,0,0,0,0,0,740,0,0,0,0,0,0,0,0,240,0,0,128,3,0,0,0,0,0,0,0,128,2,0,0,192,0,0,67,0,0,0,0,0,
740,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,56,0,750,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,56,0,
750,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,760,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
760,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,2,0,0,0,0,0,0,770,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,2,0,0,0,0,0,0,
...@@ -84,46 +85,57 @@...@@ -84,46 +85,57 @@
840,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,850,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
85128,255,0,0,128,255,0,0,0,0,128,255,0,0,0,0,0,0,0,0,0,248,0,0,192,143,0,0,0,86128,255,0,0,128,255,0,0,0,0,128,255,0,0,0,0,0,0,0,0,0,248,0,0,192,143,0,0,0,
86128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,255,255,252,255,255,255,255,255,0,0,0,0,87128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,48,255,255,252,255,255,255,255,255,0,0,0,0,
870,0,0,135,255,0,255,1,0,0,0,224,0,0,0,224,0,0,0,0,0,1,0,0,96,248,127,0,0,0,0,880,0,0,135,255,1,255,1,0,0,0,224,0,0,0,224,0,0,0,0,0,1,0,0,96,248,127,0,0,0,0,
880,0,0,0,254,0,0,0,255,0,0,0,255,0,0,0,30,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,890,0,0,0,254,0,0,0,255,0,0,0,255,0,0,0,30,0,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
890,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252,0,0,0,0,0,0,0,0,0,0,0,900,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252,0,0,0,0,0,0,0,0,0,0,0,
900,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,910,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
910,0,0,0,0,0,0,0,0,192,63,252,255,63,0,0,128,3,0,0,0,0,0,0,254,3,0,0,0,0,0,0,0,920,0,0,0,224,127,0,0,0,192,255,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
920,0,0,0,0,0,24,0,15,0,0,0,0,0,56,0,0,0,0,0,0,0,0,0,225,63,0,232,254,255,31,0,930,0,0,0,0,0,0,192,63,252,255,63,0,0,128,3,0,0,0,0,0,0,254,3,32,0,0,0,0,0,0,0,
930,0,0,0,0,0,96,63,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,940,0,0,0,0,24,0,15,0,0,0,0,0,56,0,0,0,0,0,0,0,0,0,225,63,0,232,254,255,31,0,0,
940,16,0,32,0,0,192,31,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,950,0,0,0,0,96,63,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,
95248,0,40,0,0,0,0,0,0,0,0,0,0,0,0,76,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9624,0,32,0,0,192,31,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,68,
960,0,0,0,0,0,0,0,0,128,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,128,14,0,0,0,255,31,97248,0,104,0,0,0,0,0,0,0,0,0,0,0,0,76,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
970,0,0,0,0,0,0,0,192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,252,0,0,0,0,0,0,0,0,0,0,0,980,0,0,0,0,0,0,0,0,0,128,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,128,14,0,0,0,255,
9931,0,0,0,0,0,0,0,0,192,0,0,0,0,0,0,0,0,
1000,0,0,0,0,0,8,0,252,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1010,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252,7,0,0,0,0,0,0,0,0,0,0,0,
1020,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,24,128,255,0,0,0,0,0,
1030,0,0,0,0,223,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,62,0,0,252,255,31,3,0,
1040,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,52,0,0,0,0,0,0,0,0,0,128,0,0,
1050,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1060,0,128,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,
107255,3,
108128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1090,0,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1100,0,0,192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,63,0,0,0,0,0,0,0,255,255,48,0,0,248,
1113,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,
112255,255,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1130,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,176,15,0,0,0,0,0,0,
1140,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
115255,255,255,255,255,255,255,255,255,255,255,255,255,63,
1160,255,255,255,255,127,254,255,255,255,255,255,255,255,255,255,255,255,255,255,
117255,255,255,255,255,255,255,255,255,255,1,0,0,255,255,255,255,255,255,255,255,
11863,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,15,0,255,255,255,255,255,255,
119255,255,255,255,127,0,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1200,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,8,0,0,0,8,0,0,32,0,0,0,32,0,0,128,
1210,0,0,128,0,0,0,2,0,0,0,2,0,0,8,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,
122255,255,255,255,255,255,255,255,255,15,0,248,254,255,0,0,0,0,0,0,0,0,0,0,0,0,
1230,0,0,0,127,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,0,
125128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,255,127,0,0,0,0,0,0,0,
1260,0,0,0,0,0,112,7,0,192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1270,0,0,0,0,0,0,254,255,255,255,255,255,255,255,31,0,0,0,0,0,0,0,0,0,254,255,
128255,255,255,255,255,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1290,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,255,255,255,255,255,
13015,255,255,255,255,255,255,255,255,255,255,255,255,15,0,255,127,254,255,254,
131255,254,255,255,255,63,0,255,31,255,255,255,255,0,0,0,252,0,0,0,28,0,0,0,252,
132255,255,255,31,0,0,0,0,0,0,192,255,255,255,7,0,255,255,255,255,255,15,255,1,3,
1330,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1340,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
135255,255,255,255,255,255,255,63,0,255,31,255,7,255,255,255,255,255,255,255,255,
136255,255,255,255,255,255,15,0,255,255,255,255,255,255,255,255,255,255,255,1,
137255,15,0,0,255,15,255,255,255,255,255,255,255,0,255,3,255,255,255,255,255,0,
138255,255,255,63,0,0,0,0,0,0,0,0,0,0,255,239,255,255,255,255,255,255,255,255,
139255,255,255,255,123,252,255,255,255,255,231,199,255,255,255,231,255,255,255,
140255,255,255,255,255,255,255,255,255,255,255,255,255,15,0,255,63,15,7,7,0,63,0,
980,0,0,0,0,0,0,0,0,0,0,0,1410,0,0,0,0,0,0,0,0,0,0,0,
990,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,252,7,0,0,0,0,0,0,
1000,24,128,255,0,0,0,0,0,0,0,0,0,0,223,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
101128,62,0,0,252,255,31,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,52,
1020,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31,
1030,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,0,0,0,0,0,0,0,
1040,0,0,0,0,0,0,0,0,63,0,0,0,0,0,0,0,128,255,48,0,0,248,3,0,0,0,0,0,0,0,0,0,0,0,
1050,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,7,0,0,0,0,0,0,0,0,0,0,0,
1060,
1070,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,176,15,0,0,0,0,0,0,0,0,0,0,0,255,255,
108255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
109255,255,255,255,255,255,255,255,255,63,0,255,255,255,255,127,254,255,255,255,
110255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
111255,1,0,0,255,255,255,255,255,255,255,255,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1120,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,127,0,255,255,3,0,0,0,0,
1130,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,
1140,8,0,0,0,8,0,0,32,0,0,0,32,0,0,128,0,0,0,128,0,0,0,2,0,0,0,2,0,0,8,0,0,0,0,0,
1150,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,0,
116248,254,255,0,0,0,0,0,0,0,0,0,
1170,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,255,127,0,0,0,0,0,0,0,0,
1180,0,0,0,0,112,7,0,192,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1190,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,255,255,255,255,255,15,255,
120255,255,255,255,255,255,255,255,255,255,255,15,0,255,127,254,255,254,255,254,
121255,255,255,63,0,255,31,255,255,255,127,0,0,0,252,0,0,0,12,0,0,0,252,255,255,
122255,31,0,0,0,0,0,0,192,255,255,255,7,0,255,255,255,255,255,15,255,1,3,0,63,0,
1230,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,
124255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,255,31,
125255,1,255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,0,255,255,
126255,255,255,255,255,255,255,255,31,0,0,0,0,
1270,255,15,255,255,255,255,255,255,255,0,255,3,255,255,255,255,255,0,255,255,
128255,63,0,0,0,0,0,0,0,0,0,0,255,15,255,255,255,255,255,127,255,31,255,255,255,
12915,0,0,255,255,255,0,0,0,0,0,1,0,255,255,127,0,0,0,
lib/libc/musl/src/ctype/towctrans.c+55-289
...@@ -1,307 +1,73 @@...@@ -1,307 +1,73 @@
1#include <ctype.h>
2#include <stddef.h>
3#include <wctype.h>1#include <wctype.h>
42
5#define CASEMAP(u1,u2,l) { (u1), (l)-(u1), (u2)-(u1)+1 }3static const unsigned char tab[];
6#define CASELACE(u1,u2) CASEMAP((u1),(u2),(u1)+1)
74
8static const struct {5static const unsigned char rulebases[512];
9 unsigned short upper;6static const int rules[];
10 signed char lower;
11 unsigned char len;
12} casemaps[] = {
13 CASEMAP(0xc0,0xde,0xe0),
147
15 CASELACE(0x0100,0x012e),8static const unsigned char exceptions[][2];
16 CASELACE(0x0132,0x0136),
17 CASELACE(0x0139,0x0147),
18 CASELACE(0x014a,0x0176),
19 CASELACE(0x0179,0x017d),
209
21 CASELACE(0x370,0x372),10#include "casemap.h"
22 CASEMAP(0x391,0x3a1,0x3b1),
23 CASEMAP(0x3a3,0x3ab,0x3c3),
24 CASEMAP(0x400,0x40f,0x450),
25 CASEMAP(0x410,0x42f,0x430),
2611
27 CASELACE(0x460,0x480),12static int casemap(unsigned c, int dir)
28 CASELACE(0x48a,0x4be),
29 CASELACE(0x4c1,0x4cd),
30 CASELACE(0x4d0,0x50e),
31
32 CASELACE(0x514,0x52e),
33 CASEMAP(0x531,0x556,0x561),
34
35 CASELACE(0x01a0,0x01a4),
36 CASELACE(0x01b3,0x01b5),
37 CASELACE(0x01cd,0x01db),
38 CASELACE(0x01de,0x01ee),
39 CASELACE(0x01f8,0x021e),
40 CASELACE(0x0222,0x0232),
41 CASELACE(0x03d8,0x03ee),
42
43 CASELACE(0x1e00,0x1e94),
44 CASELACE(0x1ea0,0x1efe),
45
46 CASEMAP(0x1f08,0x1f0f,0x1f00),
47 CASEMAP(0x1f18,0x1f1d,0x1f10),
48 CASEMAP(0x1f28,0x1f2f,0x1f20),
49 CASEMAP(0x1f38,0x1f3f,0x1f30),
50 CASEMAP(0x1f48,0x1f4d,0x1f40),
51
52 CASEMAP(0x1f68,0x1f6f,0x1f60),
53 CASEMAP(0x1f88,0x1f8f,0x1f80),
54 CASEMAP(0x1f98,0x1f9f,0x1f90),
55 CASEMAP(0x1fa8,0x1faf,0x1fa0),
56 CASEMAP(0x1fb8,0x1fb9,0x1fb0),
57 CASEMAP(0x1fba,0x1fbb,0x1f70),
58 CASEMAP(0x1fc8,0x1fcb,0x1f72),
59 CASEMAP(0x1fd8,0x1fd9,0x1fd0),
60 CASEMAP(0x1fda,0x1fdb,0x1f76),
61 CASEMAP(0x1fe8,0x1fe9,0x1fe0),
62 CASEMAP(0x1fea,0x1feb,0x1f7a),
63 CASEMAP(0x1ff8,0x1ff9,0x1f78),
64 CASEMAP(0x1ffa,0x1ffb,0x1f7c),
65
66 CASEMAP(0x13f0,0x13f5,0x13f8),
67 CASELACE(0xa698,0xa69a),
68 CASELACE(0xa796,0xa79e),
69
70 CASELACE(0x246,0x24e),
71 CASELACE(0x510,0x512),
72 CASEMAP(0x2160,0x216f,0x2170),
73 CASEMAP(0x2c00,0x2c2e,0x2c30),
74 CASELACE(0x2c67,0x2c6b),
75 CASELACE(0x2c80,0x2ce2),
76 CASELACE(0x2ceb,0x2ced),
77
78 CASELACE(0xa640,0xa66c),
79 CASELACE(0xa680,0xa696),
80
81 CASELACE(0xa722,0xa72e),
82 CASELACE(0xa732,0xa76e),
83 CASELACE(0xa779,0xa77b),
84 CASELACE(0xa77e,0xa786),
85
86 CASELACE(0xa790,0xa792),
87 CASELACE(0xa7a0,0xa7a8),
88
89 CASELACE(0xa7b4,0xa7b6),
90
91 CASEMAP(0xff21,0xff3a,0xff41),
92 { 0,0,0 }
93};
94
95static const unsigned short pairs[][2] = {
96 { 'I', 0x0131 },
97 { 'S', 0x017f },
98 { 0x0130, 'i' },
99 { 0x0178, 0x00ff },
100 { 0x0181, 0x0253 },
101 { 0x0182, 0x0183 },
102 { 0x0184, 0x0185 },
103 { 0x0186, 0x0254 },
104 { 0x0187, 0x0188 },
105 { 0x0189, 0x0256 },
106 { 0x018a, 0x0257 },
107 { 0x018b, 0x018c },
108 { 0x018e, 0x01dd },
109 { 0x018f, 0x0259 },
110 { 0x0190, 0x025b },
111 { 0x0191, 0x0192 },
112 { 0x0193, 0x0260 },
113 { 0x0194, 0x0263 },
114 { 0x0196, 0x0269 },
115 { 0x0197, 0x0268 },
116 { 0x0198, 0x0199 },
117 { 0x019c, 0x026f },
118 { 0x019d, 0x0272 },
119 { 0x019f, 0x0275 },
120 { 0x01a6, 0x0280 },
121 { 0x01a7, 0x01a8 },
122 { 0x01a9, 0x0283 },
123 { 0x01ac, 0x01ad },
124 { 0x01ae, 0x0288 },
125 { 0x01af, 0x01b0 },
126 { 0x01b1, 0x028a },
127 { 0x01b2, 0x028b },
128 { 0x01b7, 0x0292 },
129 { 0x01b8, 0x01b9 },
130 { 0x01bc, 0x01bd },
131 { 0x01c4, 0x01c6 },
132 { 0x01c4, 0x01c5 },
133 { 0x01c5, 0x01c6 },
134 { 0x01c7, 0x01c9 },
135 { 0x01c7, 0x01c8 },
136 { 0x01c8, 0x01c9 },
137 { 0x01ca, 0x01cc },
138 { 0x01ca, 0x01cb },
139 { 0x01cb, 0x01cc },
140 { 0x01f1, 0x01f3 },
141 { 0x01f1, 0x01f2 },
142 { 0x01f2, 0x01f3 },
143 { 0x01f4, 0x01f5 },
144 { 0x01f6, 0x0195 },
145 { 0x01f7, 0x01bf },
146 { 0x0220, 0x019e },
147 { 0x0386, 0x03ac },
148 { 0x0388, 0x03ad },
149 { 0x0389, 0x03ae },
150 { 0x038a, 0x03af },
151 { 0x038c, 0x03cc },
152 { 0x038e, 0x03cd },
153 { 0x038f, 0x03ce },
154 { 0x0399, 0x0345 },
155 { 0x0399, 0x1fbe },
156 { 0x03a3, 0x03c2 },
157 { 0x03f7, 0x03f8 },
158 { 0x03fa, 0x03fb },
159 { 0x1e60, 0x1e9b },
160 { 0x1e9e, 0xdf },
161
162 { 0x1f59, 0x1f51 },
163 { 0x1f5b, 0x1f53 },
164 { 0x1f5d, 0x1f55 },
165 { 0x1f5f, 0x1f57 },
166 { 0x1fbc, 0x1fb3 },
167 { 0x1fcc, 0x1fc3 },
168 { 0x1fec, 0x1fe5 },
169 { 0x1ffc, 0x1ff3 },
170
171 { 0x23a, 0x2c65 },
172 { 0x23b, 0x23c },
173 { 0x23d, 0x19a },
174 { 0x23e, 0x2c66 },
175 { 0x241, 0x242 },
176 { 0x243, 0x180 },
177 { 0x244, 0x289 },
178 { 0x245, 0x28c },
179 { 0x3f4, 0x3b8 },
180 { 0x3f9, 0x3f2 },
181 { 0x3fd, 0x37b },
182 { 0x3fe, 0x37c },
183 { 0x3ff, 0x37d },
184 { 0x4c0, 0x4cf },
185
186 { 0x2126, 0x3c9 },
187 { 0x212a, 'k' },
188 { 0x212b, 0xe5 },
189 { 0x2132, 0x214e },
190 { 0x2183, 0x2184 },
191 { 0x2c60, 0x2c61 },
192 { 0x2c62, 0x26b },
193 { 0x2c63, 0x1d7d },
194 { 0x2c64, 0x27d },
195 { 0x2c6d, 0x251 },
196 { 0x2c6e, 0x271 },
197 { 0x2c6f, 0x250 },
198 { 0x2c70, 0x252 },
199 { 0x2c72, 0x2c73 },
200 { 0x2c75, 0x2c76 },
201 { 0x2c7e, 0x23f },
202 { 0x2c7f, 0x240 },
203 { 0x2cf2, 0x2cf3 },
204
205 { 0xa77d, 0x1d79 },
206 { 0xa78b, 0xa78c },
207 { 0xa78d, 0x265 },
208 { 0xa7aa, 0x266 },
209
210 { 0x10c7, 0x2d27 },
211 { 0x10cd, 0x2d2d },
212
213 /* bogus greek 'symbol' letters */
214 { 0x376, 0x377 },
215 { 0x39c, 0xb5 },
216 { 0x392, 0x3d0 },
217 { 0x398, 0x3d1 },
218 { 0x3a6, 0x3d5 },
219 { 0x3a0, 0x3d6 },
220 { 0x39a, 0x3f0 },
221 { 0x3a1, 0x3f1 },
222 { 0x395, 0x3f5 },
223 { 0x3cf, 0x3d7 },
224
225 { 0xa7ab, 0x25c },
226 { 0xa7ac, 0x261 },
227 { 0xa7ad, 0x26c },
228 { 0xa7ae, 0x26a },
229 { 0xa7b0, 0x29e },
230 { 0xa7b1, 0x287 },
231 { 0xa7b2, 0x29d },
232 { 0xa7b3, 0xab53 },
233
234 /* special cyrillic lowercase forms */
235 { 0x412, 0x1c80 },
236 { 0x414, 0x1c81 },
237 { 0x41e, 0x1c82 },
238 { 0x421, 0x1c83 },
239 { 0x422, 0x1c84 },
240 { 0x422, 0x1c85 },
241 { 0x42a, 0x1c86 },
242 { 0x462, 0x1c87 },
243 { 0xa64a, 0x1c88 },
244
245 { 0,0 }
246};
247
248
249static wchar_t __towcase(wchar_t wc, int lower)
250{13{
251 int i;14 unsigned b, x, y, v, rt, xb, xn;
252 int lmul = 2*lower-1;15 int r, rd, c0 = c;
253 int lmask = lower-1;16
254 /* no letters with case in these large ranges */17 if (c >= 0x20000) return c;
255 if (!iswalpha(wc)18
256 || (unsigned)wc - 0x0600 <= 0x0fff-0x060019 b = c>>8;
257 || (unsigned)wc - 0x2e00 <= 0xa63f-0x2e0020 c &= 255;
258 || (unsigned)wc - 0xa800 <= 0xab52-0xa80021 x = c/3;
259 || (unsigned)wc - 0xabc0 <= 0xfeff-0xabc0)22 y = c%3;
260 return wc;23
261 /* special case because the diff between upper/lower is too big */24 /* lookup entry in two-level base-6 table */
262 if (lower && (unsigned)wc - 0x10a0 < 0x2e)25 v = tab[tab[b]*86+x];
263 if (wc>0x10c5 && wc != 0x10c7 && wc != 0x10cd) return wc;26 static const int mt[] = { 2048, 342, 57 };
264 else return wc + 0x2d00 - 0x10a0;27 v = (v*mt[y]>>11)%6;
265 if (!lower && (unsigned)wc - 0x2d00 < 0x26)28
266 if (wc>0x2d25 && wc != 0x2d27 && wc != 0x2d2d) return wc;29 /* use the bit vector out of the tables as an index into
267 else return wc + 0x10a0 - 0x2d00;30 * a block-specific set of rules and decode the rule into
268 if (lower && (unsigned)wc - 0x13a0 < 0x50)31 * a type and a case-mapping delta. */
269 return wc + 0xab70 - 0x13a0;32 r = rules[rulebases[b]+v];
270 if (!lower && (unsigned)wc - 0xab70 < 0x50)33 rt = r & 255;
271 return wc + 0x13a0 - 0xab70;34 rd = r >> 8;
272 for (i=0; casemaps[i].len; i++) {35
273 int base = casemaps[i].upper + (lmask & casemaps[i].lower);36 /* rules 0/1 are simple lower/upper case with a delta.
274 if ((unsigned)wc-base < casemaps[i].len) {37 * apply according to desired mapping direction. */
275 if (casemaps[i].lower == 1)38 if (rt < 2) return c0 + (rd & -(rt^dir));
276 return wc + lower - ((wc-casemaps[i].upper)&1);39
277 return wc + lmul*casemaps[i].lower;40 /* binary search. endpoints of the binary search for
41 * this block are stored in the rule delta field. */
42 xn = rd & 0xff;
43 xb = (unsigned)rd >> 8;
44 while (xn) {
45 unsigned try = exceptions[xb+xn/2][0];
46 if (try == c) {
47 r = rules[exceptions[xb+xn/2][1]];
48 rt = r & 255;
49 rd = r >> 8;
50 if (rt < 2) return c0 + (rd & -(rt^dir));
51 /* Hard-coded for the four exceptional titlecase */
52 return c0 + (dir ? -1 : 1);
53 } else if (try > c) {
54 xn /= 2;
55 } else {
56 xb += xn/2;
57 xn -= xn/2;
278 }58 }
279 }59 }
280 for (i=0; pairs[i][1-lower]; i++) {60 return c0;
281 if (pairs[i][1-lower] == wc)
282 return pairs[i][lower];
283 }
284 if ((unsigned)wc - (0x10428 - 0x28*lower) < 0x28)
285 return wc - 0x28 + 0x50*lower;
286 if ((unsigned)wc - (0x104d8 - 0x28*lower) < 0x24)
287 return wc - 0x28 + 0x50*lower;
288 if ((unsigned)wc - (0x10cc0 - 0x40*lower) < 0x33)
289 return wc - 0x40 + 0x80*lower;
290 if ((unsigned)wc - (0x118c0 - 0x20*lower) < 0x20)
291 return wc - 0x20 + 0x40*lower;
292 if ((unsigned)wc - (0x1e922 - 0x22*lower) < 0x22)
293 return wc - 0x22 + 0x44*lower;
294 return wc;
295}61}
29662
297wint_t towupper(wint_t wc)63wint_t towlower(wint_t wc)
298{64{
299 return (unsigned)wc < 128 ? toupper(wc) : __towcase(wc, 0);65 return casemap(wc, 0);
300}66}
30167
302wint_t towlower(wint_t wc)68wint_t towupper(wint_t wc)
303{69{
304 return (unsigned)wc < 128 ? tolower(wc) : __towcase(wc, 1);70 return casemap(wc, 1);
305}71}
30672
307wint_t __towupper_l(wint_t c, locale_t l)73wint_t __towupper_l(wint_t c, locale_t l)
lib/libc/musl/src/ctype/wcwidth.c+1-1
...@@ -23,7 +23,7 @@ int wcwidth(wchar_t wc)...@@ -23,7 +23,7 @@ int wcwidth(wchar_t wc)
23 return -1;23 return -1;
24 if (wc-0x20000U < 0x20000)24 if (wc-0x20000U < 0x20000)
25 return 2;25 return 2;
26 if (wc == 0xe0001 || wc-0xe0020U < 0x5f || wc-0xe0100 < 0xef)26 if (wc == 0xe0001 || wc-0xe0020U < 0x5f || wc-0xe0100U < 0xef)
27 return 0;27 return 0;
28 return 1;28 return 1;
29}29}
lib/libc/musl/src/ctype/wide.h+14-12
...@@ -17,7 +17,7 @@...@@ -17,7 +17,7 @@
1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,38,39,16,16,1716,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,38,39,16,16,
1816,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1816,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
1916,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,1916,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
2016,16,16,16,16,16,16,40,41,42,43,44,45,46,16,16,47,16,16,16,16,16,2016,16,16,16,16,16,16,40,41,42,43,44,45,46,47,16,48,49,16,16,16,16,
2116,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,2116,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,
22255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,22255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,23255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
...@@ -31,10 +31,10 @@...@@ -31,10 +31,10 @@
31255,255,255,15,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31255,255,255,15,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
32255,255,255,255,255,255,255,255,255,255,255,63,0,0,0,255,15,255,255,255,255,32255,255,255,255,255,255,255,255,255,255,255,63,0,0,0,255,15,255,255,255,255,
33255,255,255,127,254,255,255,255,255,255,255,255,255,255,127,254,255,255,255,33255,255,255,127,254,255,255,255,255,255,255,255,255,255,127,254,255,255,255,
34255,255,255,255,255,255,255,255,255,224,255,255,255,255,127,254,255,255,255,34255,255,255,255,255,255,255,255,255,224,255,255,255,255,255,254,255,255,255,
35255,255,255,255,255,255,255,127,255,255,255,255,255,7,255,255,255,255,15,0,35255,255,255,255,255,255,255,127,255,255,255,255,255,7,255,255,255,255,15,0,
36255,255,255,255,255,127,255,255,255,255,255,0,255,255,255,255,255,255,255,255,36255,255,255,255,255,127,255,255,255,255,255,0,255,255,255,255,255,255,255,255,
37255,255,255,255,255,255,255,255,255,255,255,255,255,127,255,255,255,255,255,37255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
38255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,38255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,
390,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,390,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
40255,31,255,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,40255,31,255,255,255,255,255,255,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,
...@@ -43,13 +43,13 @@...@@ -43,13 +43,13 @@
43255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,255,3,0,0,255,255,255,255,247,255,127,15,0,0,43255,15,0,0,0,0,0,0,0,0,0,0,0,0,0,255,3,0,0,255,255,255,255,247,255,127,15,0,0,
440,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,255,255,255,255,255,255,255,255,255,255,440,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,254,255,255,255,255,255,255,255,255,255,255,
45255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,45255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
460,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,255,255,255,255,255,255,255,255,255,255,255,460,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0,255,255,255,255,255,255,255,255,255,255,255,
47255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,47255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
480,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,48255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
49255,255,255,255,255,255,255,255,255,255,255,7,0,255,255,255,127,0,0,0,0,0,0,0,49255,255,255,255,255,255,255,255,255,255,255,255,7,0,255,255,255,127,0,0,0,0,0,
500,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,500,7,0,240,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
51255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,51255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
52255,255,255,255,255,255,255,255,255,255,255,255,52255,255,255,255,255,255,255,255,255,255,255,255,255,255,
5315,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,5315,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0,0,0,0,
540,0,0,0,0,0,0,0,0,0,0,0,0,64,254,7,0,0,0,0,0,0,0,0,0,0,0,0,7,0,255,255,255,540,0,0,0,0,0,0,0,0,0,0,0,0,64,254,7,0,0,0,0,0,0,0,0,0,0,0,0,7,0,255,255,255,
55255,255,15,255,1,3,0,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,55255,255,15,255,1,3,0,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,
...@@ -58,6 +58,8 @@...@@ -58,6 +58,8 @@
58255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,58255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
59159,255,255,255,255,255,255,255,63,0,120,255,255,255,0,0,4,0,0,96,0,16,0,0,0,59159,255,255,255,255,255,255,255,63,0,120,255,255,255,0,0,4,0,0,96,0,16,0,0,0,
600,0,0,0,0,0,0,248,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,255,255,600,0,0,0,0,0,0,248,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,255,255,
61255,255,255,255,255,255,63,16,7,0,0,24,240,1,0,0,255,255,255,255,255,127,255,61255,255,255,255,255,255,63,16,39,0,0,24,240,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
6231,255,255,255,15,0,0,255,255,255,0,0,0,0,0,1,0,255,255,127,0,0,620,0,0,0,0,0,0,0,0,0,0,0,255,15,0,
630,630,0,224,255,255,255,255,255,255,255,255,255,255,255,255,123,252,255,255,255,
64255,231,199,255,255,255,231,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,
650,15,7,7,0,63,0,0,0,0,0,0,0,0,0,0,0,0,0,
lib/libc/musl/src/fenv/riscv64/fenv.S+4-1
...@@ -45,8 +45,11 @@ fegetenv:...@@ -45,8 +45,11 @@ fegetenv:
45.global fesetenv45.global fesetenv
46.type fesetenv, %function46.type fesetenv, %function
47fesetenv:47fesetenv:
48 li t2, -1
49 li t1, 0
50 beq a0, t2, 1f
48 lw t1, 0(a0)51 lw t1, 0(a0)
49 fscsr t0, t1521: fscsr t1
50 li a0, 053 li a0, 0
51 ret54 ret
5255
lib/libc/musl/src/internal/dynlink.h-1
...@@ -96,7 +96,6 @@ struct fdpic_dummy_loadmap {...@@ -96,7 +96,6 @@ struct fdpic_dummy_loadmap {
96#define DYN_CNT 3296#define DYN_CNT 32
9797
98typedef void (*stage2_func)(unsigned char *, size_t *);98typedef void (*stage2_func)(unsigned char *, size_t *);
99typedef void (*stage3_func)(size_t *);
10099
101hidden void *__dlsym(void *restrict, const char *restrict, void *restrict);100hidden void *__dlsym(void *restrict, const char *restrict, void *restrict);
102101
lib/libc/musl/src/internal/floatscan.c+1-4
...@@ -33,9 +33,6 @@...@@ -33,9 +33,6 @@
3333
34#define MASK (KMAX-1)34#define MASK (KMAX-1)
3535
36#define CONCAT2(x,y) x ## y
37#define CONCAT(x,y) CONCAT2(x,y)
38
39static long long scanexp(FILE *f, int pok)36static long long scanexp(FILE *f, int pok)
40{37{
41 int c;38 int c;
...@@ -301,7 +298,7 @@ static long double decfloat(FILE *f, int c, int bits, int emin, int sign, int po...@@ -301,7 +298,7 @@ static long double decfloat(FILE *f, int c, int bits, int emin, int sign, int po
301 y -= bias;298 y -= bias;
302299
303 if ((e2+LDBL_MANT_DIG & INT_MAX) > emax-5) {300 if ((e2+LDBL_MANT_DIG & INT_MAX) > emax-5) {
304 if (fabs(y) >= CONCAT(0x1p, LDBL_MANT_DIG)) {301 if (fabsl(y) >= 2/LDBL_EPSILON) {
305 if (denormal && bits==LDBL_MANT_DIG+e2-emin)302 if (denormal && bits==LDBL_MANT_DIG+e2-emin)
306 denormal = 0;303 denormal = 0;
307 y *= 0.5;304 y *= 0.5;
lib/libc/musl/src/internal/syscall.h+46
...@@ -193,6 +193,45 @@ hidden long __syscall_ret(unsigned long),...@@ -193,6 +193,45 @@ hidden long __syscall_ret(unsigned long),
193#define SYS_sendfile SYS_sendfile64193#define SYS_sendfile SYS_sendfile64
194#endif194#endif
195195
196#ifndef SYS_timer_settime
197#define SYS_timer_settime SYS_timer_settime32
198#endif
199
200#ifndef SYS_timer_gettime
201#define SYS_timer_gettime SYS_timer_gettime32
202#endif
203
204#ifndef SYS_timerfd_settime
205#define SYS_timerfd_settime SYS_timerfd_settime32
206#endif
207
208#ifndef SYS_timerfd_gettime
209#define SYS_timerfd_gettime SYS_timerfd_gettime32
210#endif
211
212#ifndef SYS_clock_settime
213#define SYS_clock_settime SYS_clock_settime32
214#endif
215
216#ifndef SYS_clock_gettime
217#define SYS_clock_gettime SYS_clock_gettime32
218#endif
219
220#ifndef SYS_clock_getres
221#define SYS_clock_getres SYS_clock_getres_time32
222#endif
223
224#ifndef SYS_clock_nanosleep
225#define SYS_clock_nanosleep SYS_clock_nanosleep_time32
226#endif
227
228#ifndef SYS_gettimeofday
229#define SYS_gettimeofday SYS_gettimeofday_time32
230#endif
231
232#ifndef SYS_settimeofday
233#define SYS_settimeofday SYS_settimeofday_time32
234#endif
196235
197/* Ensure that the plain syscall names are defined even for "time64-only"236/* Ensure that the plain syscall names are defined even for "time64-only"
198 * archs. These facilitate callers passing null time arguments, and make237 * archs. These facilitate callers passing null time arguments, and make
...@@ -306,6 +345,13 @@ hidden long __syscall_ret(unsigned long),...@@ -306,6 +345,13 @@ hidden long __syscall_ret(unsigned long),
306#define SO_SNDTIMEO_OLD 21345#define SO_SNDTIMEO_OLD 21
307#endif346#endif
308347
348#define SO_TIMESTAMP_OLD 29
349#define SO_TIMESTAMPNS_OLD 35
350#define SO_TIMESTAMPING_OLD 37
351#define SCM_TIMESTAMP_OLD SO_TIMESTAMP_OLD
352#define SCM_TIMESTAMPNS_OLD SO_TIMESTAMPNS_OLD
353#define SCM_TIMESTAMPING_OLD SO_TIMESTAMPING_OLD
354
309#ifndef SIOCGSTAMP_OLD355#ifndef SIOCGSTAMP_OLD
310#define SIOCGSTAMP_OLD 0x8906356#define SIOCGSTAMP_OLD 0x8906
311#endif357#endif
lib/libc/musl/src/internal/version.h+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1#define VERSION "1.1.24"1#define VERSION "1.2.0"
lib/libc/musl/src/ldso/__dlsym.c+4
...@@ -8,3 +8,7 @@ static void *stub_dlsym(void *restrict p, const char *restrict s, void *restrict...@@ -8,3 +8,7 @@ static void *stub_dlsym(void *restrict p, const char *restrict s, void *restrict
8}8}
99
10weak_alias(stub_dlsym, __dlsym);10weak_alias(stub_dlsym, __dlsym);
11
12#if _REDIR_TIME64
13weak_alias(stub_dlsym, __dlsym_redir_time64);
14#endif
lib/libc/musl/src/ldso/arm/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/i386/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/m68k/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/microblaze/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/mips/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/mipsn32/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/or1k/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/powerpc/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/ldso/sh/dlsym_time64.S created+3
...@@ -0,0 +1,3 @@
1#define __dlsym __dlsym_redir_time64
2#define dlsym __dlsym_time64
3#include "dlsym.s"
lib/libc/musl/src/linux/clock_adjtime.c+46-11
...@@ -94,21 +94,56 @@ int clock_adjtime (clockid_t clock_id, struct timex *utx)...@@ -94,21 +94,56 @@ int clock_adjtime (clockid_t clock_id, struct timex *utx)
94 return __syscall_ret(-ENOTSUP);94 return __syscall_ret(-ENOTSUP);
95#endif95#endif
96 if (sizeof(time_t) > sizeof(long)) {96 if (sizeof(time_t) > sizeof(long)) {
97 union {97 struct ktimex ktx = {
98 struct timex utx;98 .modes = utx->modes,
99 struct ktimex ktx;99 .offset = utx->offset,
100 } u = { *utx };100 .freq = utx->freq,
101 u.ktx.time_sec = utx->time.tv_sec;101 .maxerror = utx->maxerror,
102 u.ktx.time_usec = utx->time.tv_usec;102 .esterror = utx->esterror,
103 .status = utx->status,
104 .constant = utx->constant,
105 .precision = utx->precision,
106 .tolerance = utx->tolerance,
107 .time_sec = utx->time.tv_sec,
108 .time_usec = utx->time.tv_usec,
109 .tick = utx->tick,
110 .ppsfreq = utx->ppsfreq,
111 .jitter = utx->jitter,
112 .shift = utx->shift,
113 .stabil = utx->stabil,
114 .jitcnt = utx->jitcnt,
115 .calcnt = utx->calcnt,
116 .errcnt = utx->errcnt,
117 .stbcnt = utx->stbcnt,
118 .tai = utx->tai,
119 };
103#ifdef SYS_adjtimex120#ifdef SYS_adjtimex
104 if (clock_id==CLOCK_REALTIME) r = __syscall(SYS_adjtimex, &u);121 if (clock_id==CLOCK_REALTIME) r = __syscall(SYS_adjtimex, &ktx);
105 else122 else
106#endif123#endif
107 r = __syscall(SYS_clock_adjtime, clock_id, &u);124 r = __syscall(SYS_clock_adjtime, clock_id, &ktx);
108 if (r>=0) {125 if (r>=0) {
109 *utx = u.utx;126 utx->modes = ktx.modes;
110 utx->time.tv_sec = u.ktx.time_sec;127 utx->offset = ktx.offset;
111 utx->time.tv_usec = u.ktx.time_usec;128 utx->freq = ktx.freq;
129 utx->maxerror = ktx.maxerror;
130 utx->esterror = ktx.esterror;
131 utx->status = ktx.status;
132 utx->constant = ktx.constant;
133 utx->precision = ktx.precision;
134 utx->tolerance = ktx.tolerance;
135 utx->time.tv_sec = ktx.time_sec;
136 utx->time.tv_usec = ktx.time_usec;
137 utx->tick = ktx.tick;
138 utx->ppsfreq = ktx.ppsfreq;
139 utx->jitter = ktx.jitter;
140 utx->shift = ktx.shift;
141 utx->stabil = ktx.stabil;
142 utx->jitcnt = ktx.jitcnt;
143 utx->calcnt = ktx.calcnt;
144 utx->errcnt = ktx.errcnt;
145 utx->stbcnt = ktx.stbcnt;
146 utx->tai = ktx.tai;
112 }147 }
113 return __syscall_ret(r);148 return __syscall_ret(r);
114 }149 }
lib/libc/musl/src/linux/wait4.c+32-2
...@@ -1,9 +1,39 @@...@@ -1,9 +1,39 @@
1#define _GNU_SOURCE1#define _GNU_SOURCE
2#include <sys/wait.h>2#include <sys/wait.h>
3#include <sys/resource.h>3#include <sys/resource.h>
4#include <string.h>
5#include <errno.h>
4#include "syscall.h"6#include "syscall.h"
57
6pid_t wait4(pid_t pid, int *status, int options, struct rusage *usage)8pid_t wait4(pid_t pid, int *status, int options, struct rusage *ru)
7{9{
8 return syscall(SYS_wait4, pid, status, options, usage);10 int r;
11#ifdef SYS_wait4_time64
12 if (ru) {
13 long long kru64[18];
14 r = __syscall(SYS_wait4_time64, pid, status, options, kru64);
15 if (!r) {
16 ru->ru_utime = (struct timeval)
17 { .tv_sec = kru64[0], .tv_usec = kru64[1] };
18 ru->ru_stime = (struct timeval)
19 { .tv_sec = kru64[2], .tv_usec = kru64[3] };
20 char *slots = (char *)&ru->ru_maxrss;
21 for (int i=0; i<14; i++)
22 *(long *)(slots + i*sizeof(long)) = kru64[4+i];
23 }
24 if (SYS_wait4_time64 == SYS_wait4 || r != -ENOSYS)
25 return __syscall_ret(r);
26 }
27#endif
28 char *dest = ru ? (char *)&ru->ru_maxrss - 4*sizeof(long) : 0;
29 r = __syscall(SYS_wait4, pid, status, options, dest);
30 if (r>0 && ru && sizeof(time_t) > sizeof(long)) {
31 long kru[4];
32 memcpy(kru, dest, 4*sizeof(long));
33 ru->ru_utime = (struct timeval)
34 { .tv_sec = kru[0], .tv_usec = kru[1] };
35 ru->ru_stime = (struct timeval)
36 { .tv_sec = kru[2], .tv_usec = kru[3] };
37 }
38 return __syscall_ret(r);
9}39}
lib/libc/musl/src/math/i386/acos.s+3-13
...@@ -1,22 +1,10 @@...@@ -1,22 +1,10 @@
1# use acos(x) = atan2(fabs(sqrt((1-x)*(1+x))), x)1# use acos(x) = atan2(fabs(sqrt((1-x)*(1+x))), x)
22
3.global acosf
4.type acosf,@function
5acosf:
6 flds 4(%esp)
7 jmp 1f
8
9.global acosl
10.type acosl,@function
11acosl:
12 fldt 4(%esp)
13 jmp 1f
14
15.global acos3.global acos
16.type acos,@function4.type acos,@function
17acos:5acos:
18 fldl 4(%esp)6 fldl 4(%esp)
191: fld %st(0)7 fld %st(0)
20 fld18 fld1
21 fsub %st(0),%st(1)9 fsub %st(0),%st(1)
22 fadd %st(2)10 fadd %st(2)
...@@ -25,4 +13,6 @@ acos:...@@ -25,4 +13,6 @@ acos:
25 fabs # fix sign of zero (matters in downward rounding mode)13 fabs # fix sign of zero (matters in downward rounding mode)
26 fxch %st(1)14 fxch %st(1)
27 fpatan15 fpatan
16 fstpl 4(%esp)
17 fldl 4(%esp)
28 ret18 ret
lib/libc/musl/src/math/i386/acosf.s+16-1
...@@ -1 +1,16 @@...@@ -1 +1,16 @@
1# see acos.s1.global acosf
2.type acosf,@function
3acosf:
4 flds 4(%esp)
5 fld %st(0)
6 fld1
7 fsub %st(0),%st(1)
8 fadd %st(2)
9 fmulp
10 fsqrt
11 fabs # fix sign of zero (matters in downward rounding mode)
12 fxch %st(1)
13 fpatan
14 fstps 4(%esp)
15 flds 4(%esp)
16 ret
lib/libc/musl/src/math/i386/acosl.s+14-1
...@@ -1 +1,14 @@...@@ -1 +1,14 @@
1# see acos.s1.global acosl
2.type acosl,@function
3acosl:
4 fldt 4(%esp)
5 fld %st(0)
6 fld1
7 fsub %st(0),%st(1)
8 fadd %st(2)
9 fmulp
10 fsqrt
11 fabs # fix sign of zero (matters in downward rounding mode)
12 fxch %st(1)
13 fpatan
14 ret
lib/libc/musl/src/math/i386/asin.s+7-25
...@@ -1,23 +1,3 @@...@@ -1,23 +1,3 @@
1.global asinf
2.type asinf,@function
3asinf:
4 flds 4(%esp)
5 mov 4(%esp),%eax
6 add %eax,%eax
7 cmp $0x01000000,%eax
8 jae 1f
9 # subnormal x, return x with underflow
10 fld %st(0)
11 fmul %st(1)
12 fstps 4(%esp)
13 ret
14
15.global asinl
16.type asinl,@function
17asinl:
18 fldt 4(%esp)
19 jmp 1f
20
21.global asin1.global asin
22.type asin,@function2.type asin,@function
23asin:3asin:
...@@ -25,15 +5,17 @@ asin:...@@ -25,15 +5,17 @@ asin:
25 mov 8(%esp),%eax5 mov 8(%esp),%eax
26 add %eax,%eax6 add %eax,%eax
27 cmp $0x00200000,%eax7 cmp $0x00200000,%eax
28 jae 1f8 jb 1f
29 # subnormal x, return x with underflow9 fld %st(0)
30 fsts 4(%esp)
31 ret
321: fld %st(0)
33 fld110 fld1
34 fsub %st(0),%st(1)11 fsub %st(0),%st(1)
35 fadd %st(2)12 fadd %st(2)
36 fmulp13 fmulp
37 fsqrt14 fsqrt
38 fpatan15 fpatan
16 fstpl 4(%esp)
17 fldl 4(%esp)
18 ret
19 # subnormal x, return x with underflow
201: fsts 4(%esp)
39 ret21 ret
lib/libc/musl/src/math/i386/asinf.s+23-1
...@@ -1 +1,23 @@...@@ -1 +1,23 @@
1# see asin.s1.global asinf
2.type asinf,@function
3asinf:
4 flds 4(%esp)
5 mov 4(%esp),%eax
6 add %eax,%eax
7 cmp $0x01000000,%eax
8 jb 1f
9 fld %st(0)
10 fld1
11 fsub %st(0),%st(1)
12 fadd %st(2)
13 fmulp
14 fsqrt
15 fpatan
16 fstps 4(%esp)
17 flds 4(%esp)
18 ret
19 # subnormal x, return x with underflow
201: fld %st(0)
21 fmul %st(1)
22 fstps 4(%esp)
23 ret
lib/libc/musl/src/math/i386/asinl.s+12-1
...@@ -1 +1,12 @@...@@ -1 +1,12 @@
1# see asin.s1.global asinl
2.type asinl,@function
3asinl:
4 fldt 4(%esp)
5 fld %st(0)
6 fld1
7 fsub %st(0),%st(1)
8 fadd %st(2)
9 fmulp
10 fsqrt
11 fpatan
12 ret
lib/libc/musl/src/math/i386/atan.s+2
...@@ -8,6 +8,8 @@ atan:...@@ -8,6 +8,8 @@ atan:
8 jb 1f8 jb 1f
9 fld19 fld1
10 fpatan10 fpatan
11 fstpl 4(%esp)
12 fldl 4(%esp)
11 ret13 ret
12 # subnormal x, return x with underflow14 # subnormal x, return x with underflow
131: fsts 4(%esp)151: fsts 4(%esp)
lib/libc/musl/src/math/i386/atan2.s+2-1
...@@ -4,7 +4,8 @@ atan2:...@@ -4,7 +4,8 @@ atan2:
4 fldl 4(%esp)4 fldl 4(%esp)
5 fldl 12(%esp)5 fldl 12(%esp)
6 fpatan6 fpatan
7 fstl 4(%esp)7 fstpl 4(%esp)
8 fldl 4(%esp)
8 mov 8(%esp),%eax9 mov 8(%esp),%eax
9 add %eax,%eax10 add %eax,%eax
10 cmp $0x00200000,%eax11 cmp $0x00200000,%eax
lib/libc/musl/src/math/i386/atan2f.s+2-1
...@@ -4,7 +4,8 @@ atan2f:...@@ -4,7 +4,8 @@ atan2f:
4 flds 4(%esp)4 flds 4(%esp)
5 flds 8(%esp)5 flds 8(%esp)
6 fpatan6 fpatan
7 fsts 4(%esp)7 fstps 4(%esp)
8 flds 4(%esp)
8 mov 4(%esp),%eax9 mov 4(%esp),%eax
9 add %eax,%eax10 add %eax,%eax
10 cmp $0x01000000,%eax11 cmp $0x01000000,%eax
lib/libc/musl/src/math/i386/atanf.s+2
...@@ -8,6 +8,8 @@ atanf:...@@ -8,6 +8,8 @@ atanf:
8 jb 1f8 jb 1f
9 fld19 fld1
10 fpatan10 fpatan
11 fstps 4(%esp)
12 flds 4(%esp)
11 ret13 ret
12 # subnormal x, return x with underflow14 # subnormal x, return x with underflow
131: fld %st(0)151: fld %st(0)
lib/libc/musl/src/math/i386/exp.s deleted-146
...@@ -1,146 +0,0 @@
1.global expm1f
2.type expm1f,@function
3expm1f:
4 flds 4(%esp)
5 mov 4(%esp),%eax
6 add %eax,%eax
7 cmp $0x01000000,%eax
8 jae 1f
9 # subnormal x, return x with underflow
10 fld %st(0)
11 fmul %st(1)
12 fstps 4(%esp)
13 ret
14
15.global expm1l
16.type expm1l,@function
17expm1l:
18 fldt 4(%esp)
19 jmp 1f
20
21.global expm1
22.type expm1,@function
23expm1:
24 fldl 4(%esp)
25 mov 8(%esp),%eax
26 add %eax,%eax
27 cmp $0x00200000,%eax
28 jae 1f
29 # subnormal x, return x with underflow
30 fsts 4(%esp)
31 ret
321: fldl2e
33 fmulp
34 mov $0xc2820000,%eax
35 push %eax
36 flds (%esp)
37 pop %eax
38 fucomp %st(1)
39 fnstsw %ax
40 sahf
41 fld1
42 jb 1f
43 # x*log2e < -65, return -1 without underflow
44 fstp %st(1)
45 fchs
46 ret
471: fld %st(1)
48 fabs
49 fucom %st(1)
50 fnstsw %ax
51 fstp %st(0)
52 fstp %st(0)
53 sahf
54 ja 1f
55 f2xm1
56 ret
571: call 1f
58 fld1
59 fsubrp
60 ret
61
62.global exp2f
63.type exp2f,@function
64exp2f:
65 flds 4(%esp)
66 jmp 1f
67
68.global exp2l
69.global __exp2l
70.hidden __exp2l
71.type exp2l,@function
72exp2l:
73__exp2l:
74 fldt 4(%esp)
75 jmp 1f
76
77.global expf
78.type expf,@function
79expf:
80 flds 4(%esp)
81 jmp 2f
82
83.global exp
84.type exp,@function
85exp:
86 fldl 4(%esp)
872: fldl2e
88 fmulp
89 jmp 1f
90
91.global exp2
92.type exp2,@function
93exp2:
94 fldl 4(%esp)
951: sub $12,%esp
96 fld %st(0)
97 fstpt (%esp)
98 mov 8(%esp),%ax
99 and $0x7fff,%ax
100 cmp $0x3fff+13,%ax
101 jb 4f # |x| < 8192
102 cmp $0x3fff+15,%ax
103 jae 3f # |x| >= 32768
104 fsts (%esp)
105 cmpl $0xc67ff800,(%esp)
106 jb 2f # x > -16382
107 movl $0x5f000000,(%esp)
108 flds (%esp) # 0x1p63
109 fld %st(1)
110 fsub %st(1)
111 faddp
112 fucomp %st(1)
113 fnstsw
114 sahf
115 je 2f # x - 0x1p63 + 0x1p63 == x
116 movl $1,(%esp)
117 flds (%esp) # 0x1p-149
118 fdiv %st(1)
119 fstps (%esp) # raise underflow
1202: fld1
121 fld %st(1)
122 frndint
123 fxch %st(2)
124 fsub %st(2) # st(0)=x-rint(x), st(1)=1, st(2)=rint(x)
125 f2xm1
126 faddp # 2^(x-rint(x))
1271: fscale
128 fstp %st(1)
129 add $12,%esp
130 ret
1313: xor %eax,%eax
1324: cmp $0x3fff-64,%ax
133 fld1
134 jb 1b # |x| < 0x1p-64
135 fstpt (%esp)
136 fistl 8(%esp)
137 fildl 8(%esp)
138 fsubrp %st(1)
139 addl $0x3fff,8(%esp)
140 f2xm1
141 fld1
142 faddp # 2^(x-rint(x))
143 fldt (%esp) # 2^rint(x)
144 fmulp
145 add $12,%esp
146 ret
lib/libc/musl/src/math/i386/exp2.s deleted-1
...@@ -1 +0,0 @@
1# see exp.s
lib/libc/musl/src/math/i386/exp2f.s deleted-1
...@@ -1 +0,0 @@
1# see exp.s
lib/libc/musl/src/math/i386/exp2l.s+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1# see exp.s1# see exp_ld.s
lib/libc/musl/src/math/i386/exp_ld.s created+93
...@@ -0,0 +1,93 @@
1.global expm1l
2.type expm1l,@function
3expm1l:
4 fldt 4(%esp)
5 fldl2e
6 fmulp
7 mov $0xc2820000,%eax
8 push %eax
9 flds (%esp)
10 pop %eax
11 fucomp %st(1)
12 fnstsw %ax
13 sahf
14 fld1
15 jb 1f
16 # x*log2e < -65, return -1 without underflow
17 fstp %st(1)
18 fchs
19 ret
201: fld %st(1)
21 fabs
22 fucom %st(1)
23 fnstsw %ax
24 fstp %st(0)
25 fstp %st(0)
26 sahf
27 ja 1f
28 f2xm1
29 ret
301: call 1f
31 fld1
32 fsubrp
33 ret
34
35.global exp2l
36.global __exp2l
37.hidden __exp2l
38.type exp2l,@function
39exp2l:
40__exp2l:
41 fldt 4(%esp)
421: sub $12,%esp
43 fld %st(0)
44 fstpt (%esp)
45 mov 8(%esp),%ax
46 and $0x7fff,%ax
47 cmp $0x3fff+13,%ax
48 jb 4f # |x| < 8192
49 cmp $0x3fff+15,%ax
50 jae 3f # |x| >= 32768
51 fsts (%esp)
52 cmpl $0xc67ff800,(%esp)
53 jb 2f # x > -16382
54 movl $0x5f000000,(%esp)
55 flds (%esp) # 0x1p63
56 fld %st(1)
57 fsub %st(1)
58 faddp
59 fucomp %st(1)
60 fnstsw
61 sahf
62 je 2f # x - 0x1p63 + 0x1p63 == x
63 movl $1,(%esp)
64 flds (%esp) # 0x1p-149
65 fdiv %st(1)
66 fstps (%esp) # raise underflow
672: fld1
68 fld %st(1)
69 frndint
70 fxch %st(2)
71 fsub %st(2) # st(0)=x-rint(x), st(1)=1, st(2)=rint(x)
72 f2xm1
73 faddp # 2^(x-rint(x))
741: fscale
75 fstp %st(1)
76 add $12,%esp
77 ret
783: xor %eax,%eax
794: cmp $0x3fff-64,%ax
80 fld1
81 jb 1b # |x| < 0x1p-64
82 fstpt (%esp)
83 fistl 8(%esp)
84 fildl 8(%esp)
85 fsubrp %st(1)
86 addl $0x3fff,8(%esp)
87 f2xm1
88 fld1
89 faddp # 2^(x-rint(x))
90 fldt (%esp) # 2^rint(x)
91 fmulp
92 add $12,%esp
93 ret
lib/libc/musl/src/math/i386/expf.s deleted-1
...@@ -1 +0,0 @@
1# see exp.s
lib/libc/musl/src/math/i386/expm1.s deleted-1
...@@ -1 +0,0 @@
1# see exp.s
lib/libc/musl/src/math/i386/expm1f.s deleted-1
...@@ -1 +0,0 @@
1# see exp.s
lib/libc/musl/src/math/i386/expm1l.s+1-1
...@@ -1 +1 @@...@@ -1 +1 @@
1# see exp.s1# see exp_ld.s
lib/libc/musl/src/math/i386/log.s+2
...@@ -4,4 +4,6 @@ log:...@@ -4,4 +4,6 @@ log:
4 fldln24 fldln2
5 fldl 4(%esp)5 fldl 4(%esp)
6 fyl2x6 fyl2x
7 fstpl 4(%esp)
8 fldl 4(%esp)
7 ret9 ret
lib/libc/musl/src/math/i386/log10.s+2
...@@ -4,4 +4,6 @@ log10:...@@ -4,4 +4,6 @@ log10:
4 fldlg24 fldlg2
5 fldl 4(%esp)5 fldl 4(%esp)
6 fyl2x6 fyl2x
7 fstpl 4(%esp)
8 fldl 4(%esp)
7 ret9 ret
lib/libc/musl/src/math/i386/log10f.s+2
...@@ -4,4 +4,6 @@ log10f:...@@ -4,4 +4,6 @@ log10f:
4 fldlg24 fldlg2
5 flds 4(%esp)5 flds 4(%esp)
6 fyl2x6 fyl2x
7 fstps 4(%esp)
8 flds 4(%esp)
7 ret9 ret
lib/libc/musl/src/math/i386/log1p.s+4
...@@ -10,10 +10,14 @@ log1p:...@@ -10,10 +10,14 @@ log1p:
10 cmp $0x00100000,%eax10 cmp $0x00100000,%eax
11 jb 2f11 jb 2f
12 fyl2xp112 fyl2xp1
13 fstpl 4(%esp)
14 fldl 4(%esp)
13 ret15 ret
141: fld1161: fld1
15 faddp17 faddp
16 fyl2x18 fyl2x
19 fstpl 4(%esp)
20 fldl 4(%esp)
17 ret21 ret
18 # subnormal x, return x with underflow22 # subnormal x, return x with underflow
192: fsts 4(%esp)232: fsts 4(%esp)
lib/libc/musl/src/math/i386/log1pf.s+4
...@@ -10,10 +10,14 @@ log1pf:...@@ -10,10 +10,14 @@ log1pf:
10 cmp $0x00800000,%eax10 cmp $0x00800000,%eax
11 jb 2f11 jb 2f
12 fyl2xp112 fyl2xp1
13 fstps 4(%esp)
14 flds 4(%esp)
13 ret15 ret
141: fld1161: fld1
15 faddp17 faddp
16 fyl2x18 fyl2x
19 fstps 4(%esp)
20 flds 4(%esp)
17 ret21 ret
18 # subnormal x, return x with underflow22 # subnormal x, return x with underflow
192: fxch232: fxch
lib/libc/musl/src/math/i386/log2.s+2
...@@ -4,4 +4,6 @@ log2:...@@ -4,4 +4,6 @@ log2:
4 fld14 fld1
5 fldl 4(%esp)5 fldl 4(%esp)
6 fyl2x6 fyl2x
7 fstpl 4(%esp)
8 fldl 4(%esp)
7 ret9 ret
lib/libc/musl/src/math/i386/log2f.s+2
...@@ -4,4 +4,6 @@ log2f:...@@ -4,4 +4,6 @@ log2f:
4 fld14 fld1
5 flds 4(%esp)5 flds 4(%esp)
6 fyl2x6 fyl2x
7 fstps 4(%esp)
8 flds 4(%esp)
7 ret9 ret
lib/libc/musl/src/math/i386/logf.s+2
...@@ -4,4 +4,6 @@ logf:...@@ -4,4 +4,6 @@ logf:
4 fldln24 fldln2
5 flds 4(%esp)5 flds 4(%esp)
6 fyl2x6 fyl2x
7 fstps 4(%esp)
8 flds 4(%esp)
7 ret9 ret
lib/libc/musl/src/math/mips/fabs.c created+16
...@@ -0,0 +1,16 @@
1#if !defined(__mips_soft_float) && defined(__mips_abs2008)
2
3#include <math.h>
4
5double fabs(double x)
6{
7 double r;
8 __asm__("abs.d %0,%1" : "=f"(r) : "f"(x));
9 return r;
10}
11
12#else
13
14#include "../fabs.c"
15
16#endif
lib/libc/musl/src/math/mips/fabsf.c created+16
...@@ -0,0 +1,16 @@
1#if !defined(__mips_soft_float) && defined(__mips_abs2008)
2
3#include <math.h>
4
5float fabsf(float x)
6{
7 float r;
8 __asm__("abs.s %0,%1" : "=f"(r) : "f"(x));
9 return r;
10}
11
12#else
13
14#include "../fabsf.c"
15
16#endif
lib/libc/musl/src/math/mips/sqrt.c created+16
...@@ -0,0 +1,16 @@
1#if !defined(__mips_soft_float) && __mips >= 3
2
3#include <math.h>
4
5double sqrt(double x)
6{
7 double r;
8 __asm__("sqrt.d %0,%1" : "=f"(r) : "f"(x));
9 return r;
10}
11
12#else
13
14#include "../sqrt.c"
15
16#endif
lib/libc/musl/src/math/mips/sqrtf.c created+16
...@@ -0,0 +1,16 @@
1#if !defined(__mips_soft_float) && __mips >= 2
2
3#include <math.h>
4
5float sqrtf(float x)
6{
7 float r;
8 __asm__("sqrt.s %0,%1" : "=f"(r) : "f"(x));
9 return r;
10}
11
12#else
13
14#include "../sqrtf.c"
15
16#endif
lib/libc/musl/src/math/powerpc/fabs.c+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1#include <math.h>1#include <math.h>
22
3#ifdef _SOFT_FLOAT3#if defined(_SOFT_FLOAT) || defined(BROKEN_PPC_D_ASM)
44
5#include "../fabs.c"5#include "../fabs.c"
66
lib/libc/musl/src/math/powerpc/fma.c+1-1
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1#include <math.h>1#include <math.h>
22
3#ifdef _SOFT_FLOAT3#if defined(_SOFT_FLOAT) || defined(BROKEN_PPC_D_ASM)
44
5#include "../fma.c"5#include "../fma.c"
66
lib/libc/musl/src/math/x32/lrintl.s+2-2
...@@ -2,6 +2,6 @@...@@ -2,6 +2,6 @@
2.type lrintl,@function2.type lrintl,@function
3lrintl:3lrintl:
4 fldt 8(%esp)4 fldt 8(%esp)
5 fistpll 8(%esp)5 fistpl 8(%esp)
6 mov 8(%esp),%rax6 movl 8(%esp),%eax
7 ret7 ret
lib/libc/musl/src/misc/getrusage.c+29-1
...@@ -1,7 +1,35 @@...@@ -1,7 +1,35 @@
1#include <sys/resource.h>1#include <sys/resource.h>
2#include <string.h>
3#include <errno.h>
2#include "syscall.h"4#include "syscall.h"
35
4int getrusage(int who, struct rusage *ru)6int getrusage(int who, struct rusage *ru)
5{7{
6 return syscall(SYS_getrusage, who, ru);8 int r;
9#ifdef SYS_getrusage_time64
10 long long kru64[18];
11 r = __syscall(SYS_getrusage_time64, who, kru64);
12 if (!r) {
13 ru->ru_utime = (struct timeval)
14 { .tv_sec = kru64[0], .tv_usec = kru64[1] };
15 ru->ru_stime = (struct timeval)
16 { .tv_sec = kru64[2], .tv_usec = kru64[3] };
17 char *slots = (char *)&ru->ru_maxrss;
18 for (int i=0; i<14; i++)
19 *(long *)(slots + i*sizeof(long)) = kru64[4+i];
20 }
21 if (SYS_getrusage_time64 == SYS_getrusage || r != -ENOSYS)
22 return __syscall_ret(r);
23#endif
24 char *dest = (char *)&ru->ru_maxrss - 4*sizeof(long);
25 r = __syscall(SYS_getrusage, who, dest);
26 if (!r && sizeof(time_t) > sizeof(long)) {
27 long kru[4];
28 memcpy(kru, dest, 4*sizeof(long));
29 ru->ru_utime = (struct timeval)
30 { .tv_sec = kru[0], .tv_usec = kru[1] };
31 ru->ru_stime = (struct timeval)
32 { .tv_sec = kru[2], .tv_usec = kru[3] };
33 }
34 return __syscall_ret(r);
7}35}
lib/libc/musl/src/misc/ioctl.c+119-17
...@@ -3,8 +3,115 @@...@@ -3,8 +3,115 @@
3#include <errno.h>3#include <errno.h>
4#include <time.h>4#include <time.h>
5#include <sys/time.h>5#include <sys/time.h>
6#include <stddef.h>
7#include <string.h>
6#include "syscall.h"8#include "syscall.h"
79
10#define alignof(t) offsetof(struct { char c; t x; }, x)
11
12#define W 1
13#define R 2
14#define WR 3
15
16struct ioctl_compat_map {
17 int new_req, old_req;
18 unsigned char old_size, dir, force_align, noffs;
19 unsigned char offsets[8];
20};
21
22#define NINTH(a,b,c,d,e,f,g,h,i,...) i
23#define COUNT(...) NINTH(__VA_ARGS__,8,7,6,5,4,3,2,1,0)
24#define OFFS(...) COUNT(__VA_ARGS__), { __VA_ARGS__ }
25
26/* yields a type for a struct with original size n, with a misaligned
27 * timeval/timespec expanded from 32- to 64-bit. for use with ioctl
28 * number producing macros; only size of result is meaningful. */
29#define new_misaligned(n) struct { int i; time_t t; char c[(n)-4]; }
30
31static const struct ioctl_compat_map compat_map[] = {
32 { SIOCGSTAMP, SIOCGSTAMP_OLD, 8, R, 0, OFFS(0, 4) },
33 { SIOCGSTAMPNS, SIOCGSTAMPNS_OLD, 8, R, 0, OFFS(0, 4) },
34
35 /* SNDRV_TIMER_IOCTL_STATUS */
36 { _IOR('T', 0x14, char[96]), _IOR('T', 0x14, 88), 88, R, 0, OFFS(0,4) },
37
38 /* SNDRV_PCM_IOCTL_STATUS[_EXT] */
39 { _IOR('A', 0x20, char[128]), _IOR('A', 0x20, char[108]), 108, R, 1, OFFS(4,8,12,16,52,56,60,64) },
40 { _IOWR('A', 0x24, char[128]), _IOWR('A', 0x24, char[108]), 108, WR, 1, OFFS(4,8,12,16,52,56,60,64) },
41
42 /* SNDRV_RAWMIDI_IOCTL_STATUS */
43 { _IOWR('W', 0x20, char[48]), _IOWR('W', 0x20, char[36]), 36, WR, 1, OFFS(4,8) },
44
45 /* SNDRV_PCM_IOCTL_SYNC_PTR - with 3 subtables */
46 { _IOWR('A', 0x23, char[136]), _IOWR('A', 0x23, char[132]), 0, WR, 1, 0 },
47 { 0, 0, 4, WR, 1, 0 }, /* snd_pcm_sync_ptr (flags only) */
48 { 0, 0, 32, WR, 1, OFFS(8,12,16,24,28) }, /* snd_pcm_mmap_status */
49 { 0, 0, 8, WR, 1, OFFS(0,4) }, /* snd_pcm_mmap_control */
50
51 /* VIDIOC_QUERYBUF, VIDIOC_QBUF, VIDIOC_DQBUF, VIDIOC_PREPARE_BUF */
52 { _IOWR('V', 9, new_misaligned(72)), _IOWR('V', 9, char[72]), 72, WR, 0, OFFS(20) },
53 { _IOWR('V', 15, new_misaligned(72)), _IOWR('V', 15, char[72]), 72, WR, 0, OFFS(20) },
54 { _IOWR('V', 17, new_misaligned(72)), _IOWR('V', 17, char[72]), 72, WR, 0, OFFS(20) },
55 { _IOWR('V', 93, new_misaligned(72)), _IOWR('V', 93, char[72]), 72, WR, 0, OFFS(20) },
56
57 /* VIDIOC_DQEVENT */
58 { _IOR('V', 89, new_misaligned(96)), _IOR('V', 89, char[96]), 96, R, 0, OFFS(76,80) },
59
60 /* VIDIOC_OMAP3ISP_STAT_REQ */
61 { _IOWR('V', 192+6, char[32]), _IOWR('V', 192+6, char[24]), 22, WR, 0, OFFS(0,4) },
62
63 /* PPPIOCGIDLE */
64 { _IOR('t', 63, char[16]), _IOR('t', 63, char[8]), 8, R, 0, OFFS(0,4) },
65
66 /* PPGETTIME, PPSETTIME */
67 { _IOR('p', 0x95, char[16]), _IOR('p', 0x95, char[8]), 8, R, 0, OFFS(0,4) },
68 { _IOW('p', 0x96, char[16]), _IOW('p', 0x96, char[8]), 8, W, 0, OFFS(0,4) },
69
70 /* LPSETTIMEOUT */
71 { _IOW(0x6, 0xf, char[16]), 0x060f, 8, W, 0, OFFS(0,4) },
72};
73
74static void convert_ioctl_struct(const struct ioctl_compat_map *map, char *old, char *new, int dir)
75{
76 int new_offset = 0;
77 int old_offset = 0;
78 int old_size = map->old_size;
79 if (!(dir & map->dir)) return;
80 if (!map->old_size) {
81 /* offsets hard-coded for SNDRV_PCM_IOCTL_SYNC_PTR;
82 * if another exception appears this needs changing. */
83 convert_ioctl_struct(map+1, old, new, dir);
84 convert_ioctl_struct(map+2, old+4, new+8, dir);
85 convert_ioctl_struct(map+3, old+68, new+72, dir);
86 return;
87 }
88 for (int i=0; i < map->noffs; i++) {
89 int ts_offset = map->offsets[i];
90 int len = ts_offset-old_offset;
91 if (dir==W) memcpy(old+old_offset, new+new_offset, len);
92 else memcpy(new+new_offset, old+old_offset, len);
93 new_offset += len;
94 old_offset += len;
95 long long new_ts;
96 long old_ts;
97 int align = map->force_align ? sizeof(time_t) : alignof(time_t);
98 new_offset += (align-1) & -new_offset;
99 if (dir==W) {
100 memcpy(&new_ts, new+new_offset, sizeof new_ts);
101 old_ts = new_ts;
102 memcpy(old+old_offset, &old_ts, sizeof old_ts);
103 } else {
104 memcpy(&old_ts, old+old_offset, sizeof old_ts);
105 new_ts = old_ts;
106 memcpy(new+new_offset, &new_ts, sizeof new_ts);
107 }
108 new_offset += sizeof new_ts;
109 old_offset += sizeof old_ts;
110 }
111 if (dir==W) memcpy(old+old_offset, new+new_offset, old_size-old_offset);
112 else memcpy(new+new_offset, old+old_offset, old_size-old_offset);
113}
114
8int ioctl(int fd, int req, ...)115int ioctl(int fd, int req, ...)
9{116{
10 void *arg;117 void *arg;
...@@ -13,23 +120,18 @@ int ioctl(int fd, int req, ...)...@@ -13,23 +120,18 @@ int ioctl(int fd, int req, ...)
13 arg = va_arg(ap, void *);120 arg = va_arg(ap, void *);
14 va_end(ap);121 va_end(ap);
15 int r = __syscall(SYS_ioctl, fd, req, arg);122 int r = __syscall(SYS_ioctl, fd, req, arg);
16 if (r==-ENOTTY) switch (req) {123 if (SIOCGSTAMP != SIOCGSTAMP_OLD && req && r==-ENOTTY) {
17 case SIOCGSTAMP:124 for (int i=0; i<sizeof compat_map/sizeof *compat_map; i++) {
18 case SIOCGSTAMPNS:125 if (compat_map[i].new_req != req) continue;
19 if (SIOCGSTAMP==SIOCGSTAMP_OLD) break;126 union {
20 if (req==SIOCGSTAMP) req=SIOCGSTAMP_OLD;127 long long align;
21 if (req==SIOCGSTAMPNS) req=SIOCGSTAMPNS_OLD;128 char buf[256];
22 long t32[2];129 } u;
23 r = __syscall(SYS_ioctl, fd, req, t32);130 convert_ioctl_struct(&compat_map[i], u.buf, arg, W);
24 if (r<0) break;131 r = __syscall(SYS_ioctl, fd, compat_map[i].old_req, u.buf);
25 if (req==SIOCGSTAMP_OLD) {132 if (r<0) break;
26 struct timeval *tv = arg;133 convert_ioctl_struct(&compat_map[i], u.buf, arg, R);
27 tv->tv_sec = t32[0];134 break;
28 tv->tv_usec = t32[1];
29 } else {
30 struct timespec *ts = arg;
31 ts->tv_sec = t32[0];
32 ts->tv_nsec = t32[1];
33 }135 }
34 }136 }
35 return __syscall_ret(r);137 return __syscall_ret(r);
lib/libc/musl/src/misc/pty.c+3-1
...@@ -7,7 +7,9 @@...@@ -7,7 +7,9 @@
77
8int posix_openpt(int flags)8int posix_openpt(int flags)
9{9{
10 return open("/dev/ptmx", flags);10 int r = open("/dev/ptmx", flags);
11 if (r < 0 && errno == ENOSPC) errno = EAGAIN;
12 return r;
11}13}
1214
13int grantpt(int fd)15int grantpt(int fd)
lib/libc/musl/src/network/getsockopt.c+9
...@@ -26,6 +26,15 @@ int getsockopt(int fd, int level, int optname, void *restrict optval, socklen_t...@@ -26,6 +26,15 @@ int getsockopt(int fd, int level, int optname, void *restrict optval, socklen_t
26 tv->tv_sec = tv32[0];26 tv->tv_sec = tv32[0];
27 tv->tv_usec = tv32[1];27 tv->tv_usec = tv32[1];
28 *optlen = sizeof *tv;28 *optlen = sizeof *tv;
29 break;
30 case SO_TIMESTAMP:
31 case SO_TIMESTAMPNS:
32 if (SO_TIMESTAMP == SO_TIMESTAMP_OLD) break;
33 if (optname==SO_TIMESTAMP) optname=SO_TIMESTAMP_OLD;
34 if (optname==SO_TIMESTAMPNS) optname=SO_TIMESTAMPNS_OLD;
35 r = __socketcall(getsockopt, fd, level,
36 optname, optval, optlen, 0);
37 break;
29 }38 }
30 }39 }
31 return __syscall_ret(r);40 return __syscall_ret(r);
lib/libc/musl/src/network/recvmmsg.c+10-4
...@@ -8,6 +8,8 @@...@@ -8,6 +8,8 @@
8#define IS32BIT(x) !((x)+0x80000000ULL>>32)8#define IS32BIT(x) !((x)+0x80000000ULL>>32)
9#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))9#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))
1010
11hidden void __convert_scm_timestamps(struct msghdr *, socklen_t);
12
11int recvmmsg(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags, struct timespec *timeout)13int recvmmsg(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags, struct timespec *timeout)
12{14{
13#if LONG_MAX > INT_MAX15#if LONG_MAX > INT_MAX
...@@ -19,14 +21,18 @@ int recvmmsg(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int fla...@@ -19,14 +21,18 @@ int recvmmsg(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int fla
19#ifdef SYS_recvmmsg_time6421#ifdef SYS_recvmmsg_time64
20 time_t s = timeout ? timeout->tv_sec : 0;22 time_t s = timeout ? timeout->tv_sec : 0;
21 long ns = timeout ? timeout->tv_nsec : 0;23 long ns = timeout ? timeout->tv_nsec : 0;
22 int r = -ENOSYS;24 int r = __syscall_cp(SYS_recvmmsg_time64, fd, msgvec, vlen, flags,
23 if (SYS_recvmmsg == SYS_recvmmsg_time64 || !IS32BIT(s))
24 r = __syscall_cp(SYS_recvmmsg_time64, fd, msgvec, vlen, flags,
25 timeout ? ((long long[]){s, ns}) : 0);25 timeout ? ((long long[]){s, ns}) : 0);
26 if (SYS_recvmmsg == SYS_recvmmsg_time64 || r!=-ENOSYS)26 if (SYS_recvmmsg == SYS_recvmmsg_time64 || r!=-ENOSYS)
27 return __syscall_ret(r);27 return __syscall_ret(r);
28 return syscall_cp(SYS_recvmmsg, fd, msgvec, vlen, flags,28 if (vlen > IOV_MAX) vlen = IOV_MAX;
29 socklen_t csize[vlen];
30 for (int i=0; i<vlen; i++) csize[i] = msgvec[i].msg_hdr.msg_controllen;
31 r = __syscall_cp(SYS_recvmmsg, fd, msgvec, vlen, flags,
29 timeout ? ((long[]){CLAMP(s), ns}) : 0);32 timeout ? ((long[]){CLAMP(s), ns}) : 0);
33 for (int i=0; i<r; i++)
34 __convert_scm_timestamps(&msgvec[i].msg_hdr, csize[i]);
35 return __syscall_ret(r);
30#else36#else
31 return syscall_cp(SYS_recvmmsg, fd, msgvec, vlen, flags, timeout);37 return syscall_cp(SYS_recvmmsg, fd, msgvec, vlen, flags, timeout);
32#endif38#endif
lib/libc/musl/src/network/recvmsg.c+47
...@@ -1,10 +1,56 @@...@@ -1,10 +1,56 @@
1#include <sys/socket.h>1#include <sys/socket.h>
2#include <limits.h>2#include <limits.h>
3#include <time.h>
4#include <sys/time.h>
5#include <string.h>
3#include "syscall.h"6#include "syscall.h"
47
8hidden void __convert_scm_timestamps(struct msghdr *, socklen_t);
9
10void __convert_scm_timestamps(struct msghdr *msg, socklen_t csize)
11{
12 if (SCM_TIMESTAMP == SCM_TIMESTAMP_OLD) return;
13 if (!msg->msg_control || !msg->msg_controllen) return;
14
15 struct cmsghdr *cmsg, *last=0;
16 long tmp;
17 long long tvts[2];
18 int type = 0;
19
20 for (cmsg=CMSG_FIRSTHDR(msg); cmsg; cmsg=CMSG_NXTHDR(msg, cmsg)) {
21 if (cmsg->cmsg_level==SOL_SOCKET) switch (cmsg->cmsg_type) {
22 case SCM_TIMESTAMP_OLD:
23 if (type) break;
24 type = SCM_TIMESTAMP;
25 goto common;
26 case SCM_TIMESTAMPNS_OLD:
27 type = SCM_TIMESTAMPNS;
28 common:
29 memcpy(&tmp, CMSG_DATA(cmsg), sizeof tmp);
30 tvts[0] = tmp;
31 memcpy(&tmp, CMSG_DATA(cmsg) + sizeof tmp, sizeof tmp);
32 tvts[1] = tmp;
33 break;
34 }
35 last = cmsg;
36 }
37 if (!last || !type) return;
38 if (CMSG_SPACE(sizeof tvts) > csize-msg->msg_controllen) {
39 msg->msg_flags |= MSG_CTRUNC;
40 return;
41 }
42 msg->msg_controllen += CMSG_SPACE(sizeof tvts);
43 cmsg = CMSG_NXTHDR(msg, last);
44 cmsg->cmsg_level = SOL_SOCKET;
45 cmsg->cmsg_type = type;
46 cmsg->cmsg_len = CMSG_LEN(sizeof tvts);
47 memcpy(CMSG_DATA(cmsg), &tvts, sizeof tvts);
48}
49
5ssize_t recvmsg(int fd, struct msghdr *msg, int flags)50ssize_t recvmsg(int fd, struct msghdr *msg, int flags)
6{51{
7 ssize_t r;52 ssize_t r;
53 socklen_t orig_controllen = msg->msg_controllen;
8#if LONG_MAX > INT_MAX54#if LONG_MAX > INT_MAX
9 struct msghdr h, *orig = msg;55 struct msghdr h, *orig = msg;
10 if (msg) {56 if (msg) {
...@@ -14,6 +60,7 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags)...@@ -14,6 +60,7 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags)
14 }60 }
15#endif61#endif
16 r = socketcall_cp(recvmsg, fd, msg, flags, 0, 0, 0);62 r = socketcall_cp(recvmsg, fd, msg, flags, 0, 0, 0);
63 if (r >= 0) __convert_scm_timestamps(msg, orig_controllen);
17#if LONG_MAX > INT_MAX64#if LONG_MAX > INT_MAX
18 if (orig) *orig = h;65 if (orig) *orig = h;
19#endif66#endif
lib/libc/musl/src/network/setsockopt.c+9
...@@ -31,6 +31,15 @@ int setsockopt(int fd, int level, int optname, const void *optval, socklen_t opt...@@ -31,6 +31,15 @@ int setsockopt(int fd, int level, int optname, const void *optval, socklen_t opt
3131
32 r = __socketcall(setsockopt, fd, level, optname,32 r = __socketcall(setsockopt, fd, level, optname,
33 ((long[]){s, CLAMP(us)}), 2*sizeof(long), 0);33 ((long[]){s, CLAMP(us)}), 2*sizeof(long), 0);
34 break;
35 case SO_TIMESTAMP:
36 case SO_TIMESTAMPNS:
37 if (SO_TIMESTAMP == SO_TIMESTAMP_OLD) break;
38 if (optname==SO_TIMESTAMP) optname=SO_TIMESTAMP_OLD;
39 if (optname==SO_TIMESTAMPNS) optname=SO_TIMESTAMPNS_OLD;
40 r = __socketcall(setsockopt, fd, level,
41 optname, optval, optlen, 0);
42 break;
34 }43 }
35 }44 }
36 return __syscall_ret(r);45 return __syscall_ret(r);
lib/libc/musl/src/signal/arm/sigsetjmp.s+3-2
...@@ -6,9 +6,10 @@...@@ -6,9 +6,10 @@
6sigsetjmp:6sigsetjmp:
7__sigsetjmp:7__sigsetjmp:
8 tst r1,r18 tst r1,r1
9 beq setjmp9 bne 1f
10 b setjmp
1011
11 str lr,[r0,#256]121: str lr,[r0,#256]
12 str r4,[r0,#260+8]13 str r4,[r0,#260+8]
13 mov r4,r014 mov r4,r0
1415
lib/libc/musl/src/stat/__xstat.c+4
...@@ -1,5 +1,7 @@...@@ -1,5 +1,7 @@
1#include <sys/stat.h>1#include <sys/stat.h>
22
3#if !_REDIR_TIME64
4
3int __fxstat(int ver, int fd, struct stat *buf)5int __fxstat(int ver, int fd, struct stat *buf)
4{6{
5 return fstat(fd, buf);7 return fstat(fd, buf);
...@@ -25,6 +27,8 @@ weak_alias(__fxstatat, __fxstatat64);...@@ -25,6 +27,8 @@ weak_alias(__fxstatat, __fxstatat64);
25weak_alias(__lxstat, __lxstat64);27weak_alias(__lxstat, __lxstat64);
26weak_alias(__xstat, __xstat64);28weak_alias(__xstat, __xstat64);
2729
30#endif
31
28int __xmknod(int ver, const char *path, mode_t mode, dev_t *dev)32int __xmknod(int ver, const char *path, mode_t mode, dev_t *dev)
29{33{
30 return mknod(path, mode, *dev);34 return mknod(path, mode, *dev);
lib/libc/musl/src/stat/fchmodat.c+2-1
...@@ -2,6 +2,7 @@...@@ -2,6 +2,7 @@
2#include <fcntl.h>2#include <fcntl.h>
3#include <errno.h>3#include <errno.h>
4#include "syscall.h"4#include "syscall.h"
5#include "kstat.h"
56
6int fchmodat(int fd, const char *path, mode_t mode, int flag)7int fchmodat(int fd, const char *path, mode_t mode, int flag)
7{8{
...@@ -10,7 +11,7 @@ int fchmodat(int fd, const char *path, mode_t mode, int flag)...@@ -10,7 +11,7 @@ int fchmodat(int fd, const char *path, mode_t mode, int flag)
10 if (flag != AT_SYMLINK_NOFOLLOW)11 if (flag != AT_SYMLINK_NOFOLLOW)
11 return __syscall_ret(-EINVAL);12 return __syscall_ret(-EINVAL);
1213
13 struct stat st;14 struct kstat st;
14 int ret, fd2;15 int ret, fd2;
15 char proc[15+3*sizeof(int)];16 char proc[15+3*sizeof(int)];
1617
lib/libc/musl/src/stat/fstat.c+2
...@@ -10,4 +10,6 @@ int fstat(int fd, struct stat *st)...@@ -10,4 +10,6 @@ int fstat(int fd, struct stat *st)
10 return fstatat(fd, "", st, AT_EMPTY_PATH);10 return fstatat(fd, "", st, AT_EMPTY_PATH);
11}11}
1212
13#if !_REDIR_TIME64
13weak_alias(fstat, fstat64);14weak_alias(fstat, fstat64);
15#endif
lib/libc/musl/src/stat/fstatat.c+18
...@@ -57,6 +57,14 @@ static int fstatat_statx(int fd, const char *restrict path, struct stat *restric...@@ -57,6 +57,14 @@ static int fstatat_statx(int fd, const char *restrict path, struct stat *restric
57 .st_mtim.tv_nsec = stx.stx_mtime.tv_nsec,57 .st_mtim.tv_nsec = stx.stx_mtime.tv_nsec,
58 .st_ctim.tv_sec = stx.stx_ctime.tv_sec,58 .st_ctim.tv_sec = stx.stx_ctime.tv_sec,
59 .st_ctim.tv_nsec = stx.stx_ctime.tv_nsec,59 .st_ctim.tv_nsec = stx.stx_ctime.tv_nsec,
60#if _REDIR_TIME64
61 .__st_atim32.tv_sec = stx.stx_atime.tv_sec,
62 .__st_atim32.tv_nsec = stx.stx_atime.tv_nsec,
63 .__st_mtim32.tv_sec = stx.stx_mtime.tv_sec,
64 .__st_mtim32.tv_nsec = stx.stx_mtime.tv_nsec,
65 .__st_ctim32.tv_sec = stx.stx_ctime.tv_sec,
66 .__st_ctim32.tv_nsec = stx.stx_ctime.tv_nsec,
67#endif
60 };68 };
61 return 0;69 return 0;
62}70}
...@@ -110,6 +118,14 @@ static int fstatat_kstat(int fd, const char *restrict path, struct stat *restric...@@ -110,6 +118,14 @@ static int fstatat_kstat(int fd, const char *restrict path, struct stat *restric
110 .st_mtim.tv_nsec = kst.st_mtime_nsec,118 .st_mtim.tv_nsec = kst.st_mtime_nsec,
111 .st_ctim.tv_sec = kst.st_ctime_sec,119 .st_ctim.tv_sec = kst.st_ctime_sec,
112 .st_ctim.tv_nsec = kst.st_ctime_nsec,120 .st_ctim.tv_nsec = kst.st_ctime_nsec,
121#if _REDIR_TIME64
122 .__st_atim32.tv_sec = kst.st_atime_sec,
123 .__st_atim32.tv_nsec = kst.st_atime_nsec,
124 .__st_mtim32.tv_sec = kst.st_mtime_sec,
125 .__st_mtim32.tv_nsec = kst.st_mtime_nsec,
126 .__st_ctim32.tv_sec = kst.st_ctime_sec,
127 .__st_ctim32.tv_nsec = kst.st_ctime_nsec,
128#endif
113 };129 };
114130
115 return 0;131 return 0;
...@@ -126,4 +142,6 @@ int fstatat(int fd, const char *restrict path, struct stat *restrict st, int fla...@@ -126,4 +142,6 @@ int fstatat(int fd, const char *restrict path, struct stat *restrict st, int fla
126 return __syscall_ret(ret);142 return __syscall_ret(ret);
127}143}
128144
145#if !_REDIR_TIME64
129weak_alias(fstatat, fstatat64);146weak_alias(fstatat, fstatat64);
147#endif
lib/libc/musl/src/stat/lstat.c+2
...@@ -6,4 +6,6 @@ int lstat(const char *restrict path, struct stat *restrict buf)...@@ -6,4 +6,6 @@ int lstat(const char *restrict path, struct stat *restrict buf)
6 return fstatat(AT_FDCWD, path, buf, AT_SYMLINK_NOFOLLOW);6 return fstatat(AT_FDCWD, path, buf, AT_SYMLINK_NOFOLLOW);
7}7}
88
9#if !_REDIR_TIME64
9weak_alias(lstat, lstat64);10weak_alias(lstat, lstat64);
11#endif
lib/libc/musl/src/stat/stat.c+2
...@@ -6,4 +6,6 @@ int stat(const char *restrict path, struct stat *restrict buf)...@@ -6,4 +6,6 @@ int stat(const char *restrict path, struct stat *restrict buf)
6 return fstatat(AT_FDCWD, path, buf, 0);6 return fstatat(AT_FDCWD, path, buf, 0);
7}7}
88
9#if !_REDIR_TIME64
9weak_alias(stat, stat64);10weak_alias(stat, stat64);
11#endif
lib/libc/musl/src/stdio/tempnam.c+3-2
...@@ -6,6 +6,7 @@...@@ -6,6 +6,7 @@
6#include <string.h>6#include <string.h>
7#include <stdlib.h>7#include <stdlib.h>
8#include "syscall.h"8#include "syscall.h"
9#include "kstat.h"
910
10#define MAXTRIES 10011#define MAXTRIES 100
1112
...@@ -37,10 +38,10 @@ char *tempnam(const char *dir, const char *pfx)...@@ -37,10 +38,10 @@ char *tempnam(const char *dir, const char *pfx)
37 for (try=0; try<MAXTRIES; try++) {38 for (try=0; try<MAXTRIES; try++) {
38 __randname(s+l-6);39 __randname(s+l-6);
39#ifdef SYS_lstat40#ifdef SYS_lstat
40 r = __syscall(SYS_lstat, s, &(struct stat){0});41 r = __syscall(SYS_lstat, s, &(struct kstat){0});
41#else42#else
42 r = __syscall(SYS_fstatat, AT_FDCWD, s,43 r = __syscall(SYS_fstatat, AT_FDCWD, s,
43 &(struct stat){0}, AT_SYMLINK_NOFOLLOW);44 &(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
44#endif45#endif
45 if (r == -ENOENT) return strdup(s);46 if (r == -ENOENT) return strdup(s);
46 }47 }
lib/libc/musl/src/stdio/tmpnam.c+3-2
...@@ -5,6 +5,7 @@...@@ -5,6 +5,7 @@
5#include <string.h>5#include <string.h>
6#include <stdlib.h>6#include <stdlib.h>
7#include "syscall.h"7#include "syscall.h"
8#include "kstat.h"
89
9#define MAXTRIES 10010#define MAXTRIES 100
1011
...@@ -17,10 +18,10 @@ char *tmpnam(char *buf)...@@ -17,10 +18,10 @@ char *tmpnam(char *buf)
17 for (try=0; try<MAXTRIES; try++) {18 for (try=0; try<MAXTRIES; try++) {
18 __randname(s+12);19 __randname(s+12);
19#ifdef SYS_lstat20#ifdef SYS_lstat
20 r = __syscall(SYS_lstat, s, &(struct stat){0});21 r = __syscall(SYS_lstat, s, &(struct kstat){0});
21#else22#else
22 r = __syscall(SYS_fstatat, AT_FDCWD, s,23 r = __syscall(SYS_fstatat, AT_FDCWD, s,
23 &(struct stat){0}, AT_SYMLINK_NOFOLLOW);24 &(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
24#endif25#endif
25 if (r == -ENOENT) return strcpy(buf ? buf : internal, s);26 if (r == -ENOENT) return strcpy(buf ? buf : internal, s);
26 }27 }
lib/libc/musl/src/stdio/ungetc.c+1-1
...@@ -16,5 +16,5 @@ int ungetc(int c, FILE *f)...@@ -16,5 +16,5 @@ int ungetc(int c, FILE *f)
16 f->flags &= ~F_EOF;16 f->flags &= ~F_EOF;
1717
18 FUNLOCK(f);18 FUNLOCK(f);
19 return c;19 return (unsigned char)c;
20}20}
lib/libc/musl/src/string/arm/memcpy.c+1-1
...@@ -1,3 +1,3 @@...@@ -1,3 +1,3 @@
1#if __ARMEB__ || __thumb__1#if __ARMEB__
2#include "../memcpy.c"2#include "../memcpy.c"
3#endif3#endif
lib/libc/musl/src/string/arm/memcpy_le.S+8-5
...@@ -1,4 +1,4 @@...@@ -1,4 +1,4 @@
1#if !__ARMEB__ && !__thumb__1#if !__ARMEB__
22
3/*3/*
4 * Copyright (C) 2008 The Android Open Source Project4 * Copyright (C) 2008 The Android Open Source Project
...@@ -40,8 +40,9 @@...@@ -40,8 +40,9 @@
40 * This file has been modified from the original for use in musl libc.40 * This file has been modified from the original for use in musl libc.
41 * The main changes are: addition of .type memcpy,%function to make the41 * The main changes are: addition of .type memcpy,%function to make the
42 * code safely callable from thumb mode, adjusting the return42 * code safely callable from thumb mode, adjusting the return
43 * instructions to be compatible with pre-thumb ARM cpus, and removal43 * instructions to be compatible with pre-thumb ARM cpus, removal of
44 * of prefetch code that is not compatible with older cpus.44 * prefetch code that is not compatible with older cpus and support for
45 * building as thumb 2.
45 */46 */
4647
47.syntax unified48.syntax unified
...@@ -241,7 +242,8 @@ non_congruent:...@@ -241,7 +242,8 @@ non_congruent:
241 beq 2f242 beq 2f
242 ldr r5, [r1], #4243 ldr r5, [r1], #4
243 sub r2, r2, #4244 sub r2, r2, #4
244 orr r4, r3, r5, lsl lr245 mov r4, r5, lsl lr
246 orr r4, r4, r3
245 mov r3, r5, lsr r12247 mov r3, r5, lsr r12
246 str r4, [r0], #4248 str r4, [r0], #4
247 cmp r2, #4249 cmp r2, #4
...@@ -348,7 +350,8 @@ less_than_thirtytwo:...@@ -348,7 +350,8 @@ less_than_thirtytwo:
348350
3491: ldr r5, [r1], #43511: ldr r5, [r1], #4
350 sub r2, r2, #4352 sub r2, r2, #4
351 orr r4, r3, r5, lsl lr353 mov r4, r5, lsl lr
354 orr r4, r4, r3
352 mov r3, r5, lsr r12355 mov r3, r5, lsr r12
353 str r4, [r0], #4356 str r4, [r0], #4
354 cmp r2, #4357 cmp r2, #4
lib/libc/musl/src/time/__map_file.c+2-1
...@@ -2,10 +2,11 @@...@@ -2,10 +2,11 @@
2#include <fcntl.h>2#include <fcntl.h>
3#include <sys/stat.h>3#include <sys/stat.h>
4#include "syscall.h"4#include "syscall.h"
5#include "kstat.h"
56
6const char unsigned *__map_file(const char *pathname, size_t *size)7const char unsigned *__map_file(const char *pathname, size_t *size)
7{8{
8 struct stat st;9 struct kstat st;
9 const unsigned char *map = MAP_FAILED;10 const unsigned char *map = MAP_FAILED;
10 int fd = sys_open(pathname, O_RDONLY|O_CLOEXEC|O_NONBLOCK);11 int fd = sys_open(pathname, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
11 if (fd < 0) return 0;12 if (fd < 0) return 0;
lib/std/atomic/int.zig+5-8
...@@ -1,6 +1,3 @@...@@ -1,6 +1,3 @@
1const builtin = @import("builtin");
2const AtomicOrder = builtin.AtomicOrder;
3
4/// Thread-safe, lock-free integer1/// Thread-safe, lock-free integer
5pub fn Int(comptime T: type) type {2pub fn Int(comptime T: type) type {
6 return struct {3 return struct {
...@@ -14,16 +11,16 @@ pub fn Int(comptime T: type) type {...@@ -14,16 +11,16 @@ pub fn Int(comptime T: type) type {
1411
15 /// Returns previous value12 /// Returns previous value
16 pub fn incr(self: *Self) T {13 pub fn incr(self: *Self) T {
17 return @atomicRmw(T, &self.unprotected_value, builtin.AtomicRmwOp.Add, 1, AtomicOrder.SeqCst);14 return @atomicRmw(T, &self.unprotected_value, .Add, 1, .SeqCst);
18 }15 }
1916
20 /// Returns previous value17 /// Returns previous value
21 pub fn decr(self: *Self) T {18 pub fn decr(self: *Self) T {
22 return @atomicRmw(T, &self.unprotected_value, builtin.AtomicRmwOp.Sub, 1, AtomicOrder.SeqCst);19 return @atomicRmw(T, &self.unprotected_value, .Sub, 1, .SeqCst);
23 }20 }
2421
25 pub fn get(self: *Self) T {22 pub fn get(self: *Self) T {
26 return @atomicLoad(T, &self.unprotected_value, AtomicOrder.SeqCst);23 return @atomicLoad(T, &self.unprotected_value, .SeqCst);
27 }24 }
2825
29 pub fn set(self: *Self, new_value: T) void {26 pub fn set(self: *Self, new_value: T) void {
...@@ -31,11 +28,11 @@ pub fn Int(comptime T: type) type {...@@ -31,11 +28,11 @@ pub fn Int(comptime T: type) type {
31 }28 }
3229
33 pub fn xchg(self: *Self, new_value: T) T {30 pub fn xchg(self: *Self, new_value: T) T {
34 return @atomicRmw(T, &self.unprotected_value, builtin.AtomicRmwOp.Xchg, new_value, AtomicOrder.SeqCst);31 return @atomicRmw(T, &self.unprotected_value, .Xchg, new_value, .SeqCst);
35 }32 }
3633
37 pub fn fetchAdd(self: *Self, op: T) T {34 pub fn fetchAdd(self: *Self, op: T) T {
38 return @atomicRmw(T, &self.unprotected_value, builtin.AtomicRmwOp.Add, op, AtomicOrder.SeqCst);35 return @atomicRmw(T, &self.unprotected_value, .Add, op, .SeqCst);
39 }36 }
40 };37 };
41}38}
lib/std/atomic/queue.zig+23-30
...@@ -1,7 +1,5 @@...@@ -1,7 +1,5 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const AtomicOrder = builtin.AtomicOrder;
4const AtomicRmwOp = builtin.AtomicRmwOp;
5const assert = std.debug.assert;3const assert = std.debug.assert;
6const expect = std.testing.expect;4const expect = std.testing.expect;
75
...@@ -104,21 +102,17 @@ pub fn Queue(comptime T: type) type {...@@ -104,21 +102,17 @@ pub fn Queue(comptime T: type) type {
104 }102 }
105103
106 pub fn dump(self: *Self) void {104 pub fn dump(self: *Self) void {
107 var stderr_file = std.io.getStdErr() catch return;105 self.dumpToStream(std.io.getStdErr().outStream()) catch return;
108 const stderr = &stderr_file.outStream().stream;
109 const Error = @typeInfo(@TypeOf(stderr)).Pointer.child.Error;
110
111 self.dumpToStream(Error, stderr) catch return;
112 }106 }
113107
114 pub fn dumpToStream(self: *Self, comptime Error: type, stream: *std.io.OutStream(Error)) Error!void {108 pub fn dumpToStream(self: *Self, stream: var) !void {
115 const S = struct {109 const S = struct {
116 fn dumpRecursive(110 fn dumpRecursive(
117 s: *std.io.OutStream(Error),111 s: var,
118 optional_node: ?*Node,112 optional_node: ?*Node,
119 indent: usize,113 indent: usize,
120 comptime depth: comptime_int,114 comptime depth: comptime_int,
121 ) Error!void {115 ) !void {
122 try s.writeByteNTimes(' ', indent);116 try s.writeByteNTimes(' ', indent);
123 if (optional_node) |node| {117 if (optional_node) |node| {
124 try s.print("0x{x}={}\n", .{ @ptrToInt(node), node.data });118 try s.print("0x{x}={}\n", .{ @ptrToInt(node), node.data });
...@@ -149,7 +143,7 @@ const Context = struct {...@@ -149,7 +143,7 @@ const Context = struct {
149 put_sum: isize,143 put_sum: isize,
150 get_sum: isize,144 get_sum: isize,
151 get_count: usize,145 get_count: usize,
152 puts_done: u8, // TODO make this a bool146 puts_done: bool,
153};147};
154148
155// TODO add lazy evaluated build options and then put puts_per_thread behind149// TODO add lazy evaluated build options and then put puts_per_thread behind
...@@ -173,7 +167,7 @@ test "std.atomic.Queue" {...@@ -173,7 +167,7 @@ test "std.atomic.Queue" {
173 .queue = &queue,167 .queue = &queue,
174 .put_sum = 0,168 .put_sum = 0,
175 .get_sum = 0,169 .get_sum = 0,
176 .puts_done = 0,170 .puts_done = false,
177 .get_count = 0,171 .get_count = 0,
178 };172 };
179173
...@@ -186,7 +180,7 @@ test "std.atomic.Queue" {...@@ -186,7 +180,7 @@ test "std.atomic.Queue" {
186 }180 }
187 }181 }
188 expect(!context.queue.isEmpty());182 expect(!context.queue.isEmpty());
189 context.puts_done = 1;183 context.puts_done = true;
190 {184 {
191 var i: usize = 0;185 var i: usize = 0;
192 while (i < put_thread_count) : (i += 1) {186 while (i < put_thread_count) : (i += 1) {
...@@ -208,7 +202,7 @@ test "std.atomic.Queue" {...@@ -208,7 +202,7 @@ test "std.atomic.Queue" {
208202
209 for (putters) |t|203 for (putters) |t|
210 t.wait();204 t.wait();
211 @atomicStore(u8, &context.puts_done, 1, AtomicOrder.SeqCst);205 @atomicStore(bool, &context.puts_done, true, .SeqCst);
212 for (getters) |t|206 for (getters) |t|
213 t.wait();207 t.wait();
214208
...@@ -235,25 +229,25 @@ fn startPuts(ctx: *Context) u8 {...@@ -235,25 +229,25 @@ fn startPuts(ctx: *Context) u8 {
235 std.time.sleep(1); // let the os scheduler be our fuzz229 std.time.sleep(1); // let the os scheduler be our fuzz
236 const x = @bitCast(i32, r.random.scalar(u32));230 const x = @bitCast(i32, r.random.scalar(u32));
237 const node = ctx.allocator.create(Queue(i32).Node) catch unreachable;231 const node = ctx.allocator.create(Queue(i32).Node) catch unreachable;
238 node.* = Queue(i32).Node{232 node.* = .{
239 .prev = undefined,233 .prev = undefined,
240 .next = undefined,234 .next = undefined,
241 .data = x,235 .data = x,
242 };236 };
243 ctx.queue.put(node);237 ctx.queue.put(node);
244 _ = @atomicRmw(isize, &ctx.put_sum, builtin.AtomicRmwOp.Add, x, AtomicOrder.SeqCst);238 _ = @atomicRmw(isize, &ctx.put_sum, .Add, x, .SeqCst);
245 }239 }
246 return 0;240 return 0;
247}241}
248242
249fn startGets(ctx: *Context) u8 {243fn startGets(ctx: *Context) u8 {
250 while (true) {244 while (true) {
251 const last = @atomicLoad(u8, &ctx.puts_done, builtin.AtomicOrder.SeqCst) == 1;245 const last = @atomicLoad(bool, &ctx.puts_done, .SeqCst);
252246
253 while (ctx.queue.get()) |node| {247 while (ctx.queue.get()) |node| {
254 std.time.sleep(1); // let the os scheduler be our fuzz248 std.time.sleep(1); // let the os scheduler be our fuzz
255 _ = @atomicRmw(isize, &ctx.get_sum, builtin.AtomicRmwOp.Add, node.data, builtin.AtomicOrder.SeqCst);249 _ = @atomicRmw(isize, &ctx.get_sum, .Add, node.data, .SeqCst);
256 _ = @atomicRmw(usize, &ctx.get_count, builtin.AtomicRmwOp.Add, 1, builtin.AtomicOrder.SeqCst);250 _ = @atomicRmw(usize, &ctx.get_count, .Add, 1, .SeqCst);
257 }251 }
258252
259 if (last) return 0;253 if (last) return 0;
...@@ -326,17 +320,16 @@ test "std.atomic.Queue single-threaded" {...@@ -326,17 +320,16 @@ test "std.atomic.Queue single-threaded" {
326320
327test "std.atomic.Queue dump" {321test "std.atomic.Queue dump" {
328 const mem = std.mem;322 const mem = std.mem;
329 const SliceOutStream = std.io.SliceOutStream;
330 var buffer: [1024]u8 = undefined;323 var buffer: [1024]u8 = undefined;
331 var expected_buffer: [1024]u8 = undefined;324 var expected_buffer: [1024]u8 = undefined;
332 var sos = SliceOutStream.init(buffer[0..]);325 var fbs = std.io.fixedBufferStream(&buffer);
333326
334 var queue = Queue(i32).init();327 var queue = Queue(i32).init();
335328
336 // Test empty stream329 // Test empty stream
337 sos.reset();330 fbs.reset();
338 try queue.dumpToStream(SliceOutStream.Error, &sos.stream);331 try queue.dumpToStream(fbs.outStream());
339 expect(mem.eql(u8, buffer[0..sos.pos],332 expect(mem.eql(u8, buffer[0..fbs.pos],
340 \\head: (null)333 \\head: (null)
341 \\tail: (null)334 \\tail: (null)
342 \\335 \\
...@@ -350,8 +343,8 @@ test "std.atomic.Queue dump" {...@@ -350,8 +343,8 @@ test "std.atomic.Queue dump" {
350 };343 };
351 queue.put(&node_0);344 queue.put(&node_0);
352345
353 sos.reset();346 fbs.reset();
354 try queue.dumpToStream(SliceOutStream.Error, &sos.stream);347 try queue.dumpToStream(fbs.outStream());
355348
356 var expected = try std.fmt.bufPrint(expected_buffer[0..],349 var expected = try std.fmt.bufPrint(expected_buffer[0..],
357 \\head: 0x{x}=1350 \\head: 0x{x}=1
...@@ -360,7 +353,7 @@ test "std.atomic.Queue dump" {...@@ -360,7 +353,7 @@ test "std.atomic.Queue dump" {
360 \\ (null)353 \\ (null)
361 \\354 \\
362 , .{ @ptrToInt(queue.head), @ptrToInt(queue.tail) });355 , .{ @ptrToInt(queue.head), @ptrToInt(queue.tail) });
363 expect(mem.eql(u8, buffer[0..sos.pos], expected));356 expect(mem.eql(u8, buffer[0..fbs.pos], expected));
364357
365 // Test a stream with two elements358 // Test a stream with two elements
366 var node_1 = Queue(i32).Node{359 var node_1 = Queue(i32).Node{
...@@ -370,8 +363,8 @@ test "std.atomic.Queue dump" {...@@ -370,8 +363,8 @@ test "std.atomic.Queue dump" {
370 };363 };
371 queue.put(&node_1);364 queue.put(&node_1);
372365
373 sos.reset();366 fbs.reset();
374 try queue.dumpToStream(SliceOutStream.Error, &sos.stream);367 try queue.dumpToStream(fbs.outStream());
375368
376 expected = try std.fmt.bufPrint(expected_buffer[0..],369 expected = try std.fmt.bufPrint(expected_buffer[0..],
377 \\head: 0x{x}=1370 \\head: 0x{x}=1
...@@ -381,5 +374,5 @@ test "std.atomic.Queue dump" {...@@ -381,5 +374,5 @@ test "std.atomic.Queue dump" {
381 \\ (null)374 \\ (null)
382 \\375 \\
383 , .{ @ptrToInt(queue.head), @ptrToInt(queue.head.?.next), @ptrToInt(queue.tail) });376 , .{ @ptrToInt(queue.head), @ptrToInt(queue.head.?.next), @ptrToInt(queue.tail) });
384 expect(mem.eql(u8, buffer[0..sos.pos], expected));377 expect(mem.eql(u8, buffer[0..fbs.pos], expected));
385}378}
lib/std/atomic/stack.zig+15-16
...@@ -1,6 +1,5 @@...@@ -1,6 +1,5 @@
1const assert = std.debug.assert;1const assert = std.debug.assert;
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const AtomicOrder = builtin.AtomicOrder;
4const expect = std.testing.expect;3const expect = std.testing.expect;
54
6/// Many reader, many writer, non-allocating, thread-safe5/// Many reader, many writer, non-allocating, thread-safe
...@@ -11,7 +10,7 @@ pub fn Stack(comptime T: type) type {...@@ -11,7 +10,7 @@ pub fn Stack(comptime T: type) type {
11 root: ?*Node,10 root: ?*Node,
12 lock: @TypeOf(lock_init),11 lock: @TypeOf(lock_init),
1312
14 const lock_init = if (builtin.single_threaded) {} else @as(u8, 0);13 const lock_init = if (builtin.single_threaded) {} else false;
1514
16 pub const Self = @This();15 pub const Self = @This();
1716
...@@ -31,7 +30,7 @@ pub fn Stack(comptime T: type) type {...@@ -31,7 +30,7 @@ pub fn Stack(comptime T: type) type {
31 /// being the first item in the stack, returns the other item that was there.30 /// being the first item in the stack, returns the other item that was there.
32 pub fn pushFirst(self: *Self, node: *Node) ?*Node {31 pub fn pushFirst(self: *Self, node: *Node) ?*Node {
33 node.next = null;32 node.next = null;
34 return @cmpxchgStrong(?*Node, &self.root, null, node, AtomicOrder.SeqCst, AtomicOrder.SeqCst);33 return @cmpxchgStrong(?*Node, &self.root, null, node, .SeqCst, .SeqCst);
35 }34 }
3635
37 pub fn push(self: *Self, node: *Node) void {36 pub fn push(self: *Self, node: *Node) void {
...@@ -39,8 +38,8 @@ pub fn Stack(comptime T: type) type {...@@ -39,8 +38,8 @@ pub fn Stack(comptime T: type) type {
39 node.next = self.root;38 node.next = self.root;
40 self.root = node;39 self.root = node;
41 } else {40 } else {
42 while (@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) != 0) {}41 while (@atomicRmw(bool, &self.lock, .Xchg, true, .SeqCst)) {}
43 defer assert(@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 1);42 defer assert(@atomicRmw(bool, &self.lock, .Xchg, false, .SeqCst));
4443
45 node.next = self.root;44 node.next = self.root;
46 self.root = node;45 self.root = node;
...@@ -53,8 +52,8 @@ pub fn Stack(comptime T: type) type {...@@ -53,8 +52,8 @@ pub fn Stack(comptime T: type) type {
53 self.root = root.next;52 self.root = root.next;
54 return root;53 return root;
55 } else {54 } else {
56 while (@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) != 0) {}55 while (@atomicRmw(bool, &self.lock, .Xchg, true, .SeqCst)) {}
57 defer assert(@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 1);56 defer assert(@atomicRmw(bool, &self.lock, .Xchg, false, .SeqCst));
5857
59 const root = self.root orelse return null;58 const root = self.root orelse return null;
60 self.root = root.next;59 self.root = root.next;
...@@ -63,7 +62,7 @@ pub fn Stack(comptime T: type) type {...@@ -63,7 +62,7 @@ pub fn Stack(comptime T: type) type {
63 }62 }
6463
65 pub fn isEmpty(self: *Self) bool {64 pub fn isEmpty(self: *Self) bool {
66 return @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst) == null;65 return @atomicLoad(?*Node, &self.root, .SeqCst) == null;
67 }66 }
68 };67 };
69}68}
...@@ -75,7 +74,7 @@ const Context = struct {...@@ -75,7 +74,7 @@ const Context = struct {
75 put_sum: isize,74 put_sum: isize,
76 get_sum: isize,75 get_sum: isize,
77 get_count: usize,76 get_count: usize,
78 puts_done: u8, // TODO make this a bool77 puts_done: bool,
79};78};
80// TODO add lazy evaluated build options and then put puts_per_thread behind79// TODO add lazy evaluated build options and then put puts_per_thread behind
81// some option such as: "AggressiveMultithreadedFuzzTest". In the AppVeyor80// some option such as: "AggressiveMultithreadedFuzzTest". In the AppVeyor
...@@ -98,7 +97,7 @@ test "std.atomic.stack" {...@@ -98,7 +97,7 @@ test "std.atomic.stack" {
98 .stack = &stack,97 .stack = &stack,
99 .put_sum = 0,98 .put_sum = 0,
100 .get_sum = 0,99 .get_sum = 0,
101 .puts_done = 0,100 .puts_done = false,
102 .get_count = 0,101 .get_count = 0,
103 };102 };
104103
...@@ -109,7 +108,7 @@ test "std.atomic.stack" {...@@ -109,7 +108,7 @@ test "std.atomic.stack" {
109 expect(startPuts(&context) == 0);108 expect(startPuts(&context) == 0);
110 }109 }
111 }110 }
112 context.puts_done = 1;111 context.puts_done = true;
113 {112 {
114 var i: usize = 0;113 var i: usize = 0;
115 while (i < put_thread_count) : (i += 1) {114 while (i < put_thread_count) : (i += 1) {
...@@ -128,7 +127,7 @@ test "std.atomic.stack" {...@@ -128,7 +127,7 @@ test "std.atomic.stack" {
128127
129 for (putters) |t|128 for (putters) |t|
130 t.wait();129 t.wait();
131 @atomicStore(u8, &context.puts_done, 1, AtomicOrder.SeqCst);130 @atomicStore(bool, &context.puts_done, true, .SeqCst);
132 for (getters) |t|131 for (getters) |t|
133 t.wait();132 t.wait();
134 }133 }
...@@ -158,19 +157,19 @@ fn startPuts(ctx: *Context) u8 {...@@ -158,19 +157,19 @@ fn startPuts(ctx: *Context) u8 {
158 .data = x,157 .data = x,
159 };158 };
160 ctx.stack.push(node);159 ctx.stack.push(node);
161 _ = @atomicRmw(isize, &ctx.put_sum, builtin.AtomicRmwOp.Add, x, AtomicOrder.SeqCst);160 _ = @atomicRmw(isize, &ctx.put_sum, .Add, x, .SeqCst);
162 }161 }
163 return 0;162 return 0;
164}163}
165164
166fn startGets(ctx: *Context) u8 {165fn startGets(ctx: *Context) u8 {
167 while (true) {166 while (true) {
168 const last = @atomicLoad(u8, &ctx.puts_done, builtin.AtomicOrder.SeqCst) == 1;167 const last = @atomicLoad(bool, &ctx.puts_done, .SeqCst);
169168
170 while (ctx.stack.pop()) |node| {169 while (ctx.stack.pop()) |node| {
171 std.time.sleep(1); // let the os scheduler be our fuzz170 std.time.sleep(1); // let the os scheduler be our fuzz
172 _ = @atomicRmw(isize, &ctx.get_sum, builtin.AtomicRmwOp.Add, node.data, builtin.AtomicOrder.SeqCst);171 _ = @atomicRmw(isize, &ctx.get_sum, .Add, node.data, .SeqCst);
173 _ = @atomicRmw(usize, &ctx.get_count, builtin.AtomicRmwOp.Add, 1, builtin.AtomicOrder.SeqCst);172 _ = @atomicRmw(usize, &ctx.get_count, .Add, 1, .SeqCst);
174 }173 }
175174
176 if (last) return 0;175 if (last) return 0;
lib/std/buffer.zig+25-10
...@@ -65,13 +65,9 @@ pub const Buffer = struct {...@@ -65,13 +65,9 @@ pub const Buffer = struct {
65 }65 }
6666
67 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer {67 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer {
68 const countSize = struct {68 const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) {
69 fn countSize(size: *usize, bytes: []const u8) (error{}!void) {69 error.Overflow => return error.OutOfMemory,
70 size.* += bytes.len;70 };
71 }
72 }.countSize;
73 var size: usize = 0;
74 std.fmt.format(&size, error{}, countSize, format, args) catch |err| switch (err) {};
75 var self = try Buffer.initSize(allocator, size);71 var self = try Buffer.initSize(allocator, size);
76 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);72 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);
77 return self;73 return self;
...@@ -154,8 +150,15 @@ pub const Buffer = struct {...@@ -154,8 +150,15 @@ pub const Buffer = struct {
154 mem.copy(u8, self.list.toSlice(), m);150 mem.copy(u8, self.list.toSlice(), m);
155 }151 }
156152
157 pub fn print(self: *Buffer, comptime fmt: []const u8, args: var) !void {153 pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) {
158 return std.fmt.format(self, error{OutOfMemory}, Buffer.append, fmt, args);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;
159 }162 }
160};163};
161164
...@@ -205,6 +208,18 @@ test "Buffer.print" {...@@ -205,6 +208,18 @@ test "Buffer.print" {
205 var buf = try Buffer.init(testing.allocator, "");208 var buf = try Buffer.init(testing.allocator, "");
206 defer buf.deinit();209 defer buf.deinit();
207210
208 try buf.print("Hello {} the {}", .{ 2, "world" });211 try buf.outStream().print("Hello {} the {}", .{ 2, "world" });
209 testing.expect(buf.eql("Hello 2 the world"));212 testing.expect(buf.eql("Hello 2 the world"));
210}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+1-2
...@@ -926,8 +926,7 @@ pub const Builder = struct {...@@ -926,8 +926,7 @@ pub const Builder = struct {
926926
927 try child.spawn();927 try child.spawn();
928928
929 var stdout_file_in_stream = child.stdout.?.inStream();929 const stdout = try child.stdout.?.inStream().readAllAlloc(self.allocator, max_output_size);
930 const stdout = try stdout_file_in_stream.stream.readAllAlloc(self.allocator, max_output_size);
931 errdefer self.allocator.free(stdout);930 errdefer self.allocator.free(stdout);
932931
933 const term = try child.wait();932 const term = try child.wait();
lib/std/build/emit_raw.zig+36-74
...@@ -14,11 +14,6 @@ const io = std.io;...@@ -14,11 +14,6 @@ const io = std.io;
14const sort = std.sort;14const sort = std.sort;
15const warn = std.debug.warn;15const warn = std.debug.warn;
1616
17const BinOutStream = io.OutStream(anyerror);
18const BinSeekStream = io.SeekableStream(anyerror, anyerror);
19const ElfSeekStream = io.SeekableStream(anyerror, anyerror);
20const ElfInStream = io.InStream(anyerror);
21
22const BinaryElfSection = struct {17const BinaryElfSection = struct {
23 elfOffset: u64,18 elfOffset: u64,
24 binaryOffset: u64,19 binaryOffset: u64,
...@@ -41,22 +36,19 @@ const BinaryElfOutput = struct {...@@ -41,22 +36,19 @@ const BinaryElfOutput = struct {
4136
42 const Self = @This();37 const Self = @This();
4338
44 pub fn init(allocator: *Allocator) Self {
45 return Self{
46 .segments = ArrayList(*BinaryElfSegment).init(allocator),
47 .sections = ArrayList(*BinaryElfSection).init(allocator),
48 };
49 }
50
51 pub fn deinit(self: *Self) void {39 pub fn deinit(self: *Self) void {
52 self.sections.deinit();40 self.sections.deinit();
53 self.segments.deinit();41 self.segments.deinit();
54 }42 }
5543
56 pub fn parseElf(self: *Self, elfFile: elf.Elf) !void {44 pub fn parse(allocator: *Allocator, elf_file: File) !Self {
57 const allocator = self.segments.allocator;45 var self: Self = .{
46 .segments = ArrayList(*BinaryElfSegment).init(allocator),
47 .sections = ArrayList(*BinaryElfSection).init(allocator),
48 };
49 const elf_hdrs = try std.elf.readAllHeaders(allocator, elf_file);
5850
59 for (elfFile.section_headers) |section, i| {51 for (elf_hdrs.section_headers) |section, i| {
60 if (sectionValidForOutput(section)) {52 if (sectionValidForOutput(section)) {
61 const newSection = try allocator.create(BinaryElfSection);53 const newSection = try allocator.create(BinaryElfSection);
6254
...@@ -69,19 +61,19 @@ const BinaryElfOutput = struct {...@@ -69,19 +61,19 @@ const BinaryElfOutput = struct {
69 }61 }
70 }62 }
7163
72 for (elfFile.program_headers) |programHeader, i| {64 for (elf_hdrs.program_headers) |phdr, i| {
73 if (programHeader.p_type == elf.PT_LOAD) {65 if (phdr.p_type == elf.PT_LOAD) {
74 const newSegment = try allocator.create(BinaryElfSegment);66 const newSegment = try allocator.create(BinaryElfSegment);
7567
76 newSegment.physicalAddress = if (programHeader.p_paddr != 0) programHeader.p_paddr else programHeader.p_vaddr;68 newSegment.physicalAddress = if (phdr.p_paddr != 0) phdr.p_paddr else phdr.p_vaddr;
77 newSegment.virtualAddress = programHeader.p_vaddr;69 newSegment.virtualAddress = phdr.p_vaddr;
78 newSegment.fileSize = @intCast(usize, programHeader.p_filesz);70 newSegment.fileSize = @intCast(usize, phdr.p_filesz);
79 newSegment.elfOffset = programHeader.p_offset;71 newSegment.elfOffset = phdr.p_offset;
80 newSegment.binaryOffset = 0;72 newSegment.binaryOffset = 0;
81 newSegment.firstSection = null;73 newSegment.firstSection = null;
8274
83 for (self.sections.toSlice()) |section| {75 for (self.sections.toSlice()) |section| {
84 if (sectionWithinSegment(section, programHeader)) {76 if (sectionWithinSegment(section, phdr)) {
85 if (section.segment) |sectionSegment| {77 if (section.segment) |sectionSegment| {
86 if (sectionSegment.elfOffset > newSegment.elfOffset) {78 if (sectionSegment.elfOffset > newSegment.elfOffset) {
87 section.segment = newSegment;79 section.segment = newSegment;
...@@ -126,14 +118,17 @@ const BinaryElfOutput = struct {...@@ -126,14 +118,17 @@ const BinaryElfOutput = struct {
126 }118 }
127119
128 sort.sort(*BinaryElfSection, self.sections.toSlice(), sectionSortCompare);120 sort.sort(*BinaryElfSection, self.sections.toSlice(), sectionSortCompare);
121
122 return self;
129 }123 }
130124
131 fn sectionWithinSegment(section: *BinaryElfSection, segment: elf.ProgramHeader) bool {125 fn sectionWithinSegment(section: *BinaryElfSection, segment: elf.Elf64_Phdr) bool {
132 return segment.p_offset <= section.elfOffset and (segment.p_offset + segment.p_filesz) >= (section.elfOffset + section.fileSize);126 return segment.p_offset <= section.elfOffset and (segment.p_offset + segment.p_filesz) >= (section.elfOffset + section.fileSize);
133 }127 }
134128
135 fn sectionValidForOutput(section: elf.SectionHeader) bool {129 fn sectionValidForOutput(shdr: var) bool {
136 return section.sh_size > 0 and section.sh_type != elf.SHT_NOBITS and ((section.sh_flags & elf.SHF_ALLOC) == elf.SHF_ALLOC);130 return shdr.sh_size > 0 and shdr.sh_type != elf.SHT_NOBITS and
131 ((shdr.sh_flags & elf.SHF_ALLOC) == elf.SHF_ALLOC);
137 }132 }
138133
139 fn segmentSortCompare(left: *BinaryElfSegment, right: *BinaryElfSegment) bool {134 fn segmentSortCompare(left: *BinaryElfSegment, right: *BinaryElfSegment) bool {
...@@ -151,60 +146,27 @@ const BinaryElfOutput = struct {...@@ -151,60 +146,27 @@ const BinaryElfOutput = struct {
151 }146 }
152};147};
153148
154const WriteContext = struct {149fn writeBinaryElfSection(elf_file: File, out_file: File, section: *BinaryElfSection) !void {
155 inStream: *ElfInStream,150 try out_file.seekTo(section.binaryOffset);
156 inSeekStream: *ElfSeekStream,
157 outStream: *BinOutStream,
158 outSeekStream: *BinSeekStream,
159};
160
161fn writeBinaryElfSection(allocator: *Allocator, context: WriteContext, section: *BinaryElfSection) !void {
162 var readBuffer = try allocator.alloc(u8, section.fileSize);
163 defer allocator.free(readBuffer);
164
165 try context.inSeekStream.seekTo(section.elfOffset);
166 _ = try context.inStream.read(readBuffer);
167151
168 try context.outSeekStream.seekTo(section.binaryOffset);152 try out_file.writeFileAll(elf_file, .{
169 try context.outStream.write(readBuffer);153 .in_offset = section.elfOffset,
154 .in_len = section.fileSize,
155 });
170}156}
171157
172fn emit_raw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !void {158fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !void {
173 var arenaAlloc = ArenaAllocator.init(allocator);159 var elf_file = try fs.cwd().openFile(elf_path, .{});
174 errdefer arenaAlloc.deinit();160 defer elf_file.close();
175 var arena_allocator = &arenaAlloc.allocator;
176
177 const currentDir = fs.cwd();
178
179 var file = try currentDir.openFile(elf_path, File.OpenFlags{});
180 defer file.close();
181
182 var fileInStream = file.inStream();
183 var fileSeekStream = file.seekableStream();
184
185 var elfFile = try elf.Elf.openStream(allocator, @ptrCast(*ElfSeekStream, &fileSeekStream.stream), @ptrCast(*ElfInStream, &fileInStream.stream));
186 defer elfFile.close();
187
188 var outFile = try currentDir.createFile(raw_path, File.CreateFlags{});
189 defer outFile.close();
190
191 var outFileOutStream = outFile.outStream();
192 var outFileSeekStream = outFile.seekableStream();
193
194 const writeContext = WriteContext{
195 .inStream = @ptrCast(*ElfInStream, &fileInStream.stream),
196 .inSeekStream = @ptrCast(*ElfSeekStream, &fileSeekStream.stream),
197 .outStream = @ptrCast(*BinOutStream, &outFileOutStream.stream),
198 .outSeekStream = @ptrCast(*BinSeekStream, &outFileSeekStream.stream),
199 };
200161
201 var binaryElfOutput = BinaryElfOutput.init(arena_allocator);162 var out_file = try fs.cwd().createFile(raw_path, .{});
202 defer binaryElfOutput.deinit();163 defer out_file.close();
203164
204 try binaryElfOutput.parseElf(elfFile);165 var binary_elf_output = try BinaryElfOutput.parse(allocator, elf_file);
166 defer binary_elf_output.deinit();
205167
206 for (binaryElfOutput.sections.toSlice()) |section| {168 for (binary_elf_output.sections.toSlice()) |section| {
207 try writeBinaryElfSection(allocator, writeContext, section);169 try writeBinaryElfSection(elf_file, out_file, section);
208 }170 }
209}171}
210172
...@@ -250,6 +212,6 @@ pub const InstallRawStep = struct {...@@ -250,6 +212,6 @@ pub const InstallRawStep = struct {
250 const full_dest_path = builder.getInstallPath(self.dest_dir, self.dest_filename);212 const full_dest_path = builder.getInstallPath(self.dest_dir, self.dest_filename);
251213
252 fs.cwd().makePath(builder.getInstallPath(self.dest_dir, "")) catch unreachable;214 fs.cwd().makePath(builder.getInstallPath(self.dest_dir, "")) catch unreachable;
253 try emit_raw(builder.allocator, full_src_path, full_dest_path);215 try emitRaw(builder.allocator, full_src_path, full_dest_path);
254 }216 }
255};217};
lib/std/build/run.zig+2-4
...@@ -175,8 +175,7 @@ pub const RunStep = struct {...@@ -175,8 +175,7 @@ pub const RunStep = struct {
175175
176 switch (self.stdout_action) {176 switch (self.stdout_action) {
177 .expect_exact, .expect_matches => {177 .expect_exact, .expect_matches => {
178 var stdout_file_in_stream = child.stdout.?.inStream();178 stdout = child.stdout.?.inStream().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
179 stdout = stdout_file_in_stream.stream.readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
180 },179 },
181 .inherit, .ignore => {},180 .inherit, .ignore => {},
182 }181 }
...@@ -186,8 +185,7 @@ pub const RunStep = struct {...@@ -186,8 +185,7 @@ pub const RunStep = struct {
186185
187 switch (self.stderr_action) {186 switch (self.stderr_action) {
188 .expect_exact, .expect_matches => {187 .expect_exact, .expect_matches => {
189 var stderr_file_in_stream = child.stderr.?.inStream();188 stderr = child.stderr.?.inStream().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
190 stderr = stderr_file_in_stream.stream.readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
191 },189 },
192 .inherit, .ignore => {},190 .inherit, .ignore => {},
193 }191 }
lib/std/builtin.zig+5-7
...@@ -436,19 +436,17 @@ pub const Version = struct {...@@ -436,19 +436,17 @@ pub const Version = struct {
436 self: Version,436 self: Version,
437 comptime fmt: []const u8,437 comptime fmt: []const u8,
438 options: std.fmt.FormatOptions,438 options: std.fmt.FormatOptions,
439 context: var,439 out_stream: var,
440 comptime Error: type,440 ) !void {
441 comptime output: fn (@TypeOf(context), []const u8) Error!void,
442 ) Error!void {
443 if (fmt.len == 0) {441 if (fmt.len == 0) {
444 if (self.patch == 0) {442 if (self.patch == 0) {
445 if (self.minor == 0) {443 if (self.minor == 0) {
446 return std.fmt.format(context, Error, output, "{}", .{self.major});444 return std.fmt.format(out_stream, "{}", .{self.major});
447 } else {445 } else {
448 return std.fmt.format(context, Error, output, "{}.{}", .{ self.major, self.minor });446 return std.fmt.format(out_stream, "{}.{}", .{ self.major, self.minor });
449 }447 }
450 } else {448 } else {
451 return std.fmt.format(context, Error, output, "{}.{}.{}", .{ self.major, self.minor, self.patch });449 return std.fmt.format(out_stream, "{}.{}.{}", .{ self.major, self.minor, self.patch });
452 }450 }
453 } else {451 } else {
454 @compileError("Unknown format string: '" ++ fmt ++ "'");452 @compileError("Unknown format string: '" ++ fmt ++ "'");
lib/std/c.zig+1
...@@ -79,6 +79,7 @@ pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, fla...@@ -79,6 +79,7 @@ pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, fla
79pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t;79pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t;
80pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;80pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;
81pub extern "c" fn openat(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int;81pub extern "c" fn openat(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int;
82pub extern "c" fn ftruncate(fd: c_int, length: off_t) c_int;
82pub extern "c" fn raise(sig: c_int) c_int;83pub extern "c" fn raise(sig: c_int) c_int;
83pub extern "c" fn read(fd: fd_t, buf: [*]u8, nbyte: usize) isize;84pub extern "c" fn read(fd: fd_t, buf: [*]u8, nbyte: usize) isize;
84pub extern "c" fn readv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint) isize;85pub extern "c" fn readv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint) isize;
lib/std/c/linux.zig+2
...@@ -82,6 +82,8 @@ pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;...@@ -82,6 +82,8 @@ pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
8282
83pub extern "c" fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int;83pub extern "c" fn memfd_create(name: [*:0]const u8, flags: c_uint) c_int;
8484
85pub extern "c" fn ftruncate64(fd: c_int, length: off_t) c_int;
86
85pub extern "c" fn sendfile(87pub extern "c" fn sendfile(
86 out_fd: fd_t,88 out_fd: fd_t,
87 in_fd: fd_t,89 in_fd: fd_t,
lib/std/child_process.zig+7-9
...@@ -217,13 +217,13 @@ pub const ChildProcess = struct {...@@ -217,13 +217,13 @@ pub const ChildProcess = struct {
217217
218 try child.spawn();218 try child.spawn();
219219
220 var stdout_file_in_stream = child.stdout.?.inStream();220 const stdout_in = child.stdout.?.inStream();
221 var stderr_file_in_stream = child.stderr.?.inStream();221 const stderr_in = child.stderr.?.inStream();
222222
223 // TODO need to poll to read these streams to prevent a deadlock (or rely on evented I/O).223 // TODO need to poll to read these streams to prevent a deadlock (or rely on evented I/O).
224 const stdout = try stdout_file_in_stream.stream.readAllAlloc(args.allocator, args.max_output_bytes);224 const stdout = try stdout_in.readAllAlloc(args.allocator, args.max_output_bytes);
225 errdefer args.allocator.free(stdout);225 errdefer args.allocator.free(stdout);
226 const stderr = try stderr_file_in_stream.stream.readAllAlloc(args.allocator, args.max_output_bytes);226 const stderr = try stderr_in.readAllAlloc(args.allocator, args.max_output_bytes);
227 errdefer args.allocator.free(stderr);227 errdefer args.allocator.free(stderr);
228228
229 return ExecResult{229 return ExecResult{
...@@ -780,7 +780,7 @@ fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8)...@@ -780,7 +780,7 @@ fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8)
780 var buf = try Buffer.initSize(allocator, 0);780 var buf = try Buffer.initSize(allocator, 0);
781 defer buf.deinit();781 defer buf.deinit();
782782
783 var buf_stream = &io.BufferOutStream.init(&buf).stream;783 var buf_stream = buf.outStream();
784784
785 for (argv) |arg, arg_i| {785 for (argv) |arg, arg_i| {
786 if (arg_i != 0) try buf.appendByte(' ');786 if (arg_i != 0) try buf.appendByte(' ');
...@@ -857,8 +857,7 @@ fn writeIntFd(fd: i32, value: ErrInt) !void {...@@ -857,8 +857,7 @@ fn writeIntFd(fd: i32, value: ErrInt) !void {
857 .io_mode = .blocking,857 .io_mode = .blocking,
858 .async_block_allowed = File.async_block_allowed_yes,858 .async_block_allowed = File.async_block_allowed_yes,
859 };859 };
860 const stream = &file.outStream().stream;860 file.outStream().writeIntNative(u64, @intCast(u64, value)) catch return error.SystemResources;
861 stream.writeIntNative(u64, @intCast(u64, value)) catch return error.SystemResources;
862}861}
863862
864fn readIntFd(fd: i32) !ErrInt {863fn readIntFd(fd: i32) !ErrInt {
...@@ -867,8 +866,7 @@ fn readIntFd(fd: i32) !ErrInt {...@@ -867,8 +866,7 @@ fn readIntFd(fd: i32) !ErrInt {
867 .io_mode = .blocking,866 .io_mode = .blocking,
868 .async_block_allowed = File.async_block_allowed_yes,867 .async_block_allowed = File.async_block_allowed_yes,
869 };868 };
870 const stream = &file.inStream().stream;869 return @intCast(ErrInt, file.inStream().readIntNative(u64) catch return error.SystemResources);
871 return @intCast(ErrInt, stream.readIntNative(u64) catch return error.SystemResources);
872}870}
873871
874/// Caller must free result.872/// Caller must free result.
lib/std/coff.zig+6-9
...@@ -56,8 +56,7 @@ pub const Coff = struct {...@@ -56,8 +56,7 @@ pub const Coff = struct {
56 pub fn loadHeader(self: *Coff) !void {56 pub fn loadHeader(self: *Coff) !void {
57 const pe_pointer_offset = 0x3C;57 const pe_pointer_offset = 0x3C;
5858
59 var file_stream = self.in_file.inStream();59 const in = self.in_file.inStream();
60 const in = &file_stream.stream;
6160
62 var magic: [2]u8 = undefined;61 var magic: [2]u8 = undefined;
63 try in.readNoEof(magic[0..]);62 try in.readNoEof(magic[0..]);
...@@ -89,11 +88,11 @@ pub const Coff = struct {...@@ -89,11 +88,11 @@ pub const Coff = struct {
89 else => return error.InvalidMachine,88 else => return error.InvalidMachine,
90 }89 }
9190
92 try self.loadOptionalHeader(&file_stream);91 try self.loadOptionalHeader();
93 }92 }
9493
95 fn loadOptionalHeader(self: *Coff, file_stream: *File.InStream) !void {94 fn loadOptionalHeader(self: *Coff) !void {
96 const in = &file_stream.stream;95 const in = self.in_file.inStream();
97 self.pe_header.magic = try in.readIntLittle(u16);96 self.pe_header.magic = try in.readIntLittle(u16);
98 // For now we're only interested in finding the reference to the .pdb,97 // For now we're only interested in finding the reference to the .pdb,
99 // so we'll skip most of this header, which size is different in 3298 // so we'll skip most of this header, which size is different in 32
...@@ -136,8 +135,7 @@ pub const Coff = struct {...@@ -136,8 +135,7 @@ pub const Coff = struct {
136 const debug_dir = &self.pe_header.data_directory[DEBUG_DIRECTORY];135 const debug_dir = &self.pe_header.data_directory[DEBUG_DIRECTORY];
137 const file_offset = debug_dir.virtual_address - header.virtual_address + header.pointer_to_raw_data;136 const file_offset = debug_dir.virtual_address - header.virtual_address + header.pointer_to_raw_data;
138137
139 var file_stream = self.in_file.inStream();138 const in = self.in_file.inStream();
140 const in = &file_stream.stream;
141 try self.in_file.seekTo(file_offset);139 try self.in_file.seekTo(file_offset);
142140
143 // Find the correct DebugDirectoryEntry, and where its data is stored.141 // Find the correct DebugDirectoryEntry, and where its data is stored.
...@@ -188,8 +186,7 @@ pub const Coff = struct {...@@ -188,8 +186,7 @@ pub const Coff = struct {
188186
189 try self.sections.ensureCapacity(self.coff_header.number_of_sections);187 try self.sections.ensureCapacity(self.coff_header.number_of_sections);
190188
191 var file_stream = self.in_file.inStream();189 const in = self.in_file.inStream();
192 const in = &file_stream.stream;
193190
194 var name: [8]u8 = undefined;191 var name: [8]u8 = undefined;
195192
lib/std/debug.zig+156-124
...@@ -55,7 +55,7 @@ pub const LineInfo = struct {...@@ -55,7 +55,7 @@ pub const LineInfo = struct {
55var stderr_file: File = undefined;55var stderr_file: File = undefined;
56var stderr_file_out_stream: File.OutStream = undefined;56var stderr_file_out_stream: File.OutStream = undefined;
5757
58var stderr_stream: ?*io.OutStream(File.WriteError) = null;58var stderr_stream: ?*File.OutStream = null;
59var stderr_mutex = std.Mutex.init();59var stderr_mutex = std.Mutex.init();
6060
61pub fn warn(comptime fmt: []const u8, args: var) void {61pub fn warn(comptime fmt: []const u8, args: var) void {
...@@ -65,13 +65,13 @@ pub fn warn(comptime fmt: []const u8, args: var) void {...@@ -65,13 +65,13 @@ pub fn warn(comptime fmt: []const u8, args: var) void {
65 noasync stderr.print(fmt, args) catch return;65 noasync stderr.print(fmt, args) catch return;
66}66}
6767
68pub fn getStderrStream() *io.OutStream(File.WriteError) {68pub fn getStderrStream() *File.OutStream {
69 if (stderr_stream) |st| {69 if (stderr_stream) |st| {
70 return st;70 return st;
71 } else {71 } else {
72 stderr_file = io.getStdErr();72 stderr_file = io.getStdErr();
73 stderr_file_out_stream = stderr_file.outStream();73 stderr_file_out_stream = stderr_file.outStream();
74 const st = &stderr_file_out_stream.stream;74 const st = &stderr_file_out_stream;
75 stderr_stream = st;75 stderr_stream = st;
76 return st;76 return st;
77 }77 }
...@@ -408,15 +408,15 @@ pub const TTY = struct {...@@ -408,15 +408,15 @@ pub const TTY = struct {
408 windows_api,408 windows_api,
409409
410 fn setColor(conf: Config, out_stream: var, color: Color) void {410 fn setColor(conf: Config, out_stream: var, color: Color) void {
411 switch (conf) {411 noasync switch (conf) {
412 .no_color => return,412 .no_color => return,
413 .escape_codes => switch (color) {413 .escape_codes => switch (color) {
414 .Red => noasync out_stream.write(RED) catch return,414 .Red => out_stream.writeAll(RED) catch return,
415 .Green => noasync out_stream.write(GREEN) catch return,415 .Green => out_stream.writeAll(GREEN) catch return,
416 .Cyan => noasync out_stream.write(CYAN) catch return,416 .Cyan => out_stream.writeAll(CYAN) catch return,
417 .White, .Bold => noasync out_stream.write(WHITE) catch return,417 .White, .Bold => out_stream.writeAll(WHITE) catch return,
418 .Dim => noasync out_stream.write(DIM) catch return,418 .Dim => out_stream.writeAll(DIM) catch return,
419 .Reset => noasync out_stream.write(RESET) catch return,419 .Reset => out_stream.writeAll(RESET) catch return,
420 },420 },
421 .windows_api => if (builtin.os.tag == .windows) {421 .windows_api => if (builtin.os.tag == .windows) {
422 const S = struct {422 const S = struct {
...@@ -455,7 +455,7 @@ pub const TTY = struct {...@@ -455,7 +455,7 @@ pub const TTY = struct {
455 } else {455 } else {
456 unreachable;456 unreachable;
457 },457 },
458 }458 };
459 }459 }
460 };460 };
461};461};
...@@ -475,15 +475,15 @@ fn populateModule(di: *ModuleDebugInfo, mod: *Module) !void {...@@ -475,15 +475,15 @@ fn populateModule(di: *ModuleDebugInfo, mod: *Module) !void {
475475
476 const modi = di.pdb.getStreamById(mod.mod_info.ModuleSymStream) orelse return error.MissingDebugInfo;476 const modi = di.pdb.getStreamById(mod.mod_info.ModuleSymStream) orelse return error.MissingDebugInfo;
477477
478 const signature = try modi.stream.readIntLittle(u32);478 const signature = try modi.inStream().readIntLittle(u32);
479 if (signature != 4)479 if (signature != 4)
480 return error.InvalidDebugInfo;480 return error.InvalidDebugInfo;
481481
482 mod.symbols = try allocator.alloc(u8, mod.mod_info.SymByteSize - 4);482 mod.symbols = try allocator.alloc(u8, mod.mod_info.SymByteSize - 4);
483 try modi.stream.readNoEof(mod.symbols);483 try modi.inStream().readNoEof(mod.symbols);
484484
485 mod.subsect_info = try allocator.alloc(u8, mod.mod_info.C13ByteSize);485 mod.subsect_info = try allocator.alloc(u8, mod.mod_info.C13ByteSize);
486 try modi.stream.readNoEof(mod.subsect_info);486 try modi.inStream().readNoEof(mod.subsect_info);
487487
488 var sect_offset: usize = 0;488 var sect_offset: usize = 0;
489 var skip_len: usize = undefined;489 var skip_len: usize = undefined;
...@@ -565,38 +565,40 @@ fn printLineInfo(...@@ -565,38 +565,40 @@ fn printLineInfo(
565 tty_config: TTY.Config,565 tty_config: TTY.Config,
566 comptime printLineFromFile: var,566 comptime printLineFromFile: var,
567) !void {567) !void {
568 tty_config.setColor(out_stream, .White);568 noasync {
569 tty_config.setColor(out_stream, .White);
569570
570 if (line_info) |*li| {571 if (line_info) |*li| {
571 try noasync out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column });572 try out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column });
572 } else {573 } else {
573 try noasync out_stream.write("???:?:?");574 try out_stream.writeAll("???:?:?");
574 }575 }
575576
576 tty_config.setColor(out_stream, .Reset);577 tty_config.setColor(out_stream, .Reset);
577 try noasync out_stream.write(": ");578 try out_stream.writeAll(": ");
578 tty_config.setColor(out_stream, .Dim);579 tty_config.setColor(out_stream, .Dim);
579 try noasync out_stream.print("0x{x} in {} ({})", .{ address, symbol_name, compile_unit_name });580 try out_stream.print("0x{x} in {} ({})", .{ address, symbol_name, compile_unit_name });
580 tty_config.setColor(out_stream, .Reset);581 tty_config.setColor(out_stream, .Reset);
581 try noasync out_stream.write("\n");582 try out_stream.writeAll("\n");
582583
583 // Show the matching source code line if possible584 // Show the matching source code line if possible
584 if (line_info) |li| {585 if (line_info) |li| {
585 if (noasync printLineFromFile(out_stream, li)) {586 if (printLineFromFile(out_stream, li)) {
586 if (li.column > 0) {587 if (li.column > 0) {
587 // The caret already takes one char588 // The caret already takes one char
588 const space_needed = @intCast(usize, li.column - 1);589 const space_needed = @intCast(usize, li.column - 1);
589590
590 try noasync out_stream.writeByteNTimes(' ', space_needed);591 try out_stream.writeByteNTimes(' ', space_needed);
591 tty_config.setColor(out_stream, .Green);592 tty_config.setColor(out_stream, .Green);
592 try noasync out_stream.write("^");593 try out_stream.writeAll("^");
593 tty_config.setColor(out_stream, .Reset);594 tty_config.setColor(out_stream, .Reset);
595 }
596 try out_stream.writeAll("\n");
597 } else |err| switch (err) {
598 error.EndOfFile, error.FileNotFound => {},
599 error.BadPathName => {},
600 else => return err,
594 }601 }
595 try noasync out_stream.write("\n");
596 } else |err| switch (err) {
597 error.EndOfFile, error.FileNotFound => {},
598 error.BadPathName => {},
599 else => return err,
600 }602 }
601 }603 }
602}604}
...@@ -609,21 +611,21 @@ pub const OpenSelfDebugInfoError = error{...@@ -609,21 +611,21 @@ pub const OpenSelfDebugInfoError = error{
609};611};
610612
611/// TODO resources https://github.com/ziglang/zig/issues/4353613/// TODO resources https://github.com/ziglang/zig/issues/4353
612/// TODO once https://github.com/ziglang/zig/issues/3157 is fully implemented,
613/// make this `noasync fn` and remove the individual noasync calls.
614pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {614pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {
615 if (builtin.strip_debug_info)615 noasync {
616 return error.MissingDebugInfo;616 if (builtin.strip_debug_info)
617 if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {617 return error.MissingDebugInfo;
618 return noasync root.os.debug.openSelfDebugInfo(allocator);618 if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {
619 }619 return root.os.debug.openSelfDebugInfo(allocator);
620 switch (builtin.os.tag) {620 }
621 .linux,621 switch (builtin.os.tag) {
622 .freebsd,622 .linux,
623 .macosx,623 .freebsd,
624 .windows,624 .macosx,
625 => return DebugInfo.init(allocator),625 .windows,
626 else => @compileError("openSelfDebugInfo unsupported for this platform"),626 => return DebugInfo.init(allocator),
627 else => @compileError("openSelfDebugInfo unsupported for this platform"),
628 }
627 }629 }
628}630}
629631
...@@ -654,11 +656,11 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -654,11 +656,11 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
654 try di.pdb.openFile(di.coff, path);656 try di.pdb.openFile(di.coff, path);
655657
656 var pdb_stream = di.pdb.getStream(pdb.StreamType.Pdb) orelse return error.InvalidDebugInfo;658 var pdb_stream = di.pdb.getStream(pdb.StreamType.Pdb) orelse return error.InvalidDebugInfo;
657 const version = try pdb_stream.stream.readIntLittle(u32);659 const version = try pdb_stream.inStream().readIntLittle(u32);
658 const signature = try pdb_stream.stream.readIntLittle(u32);660 const signature = try pdb_stream.inStream().readIntLittle(u32);
659 const age = try pdb_stream.stream.readIntLittle(u32);661 const age = try pdb_stream.inStream().readIntLittle(u32);
660 var guid: [16]u8 = undefined;662 var guid: [16]u8 = undefined;
661 try pdb_stream.stream.readNoEof(&guid);663 try pdb_stream.inStream().readNoEof(&guid);
662 if (version != 20000404) // VC70, only value observed by LLVM team664 if (version != 20000404) // VC70, only value observed by LLVM team
663 return error.UnknownPDBVersion;665 return error.UnknownPDBVersion;
664 if (!mem.eql(u8, &di.coff.guid, &guid) or di.coff.age != age)666 if (!mem.eql(u8, &di.coff.guid, &guid) or di.coff.age != age)
...@@ -666,9 +668,9 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -666,9 +668,9 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
666 // We validated the executable and pdb match.668 // We validated the executable and pdb match.
667669
668 const string_table_index = str_tab_index: {670 const string_table_index = str_tab_index: {
669 const name_bytes_len = try pdb_stream.stream.readIntLittle(u32);671 const name_bytes_len = try pdb_stream.inStream().readIntLittle(u32);
670 const name_bytes = try allocator.alloc(u8, name_bytes_len);672 const name_bytes = try allocator.alloc(u8, name_bytes_len);
671 try pdb_stream.stream.readNoEof(name_bytes);673 try pdb_stream.inStream().readNoEof(name_bytes);
672674
673 const HashTableHeader = packed struct {675 const HashTableHeader = packed struct {
674 Size: u32,676 Size: u32,
...@@ -678,17 +680,17 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -678,17 +680,17 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
678 return cap * 2 / 3 + 1;680 return cap * 2 / 3 + 1;
679 }681 }
680 };682 };
681 const hash_tbl_hdr = try pdb_stream.stream.readStruct(HashTableHeader);683 const hash_tbl_hdr = try pdb_stream.inStream().readStruct(HashTableHeader);
682 if (hash_tbl_hdr.Capacity == 0)684 if (hash_tbl_hdr.Capacity == 0)
683 return error.InvalidDebugInfo;685 return error.InvalidDebugInfo;
684686
685 if (hash_tbl_hdr.Size > HashTableHeader.maxLoad(hash_tbl_hdr.Capacity))687 if (hash_tbl_hdr.Size > HashTableHeader.maxLoad(hash_tbl_hdr.Capacity))
686 return error.InvalidDebugInfo;688 return error.InvalidDebugInfo;
687689
688 const present = try readSparseBitVector(&pdb_stream.stream, allocator);690 const present = try readSparseBitVector(&pdb_stream.inStream(), allocator);
689 if (present.len != hash_tbl_hdr.Size)691 if (present.len != hash_tbl_hdr.Size)
690 return error.InvalidDebugInfo;692 return error.InvalidDebugInfo;
691 const deleted = try readSparseBitVector(&pdb_stream.stream, allocator);693 const deleted = try readSparseBitVector(&pdb_stream.inStream(), allocator);
692694
693 const Bucket = struct {695 const Bucket = struct {
694 first: u32,696 first: u32,
...@@ -696,8 +698,8 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -696,8 +698,8 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
696 };698 };
697 const bucket_list = try allocator.alloc(Bucket, present.len);699 const bucket_list = try allocator.alloc(Bucket, present.len);
698 for (present) |_| {700 for (present) |_| {
699 const name_offset = try pdb_stream.stream.readIntLittle(u32);701 const name_offset = try pdb_stream.inStream().readIntLittle(u32);
700 const name_index = try pdb_stream.stream.readIntLittle(u32);702 const name_index = try pdb_stream.inStream().readIntLittle(u32);
701 const name = mem.toSlice(u8, @ptrCast([*:0]u8, name_bytes.ptr + name_offset));703 const name = mem.toSlice(u8, @ptrCast([*:0]u8, name_bytes.ptr + name_offset));
702 if (mem.eql(u8, name, "/names")) {704 if (mem.eql(u8, name, "/names")) {
703 break :str_tab_index name_index;705 break :str_tab_index name_index;
...@@ -712,7 +714,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -712,7 +714,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
712 const dbi = di.pdb.dbi;714 const dbi = di.pdb.dbi;
713715
714 // Dbi Header716 // Dbi Header
715 const dbi_stream_header = try dbi.stream.readStruct(pdb.DbiStreamHeader);717 const dbi_stream_header = try dbi.inStream().readStruct(pdb.DbiStreamHeader);
716 if (dbi_stream_header.VersionHeader != 19990903) // V70, only value observed by LLVM team718 if (dbi_stream_header.VersionHeader != 19990903) // V70, only value observed by LLVM team
717 return error.UnknownPDBVersion;719 return error.UnknownPDBVersion;
718 if (dbi_stream_header.Age != age)720 if (dbi_stream_header.Age != age)
...@@ -726,7 +728,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -726,7 +728,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
726 // Module Info Substream728 // Module Info Substream
727 var mod_info_offset: usize = 0;729 var mod_info_offset: usize = 0;
728 while (mod_info_offset != mod_info_size) {730 while (mod_info_offset != mod_info_size) {
729 const mod_info = try dbi.stream.readStruct(pdb.ModInfo);731 const mod_info = try dbi.inStream().readStruct(pdb.ModInfo);
730 var this_record_len: usize = @sizeOf(pdb.ModInfo);732 var this_record_len: usize = @sizeOf(pdb.ModInfo);
731733
732 const module_name = try dbi.readNullTermString(allocator);734 const module_name = try dbi.readNullTermString(allocator);
...@@ -764,14 +766,14 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !...@@ -764,14 +766,14 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
764 var sect_contribs = ArrayList(pdb.SectionContribEntry).init(allocator);766 var sect_contribs = ArrayList(pdb.SectionContribEntry).init(allocator);
765 var sect_cont_offset: usize = 0;767 var sect_cont_offset: usize = 0;
766 if (section_contrib_size != 0) {768 if (section_contrib_size != 0) {
767 const ver = @intToEnum(pdb.SectionContrSubstreamVersion, try dbi.stream.readIntLittle(u32));769 const ver = @intToEnum(pdb.SectionContrSubstreamVersion, try dbi.inStream().readIntLittle(u32));
768 if (ver != pdb.SectionContrSubstreamVersion.Ver60)770 if (ver != pdb.SectionContrSubstreamVersion.Ver60)
769 return error.InvalidDebugInfo;771 return error.InvalidDebugInfo;
770 sect_cont_offset += @sizeOf(u32);772 sect_cont_offset += @sizeOf(u32);
771 }773 }
772 while (sect_cont_offset != section_contrib_size) {774 while (sect_cont_offset != section_contrib_size) {
773 const entry = try sect_contribs.addOne();775 const entry = try sect_contribs.addOne();
774 entry.* = try dbi.stream.readStruct(pdb.SectionContribEntry);776 entry.* = try dbi.inStream().readStruct(pdb.SectionContribEntry);
775 sect_cont_offset += @sizeOf(pdb.SectionContribEntry);777 sect_cont_offset += @sizeOf(pdb.SectionContribEntry);
776778
777 if (sect_cont_offset > section_contrib_size)779 if (sect_cont_offset > section_contrib_size)
...@@ -808,45 +810,71 @@ fn chopSlice(ptr: []const u8, offset: u64, size: u64) ![]const u8 {...@@ -808,45 +810,71 @@ fn chopSlice(ptr: []const u8, offset: u64, size: u64) ![]const u8 {
808810
809/// TODO resources https://github.com/ziglang/zig/issues/4353811/// TODO resources https://github.com/ziglang/zig/issues/4353
810pub fn openElfDebugInfo(allocator: *mem.Allocator, elf_file_path: []const u8) !ModuleDebugInfo {812pub fn openElfDebugInfo(allocator: *mem.Allocator, elf_file_path: []const u8) !ModuleDebugInfo {
811 const mapped_mem = try mapWholeFile(elf_file_path);813 noasync {
812814 const mapped_mem = try mapWholeFile(elf_file_path);
813 var seekable_stream = io.SliceSeekableInStream.init(mapped_mem);815 const hdr = @ptrCast(*const elf.Ehdr, &mapped_mem[0]);
814 var efile = try noasync elf.Elf.openStream(816 if (!mem.eql(u8, hdr.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
815 allocator,817 if (hdr.e_ident[elf.EI_VERSION] != 1) return error.InvalidElfVersion;
816 @ptrCast(*DW.DwarfSeekableStream, &seekable_stream.seekable_stream),818
817 @ptrCast(*DW.DwarfInStream, &seekable_stream.stream),819 const endian: builtin.Endian = switch (hdr.e_ident[elf.EI_DATA]) {
818 );820 elf.ELFDATA2LSB => .Little,
819 defer noasync efile.close();821 elf.ELFDATA2MSB => .Big,
822 else => return error.InvalidElfEndian,
823 };
824 assert(endian == std.builtin.endian); // this is our own debug info
825
826 const shoff = hdr.e_shoff;
827 const str_section_off = shoff + @as(u64, hdr.e_shentsize) * @as(u64, hdr.e_shstrndx);
828 const str_shdr = @ptrCast(
829 *const elf.Shdr,
830 @alignCast(@alignOf(elf.Shdr), &mapped_mem[try math.cast(usize, str_section_off)]),
831 );
832 const header_strings = mapped_mem[str_shdr.sh_offset .. str_shdr.sh_offset + str_shdr.sh_size];
833 const shdrs = @ptrCast(
834 [*]const elf.Shdr,
835 @alignCast(@alignOf(elf.Shdr), &mapped_mem[shoff]),
836 )[0..hdr.e_shnum];
837
838 var opt_debug_info: ?[]const u8 = null;
839 var opt_debug_abbrev: ?[]const u8 = null;
840 var opt_debug_str: ?[]const u8 = null;
841 var opt_debug_line: ?[]const u8 = null;
842 var opt_debug_ranges: ?[]const u8 = null;
843
844 for (shdrs) |*shdr| {
845 if (shdr.sh_type == elf.SHT_NULL) continue;
846
847 const name = std.mem.span(@ptrCast([*:0]const u8, header_strings[shdr.sh_name..].ptr));
848 if (mem.eql(u8, name, ".debug_info")) {
849 opt_debug_info = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size);
850 } else if (mem.eql(u8, name, ".debug_abbrev")) {
851 opt_debug_abbrev = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size);
852 } else if (mem.eql(u8, name, ".debug_str")) {
853 opt_debug_str = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size);
854 } else if (mem.eql(u8, name, ".debug_line")) {
855 opt_debug_line = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size);
856 } else if (mem.eql(u8, name, ".debug_ranges")) {
857 opt_debug_ranges = try chopSlice(mapped_mem, shdr.sh_offset, shdr.sh_size);
858 }
859 }
820860
821 const debug_info = (try noasync efile.findSection(".debug_info")) orelse861 var di = DW.DwarfInfo{
822 return error.MissingDebugInfo;862 .endian = endian,
823 const debug_abbrev = (try noasync efile.findSection(".debug_abbrev")) orelse863 .debug_info = opt_debug_info orelse return error.MissingDebugInfo,
824 return error.MissingDebugInfo;864 .debug_abbrev = opt_debug_abbrev orelse return error.MissingDebugInfo,
825 const debug_str = (try noasync efile.findSection(".debug_str")) orelse865 .debug_str = opt_debug_str orelse return error.MissingDebugInfo,
826 return error.MissingDebugInfo;866 .debug_line = opt_debug_line orelse return error.MissingDebugInfo,
827 const debug_line = (try noasync efile.findSection(".debug_line")) orelse867 .debug_ranges = opt_debug_ranges,
828 return error.MissingDebugInfo;868 };
829 const opt_debug_ranges = try noasync efile.findSection(".debug_ranges");
830
831 var di = DW.DwarfInfo{
832 .endian = efile.endian,
833 .debug_info = try chopSlice(mapped_mem, debug_info.sh_offset, debug_info.sh_size),
834 .debug_abbrev = try chopSlice(mapped_mem, debug_abbrev.sh_offset, debug_abbrev.sh_size),
835 .debug_str = try chopSlice(mapped_mem, debug_str.sh_offset, debug_str.sh_size),
836 .debug_line = try chopSlice(mapped_mem, debug_line.sh_offset, debug_line.sh_size),
837 .debug_ranges = if (opt_debug_ranges) |debug_ranges|
838 try chopSlice(mapped_mem, debug_ranges.sh_offset, debug_ranges.sh_size)
839 else
840 null,
841 };
842869
843 try noasync DW.openDwarfDebugInfo(&di, allocator);870 try DW.openDwarfDebugInfo(&di, allocator);
844871
845 return ModuleDebugInfo{872 return ModuleDebugInfo{
846 .base_address = undefined,873 .base_address = undefined,
847 .dwarf = di,874 .dwarf = di,
848 .mapped_memory = mapped_mem,875 .mapped_memory = mapped_mem,
849 };876 };
877 }
850}878}
851879
852/// TODO resources https://github.com/ziglang/zig/issues/4353880/// TODO resources https://github.com/ziglang/zig/issues/4353
...@@ -936,7 +964,9 @@ fn openMachODebugInfo(allocator: *mem.Allocator, macho_file_path: []const u8) !M...@@ -936,7 +964,9 @@ fn openMachODebugInfo(allocator: *mem.Allocator, macho_file_path: []const u8) !M
936}964}
937965
938fn printLineFromFileAnyOs(out_stream: var, line_info: LineInfo) !void {966fn printLineFromFileAnyOs(out_stream: var, line_info: LineInfo) !void {
939 var f = try fs.cwd().openFile(line_info.file_name, .{});967 // Need this to always block even in async I/O mode, because this could potentially
968 // be called from e.g. the event loop code crashing.
969 var f = try fs.cwd().openFile(line_info.file_name, .{ .always_blocking = true });
940 defer f.close();970 defer f.close();
941 // TODO fstat and make sure that the file has the correct size971 // TODO fstat and make sure that the file has the correct size
942972
...@@ -982,22 +1012,24 @@ const MachoSymbol = struct {...@@ -982,22 +1012,24 @@ const MachoSymbol = struct {
982 }1012 }
983};1013};
9841014
985fn mapWholeFile(path: []const u8) ![]const u8 {1015fn mapWholeFile(path: []const u8) ![]align(mem.page_size) const u8 {
986 const file = try noasync fs.openFileAbsolute(path, .{ .always_blocking = true });1016 noasync {
987 defer noasync file.close();1017 const file = try fs.openFileAbsolute(path, .{ .always_blocking = true });
9881018 defer file.close();
989 const file_len = try math.cast(usize, try file.getEndPos());
990 const mapped_mem = try os.mmap(
991 null,
992 file_len,
993 os.PROT_READ,
994 os.MAP_SHARED,
995 file.handle,
996 0,
997 );
998 errdefer os.munmap(mapped_mem);
9991019
1000 return mapped_mem;1020 const file_len = try math.cast(usize, try file.getEndPos());
1021 const mapped_mem = try os.mmap(
1022 null,
1023 file_len,
1024 os.PROT_READ,
1025 os.MAP_SHARED,
1026 file.handle,
1027 0,
1028 );
1029 errdefer os.munmap(mapped_mem);
1030
1031 return mapped_mem;
1032 }
1001}1033}
10021034
1003pub const DebugInfo = struct {1035pub const DebugInfo = struct {
lib/std/debug/leb128.zig+12-12
...@@ -121,18 +121,18 @@ pub fn readILEB128Mem(comptime T: type, ptr: *[*]const u8) !T {...@@ -121,18 +121,18 @@ pub fn readILEB128Mem(comptime T: type, ptr: *[*]const u8) !T {
121}121}
122122
123fn test_read_stream_ileb128(comptime T: type, encoded: []const u8) !T {123fn test_read_stream_ileb128(comptime T: type, encoded: []const u8) !T {
124 var in_stream = std.io.SliceInStream.init(encoded);124 var in_stream = std.io.fixedBufferStream(encoded);
125 return try readILEB128(T, &in_stream.stream);125 return try readILEB128(T, in_stream.inStream());
126}126}
127127
128fn test_read_stream_uleb128(comptime T: type, encoded: []const u8) !T {128fn test_read_stream_uleb128(comptime T: type, encoded: []const u8) !T {
129 var in_stream = std.io.SliceInStream.init(encoded);129 var in_stream = std.io.fixedBufferStream(encoded);
130 return try readULEB128(T, &in_stream.stream);130 return try readULEB128(T, in_stream.inStream());
131}131}
132132
133fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {133fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
134 var in_stream = std.io.SliceInStream.init(encoded);134 var in_stream = std.io.fixedBufferStream(encoded);
135 const v1 = readILEB128(T, &in_stream.stream);135 const v1 = readILEB128(T, in_stream.inStream());
136 var in_ptr = encoded.ptr;136 var in_ptr = encoded.ptr;
137 const v2 = readILEB128Mem(T, &in_ptr);137 const v2 = readILEB128Mem(T, &in_ptr);
138 testing.expectEqual(v1, v2);138 testing.expectEqual(v1, v2);
...@@ -140,8 +140,8 @@ fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {...@@ -140,8 +140,8 @@ fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
140}140}
141141
142fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {142fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
143 var in_stream = std.io.SliceInStream.init(encoded);143 var in_stream = std.io.fixedBufferStream(encoded);
144 const v1 = readULEB128(T, &in_stream.stream);144 const v1 = readULEB128(T, in_stream.inStream());
145 var in_ptr = encoded.ptr;145 var in_ptr = encoded.ptr;
146 const v2 = readULEB128Mem(T, &in_ptr);146 const v2 = readULEB128Mem(T, &in_ptr);
147 testing.expectEqual(v1, v2);147 testing.expectEqual(v1, v2);
...@@ -149,22 +149,22 @@ fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {...@@ -149,22 +149,22 @@ fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
149}149}
150150
151fn test_read_ileb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) void {151fn test_read_ileb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) void {
152 var in_stream = std.io.SliceInStream.init(encoded);152 var in_stream = std.io.fixedBufferStream(encoded);
153 var in_ptr = encoded.ptr;153 var in_ptr = encoded.ptr;
154 var i: usize = 0;154 var i: usize = 0;
155 while (i < N) : (i += 1) {155 while (i < N) : (i += 1) {
156 const v1 = readILEB128(T, &in_stream.stream);156 const v1 = readILEB128(T, in_stream.inStream());
157 const v2 = readILEB128Mem(T, &in_ptr);157 const v2 = readILEB128Mem(T, &in_ptr);
158 testing.expectEqual(v1, v2);158 testing.expectEqual(v1, v2);
159 }159 }
160}160}
161161
162fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) void {162fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u8) void {
163 var in_stream = std.io.SliceInStream.init(encoded);163 var in_stream = std.io.fixedBufferStream(encoded);
164 var in_ptr = encoded.ptr;164 var in_ptr = encoded.ptr;
165 var i: usize = 0;165 var i: usize = 0;
166 while (i < N) : (i += 1) {166 while (i < N) : (i += 1) {
167 const v1 = readULEB128(T, &in_stream.stream);167 const v1 = readULEB128(T, in_stream.inStream());
168 const v2 = readULEB128Mem(T, &in_ptr);168 const v2 = readULEB128Mem(T, &in_ptr);
169 testing.expectEqual(v1, v2);169 testing.expectEqual(v1, v2);
170 }170 }
lib/std/dwarf.zig+84-77
...@@ -11,9 +11,6 @@ const ArrayList = std.ArrayList;...@@ -11,9 +11,6 @@ const ArrayList = std.ArrayList;
1111
12usingnamespace @import("dwarf_bits.zig");12usingnamespace @import("dwarf_bits.zig");
1313
14pub const DwarfSeekableStream = io.SeekableStream(anyerror, anyerror);
15pub const DwarfInStream = io.InStream(anyerror);
16
17const PcRange = struct {14const PcRange = struct {
18 start: u64,15 start: u64,
19 end: u64,16 end: u64,
...@@ -239,7 +236,7 @@ const LineNumberProgram = struct {...@@ -239,7 +236,7 @@ const LineNumberProgram = struct {
239 }236 }
240};237};
241238
242fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 {239fn readInitialLength(in_stream: var, is_64: *bool) !u64 {
243 const first_32_bits = try in_stream.readIntLittle(u32);240 const first_32_bits = try in_stream.readIntLittle(u32);
244 is_64.* = (first_32_bits == 0xffffffff);241 is_64.* = (first_32_bits == 0xffffffff);
245 if (is_64.*) {242 if (is_64.*) {
...@@ -414,40 +411,42 @@ pub const DwarfInfo = struct {...@@ -414,40 +411,42 @@ pub const DwarfInfo = struct {
414 }411 }
415412
416 fn scanAllFunctions(di: *DwarfInfo) !void {413 fn scanAllFunctions(di: *DwarfInfo) !void {
417 var s = io.SliceSeekableInStream.init(di.debug_info);414 var stream = io.fixedBufferStream(di.debug_info);
415 const in = &stream.inStream();
416 const seekable = &stream.seekableStream();
418 var this_unit_offset: u64 = 0;417 var this_unit_offset: u64 = 0;
419418
420 while (this_unit_offset < try s.seekable_stream.getEndPos()) {419 while (this_unit_offset < try seekable.getEndPos()) {
421 s.seekable_stream.seekTo(this_unit_offset) catch |err| switch (err) {420 seekable.seekTo(this_unit_offset) catch |err| switch (err) {
422 error.EndOfStream => unreachable,421 error.EndOfStream => unreachable,
423 else => return err,422 else => return err,
424 };423 };
425424
426 var is_64: bool = undefined;425 var is_64: bool = undefined;
427 const unit_length = try readInitialLength(@TypeOf(s.stream.readFn).ReturnType.ErrorSet, &s.stream, &is_64);426 const unit_length = try readInitialLength(in, &is_64);
428 if (unit_length == 0) return;427 if (unit_length == 0) return;
429 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));428 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
430429
431 const version = try s.stream.readInt(u16, di.endian);430 const version = try in.readInt(u16, di.endian);
432 if (version < 2 or version > 5) return error.InvalidDebugInfo;431 if (version < 2 or version > 5) return error.InvalidDebugInfo;
433432
434 const debug_abbrev_offset = if (is_64) try s.stream.readInt(u64, di.endian) else try s.stream.readInt(u32, di.endian);433 const debug_abbrev_offset = if (is_64) try in.readInt(u64, di.endian) else try in.readInt(u32, di.endian);
435434
436 const address_size = try s.stream.readByte();435 const address_size = try in.readByte();
437 if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo;436 if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo;
438437
439 const compile_unit_pos = try s.seekable_stream.getPos();438 const compile_unit_pos = try seekable.getPos();
440 const abbrev_table = try di.getAbbrevTable(debug_abbrev_offset);439 const abbrev_table = try di.getAbbrevTable(debug_abbrev_offset);
441440
442 try s.seekable_stream.seekTo(compile_unit_pos);441 try seekable.seekTo(compile_unit_pos);
443442
444 const next_unit_pos = this_unit_offset + next_offset;443 const next_unit_pos = this_unit_offset + next_offset;
445444
446 while ((try s.seekable_stream.getPos()) < next_unit_pos) {445 while ((try seekable.getPos()) < next_unit_pos) {
447 const die_obj = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse continue;446 const die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse continue;
448 defer die_obj.attrs.deinit();447 defer die_obj.attrs.deinit();
449448
450 const after_die_offset = try s.seekable_stream.getPos();449 const after_die_offset = try seekable.getPos();
451450
452 switch (die_obj.tag_id) {451 switch (die_obj.tag_id) {
453 TAG_subprogram, TAG_inlined_subroutine, TAG_subroutine, TAG_entry_point => {452 TAG_subprogram, TAG_inlined_subroutine, TAG_subroutine, TAG_entry_point => {
...@@ -463,14 +462,14 @@ pub const DwarfInfo = struct {...@@ -463,14 +462,14 @@ pub const DwarfInfo = struct {
463 // Follow the DIE it points to and repeat462 // Follow the DIE it points to and repeat
464 const ref_offset = try this_die_obj.getAttrRef(AT_abstract_origin);463 const ref_offset = try this_die_obj.getAttrRef(AT_abstract_origin);
465 if (ref_offset > next_offset) return error.InvalidDebugInfo;464 if (ref_offset > next_offset) return error.InvalidDebugInfo;
466 try s.seekable_stream.seekTo(this_unit_offset + ref_offset);465 try seekable.seekTo(this_unit_offset + ref_offset);
467 this_die_obj = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;466 this_die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
468 } else if (this_die_obj.getAttr(AT_specification)) |ref| {467 } else if (this_die_obj.getAttr(AT_specification)) |ref| {
469 // Follow the DIE it points to and repeat468 // Follow the DIE it points to and repeat
470 const ref_offset = try this_die_obj.getAttrRef(AT_specification);469 const ref_offset = try this_die_obj.getAttrRef(AT_specification);
471 if (ref_offset > next_offset) return error.InvalidDebugInfo;470 if (ref_offset > next_offset) return error.InvalidDebugInfo;
472 try s.seekable_stream.seekTo(this_unit_offset + ref_offset);471 try seekable.seekTo(this_unit_offset + ref_offset);
473 this_die_obj = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;472 this_die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
474 } else {473 } else {
475 break :x null;474 break :x null;
476 }475 }
...@@ -511,7 +510,7 @@ pub const DwarfInfo = struct {...@@ -511,7 +510,7 @@ pub const DwarfInfo = struct {
511 else => {},510 else => {},
512 }511 }
513512
514 try s.seekable_stream.seekTo(after_die_offset);513 try seekable.seekTo(after_die_offset);
515 }514 }
516515
517 this_unit_offset += next_offset;516 this_unit_offset += next_offset;
...@@ -519,35 +518,37 @@ pub const DwarfInfo = struct {...@@ -519,35 +518,37 @@ pub const DwarfInfo = struct {
519 }518 }
520519
521 fn scanAllCompileUnits(di: *DwarfInfo) !void {520 fn scanAllCompileUnits(di: *DwarfInfo) !void {
522 var s = io.SliceSeekableInStream.init(di.debug_info);521 var stream = io.fixedBufferStream(di.debug_info);
522 const in = &stream.inStream();
523 const seekable = &stream.seekableStream();
523 var this_unit_offset: u64 = 0;524 var this_unit_offset: u64 = 0;
524525
525 while (this_unit_offset < try s.seekable_stream.getEndPos()) {526 while (this_unit_offset < try seekable.getEndPos()) {
526 s.seekable_stream.seekTo(this_unit_offset) catch |err| switch (err) {527 seekable.seekTo(this_unit_offset) catch |err| switch (err) {
527 error.EndOfStream => unreachable,528 error.EndOfStream => unreachable,
528 else => return err,529 else => return err,
529 };530 };
530531
531 var is_64: bool = undefined;532 var is_64: bool = undefined;
532 const unit_length = try readInitialLength(@TypeOf(s.stream.readFn).ReturnType.ErrorSet, &s.stream, &is_64);533 const unit_length = try readInitialLength(in, &is_64);
533 if (unit_length == 0) return;534 if (unit_length == 0) return;
534 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));535 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
535536
536 const version = try s.stream.readInt(u16, di.endian);537 const version = try in.readInt(u16, di.endian);
537 if (version < 2 or version > 5) return error.InvalidDebugInfo;538 if (version < 2 or version > 5) return error.InvalidDebugInfo;
538539
539 const debug_abbrev_offset = if (is_64) try s.stream.readInt(u64, di.endian) else try s.stream.readInt(u32, di.endian);540 const debug_abbrev_offset = if (is_64) try in.readInt(u64, di.endian) else try in.readInt(u32, di.endian);
540541
541 const address_size = try s.stream.readByte();542 const address_size = try in.readByte();
542 if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo;543 if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo;
543544
544 const compile_unit_pos = try s.seekable_stream.getPos();545 const compile_unit_pos = try seekable.getPos();
545 const abbrev_table = try di.getAbbrevTable(debug_abbrev_offset);546 const abbrev_table = try di.getAbbrevTable(debug_abbrev_offset);
546547
547 try s.seekable_stream.seekTo(compile_unit_pos);548 try seekable.seekTo(compile_unit_pos);
548549
549 const compile_unit_die = try di.allocator().create(Die);550 const compile_unit_die = try di.allocator().create(Die);
550 compile_unit_die.* = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;551 compile_unit_die.* = (try di.parseDie(in, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
551552
552 if (compile_unit_die.tag_id != TAG_compile_unit) return error.InvalidDebugInfo;553 if (compile_unit_die.tag_id != TAG_compile_unit) return error.InvalidDebugInfo;
553554
...@@ -593,7 +594,9 @@ pub const DwarfInfo = struct {...@@ -593,7 +594,9 @@ pub const DwarfInfo = struct {
593 }594 }
594 if (di.debug_ranges) |debug_ranges| {595 if (di.debug_ranges) |debug_ranges| {
595 if (compile_unit.die.getAttrSecOffset(AT_ranges)) |ranges_offset| {596 if (compile_unit.die.getAttrSecOffset(AT_ranges)) |ranges_offset| {
596 var s = io.SliceSeekableInStream.init(debug_ranges);597 var stream = io.fixedBufferStream(debug_ranges);
598 const in = &stream.inStream();
599 const seekable = &stream.seekableStream();
597600
598 // All the addresses in the list are relative to the value601 // All the addresses in the list are relative to the value
599 // specified by DW_AT_low_pc or to some other value encoded602 // specified by DW_AT_low_pc or to some other value encoded
...@@ -604,11 +607,11 @@ pub const DwarfInfo = struct {...@@ -604,11 +607,11 @@ pub const DwarfInfo = struct {
604 else => return err,607 else => return err,
605 };608 };
606609
607 try s.seekable_stream.seekTo(ranges_offset);610 try seekable.seekTo(ranges_offset);
608611
609 while (true) {612 while (true) {
610 const begin_addr = try s.stream.readIntLittle(usize);613 const begin_addr = try in.readIntLittle(usize);
611 const end_addr = try s.stream.readIntLittle(usize);614 const end_addr = try in.readIntLittle(usize);
612 if (begin_addr == 0 and end_addr == 0) {615 if (begin_addr == 0 and end_addr == 0) {
613 break;616 break;
614 }617 }
...@@ -646,25 +649,27 @@ pub const DwarfInfo = struct {...@@ -646,25 +649,27 @@ pub const DwarfInfo = struct {
646 }649 }
647650
648 fn parseAbbrevTable(di: *DwarfInfo, offset: u64) !AbbrevTable {651 fn parseAbbrevTable(di: *DwarfInfo, offset: u64) !AbbrevTable {
649 var s = io.SliceSeekableInStream.init(di.debug_abbrev);652 var stream = io.fixedBufferStream(di.debug_abbrev);
653 const in = &stream.inStream();
654 const seekable = &stream.seekableStream();
650655
651 try s.seekable_stream.seekTo(offset);656 try seekable.seekTo(offset);
652 var result = AbbrevTable.init(di.allocator());657 var result = AbbrevTable.init(di.allocator());
653 errdefer result.deinit();658 errdefer result.deinit();
654 while (true) {659 while (true) {
655 const abbrev_code = try leb.readULEB128(u64, &s.stream);660 const abbrev_code = try leb.readULEB128(u64, in);
656 if (abbrev_code == 0) return result;661 if (abbrev_code == 0) return result;
657 try result.append(AbbrevTableEntry{662 try result.append(AbbrevTableEntry{
658 .abbrev_code = abbrev_code,663 .abbrev_code = abbrev_code,
659 .tag_id = try leb.readULEB128(u64, &s.stream),664 .tag_id = try leb.readULEB128(u64, in),
660 .has_children = (try s.stream.readByte()) == CHILDREN_yes,665 .has_children = (try in.readByte()) == CHILDREN_yes,
661 .attrs = ArrayList(AbbrevAttr).init(di.allocator()),666 .attrs = ArrayList(AbbrevAttr).init(di.allocator()),
662 });667 });
663 const attrs = &result.items[result.len - 1].attrs;668 const attrs = &result.items[result.len - 1].attrs;
664669
665 while (true) {670 while (true) {
666 const attr_id = try leb.readULEB128(u64, &s.stream);671 const attr_id = try leb.readULEB128(u64, in);
667 const form_id = try leb.readULEB128(u64, &s.stream);672 const form_id = try leb.readULEB128(u64, in);
668 if (attr_id == 0 and form_id == 0) break;673 if (attr_id == 0 and form_id == 0) break;
669 try attrs.append(AbbrevAttr{674 try attrs.append(AbbrevAttr{
670 .attr_id = attr_id,675 .attr_id = attr_id,
...@@ -695,42 +700,44 @@ pub const DwarfInfo = struct {...@@ -695,42 +700,44 @@ pub const DwarfInfo = struct {
695 }700 }
696701
697 fn getLineNumberInfo(di: *DwarfInfo, compile_unit: CompileUnit, target_address: usize) !debug.LineInfo {702 fn getLineNumberInfo(di: *DwarfInfo, compile_unit: CompileUnit, target_address: usize) !debug.LineInfo {
698 var s = io.SliceSeekableInStream.init(di.debug_line);703 var stream = io.fixedBufferStream(di.debug_line);
704 const in = &stream.inStream();
705 const seekable = &stream.seekableStream();
699706
700 const compile_unit_cwd = try compile_unit.die.getAttrString(di, AT_comp_dir);707 const compile_unit_cwd = try compile_unit.die.getAttrString(di, AT_comp_dir);
701 const line_info_offset = try compile_unit.die.getAttrSecOffset(AT_stmt_list);708 const line_info_offset = try compile_unit.die.getAttrSecOffset(AT_stmt_list);
702709
703 try s.seekable_stream.seekTo(line_info_offset);710 try seekable.seekTo(line_info_offset);
704711
705 var is_64: bool = undefined;712 var is_64: bool = undefined;
706 const unit_length = try readInitialLength(@TypeOf(s.stream.readFn).ReturnType.ErrorSet, &s.stream, &is_64);713 const unit_length = try readInitialLength(in, &is_64);
707 if (unit_length == 0) {714 if (unit_length == 0) {
708 return error.MissingDebugInfo;715 return error.MissingDebugInfo;
709 }716 }
710 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));717 const next_offset = unit_length + (if (is_64) @as(usize, 12) else @as(usize, 4));
711718
712 const version = try s.stream.readInt(u16, di.endian);719 const version = try in.readInt(u16, di.endian);
713 // TODO support 3 and 5720 // TODO support 3 and 5
714 if (version != 2 and version != 4) return error.InvalidDebugInfo;721 if (version != 2 and version != 4) return error.InvalidDebugInfo;
715722
716 const prologue_length = if (is_64) try s.stream.readInt(u64, di.endian) else try s.stream.readInt(u32, di.endian);723 const prologue_length = if (is_64) try in.readInt(u64, di.endian) else try in.readInt(u32, di.endian);
717 const prog_start_offset = (try s.seekable_stream.getPos()) + prologue_length;724 const prog_start_offset = (try seekable.getPos()) + prologue_length;
718725
719 const minimum_instruction_length = try s.stream.readByte();726 const minimum_instruction_length = try in.readByte();
720 if (minimum_instruction_length == 0) return error.InvalidDebugInfo;727 if (minimum_instruction_length == 0) return error.InvalidDebugInfo;
721728
722 if (version >= 4) {729 if (version >= 4) {
723 // maximum_operations_per_instruction730 // maximum_operations_per_instruction
724 _ = try s.stream.readByte();731 _ = try in.readByte();
725 }732 }
726733
727 const default_is_stmt = (try s.stream.readByte()) != 0;734 const default_is_stmt = (try in.readByte()) != 0;
728 const line_base = try s.stream.readByteSigned();735 const line_base = try in.readByteSigned();
729736
730 const line_range = try s.stream.readByte();737 const line_range = try in.readByte();
731 if (line_range == 0) return error.InvalidDebugInfo;738 if (line_range == 0) return error.InvalidDebugInfo;
732739
733 const opcode_base = try s.stream.readByte();740 const opcode_base = try in.readByte();
734741
735 const standard_opcode_lengths = try di.allocator().alloc(u8, opcode_base - 1);742 const standard_opcode_lengths = try di.allocator().alloc(u8, opcode_base - 1);
736 defer di.allocator().free(standard_opcode_lengths);743 defer di.allocator().free(standard_opcode_lengths);
...@@ -738,14 +745,14 @@ pub const DwarfInfo = struct {...@@ -738,14 +745,14 @@ pub const DwarfInfo = struct {
738 {745 {
739 var i: usize = 0;746 var i: usize = 0;
740 while (i < opcode_base - 1) : (i += 1) {747 while (i < opcode_base - 1) : (i += 1) {
741 standard_opcode_lengths[i] = try s.stream.readByte();748 standard_opcode_lengths[i] = try in.readByte();
742 }749 }
743 }750 }
744751
745 var include_directories = ArrayList([]const u8).init(di.allocator());752 var include_directories = ArrayList([]const u8).init(di.allocator());
746 try include_directories.append(compile_unit_cwd);753 try include_directories.append(compile_unit_cwd);
747 while (true) {754 while (true) {
748 const dir = try s.stream.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));755 const dir = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));
749 if (dir.len == 0) break;756 if (dir.len == 0) break;
750 try include_directories.append(dir);757 try include_directories.append(dir);
751 }758 }
...@@ -754,11 +761,11 @@ pub const DwarfInfo = struct {...@@ -754,11 +761,11 @@ pub const DwarfInfo = struct {
754 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);761 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);
755762
756 while (true) {763 while (true) {
757 const file_name = try s.stream.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));764 const file_name = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));
758 if (file_name.len == 0) break;765 if (file_name.len == 0) break;
759 const dir_index = try leb.readULEB128(usize, &s.stream);766 const dir_index = try leb.readULEB128(usize, in);
760 const mtime = try leb.readULEB128(usize, &s.stream);767 const mtime = try leb.readULEB128(usize, in);
761 const len_bytes = try leb.readULEB128(usize, &s.stream);768 const len_bytes = try leb.readULEB128(usize, in);
762 try file_entries.append(FileEntry{769 try file_entries.append(FileEntry{
763 .file_name = file_name,770 .file_name = file_name,
764 .dir_index = dir_index,771 .dir_index = dir_index,
...@@ -767,17 +774,17 @@ pub const DwarfInfo = struct {...@@ -767,17 +774,17 @@ pub const DwarfInfo = struct {
767 });774 });
768 }775 }
769776
770 try s.seekable_stream.seekTo(prog_start_offset);777 try seekable.seekTo(prog_start_offset);
771778
772 const next_unit_pos = line_info_offset + next_offset;779 const next_unit_pos = line_info_offset + next_offset;
773780
774 while ((try s.seekable_stream.getPos()) < next_unit_pos) {781 while ((try seekable.getPos()) < next_unit_pos) {
775 const opcode = try s.stream.readByte();782 const opcode = try in.readByte();
776783
777 if (opcode == LNS_extended_op) {784 if (opcode == LNS_extended_op) {
778 const op_size = try leb.readULEB128(u64, &s.stream);785 const op_size = try leb.readULEB128(u64, in);
779 if (op_size < 1) return error.InvalidDebugInfo;786 if (op_size < 1) return error.InvalidDebugInfo;
780 var sub_op = try s.stream.readByte();787 var sub_op = try in.readByte();
781 switch (sub_op) {788 switch (sub_op) {
782 LNE_end_sequence => {789 LNE_end_sequence => {
783 prog.end_sequence = true;790 prog.end_sequence = true;
...@@ -785,14 +792,14 @@ pub const DwarfInfo = struct {...@@ -785,14 +792,14 @@ pub const DwarfInfo = struct {
785 prog.reset();792 prog.reset();
786 },793 },
787 LNE_set_address => {794 LNE_set_address => {
788 const addr = try s.stream.readInt(usize, di.endian);795 const addr = try in.readInt(usize, di.endian);
789 prog.address = addr;796 prog.address = addr;
790 },797 },
791 LNE_define_file => {798 LNE_define_file => {
792 const file_name = try s.stream.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));799 const file_name = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));
793 const dir_index = try leb.readULEB128(usize, &s.stream);800 const dir_index = try leb.readULEB128(usize, in);
794 const mtime = try leb.readULEB128(usize, &s.stream);801 const mtime = try leb.readULEB128(usize, in);
795 const len_bytes = try leb.readULEB128(usize, &s.stream);802 const len_bytes = try leb.readULEB128(usize, in);
796 try file_entries.append(FileEntry{803 try file_entries.append(FileEntry{
797 .file_name = file_name,804 .file_name = file_name,
798 .dir_index = dir_index,805 .dir_index = dir_index,
...@@ -802,7 +809,7 @@ pub const DwarfInfo = struct {...@@ -802,7 +809,7 @@ pub const DwarfInfo = struct {
802 },809 },
803 else => {810 else => {
804 const fwd_amt = math.cast(isize, op_size - 1) catch return error.InvalidDebugInfo;811 const fwd_amt = math.cast(isize, op_size - 1) catch return error.InvalidDebugInfo;
805 try s.seekable_stream.seekBy(fwd_amt);812 try seekable.seekBy(fwd_amt);
806 },813 },
807 }814 }
808 } else if (opcode >= opcode_base) {815 } else if (opcode >= opcode_base) {
...@@ -821,19 +828,19 @@ pub const DwarfInfo = struct {...@@ -821,19 +828,19 @@ pub const DwarfInfo = struct {
821 prog.basic_block = false;828 prog.basic_block = false;
822 },829 },
823 LNS_advance_pc => {830 LNS_advance_pc => {
824 const arg = try leb.readULEB128(usize, &s.stream);831 const arg = try leb.readULEB128(usize, in);
825 prog.address += arg * minimum_instruction_length;832 prog.address += arg * minimum_instruction_length;
826 },833 },
827 LNS_advance_line => {834 LNS_advance_line => {
828 const arg = try leb.readILEB128(i64, &s.stream);835 const arg = try leb.readILEB128(i64, in);
829 prog.line += arg;836 prog.line += arg;
830 },837 },
831 LNS_set_file => {838 LNS_set_file => {
832 const arg = try leb.readULEB128(usize, &s.stream);839 const arg = try leb.readULEB128(usize, in);
833 prog.file = arg;840 prog.file = arg;
834 },841 },
835 LNS_set_column => {842 LNS_set_column => {
836 const arg = try leb.readULEB128(u64, &s.stream);843 const arg = try leb.readULEB128(u64, in);
837 prog.column = arg;844 prog.column = arg;
838 },845 },
839 LNS_negate_stmt => {846 LNS_negate_stmt => {
...@@ -847,14 +854,14 @@ pub const DwarfInfo = struct {...@@ -847,14 +854,14 @@ pub const DwarfInfo = struct {
847 prog.address += inc_addr;854 prog.address += inc_addr;
848 },855 },
849 LNS_fixed_advance_pc => {856 LNS_fixed_advance_pc => {
850 const arg = try s.stream.readInt(u16, di.endian);857 const arg = try in.readInt(u16, di.endian);
851 prog.address += arg;858 prog.address += arg;
852 },859 },
853 LNS_set_prologue_end => {},860 LNS_set_prologue_end => {},
854 else => {861 else => {
855 if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo;862 if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo;
856 const len_bytes = standard_opcode_lengths[opcode - 1];863 const len_bytes = standard_opcode_lengths[opcode - 1];
857 try s.seekable_stream.seekBy(len_bytes);864 try seekable.seekBy(len_bytes);
858 },865 },
859 }866 }
860 }867 }
lib/std/elf.zig+207-193
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");
2const std = @import("std.zig");1const std = @import("std.zig");
2const builtin = std.builtin;
3const io = std.io;3const io = std.io;
4const os = std.os;4const os = std.os;
5const math = std.math;5const math = std.math;
...@@ -330,218 +330,232 @@ pub const ET = extern enum(u16) {...@@ -330,218 +330,232 @@ pub const ET = extern enum(u16) {
330 pub const HIPROC = 0xffff;330 pub const HIPROC = 0xffff;
331};331};
332332
333pub const SectionHeader = Elf64_Shdr;333/// All integers are native endian.
334pub const ProgramHeader = Elf64_Phdr;334const Header = struct {
335
336pub const Elf = struct {
337 seekable_stream: *io.SeekableStream(anyerror, anyerror),
338 in_stream: *io.InStream(anyerror),
339 is_64: bool,
340 endian: builtin.Endian,335 endian: builtin.Endian,
341 file_type: ET,336 is_64: bool,
342 arch: EM,337 entry: u64,
343 entry_addr: u64,338 phoff: u64,
344 program_header_offset: u64,339 shoff: u64,
345 section_header_offset: u64,340 phentsize: u16,
346 string_section_index: usize,341 phnum: u16,
347 string_section: *SectionHeader,342 shentsize: u16,
348 section_headers: []SectionHeader,343 shnum: u16,
349 program_headers: []ProgramHeader,344 shstrndx: u16,
350 allocator: *mem.Allocator,345};
351
352 pub fn openStream(
353 allocator: *mem.Allocator,
354 seekable_stream: *io.SeekableStream(anyerror, anyerror),
355 in: *io.InStream(anyerror),
356 ) !Elf {
357 var elf: Elf = undefined;
358 elf.allocator = allocator;
359 elf.seekable_stream = seekable_stream;
360 elf.in_stream = in;
361
362 var magic: [4]u8 = undefined;
363 try in.readNoEof(magic[0..]);
364 if (!mem.eql(u8, &magic, "\x7fELF")) return error.InvalidFormat;
365
366 elf.is_64 = switch (try in.readByte()) {
367 1 => false,
368 2 => true,
369 else => return error.InvalidFormat,
370 };
371
372 elf.endian = switch (try in.readByte()) {
373 1 => .Little,
374 2 => .Big,
375 else => return error.InvalidFormat,
376 };
377
378 const version_byte = try in.readByte();
379 if (version_byte != 1) return error.InvalidFormat;
380
381 // skip over padding
382 try seekable_stream.seekBy(9);
383346
384 elf.file_type = try in.readEnum(ET, elf.endian);347pub fn readHeader(file: File) !Header {
385 elf.arch = try in.readEnum(EM, elf.endian);348 var hdr_buf: [@sizeOf(Elf64_Ehdr)]u8 align(@alignOf(Elf64_Ehdr)) = undefined;
349 try preadNoEof(file, &hdr_buf, 0);
350 const hdr32 = @ptrCast(*Elf32_Ehdr, &hdr_buf);
351 const hdr64 = @ptrCast(*Elf64_Ehdr, &hdr_buf);
352 if (!mem.eql(u8, hdr32.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
353 if (hdr32.e_ident[EI_VERSION] != 1) return error.InvalidElfVersion;
354
355 const endian: std.builtin.Endian = switch (hdr32.e_ident[EI_DATA]) {
356 ELFDATA2LSB => .Little,
357 ELFDATA2MSB => .Big,
358 else => return error.InvalidElfEndian,
359 };
360 const need_bswap = endian != std.builtin.endian;
361
362 const is_64 = switch (hdr32.e_ident[EI_CLASS]) {
363 ELFCLASS32 => false,
364 ELFCLASS64 => true,
365 else => return error.InvalidElfClass,
366 };
367
368 return @as(Header, .{
369 .endian = endian,
370 .is_64 = is_64,
371 .entry = int(is_64, need_bswap, hdr32.e_entry, hdr64.e_entry),
372 .phoff = int(is_64, need_bswap, hdr32.e_phoff, hdr64.e_phoff),
373 .shoff = int(is_64, need_bswap, hdr32.e_shoff, hdr64.e_shoff),
374 .phentsize = int(is_64, need_bswap, hdr32.e_phentsize, hdr64.e_phentsize),
375 .phnum = int(is_64, need_bswap, hdr32.e_phnum, hdr64.e_phnum),
376 .shentsize = int(is_64, need_bswap, hdr32.e_shentsize, hdr64.e_shentsize),
377 .shnum = int(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum),
378 .shstrndx = int(is_64, need_bswap, hdr32.e_shstrndx, hdr64.e_shstrndx),
379 });
380}
386381
387 const elf_version = try in.readInt(u32, elf.endian);382/// All integers are native endian.
388 if (elf_version != 1) return error.InvalidFormat;383pub const AllHeaders = struct {
384 header: Header,
385 section_headers: []Elf64_Shdr,
386 program_headers: []Elf64_Phdr,
387 allocator: *mem.Allocator,
388};
389389
390 if (elf.is_64) {390pub fn readAllHeaders(allocator: *mem.Allocator, file: File) !AllHeaders {
391 elf.entry_addr = try in.readInt(u64, elf.endian);391 var hdrs: AllHeaders = .{
392 elf.program_header_offset = try in.readInt(u64, elf.endian);392 .allocator = allocator,
393 elf.section_header_offset = try in.readInt(u64, elf.endian);393 .header = try readHeader(file),
394 } else {394 .section_headers = undefined,
395 elf.entry_addr = @as(u64, try in.readInt(u32, elf.endian));395 .program_headers = undefined,
396 elf.program_header_offset = @as(u64, try in.readInt(u32, elf.endian));396 };
397 elf.section_header_offset = @as(u64, try in.readInt(u32, elf.endian));397 const is_64 = hdrs.header.is_64;
398 const need_bswap = hdrs.header.endian != std.builtin.endian;
399
400 hdrs.section_headers = try allocator.alloc(Elf64_Shdr, hdrs.header.shnum);
401 errdefer allocator.free(hdrs.section_headers);
402
403 hdrs.program_headers = try allocator.alloc(Elf64_Phdr, hdrs.header.phnum);
404 errdefer allocator.free(hdrs.program_headers);
405
406 // If the ELF file is 64-bit and same-endianness, then all we have to do is
407 // yeet the bytes into memory.
408 // If only the endianness is different, they can be simply byte swapped.
409 if (is_64) {
410 const shdr_buf = std.mem.sliceAsBytes(hdrs.section_headers);
411 const phdr_buf = std.mem.sliceAsBytes(hdrs.program_headers);
412 try preadNoEof(file, shdr_buf, hdrs.header.shoff);
413 try preadNoEof(file, phdr_buf, hdrs.header.phoff);
414
415 if (need_bswap) {
416 for (hdrs.section_headers) |*shdr| {
417 shdr.* = .{
418 .sh_name = @byteSwap(@TypeOf(shdr.sh_name), shdr.sh_name),
419 .sh_type = @byteSwap(@TypeOf(shdr.sh_type), shdr.sh_type),
420 .sh_flags = @byteSwap(@TypeOf(shdr.sh_flags), shdr.sh_flags),
421 .sh_addr = @byteSwap(@TypeOf(shdr.sh_addr), shdr.sh_addr),
422 .sh_offset = @byteSwap(@TypeOf(shdr.sh_offset), shdr.sh_offset),
423 .sh_size = @byteSwap(@TypeOf(shdr.sh_size), shdr.sh_size),
424 .sh_link = @byteSwap(@TypeOf(shdr.sh_link), shdr.sh_link),
425 .sh_info = @byteSwap(@TypeOf(shdr.sh_info), shdr.sh_info),
426 .sh_addralign = @byteSwap(@TypeOf(shdr.sh_addralign), shdr.sh_addralign),
427 .sh_entsize = @byteSwap(@TypeOf(shdr.sh_entsize), shdr.sh_entsize),
428 };
429 }
430 for (hdrs.program_headers) |*phdr| {
431 phdr.* = .{
432 .p_type = @byteSwap(@TypeOf(phdr.p_type), phdr.p_type),
433 .p_offset = @byteSwap(@TypeOf(phdr.p_offset), phdr.p_offset),
434 .p_vaddr = @byteSwap(@TypeOf(phdr.p_vaddr), phdr.p_vaddr),
435 .p_paddr = @byteSwap(@TypeOf(phdr.p_paddr), phdr.p_paddr),
436 .p_filesz = @byteSwap(@TypeOf(phdr.p_filesz), phdr.p_filesz),
437 .p_memsz = @byteSwap(@TypeOf(phdr.p_memsz), phdr.p_memsz),
438 .p_flags = @byteSwap(@TypeOf(phdr.p_flags), phdr.p_flags),
439 .p_align = @byteSwap(@TypeOf(phdr.p_align), phdr.p_align),
440 };
441 }
398 }442 }
399443
400 // skip over flags444 return hdrs;
401 try seekable_stream.seekBy(4);445 }
402446
403 const header_size = try in.readInt(u16, elf.endian);447 const shdrs_32 = try allocator.alloc(Elf32_Shdr, hdrs.header.shnum);
404 if ((elf.is_64 and header_size != @sizeOf(Elf64_Ehdr)) or (!elf.is_64 and header_size != @sizeOf(Elf32_Ehdr))) {448 defer allocator.free(shdrs_32);
405 return error.InvalidFormat;449
450 const phdrs_32 = try allocator.alloc(Elf32_Phdr, hdrs.header.phnum);
451 defer allocator.free(phdrs_32);
452
453 const shdr_buf = std.mem.sliceAsBytes(shdrs_32);
454 const phdr_buf = std.mem.sliceAsBytes(phdrs_32);
455 try preadNoEof(file, shdr_buf, hdrs.header.shoff);
456 try preadNoEof(file, phdr_buf, hdrs.header.phoff);
457
458 if (need_bswap) {
459 for (hdrs.section_headers) |*shdr, i| {
460 const o = shdrs_32[i];
461 shdr.* = .{
462 .sh_name = @byteSwap(@TypeOf(o.sh_name), o.sh_name),
463 .sh_type = @byteSwap(@TypeOf(o.sh_type), o.sh_type),
464 .sh_flags = @byteSwap(@TypeOf(o.sh_flags), o.sh_flags),
465 .sh_addr = @byteSwap(@TypeOf(o.sh_addr), o.sh_addr),
466 .sh_offset = @byteSwap(@TypeOf(o.sh_offset), o.sh_offset),
467 .sh_size = @byteSwap(@TypeOf(o.sh_size), o.sh_size),
468 .sh_link = @byteSwap(@TypeOf(o.sh_link), o.sh_link),
469 .sh_info = @byteSwap(@TypeOf(o.sh_info), o.sh_info),
470 .sh_addralign = @byteSwap(@TypeOf(o.sh_addralign), o.sh_addralign),
471 .sh_entsize = @byteSwap(@TypeOf(o.sh_entsize), o.sh_entsize),
472 };
406 }473 }
407474 for (hdrs.program_headers) |*phdr, i| {
408 const ph_entry_size = try in.readInt(u16, elf.endian);475 const o = phdrs_32[i];
409 const ph_entry_count = try in.readInt(u16, elf.endian);476 phdr.* = .{
410477 .p_type = @byteSwap(@TypeOf(o.p_type), o.p_type),
411 if ((elf.is_64 and ph_entry_size != @sizeOf(Elf64_Phdr)) or (!elf.is_64 and ph_entry_size != @sizeOf(Elf32_Phdr))) {478 .p_offset = @byteSwap(@TypeOf(o.p_offset), o.p_offset),
412 return error.InvalidFormat;479 .p_vaddr = @byteSwap(@TypeOf(o.p_vaddr), o.p_vaddr),
480 .p_paddr = @byteSwap(@TypeOf(o.p_paddr), o.p_paddr),
481 .p_filesz = @byteSwap(@TypeOf(o.p_filesz), o.p_filesz),
482 .p_memsz = @byteSwap(@TypeOf(o.p_memsz), o.p_memsz),
483 .p_flags = @byteSwap(@TypeOf(o.p_flags), o.p_flags),
484 .p_align = @byteSwap(@TypeOf(o.p_align), o.p_align),
485 };
413 }486 }
414487 } else {
415 const sh_entry_size = try in.readInt(u16, elf.endian);488 for (hdrs.section_headers) |*shdr, i| {
416 const sh_entry_count = try in.readInt(u16, elf.endian);489 const o = shdrs_32[i];
417490 shdr.* = .{
418 if ((elf.is_64 and sh_entry_size != @sizeOf(Elf64_Shdr)) or (!elf.is_64 and sh_entry_size != @sizeOf(Elf32_Shdr))) {491 .sh_name = o.sh_name,
419 return error.InvalidFormat;492 .sh_type = o.sh_type,
493 .sh_flags = o.sh_flags,
494 .sh_addr = o.sh_addr,
495 .sh_offset = o.sh_offset,
496 .sh_size = o.sh_size,
497 .sh_link = o.sh_link,
498 .sh_info = o.sh_info,
499 .sh_addralign = o.sh_addralign,
500 .sh_entsize = o.sh_entsize,
501 };
420 }502 }
421503 for (hdrs.program_headers) |*phdr, i| {
422 elf.string_section_index = @as(usize, try in.readInt(u16, elf.endian));504 const o = phdrs_32[i];
423505 phdr.* = .{
424 if (elf.string_section_index >= sh_entry_count) return error.InvalidFormat;506 .p_type = o.p_type,
425507 .p_offset = o.p_offset,
426 const sh_byte_count = @as(u64, sh_entry_size) * @as(u64, sh_entry_count);508 .p_vaddr = o.p_vaddr,
427 const end_sh = try math.add(u64, elf.section_header_offset, sh_byte_count);509 .p_paddr = o.p_paddr,
428 const ph_byte_count = @as(u64, ph_entry_size) * @as(u64, ph_entry_count);510 .p_filesz = o.p_filesz,
429 const end_ph = try math.add(u64, elf.program_header_offset, ph_byte_count);511 .p_memsz = o.p_memsz,
430512 .p_flags = o.p_flags,
431 const stream_end = try seekable_stream.getEndPos();513 .p_align = o.p_align,
432 if (stream_end < end_sh or stream_end < end_ph) {514 };
433 return error.InvalidFormat;
434 }515 }
516 }
435517
436 try seekable_stream.seekTo(elf.program_header_offset);518 return hdrs;
437519}
438 elf.program_headers = try elf.allocator.alloc(ProgramHeader, ph_entry_count);
439 errdefer elf.allocator.free(elf.program_headers);
440
441 if (elf.is_64) {
442 for (elf.program_headers) |*elf_program| {
443 elf_program.p_type = try in.readInt(Elf64_Word, elf.endian);
444 elf_program.p_flags = try in.readInt(Elf64_Word, elf.endian);
445 elf_program.p_offset = try in.readInt(Elf64_Off, elf.endian);
446 elf_program.p_vaddr = try in.readInt(Elf64_Addr, elf.endian);
447 elf_program.p_paddr = try in.readInt(Elf64_Addr, elf.endian);
448 elf_program.p_filesz = try in.readInt(Elf64_Xword, elf.endian);
449 elf_program.p_memsz = try in.readInt(Elf64_Xword, elf.endian);
450 elf_program.p_align = try in.readInt(Elf64_Xword, elf.endian);
451 }
452 } else {
453 for (elf.program_headers) |*elf_program| {
454 elf_program.p_type = @as(Elf64_Word, try in.readInt(Elf32_Word, elf.endian));
455 elf_program.p_offset = @as(Elf64_Off, try in.readInt(Elf32_Off, elf.endian));
456 elf_program.p_vaddr = @as(Elf64_Addr, try in.readInt(Elf32_Addr, elf.endian));
457 elf_program.p_paddr = @as(Elf64_Addr, try in.readInt(Elf32_Addr, elf.endian));
458 elf_program.p_filesz = @as(Elf64_Word, try in.readInt(Elf32_Word, elf.endian));
459 elf_program.p_memsz = @as(Elf64_Word, try in.readInt(Elf32_Word, elf.endian));
460 elf_program.p_flags = @as(Elf64_Word, try in.readInt(Elf32_Word, elf.endian));
461 elf_program.p_align = @as(Elf64_Word, try in.readInt(Elf32_Word, elf.endian));
462 }
463 }
464520
465 try seekable_stream.seekTo(elf.section_header_offset);521pub fn int(is_64: bool, need_bswap: bool, int_32: var, int_64: var) @TypeOf(int_64) {
466522 if (is_64) {
467 elf.section_headers = try elf.allocator.alloc(SectionHeader, sh_entry_count);523 if (need_bswap) {
468 errdefer elf.allocator.free(elf.section_headers);524 return @byteSwap(@TypeOf(int_64), int_64);
469
470 if (elf.is_64) {
471 for (elf.section_headers) |*elf_section| {
472 elf_section.sh_name = try in.readInt(u32, elf.endian);
473 elf_section.sh_type = try in.readInt(u32, elf.endian);
474 elf_section.sh_flags = try in.readInt(u64, elf.endian);
475 elf_section.sh_addr = try in.readInt(u64, elf.endian);
476 elf_section.sh_offset = try in.readInt(u64, elf.endian);
477 elf_section.sh_size = try in.readInt(u64, elf.endian);
478 elf_section.sh_link = try in.readInt(u32, elf.endian);
479 elf_section.sh_info = try in.readInt(u32, elf.endian);
480 elf_section.sh_addralign = try in.readInt(u64, elf.endian);
481 elf_section.sh_entsize = try in.readInt(u64, elf.endian);
482 }
483 } else {525 } else {
484 for (elf.section_headers) |*elf_section| {526 return int_64;
485 // TODO (multiple occurrences) allow implicit cast from %u32 -> %u64 ?
486 elf_section.sh_name = try in.readInt(u32, elf.endian);
487 elf_section.sh_type = try in.readInt(u32, elf.endian);
488 elf_section.sh_flags = @as(u64, try in.readInt(u32, elf.endian));
489 elf_section.sh_addr = @as(u64, try in.readInt(u32, elf.endian));
490 elf_section.sh_offset = @as(u64, try in.readInt(u32, elf.endian));
491 elf_section.sh_size = @as(u64, try in.readInt(u32, elf.endian));
492 elf_section.sh_link = try in.readInt(u32, elf.endian);
493 elf_section.sh_info = try in.readInt(u32, elf.endian);
494 elf_section.sh_addralign = @as(u64, try in.readInt(u32, elf.endian));
495 elf_section.sh_entsize = @as(u64, try in.readInt(u32, elf.endian));
496 }
497 }527 }
498528 } else {
499 for (elf.section_headers) |*elf_section| {529 return int32(need_bswap, int_32, @TypeOf(int_64));
500 if (elf_section.sh_type != SHT_NOBITS) {
501 const file_end_offset = try math.add(u64, elf_section.sh_offset, elf_section.sh_size);
502 if (stream_end < file_end_offset) return error.InvalidFormat;
503 }
504 }
505
506 elf.string_section = &elf.section_headers[elf.string_section_index];
507 if (elf.string_section.sh_type != SHT_STRTAB) {
508 // not a string table
509 return error.InvalidFormat;
510 }
511
512 return elf;
513 }530 }
531}
514532
515 pub fn close(elf: *Elf) void {533pub fn int32(need_bswap: bool, int_32: var, comptime Int64: var) Int64 {
516 elf.allocator.free(elf.section_headers);534 if (need_bswap) {
517 elf.allocator.free(elf.program_headers);535 return @byteSwap(@TypeOf(int_32), int_32);
518 }536 } else {
519537 return int_32;
520 pub fn findSection(elf: *Elf, name: []const u8) !?*SectionHeader {
521 section_loop: for (elf.section_headers) |*elf_section| {
522 if (elf_section.sh_type == SHT_NULL) continue;
523
524 const name_offset = elf.string_section.sh_offset + elf_section.sh_name;
525 try elf.seekable_stream.seekTo(name_offset);
526
527 for (name) |expected_c| {
528 const target_c = try elf.in_stream.readByte();
529 if (target_c == 0 or expected_c != target_c) continue :section_loop;
530 }
531
532 {
533 const null_byte = try elf.in_stream.readByte();
534 if (null_byte == 0) return elf_section;
535 }
536 }
537
538 return null;
539 }538 }
539}
540540
541 pub fn seekToSection(elf: *Elf, elf_section: *SectionHeader) !void {541fn preadNoEof(file: std.fs.File, buf: []u8, offset: u64) !void {
542 try elf.seekable_stream.seekTo(elf_section.sh_offset);542 var i: u64 = 0;
543 while (i < buf.len) {
544 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {
545 error.SystemResources => return error.SystemResources,
546 error.IsDir => return error.UnableToReadElfFile,
547 error.OperationAborted => return error.UnableToReadElfFile,
548 error.BrokenPipe => return error.UnableToReadElfFile,
549 error.Unseekable => return error.UnableToReadElfFile,
550 error.ConnectionResetByPeer => return error.UnableToReadElfFile,
551 error.InputOutput => return error.FileSystem,
552 error.Unexpected => return error.Unexpected,
553 error.WouldBlock => return error.Unexpected,
554 };
555 if (len == 0) return error.UnexpectedEndOfFile;
556 i += len;
543 }557 }
544};558}
545559
546pub const EI_NIDENT = 16;560pub const EI_NIDENT = 16;
547561
lib/std/event/channel.zig+10-13
...@@ -14,8 +14,8 @@ pub fn Channel(comptime T: type) type {...@@ -14,8 +14,8 @@ pub fn Channel(comptime T: type) type {
14 putters: std.atomic.Queue(PutNode),14 putters: std.atomic.Queue(PutNode),
15 get_count: usize,15 get_count: usize,
16 put_count: usize,16 put_count: usize,
17 dispatch_lock: u8, // TODO make this a bool17 dispatch_lock: bool,
18 need_dispatch: u8, // TODO make this a bool18 need_dispatch: bool,
1919
20 // simple fixed size ring buffer20 // simple fixed size ring buffer
21 buffer_nodes: []T,21 buffer_nodes: []T,
...@@ -62,8 +62,8 @@ pub fn Channel(comptime T: type) type {...@@ -62,8 +62,8 @@ pub fn Channel(comptime T: type) type {
62 .buffer_len = 0,62 .buffer_len = 0,
63 .buffer_nodes = buffer,63 .buffer_nodes = buffer,
64 .buffer_index = 0,64 .buffer_index = 0,
65 .dispatch_lock = 0,65 .dispatch_lock = false,
66 .need_dispatch = 0,66 .need_dispatch = false,
67 .getters = std.atomic.Queue(GetNode).init(),67 .getters = std.atomic.Queue(GetNode).init(),
68 .putters = std.atomic.Queue(PutNode).init(),68 .putters = std.atomic.Queue(PutNode).init(),
69 .or_null_queue = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).init(),69 .or_null_queue = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).init(),
...@@ -165,15 +165,14 @@ pub fn Channel(comptime T: type) type {...@@ -165,15 +165,14 @@ pub fn Channel(comptime T: type) type {
165165
166 fn dispatch(self: *SelfChannel) void {166 fn dispatch(self: *SelfChannel) void {
167 // set the "need dispatch" flag167 // set the "need dispatch" flag
168 @atomicStore(u8, &self.need_dispatch, 1, .SeqCst);168 @atomicStore(bool, &self.need_dispatch, true, .SeqCst);
169169
170 lock: while (true) {170 lock: while (true) {
171 // set the lock flag171 // set the lock flag
172 const prev_lock = @atomicRmw(u8, &self.dispatch_lock, .Xchg, 1, .SeqCst);172 if (@atomicRmw(bool, &self.dispatch_lock, .Xchg, true, .SeqCst)) return;
173 if (prev_lock != 0) return;
174173
175 // clear the need_dispatch flag since we're about to do it174 // clear the need_dispatch flag since we're about to do it
176 @atomicStore(u8, &self.need_dispatch, 0, .SeqCst);175 @atomicStore(bool, &self.need_dispatch, false, .SeqCst);
177176
178 while (true) {177 while (true) {
179 one_dispatch: {178 one_dispatch: {
...@@ -250,14 +249,12 @@ pub fn Channel(comptime T: type) type {...@@ -250,14 +249,12 @@ pub fn Channel(comptime T: type) type {
250 }249 }
251250
252 // clear need-dispatch flag251 // clear need-dispatch flag
253 const need_dispatch = @atomicRmw(u8, &self.need_dispatch, .Xchg, 0, .SeqCst);252 if (@atomicRmw(bool, &self.need_dispatch, .Xchg, false, .SeqCst)) continue;
254 if (need_dispatch != 0) continue;
255253
256 const my_lock = @atomicRmw(u8, &self.dispatch_lock, .Xchg, 0, .SeqCst);254 assert(@atomicRmw(bool, &self.dispatch_lock, .Xchg, false, .SeqCst));
257 assert(my_lock != 0);
258255
259 // we have to check again now that we unlocked256 // we have to check again now that we unlocked
260 if (@atomicLoad(u8, &self.need_dispatch, .SeqCst) != 0) continue :lock;257 if (@atomicLoad(bool, &self.need_dispatch, .SeqCst)) continue :lock;
261258
262 return;259 return;
263 }260 }
lib/std/event/group.zig+3-1
...@@ -120,9 +120,11 @@ test "std.event.Group" {...@@ -120,9 +120,11 @@ test "std.event.Group" {
120 // https://github.com/ziglang/zig/issues/1908120 // https://github.com/ziglang/zig/issues/1908
121 if (builtin.single_threaded) return error.SkipZigTest;121 if (builtin.single_threaded) return error.SkipZigTest;
122122
123 // TODO provide a way to run tests in evented I/O mode
124 if (!std.io.is_async) return error.SkipZigTest;123 if (!std.io.is_async) return error.SkipZigTest;
125124
125 // TODO this file has bit-rotted. repair it
126 if (true) return error.SkipZigTest;
127
126 const handle = async testGroup(std.heap.page_allocator);128 const handle = async testGroup(std.heap.page_allocator);
127}129}
128130
lib/std/event/lock.zig+20-19
...@@ -11,9 +11,9 @@ const Loop = std.event.Loop;...@@ -11,9 +11,9 @@ const Loop = std.event.Loop;
11/// Allows only one actor to hold the lock.11/// Allows only one actor to hold the lock.
12/// TODO: make this API also work in blocking I/O mode.12/// TODO: make this API also work in blocking I/O mode.
13pub const Lock = struct {13pub const Lock = struct {
14 shared_bit: u8, // TODO make this a bool14 shared: bool,
15 queue: Queue,15 queue: Queue,
16 queue_empty_bit: u8, // TODO make this a bool16 queue_empty: bool,
1717
18 const Queue = std.atomic.Queue(anyframe);18 const Queue = std.atomic.Queue(anyframe);
1919
...@@ -31,20 +31,19 @@ pub const Lock = struct {...@@ -31,20 +31,19 @@ pub const Lock = struct {
31 }31 }
3232
33 // We need to release the lock.33 // We need to release the lock.
34 @atomicStore(u8, &self.lock.queue_empty_bit, 1, .SeqCst);34 @atomicStore(bool, &self.lock.queue_empty, true, .SeqCst);
35 @atomicStore(u8, &self.lock.shared_bit, 0, .SeqCst);35 @atomicStore(bool, &self.lock.shared, false, .SeqCst);
3636
37 // There might be a queue item. If we know the queue is empty, we can be done,37 // There might be a queue item. If we know the queue is empty, we can be done,
38 // because the other actor will try to obtain the lock.38 // because the other actor will try to obtain the lock.
39 // But if there's a queue item, we are the actor which must loop and attempt39 // But if there's a queue item, we are the actor which must loop and attempt
40 // to grab the lock again.40 // to grab the lock again.
41 if (@atomicLoad(u8, &self.lock.queue_empty_bit, .SeqCst) == 1) {41 if (@atomicLoad(bool, &self.lock.queue_empty, .SeqCst)) {
42 return;42 return;
43 }43 }
4444
45 while (true) {45 while (true) {
46 const old_bit = @atomicRmw(u8, &self.lock.shared_bit, .Xchg, 1, .SeqCst);46 if (@atomicRmw(bool, &self.lock.shared, .Xchg, true, .SeqCst)) {
47 if (old_bit != 0) {
48 // We did not obtain the lock. Great, the queue is someone else's problem.47 // We did not obtain the lock. Great, the queue is someone else's problem.
49 return;48 return;
50 }49 }
...@@ -56,11 +55,11 @@ pub const Lock = struct {...@@ -56,11 +55,11 @@ pub const Lock = struct {
56 }55 }
5756
58 // Release the lock again.57 // Release the lock again.
59 @atomicStore(u8, &self.lock.queue_empty_bit, 1, .SeqCst);58 @atomicStore(bool, &self.lock.queue_empty, true, .SeqCst);
60 @atomicStore(u8, &self.lock.shared_bit, 0, .SeqCst);59 @atomicStore(bool, &self.lock.shared, false, .SeqCst);
6160
62 // Find out if we can be done.61 // Find out if we can be done.
63 if (@atomicLoad(u8, &self.lock.queue_empty_bit, .SeqCst) == 1) {62 if (@atomicLoad(bool, &self.lock.queue_empty, .SeqCst)) {
64 return;63 return;
65 }64 }
66 }65 }
...@@ -69,24 +68,24 @@ pub const Lock = struct {...@@ -69,24 +68,24 @@ pub const Lock = struct {
6968
70 pub fn init() Lock {69 pub fn init() Lock {
71 return Lock{70 return Lock{
72 .shared_bit = 0,71 .shared = false,
73 .queue = Queue.init(),72 .queue = Queue.init(),
74 .queue_empty_bit = 1,73 .queue_empty = true,
75 };74 };
76 }75 }
7776
78 pub fn initLocked() Lock {77 pub fn initLocked() Lock {
79 return Lock{78 return Lock{
80 .shared_bit = 1,79 .shared = true,
81 .queue = Queue.init(),80 .queue = Queue.init(),
82 .queue_empty_bit = 1,81 .queue_empty = true,
83 };82 };
84 }83 }
8584
86 /// Must be called when not locked. Not thread safe.85 /// Must be called when not locked. Not thread safe.
87 /// All calls to acquire() and release() must complete before calling deinit().86 /// All calls to acquire() and release() must complete before calling deinit().
88 pub fn deinit(self: *Lock) void {87 pub fn deinit(self: *Lock) void {
89 assert(self.shared_bit == 0);88 assert(!self.shared);
90 while (self.queue.get()) |node| resume node.data;89 while (self.queue.get()) |node| resume node.data;
91 }90 }
9291
...@@ -99,12 +98,11 @@ pub const Lock = struct {...@@ -99,12 +98,11 @@ pub const Lock = struct {
9998
100 // At this point, we are in the queue, so we might have already been resumed.99 // At this point, we are in the queue, so we might have already been resumed.
101100
102 // We set this bit so that later we can rely on the fact, that if queue_empty_bit is 1, some actor101 // We set this bit so that later we can rely on the fact, that if queue_empty == true, some actor
103 // will attempt to grab the lock.102 // will attempt to grab the lock.
104 @atomicStore(u8, &self.queue_empty_bit, 0, .SeqCst);103 @atomicStore(bool, &self.queue_empty, false, .SeqCst);
105104
106 const old_bit = @atomicRmw(u8, &self.shared_bit, .Xchg, 1, .SeqCst);105 if (!@atomicRmw(bool, &self.shared, .Xchg, true, .SeqCst)) {
107 if (old_bit == 0) {
108 if (self.queue.get()) |node| {106 if (self.queue.get()) |node| {
109 // Whether this node is us or someone else, we tail resume it.107 // Whether this node is us or someone else, we tail resume it.
110 resume node.data;108 resume node.data;
...@@ -125,6 +123,9 @@ test "std.event.Lock" {...@@ -125,6 +123,9 @@ test "std.event.Lock" {
125 // TODO https://github.com/ziglang/zig/issues/3251123 // TODO https://github.com/ziglang/zig/issues/3251
126 if (builtin.os.tag == .freebsd) return error.SkipZigTest;124 if (builtin.os.tag == .freebsd) return error.SkipZigTest;
127125
126 // TODO this file has bit-rotted. repair it
127 if (true) return error.SkipZigTest;
128
128 var lock = Lock.init();129 var lock = Lock.init();
129 defer lock.deinit();130 defer lock.deinit();
130131
lib/std/event/loop.zig+78
...@@ -809,6 +809,28 @@ pub const Loop = struct {...@@ -809,6 +809,28 @@ pub const Loop = struct {
809 return req_node.data.msg.readv.result;809 return req_node.data.msg.readv.result;
810 }810 }
811811
812 /// Performs an async `os.pread` using a separate thread.
813 /// `fd` must block and not return EAGAIN.
814 pub fn pread(self: *Loop, fd: os.fd_t, buf: []u8, offset: u64) os.PReadError!usize {
815 var req_node = Request.Node{
816 .data = .{
817 .msg = .{
818 .pread = .{
819 .fd = fd,
820 .buf = buf,
821 .offset = offset,
822 .result = undefined,
823 },
824 },
825 .finish = .{ .TickNode = .{ .data = @frame() } },
826 },
827 };
828 suspend {
829 self.posixFsRequest(&req_node);
830 }
831 return req_node.data.msg.pread.result;
832 }
833
812 /// Performs an async `os.preadv` using a separate thread.834 /// Performs an async `os.preadv` using a separate thread.
813 /// `fd` must block and not return EAGAIN.835 /// `fd` must block and not return EAGAIN.
814 pub fn preadv(self: *Loop, fd: os.fd_t, iov: []const os.iovec, offset: u64) os.ReadError!usize {836 pub fn preadv(self: *Loop, fd: os.fd_t, iov: []const os.iovec, offset: u64) os.ReadError!usize {
...@@ -895,6 +917,35 @@ pub const Loop = struct {...@@ -895,6 +917,35 @@ pub const Loop = struct {
895 return req_node.data.msg.pwritev.result;917 return req_node.data.msg.pwritev.result;
896 }918 }
897919
920 /// Performs an async `os.faccessatZ` using a separate thread.
921 /// `fd` must block and not return EAGAIN.
922 pub fn faccessatZ(
923 self: *Loop,
924 dirfd: os.fd_t,
925 path_z: [*:0]const u8,
926 mode: u32,
927 flags: u32,
928 ) os.AccessError!void {
929 var req_node = Request.Node{
930 .data = .{
931 .msg = .{
932 .faccessat = .{
933 .dirfd = dirfd,
934 .path = path_z,
935 .mode = mode,
936 .flags = flags,
937 .result = undefined,
938 },
939 },
940 .finish = .{ .TickNode = .{ .data = @frame() } },
941 },
942 };
943 suspend {
944 self.posixFsRequest(&req_node);
945 }
946 return req_node.data.msg.faccessat.result;
947 }
948
898 fn workerRun(self: *Loop) void {949 fn workerRun(self: *Loop) void {
899 while (true) {950 while (true) {
900 while (true) {951 while (true) {
...@@ -1038,6 +1089,9 @@ pub const Loop = struct {...@@ -1038,6 +1089,9 @@ pub const Loop = struct {
1038 .pwritev => |*msg| {1089 .pwritev => |*msg| {
1039 msg.result = noasync os.pwritev(msg.fd, msg.iov, msg.offset);1090 msg.result = noasync os.pwritev(msg.fd, msg.iov, msg.offset);
1040 },1091 },
1092 .pread => |*msg| {
1093 msg.result = noasync os.pread(msg.fd, msg.buf, msg.offset);
1094 },
1041 .preadv => |*msg| {1095 .preadv => |*msg| {
1042 msg.result = noasync os.preadv(msg.fd, msg.iov, msg.offset);1096 msg.result = noasync os.preadv(msg.fd, msg.iov, msg.offset);
1043 },1097 },
...@@ -1047,6 +1101,9 @@ pub const Loop = struct {...@@ -1047,6 +1101,9 @@ pub const Loop = struct {
1047 .openat => |*msg| {1101 .openat => |*msg| {
1048 msg.result = noasync os.openatC(msg.fd, msg.path, msg.flags, msg.mode);1102 msg.result = noasync os.openatC(msg.fd, msg.path, msg.flags, msg.mode);
1049 },1103 },
1104 .faccessat => |*msg| {
1105 msg.result = noasync os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags);
1106 },
1050 .close => |*msg| noasync os.close(msg.fd),1107 .close => |*msg| noasync os.close(msg.fd),
1051 }1108 }
1052 switch (node.data.finish) {1109 switch (node.data.finish) {
...@@ -1120,10 +1177,12 @@ pub const Loop = struct {...@@ -1120,10 +1177,12 @@ pub const Loop = struct {
1120 write: Write,1177 write: Write,
1121 writev: WriteV,1178 writev: WriteV,
1122 pwritev: PWriteV,1179 pwritev: PWriteV,
1180 pread: PRead,
1123 preadv: PReadV,1181 preadv: PReadV,
1124 open: Open,1182 open: Open,
1125 openat: OpenAt,1183 openat: OpenAt,
1126 close: Close,1184 close: Close,
1185 faccessat: FAccessAt,
11271186
1128 /// special - means the fs thread should exit1187 /// special - means the fs thread should exit
1129 end,1188 end,
...@@ -1161,6 +1220,15 @@ pub const Loop = struct {...@@ -1161,6 +1220,15 @@ pub const Loop = struct {
1161 pub const Error = os.PWriteError;1220 pub const Error = os.PWriteError;
1162 };1221 };
11631222
1223 pub const PRead = struct {
1224 fd: os.fd_t,
1225 buf: []u8,
1226 offset: usize,
1227 result: Error!usize,
1228
1229 pub const Error = os.PReadError;
1230 };
1231
1164 pub const PReadV = struct {1232 pub const PReadV = struct {
1165 fd: os.fd_t,1233 fd: os.fd_t,
1166 iov: []const os.iovec,1234 iov: []const os.iovec,
...@@ -1192,6 +1260,16 @@ pub const Loop = struct {...@@ -1192,6 +1260,16 @@ pub const Loop = struct {
1192 pub const Close = struct {1260 pub const Close = struct {
1193 fd: os.fd_t,1261 fd: os.fd_t,
1194 };1262 };
1263
1264 pub const FAccessAt = struct {
1265 dirfd: os.fd_t,
1266 path: [*:0]const u8,
1267 mode: u32,
1268 flags: u32,
1269 result: Error!void,
1270
1271 pub const Error = os.AccessError;
1272 };
1195 };1273 };
1196 };1274 };
1197};1275};
lib/std/event/rwlock.zig+16-16
...@@ -16,8 +16,8 @@ pub const RwLock = struct {...@@ -16,8 +16,8 @@ pub const RwLock = struct {
16 shared_state: State,16 shared_state: State,
17 writer_queue: Queue,17 writer_queue: Queue,
18 reader_queue: Queue,18 reader_queue: Queue,
19 writer_queue_empty_bit: u8, // TODO make this a bool19 writer_queue_empty: bool,
20 reader_queue_empty_bit: u8, // TODO make this a bool20 reader_queue_empty: bool,
21 reader_lock_count: usize,21 reader_lock_count: usize,
2222
23 const State = enum(u8) {23 const State = enum(u8) {
...@@ -40,7 +40,7 @@ pub const RwLock = struct {...@@ -40,7 +40,7 @@ pub const RwLock = struct {
40 return;40 return;
41 }41 }
4242
43 @atomicStore(u8, &self.lock.reader_queue_empty_bit, 1, .SeqCst);43 @atomicStore(bool, &self.lock.reader_queue_empty, true, .SeqCst);
44 if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {44 if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
45 // Didn't unlock. Someone else's problem.45 // Didn't unlock. Someone else's problem.
46 return;46 return;
...@@ -62,7 +62,7 @@ pub const RwLock = struct {...@@ -62,7 +62,7 @@ pub const RwLock = struct {
62 }62 }
6363
64 // We need to release the write lock. Check if any readers are waiting to grab the lock.64 // We need to release the write lock. Check if any readers are waiting to grab the lock.
65 if (@atomicLoad(u8, &self.lock.reader_queue_empty_bit, .SeqCst) == 0) {65 if (!@atomicLoad(bool, &self.lock.reader_queue_empty, .SeqCst)) {
66 // Switch to a read lock.66 // Switch to a read lock.
67 @atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst);67 @atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst);
68 while (self.lock.reader_queue.get()) |node| {68 while (self.lock.reader_queue.get()) |node| {
...@@ -71,7 +71,7 @@ pub const RwLock = struct {...@@ -71,7 +71,7 @@ pub const RwLock = struct {
71 return;71 return;
72 }72 }
7373
74 @atomicStore(u8, &self.lock.writer_queue_empty_bit, 1, .SeqCst);74 @atomicStore(bool, &self.lock.writer_queue_empty, true, .SeqCst);
75 @atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst);75 @atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst);
7676
77 self.lock.commonPostUnlock();77 self.lock.commonPostUnlock();
...@@ -79,12 +79,12 @@ pub const RwLock = struct {...@@ -79,12 +79,12 @@ pub const RwLock = struct {
79 };79 };
8080
81 pub fn init() RwLock {81 pub fn init() RwLock {
82 return RwLock{82 return .{
83 .shared_state = .Unlocked,83 .shared_state = .Unlocked,
84 .writer_queue = Queue.init(),84 .writer_queue = Queue.init(),
85 .writer_queue_empty_bit = 1,85 .writer_queue_empty = true,
86 .reader_queue = Queue.init(),86 .reader_queue = Queue.init(),
87 .reader_queue_empty_bit = 1,87 .reader_queue_empty = true,
88 .reader_lock_count = 0,88 .reader_lock_count = 0,
89 };89 };
90 }90 }
...@@ -111,9 +111,9 @@ pub const RwLock = struct {...@@ -111,9 +111,9 @@ pub const RwLock = struct {
111111
112 // At this point, we are in the reader_queue, so we might have already been resumed.112 // At this point, we are in the reader_queue, so we might have already been resumed.
113113
114 // We set this bit so that later we can rely on the fact, that if reader_queue_empty_bit is 1,114 // We set this bit so that later we can rely on the fact, that if reader_queue_empty == true,
115 // some actor will attempt to grab the lock.115 // some actor will attempt to grab the lock.
116 @atomicStore(u8, &self.reader_queue_empty_bit, 0, .SeqCst);116 @atomicStore(bool, &self.reader_queue_empty, false, .SeqCst);
117117
118 // Here we don't care if we are the one to do the locking or if it was already locked for reading.118 // Here we don't care if we are the one to do the locking or if it was already locked for reading.
119 const have_read_lock = if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == .ReadLock else true;119 const have_read_lock = if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == .ReadLock else true;
...@@ -142,9 +142,9 @@ pub const RwLock = struct {...@@ -142,9 +142,9 @@ pub const RwLock = struct {
142142
143 // At this point, we are in the writer_queue, so we might have already been resumed.143 // At this point, we are in the writer_queue, so we might have already been resumed.
144144
145 // We set this bit so that later we can rely on the fact, that if writer_queue_empty_bit is 1,145 // We set this bit so that later we can rely on the fact, that if writer_queue_empty == true,
146 // some actor will attempt to grab the lock.146 // some actor will attempt to grab the lock.
147 @atomicStore(u8, &self.writer_queue_empty_bit, 0, .SeqCst);147 @atomicStore(bool, &self.writer_queue_empty, false, .SeqCst);
148148
149 // Here we must be the one to acquire the write lock. It cannot already be locked.149 // Here we must be the one to acquire the write lock. It cannot already be locked.
150 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) {150 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) {
...@@ -165,7 +165,7 @@ pub const RwLock = struct {...@@ -165,7 +165,7 @@ pub const RwLock = struct {
165 // obtain the lock.165 // obtain the lock.
166 // But if there's a writer_queue item or a reader_queue item,166 // But if there's a writer_queue item or a reader_queue item,
167 // we are the actor which must loop and attempt to grab the lock again.167 // we are the actor which must loop and attempt to grab the lock again.
168 if (@atomicLoad(u8, &self.writer_queue_empty_bit, .SeqCst) == 0) {168 if (!@atomicLoad(bool, &self.writer_queue_empty, .SeqCst)) {
169 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) {169 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) {
170 // We did not obtain the lock. Great, the queues are someone else's problem.170 // We did not obtain the lock. Great, the queues are someone else's problem.
171 return;171 return;
...@@ -176,12 +176,12 @@ pub const RwLock = struct {...@@ -176,12 +176,12 @@ pub const RwLock = struct {
176 return;176 return;
177 }177 }
178 // Release the lock again.178 // Release the lock again.
179 @atomicStore(u8, &self.writer_queue_empty_bit, 1, .SeqCst);179 @atomicStore(bool, &self.writer_queue_empty, true, .SeqCst);
180 @atomicStore(State, &self.shared_state, .Unlocked, .SeqCst);180 @atomicStore(State, &self.shared_state, .Unlocked, .SeqCst);
181 continue;181 continue;
182 }182 }
183183
184 if (@atomicLoad(u8, &self.reader_queue_empty_bit, .SeqCst) == 0) {184 if (!@atomicLoad(bool, &self.reader_queue_empty, .SeqCst)) {
185 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) {185 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) {
186 // We did not obtain the lock. Great, the queues are someone else's problem.186 // We did not obtain the lock. Great, the queues are someone else's problem.
187 return;187 return;
...@@ -195,7 +195,7 @@ pub const RwLock = struct {...@@ -195,7 +195,7 @@ pub const RwLock = struct {
195 return;195 return;
196 }196 }
197 // Release the lock again.197 // Release the lock again.
198 @atomicStore(u8, &self.reader_queue_empty_bit, 1, .SeqCst);198 @atomicStore(bool, &self.reader_queue_empty, true, .SeqCst);
199 if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {199 if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
200 // Didn't unlock. Someone else's problem.200 // Didn't unlock. Someone else's problem.
201 return;201 return;
lib/std/fifo.zig+13-3
...@@ -293,8 +293,18 @@ pub fn LinearFifo(...@@ -293,8 +293,18 @@ pub fn LinearFifo(
293293
294 pub usingnamespace if (T == u8)294 pub usingnamespace if (T == u8)
295 struct {295 struct {
296 pub fn print(self: *Self, comptime format: []const u8, args: var) !void {296 const OutStream = std.io.OutStream(*Self, Error, appendWrite);
297 return std.fmt.format(self, error{OutOfMemory}, Self.write, format, args);297 const Error = error{OutOfMemory};
298
299 /// Same as `write` except it returns the number of bytes written, which is always the same
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 }
305
306 pub fn outStream(self: *Self) OutStream {
307 return .{ .context = self };
298 }308 }
299 }309 }
300 else310 else
...@@ -407,7 +417,7 @@ test "LinearFifo(u8, .Dynamic)" {...@@ -407,7 +417,7 @@ test "LinearFifo(u8, .Dynamic)" {
407 fifo.shrink(0);417 fifo.shrink(0);
408418
409 {419 {
410 try fifo.print("{}, {}!", .{ "Hello", "World" });420 try fifo.outStream().print("{}, {}!", .{ "Hello", "World" });
411 var result: [30]u8 = undefined;421 var result: [30]u8 = undefined;
412 testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);422 testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);
413 testing.expectEqual(@as(usize, 0), fifo.readableLength());423 testing.expectEqual(@as(usize, 0), fifo.readableLength());
lib/std/fmt.zig+225-301
...@@ -69,19 +69,17 @@ fn peekIsAlign(comptime fmt: []const u8) bool {...@@ -69,19 +69,17 @@ fn peekIsAlign(comptime fmt: []const u8) bool {
69///69///
70/// If a formatted user type contains a function of the type70/// If a formatted user type contains a function of the type
71/// ```71/// ```
72/// fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, context: var, comptime Errors: type, comptime output: fn (@TypeOf(context), []const u8) Errors!void) Errors!void72/// fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void
73/// ```73/// ```
74/// with `?` being the type formatted, this function will be called instead of the default implementation.74/// with `?` being the type formatted, this function will be called instead of the default implementation.
75/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.75/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.
76///76///
77/// A user type may be a `struct`, `vector`, `union` or `enum` type.77/// A user type may be a `struct`, `vector`, `union` or `enum` type.
78pub fn format(78pub fn format(
79 context: var,79 out_stream: var,
80 comptime Errors: type,
81 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
82 comptime fmt: []const u8,80 comptime fmt: []const u8,
83 args: var,81 args: var,
84) Errors!void {82) !void {
85 const ArgSetType = u32;83 const ArgSetType = u32;
86 if (@typeInfo(@TypeOf(args)) != .Struct) {84 if (@typeInfo(@TypeOf(args)) != .Struct) {
87 @compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));85 @compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));
...@@ -138,7 +136,7 @@ pub fn format(...@@ -138,7 +136,7 @@ pub fn format(
138 .Start => switch (c) {136 .Start => switch (c) {
139 '{' => {137 '{' => {
140 if (start_index < i) {138 if (start_index < i) {
141 try output(context, fmt[start_index..i]);139 try out_stream.writeAll(fmt[start_index..i]);
142 }140 }
143141
144 start_index = i;142 start_index = i;
...@@ -150,7 +148,7 @@ pub fn format(...@@ -150,7 +148,7 @@ pub fn format(
150 },148 },
151 '}' => {149 '}' => {
152 if (start_index < i) {150 if (start_index < i) {
153 try output(context, fmt[start_index..i]);151 try out_stream.writeAll(fmt[start_index..i]);
154 }152 }
155 state = .CloseBrace;153 state = .CloseBrace;
156 },154 },
...@@ -185,9 +183,7 @@ pub fn format(...@@ -185,9 +183,7 @@ pub fn format(
185 args[arg_to_print],183 args[arg_to_print],
186 fmt[0..0],184 fmt[0..0],
187 options,185 options,
188 context,186 out_stream,
189 Errors,
190 output,
191 default_max_depth,187 default_max_depth,
192 );188 );
193189
...@@ -218,9 +214,7 @@ pub fn format(...@@ -218,9 +214,7 @@ pub fn format(
218 args[arg_to_print],214 args[arg_to_print],
219 fmt[specifier_start..i],215 fmt[specifier_start..i],
220 options,216 options,
221 context,217 out_stream,
222 Errors,
223 output,
224 default_max_depth,218 default_max_depth,
225 );219 );
226 state = .Start;220 state = .Start;
...@@ -265,9 +259,7 @@ pub fn format(...@@ -265,9 +259,7 @@ pub fn format(
265 args[arg_to_print],259 args[arg_to_print],
266 fmt[specifier_start..specifier_end],260 fmt[specifier_start..specifier_end],
267 options,261 options,
268 context,262 out_stream,
269 Errors,
270 output,
271 default_max_depth,263 default_max_depth,
272 );264 );
273 state = .Start;265 state = .Start;
...@@ -293,9 +285,7 @@ pub fn format(...@@ -293,9 +285,7 @@ pub fn format(
293 args[arg_to_print],285 args[arg_to_print],
294 fmt[specifier_start..specifier_end],286 fmt[specifier_start..specifier_end],
295 options,287 options,
296 context,288 out_stream,
297 Errors,
298 output,
299 default_max_depth,289 default_max_depth,
300 );290 );
301 state = .Start;291 state = .Start;
...@@ -316,7 +306,7 @@ pub fn format(...@@ -316,7 +306,7 @@ pub fn format(
316 }306 }
317 }307 }
318 if (start_index < fmt.len) {308 if (start_index < fmt.len) {
319 try output(context, fmt[start_index..]);309 try out_stream.writeAll(fmt[start_index..]);
320 }310 }
321}311}
322312
...@@ -324,141 +314,131 @@ pub fn formatType(...@@ -324,141 +314,131 @@ pub fn formatType(
324 value: var,314 value: var,
325 comptime fmt: []const u8,315 comptime fmt: []const u8,
326 options: FormatOptions,316 options: FormatOptions,
327 context: var,317 out_stream: var,
328 comptime Errors: type,
329 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
330 max_depth: usize,318 max_depth: usize,
331) Errors!void {319) @TypeOf(out_stream).Error!void {
332 if (comptime std.mem.eql(u8, fmt, "*")) {320 if (comptime std.mem.eql(u8, fmt, "*")) {
333 try output(context, @typeName(@TypeOf(value).Child));321 try out_stream.writeAll(@typeName(@TypeOf(value).Child));
334 try output(context, "@");322 try out_stream.writeAll("@");
335 try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, context, Errors, output);323 try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, out_stream);
336 return;324 return;
337 }325 }
338326
339 const T = @TypeOf(value);327 const T = @TypeOf(value);
328 if (comptime std.meta.trait.hasFn("format")(T)) {
329 return try value.format(fmt, options, out_stream);
330 }
331
340 switch (@typeInfo(T)) {332 switch (@typeInfo(T)) {
341 .ComptimeInt, .Int, .Float => {333 .ComptimeInt, .Int, .Float => {
342 return formatValue(value, fmt, options, context, Errors, output);334 return formatValue(value, fmt, options, out_stream);
343 },335 },
344 .Void => {336 .Void => {
345 return output(context, "void");337 return out_stream.writeAll("void");
346 },338 },
347 .Bool => {339 .Bool => {
348 return output(context, if (value) "true" else "false");340 return out_stream.writeAll(if (value) "true" else "false");
349 },341 },
350 .Optional => {342 .Optional => {
351 if (value) |payload| {343 if (value) |payload| {
352 return formatType(payload, fmt, options, context, Errors, output, max_depth);344 return formatType(payload, fmt, options, out_stream, max_depth);
353 } else {345 } else {
354 return output(context, "null");346 return out_stream.writeAll("null");
355 }347 }
356 },348 },
357 .ErrorUnion => {349 .ErrorUnion => {
358 if (value) |payload| {350 if (value) |payload| {
359 return formatType(payload, fmt, options, context, Errors, output, max_depth);351 return formatType(payload, fmt, options, out_stream, max_depth);
360 } else |err| {352 } else |err| {
361 return formatType(err, fmt, options, context, Errors, output, max_depth);353 return formatType(err, fmt, options, out_stream, max_depth);
362 }354 }
363 },355 },
364 .ErrorSet => {356 .ErrorSet => {
365 try output(context, "error.");357 try out_stream.writeAll("error.");
366 return output(context, @errorName(value));358 return out_stream.writeAll(@errorName(value));
367 },359 },
368 .Enum => |enumInfo| {360 .Enum => |enumInfo| {
369 if (comptime std.meta.trait.hasFn("format")(T)) {361 try out_stream.writeAll(@typeName(T));
370 return value.format(fmt, options, context, Errors, output);
371 }
372
373 try output(context, @typeName(T));
374 if (enumInfo.is_exhaustive) {362 if (enumInfo.is_exhaustive) {
375 try output(context, ".");363 try out_stream.writeAll(".");
376 try output(context, @tagName(value));364 try out_stream.writeAll(@tagName(value));
377 } else {365 } else {
378 // TODO: when @tagName works on exhaustive enums print known enum strings366 // TODO: when @tagName works on exhaustive enums print known enum strings
379 try output(context, "(");367 try out_stream.writeAll("(");
380 try formatType(@enumToInt(value), fmt, options, context, Errors, output, max_depth);368 try formatType(@enumToInt(value), fmt, options, out_stream, max_depth);
381 try output(context, ")");369 try out_stream.writeAll(")");
382 }370 }
383 },371 },
384 .Union => {372 .Union => {
385 if (comptime std.meta.trait.hasFn("format")(T)) {373 try out_stream.writeAll(@typeName(T));
386 return value.format(fmt, options, context, Errors, output);
387 }
388
389 try output(context, @typeName(T));
390 if (max_depth == 0) {374 if (max_depth == 0) {
391 return output(context, "{ ... }");375 return out_stream.writeAll("{ ... }");
392 }376 }
393 const info = @typeInfo(T).Union;377 const info = @typeInfo(T).Union;
394 if (info.tag_type) |UnionTagType| {378 if (info.tag_type) |UnionTagType| {
395 try output(context, "{ .");379 try out_stream.writeAll("{ .");
396 try output(context, @tagName(@as(UnionTagType, value)));380 try out_stream.writeAll(@tagName(@as(UnionTagType, value)));
397 try output(context, " = ");381 try out_stream.writeAll(" = ");
398 inline for (info.fields) |u_field| {382 inline for (info.fields) |u_field| {
399 if (@enumToInt(@as(UnionTagType, value)) == u_field.enum_field.?.value) {383 if (@enumToInt(@as(UnionTagType, value)) == u_field.enum_field.?.value) {
400 try formatType(@field(value, u_field.name), fmt, options, context, Errors, output, max_depth - 1);384 try formatType(@field(value, u_field.name), fmt, options, out_stream, max_depth - 1);
401 }385 }
402 }386 }
403 try output(context, " }");387 try out_stream.writeAll(" }");
404 } else {388 } else {
405 try format(context, Errors, output, "@{x}", .{@ptrToInt(&value)});389 try format(out_stream, "@{x}", .{@ptrToInt(&value)});
406 }390 }
407 },391 },
408 .Struct => |StructT| {392 .Struct => |StructT| {
409 if (comptime std.meta.trait.hasFn("format")(T)) {393 try out_stream.writeAll(@typeName(T));
410 return value.format(fmt, options, context, Errors, output);
411 }
412
413 try output(context, @typeName(T));
414 if (max_depth == 0) {394 if (max_depth == 0) {
415 return output(context, "{ ... }");395 return out_stream.writeAll("{ ... }");
416 }396 }
417 try output(context, "{");397 try out_stream.writeAll("{");
418 inline for (StructT.fields) |f, i| {398 inline for (StructT.fields) |f, i| {
419 if (i == 0) {399 if (i == 0) {
420 try output(context, " .");400 try out_stream.writeAll(" .");
421 } else {401 } else {
422 try output(context, ", .");402 try out_stream.writeAll(", .");
423 }403 }
424 try output(context, f.name);404 try out_stream.writeAll(f.name);
425 try output(context, " = ");405 try out_stream.writeAll(" = ");
426 try formatType(@field(value, f.name), fmt, options, context, Errors, output, max_depth - 1);406 try formatType(@field(value, f.name), fmt, options, out_stream, max_depth - 1);
427 }407 }
428 try output(context, " }");408 try out_stream.writeAll(" }");
429 },409 },
430 .Pointer => |ptr_info| switch (ptr_info.size) {410 .Pointer => |ptr_info| switch (ptr_info.size) {
431 .One => switch (@typeInfo(ptr_info.child)) {411 .One => switch (@typeInfo(ptr_info.child)) {
432 .Array => |info| {412 .Array => |info| {
433 if (info.child == u8) {413 if (info.child == u8) {
434 return formatText(value, fmt, options, context, Errors, output);414 return formatText(value, fmt, options, out_stream);
435 }415 }
436 return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });416 return format(out_stream, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
437 },417 },
438 .Enum, .Union, .Struct => {418 .Enum, .Union, .Struct => {
439 return formatType(value.*, fmt, options, context, Errors, output, max_depth);419 return formatType(value.*, fmt, options, out_stream, max_depth);
440 },420 },
441 else => return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }),421 else => return format(out_stream, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) }),
442 },422 },
443 .Many, .C => {423 .Many, .C => {
444 if (ptr_info.sentinel) |sentinel| {424 if (ptr_info.sentinel) |sentinel| {
445 return formatType(mem.span(value), fmt, options, context, Errors, output, max_depth);425 return formatType(mem.span(value), fmt, options, out_stream, max_depth);
446 }426 }
447 if (ptr_info.child == u8) {427 if (ptr_info.child == u8) {
448 if (fmt.len > 0 and fmt[0] == 's') {428 if (fmt.len > 0 and fmt[0] == 's') {
449 return formatText(mem.span(value), fmt, options, context, Errors, output);429 return formatText(mem.span(value), fmt, options, out_stream);
450 }430 }
451 }431 }
452 return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });432 return format(out_stream, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
453 },433 },
454 .Slice => {434 .Slice => {
455 if (fmt.len > 0 and ((fmt[0] == 'x') or (fmt[0] == 'X'))) {435 if (fmt.len > 0 and ((fmt[0] == 'x') or (fmt[0] == 'X'))) {
456 return formatText(value, fmt, options, context, Errors, output);436 return formatText(value, fmt, options, out_stream);
457 }437 }
458 if (ptr_info.child == u8) {438 if (ptr_info.child == u8) {
459 return formatText(value, fmt, options, context, Errors, output);439 return formatText(value, fmt, options, out_stream);
460 }440 }
461 return format(context, Errors, output, "{}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value.ptr) });441 return format(out_stream, "{}@{x}", .{ @typeName(ptr_info.child), @ptrToInt(value.ptr) });
462 },442 },
463 },443 },
464 .Array => |info| {444 .Array => |info| {
...@@ -473,30 +453,27 @@ pub fn formatType(...@@ -473,30 +453,27 @@ pub fn formatType(
473 .sentinel = null,453 .sentinel = null,
474 },454 },
475 });455 });
476 return formatType(@as(Slice, &value), fmt, options, context, Errors, output, max_depth);456 return formatType(@as(Slice, &value), fmt, options, out_stream, max_depth);
477 },457 },
478 .Vector => {458 .Vector => {
479 const len = @typeInfo(T).Vector.len;459 const len = @typeInfo(T).Vector.len;
480 try output(context, "{ ");460 try out_stream.writeAll("{ ");
481 var i: usize = 0;461 var i: usize = 0;
482 while (i < len) : (i += 1) {462 while (i < len) : (i += 1) {
483 try formatValue(value[i], fmt, options, context, Errors, output);463 try formatValue(value[i], fmt, options, out_stream);
484 if (i < len - 1) {464 if (i < len - 1) {
485 try output(context, ", ");465 try out_stream.writeAll(", ");
486 }466 }
487 }467 }
488 try output(context, " }");468 try out_stream.writeAll(" }");
489 },469 },
490 .Fn => {470 .Fn => {
491 return format(context, Errors, output, "{}@{x}", .{ @typeName(T), @ptrToInt(value) });471 return format(out_stream, "{}@{x}", .{ @typeName(T), @ptrToInt(value) });
492 },472 },
493 .Type => return output(context, @typeName(T)),473 .Type => return out_stream.writeAll(@typeName(T)),
494 .EnumLiteral => {474 .EnumLiteral => {
495 const name = @tagName(value);475 const buffer = [_]u8{'.'} ++ @tagName(value);
496 var buffer: [name.len + 1]u8 = undefined;476 return formatType(buffer, fmt, options, out_stream, max_depth);
497 buffer[0] = '.';
498 std.mem.copy(u8, buffer[1..], name);
499 return formatType(buffer, fmt, options, context, Errors, output, max_depth);
500 },477 },
501 else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"),478 else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"),
502 }479 }
...@@ -506,21 +483,19 @@ fn formatValue(...@@ -506,21 +483,19 @@ fn formatValue(
506 value: var,483 value: var,
507 comptime fmt: []const u8,484 comptime fmt: []const u8,
508 options: FormatOptions,485 options: FormatOptions,
509 context: var,486 out_stream: var,
510 comptime Errors: type,487) !void {
511 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
512) Errors!void {
513 if (comptime std.mem.eql(u8, fmt, "B")) {488 if (comptime std.mem.eql(u8, fmt, "B")) {
514 return formatBytes(value, options, 1000, context, Errors, output);489 return formatBytes(value, options, 1000, out_stream);
515 } else if (comptime std.mem.eql(u8, fmt, "Bi")) {490 } else if (comptime std.mem.eql(u8, fmt, "Bi")) {
516 return formatBytes(value, options, 1024, context, Errors, output);491 return formatBytes(value, options, 1024, out_stream);
517 }492 }
518493
519 const T = @TypeOf(value);494 const T = @TypeOf(value);
520 switch (@typeInfo(T)) {495 switch (@typeInfo(T)) {
521 .Float => return formatFloatValue(value, fmt, options, context, Errors, output),496 .Float => return formatFloatValue(value, fmt, options, out_stream),
522 .Int, .ComptimeInt => return formatIntValue(value, fmt, options, context, Errors, output),497 .Int, .ComptimeInt => return formatIntValue(value, fmt, options, out_stream),
523 .Bool => return output(context, if (value) "true" else "false"),498 .Bool => return out_stream.writeAll(if (value) "true" else "false"),
524 else => comptime unreachable,499 else => comptime unreachable,
525 }500 }
526}501}
...@@ -529,10 +504,8 @@ pub fn formatIntValue(...@@ -529,10 +504,8 @@ pub fn formatIntValue(
529 value: var,504 value: var,
530 comptime fmt: []const u8,505 comptime fmt: []const u8,
531 options: FormatOptions,506 options: FormatOptions,
532 context: var,507 out_stream: var,
533 comptime Errors: type,508) !void {
534 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
535) Errors!void {
536 comptime var radix = 10;509 comptime var radix = 10;
537 comptime var uppercase = false;510 comptime var uppercase = false;
538511
...@@ -547,7 +520,7 @@ pub fn formatIntValue(...@@ -547,7 +520,7 @@ pub fn formatIntValue(
547 uppercase = false;520 uppercase = false;
548 } else if (comptime std.mem.eql(u8, fmt, "c")) {521 } else if (comptime std.mem.eql(u8, fmt, "c")) {
549 if (@TypeOf(int_value).bit_count <= 8) {522 if (@TypeOf(int_value).bit_count <= 8) {
550 return formatAsciiChar(@as(u8, int_value), options, context, Errors, output);523 return formatAsciiChar(@as(u8, int_value), options, out_stream);
551 } else {524 } else {
552 @compileError("Cannot print integer that is larger than 8 bits as a ascii");525 @compileError("Cannot print integer that is larger than 8 bits as a ascii");
553 }526 }
...@@ -564,21 +537,19 @@ pub fn formatIntValue(...@@ -564,21 +537,19 @@ pub fn formatIntValue(
564 @compileError("Unknown format string: '" ++ fmt ++ "'");537 @compileError("Unknown format string: '" ++ fmt ++ "'");
565 }538 }
566539
567 return formatInt(int_value, radix, uppercase, options, context, Errors, output);540 return formatInt(int_value, radix, uppercase, options, out_stream);
568}541}
569542
570fn formatFloatValue(543fn formatFloatValue(
571 value: var,544 value: var,
572 comptime fmt: []const u8,545 comptime fmt: []const u8,
573 options: FormatOptions,546 options: FormatOptions,
574 context: var,547 out_stream: var,
575 comptime Errors: type,548) !void {
576 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
577) Errors!void {
578 if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "e")) {549 if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "e")) {
579 return formatFloatScientific(value, options, context, Errors, output);550 return formatFloatScientific(value, options, out_stream);
580 } else if (comptime std.mem.eql(u8, fmt, "d")) {551 } else if (comptime std.mem.eql(u8, fmt, "d")) {
581 return formatFloatDecimal(value, options, context, Errors, output);552 return formatFloatDecimal(value, options, out_stream);
582 } else {553 } else {
583 @compileError("Unknown format string: '" ++ fmt ++ "'");554 @compileError("Unknown format string: '" ++ fmt ++ "'");
584 }555 }
...@@ -588,17 +559,15 @@ pub fn formatText(...@@ -588,17 +559,15 @@ pub fn formatText(
588 bytes: []const u8,559 bytes: []const u8,
589 comptime fmt: []const u8,560 comptime fmt: []const u8,
590 options: FormatOptions,561 options: FormatOptions,
591 context: var,562 out_stream: var,
592 comptime Errors: type,563) !void {
593 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
594) Errors!void {
595 if (fmt.len == 0) {564 if (fmt.len == 0) {
596 return output(context, bytes);565 return out_stream.writeAll(bytes);
597 } else if (comptime std.mem.eql(u8, fmt, "s")) {566 } else if (comptime std.mem.eql(u8, fmt, "s")) {
598 return formatBuf(bytes, options, context, Errors, output);567 return formatBuf(bytes, options, out_stream);
599 } else if (comptime (std.mem.eql(u8, fmt, "x") or std.mem.eql(u8, fmt, "X"))) {568 } else if (comptime (std.mem.eql(u8, fmt, "x") or std.mem.eql(u8, fmt, "X"))) {
600 for (bytes) |c| {569 for (bytes) |c| {
601 try formatInt(c, 16, fmt[0] == 'X', FormatOptions{ .width = 2, .fill = '0' }, context, Errors, output);570 try formatInt(c, 16, fmt[0] == 'X', FormatOptions{ .width = 2, .fill = '0' }, out_stream);
602 }571 }
603 return;572 return;
604 } else {573 } else {
...@@ -609,27 +578,23 @@ pub fn formatText(...@@ -609,27 +578,23 @@ pub fn formatText(
609pub fn formatAsciiChar(578pub fn formatAsciiChar(
610 c: u8,579 c: u8,
611 options: FormatOptions,580 options: FormatOptions,
612 context: var,581 out_stream: var,
613 comptime Errors: type,582) !void {
614 comptime output: fn (@TypeOf(context), []const u8) Errors!void,583 return out_stream.writeAll(@as(*const [1]u8, &c));
615) Errors!void {
616 return output(context, @as(*const [1]u8, &c)[0..]);
617}584}
618585
619pub fn formatBuf(586pub fn formatBuf(
620 buf: []const u8,587 buf: []const u8,
621 options: FormatOptions,588 options: FormatOptions,
622 context: var,589 out_stream: var,
623 comptime Errors: type,590) !void {
624 comptime output: fn (@TypeOf(context), []const u8) Errors!void,591 try out_stream.writeAll(buf);
625) Errors!void {
626 try output(context, buf);
627592
628 const width = options.width orelse 0;593 const width = options.width orelse 0;
629 var leftover_padding = if (width > buf.len) (width - buf.len) else return;594 var leftover_padding = if (width > buf.len) (width - buf.len) else return;
630 const pad_byte: u8 = options.fill;595 const pad_byte = [1]u8{options.fill};
631 while (leftover_padding > 0) : (leftover_padding -= 1) {596 while (leftover_padding > 0) : (leftover_padding -= 1) {
632 try output(context, @as(*const [1]u8, &pad_byte)[0..1]);597 try out_stream.writeAll(&pad_byte);
633 }598 }
634}599}
635600
...@@ -639,40 +604,38 @@ pub fn formatBuf(...@@ -639,40 +604,38 @@ pub fn formatBuf(
639pub fn formatFloatScientific(604pub fn formatFloatScientific(
640 value: var,605 value: var,
641 options: FormatOptions,606 options: FormatOptions,
642 context: var,607 out_stream: var,
643 comptime Errors: type,608) !void {
644 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
645) Errors!void {
646 var x = @floatCast(f64, value);609 var x = @floatCast(f64, value);
647610
648 // Errol doesn't handle these special cases.611 // Errol doesn't handle these special cases.
649 if (math.signbit(x)) {612 if (math.signbit(x)) {
650 try output(context, "-");613 try out_stream.writeAll("-");
651 x = -x;614 x = -x;
652 }615 }
653616
654 if (math.isNan(x)) {617 if (math.isNan(x)) {
655 return output(context, "nan");618 return out_stream.writeAll("nan");
656 }619 }
657 if (math.isPositiveInf(x)) {620 if (math.isPositiveInf(x)) {
658 return output(context, "inf");621 return out_stream.writeAll("inf");
659 }622 }
660 if (x == 0.0) {623 if (x == 0.0) {
661 try output(context, "0");624 try out_stream.writeAll("0");
662625
663 if (options.precision) |precision| {626 if (options.precision) |precision| {
664 if (precision != 0) {627 if (precision != 0) {
665 try output(context, ".");628 try out_stream.writeAll(".");
666 var i: usize = 0;629 var i: usize = 0;
667 while (i < precision) : (i += 1) {630 while (i < precision) : (i += 1) {
668 try output(context, "0");631 try out_stream.writeAll("0");
669 }632 }
670 }633 }
671 } else {634 } else {
672 try output(context, ".0");635 try out_stream.writeAll(".0");
673 }636 }
674637
675 try output(context, "e+00");638 try out_stream.writeAll("e+00");
676 return;639 return;
677 }640 }
678641
...@@ -682,50 +645,50 @@ pub fn formatFloatScientific(...@@ -682,50 +645,50 @@ pub fn formatFloatScientific(
682 if (options.precision) |precision| {645 if (options.precision) |precision| {
683 errol.roundToPrecision(&float_decimal, precision, errol.RoundMode.Scientific);646 errol.roundToPrecision(&float_decimal, precision, errol.RoundMode.Scientific);
684647
685 try output(context, float_decimal.digits[0..1]);648 try out_stream.writeAll(float_decimal.digits[0..1]);
686649
687 // {e0} case prints no `.`650 // {e0} case prints no `.`
688 if (precision != 0) {651 if (precision != 0) {
689 try output(context, ".");652 try out_stream.writeAll(".");
690653
691 var printed: usize = 0;654 var printed: usize = 0;
692 if (float_decimal.digits.len > 1) {655 if (float_decimal.digits.len > 1) {
693 const num_digits = math.min(float_decimal.digits.len, precision + 1);656 const num_digits = math.min(float_decimal.digits.len, precision + 1);
694 try output(context, float_decimal.digits[1..num_digits]);657 try out_stream.writeAll(float_decimal.digits[1..num_digits]);
695 printed += num_digits - 1;658 printed += num_digits - 1;
696 }659 }
697660
698 while (printed < precision) : (printed += 1) {661 while (printed < precision) : (printed += 1) {
699 try output(context, "0");662 try out_stream.writeAll("0");
700 }663 }
701 }664 }
702 } else {665 } else {
703 try output(context, float_decimal.digits[0..1]);666 try out_stream.writeAll(float_decimal.digits[0..1]);
704 try output(context, ".");667 try out_stream.writeAll(".");
705 if (float_decimal.digits.len > 1) {668 if (float_decimal.digits.len > 1) {
706 const num_digits = if (@TypeOf(value) == f32) math.min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len;669 const num_digits = if (@TypeOf(value) == f32) math.min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len;
707670
708 try output(context, float_decimal.digits[1..num_digits]);671 try out_stream.writeAll(float_decimal.digits[1..num_digits]);
709 } else {672 } else {
710 try output(context, "0");673 try out_stream.writeAll("0");
711 }674 }
712 }675 }
713676
714 try output(context, "e");677 try out_stream.writeAll("e");
715 const exp = float_decimal.exp - 1;678 const exp = float_decimal.exp - 1;
716679
717 if (exp >= 0) {680 if (exp >= 0) {
718 try output(context, "+");681 try out_stream.writeAll("+");
719 if (exp > -10 and exp < 10) {682 if (exp > -10 and exp < 10) {
720 try output(context, "0");683 try out_stream.writeAll("0");
721 }684 }
722 try formatInt(exp, 10, false, FormatOptions{ .width = 0 }, context, Errors, output);685 try formatInt(exp, 10, false, FormatOptions{ .width = 0 }, out_stream);
723 } else {686 } else {
724 try output(context, "-");687 try out_stream.writeAll("-");
725 if (exp > -10 and exp < 10) {688 if (exp > -10 and exp < 10) {
726 try output(context, "0");689 try out_stream.writeAll("0");
727 }690 }
728 try formatInt(-exp, 10, false, FormatOptions{ .width = 0 }, context, Errors, output);691 try formatInt(-exp, 10, false, FormatOptions{ .width = 0 }, out_stream);
729 }692 }
730}693}
731694
...@@ -734,36 +697,34 @@ pub fn formatFloatScientific(...@@ -734,36 +697,34 @@ pub fn formatFloatScientific(
734pub fn formatFloatDecimal(697pub fn formatFloatDecimal(
735 value: var,698 value: var,
736 options: FormatOptions,699 options: FormatOptions,
737 context: var,700 out_stream: var,
738 comptime Errors: type,701) !void {
739 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
740) Errors!void {
741 var x = @as(f64, value);702 var x = @as(f64, value);
742703
743 // Errol doesn't handle these special cases.704 // Errol doesn't handle these special cases.
744 if (math.signbit(x)) {705 if (math.signbit(x)) {
745 try output(context, "-");706 try out_stream.writeAll("-");
746 x = -x;707 x = -x;
747 }708 }
748709
749 if (math.isNan(x)) {710 if (math.isNan(x)) {
750 return output(context, "nan");711 return out_stream.writeAll("nan");
751 }712 }
752 if (math.isPositiveInf(x)) {713 if (math.isPositiveInf(x)) {
753 return output(context, "inf");714 return out_stream.writeAll("inf");
754 }715 }
755 if (x == 0.0) {716 if (x == 0.0) {
756 try output(context, "0");717 try out_stream.writeAll("0");
757718
758 if (options.precision) |precision| {719 if (options.precision) |precision| {
759 if (precision != 0) {720 if (precision != 0) {
760 try output(context, ".");721 try out_stream.writeAll(".");
761 var i: usize = 0;722 var i: usize = 0;
762 while (i < precision) : (i += 1) {723 while (i < precision) : (i += 1) {
763 try output(context, "0");724 try out_stream.writeAll("0");
764 }725 }
765 } else {726 } else {
766 try output(context, ".0");727 try out_stream.writeAll(".0");
767 }728 }
768 }729 }
769730
...@@ -785,14 +746,14 @@ pub fn formatFloatDecimal(...@@ -785,14 +746,14 @@ pub fn formatFloatDecimal(
785746
786 if (num_digits_whole > 0) {747 if (num_digits_whole > 0) {
787 // We may have to zero pad, for instance 1e4 requires zero padding.748 // We may have to zero pad, for instance 1e4 requires zero padding.
788 try output(context, float_decimal.digits[0..num_digits_whole_no_pad]);749 try out_stream.writeAll(float_decimal.digits[0..num_digits_whole_no_pad]);
789750
790 var i = num_digits_whole_no_pad;751 var i = num_digits_whole_no_pad;
791 while (i < num_digits_whole) : (i += 1) {752 while (i < num_digits_whole) : (i += 1) {
792 try output(context, "0");753 try out_stream.writeAll("0");
793 }754 }
794 } else {755 } else {
795 try output(context, "0");756 try out_stream.writeAll("0");
796 }757 }
797758
798 // {.0} special case doesn't want a trailing '.'759 // {.0} special case doesn't want a trailing '.'
...@@ -800,7 +761,7 @@ pub fn formatFloatDecimal(...@@ -800,7 +761,7 @@ pub fn formatFloatDecimal(
800 return;761 return;
801 }762 }
802763
803 try output(context, ".");764 try out_stream.writeAll(".");
804765
805 // Keep track of fractional count printed for case where we pre-pad then post-pad with 0's.766 // Keep track of fractional count printed for case where we pre-pad then post-pad with 0's.
806 var printed: usize = 0;767 var printed: usize = 0;
...@@ -812,7 +773,7 @@ pub fn formatFloatDecimal(...@@ -812,7 +773,7 @@ pub fn formatFloatDecimal(
812773
813 var i: usize = 0;774 var i: usize = 0;
814 while (i < zeros_to_print) : (i += 1) {775 while (i < zeros_to_print) : (i += 1) {
815 try output(context, "0");776 try out_stream.writeAll("0");
816 printed += 1;777 printed += 1;
817 }778 }
818779
...@@ -824,14 +785,14 @@ pub fn formatFloatDecimal(...@@ -824,14 +785,14 @@ pub fn formatFloatDecimal(
824 // Remaining fractional portion, zero-padding if insufficient.785 // Remaining fractional portion, zero-padding if insufficient.
825 assert(precision >= printed);786 assert(precision >= printed);
826 if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) {787 if (num_digits_whole_no_pad + precision - printed < float_decimal.digits.len) {
827 try output(context, float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]);788 try out_stream.writeAll(float_decimal.digits[num_digits_whole_no_pad .. num_digits_whole_no_pad + precision - printed]);
828 return;789 return;
829 } else {790 } else {
830 try output(context, float_decimal.digits[num_digits_whole_no_pad..]);791 try out_stream.writeAll(float_decimal.digits[num_digits_whole_no_pad..]);
831 printed += float_decimal.digits.len - num_digits_whole_no_pad;792 printed += float_decimal.digits.len - num_digits_whole_no_pad;
832793
833 while (printed < precision) : (printed += 1) {794 while (printed < precision) : (printed += 1) {
834 try output(context, "0");795 try out_stream.writeAll("0");
835 }796 }
836 }797 }
837 } else {798 } else {
...@@ -843,14 +804,14 @@ pub fn formatFloatDecimal(...@@ -843,14 +804,14 @@ pub fn formatFloatDecimal(
843804
844 if (num_digits_whole > 0) {805 if (num_digits_whole > 0) {
845 // We may have to zero pad, for instance 1e4 requires zero padding.806 // We may have to zero pad, for instance 1e4 requires zero padding.
846 try output(context, float_decimal.digits[0..num_digits_whole_no_pad]);807 try out_stream.writeAll(float_decimal.digits[0..num_digits_whole_no_pad]);
847808
848 var i = num_digits_whole_no_pad;809 var i = num_digits_whole_no_pad;
849 while (i < num_digits_whole) : (i += 1) {810 while (i < num_digits_whole) : (i += 1) {
850 try output(context, "0");811 try out_stream.writeAll("0");
851 }812 }
852 } else {813 } else {
853 try output(context, "0");814 try out_stream.writeAll("0");
854 }815 }
855816
856 // Omit `.` if no fractional portion817 // Omit `.` if no fractional portion
...@@ -858,7 +819,7 @@ pub fn formatFloatDecimal(...@@ -858,7 +819,7 @@ pub fn formatFloatDecimal(
858 return;819 return;
859 }820 }
860821
861 try output(context, ".");822 try out_stream.writeAll(".");
862823
863 // Zero-fill until we reach significant digits or run out of precision.824 // Zero-fill until we reach significant digits or run out of precision.
864 if (float_decimal.exp < 0) {825 if (float_decimal.exp < 0) {
...@@ -866,11 +827,11 @@ pub fn formatFloatDecimal(...@@ -866,11 +827,11 @@ pub fn formatFloatDecimal(
866827
867 var i: usize = 0;828 var i: usize = 0;
868 while (i < zero_digit_count) : (i += 1) {829 while (i < zero_digit_count) : (i += 1) {
869 try output(context, "0");830 try out_stream.writeAll("0");
870 }831 }
871 }832 }
872833
873 try output(context, float_decimal.digits[num_digits_whole_no_pad..]);834 try out_stream.writeAll(float_decimal.digits[num_digits_whole_no_pad..]);
874 }835 }
875}836}
876837
...@@ -878,12 +839,10 @@ pub fn formatBytes(...@@ -878,12 +839,10 @@ pub fn formatBytes(
878 value: var,839 value: var,
879 options: FormatOptions,840 options: FormatOptions,
880 comptime radix: usize,841 comptime radix: usize,
881 context: var,842 out_stream: var,
882 comptime Errors: type,843) !void {
883 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
884) Errors!void {
885 if (value == 0) {844 if (value == 0) {
886 return output(context, "0B");845 return out_stream.writeAll("0B");
887 }846 }
888847
889 const mags_si = " kMGTPEZY";848 const mags_si = " kMGTPEZY";
...@@ -900,10 +859,10 @@ pub fn formatBytes(...@@ -900,10 +859,10 @@ pub fn formatBytes(
900 else => unreachable,859 else => unreachable,
901 };860 };
902861
903 try formatFloatDecimal(new_value, options, context, Errors, output);862 try formatFloatDecimal(new_value, options, out_stream);
904863
905 if (suffix == ' ') {864 if (suffix == ' ') {
906 return output(context, "B");865 return out_stream.writeAll("B");
907 }866 }
908867
909 const buf = switch (radix) {868 const buf = switch (radix) {
...@@ -911,7 +870,7 @@ pub fn formatBytes(...@@ -911,7 +870,7 @@ pub fn formatBytes(
911 1024 => &[_]u8{ suffix, 'i', 'B' },870 1024 => &[_]u8{ suffix, 'i', 'B' },
912 else => unreachable,871 else => unreachable,
913 };872 };
914 return output(context, buf);873 return out_stream.writeAll(buf);
915}874}
916875
917pub fn formatInt(876pub fn formatInt(
...@@ -919,10 +878,8 @@ pub fn formatInt(...@@ -919,10 +878,8 @@ pub fn formatInt(
919 base: u8,878 base: u8,
920 uppercase: bool,879 uppercase: bool,
921 options: FormatOptions,880 options: FormatOptions,
922 context: var,881 out_stream: var,
923 comptime Errors: type,882) !void {
924 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
925) Errors!void {
926 const int_value = if (@TypeOf(value) == comptime_int) blk: {883 const int_value = if (@TypeOf(value) == comptime_int) blk: {
927 const Int = math.IntFittingRange(value, value);884 const Int = math.IntFittingRange(value, value);
928 break :blk @as(Int, value);885 break :blk @as(Int, value);
...@@ -930,9 +887,9 @@ pub fn formatInt(...@@ -930,9 +887,9 @@ pub fn formatInt(
930 value;887 value;
931888
932 if (@TypeOf(int_value).is_signed) {889 if (@TypeOf(int_value).is_signed) {
933 return formatIntSigned(int_value, base, uppercase, options, context, Errors, output);890 return formatIntSigned(int_value, base, uppercase, options, out_stream);
934 } else {891 } else {
935 return formatIntUnsigned(int_value, base, uppercase, options, context, Errors, output);892 return formatIntUnsigned(int_value, base, uppercase, options, out_stream);
936 }893 }
937}894}
938895
...@@ -941,10 +898,8 @@ fn formatIntSigned(...@@ -941,10 +898,8 @@ fn formatIntSigned(
941 base: u8,898 base: u8,
942 uppercase: bool,899 uppercase: bool,
943 options: FormatOptions,900 options: FormatOptions,
944 context: var,901 out_stream: var,
945 comptime Errors: type,902) !void {
946 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
947) Errors!void {
948 const new_options = FormatOptions{903 const new_options = FormatOptions{
949 .width = if (options.width) |w| (if (w == 0) 0 else w - 1) else null,904 .width = if (options.width) |w| (if (w == 0) 0 else w - 1) else null,
950 .precision = options.precision,905 .precision = options.precision,
...@@ -953,15 +908,15 @@ fn formatIntSigned(...@@ -953,15 +908,15 @@ fn formatIntSigned(
953 const bit_count = @typeInfo(@TypeOf(value)).Int.bits;908 const bit_count = @typeInfo(@TypeOf(value)).Int.bits;
954 const Uint = std.meta.IntType(false, bit_count);909 const Uint = std.meta.IntType(false, bit_count);
955 if (value < 0) {910 if (value < 0) {
956 try output(context, "-");911 try out_stream.writeAll("-");
957 const new_value = math.absCast(value);912 const new_value = math.absCast(value);
958 return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output);913 return formatIntUnsigned(new_value, base, uppercase, new_options, out_stream);
959 } else if (options.width == null or options.width.? == 0) {914 } else if (options.width == null or options.width.? == 0) {
960 return formatIntUnsigned(@intCast(Uint, value), base, uppercase, options, context, Errors, output);915 return formatIntUnsigned(@intCast(Uint, value), base, uppercase, options, out_stream);
961 } else {916 } else {
962 try output(context, "+");917 try out_stream.writeAll("+");
963 const new_value = @intCast(Uint, value);918 const new_value = @intCast(Uint, value);
964 return formatIntUnsigned(new_value, base, uppercase, new_options, context, Errors, output);919 return formatIntUnsigned(new_value, base, uppercase, new_options, out_stream);
965 }920 }
966}921}
967922
...@@ -970,10 +925,8 @@ fn formatIntUnsigned(...@@ -970,10 +925,8 @@ fn formatIntUnsigned(
970 base: u8,925 base: u8,
971 uppercase: bool,926 uppercase: bool,
972 options: FormatOptions,927 options: FormatOptions,
973 context: var,928 out_stream: var,
974 comptime Errors: type,929) !void {
975 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
976) Errors!void {
977 assert(base >= 2);930 assert(base >= 2);
978 var buf: [math.max(@TypeOf(value).bit_count, 1)]u8 = undefined;931 var buf: [math.max(@TypeOf(value).bit_count, 1)]u8 = undefined;
979 const min_int_bits = comptime math.max(@TypeOf(value).bit_count, @TypeOf(base).bit_count);932 const min_int_bits = comptime math.max(@TypeOf(value).bit_count, @TypeOf(base).bit_count);
...@@ -997,34 +950,23 @@ fn formatIntUnsigned(...@@ -997,34 +950,23 @@ fn formatIntUnsigned(
997 const zero_byte: u8 = options.fill;950 const zero_byte: u8 = options.fill;
998 var leftover_padding = padding - index;951 var leftover_padding = padding - index;
999 while (true) {952 while (true) {
1000 try output(context, @as(*const [1]u8, &zero_byte)[0..]);953 try out_stream.writeAll(@as(*const [1]u8, &zero_byte)[0..]);
1001 leftover_padding -= 1;954 leftover_padding -= 1;
1002 if (leftover_padding == 0) break;955 if (leftover_padding == 0) break;
1003 }956 }
1004 mem.set(u8, buf[0..index], options.fill);957 mem.set(u8, buf[0..index], options.fill);
1005 return output(context, &buf);958 return out_stream.writeAll(&buf);
1006 } else {959 } else {
1007 const padded_buf = buf[index - padding ..];960 const padded_buf = buf[index - padding ..];
1008 mem.set(u8, padded_buf[0..padding], options.fill);961 mem.set(u8, padded_buf[0..padding], options.fill);
1009 return output(context, padded_buf);962 return out_stream.writeAll(padded_buf);
1010 }963 }
1011}964}
1012965
1013pub fn formatIntBuf(out_buf: []u8, value: var, base: u8, uppercase: bool, options: FormatOptions) usize {966pub fn formatIntBuf(out_buf: []u8, value: var, base: u8, uppercase: bool, options: FormatOptions) usize {
1014 var context = FormatIntBuf{967 var fbs = std.io.fixedBufferStream(out_buf);
1015 .out_buf = out_buf,968 formatInt(value, base, uppercase, options, fbs.outStream()) catch unreachable;
1016 .index = 0,969 return fbs.pos;
1017 };
1018 formatInt(value, base, uppercase, options, &context, error{}, formatIntCallback) catch unreachable;
1019 return context.index;
1020}
1021const FormatIntBuf = struct {
1022 out_buf: []u8,
1023 index: usize,
1024};
1025fn formatIntCallback(context: *FormatIntBuf, bytes: []const u8) (error{}!void) {
1026 mem.copy(u8, context.out_buf[context.index..], bytes);
1027 context.index += bytes.len;
1028}970}
1029971
1030pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) !T {972pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) !T {
...@@ -1124,44 +1066,36 @@ fn digitToChar(digit: u8, uppercase: bool) u8 {...@@ -1124,44 +1066,36 @@ fn digitToChar(digit: u8, uppercase: bool) u8 {
1124 };1066 };
1125}1067}
11261068
1127const BufPrintContext = struct {
1128 remaining: []u8,
1129};
1130
1131fn bufPrintWrite(context: *BufPrintContext, bytes: []const u8) !void {
1132 if (context.remaining.len < bytes.len) {
1133 mem.copy(u8, context.remaining, bytes[0..context.remaining.len]);
1134 return error.BufferTooSmall;
1135 }
1136 mem.copy(u8, context.remaining, bytes);
1137 context.remaining = context.remaining[bytes.len..];
1138}
1139
1140pub const BufPrintError = error{1069pub const BufPrintError = error{
1141 /// As much as possible was written to the buffer, but it was too small to fit all the printed bytes.1070 /// As much as possible was written to the buffer, but it was too small to fit all the printed bytes.
1142 BufferTooSmall,1071 NoSpaceLeft,
1143};1072};
1144pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![]u8 {1073pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![]u8 {
1145 var context = BufPrintContext{ .remaining = buf };1074 var fbs = std.io.fixedBufferStream(buf);
1146 try format(&context, BufPrintError, bufPrintWrite, fmt, args);1075 try format(fbs.outStream(), fmt, args);
1147 return buf[0 .. buf.len - context.remaining.len];1076 return fbs.getWritten();
1077}
1078
1079// Count the characters needed for format. Useful for preallocating memory
1080pub fn count(comptime fmt: []const u8, args: var) u64 {
1081 var counting_stream = std.io.countingOutStream(std.io.null_out_stream);
1082 format(counting_stream.outStream(), fmt, args) catch |err| switch (err) {};
1083 return counting_stream.bytes_written;
1148}1084}
11491085
1150pub const AllocPrintError = error{OutOfMemory};1086pub const AllocPrintError = error{OutOfMemory};
11511087
1152pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {1088pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {
1153 var size: usize = 0;1089 const size = math.cast(usize, count(fmt, args)) catch |err| switch (err) {
1154 format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {};1090 // Output too long. Can't possibly allocate enough memory to display it.
1091 error.Overflow => return error.OutOfMemory,
1092 };
1155 const buf = try allocator.alloc(u8, size);1093 const buf = try allocator.alloc(u8, size);
1156 return bufPrint(buf, fmt, args) catch |err| switch (err) {1094 return bufPrint(buf, fmt, args) catch |err| switch (err) {
1157 error.BufferTooSmall => unreachable, // we just counted the size above1095 error.NoSpaceLeft => unreachable, // we just counted the size above
1158 };1096 };
1159}1097}
11601098
1161fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
1162 size.* += bytes.len;
1163}
1164
1165pub fn allocPrint0(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![:0]u8 {1099pub fn allocPrint0(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![:0]u8 {
1166 const result = try allocPrint(allocator, fmt ++ "\x00", args);1100 const result = try allocPrint(allocator, fmt ++ "\x00", args);
1167 return result[0 .. result.len - 1 :0];1101 return result[0 .. result.len - 1 :0];
...@@ -1254,20 +1188,17 @@ test "int.padded" {...@@ -1254,20 +1188,17 @@ test "int.padded" {
1254test "buffer" {1188test "buffer" {
1255 {1189 {
1256 var buf1: [32]u8 = undefined;1190 var buf1: [32]u8 = undefined;
1257 var context = BufPrintContext{ .remaining = buf1[0..] };1191 var fbs = std.io.fixedBufferStream(&buf1);
1258 try formatType(1234, "", FormatOptions{}, &context, error{BufferTooSmall}, bufPrintWrite, default_max_depth);1192 try formatType(1234, "", FormatOptions{}, fbs.outStream(), default_max_depth);
1259 var res = buf1[0 .. buf1.len - context.remaining.len];1193 std.testing.expect(mem.eql(u8, fbs.getWritten(), "1234"));
1260 std.testing.expect(mem.eql(u8, res, "1234"));1194
12611195 fbs.reset();
1262 context = BufPrintContext{ .remaining = buf1[0..] };1196 try formatType('a', "c", FormatOptions{}, fbs.outStream(), default_max_depth);
1263 try formatType('a', "c", FormatOptions{}, &context, error{BufferTooSmall}, bufPrintWrite, default_max_depth);1197 std.testing.expect(mem.eql(u8, fbs.getWritten(), "a"));
1264 res = buf1[0 .. buf1.len - context.remaining.len];1198
1265 std.testing.expect(mem.eql(u8, res, "a"));1199 fbs.reset();
12661200 try formatType(0b1100, "b", FormatOptions{}, fbs.outStream(), default_max_depth);
1267 context = BufPrintContext{ .remaining = buf1[0..] };1201 std.testing.expect(mem.eql(u8, fbs.getWritten(), "1100"));
1268 try formatType(0b1100, "b", FormatOptions{}, &context, error{BufferTooSmall}, bufPrintWrite, default_max_depth);
1269 res = buf1[0 .. buf1.len - context.remaining.len];
1270 std.testing.expect(mem.eql(u8, res, "1100"));
1271 }1202 }
1272}1203}
12731204
...@@ -1452,14 +1383,12 @@ test "custom" {...@@ -1452,14 +1383,12 @@ test "custom" {
1452 self: SelfType,1383 self: SelfType,
1453 comptime fmt: []const u8,1384 comptime fmt: []const u8,
1454 options: FormatOptions,1385 options: FormatOptions,
1455 context: var,1386 out_stream: var,
1456 comptime Errors: type,1387 ) !void {
1457 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
1458 ) Errors!void {
1459 if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "p")) {1388 if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "p")) {
1460 return std.fmt.format(context, Errors, output, "({d:.3},{d:.3})", .{ self.x, self.y });1389 return std.fmt.format(out_stream, "({d:.3},{d:.3})", .{ self.x, self.y });
1461 } else if (comptime std.mem.eql(u8, fmt, "d")) {1390 } else if (comptime std.mem.eql(u8, fmt, "d")) {
1462 return std.fmt.format(context, Errors, output, "{d:.3}x{d:.3}", .{ self.x, self.y });1391 return std.fmt.format(out_stream, "{d:.3}x{d:.3}", .{ self.x, self.y });
1463 } else {1392 } else {
1464 @compileError("Unknown format character: '" ++ fmt ++ "'");1393 @compileError("Unknown format character: '" ++ fmt ++ "'");
1465 }1394 }
...@@ -1643,10 +1572,10 @@ test "hexToBytes" {...@@ -1643,10 +1572,10 @@ test "hexToBytes" {
1643test "formatIntValue with comptime_int" {1572test "formatIntValue with comptime_int" {
1644 const value: comptime_int = 123456789123456789;1573 const value: comptime_int = 123456789123456789;
16451574
1646 var buf = std.ArrayList(u8).init(std.testing.allocator);1575 var buf: [20]u8 = undefined;
1647 defer buf.deinit();1576 var fbs = std.io.fixedBufferStream(&buf);
1648 try formatIntValue(value, "", FormatOptions{}, &buf, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice);1577 try formatIntValue(value, "", FormatOptions{}, fbs.outStream());
1649 std.testing.expect(mem.eql(u8, buf.toSliceConst(), "123456789123456789"));1578 std.testing.expect(mem.eql(u8, fbs.getWritten(), "123456789123456789"));
1650}1579}
16511580
1652test "formatType max_depth" {1581test "formatType max_depth" {
...@@ -1659,12 +1588,10 @@ test "formatType max_depth" {...@@ -1659,12 +1588,10 @@ test "formatType max_depth" {
1659 self: SelfType,1588 self: SelfType,
1660 comptime fmt: []const u8,1589 comptime fmt: []const u8,
1661 options: FormatOptions,1590 options: FormatOptions,
1662 context: var,1591 out_stream: var,
1663 comptime Errors: type,1592 ) !void {
1664 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
1665 ) Errors!void {
1666 if (fmt.len == 0) {1593 if (fmt.len == 0) {
1667 return std.fmt.format(context, Errors, output, "({d:.3},{d:.3})", .{ self.x, self.y });1594 return std.fmt.format(out_stream, "({d:.3},{d:.3})", .{ self.x, self.y });
1668 } else {1595 } else {
1669 @compileError("Unknown format string: '" ++ fmt ++ "'");1596 @compileError("Unknown format string: '" ++ fmt ++ "'");
1670 }1597 }
...@@ -1698,25 +1625,22 @@ test "formatType max_depth" {...@@ -1698,25 +1625,22 @@ test "formatType max_depth" {
1698 inst.a = &inst;1625 inst.a = &inst;
1699 inst.tu.ptr = &inst.tu;1626 inst.tu.ptr = &inst.tu;
17001627
1701 var buf0 = std.ArrayList(u8).init(std.testing.allocator);1628 var buf: [1000]u8 = undefined;
1702 defer buf0.deinit();1629 var fbs = std.io.fixedBufferStream(&buf);
1703 try formatType(inst, "", FormatOptions{}, &buf0, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 0);1630 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 0);
1704 std.testing.expect(mem.eql(u8, buf0.toSlice(), "S{ ... }"));1631 std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ ... }"));
17051632
1706 var buf1 = std.ArrayList(u8).init(std.testing.allocator);1633 fbs.reset();
1707 defer buf1.deinit();1634 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 1);
1708 try formatType(inst, "", FormatOptions{}, &buf1, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 1);1635 std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }"));
1709 std.testing.expect(mem.eql(u8, buf1.toSlice(), "S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }"));1636
17101637 fbs.reset();
1711 var buf2 = std.ArrayList(u8).init(std.testing.allocator);1638 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 2);
1712 defer buf2.deinit();1639 std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }"));
1713 try formatType(inst, "", FormatOptions{}, &buf2, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 2);1640
1714 std.testing.expect(mem.eql(u8, buf2.toSlice(), "S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }"));1641 fbs.reset();
17151642 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 3);
1716 var buf3 = std.ArrayList(u8).init(std.testing.allocator);1643 std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ .ptr = TU{ ... } } }, .e = E.Two, .vec = (10.200,2.220) }"));
1717 defer buf3.deinit();
1718 try formatType(inst, "", FormatOptions{}, &buf3, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 3);
1719 std.testing.expect(mem.eql(u8, buf3.toSlice(), "S{ .a = S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ .ptr = TU{ ... } } }, .e = E.Two, .vec = (10.200,2.220) }"));
1720}1644}
17211645
1722test "positional" {1646test "positional" {
lib/std/fs.zig+17-24
...@@ -96,6 +96,7 @@ pub fn updateFile(source_path: []const u8, dest_path: []const u8) !PrevStatus {...@@ -96,6 +96,7 @@ pub fn updateFile(source_path: []const u8, dest_path: []const u8) !PrevStatus {
96/// atime, and mode of the source file so that the next call to `updateFile` will not need a copy.96/// atime, and mode of the source file so that the next call to `updateFile` will not need a copy.
97/// Returns the previous status of the file before updating.97/// Returns the previous status of the file before updating.
98/// If any of the directories do not exist for dest_path, they are created.98/// If any of the directories do not exist for dest_path, they are created.
99/// TODO rework this to integrate with Dir
99pub fn updateFileMode(source_path: []const u8, dest_path: []const u8, mode: ?File.Mode) !PrevStatus {100pub fn updateFileMode(source_path: []const u8, dest_path: []const u8, mode: ?File.Mode) !PrevStatus {
100 const my_cwd = cwd();101 const my_cwd = cwd();
101102
...@@ -141,29 +142,25 @@ pub fn updateFileMode(source_path: []const u8, dest_path: []const u8, mode: ?Fil...@@ -141,29 +142,25 @@ pub fn updateFileMode(source_path: []const u8, dest_path: []const u8, mode: ?Fil
141/// there is a possibility of power loss or application termination leaving temporary files present142/// there is a possibility of power loss or application termination leaving temporary files present
142/// in the same directory as dest_path.143/// in the same directory as dest_path.
143/// Destination file will have the same mode as the source file.144/// Destination file will have the same mode as the source file.
145/// TODO rework this to integrate with Dir
144pub fn copyFile(source_path: []const u8, dest_path: []const u8) !void {146pub fn copyFile(source_path: []const u8, dest_path: []const u8) !void {
145 var in_file = try cwd().openFile(source_path, .{});147 var in_file = try cwd().openFile(source_path, .{});
146 defer in_file.close();148 defer in_file.close();
147149
148 const mode = try in_file.mode();150 const stat = try in_file.stat();
149 const in_stream = &in_file.inStream().stream;
150151
151 var atomic_file = try AtomicFile.init(dest_path, mode);152 var atomic_file = try AtomicFile.init(dest_path, stat.mode);
152 defer atomic_file.deinit();153 defer atomic_file.deinit();
153154
154 var buf: [mem.page_size]u8 = undefined;155 try atomic_file.file.writeFileAll(in_file, .{ .in_len = stat.size });
155 while (true) {156 return atomic_file.finish();
156 const amt = try in_stream.readFull(buf[0..]);
157 try atomic_file.file.write(buf[0..amt]);
158 if (amt != buf.len) {
159 return atomic_file.finish();
160 }
161 }
162}157}
163158
164/// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is159/// Guaranteed to be atomic.
165/// merged and readily available,160/// On Linux, until https://patchwork.kernel.org/patch/9636735/ is merged and readily available,
166/// there is a possibility of power loss or application termination leaving temporary files present161/// there is a possibility of power loss or application termination leaving temporary files present
162/// in the same directory as dest_path.
163/// TODO rework this to integrate with Dir
167pub fn copyFileMode(source_path: []const u8, dest_path: []const u8, mode: File.Mode) !void {164pub fn copyFileMode(source_path: []const u8, dest_path: []const u8, mode: File.Mode) !void {
168 var in_file = try cwd().openFile(source_path, .{});165 var in_file = try cwd().openFile(source_path, .{});
169 defer in_file.close();166 defer in_file.close();
...@@ -171,14 +168,8 @@ pub fn copyFileMode(source_path: []const u8, dest_path: []const u8, mode: File.M...@@ -171,14 +168,8 @@ pub fn copyFileMode(source_path: []const u8, dest_path: []const u8, mode: File.M
171 var atomic_file = try AtomicFile.init(dest_path, mode);168 var atomic_file = try AtomicFile.init(dest_path, mode);
172 defer atomic_file.deinit();169 defer atomic_file.deinit();
173170
174 var buf: [mem.page_size * 6]u8 = undefined;171 try atomic_file.file.writeFileAll(in_file, .{});
175 while (true) {172 return atomic_file.finish();
176 const amt = try in_file.read(buf[0..]);
177 try atomic_file.file.write(buf[0..amt]);
178 if (amt != buf.len) {
179 return atomic_file.finish();
180 }
181 }
182}173}
183174
184/// TODO update this API to avoid a getrandom syscall for every operation. It175/// TODO update this API to avoid a getrandom syscall for every operation. It
...@@ -266,7 +257,7 @@ const default_new_dir_mode = 0o755;...@@ -266,7 +257,7 @@ const default_new_dir_mode = 0o755;
266/// Asserts that the path is absolute. See `Dir.makeDir` for a function that operates257/// Asserts that the path is absolute. See `Dir.makeDir` for a function that operates
267/// on both absolute and relative paths.258/// on both absolute and relative paths.
268pub fn makeDirAbsolute(absolute_path: []const u8) !void {259pub fn makeDirAbsolute(absolute_path: []const u8) !void {
269 assert(path.isAbsoluteC(absolute_path));260 assert(path.isAbsolute(absolute_path));
270 return os.mkdir(absolute_path, default_new_dir_mode);261 return os.mkdir(absolute_path, default_new_dir_mode);
271}262}
272263
...@@ -1150,7 +1141,7 @@ pub const Dir = struct {...@@ -1150,7 +1141,7 @@ pub const Dir = struct {
1150 const buf = try allocator.alignedAlloc(u8, A, size);1141 const buf = try allocator.alignedAlloc(u8, A, size);
1151 errdefer allocator.free(buf);1142 errdefer allocator.free(buf);
11521143
1153 try file.inStream().stream.readNoEof(buf);1144 try file.inStream().readNoEof(buf);
1154 return buf;1145 return buf;
1155 }1146 }
11561147
...@@ -1365,7 +1356,7 @@ pub const Dir = struct {...@@ -1365,7 +1356,7 @@ pub const Dir = struct {
1365 else1356 else
1366 @as(u32, os.F_OK);1357 @as(u32, os.F_OK);
1367 const result = if (need_async_thread)1358 const result = if (need_async_thread)
1368 std.event.Loop.instance.?.faccessatZ(self.fd, sub_path, os_mode)1359 std.event.Loop.instance.?.faccessatZ(self.fd, sub_path, os_mode, 0)
1369 else1360 else
1370 os.faccessatZ(self.fd, sub_path, os_mode, 0);1361 os.faccessatZ(self.fd, sub_path, os_mode, 0);
1371 return result;1362 return result;
...@@ -1669,6 +1660,8 @@ pub fn realpathAlloc(allocator: *Allocator, pathname: []const u8) ![]u8 {...@@ -1669,6 +1660,8 @@ pub fn realpathAlloc(allocator: *Allocator, pathname: []const u8) ![]u8 {
1669}1660}
16701661
1671test "" {1662test "" {
1663 _ = makeDirAbsolute;
1664 _ = makeDirAbsoluteZ;
1672 _ = @import("fs/path.zig");1665 _ = @import("fs/path.zig");
1673 _ = @import("fs/file.zig");1666 _ = @import("fs/file.zig");
1674 _ = @import("fs/get_app_data_dir.zig");1667 _ = @import("fs/get_app_data_dir.zig");
lib/std/fs/file.zig+72-84
...@@ -71,7 +71,7 @@ pub const File = struct {...@@ -71,7 +71,7 @@ pub const File = struct {
71 if (need_async_thread and self.io_mode == .blocking and !self.async_block_allowed) {71 if (need_async_thread and self.io_mode == .blocking and !self.async_block_allowed) {
72 std.event.Loop.instance.?.close(self.handle);72 std.event.Loop.instance.?.close(self.handle);
73 } else {73 } else {
74 return os.close(self.handle);74 os.close(self.handle);
75 }75 }
76 }76 }
7777
...@@ -99,6 +99,14 @@ pub const File = struct {...@@ -99,6 +99,14 @@ pub const File = struct {
99 return false;99 return false;
100 }100 }
101101
102 pub const SetEndPosError = os.TruncateError;
103
104 /// Shrinks or expands the file.
105 /// The file offset after this call is left unchanged.
106 pub fn setEndPos(self: File, length: u64) SetEndPosError!void {
107 try os.ftruncate(self.handle, length);
108 }
109
102 pub const SeekError = os.SeekError;110 pub const SeekError = os.SeekError;
103111
104 /// Repositions read/write file offset relative to the current offset.112 /// Repositions read/write file offset relative to the current offset.
...@@ -145,6 +153,16 @@ pub const File = struct {...@@ -145,6 +153,16 @@ pub const File = struct {
145 }153 }
146154
147 pub const Stat = struct {155 pub const Stat = struct {
156 /// A number that the system uses to point to the file metadata. This number is not guaranteed to be
157 /// unique across time, as some file systems may reuse an inode after it's file has been deleted.
158 /// Some systems may change the inode of a file over time.
159 ///
160 /// On Linux, the inode _is_ structure that stores the metadata, and the inode _number_ is what
161 /// you see here: the index number of the inode.
162 ///
163 /// The FileIndex on Windows is similar. It is a number for a file that is unique to each filesystem.
164 inode: os.ino_t,
165
148 size: u64,166 size: u64,
149 mode: Mode,167 mode: Mode,
150168
...@@ -174,6 +192,7 @@ pub const File = struct {...@@ -174,6 +192,7 @@ pub const File = struct {
174 else => return windows.unexpectedStatus(rc),192 else => return windows.unexpectedStatus(rc),
175 }193 }
176 return Stat{194 return Stat{
195 .inode = info.InternalInformation.IndexNumber,
177 .size = @bitCast(u64, info.StandardInformation.EndOfFile),196 .size = @bitCast(u64, info.StandardInformation.EndOfFile),
178 .mode = 0,197 .mode = 0,
179 .atime = windows.fromSysTime(info.BasicInformation.LastAccessTime),198 .atime = windows.fromSysTime(info.BasicInformation.LastAccessTime),
...@@ -187,6 +206,7 @@ pub const File = struct {...@@ -187,6 +206,7 @@ pub const File = struct {
187 const mtime = st.mtime();206 const mtime = st.mtime();
188 const ctime = st.ctime();207 const ctime = st.ctime();
189 return Stat{208 return Stat{
209 .inode = st.ino,
190 .size = @bitCast(u64, st.size),210 .size = @bitCast(u64, st.size),
191 .mode = st.mode,211 .mode = st.mode,
192 .atime = @as(i64, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,212 .atime = @as(i64, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,
...@@ -238,11 +258,16 @@ pub const File = struct {...@@ -238,11 +258,16 @@ pub const File = struct {
238 }258 }
239 }259 }
240260
241 pub fn readAll(self: File, buffer: []u8) ReadError!void {261 /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
262 /// means the file reached the end. Reaching the end of a file is not an error condition.
263 pub fn readAll(self: File, buffer: []u8) ReadError!usize {
242 var index: usize = 0;264 var index: usize = 0;
243 while (index < buffer.len) {265 while (index != buffer.len) {
244 index += try self.read(buffer[index..]);266 const amt = try self.read(buffer[index..]);
267 if (amt == 0) break;
268 index += amt;
245 }269 }
270 return index;
246 }271 }
247272
248 pub fn pread(self: File, buffer: []u8, offset: u64) PReadError!usize {273 pub fn pread(self: File, buffer: []u8, offset: u64) PReadError!usize {
...@@ -253,11 +278,16 @@ pub const File = struct {...@@ -253,11 +278,16 @@ pub const File = struct {
253 }278 }
254 }279 }
255280
256 pub fn preadAll(self: File, buffer: []u8, offset: u64) PReadError!void {281 /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
282 /// means the file reached the end. Reaching the end of a file is not an error condition.
283 pub fn preadAll(self: File, buffer: []u8, offset: u64) PReadError!usize {
257 var index: usize = 0;284 var index: usize = 0;
258 while (index < buffer.len) {285 while (index != buffer.len) {
259 index += try self.pread(buffer[index..], offset + index);286 const amt = try self.pread(buffer[index..], offset + index);
287 if (amt == 0) break;
288 index += amt;
260 }289 }
290 return index;
261 }291 }
262292
263 pub fn readv(self: File, iovecs: []const os.iovec) ReadError!usize {293 pub fn readv(self: File, iovecs: []const os.iovec) ReadError!usize {
...@@ -268,19 +298,27 @@ pub const File = struct {...@@ -268,19 +298,27 @@ pub const File = struct {
268 }298 }
269 }299 }
270300
301 /// Returns the number of bytes read. If the number read is smaller than the total bytes
302 /// from all the buffers, it means the file reached the end. Reaching the end of a file
303 /// is not an error condition.
271 /// The `iovecs` parameter is mutable because this function needs to mutate the fields in304 /// The `iovecs` parameter is mutable because this function needs to mutate the fields in
272 /// order to handle partial reads from the underlying OS layer.305 /// order to handle partial reads from the underlying OS layer.
273 pub fn readvAll(self: File, iovecs: []os.iovec) ReadError!void {306 pub fn readvAll(self: File, iovecs: []os.iovec) ReadError!usize {
274 if (iovecs.len == 0) return;307 if (iovecs.len == 0) return;
275308
276 var i: usize = 0;309 var i: usize = 0;
310 var off: usize = 0;
277 while (true) {311 while (true) {
278 var amt = try self.readv(iovecs[i..]);312 var amt = try self.readv(iovecs[i..]);
313 var eof = amt == 0;
314 off += amt;
279 while (amt >= iovecs[i].iov_len) {315 while (amt >= iovecs[i].iov_len) {
280 amt -= iovecs[i].iov_len;316 amt -= iovecs[i].iov_len;
281 i += 1;317 i += 1;
282 if (i >= iovecs.len) return;318 if (i >= iovecs.len) return off;
319 eof = false;
283 }320 }
321 if (eof) return off;
284 iovecs[i].iov_base += amt;322 iovecs[i].iov_base += amt;
285 iovecs[i].iov_len -= amt;323 iovecs[i].iov_len -= amt;
286 }324 }
...@@ -294,6 +332,9 @@ pub const File = struct {...@@ -294,6 +332,9 @@ pub const File = struct {
294 }332 }
295 }333 }
296334
335 /// Returns the number of bytes read. If the number read is smaller than the total bytes
336 /// from all the buffers, it means the file reached the end. Reaching the end of a file
337 /// is not an error condition.
297 /// The `iovecs` parameter is mutable because this function needs to mutate the fields in338 /// The `iovecs` parameter is mutable because this function needs to mutate the fields in
298 /// order to handle partial reads from the underlying OS layer.339 /// order to handle partial reads from the underlying OS layer.
299 pub fn preadvAll(self: File, iovecs: []const os.iovec, offset: u64) PReadError!void {340 pub fn preadvAll(self: File, iovecs: []const os.iovec, offset: u64) PReadError!void {
...@@ -303,12 +344,15 @@ pub const File = struct {...@@ -303,12 +344,15 @@ pub const File = struct {
303 var off: usize = 0;344 var off: usize = 0;
304 while (true) {345 while (true) {
305 var amt = try self.preadv(iovecs[i..], offset + off);346 var amt = try self.preadv(iovecs[i..], offset + off);
347 var eof = amt == 0;
306 off += amt;348 off += amt;
307 while (amt >= iovecs[i].iov_len) {349 while (amt >= iovecs[i].iov_len) {
308 amt -= iovecs[i].iov_len;350 amt -= iovecs[i].iov_len;
309 i += 1;351 i += 1;
310 if (i >= iovecs.len) return;352 if (i >= iovecs.len) return off;
353 eof = false;
311 }354 }
355 if (eof) return off;
312 iovecs[i].iov_base += amt;356 iovecs[i].iov_base += amt;
313 iovecs[i].iov_len -= amt;357 iovecs[i].iov_len -= amt;
314 }358 }
...@@ -484,85 +528,29 @@ pub const File = struct {...@@ -484,85 +528,29 @@ pub const File = struct {
484 }528 }
485 }529 }
486530
487 pub fn inStream(file: File) InStream {531 pub const InStream = io.InStream(File, ReadError, read);
488 return InStream{532
489 .file = file,533 pub fn inStream(file: File) io.InStream(File, ReadError, read) {
490 .stream = InStream.Stream{ .readFn = InStream.readFn },534 return .{ .context = file };
491 };
492 }535 }
493536
537 pub const OutStream = io.OutStream(File, WriteError, write);
538
494 pub fn outStream(file: File) OutStream {539 pub fn outStream(file: File) OutStream {
495 return OutStream{540 return .{ .context = file };
496 .file = file,
497 .stream = OutStream.Stream{ .writeFn = OutStream.writeFn },
498 };
499 }541 }
500542
543 pub const SeekableStream = io.SeekableStream(
544 File,
545 SeekError,
546 GetPosError,
547 seekTo,
548 seekBy,
549 getPos,
550 getEndPos,
551 );
552
501 pub fn seekableStream(file: File) SeekableStream {553 pub fn seekableStream(file: File) SeekableStream {
502 return SeekableStream{554 return .{ .context = file };
503 .file = file,
504 .stream = SeekableStream.Stream{
505 .seekToFn = SeekableStream.seekToFn,
506 .seekByFn = SeekableStream.seekByFn,
507 .getPosFn = SeekableStream.getPosFn,
508 .getEndPosFn = SeekableStream.getEndPosFn,
509 },
510 };
511 }555 }
512
513 /// Implementation of io.InStream trait for File
514 pub const InStream = struct {
515 file: File,
516 stream: Stream,
517
518 pub const Error = ReadError;
519 pub const Stream = io.InStream(Error);
520
521 fn readFn(in_stream: *Stream, buffer: []u8) Error!usize {
522 const self = @fieldParentPtr(InStream, "stream", in_stream);
523 return self.file.read(buffer);
524 }
525 };
526
527 /// Implementation of io.OutStream trait for File
528 pub const OutStream = struct {
529 file: File,
530 stream: Stream,
531
532 pub const Error = WriteError;
533 pub const Stream = io.OutStream(Error);
534
535 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
536 const self = @fieldParentPtr(OutStream, "stream", out_stream);
537 return self.file.write(bytes);
538 }
539 };
540
541 /// Implementation of io.SeekableStream trait for File
542 pub const SeekableStream = struct {
543 file: File,
544 stream: Stream,
545
546 pub const Stream = io.SeekableStream(SeekError, GetPosError);
547
548 pub fn seekToFn(seekable_stream: *Stream, pos: u64) SeekError!void {
549 const self = @fieldParentPtr(SeekableStream, "stream", seekable_stream);
550 return self.file.seekTo(pos);
551 }
552
553 pub fn seekByFn(seekable_stream: *Stream, amt: i64) SeekError!void {
554 const self = @fieldParentPtr(SeekableStream, "stream", seekable_stream);
555 return self.file.seekBy(amt);
556 }
557
558 pub fn getEndPosFn(seekable_stream: *Stream) GetPosError!u64 {
559 const self = @fieldParentPtr(SeekableStream, "stream", seekable_stream);
560 return self.file.getEndPos();
561 }
562
563 pub fn getPosFn(seekable_stream: *Stream) GetPosError!u64 {
564 const self = @fieldParentPtr(SeekableStream, "stream", seekable_stream);
565 return self.file.getPos();
566 }
567 };
568};556};
lib/std/heap.zig+1
...@@ -10,6 +10,7 @@ const c = std.c;...@@ -10,6 +10,7 @@ const c = std.c;
10const maxInt = std.math.maxInt;10const maxInt = std.math.maxInt;
1111
12pub const LoggingAllocator = @import("heap/logging_allocator.zig").LoggingAllocator;12pub const LoggingAllocator = @import("heap/logging_allocator.zig").LoggingAllocator;
13pub const loggingAllocator = @import("heap/logging_allocator.zig").loggingAllocator;
1314
14const Allocator = mem.Allocator;15const Allocator = mem.Allocator;
1516
lib/std/heap/logging_allocator.zig+51-45
...@@ -1,63 +1,69 @@...@@ -1,63 +1,69 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const Allocator = std.mem.Allocator;2const Allocator = std.mem.Allocator;
33
4const AnyErrorOutStream = std.io.OutStream(anyerror);
5
6/// This allocator is used in front of another allocator and logs to the provided stream4/// This allocator is used in front of another allocator and logs to the provided stream
7/// on every call to the allocator. Stream errors are ignored.5/// on every call to the allocator. Stream errors are ignored.
8/// If https://github.com/ziglang/zig/issues/2586 is implemented, this API can be improved.6/// If https://github.com/ziglang/zig/issues/2586 is implemented, this API can be improved.
9pub const LoggingAllocator = struct {7pub fn LoggingAllocator(comptime OutStreamType: type) type {
10 allocator: Allocator,8 return struct {
11 parent_allocator: *Allocator,9 allocator: Allocator,
12 out_stream: *AnyErrorOutStream,10 parent_allocator: *Allocator,
11 out_stream: OutStreamType,
1312
14 const Self = @This();13 const Self = @This();
1514
16 pub fn init(parent_allocator: *Allocator, out_stream: *AnyErrorOutStream) Self {15 pub fn init(parent_allocator: *Allocator, out_stream: OutStreamType) Self {
17 return Self{16 return Self{
18 .allocator = Allocator{17 .allocator = Allocator{
19 .reallocFn = realloc,18 .reallocFn = realloc,
20 .shrinkFn = shrink,19 .shrinkFn = shrink,
21 },20 },
22 .parent_allocator = parent_allocator,21 .parent_allocator = parent_allocator,
23 .out_stream = out_stream,22 .out_stream = out_stream,
24 };23 };
25 }
26
27 fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
28 const self = @fieldParentPtr(Self, "allocator", allocator);
29 if (old_mem.len == 0) {
30 self.out_stream.print("allocation of {} ", .{new_size}) catch {};
31 } else {
32 self.out_stream.print("resize from {} to {} ", .{ old_mem.len, new_size }) catch {};
33 }24 }
34 const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align);25
35 if (result) |buff| {26 fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
36 self.out_stream.print("success!\n", .{}) catch {};27 const self = @fieldParentPtr(Self, "allocator", allocator);
37 } else |err| {28 if (old_mem.len == 0) {
38 self.out_stream.print("failure!\n", .{}) catch {};29 self.out_stream.print("allocation of {} ", .{new_size}) catch {};
30 } else {
31 self.out_stream.print("resize from {} to {} ", .{ old_mem.len, new_size }) catch {};
32 }
33 const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
34 if (result) |buff| {
35 self.out_stream.print("success!\n", .{}) catch {};
36 } else |err| {
37 self.out_stream.print("failure!\n", .{}) catch {};
38 }
39 return result;
39 }40 }
40 return result;
41 }
4241
43 fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {42 fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
44 const self = @fieldParentPtr(Self, "allocator", allocator);43 const self = @fieldParentPtr(Self, "allocator", allocator);
45 const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align);44 const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
46 if (new_size == 0) {45 if (new_size == 0) {
47 self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {};46 self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {};
48 } else {47 } else {
49 self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {};48 self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {};
49 }
50 return result;
50 }51 }
51 return result;52 };
52 }53}
53};54
55pub fn loggingAllocator(
56 parent_allocator: *Allocator,
57 out_stream: var,
58) LoggingAllocator(@TypeOf(out_stream)) {
59 return LoggingAllocator(@TypeOf(out_stream)).init(parent_allocator, out_stream);
60}
5461
55test "LoggingAllocator" {62test "LoggingAllocator" {
56 var buf: [255]u8 = undefined;63 var buf: [255]u8 = undefined;
57 var slice_stream = std.io.SliceOutStream.init(buf[0..]);64 var fbs = std.io.fixedBufferStream(&buf);
58 const stream = &slice_stream.stream;
5965
60 const allocator = &LoggingAllocator.init(std.testing.allocator, @ptrCast(*AnyErrorOutStream, stream)).allocator;66 const allocator = &loggingAllocator(std.testing.allocator, fbs.outStream()).allocator;
6167
62 const ptr = try allocator.alloc(u8, 10);68 const ptr = try allocator.alloc(u8, 10);
63 allocator.free(ptr);69 allocator.free(ptr);
...@@ -66,5 +72,5 @@ test "LoggingAllocator" {...@@ -66,5 +72,5 @@ test "LoggingAllocator" {
66 \\allocation of 10 success!72 \\allocation of 10 success!
67 \\free of 10 bytes success!73 \\free of 10 bytes success!
68 \\74 \\
69 , slice_stream.getWritten());75 , fbs.getWritten());
70}76}
lib/std/http/headers.zig+6-8
...@@ -350,15 +350,13 @@ pub const Headers = struct {...@@ -350,15 +350,13 @@ pub const Headers = struct {
350 self: Self,350 self: Self,
351 comptime fmt: []const u8,351 comptime fmt: []const u8,
352 options: std.fmt.FormatOptions,352 options: std.fmt.FormatOptions,
353 context: var,353 out_stream: var,
354 comptime Errors: type,354 ) !void {
355 output: fn (@TypeOf(context), []const u8) Errors!void,
356 ) Errors!void {
357 for (self.toSlice()) |entry| {355 for (self.toSlice()) |entry| {
358 try output(context, entry.name);356 try out_stream.writeAll(entry.name);
359 try output(context, ": ");357 try out_stream.writeAll(": ");
360 try output(context, entry.value);358 try out_stream.writeAll(entry.value);
361 try output(context, "\n");359 try out_stream.writeAll("\n");
362 }360 }
363 }361 }
364};362};
lib/std/io.zig+39-1020
...@@ -4,17 +4,13 @@ const root = @import("root");...@@ -4,17 +4,13 @@ const root = @import("root");
4const c = std.c;4const c = std.c;
55
6const math = std.math;6const math = std.math;
7const debug = std.debug;7const assert = std.debug.assert;
8const assert = debug.assert;
9const os = std.os;8const os = std.os;
10const fs = std.fs;9const fs = std.fs;
11const mem = std.mem;10const mem = std.mem;
12const meta = std.meta;11const meta = std.meta;
13const trait = meta.trait;12const trait = meta.trait;
14const Buffer = std.Buffer;
15const fmt = std.fmt;
16const File = std.fs.File;13const File = std.fs.File;
17const testing = std.testing;
1814
19pub const Mode = enum {15pub const Mode = enum {
20 /// I/O operates normally, waiting for the operating system syscalls to complete.16 /// I/O operates normally, waiting for the operating system syscalls to complete.
...@@ -92,1045 +88,68 @@ pub fn getStdIn() File {...@@ -92,1045 +88,68 @@ pub fn getStdIn() File {
92 };88 };
93}89}
9490
95pub const SeekableStream = @import("io/seekable_stream.zig").SeekableStream;
96pub const SliceSeekableInStream = @import("io/seekable_stream.zig").SliceSeekableInStream;
97pub const COutStream = @import("io/c_out_stream.zig").COutStream;
98pub const InStream = @import("io/in_stream.zig").InStream;91pub const InStream = @import("io/in_stream.zig").InStream;
99pub const OutStream = @import("io/out_stream.zig").OutStream;92pub const OutStream = @import("io/out_stream.zig").OutStream;
93pub const SeekableStream = @import("io/seekable_stream.zig").SeekableStream;
10094
101/// Deprecated; use `std.fs.Dir.writeFile`.95pub const BufferedOutStream = @import("io/buffered_out_stream.zig").BufferedOutStream;
102pub fn writeFile(path: []const u8, data: []const u8) !void {96pub const bufferedOutStream = @import("io/buffered_out_stream.zig").bufferedOutStream;
103 return fs.cwd().writeFile(path, data);
104}
105
106/// Deprecated; use `std.fs.Dir.readFileAlloc`.
107pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 {
108 return fs.cwd().readFileAlloc(allocator, path, math.maxInt(usize));
109}
110
111pub fn BufferedInStream(comptime Error: type) type {
112 return BufferedInStreamCustom(mem.page_size, Error);
113}
114
115pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) type {
116 return struct {
117 const Self = @This();
118 const Stream = InStream(Error);
119
120 stream: Stream,
121
122 unbuffered_in_stream: *Stream,
123
124 const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
125 fifo: FifoType,
126
127 pub fn init(unbuffered_in_stream: *Stream) Self {
128 return Self{
129 .unbuffered_in_stream = unbuffered_in_stream,
130 .fifo = FifoType.init(),
131 .stream = Stream{ .readFn = readFn },
132 };
133 }
134
135 fn readFn(in_stream: *Stream, dest: []u8) !usize {
136 const self = @fieldParentPtr(Self, "stream", in_stream);
137 var dest_index: usize = 0;
138 while (dest_index < dest.len) {
139 const written = self.fifo.read(dest[dest_index..]);
140 if (written == 0) {
141 // fifo empty, fill it
142 const writable = self.fifo.writableSlice(0);
143 assert(writable.len > 0);
144 const n = try self.unbuffered_in_stream.read(writable);
145 if (n == 0) {
146 // reading from the unbuffered stream returned nothing
147 // so we have nothing left to read.
148 return dest_index;
149 }
150 self.fifo.update(n);
151 }
152 dest_index += written;
153 }
154 return dest.len;
155 }
156 };
157}
158
159test "io.BufferedInStream" {
160 const OneByteReadInStream = struct {
161 const Error = error{NoError};
162 const Stream = InStream(Error);
163
164 stream: Stream,
165 str: []const u8,
166 curr: usize,
167
168 fn init(str: []const u8) @This() {
169 return @This(){
170 .stream = Stream{ .readFn = readFn },
171 .str = str,
172 .curr = 0,
173 };
174 }
175
176 fn readFn(in_stream: *Stream, dest: []u8) Error!usize {
177 const self = @fieldParentPtr(@This(), "stream", in_stream);
178 if (self.str.len <= self.curr or dest.len == 0)
179 return 0;
180
181 dest[0] = self.str[self.curr];
182 self.curr += 1;
183 return 1;
184 }
185 };
186
187 const str = "This is a test";
188 var one_byte_stream = OneByteReadInStream.init(str);
189 var buf_in_stream = BufferedInStream(OneByteReadInStream.Error).init(&one_byte_stream.stream);
190 const stream = &buf_in_stream.stream;
191
192 const res = try stream.readAllAlloc(testing.allocator, str.len + 1);
193 defer testing.allocator.free(res);
194 testing.expectEqualSlices(u8, str, res);
195}
196
197/// Creates a stream which supports 'un-reading' data, so that it can be read again.
198/// This makes look-ahead style parsing much easier.
199pub fn PeekStream(comptime buffer_type: std.fifo.LinearFifoBufferType, comptime InStreamError: type) type {
200 return struct {
201 const Self = @This();
202 pub const Error = InStreamError;
203 pub const Stream = InStream(Error);
204
205 stream: Stream,
206 base: *Stream,
207
208 const FifoType = std.fifo.LinearFifo(u8, buffer_type);
209 fifo: FifoType,
210
211 pub usingnamespace switch (buffer_type) {
212 .Static => struct {
213 pub fn init(base: *Stream) Self {
214 return .{
215 .base = base,
216 .fifo = FifoType.init(),
217 .stream = Stream{ .readFn = readFn },
218 };
219 }
220 },
221 .Slice => struct {
222 pub fn init(base: *Stream, buf: []u8) Self {
223 return .{
224 .base = base,
225 .fifo = FifoType.init(buf),
226 .stream = Stream{ .readFn = readFn },
227 };
228 }
229 },
230 .Dynamic => struct {
231 pub fn init(base: *Stream, allocator: *mem.Allocator) Self {
232 return .{
233 .base = base,
234 .fifo = FifoType.init(allocator),
235 .stream = Stream{ .readFn = readFn },
236 };
237 }
238 },
239 };
240
241 pub fn putBackByte(self: *Self, byte: u8) !void {
242 try self.putBack(&[_]u8{byte});
243 }
244
245 pub fn putBack(self: *Self, bytes: []const u8) !void {
246 try self.fifo.unget(bytes);
247 }
248
249 fn readFn(in_stream: *Stream, dest: []u8) Error!usize {
250 const self = @fieldParentPtr(Self, "stream", in_stream);
251
252 // copy over anything putBack()'d
253 var dest_index = self.fifo.read(dest);
254 if (dest_index == dest.len) return dest_index;
255
256 // ask the backing stream for more
257 dest_index += try self.base.read(dest[dest_index..]);
258 return dest_index;
259 }
260 };
261}
262
263pub const SliceInStream = struct {
264 const Self = @This();
265 pub const Error = error{};
266 pub const Stream = InStream(Error);
267
268 stream: Stream,
269
270 pos: usize,
271 slice: []const u8,
272
273 pub fn init(slice: []const u8) Self {
274 return Self{
275 .slice = slice,
276 .pos = 0,
277 .stream = Stream{ .readFn = readFn },
278 };
279 }
280
281 fn readFn(in_stream: *Stream, dest: []u8) Error!usize {
282 const self = @fieldParentPtr(Self, "stream", in_stream);
283 const size = math.min(dest.len, self.slice.len - self.pos);
284 const end = self.pos + size;
285
286 mem.copy(u8, dest[0..size], self.slice[self.pos..end]);
287 self.pos = end;
288
289 return size;
290 }
291};
292
293/// Creates a stream which allows for reading bit fields from another stream
294pub fn BitInStream(endian: builtin.Endian, comptime Error: type) type {
295 return struct {
296 const Self = @This();
297
298 in_stream: *Stream,
299 bit_buffer: u7,
300 bit_count: u3,
301 stream: Stream,
302
303 pub const Stream = InStream(Error);
304 const u8_bit_count = comptime meta.bitCount(u8);
305 const u7_bit_count = comptime meta.bitCount(u7);
306 const u4_bit_count = comptime meta.bitCount(u4);
307
308 pub fn init(in_stream: *Stream) Self {
309 return Self{
310 .in_stream = in_stream,
311 .bit_buffer = 0,
312 .bit_count = 0,
313 .stream = Stream{ .readFn = read },
314 };
315 }
316
317 /// Reads `bits` bits from the stream and returns a specified unsigned int type
318 /// containing them in the least significant end, returning an error if the
319 /// specified number of bits could not be read.
320 pub fn readBitsNoEof(self: *Self, comptime U: type, bits: usize) !U {
321 var n: usize = undefined;
322 const result = try self.readBits(U, bits, &n);
323 if (n < bits) return error.EndOfStream;
324 return result;
325 }
32697
327 /// Reads `bits` bits from the stream and returns a specified unsigned int type98pub const BufferedInStream = @import("io/buffered_in_stream.zig").BufferedInStream;
328 /// containing them in the least significant end. The number of bits successfully99pub const bufferedInStream = @import("io/buffered_in_stream.zig").bufferedInStream;
329 /// read is placed in `out_bits`, as reaching the end of the stream is not an error.
330 pub fn readBits(self: *Self, comptime U: type, bits: usize, out_bits: *usize) Error!U {
331 comptime assert(trait.isUnsignedInt(U));
332100
333 //by extending the buffer to a minimum of u8 we can cover a number of edge cases101pub const PeekStream = @import("io/peek_stream.zig").PeekStream;
334 // related to shifting and casting.102pub const peekStream = @import("io/peek_stream.zig").peekStream;
335 const u_bit_count = comptime meta.bitCount(U);
336 const buf_bit_count = bc: {
337 assert(u_bit_count >= bits);
338 break :bc if (u_bit_count <= u8_bit_count) u8_bit_count else u_bit_count;
339 };
340 const Buf = std.meta.IntType(false, buf_bit_count);
341 const BufShift = math.Log2Int(Buf);
342103
343 out_bits.* = @as(usize, 0);104pub const FixedBufferStream = @import("io/fixed_buffer_stream.zig").FixedBufferStream;
344 if (U == u0 or bits == 0) return 0;105pub const fixedBufferStream = @import("io/fixed_buffer_stream.zig").fixedBufferStream;
345 var out_buffer = @as(Buf, 0);
346106
347 if (self.bit_count > 0) {107pub const COutStream = @import("io/c_out_stream.zig").COutStream;
348 const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;108pub const cOutStream = @import("io/c_out_stream.zig").cOutStream;
349 const shift = u7_bit_count - n;
350 switch (endian) {
351 .Big => {
352 out_buffer = @as(Buf, self.bit_buffer >> shift);
353 self.bit_buffer <<= n;
354 },
355 .Little => {
356 const value = (self.bit_buffer << shift) >> shift;
357 out_buffer = @as(Buf, value);
358 self.bit_buffer >>= n;
359 },
360 }
361 self.bit_count -= n;
362 out_bits.* = n;
363 }
364 //at this point we know bit_buffer is empty
365109
366 //copy bytes until we have enough bits, then leave the rest in bit_buffer110pub const CountingOutStream = @import("io/counting_out_stream.zig").CountingOutStream;
367 while (out_bits.* < bits) {111pub const countingOutStream = @import("io/counting_out_stream.zig").countingOutStream;
368 const n = bits - out_bits.*;
369 const next_byte = self.in_stream.readByte() catch |err| {
370 if (err == error.EndOfStream) {
371 return @intCast(U, out_buffer);
372 }
373 //@BUG: See #1810. Not sure if the bug is that I have to do this for some
374 // streams, or that I don't for streams with emtpy errorsets.
375 return @errSetCast(Error, err);
376 };
377112
378 switch (endian) {113pub const BitInStream = @import("io/bit_in_stream.zig").BitInStream;
379 .Big => {114pub const bitInStream = @import("io/bit_in_stream.zig").bitInStream;
380 if (n >= u8_bit_count) {
381 out_buffer <<= @intCast(u3, u8_bit_count - 1);
382 out_buffer <<= 1;
383 out_buffer |= @as(Buf, next_byte);
384 out_bits.* += u8_bit_count;
385 continue;
386 }
387115
388 const shift = @intCast(u3, u8_bit_count - n);116pub const BitOutStream = @import("io/bit_out_stream.zig").BitOutStream;
389 out_buffer <<= @intCast(BufShift, n);117pub const bitOutStream = @import("io/bit_out_stream.zig").bitOutStream;
390 out_buffer |= @as(Buf, next_byte >> shift);
391 out_bits.* += n;
392 self.bit_buffer = @truncate(u7, next_byte << @intCast(u3, n - 1));
393 self.bit_count = shift;
394 },
395 .Little => {
396 if (n >= u8_bit_count) {
397 out_buffer |= @as(Buf, next_byte) << @intCast(BufShift, out_bits.*);
398 out_bits.* += u8_bit_count;
399 continue;
400 }
401118
402 const shift = @intCast(u3, u8_bit_count - n);119pub const Packing = @import("io/serialization.zig").Packing;
403 const value = (next_byte << shift) >> shift;
404 out_buffer |= @as(Buf, value) << @intCast(BufShift, out_bits.*);
405 out_bits.* += n;
406 self.bit_buffer = @truncate(u7, next_byte >> @intCast(u3, n));
407 self.bit_count = shift;
408 },
409 }
410 }
411120
412 return @intCast(U, out_buffer);121pub const Serializer = @import("io/serialization.zig").Serializer;
413 }122pub const serializer = @import("io/serialization.zig").serializer;
414123
415 pub fn alignToByte(self: *Self) void {124pub const Deserializer = @import("io/serialization.zig").Deserializer;
416 self.bit_buffer = 0;125pub const deserializer = @import("io/serialization.zig").deserializer;
417 self.bit_count = 0;
418 }
419126
420 pub fn read(self_stream: *Stream, buffer: []u8) Error!usize {127pub const BufferedAtomicFile = @import("io/buffered_atomic_file.zig").BufferedAtomicFile;
421 var self = @fieldParentPtr(Self, "stream", self_stream);
422128
423 var out_bits: usize = undefined;129pub const StreamSource = @import("io/stream_source.zig").StreamSource;
424 var out_bits_total = @as(usize, 0);
425 //@NOTE: I'm not sure this is a good idea, maybe alignToByte should be forced
426 if (self.bit_count > 0) {
427 for (buffer) |*b, i| {
428 b.* = try self.readBits(u8, u8_bit_count, &out_bits);
429 out_bits_total += out_bits;
430 }
431 const incomplete_byte = @boolToInt(out_bits_total % u8_bit_count > 0);
432 return (out_bits_total / u8_bit_count) + incomplete_byte;
433 }
434130
435 return self.in_stream.read(buffer);131/// Deprecated; use `std.fs.Dir.writeFile`.
436 }132pub fn writeFile(path: []const u8, data: []const u8) !void {
437 };133 return fs.cwd().writeFile(path, data);
438}134}
439135
440/// This is a simple OutStream that writes to a fixed buffer. If the returned number136/// Deprecated; use `std.fs.Dir.readFileAlloc`.
441/// of bytes written is less than requested, the buffer is full.137pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 {
442/// Returns error.OutOfMemory when no bytes would be written.138 return fs.cwd().readFileAlloc(allocator, path, math.maxInt(usize));
443pub const SliceOutStream = struct {
444 pub const Error = error{OutOfMemory};
445 pub const Stream = OutStream(Error);
446
447 stream: Stream,
448
449 pos: usize,
450 slice: []u8,
451
452 pub fn init(slice: []u8) SliceOutStream {
453 return SliceOutStream{
454 .slice = slice,
455 .pos = 0,
456 .stream = Stream{ .writeFn = writeFn },
457 };
458 }
459
460 pub fn getWritten(self: *const SliceOutStream) []const u8 {
461 return self.slice[0..self.pos];
462 }
463
464 pub fn reset(self: *SliceOutStream) void {
465 self.pos = 0;
466 }
467
468 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
469 const self = @fieldParentPtr(SliceOutStream, "stream", out_stream);
470
471 if (bytes.len == 0) return 0;
472
473 assert(self.pos <= self.slice.len);
474
475 const n = if (self.pos + bytes.len <= self.slice.len)
476 bytes.len
477 else
478 self.slice.len - self.pos;
479
480 std.mem.copy(u8, self.slice[self.pos .. self.pos + n], bytes[0..n]);
481 self.pos += n;
482
483 if (n == 0) return error.OutOfMemory;
484
485 return n;
486 }
487};
488
489test "io.SliceOutStream" {
490 var buf: [255]u8 = undefined;
491 var slice_stream = SliceOutStream.init(buf[0..]);
492 const stream = &slice_stream.stream;
493
494 try stream.print("{}{}!", .{ "Hello", "World" });
495 testing.expectEqualSlices(u8, "HelloWorld!", slice_stream.getWritten());
496}139}
497140
498var null_out_stream_state = NullOutStream.init();
499pub const null_out_stream = &null_out_stream_state.stream;
500
501/// An OutStream that doesn't write to anything.141/// An OutStream that doesn't write to anything.
502pub const NullOutStream = struct {142pub const null_out_stream = @as(NullOutStream, .{ .context = {} });
503 pub const Error = error{};
504 pub const Stream = OutStream(Error);
505
506 stream: Stream,
507
508 pub fn init() NullOutStream {
509 return NullOutStream{
510 .stream = Stream{ .writeFn = writeFn },
511 };
512 }
513
514 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
515 return bytes.len;
516 }
517};
518
519test "io.NullOutStream" {
520 var null_stream = NullOutStream.init();
521 const stream = &null_stream.stream;
522 stream.write("yay" ** 10000) catch unreachable;
523}
524
525/// An OutStream that counts how many bytes has been written to it.
526pub fn CountingOutStream(comptime OutStreamError: type) type {
527 return struct {
528 const Self = @This();
529 pub const Stream = OutStream(Error);
530 pub const Error = OutStreamError;
531
532 stream: Stream,
533 bytes_written: u64,
534 child_stream: *Stream,
535
536 pub fn init(child_stream: *Stream) Self {
537 return Self{
538 .stream = Stream{ .writeFn = writeFn },
539 .bytes_written = 0,
540 .child_stream = child_stream,
541 };
542 }
543
544 fn writeFn(out_stream: *Stream, bytes: []const u8) OutStreamError!usize {
545 const self = @fieldParentPtr(Self, "stream", out_stream);
546 try self.child_stream.write(bytes);
547 self.bytes_written += bytes.len;
548 return bytes.len;
549 }
550 };
551}
552
553test "io.CountingOutStream" {
554 var null_stream = NullOutStream.init();
555 var counting_stream = CountingOutStream(NullOutStream.Error).init(&null_stream.stream);
556 const stream = &counting_stream.stream;
557
558 const bytes = "yay" ** 10000;
559 stream.write(bytes) catch unreachable;
560 testing.expect(counting_stream.bytes_written == bytes.len);
561}
562143
563pub fn BufferedOutStream(comptime Error: type) type {144const NullOutStream = OutStream(void, error{}, dummyWrite);
564 return BufferedOutStreamCustom(mem.page_size, Error);145fn dummyWrite(context: void, data: []const u8) error{}!usize {
146 return data.len;
565}147}
566148
567pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamError: type) type {149test "null_out_stream" {
568 return struct {150 null_out_stream.writeAll("yay" ** 10) catch |err| switch (err) {};
569 const Self = @This();
570 pub const Stream = OutStream(Error);
571 pub const Error = OutStreamError;
572
573 stream: Stream,
574
575 unbuffered_out_stream: *Stream,
576
577 const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
578 fifo: FifoType,
579
580 pub fn init(unbuffered_out_stream: *Stream) Self {
581 return Self{
582 .unbuffered_out_stream = unbuffered_out_stream,
583 .fifo = FifoType.init(),
584 .stream = Stream{ .writeFn = writeFn },
585 };
586 }
587
588 pub fn flush(self: *Self) !void {
589 while (true) {
590 const slice = self.fifo.readableSlice(0);
591 if (slice.len == 0) break;
592 try self.unbuffered_out_stream.write(slice);
593 self.fifo.discard(slice.len);
594 }
595 }
596
597 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
598 const self = @fieldParentPtr(Self, "stream", out_stream);
599 if (bytes.len >= self.fifo.writableLength()) {
600 try self.flush();
601 return self.unbuffered_out_stream.writeOnce(bytes);
602 }
603 self.fifo.writeAssumeCapacity(bytes);
604 return bytes.len;
605 }
606 };
607}
608
609/// Implementation of OutStream trait for Buffer
610pub const BufferOutStream = struct {
611 buffer: *Buffer,
612 stream: Stream,
613
614 pub const Error = error{OutOfMemory};
615 pub const Stream = OutStream(Error);
616
617 pub fn init(buffer: *Buffer) BufferOutStream {
618 return BufferOutStream{
619 .buffer = buffer,
620 .stream = Stream{ .writeFn = writeFn },
621 };
622 }
623
624 fn writeFn(out_stream: *Stream, bytes: []const u8) !usize {
625 const self = @fieldParentPtr(BufferOutStream, "stream", out_stream);
626 try self.buffer.append(bytes);
627 return bytes.len;
628 }
629};
630
631/// Creates a stream which allows for writing bit fields to another stream
632pub fn BitOutStream(endian: builtin.Endian, comptime Error: type) type {
633 return struct {
634 const Self = @This();
635
636 out_stream: *Stream,
637 bit_buffer: u8,
638 bit_count: u4,
639 stream: Stream,
640
641 pub const Stream = OutStream(Error);
642 const u8_bit_count = comptime meta.bitCount(u8);
643 const u4_bit_count = comptime meta.bitCount(u4);
644
645 pub fn init(out_stream: *Stream) Self {
646 return Self{
647 .out_stream = out_stream,
648 .bit_buffer = 0,
649 .bit_count = 0,
650 .stream = Stream{ .writeFn = write },
651 };
652 }
653
654 /// Write the specified number of bits to the stream from the least significant bits of
655 /// the specified unsigned int value. Bits will only be written to the stream when there
656 /// are enough to fill a byte.
657 pub fn writeBits(self: *Self, value: var, bits: usize) Error!void {
658 if (bits == 0) return;
659
660 const U = @TypeOf(value);
661 comptime assert(trait.isUnsignedInt(U));
662
663 //by extending the buffer to a minimum of u8 we can cover a number of edge cases
664 // related to shifting and casting.
665 const u_bit_count = comptime meta.bitCount(U);
666 const buf_bit_count = bc: {
667 assert(u_bit_count >= bits);
668 break :bc if (u_bit_count <= u8_bit_count) u8_bit_count else u_bit_count;
669 };
670 const Buf = std.meta.IntType(false, buf_bit_count);
671 const BufShift = math.Log2Int(Buf);
672
673 const buf_value = @intCast(Buf, value);
674
675 const high_byte_shift = @intCast(BufShift, buf_bit_count - u8_bit_count);
676 var in_buffer = switch (endian) {
677 .Big => buf_value << @intCast(BufShift, buf_bit_count - bits),
678 .Little => buf_value,
679 };
680 var in_bits = bits;
681
682 if (self.bit_count > 0) {
683 const bits_remaining = u8_bit_count - self.bit_count;
684 const n = @intCast(u3, if (bits_remaining > bits) bits else bits_remaining);
685 switch (endian) {
686 .Big => {
687 const shift = @intCast(BufShift, high_byte_shift + self.bit_count);
688 const v = @intCast(u8, in_buffer >> shift);
689 self.bit_buffer |= v;
690 in_buffer <<= n;
691 },
692 .Little => {
693 const v = @truncate(u8, in_buffer) << @intCast(u3, self.bit_count);
694 self.bit_buffer |= v;
695 in_buffer >>= n;
696 },
697 }
698 self.bit_count += n;
699 in_bits -= n;
700
701 //if we didn't fill the buffer, it's because bits < bits_remaining;
702 if (self.bit_count != u8_bit_count) return;
703 try self.out_stream.writeByte(self.bit_buffer);
704 self.bit_buffer = 0;
705 self.bit_count = 0;
706 }
707 //at this point we know bit_buffer is empty
708
709 //copy bytes until we can't fill one anymore, then leave the rest in bit_buffer
710 while (in_bits >= u8_bit_count) {
711 switch (endian) {
712 .Big => {
713 const v = @intCast(u8, in_buffer >> high_byte_shift);
714 try self.out_stream.writeByte(v);
715 in_buffer <<= @intCast(u3, u8_bit_count - 1);
716 in_buffer <<= 1;
717 },
718 .Little => {
719 const v = @truncate(u8, in_buffer);
720 try self.out_stream.writeByte(v);
721 in_buffer >>= @intCast(u3, u8_bit_count - 1);
722 in_buffer >>= 1;
723 },
724 }
725 in_bits -= u8_bit_count;
726 }
727
728 if (in_bits > 0) {
729 self.bit_count = @intCast(u4, in_bits);
730 self.bit_buffer = switch (endian) {
731 .Big => @truncate(u8, in_buffer >> high_byte_shift),
732 .Little => @truncate(u8, in_buffer),
733 };
734 }
735 }
736
737 /// Flush any remaining bits to the stream.
738 pub fn flushBits(self: *Self) Error!void {
739 if (self.bit_count == 0) return;
740 try self.out_stream.writeByte(self.bit_buffer);
741 self.bit_buffer = 0;
742 self.bit_count = 0;
743 }
744
745 pub fn write(self_stream: *Stream, buffer: []const u8) Error!usize {
746 var self = @fieldParentPtr(Self, "stream", self_stream);
747
748 // TODO: I'm not sure this is a good idea, maybe flushBits should be forced
749 if (self.bit_count > 0) {
750 for (buffer) |b, i|
751 try self.writeBits(b, u8_bit_count);
752 return buffer.len;
753 }
754
755 return self.out_stream.writeOnce(buffer);
756 }
757 };
758}
759
760pub const BufferedAtomicFile = struct {
761 atomic_file: fs.AtomicFile,
762 file_stream: File.OutStream,
763 buffered_stream: BufferedOutStream(File.WriteError),
764 allocator: *mem.Allocator,
765
766 pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile {
767 // TODO with well defined copy elision we don't need this allocation
768 var self = try allocator.create(BufferedAtomicFile);
769 self.* = BufferedAtomicFile{
770 .atomic_file = undefined,
771 .file_stream = undefined,
772 .buffered_stream = undefined,
773 .allocator = allocator,
774 };
775 errdefer allocator.destroy(self);
776
777 self.atomic_file = try fs.AtomicFile.init(dest_path, File.default_mode);
778 errdefer self.atomic_file.deinit();
779
780 self.file_stream = self.atomic_file.file.outStream();
781 self.buffered_stream = BufferedOutStream(File.WriteError).init(&self.file_stream.stream);
782 return self;
783 }
784
785 /// always call destroy, even after successful finish()
786 pub fn destroy(self: *BufferedAtomicFile) void {
787 self.atomic_file.deinit();
788 self.allocator.destroy(self);
789 }
790
791 pub fn finish(self: *BufferedAtomicFile) !void {
792 try self.buffered_stream.flush();
793 try self.atomic_file.finish();
794 }
795
796 pub fn stream(self: *BufferedAtomicFile) *OutStream(File.WriteError) {
797 return &self.buffered_stream.stream;
798 }
799};
800
801pub const Packing = enum {
802 /// Pack data to byte alignment
803 Byte,
804
805 /// Pack data to bit alignment
806 Bit,
807};
808
809/// Creates a deserializer that deserializes types from any stream.
810/// If `is_packed` is true, the data stream is treated as bit-packed,
811/// otherwise data is expected to be packed to the smallest byte.
812/// Types may implement a custom deserialization routine with a
813/// function named `deserialize` in the form of:
814/// pub fn deserialize(self: *Self, deserializer: var) !void
815/// which will be called when the deserializer is used to deserialize
816/// that type. It will pass a pointer to the type instance to deserialize
817/// into and a pointer to the deserializer struct.
818pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime Error: type) type {
819 return struct {
820 const Self = @This();
821
822 in_stream: if (packing == .Bit) BitInStream(endian, Stream.Error) else *Stream,
823
824 pub const Stream = InStream(Error);
825
826 pub fn init(in_stream: *Stream) Self {
827 return Self{
828 .in_stream = switch (packing) {
829 .Bit => BitInStream(endian, Stream.Error).init(in_stream),
830 .Byte => in_stream,
831 },
832 };
833 }
834
835 pub fn alignToByte(self: *Self) void {
836 if (packing == .Byte) return;
837 self.in_stream.alignToByte();
838 }
839
840 //@BUG: inferred error issue. See: #1386
841 fn deserializeInt(self: *Self, comptime T: type) (Error || error{EndOfStream})!T {
842 comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
843
844 const u8_bit_count = 8;
845 const t_bit_count = comptime meta.bitCount(T);
846
847 const U = std.meta.IntType(false, t_bit_count);
848 const Log2U = math.Log2Int(U);
849 const int_size = (U.bit_count + 7) / 8;
850
851 if (packing == .Bit) {
852 const result = try self.in_stream.readBitsNoEof(U, t_bit_count);
853 return @bitCast(T, result);
854 }
855
856 var buffer: [int_size]u8 = undefined;
857 const read_size = try self.in_stream.read(buffer[0..]);
858 if (read_size < int_size) return error.EndOfStream;
859
860 if (int_size == 1) {
861 if (t_bit_count == 8) return @bitCast(T, buffer[0]);
862 const PossiblySignedByte = std.meta.IntType(T.is_signed, 8);
863 return @truncate(T, @bitCast(PossiblySignedByte, buffer[0]));
864 }
865
866 var result = @as(U, 0);
867 for (buffer) |byte, i| {
868 switch (endian) {
869 .Big => {
870 result = (result << u8_bit_count) | byte;
871 },
872 .Little => {
873 result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);
874 },
875 }
876 }
877
878 return @bitCast(T, result);
879 }
880
881 /// Deserializes and returns data of the specified type from the stream
882 pub fn deserialize(self: *Self, comptime T: type) !T {
883 var value: T = undefined;
884 try self.deserializeInto(&value);
885 return value;
886 }
887
888 /// Deserializes data into the type pointed to by `ptr`
889 pub fn deserializeInto(self: *Self, ptr: var) !void {
890 const T = @TypeOf(ptr);
891 comptime assert(trait.is(.Pointer)(T));
892
893 if (comptime trait.isSlice(T) or comptime trait.isPtrTo(.Array)(T)) {
894 for (ptr) |*v|
895 try self.deserializeInto(v);
896 return;
897 }
898
899 comptime assert(trait.isSingleItemPtr(T));
900
901 const C = comptime meta.Child(T);
902 const child_type_id = @typeInfo(C);
903
904 //custom deserializer: fn(self: *Self, deserializer: var) !void
905 if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self);
906
907 if (comptime trait.isPacked(C) and packing != .Bit) {
908 var packed_deserializer = Deserializer(endian, .Bit, Error).init(self.in_stream);
909 return packed_deserializer.deserializeInto(ptr);
910 }
911
912 switch (child_type_id) {
913 .Void => return,
914 .Bool => ptr.* = (try self.deserializeInt(u1)) > 0,
915 .Float, .Int => ptr.* = try self.deserializeInt(C),
916 .Struct => {
917 const info = @typeInfo(C).Struct;
918
919 inline for (info.fields) |*field_info| {
920 const name = field_info.name;
921 const FieldType = field_info.field_type;
922
923 if (FieldType == void or FieldType == u0) continue;
924
925 //it doesn't make any sense to read pointers
926 if (comptime trait.is(.Pointer)(FieldType)) {
927 @compileError("Will not " ++ "read field " ++ name ++ " of struct " ++
928 @typeName(C) ++ " because it " ++ "is of pointer-type " ++
929 @typeName(FieldType) ++ ".");
930 }
931
932 try self.deserializeInto(&@field(ptr, name));
933 }
934 },
935 .Union => {
936 const info = @typeInfo(C).Union;
937 if (info.tag_type) |TagType| {
938 //we avoid duplicate iteration over the enum tags
939 // by getting the int directly and casting it without
940 // safety. If it is bad, it will be caught anyway.
941 const TagInt = @TagType(TagType);
942 const tag = try self.deserializeInt(TagInt);
943
944 inline for (info.fields) |field_info| {
945 if (field_info.enum_field.?.value == tag) {
946 const name = field_info.name;
947 const FieldType = field_info.field_type;
948 ptr.* = @unionInit(C, name, undefined);
949 try self.deserializeInto(&@field(ptr, name));
950 return;
951 }
952 }
953 //This is reachable if the enum data is bad
954 return error.InvalidEnumTag;
955 }
956 @compileError("Cannot meaningfully deserialize " ++ @typeName(C) ++
957 " because it is an untagged union. Use a custom deserialize().");
958 },
959 .Optional => {
960 const OC = comptime meta.Child(C);
961 const exists = (try self.deserializeInt(u1)) > 0;
962 if (!exists) {
963 ptr.* = null;
964 return;
965 }
966
967 ptr.* = @as(OC, undefined); //make it non-null so the following .? is guaranteed safe
968 const val_ptr = &ptr.*.?;
969 try self.deserializeInto(val_ptr);
970 },
971 .Enum => {
972 var value = try self.deserializeInt(@TagType(C));
973 ptr.* = try meta.intToEnum(C, value);
974 },
975 else => {
976 @compileError("Cannot deserialize " ++ @tagName(child_type_id) ++ " types (unimplemented).");
977 },
978 }
979 }
980 };
981}151}
982152
983/// Creates a serializer that serializes types to any stream.153test "" {
984/// If `is_packed` is true, the data will be bit-packed into the stream.154 _ = @import("io/test.zig");
985/// Note that the you must call `serializer.flush()` when you are done
986/// writing bit-packed data in order ensure any unwritten bits are committed.
987/// If `is_packed` is false, data is packed to the smallest byte. In the case
988/// of packed structs, the struct will written bit-packed and with the specified
989/// endianess, after which data will resume being written at the next byte boundary.
990/// Types may implement a custom serialization routine with a
991/// function named `serialize` in the form of:
992/// pub fn serialize(self: Self, serializer: var) !void
993/// which will be called when the serializer is used to serialize that type. It will
994/// pass a const pointer to the type instance to be serialized and a pointer
995/// to the serializer struct.
996pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime Error: type) type {
997 return struct {
998 const Self = @This();
999
1000 out_stream: if (packing == .Bit) BitOutStream(endian, Stream.Error) else *Stream,
1001
1002 pub const Stream = OutStream(Error);
1003
1004 pub fn init(out_stream: *Stream) Self {
1005 return Self{
1006 .out_stream = switch (packing) {
1007 .Bit => BitOutStream(endian, Stream.Error).init(out_stream),
1008 .Byte => out_stream,
1009 },
1010 };
1011 }
1012
1013 /// Flushes any unwritten bits to the stream
1014 pub fn flush(self: *Self) Error!void {
1015 if (packing == .Bit) return self.out_stream.flushBits();
1016 }
1017
1018 fn serializeInt(self: *Self, value: var) Error!void {
1019 const T = @TypeOf(value);
1020 comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
1021
1022 const t_bit_count = comptime meta.bitCount(T);
1023 const u8_bit_count = comptime meta.bitCount(u8);
1024
1025 const U = std.meta.IntType(false, t_bit_count);
1026 const Log2U = math.Log2Int(U);
1027 const int_size = (U.bit_count + 7) / 8;
1028
1029 const u_value = @bitCast(U, value);
1030
1031 if (packing == .Bit) return self.out_stream.writeBits(u_value, t_bit_count);
1032
1033 var buffer: [int_size]u8 = undefined;
1034 if (int_size == 1) buffer[0] = u_value;
1035
1036 for (buffer) |*byte, i| {
1037 const idx = switch (endian) {
1038 .Big => int_size - i - 1,
1039 .Little => i,
1040 };
1041 const shift = @intCast(Log2U, idx * u8_bit_count);
1042 const v = u_value >> shift;
1043 byte.* = if (t_bit_count < u8_bit_count) v else @truncate(u8, v);
1044 }
1045
1046 try self.out_stream.write(&buffer);
1047 }
1048
1049 /// Serializes the passed value into the stream
1050 pub fn serialize(self: *Self, value: var) Error!void {
1051 const T = comptime @TypeOf(value);
1052
1053 if (comptime trait.isIndexable(T)) {
1054 for (value) |v|
1055 try self.serialize(v);
1056 return;
1057 }
1058
1059 //custom serializer: fn(self: Self, serializer: var) !void
1060 if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);
1061
1062 if (comptime trait.isPacked(T) and packing != .Bit) {
1063 var packed_serializer = Serializer(endian, .Bit, Error).init(self.out_stream);
1064 try packed_serializer.serialize(value);
1065 try packed_serializer.flush();
1066 return;
1067 }
1068
1069 switch (@typeInfo(T)) {
1070 .Void => return,
1071 .Bool => try self.serializeInt(@as(u1, @boolToInt(value))),
1072 .Float, .Int => try self.serializeInt(value),
1073 .Struct => {
1074 const info = @typeInfo(T);
1075
1076 inline for (info.Struct.fields) |*field_info| {
1077 const name = field_info.name;
1078 const FieldType = field_info.field_type;
1079
1080 if (FieldType == void or FieldType == u0) continue;
1081
1082 //It doesn't make sense to write pointers
1083 if (comptime trait.is(.Pointer)(FieldType)) {
1084 @compileError("Will not " ++ "serialize field " ++ name ++
1085 " of struct " ++ @typeName(T) ++ " because it " ++
1086 "is of pointer-type " ++ @typeName(FieldType) ++ ".");
1087 }
1088 try self.serialize(@field(value, name));
1089 }
1090 },
1091 .Union => {
1092 const info = @typeInfo(T).Union;
1093 if (info.tag_type) |TagType| {
1094 const active_tag = meta.activeTag(value);
1095 try self.serialize(active_tag);
1096 //This inline loop is necessary because active_tag is a runtime
1097 // value, but @field requires a comptime value. Our alternative
1098 // is to check each field for a match
1099 inline for (info.fields) |field_info| {
1100 if (field_info.enum_field.?.value == @enumToInt(active_tag)) {
1101 const name = field_info.name;
1102 const FieldType = field_info.field_type;
1103 try self.serialize(@field(value, name));
1104 return;
1105 }
1106 }
1107 unreachable;
1108 }
1109 @compileError("Cannot meaningfully serialize " ++ @typeName(T) ++
1110 " because it is an untagged union. Use a custom serialize().");
1111 },
1112 .Optional => {
1113 if (value == null) {
1114 try self.serializeInt(@as(u1, @boolToInt(false)));
1115 return;
1116 }
1117 try self.serializeInt(@as(u1, @boolToInt(true)));
1118
1119 const OC = comptime meta.Child(T);
1120 const val_ptr = &value.?;
1121 try self.serialize(val_ptr.*);
1122 },
1123 .Enum => {
1124 try self.serializeInt(@enumToInt(value));
1125 },
1126 else => @compileError("Cannot serialize " ++ @tagName(@typeInfo(T)) ++ " types (unimplemented)."),
1127 }
1128 }
1129 };
1130}
1131
1132test "import io tests" {
1133 comptime {
1134 _ = @import("io/test.zig");
1135 }
1136}155}
lib/std/io/bit_in_stream.zig created+243
...@@ -0,0 +1,243 @@
1const std = @import("../std.zig");
2const builtin = std.builtin;
3const io = std.io;
4const assert = std.debug.assert;
5const testing = std.testing;
6const trait = std.meta.trait;
7const meta = std.meta;
8const math = std.math;
9
10/// Creates a stream which allows for reading bit fields from another stream
11pub fn BitInStream(endian: builtin.Endian, comptime InStreamType: type) type {
12 return struct {
13 in_stream: InStreamType,
14 bit_buffer: u7,
15 bit_count: u3,
16
17 pub const Error = InStreamType.Error;
18 pub const InStream = io.InStream(*Self, Error, read);
19
20 const Self = @This();
21 const u8_bit_count = comptime meta.bitCount(u8);
22 const u7_bit_count = comptime meta.bitCount(u7);
23 const u4_bit_count = comptime meta.bitCount(u4);
24
25 pub fn init(in_stream: InStreamType) Self {
26 return Self{
27 .in_stream = in_stream,
28 .bit_buffer = 0,
29 .bit_count = 0,
30 };
31 }
32
33 /// Reads `bits` bits from the stream and returns a specified unsigned int type
34 /// containing them in the least significant end, returning an error if the
35 /// specified number of bits could not be read.
36 pub fn readBitsNoEof(self: *Self, comptime U: type, bits: usize) !U {
37 var n: usize = undefined;
38 const result = try self.readBits(U, bits, &n);
39 if (n < bits) return error.EndOfStream;
40 return result;
41 }
42
43 /// Reads `bits` bits from the stream and returns a specified unsigned int type
44 /// containing them in the least significant end. The number of bits successfully
45 /// read is placed in `out_bits`, as reaching the end of the stream is not an error.
46 pub fn readBits(self: *Self, comptime U: type, bits: usize, out_bits: *usize) Error!U {
47 comptime assert(trait.isUnsignedInt(U));
48
49 //by extending the buffer to a minimum of u8 we can cover a number of edge cases
50 // related to shifting and casting.
51 const u_bit_count = comptime meta.bitCount(U);
52 const buf_bit_count = bc: {
53 assert(u_bit_count >= bits);
54 break :bc if (u_bit_count <= u8_bit_count) u8_bit_count else u_bit_count;
55 };
56 const Buf = std.meta.IntType(false, buf_bit_count);
57 const BufShift = math.Log2Int(Buf);
58
59 out_bits.* = @as(usize, 0);
60 if (U == u0 or bits == 0) return 0;
61 var out_buffer = @as(Buf, 0);
62
63 if (self.bit_count > 0) {
64 const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;
65 const shift = u7_bit_count - n;
66 switch (endian) {
67 .Big => {
68 out_buffer = @as(Buf, self.bit_buffer >> shift);
69 if (n >= u7_bit_count)
70 self.bit_buffer = 0
71 else
72 self.bit_buffer <<= n;
73 },
74 .Little => {
75 const value = (self.bit_buffer << shift) >> shift;
76 out_buffer = @as(Buf, value);
77 if (n >= u7_bit_count)
78 self.bit_buffer = 0
79 else
80 self.bit_buffer >>= n;
81 },
82 }
83 self.bit_count -= n;
84 out_bits.* = n;
85 }
86 //at this point we know bit_buffer is empty
87
88 //copy bytes until we have enough bits, then leave the rest in bit_buffer
89 while (out_bits.* < bits) {
90 const n = bits - out_bits.*;
91 const next_byte = self.in_stream.readByte() catch |err| {
92 if (err == error.EndOfStream) {
93 return @intCast(U, out_buffer);
94 }
95 //@BUG: See #1810. Not sure if the bug is that I have to do this for some
96 // streams, or that I don't for streams with emtpy errorsets.
97 return @errSetCast(Error, err);
98 };
99
100 switch (endian) {
101 .Big => {
102 if (n >= u8_bit_count) {
103 out_buffer <<= @intCast(u3, u8_bit_count - 1);
104 out_buffer <<= 1;
105 out_buffer |= @as(Buf, next_byte);
106 out_bits.* += u8_bit_count;
107 continue;
108 }
109
110 const shift = @intCast(u3, u8_bit_count - n);
111 out_buffer <<= @intCast(BufShift, n);
112 out_buffer |= @as(Buf, next_byte >> shift);
113 out_bits.* += n;
114 self.bit_buffer = @truncate(u7, next_byte << @intCast(u3, n - 1));
115 self.bit_count = shift;
116 },
117 .Little => {
118 if (n >= u8_bit_count) {
119 out_buffer |= @as(Buf, next_byte) << @intCast(BufShift, out_bits.*);
120 out_bits.* += u8_bit_count;
121 continue;
122 }
123
124 const shift = @intCast(u3, u8_bit_count - n);
125 const value = (next_byte << shift) >> shift;
126 out_buffer |= @as(Buf, value) << @intCast(BufShift, out_bits.*);
127 out_bits.* += n;
128 self.bit_buffer = @truncate(u7, next_byte >> @intCast(u3, n));
129 self.bit_count = shift;
130 },
131 }
132 }
133
134 return @intCast(U, out_buffer);
135 }
136
137 pub fn alignToByte(self: *Self) void {
138 self.bit_buffer = 0;
139 self.bit_count = 0;
140 }
141
142 pub fn read(self: *Self, buffer: []u8) Error!usize {
143 var out_bits: usize = undefined;
144 var out_bits_total = @as(usize, 0);
145 //@NOTE: I'm not sure this is a good idea, maybe alignToByte should be forced
146 if (self.bit_count > 0) {
147 for (buffer) |*b, i| {
148 b.* = try self.readBits(u8, u8_bit_count, &out_bits);
149 out_bits_total += out_bits;
150 }
151 const incomplete_byte = @boolToInt(out_bits_total % u8_bit_count > 0);
152 return (out_bits_total / u8_bit_count) + incomplete_byte;
153 }
154
155 return self.in_stream.read(buffer);
156 }
157
158 pub fn inStream(self: *Self) InStream {
159 return .{ .context = self };
160 }
161 };
162}
163
164pub fn bitInStream(
165 comptime endian: builtin.Endian,
166 underlying_stream: var,
167) BitInStream(endian, @TypeOf(underlying_stream)) {
168 return BitInStream(endian, @TypeOf(underlying_stream)).init(underlying_stream);
169}
170
171test "api coverage" {
172 const mem_be = [_]u8{ 0b11001101, 0b00001011 };
173 const mem_le = [_]u8{ 0b00011101, 0b10010101 };
174
175 var mem_in_be = io.fixedBufferStream(&mem_be);
176 var bit_stream_be = bitInStream(.Big, mem_in_be.inStream());
177
178 var out_bits: usize = undefined;
179
180 const expect = testing.expect;
181 const expectError = testing.expectError;
182
183 expect(1 == try bit_stream_be.readBits(u2, 1, &out_bits));
184 expect(out_bits == 1);
185 expect(2 == try bit_stream_be.readBits(u5, 2, &out_bits));
186 expect(out_bits == 2);
187 expect(3 == try bit_stream_be.readBits(u128, 3, &out_bits));
188 expect(out_bits == 3);
189 expect(4 == try bit_stream_be.readBits(u8, 4, &out_bits));
190 expect(out_bits == 4);
191 expect(5 == try bit_stream_be.readBits(u9, 5, &out_bits));
192 expect(out_bits == 5);
193 expect(1 == try bit_stream_be.readBits(u1, 1, &out_bits));
194 expect(out_bits == 1);
195
196 mem_in_be.pos = 0;
197 bit_stream_be.bit_count = 0;
198 expect(0b110011010000101 == try bit_stream_be.readBits(u15, 15, &out_bits));
199 expect(out_bits == 15);
200
201 mem_in_be.pos = 0;
202 bit_stream_be.bit_count = 0;
203 expect(0b1100110100001011 == try bit_stream_be.readBits(u16, 16, &out_bits));
204 expect(out_bits == 16);
205
206 _ = try bit_stream_be.readBits(u0, 0, &out_bits);
207
208 expect(0 == try bit_stream_be.readBits(u1, 1, &out_bits));
209 expect(out_bits == 0);
210 expectError(error.EndOfStream, bit_stream_be.readBitsNoEof(u1, 1));
211
212 var mem_in_le = io.fixedBufferStream(&mem_le);
213 var bit_stream_le = bitInStream(.Little, mem_in_le.inStream());
214
215 expect(1 == try bit_stream_le.readBits(u2, 1, &out_bits));
216 expect(out_bits == 1);
217 expect(2 == try bit_stream_le.readBits(u5, 2, &out_bits));
218 expect(out_bits == 2);
219 expect(3 == try bit_stream_le.readBits(u128, 3, &out_bits));
220 expect(out_bits == 3);
221 expect(4 == try bit_stream_le.readBits(u8, 4, &out_bits));
222 expect(out_bits == 4);
223 expect(5 == try bit_stream_le.readBits(u9, 5, &out_bits));
224 expect(out_bits == 5);
225 expect(1 == try bit_stream_le.readBits(u1, 1, &out_bits));
226 expect(out_bits == 1);
227
228 mem_in_le.pos = 0;
229 bit_stream_le.bit_count = 0;
230 expect(0b001010100011101 == try bit_stream_le.readBits(u15, 15, &out_bits));
231 expect(out_bits == 15);
232
233 mem_in_le.pos = 0;
234 bit_stream_le.bit_count = 0;
235 expect(0b1001010100011101 == try bit_stream_le.readBits(u16, 16, &out_bits));
236 expect(out_bits == 16);
237
238 _ = try bit_stream_le.readBits(u0, 0, &out_bits);
239
240 expect(0 == try bit_stream_le.readBits(u1, 1, &out_bits));
241 expect(out_bits == 0);
242 expectError(error.EndOfStream, bit_stream_le.readBitsNoEof(u1, 1));
243}
lib/std/io/bit_out_stream.zig created+197
...@@ -0,0 +1,197 @@
1const std = @import("../std.zig");
2const builtin = std.builtin;
3const io = std.io;
4const testing = std.testing;
5const assert = std.debug.assert;
6const trait = std.meta.trait;
7const meta = std.meta;
8const math = std.math;
9
10/// Creates a stream which allows for writing bit fields to another stream
11pub fn BitOutStream(endian: builtin.Endian, comptime OutStreamType: type) type {
12 return struct {
13 out_stream: OutStreamType,
14 bit_buffer: u8,
15 bit_count: u4,
16
17 pub const Error = OutStreamType.Error;
18 pub const OutStream = io.OutStream(*Self, Error, write);
19
20 const Self = @This();
21 const u8_bit_count = comptime meta.bitCount(u8);
22 const u4_bit_count = comptime meta.bitCount(u4);
23
24 pub fn init(out_stream: OutStreamType) Self {
25 return Self{
26 .out_stream = out_stream,
27 .bit_buffer = 0,
28 .bit_count = 0,
29 };
30 }
31
32 /// Write the specified number of bits to the stream from the least significant bits of
33 /// the specified unsigned int value. Bits will only be written to the stream when there
34 /// are enough to fill a byte.
35 pub fn writeBits(self: *Self, value: var, bits: usize) Error!void {
36 if (bits == 0) return;
37
38 const U = @TypeOf(value);
39 comptime assert(trait.isUnsignedInt(U));
40
41 //by extending the buffer to a minimum of u8 we can cover a number of edge cases
42 // related to shifting and casting.
43 const u_bit_count = comptime meta.bitCount(U);
44 const buf_bit_count = bc: {
45 assert(u_bit_count >= bits);
46 break :bc if (u_bit_count <= u8_bit_count) u8_bit_count else u_bit_count;
47 };
48 const Buf = std.meta.IntType(false, buf_bit_count);
49 const BufShift = math.Log2Int(Buf);
50
51 const buf_value = @intCast(Buf, value);
52
53 const high_byte_shift = @intCast(BufShift, buf_bit_count - u8_bit_count);
54 var in_buffer = switch (endian) {
55 .Big => buf_value << @intCast(BufShift, buf_bit_count - bits),
56 .Little => buf_value,
57 };
58 var in_bits = bits;
59
60 if (self.bit_count > 0) {
61 const bits_remaining = u8_bit_count - self.bit_count;
62 const n = @intCast(u3, if (bits_remaining > bits) bits else bits_remaining);
63 switch (endian) {
64 .Big => {
65 const shift = @intCast(BufShift, high_byte_shift + self.bit_count);
66 const v = @intCast(u8, in_buffer >> shift);
67 self.bit_buffer |= v;
68 in_buffer <<= n;
69 },
70 .Little => {
71 const v = @truncate(u8, in_buffer) << @intCast(u3, self.bit_count);
72 self.bit_buffer |= v;
73 in_buffer >>= n;
74 },
75 }
76 self.bit_count += n;
77 in_bits -= n;
78
79 //if we didn't fill the buffer, it's because bits < bits_remaining;
80 if (self.bit_count != u8_bit_count) return;
81 try self.out_stream.writeByte(self.bit_buffer);
82 self.bit_buffer = 0;
83 self.bit_count = 0;
84 }
85 //at this point we know bit_buffer is empty
86
87 //copy bytes until we can't fill one anymore, then leave the rest in bit_buffer
88 while (in_bits >= u8_bit_count) {
89 switch (endian) {
90 .Big => {
91 const v = @intCast(u8, in_buffer >> high_byte_shift);
92 try self.out_stream.writeByte(v);
93 in_buffer <<= @intCast(u3, u8_bit_count - 1);
94 in_buffer <<= 1;
95 },
96 .Little => {
97 const v = @truncate(u8, in_buffer);
98 try self.out_stream.writeByte(v);
99 in_buffer >>= @intCast(u3, u8_bit_count - 1);
100 in_buffer >>= 1;
101 },
102 }
103 in_bits -= u8_bit_count;
104 }
105
106 if (in_bits > 0) {
107 self.bit_count = @intCast(u4, in_bits);
108 self.bit_buffer = switch (endian) {
109 .Big => @truncate(u8, in_buffer >> high_byte_shift),
110 .Little => @truncate(u8, in_buffer),
111 };
112 }
113 }
114
115 /// Flush any remaining bits to the stream.
116 pub fn flushBits(self: *Self) Error!void {
117 if (self.bit_count == 0) return;
118 try self.out_stream.writeByte(self.bit_buffer);
119 self.bit_buffer = 0;
120 self.bit_count = 0;
121 }
122
123 pub fn write(self: *Self, buffer: []const u8) Error!usize {
124 // TODO: I'm not sure this is a good idea, maybe flushBits should be forced
125 if (self.bit_count > 0) {
126 for (buffer) |b, i|
127 try self.writeBits(b, u8_bit_count);
128 return buffer.len;
129 }
130
131 return self.out_stream.write(buffer);
132 }
133
134 pub fn outStream(self: *Self) OutStream {
135 return .{ .context = self };
136 }
137 };
138}
139
140pub fn bitOutStream(
141 comptime endian: builtin.Endian,
142 underlying_stream: var,
143) BitOutStream(endian, @TypeOf(underlying_stream)) {
144 return BitOutStream(endian, @TypeOf(underlying_stream)).init(underlying_stream);
145}
146
147test "api coverage" {
148 var mem_be = [_]u8{0} ** 2;
149 var mem_le = [_]u8{0} ** 2;
150
151 var mem_out_be = io.fixedBufferStream(&mem_be);
152 var bit_stream_be = bitOutStream(.Big, mem_out_be.outStream());
153
154 try bit_stream_be.writeBits(@as(u2, 1), 1);
155 try bit_stream_be.writeBits(@as(u5, 2), 2);
156 try bit_stream_be.writeBits(@as(u128, 3), 3);
157 try bit_stream_be.writeBits(@as(u8, 4), 4);
158 try bit_stream_be.writeBits(@as(u9, 5), 5);
159 try bit_stream_be.writeBits(@as(u1, 1), 1);
160
161 testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
162
163 mem_out_be.pos = 0;
164
165 try bit_stream_be.writeBits(@as(u15, 0b110011010000101), 15);
166 try bit_stream_be.flushBits();
167 testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
168
169 mem_out_be.pos = 0;
170 try bit_stream_be.writeBits(@as(u32, 0b110011010000101), 16);
171 testing.expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
172
173 try bit_stream_be.writeBits(@as(u0, 0), 0);
174
175 var mem_out_le = io.fixedBufferStream(&mem_le);
176 var bit_stream_le = bitOutStream(.Little, mem_out_le.outStream());
177
178 try bit_stream_le.writeBits(@as(u2, 1), 1);
179 try bit_stream_le.writeBits(@as(u5, 2), 2);
180 try bit_stream_le.writeBits(@as(u128, 3), 3);
181 try bit_stream_le.writeBits(@as(u8, 4), 4);
182 try bit_stream_le.writeBits(@as(u9, 5), 5);
183 try bit_stream_le.writeBits(@as(u1, 1), 1);
184
185 testing.expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
186
187 mem_out_le.pos = 0;
188 try bit_stream_le.writeBits(@as(u15, 0b110011010000101), 15);
189 try bit_stream_le.flushBits();
190 testing.expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
191
192 mem_out_le.pos = 0;
193 try bit_stream_le.writeBits(@as(u32, 0b1100110100001011), 16);
194 testing.expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
195
196 try bit_stream_le.writeBits(@as(u0, 0), 0);
197}
lib/std/io/buffered_atomic_file.zig created+50
...@@ -0,0 +1,50 @@
1const std = @import("../std.zig");
2const mem = std.mem;
3const fs = std.fs;
4const File = std.fs.File;
5
6pub const BufferedAtomicFile = struct {
7 atomic_file: fs.AtomicFile,
8 file_stream: File.OutStream,
9 buffered_stream: BufferedOutStream,
10 allocator: *mem.Allocator,
11
12 pub const buffer_size = 4096;
13 pub const BufferedOutStream = std.io.BufferedOutStream(buffer_size, File.OutStream);
14 pub const OutStream = std.io.OutStream(*BufferedOutStream, BufferedOutStream.Error, BufferedOutStream.write);
15
16 /// TODO when https://github.com/ziglang/zig/issues/2761 is solved
17 /// this API will not need an allocator
18 pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile {
19 var self = try allocator.create(BufferedAtomicFile);
20 self.* = BufferedAtomicFile{
21 .atomic_file = undefined,
22 .file_stream = undefined,
23 .buffered_stream = undefined,
24 .allocator = allocator,
25 };
26 errdefer allocator.destroy(self);
27
28 self.atomic_file = try fs.AtomicFile.init(dest_path, File.default_mode);
29 errdefer self.atomic_file.deinit();
30
31 self.file_stream = self.atomic_file.file.outStream();
32 self.buffered_stream = .{ .unbuffered_out_stream = self.file_stream };
33 return self;
34 }
35
36 /// always call destroy, even after successful finish()
37 pub fn destroy(self: *BufferedAtomicFile) void {
38 self.atomic_file.deinit();
39 self.allocator.destroy(self);
40 }
41
42 pub fn finish(self: *BufferedAtomicFile) !void {
43 try self.buffered_stream.flush();
44 try self.atomic_file.finish();
45 }
46
47 pub fn stream(self: *BufferedAtomicFile) OutStream {
48 return .{ .context = &self.buffered_stream };
49 }
50};
lib/std/io/buffered_in_stream.zig created+86
...@@ -0,0 +1,86 @@
1const std = @import("../std.zig");
2const io = std.io;
3const assert = std.debug.assert;
4const testing = std.testing;
5
6pub fn BufferedInStream(comptime buffer_size: usize, comptime InStreamType: type) type {
7 return struct {
8 unbuffered_in_stream: InStreamType,
9 fifo: FifoType = FifoType.init(),
10
11 pub const Error = InStreamType.Error;
12 pub const InStream = io.InStream(*Self, Error, read);
13
14 const Self = @This();
15 const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
16
17 pub fn read(self: *Self, dest: []u8) Error!usize {
18 var dest_index: usize = 0;
19 while (dest_index < dest.len) {
20 const written = self.fifo.read(dest[dest_index..]);
21 if (written == 0) {
22 // fifo empty, fill it
23 const writable = self.fifo.writableSlice(0);
24 assert(writable.len > 0);
25 const n = try self.unbuffered_in_stream.read(writable);
26 if (n == 0) {
27 // reading from the unbuffered stream returned nothing
28 // so we have nothing left to read.
29 return dest_index;
30 }
31 self.fifo.update(n);
32 }
33 dest_index += written;
34 }
35 return dest.len;
36 }
37
38 pub fn inStream(self: *Self) InStream {
39 return .{ .context = self };
40 }
41 };
42}
43
44pub fn bufferedInStream(underlying_stream: var) BufferedInStream(4096, @TypeOf(underlying_stream)) {
45 return .{ .unbuffered_in_stream = underlying_stream };
46}
47
48test "io.BufferedInStream" {
49 const OneByteReadInStream = struct {
50 str: []const u8,
51 curr: usize,
52
53 const Error = error{NoError};
54 const Self = @This();
55 const InStream = io.InStream(*Self, Error, read);
56
57 fn init(str: []const u8) Self {
58 return Self{
59 .str = str,
60 .curr = 0,
61 };
62 }
63
64 fn read(self: *Self, dest: []u8) Error!usize {
65 if (self.str.len <= self.curr or dest.len == 0)
66 return 0;
67
68 dest[0] = self.str[self.curr];
69 self.curr += 1;
70 return 1;
71 }
72
73 fn inStream(self: *Self) InStream {
74 return .{ .context = self };
75 }
76 };
77
78 const str = "This is a test";
79 var one_byte_stream = OneByteReadInStream.init(str);
80 var buf_in_stream = bufferedInStream(one_byte_stream.inStream());
81 const stream = buf_in_stream.inStream();
82
83 const res = try stream.readAllAlloc(testing.allocator, str.len + 1);
84 defer testing.allocator.free(res);
85 testing.expectEqualSlices(u8, str, res);
86}
lib/std/io/buffered_out_stream.zig created+41
...@@ -0,0 +1,41 @@
1const std = @import("../std.zig");
2const io = std.io;
3
4pub fn BufferedOutStream(comptime buffer_size: usize, comptime OutStreamType: type) type {
5 return struct {
6 unbuffered_out_stream: OutStreamType,
7 fifo: FifoType = FifoType.init(),
8
9 pub const Error = OutStreamType.Error;
10 pub const OutStream = io.OutStream(*Self, Error, write);
11
12 const Self = @This();
13 const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
14
15 pub fn flush(self: *Self) !void {
16 while (true) {
17 const slice = self.fifo.readableSlice(0);
18 if (slice.len == 0) break;
19 try self.unbuffered_out_stream.writeAll(slice);
20 self.fifo.discard(slice.len);
21 }
22 }
23
24 pub fn outStream(self: *Self) OutStream {
25 return .{ .context = self };
26 }
27
28 pub fn write(self: *Self, bytes: []const u8) Error!usize {
29 if (bytes.len >= self.fifo.writableLength()) {
30 try self.flush();
31 return self.unbuffered_out_stream.write(bytes);
32 }
33 self.fifo.writeAssumeCapacity(bytes);
34 return bytes.len;
35 }
36 };
37}
38
39pub fn bufferedOutStream(underlying_stream: var) BufferedOutStream(4096, @TypeOf(underlying_stream)) {
40 return .{ .unbuffered_out_stream = underlying_stream };
41}
lib/std/io/c_out_stream.zig+37-36
...@@ -1,43 +1,44 @@...@@ -1,43 +1,44 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const os = std.os;2const builtin = std.builtin;
3const OutStream = std.io.OutStream;3const io = std.io;
4const builtin = @import("builtin");4const testing = std.testing;
55
6/// TODO make a proposal to make `std.fs.File` use *FILE when linking libc and this just becomes6pub const COutStream = io.OutStream(*std.c.FILE, std.fs.File.WriteError, cOutStreamWrite);
7/// std.io.FileOutStream because std.fs.File.write would do this when linking
8/// libc.
9pub const COutStream = struct {
10 pub const Error = std.fs.File.WriteError;
11 pub const Stream = OutStream(Error);
127
13 stream: Stream,8pub fn cOutStream(c_file: *std.c.FILE) COutStream {
14 c_file: *std.c.FILE,9 return .{ .context = c_file };
10}
1511
16 pub fn init(c_file: *std.c.FILE) COutStream {12fn cOutStreamWrite(c_file: *std.c.FILE, bytes: []const u8) std.fs.File.WriteError!usize {
17 return COutStream{13 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, c_file);
18 .c_file = c_file,14 if (amt_written >= 0) return amt_written;
19 .stream = Stream{ .writeFn = writeFn },15 switch (std.c._errno().*) {
20 };16 0 => unreachable,
17 os.EINVAL => unreachable,
18 os.EFAULT => unreachable,
19 os.EAGAIN => unreachable, // this is a blocking API
20 os.EBADF => unreachable, // always a race condition
21 os.EDESTADDRREQ => unreachable, // connect was never called
22 os.EDQUOT => return error.DiskQuota,
23 os.EFBIG => return error.FileTooBig,
24 os.EIO => return error.InputOutput,
25 os.ENOSPC => return error.NoSpaceLeft,
26 os.EPERM => return error.AccessDenied,
27 os.EPIPE => return error.BrokenPipe,
28 else => |err| return os.unexpectedErrno(@intCast(usize, err)),
21 }29 }
30}
2231
23 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {32test "" {
24 const self = @fieldParentPtr(COutStream, "stream", out_stream);33 if (!builtin.link_libc) return error.SkipZigTest;
25 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, self.c_file);34
26 if (amt_written >= 0) return amt_written;35 const filename = "tmp_io_test_file.txt";
27 switch (std.c._errno().*) {36 const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile;
28 0 => unreachable,37 defer {
29 os.EINVAL => unreachable,38 _ = std.c.fclose(out_file);
30 os.EFAULT => unreachable,39 fs.cwd().deleteFileC(filename) catch {};
31 os.EAGAIN => unreachable, // this is a blocking API
32 os.EBADF => unreachable, // always a race condition
33 os.EDESTADDRREQ => unreachable, // connect was never called
34 os.EDQUOT => return error.DiskQuota,
35 os.EFBIG => return error.FileTooBig,
36 os.EIO => return error.InputOutput,
37 os.ENOSPC => return error.NoSpaceLeft,
38 os.EPERM => return error.AccessDenied,
39 os.EPIPE => return error.BrokenPipe,
40 else => |err| return os.unexpectedErrno(@intCast(usize, err)),
41 }
42 }40 }
43};41
42 const out_stream = &io.COutStream.init(out_file).stream;
43 try out_stream.print("hi: {}\n", .{@as(i32, 123)});
44}
lib/std/io/counting_out_stream.zig created+39
...@@ -0,0 +1,39 @@
1const std = @import("../std.zig");
2const io = std.io;
3const testing = std.testing;
4
5/// An OutStream that counts how many bytes has been written to it.
6pub fn CountingOutStream(comptime OutStreamType: type) type {
7 return struct {
8 bytes_written: u64,
9 child_stream: OutStreamType,
10
11 pub const Error = OutStreamType.Error;
12 pub const OutStream = io.OutStream(*Self, Error, write);
13
14 const Self = @This();
15
16 pub fn write(self: *Self, bytes: []const u8) Error!usize {
17 const amt = try self.child_stream.write(bytes);
18 self.bytes_written += amt;
19 return amt;
20 }
21
22 pub fn outStream(self: *Self) OutStream {
23 return .{ .context = self };
24 }
25 };
26}
27
28pub fn countingOutStream(child_stream: var) CountingOutStream(@TypeOf(child_stream)) {
29 return .{ .bytes_written = 0, .child_stream = child_stream };
30}
31
32test "io.CountingOutStream" {
33 var counting_stream = countingOutStream(std.io.null_out_stream);
34 const stream = counting_stream.outStream();
35
36 const bytes = "yay" ** 100;
37 stream.writeAll(bytes) catch unreachable;
38 testing.expect(counting_stream.bytes_written == bytes.len);
39}
lib/std/io/fixed_buffer_stream.zig created+171
...@@ -0,0 +1,171 @@
1const std = @import("../std.zig");
2const io = std.io;
3const testing = std.testing;
4const mem = std.mem;
5const assert = std.debug.assert;
6
7/// This turns a byte buffer into an `io.OutStream`, `io.InStream`, or `io.SeekableStream`.
8/// If the supplied byte buffer is const, then `io.OutStream` is not available.
9pub fn FixedBufferStream(comptime Buffer: type) type {
10 return struct {
11 /// `Buffer` is either a `[]u8` or `[]const u8`.
12 buffer: Buffer,
13 pos: usize,
14
15 pub const ReadError = error{};
16 pub const WriteError = error{NoSpaceLeft};
17 pub const SeekError = error{};
18 pub const GetSeekPosError = error{};
19
20 pub const InStream = io.InStream(*Self, ReadError, read);
21 pub const OutStream = io.OutStream(*Self, WriteError, write);
22
23 pub const SeekableStream = io.SeekableStream(
24 *Self,
25 SeekError,
26 GetSeekPosError,
27 seekTo,
28 seekBy,
29 getPos,
30 getEndPos,
31 );
32
33 const Self = @This();
34
35 pub fn inStream(self: *Self) InStream {
36 return .{ .context = self };
37 }
38
39 pub fn outStream(self: *Self) OutStream {
40 return .{ .context = self };
41 }
42
43 pub fn seekableStream(self: *Self) SeekableStream {
44 return .{ .context = self };
45 }
46
47 pub fn read(self: *Self, dest: []u8) ReadError!usize {
48 const size = std.math.min(dest.len, self.buffer.len - self.pos);
49 const end = self.pos + size;
50
51 mem.copy(u8, dest[0..size], self.buffer[self.pos..end]);
52 self.pos = end;
53
54 return size;
55 }
56
57 /// If the returned number of bytes written is less than requested, the
58 /// buffer is full. Returns `error.NoSpaceLeft` when no bytes would be written.
59 /// Note: `error.NoSpaceLeft` matches the corresponding error from
60 /// `std.fs.File.WriteError`.
61 pub fn write(self: *Self, bytes: []const u8) WriteError!usize {
62 if (bytes.len == 0) return 0;
63 if (self.pos >= self.buffer.len) return error.NoSpaceLeft;
64
65 const n = if (self.pos + bytes.len <= self.buffer.len)
66 bytes.len
67 else
68 self.buffer.len - self.pos;
69
70 mem.copy(u8, self.buffer[self.pos .. self.pos + n], bytes[0..n]);
71 self.pos += n;
72
73 if (n == 0) return error.NoSpaceLeft;
74
75 return n;
76 }
77
78 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
79 self.pos = if (std.math.cast(usize, pos)) |x| x else |_| self.buffer.len;
80 }
81
82 pub fn seekBy(self: *Self, amt: i64) SeekError!void {
83 if (amt < 0) {
84 const abs_amt = std.math.absCast(amt);
85 const abs_amt_usize = std.math.cast(usize, abs_amt) catch std.math.maxInt(usize);
86 if (abs_amt_usize > self.pos) {
87 self.pos = 0;
88 } else {
89 self.pos -= abs_amt_usize;
90 }
91 } else {
92 const amt_usize = std.math.cast(usize, amt) catch std.math.maxInt(usize);
93 const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize);
94 self.pos = std.math.min(self.buffer.len, new_pos);
95 }
96 }
97
98 pub fn getEndPos(self: *Self) GetSeekPosError!u64 {
99 return self.buffer.len;
100 }
101
102 pub fn getPos(self: *Self) GetSeekPosError!u64 {
103 return self.pos;
104 }
105
106 pub fn getWritten(self: Self) Buffer {
107 return self.buffer[0..self.pos];
108 }
109
110 pub fn reset(self: *Self) void {
111 self.pos = 0;
112 }
113 };
114}
115
116pub fn fixedBufferStream(buffer: var) FixedBufferStream(NonSentinelSpan(@TypeOf(buffer))) {
117 return .{ .buffer = mem.span(buffer), .pos = 0 };
118}
119
120fn NonSentinelSpan(comptime T: type) type {
121 var ptr_info = @typeInfo(mem.Span(T)).Pointer;
122 ptr_info.sentinel = null;
123 return @Type(std.builtin.TypeInfo{ .Pointer = ptr_info });
124}
125
126test "FixedBufferStream output" {
127 var buf: [255]u8 = undefined;
128 var fbs = fixedBufferStream(&buf);
129 const stream = fbs.outStream();
130
131 try stream.print("{}{}!", .{ "Hello", "World" });
132 testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
133}
134
135test "FixedBufferStream output 2" {
136 var buffer: [10]u8 = undefined;
137 var fbs = fixedBufferStream(&buffer);
138
139 try fbs.outStream().writeAll("Hello");
140 testing.expect(mem.eql(u8, fbs.getWritten(), "Hello"));
141
142 try fbs.outStream().writeAll("world");
143 testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
144
145 testing.expectError(error.NoSpaceLeft, fbs.outStream().writeAll("!"));
146 testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
147
148 fbs.reset();
149 testing.expect(fbs.getWritten().len == 0);
150
151 testing.expectError(error.NoSpaceLeft, fbs.outStream().writeAll("Hello world!"));
152 testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl"));
153}
154
155test "FixedBufferStream input" {
156 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
157 var fbs = fixedBufferStream(&bytes);
158
159 var dest: [4]u8 = undefined;
160
161 var read = try fbs.inStream().read(dest[0..4]);
162 testing.expect(read == 4);
163 testing.expect(mem.eql(u8, dest[0..4], bytes[0..4]));
164
165 read = try fbs.inStream().read(dest[0..4]);
166 testing.expect(read == 3);
167 testing.expect(mem.eql(u8, dest[0..3], bytes[4..7]));
168
169 read = try fbs.inStream().read(dest[0..4]);
170 testing.expect(read == 0);
171}
lib/std/io/in_stream.zig+36-53
...@@ -1,53 +1,37 @@...@@ -1,53 +1,37 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const builtin = @import("builtin");2const builtin = std.builtin;
3const root = @import("root");
4const math = std.math;3const math = std.math;
5const assert = std.debug.assert;4const assert = std.debug.assert;
6const mem = std.mem;5const mem = std.mem;
7const Buffer = std.Buffer;6const Buffer = std.Buffer;
8const testing = std.testing;7const testing = std.testing;
98
10pub const default_stack_size = 1 * 1024 * 1024;9pub fn InStream(
11pub const stack_size: usize = if (@hasDecl(root, "stack_size_std_io_InStream"))10 comptime Context: type,
12 root.stack_size_std_io_InStream11 comptime ReadError: type,
13else12 /// Returns the number of bytes read. It may be less than buffer.len.
14 default_stack_size;13 /// If the number of bytes read is 0, it means end of stream.
1514 /// End of stream is not an error condition.
16pub fn InStream(comptime ReadError: type) type {15 comptime readFn: fn (context: Context, buffer: []u8) ReadError!usize,
16) type {
17 return struct {17 return struct {
18 const Self = @This();
19 pub const Error = ReadError;18 pub const Error = ReadError;
20 pub const ReadFn = if (std.io.is_async)
21 async fn (self: *Self, buffer: []u8) Error!usize
22 else
23 fn (self: *Self, buffer: []u8) Error!usize;
2419
25 /// Returns the number of bytes read. It may be less than buffer.len.20 context: Context,
26 /// If the number of bytes read is 0, it means end of stream.21
27 /// End of stream is not an error condition.22 const Self = @This();
28 readFn: ReadFn,
2923
30 /// Returns the number of bytes read. It may be less than buffer.len.24 /// Returns the number of bytes read. It may be less than buffer.len.
31 /// If the number of bytes read is 0, it means end of stream.25 /// If the number of bytes read is 0, it means end of stream.
32 /// End of stream is not an error condition.26 /// End of stream is not an error condition.
33 pub fn read(self: *Self, buffer: []u8) Error!usize {27 pub fn read(self: Self, buffer: []u8) Error!usize {
34 if (std.io.is_async) {28 return readFn(self.context, buffer);
35 // Let's not be writing 0xaa in safe modes for upwards of 4 MiB for every stream read.
36 @setRuntimeSafety(false);
37 var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined;
38 return await @asyncCall(&stack_frame, {}, self.readFn, self, buffer);
39 } else {
40 return self.readFn(self, buffer);
41 }
42 }29 }
4330
44 /// Deprecated: use `readAll`.31 /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
45 pub const readFull = readAll;
46
47 /// Returns the number of bytes read. If the number read is smaller than buf.len, it
48 /// means the stream reached the end. Reaching the end of a stream is not an error32 /// means the stream reached the end. Reaching the end of a stream is not an error
49 /// condition.33 /// condition.
50 pub fn readAll(self: *Self, buffer: []u8) Error!usize {34 pub fn readAll(self: Self, buffer: []u8) Error!usize {
51 var index: usize = 0;35 var index: usize = 0;
52 while (index != buffer.len) {36 while (index != buffer.len) {
53 const amt = try self.read(buffer[index..]);37 const amt = try self.read(buffer[index..]);
...@@ -59,13 +43,13 @@ pub fn InStream(comptime ReadError: type) type {...@@ -59,13 +43,13 @@ pub fn InStream(comptime ReadError: type) type {
5943
60 /// Returns the number of bytes read. If the number read would be smaller than buf.len,44 /// Returns the number of bytes read. If the number read would be smaller than buf.len,
61 /// error.EndOfStream is returned instead.45 /// error.EndOfStream is returned instead.
62 pub fn readNoEof(self: *Self, buf: []u8) !void {46 pub fn readNoEof(self: Self, buf: []u8) !void {
63 const amt_read = try self.readAll(buf);47 const amt_read = try self.readAll(buf);
64 if (amt_read < buf.len) return error.EndOfStream;48 if (amt_read < buf.len) return error.EndOfStream;
65 }49 }
6650
67 /// Deprecated: use `readAllArrayList`.51 /// Deprecated: use `readAllArrayList`.
68 pub fn readAllBuffer(self: *Self, buffer: *Buffer, max_size: usize) !void {52 pub fn readAllBuffer(self: Self, buffer: *Buffer, max_size: usize) !void {
69 buffer.list.shrink(0);53 buffer.list.shrink(0);
70 try self.readAllArrayList(&buffer.list, max_size);54 try self.readAllArrayList(&buffer.list, max_size);
71 errdefer buffer.shrink(0);55 errdefer buffer.shrink(0);
...@@ -75,7 +59,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -75,7 +59,7 @@ pub fn InStream(comptime ReadError: type) type {
75 /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found.59 /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found.
76 /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned60 /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned
77 /// and the `std.ArrayList` has exactly `max_append_size` bytes appended.61 /// and the `std.ArrayList` has exactly `max_append_size` bytes appended.
78 pub fn readAllArrayList(self: *Self, array_list: *std.ArrayList(u8), max_append_size: usize) !void {62 pub fn readAllArrayList(self: Self, array_list: *std.ArrayList(u8), max_append_size: usize) !void {
79 try array_list.ensureCapacity(math.min(max_append_size, 4096));63 try array_list.ensureCapacity(math.min(max_append_size, 4096));
80 const original_len = array_list.len;64 const original_len = array_list.len;
81 var start_index: usize = original_len;65 var start_index: usize = original_len;
...@@ -104,7 +88,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -104,7 +88,7 @@ pub fn InStream(comptime ReadError: type) type {
104 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.88 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.
105 /// Caller owns returned memory.89 /// Caller owns returned memory.
106 /// If this function returns an error, the contents from the stream read so far are lost.90 /// If this function returns an error, the contents from the stream read so far are lost.
107 pub fn readAllAlloc(self: *Self, allocator: *mem.Allocator, max_size: usize) ![]u8 {91 pub fn readAllAlloc(self: Self, allocator: *mem.Allocator, max_size: usize) ![]u8 {
108 var array_list = std.ArrayList(u8).init(allocator);92 var array_list = std.ArrayList(u8).init(allocator);
109 defer array_list.deinit();93 defer array_list.deinit();
110 try self.readAllArrayList(&array_list, max_size);94 try self.readAllArrayList(&array_list, max_size);
...@@ -116,7 +100,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -116,7 +100,7 @@ pub fn InStream(comptime ReadError: type) type {
116 /// If the `std.ArrayList` length would exceed `max_size`, `error.StreamTooLong` is returned and the100 /// If the `std.ArrayList` length would exceed `max_size`, `error.StreamTooLong` is returned and the
117 /// `std.ArrayList` is populated with `max_size` bytes from the stream.101 /// `std.ArrayList` is populated with `max_size` bytes from the stream.
118 pub fn readUntilDelimiterArrayList(102 pub fn readUntilDelimiterArrayList(
119 self: *Self,103 self: Self,
120 array_list: *std.ArrayList(u8),104 array_list: *std.ArrayList(u8),
121 delimiter: u8,105 delimiter: u8,
122 max_size: usize,106 max_size: usize,
...@@ -142,7 +126,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -142,7 +126,7 @@ pub fn InStream(comptime ReadError: type) type {
142 /// Caller owns returned memory.126 /// Caller owns returned memory.
143 /// If this function returns an error, the contents from the stream read so far are lost.127 /// If this function returns an error, the contents from the stream read so far are lost.
144 pub fn readUntilDelimiterAlloc(128 pub fn readUntilDelimiterAlloc(
145 self: *Self,129 self: Self,
146 allocator: *mem.Allocator,130 allocator: *mem.Allocator,
147 delimiter: u8,131 delimiter: u8,
148 max_size: usize,132 max_size: usize,
...@@ -159,7 +143,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -159,7 +143,7 @@ pub fn InStream(comptime ReadError: type) type {
159 /// function is called again after that, returns null.143 /// function is called again after that, returns null.
160 /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The144 /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
161 /// delimiter byte is not included in the returned slice.145 /// delimiter byte is not included in the returned slice.
162 pub fn readUntilDelimiterOrEof(self: *Self, buf: []u8, delimiter: u8) !?[]u8 {146 pub fn readUntilDelimiterOrEof(self: Self, buf: []u8, delimiter: u8) !?[]u8 {
163 var index: usize = 0;147 var index: usize = 0;
164 while (true) {148 while (true) {
165 const byte = self.readByte() catch |err| switch (err) {149 const byte = self.readByte() catch |err| switch (err) {
...@@ -184,7 +168,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -184,7 +168,7 @@ pub fn InStream(comptime ReadError: type) type {
184 /// Reads from the stream until specified byte is found, discarding all data,168 /// Reads from the stream until specified byte is found, discarding all data,
185 /// including the delimiter.169 /// including the delimiter.
186 /// If end-of-stream is found, this function succeeds.170 /// If end-of-stream is found, this function succeeds.
187 pub fn skipUntilDelimiterOrEof(self: *Self, delimiter: u8) !void {171 pub fn skipUntilDelimiterOrEof(self: Self, delimiter: u8) !void {
188 while (true) {172 while (true) {
189 const byte = self.readByte() catch |err| switch (err) {173 const byte = self.readByte() catch |err| switch (err) {
190 error.EndOfStream => return,174 error.EndOfStream => return,
...@@ -195,7 +179,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -195,7 +179,7 @@ pub fn InStream(comptime ReadError: type) type {
195 }179 }
196180
197 /// Reads 1 byte from the stream or returns `error.EndOfStream`.181 /// Reads 1 byte from the stream or returns `error.EndOfStream`.
198 pub fn readByte(self: *Self) !u8 {182 pub fn readByte(self: Self) !u8 {
199 var result: [1]u8 = undefined;183 var result: [1]u8 = undefined;
200 const amt_read = try self.read(result[0..]);184 const amt_read = try self.read(result[0..]);
201 if (amt_read < 1) return error.EndOfStream;185 if (amt_read < 1) return error.EndOfStream;
...@@ -203,43 +187,43 @@ pub fn InStream(comptime ReadError: type) type {...@@ -203,43 +187,43 @@ pub fn InStream(comptime ReadError: type) type {
203 }187 }
204188
205 /// Same as `readByte` except the returned byte is signed.189 /// Same as `readByte` except the returned byte is signed.
206 pub fn readByteSigned(self: *Self) !i8 {190 pub fn readByteSigned(self: Self) !i8 {
207 return @bitCast(i8, try self.readByte());191 return @bitCast(i8, try self.readByte());
208 }192 }
209193
210 /// Reads a native-endian integer194 /// Reads a native-endian integer
211 pub fn readIntNative(self: *Self, comptime T: type) !T {195 pub fn readIntNative(self: Self, comptime T: type) !T {
212 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;196 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
213 try self.readNoEof(bytes[0..]);197 try self.readNoEof(bytes[0..]);
214 return mem.readIntNative(T, &bytes);198 return mem.readIntNative(T, &bytes);
215 }199 }
216200
217 /// Reads a foreign-endian integer201 /// Reads a foreign-endian integer
218 pub fn readIntForeign(self: *Self, comptime T: type) !T {202 pub fn readIntForeign(self: Self, comptime T: type) !T {
219 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;203 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
220 try self.readNoEof(bytes[0..]);204 try self.readNoEof(bytes[0..]);
221 return mem.readIntForeign(T, &bytes);205 return mem.readIntForeign(T, &bytes);
222 }206 }
223207
224 pub fn readIntLittle(self: *Self, comptime T: type) !T {208 pub fn readIntLittle(self: Self, comptime T: type) !T {
225 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;209 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
226 try self.readNoEof(bytes[0..]);210 try self.readNoEof(bytes[0..]);
227 return mem.readIntLittle(T, &bytes);211 return mem.readIntLittle(T, &bytes);
228 }212 }
229213
230 pub fn readIntBig(self: *Self, comptime T: type) !T {214 pub fn readIntBig(self: Self, comptime T: type) !T {
231 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;215 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
232 try self.readNoEof(bytes[0..]);216 try self.readNoEof(bytes[0..]);
233 return mem.readIntBig(T, &bytes);217 return mem.readIntBig(T, &bytes);
234 }218 }
235219
236 pub fn readInt(self: *Self, comptime T: type, endian: builtin.Endian) !T {220 pub fn readInt(self: Self, comptime T: type, endian: builtin.Endian) !T {
237 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;221 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
238 try self.readNoEof(bytes[0..]);222 try self.readNoEof(bytes[0..]);
239 return mem.readInt(T, &bytes, endian);223 return mem.readInt(T, &bytes, endian);
240 }224 }
241225
242 pub fn readVarInt(self: *Self, comptime ReturnType: type, endian: builtin.Endian, size: usize) !ReturnType {226 pub fn readVarInt(self: Self, comptime ReturnType: type, endian: builtin.Endian, size: usize) !ReturnType {
243 assert(size <= @sizeOf(ReturnType));227 assert(size <= @sizeOf(ReturnType));
244 var bytes_buf: [@sizeOf(ReturnType)]u8 = undefined;228 var bytes_buf: [@sizeOf(ReturnType)]u8 = undefined;
245 const bytes = bytes_buf[0..size];229 const bytes = bytes_buf[0..size];
...@@ -247,14 +231,14 @@ pub fn InStream(comptime ReadError: type) type {...@@ -247,14 +231,14 @@ pub fn InStream(comptime ReadError: type) type {
247 return mem.readVarInt(ReturnType, bytes, endian);231 return mem.readVarInt(ReturnType, bytes, endian);
248 }232 }
249233
250 pub fn skipBytes(self: *Self, num_bytes: u64) !void {234 pub fn skipBytes(self: Self, num_bytes: u64) !void {
251 var i: u64 = 0;235 var i: u64 = 0;
252 while (i < num_bytes) : (i += 1) {236 while (i < num_bytes) : (i += 1) {
253 _ = try self.readByte();237 _ = try self.readByte();
254 }238 }
255 }239 }
256240
257 pub fn readStruct(self: *Self, comptime T: type) !T {241 pub fn readStruct(self: Self, comptime T: type) !T {
258 // Only extern and packed structs have defined in-memory layout.242 // Only extern and packed structs have defined in-memory layout.
259 comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);243 comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);
260 var res: [1]T = undefined;244 var res: [1]T = undefined;
...@@ -265,7 +249,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -265,7 +249,7 @@ pub fn InStream(comptime ReadError: type) type {
265 /// Reads an integer with the same size as the given enum's tag type. If the integer matches249 /// Reads an integer with the same size as the given enum's tag type. If the integer matches
266 /// an enum tag, casts the integer to the enum tag and returns it. Otherwise, returns an error.250 /// an enum tag, casts the integer to the enum tag and returns it. Otherwise, returns an error.
267 /// TODO optimization taking advantage of most fields being in order251 /// TODO optimization taking advantage of most fields being in order
268 pub fn readEnum(self: *Self, comptime Enum: type, endian: builtin.Endian) !Enum {252 pub fn readEnum(self: Self, comptime Enum: type, endian: builtin.Endian) !Enum {
269 const E = error{253 const E = error{
270 /// An integer was read, but it did not match any of the tags in the supplied enum.254 /// An integer was read, but it did not match any of the tags in the supplied enum.
271 InvalidValue,255 InvalidValue,
...@@ -286,8 +270,7 @@ pub fn InStream(comptime ReadError: type) type {...@@ -286,8 +270,7 @@ pub fn InStream(comptime ReadError: type) type {
286270
287test "InStream" {271test "InStream" {
288 var buf = "a\x02".*;272 var buf = "a\x02".*;
289 var slice_stream = std.io.SliceInStream.init(&buf);273 const in_stream = std.io.fixedBufferStream(&buf).inStream();
290 const in_stream = &slice_stream.stream;
291 testing.expect((try in_stream.readByte()) == 'a');274 testing.expect((try in_stream.readByte()) == 'a');
292 testing.expect((try in_stream.readEnum(enum(u8) {275 testing.expect((try in_stream.readEnum(enum(u8) {
293 a = 0,276 a = 0,
lib/std/io/out_stream.zig+33-42
...@@ -1,94 +1,85 @@...@@ -1,94 +1,85 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const builtin = @import("builtin");2const builtin = std.builtin;
3const root = @import("root");
4const mem = std.mem;3const mem = std.mem;
54
6pub const default_stack_size = 1 * 1024 * 1024;5pub fn OutStream(
7pub const stack_size: usize = if (@hasDecl(root, "stack_size_std_io_OutStream"))6 comptime Context: type,
8 root.stack_size_std_io_OutStream7 comptime WriteError: type,
9else8 comptime writeFn: fn (context: Context, bytes: []const u8) WriteError!usize,
10 default_stack_size;9) type {
11
12pub fn OutStream(comptime WriteError: type) type {
13 return struct {10 return struct {
11 context: Context,
12
14 const Self = @This();13 const Self = @This();
15 pub const Error = WriteError;14 pub const Error = WriteError;
16 pub const WriteFn = if (std.io.is_async)
17 async fn (self: *Self, bytes: []const u8) Error!usize
18 else
19 fn (self: *Self, bytes: []const u8) Error!usize;
2015
21 writeFn: WriteFn,16 pub fn write(self: Self, bytes: []const u8) Error!usize {
2217 return writeFn(self.context, bytes);
23 pub fn writeOnce(self: *Self, bytes: []const u8) Error!usize {
24 if (std.io.is_async) {
25 // Let's not be writing 0xaa in safe modes for upwards of 4 MiB for every stream write.
26 @setRuntimeSafety(false);
27 var stack_frame: [stack_size]u8 align(std.Target.stack_align) = undefined;
28 return await @asyncCall(&stack_frame, {}, self.writeFn, self, bytes);
29 } else {
30 return self.writeFn(self, bytes);
31 }
32 }18 }
3319
34 pub fn write(self: *Self, bytes: []const u8) Error!void {20 pub fn writeAll(self: Self, bytes: []const u8) Error!void {
35 var index: usize = 0;21 var index: usize = 0;
36 while (index != bytes.len) {22 while (index != bytes.len) {
37 index += try self.writeOnce(bytes[index..]);23 index += try self.write(bytes[index..]);
38 }24 }
39 }25 }
4026
41 pub fn print(self: *Self, comptime format: []const u8, args: var) Error!void {27 pub fn print(self: Self, comptime format: []const u8, args: var) Error!void {
42 return std.fmt.format(self, Error, write, format, args);28 return std.fmt.format(self, format, args);
43 }29 }
4430
45 pub fn writeByte(self: *Self, byte: u8) Error!void {31 pub fn writeByte(self: Self, byte: u8) Error!void {
46 const array = [1]u8{byte};32 const array = [1]u8{byte};
47 return self.write(&array);33 return self.writeAll(&array);
48 }34 }
4935
50 pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) Error!void {36 pub fn writeByteNTimes(self: Self, byte: u8, n: usize) Error!void {
51 var bytes: [256]u8 = undefined;37 var bytes: [256]u8 = undefined;
52 mem.set(u8, bytes[0..], byte);38 mem.set(u8, bytes[0..], byte);
5339
54 var remaining: usize = n;40 var remaining: usize = n;
55 while (remaining > 0) {41 while (remaining > 0) {
56 const to_write = std.math.min(remaining, bytes.len);42 const to_write = std.math.min(remaining, bytes.len);
57 try self.write(bytes[0..to_write]);43 try self.writeAll(bytes[0..to_write]);
58 remaining -= to_write;44 remaining -= to_write;
59 }45 }
60 }46 }
6147
62 /// Write a native-endian integer.48 /// Write a native-endian integer.
63 pub fn writeIntNative(self: *Self, comptime T: type, value: T) Error!void {49 /// TODO audit non-power-of-two int sizes
50 pub fn writeIntNative(self: Self, comptime T: type, value: T) Error!void {
64 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;51 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
65 mem.writeIntNative(T, &bytes, value);52 mem.writeIntNative(T, &bytes, value);
66 return self.write(&bytes);53 return self.writeAll(&bytes);
67 }54 }
6855
69 /// Write a foreign-endian integer.56 /// Write a foreign-endian integer.
70 pub fn writeIntForeign(self: *Self, comptime T: type, value: T) Error!void {57 /// TODO audit non-power-of-two int sizes
58 pub fn writeIntForeign(self: Self, comptime T: type, value: T) Error!void {
71 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;59 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
72 mem.writeIntForeign(T, &bytes, value);60 mem.writeIntForeign(T, &bytes, value);
73 return self.write(&bytes);61 return self.writeAll(&bytes);
74 }62 }
7563
76 pub fn writeIntLittle(self: *Self, comptime T: type, value: T) Error!void {64 /// TODO audit non-power-of-two int sizes
65 pub fn writeIntLittle(self: Self, comptime T: type, value: T) Error!void {
77 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;66 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
78 mem.writeIntLittle(T, &bytes, value);67 mem.writeIntLittle(T, &bytes, value);
79 return self.write(&bytes);68 return self.writeAll(&bytes);
80 }69 }
8170
82 pub fn writeIntBig(self: *Self, comptime T: type, value: T) Error!void {71 /// TODO audit non-power-of-two int sizes
72 pub fn writeIntBig(self: Self, comptime T: type, value: T) Error!void {
83 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;73 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
84 mem.writeIntBig(T, &bytes, value);74 mem.writeIntBig(T, &bytes, value);
85 return self.write(&bytes);75 return self.writeAll(&bytes);
86 }76 }
8777
88 pub fn writeInt(self: *Self, comptime T: type, value: T, endian: builtin.Endian) Error!void {78 /// TODO audit non-power-of-two int sizes
79 pub fn writeInt(self: Self, comptime T: type, value: T, endian: builtin.Endian) Error!void {
89 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;80 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
90 mem.writeInt(T, &bytes, value, endian);81 mem.writeInt(T, &bytes, value, endian);
91 return self.write(&bytes);82 return self.writeAll(&bytes);
92 }83 }
93 };84 };
94}85}
lib/std/io/peek_stream.zig created+112
...@@ -0,0 +1,112 @@
1const std = @import("../std.zig");
2const io = std.io;
3const mem = std.mem;
4const testing = std.testing;
5
6/// Creates a stream which supports 'un-reading' data, so that it can be read again.
7/// This makes look-ahead style parsing much easier.
8/// TODO merge this with `std.io.BufferedInStream`: https://github.com/ziglang/zig/issues/4501
9pub fn PeekStream(
10 comptime buffer_type: std.fifo.LinearFifoBufferType,
11 comptime InStreamType: type,
12) type {
13 return struct {
14 unbuffered_in_stream: InStreamType,
15 fifo: FifoType,
16
17 pub const Error = InStreamType.Error;
18 pub const InStream = io.InStream(*Self, Error, read);
19
20 const Self = @This();
21 const FifoType = std.fifo.LinearFifo(u8, buffer_type);
22
23 pub usingnamespace switch (buffer_type) {
24 .Static => struct {
25 pub fn init(base: InStreamType) Self {
26 return .{
27 .base = base,
28 .fifo = FifoType.init(),
29 };
30 }
31 },
32 .Slice => struct {
33 pub fn init(base: InStreamType, buf: []u8) Self {
34 return .{
35 .base = base,
36 .fifo = FifoType.init(buf),
37 };
38 }
39 },
40 .Dynamic => struct {
41 pub fn init(base: InStreamType, allocator: *mem.Allocator) Self {
42 return .{
43 .base = base,
44 .fifo = FifoType.init(allocator),
45 };
46 }
47 },
48 };
49
50 pub fn putBackByte(self: *Self, byte: u8) !void {
51 try self.putBack(&[_]u8{byte});
52 }
53
54 pub fn putBack(self: *Self, bytes: []const u8) !void {
55 try self.fifo.unget(bytes);
56 }
57
58 pub fn read(self: *Self, dest: []u8) Error!usize {
59 // copy over anything putBack()'d
60 var dest_index = self.fifo.read(dest);
61 if (dest_index == dest.len) return dest_index;
62
63 // ask the backing stream for more
64 dest_index += try self.base.read(dest[dest_index..]);
65 return dest_index;
66 }
67
68 pub fn inStream(self: *Self) InStream {
69 return .{ .context = self };
70 }
71 };
72}
73
74pub fn peekStream(
75 comptime lookahead: comptime_int,
76 underlying_stream: var,
77) PeekStream(.{ .Static = lookahead }, @TypeOf(underlying_stream)) {
78 return PeekStream(.{ .Static = lookahead }, @TypeOf(underlying_stream)).init(underlying_stream);
79}
80
81test "PeekStream" {
82 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 };
83 var fbs = io.fixedBufferStream(&bytes);
84 var ps = peekStream(2, fbs.inStream());
85
86 var dest: [4]u8 = undefined;
87
88 try ps.putBackByte(9);
89 try ps.putBackByte(10);
90
91 var read = try ps.inStream().read(dest[0..4]);
92 testing.expect(read == 4);
93 testing.expect(dest[0] == 10);
94 testing.expect(dest[1] == 9);
95 testing.expect(mem.eql(u8, dest[2..4], bytes[0..2]));
96
97 read = try ps.inStream().read(dest[0..4]);
98 testing.expect(read == 4);
99 testing.expect(mem.eql(u8, dest[0..4], bytes[2..6]));
100
101 read = try ps.inStream().read(dest[0..4]);
102 testing.expect(read == 2);
103 testing.expect(mem.eql(u8, dest[0..2], bytes[6..8]));
104
105 try ps.putBackByte(11);
106 try ps.putBackByte(12);
107
108 read = try ps.inStream().read(dest[0..4]);
109 testing.expect(read == 2);
110 testing.expect(dest[0] == 12);
111 testing.expect(dest[1] == 11);
112}
lib/std/io/seekable_stream.zig+19-86
...@@ -1,103 +1,36 @@...@@ -1,103 +1,36 @@
1const std = @import("../std.zig");1const std = @import("../std.zig");
2const InStream = std.io.InStream;2const InStream = std.io.InStream;
33
4pub fn SeekableStream(comptime SeekErrorType: type, comptime GetSeekPosErrorType: type) type {4pub fn SeekableStream(
5 comptime Context: type,
6 comptime SeekErrorType: type,
7 comptime GetSeekPosErrorType: type,
8 comptime seekToFn: fn (context: Context, pos: u64) SeekErrorType!void,
9 comptime seekByFn: fn (context: Context, pos: i64) SeekErrorType!void,
10 comptime getPosFn: fn (context: Context) GetSeekPosErrorType!u64,
11 comptime getEndPosFn: fn (context: Context) GetSeekPosErrorType!u64,
12) type {
5 return struct {13 return struct {
14 context: Context,
15
6 const Self = @This();16 const Self = @This();
7 pub const SeekError = SeekErrorType;17 pub const SeekError = SeekErrorType;
8 pub const GetSeekPosError = GetSeekPosErrorType;18 pub const GetSeekPosError = GetSeekPosErrorType;
919
10 seekToFn: fn (self: *Self, pos: u64) SeekError!void,20 pub fn seekTo(self: Self, pos: u64) SeekError!void {
11 seekByFn: fn (self: *Self, pos: i64) SeekError!void,21 return seekToFn(self.context, pos);
12
13 getPosFn: fn (self: *Self) GetSeekPosError!u64,
14 getEndPosFn: fn (self: *Self) GetSeekPosError!u64,
15
16 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
17 return self.seekToFn(self, pos);
18 }22 }
1923
20 pub fn seekBy(self: *Self, amt: i64) SeekError!void {24 pub fn seekBy(self: Self, amt: i64) SeekError!void {
21 return self.seekByFn(self, amt);25 return seekByFn(self.context, amt);
22 }26 }
2327
24 pub fn getEndPos(self: *Self) GetSeekPosError!u64 {28 pub fn getEndPos(self: Self) GetSeekPosError!u64 {
25 return self.getEndPosFn(self);29 return getEndPosFn(self.context);
26 }30 }
2731
28 pub fn getPos(self: *Self) GetSeekPosError!u64 {32 pub fn getPos(self: Self) GetSeekPosError!u64 {
29 return self.getPosFn(self);33 return getPosFn(self.context);
30 }34 }
31 };35 };
32}36}
33
34pub const SliceSeekableInStream = struct {
35 const Self = @This();
36 pub const Error = error{};
37 pub const SeekError = error{EndOfStream};
38 pub const GetSeekPosError = error{};
39 pub const Stream = InStream(Error);
40 pub const SeekableInStream = SeekableStream(SeekError, GetSeekPosError);
41
42 stream: Stream,
43 seekable_stream: SeekableInStream,
44
45 pos: usize,
46 slice: []const u8,
47
48 pub fn init(slice: []const u8) Self {
49 return Self{
50 .slice = slice,
51 .pos = 0,
52 .stream = Stream{ .readFn = readFn },
53 .seekable_stream = SeekableInStream{
54 .seekToFn = seekToFn,
55 .seekByFn = seekByFn,
56 .getEndPosFn = getEndPosFn,
57 .getPosFn = getPosFn,
58 },
59 };
60 }
61
62 fn readFn(in_stream: *Stream, dest: []u8) Error!usize {
63 const self = @fieldParentPtr(Self, "stream", in_stream);
64 const size = std.math.min(dest.len, self.slice.len - self.pos);
65 const end = self.pos + size;
66
67 std.mem.copy(u8, dest[0..size], self.slice[self.pos..end]);
68 self.pos = end;
69
70 return size;
71 }
72
73 fn seekToFn(in_stream: *SeekableInStream, pos: u64) SeekError!void {
74 const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
75 const usize_pos = @intCast(usize, pos);
76 if (usize_pos > self.slice.len) return error.EndOfStream;
77 self.pos = usize_pos;
78 }
79
80 fn seekByFn(in_stream: *SeekableInStream, amt: i64) SeekError!void {
81 const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
82
83 if (amt < 0) {
84 const abs_amt = @intCast(usize, -amt);
85 if (abs_amt > self.pos) return error.EndOfStream;
86 self.pos -= abs_amt;
87 } else {
88 const usize_amt = @intCast(usize, amt);
89 if (self.pos + usize_amt > self.slice.len) return error.EndOfStream;
90 self.pos += usize_amt;
91 }
92 }
93
94 fn getEndPosFn(in_stream: *SeekableInStream) GetSeekPosError!u64 {
95 const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
96 return @intCast(u64, self.slice.len);
97 }
98
99 fn getPosFn(in_stream: *SeekableInStream) GetSeekPosError!u64 {
100 const self = @fieldParentPtr(Self, "seekable_stream", in_stream);
101 return @intCast(u64, self.pos);
102 }
103};
lib/std/io/serialization.zig created+602
...@@ -0,0 +1,602 @@
1const std = @import("../std.zig");
2const builtin = std.builtin;
3const io = std.io;
4
5pub const Packing = enum {
6 /// Pack data to byte alignment
7 Byte,
8
9 /// Pack data to bit alignment
10 Bit,
11};
12
13/// Creates a deserializer that deserializes types from any stream.
14/// If `is_packed` is true, the data stream is treated as bit-packed,
15/// otherwise data is expected to be packed to the smallest byte.
16/// Types may implement a custom deserialization routine with a
17/// function named `deserialize` in the form of:
18/// pub fn deserialize(self: *Self, deserializer: var) !void
19/// which will be called when the deserializer is used to deserialize
20/// that type. It will pass a pointer to the type instance to deserialize
21/// into and a pointer to the deserializer struct.
22pub fn Deserializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime InStreamType: type) type {
23 return struct {
24 in_stream: if (packing == .Bit) io.BitInStream(endian, InStreamType) else InStreamType,
25
26 const Self = @This();
27
28 pub fn init(in_stream: InStreamType) Self {
29 return Self{
30 .in_stream = switch (packing) {
31 .Bit => io.bitInStream(endian, in_stream),
32 .Byte => in_stream,
33 },
34 };
35 }
36
37 pub fn alignToByte(self: *Self) void {
38 if (packing == .Byte) return;
39 self.in_stream.alignToByte();
40 }
41
42 //@BUG: inferred error issue. See: #1386
43 fn deserializeInt(self: *Self, comptime T: type) (InStreamType.Error || error{EndOfStream})!T {
44 comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
45
46 const u8_bit_count = 8;
47 const t_bit_count = comptime meta.bitCount(T);
48
49 const U = std.meta.IntType(false, t_bit_count);
50 const Log2U = math.Log2Int(U);
51 const int_size = (U.bit_count + 7) / 8;
52
53 if (packing == .Bit) {
54 const result = try self.in_stream.readBitsNoEof(U, t_bit_count);
55 return @bitCast(T, result);
56 }
57
58 var buffer: [int_size]u8 = undefined;
59 const read_size = try self.in_stream.read(buffer[0..]);
60 if (read_size < int_size) return error.EndOfStream;
61
62 if (int_size == 1) {
63 if (t_bit_count == 8) return @bitCast(T, buffer[0]);
64 const PossiblySignedByte = std.meta.IntType(T.is_signed, 8);
65 return @truncate(T, @bitCast(PossiblySignedByte, buffer[0]));
66 }
67
68 var result = @as(U, 0);
69 for (buffer) |byte, i| {
70 switch (endian) {
71 .Big => {
72 result = (result << u8_bit_count) | byte;
73 },
74 .Little => {
75 result |= @as(U, byte) << @intCast(Log2U, u8_bit_count * i);
76 },
77 }
78 }
79
80 return @bitCast(T, result);
81 }
82
83 /// Deserializes and returns data of the specified type from the stream
84 pub fn deserialize(self: *Self, comptime T: type) !T {
85 var value: T = undefined;
86 try self.deserializeInto(&value);
87 return value;
88 }
89
90 /// Deserializes data into the type pointed to by `ptr`
91 pub fn deserializeInto(self: *Self, ptr: var) !void {
92 const T = @TypeOf(ptr);
93 comptime assert(trait.is(.Pointer)(T));
94
95 if (comptime trait.isSlice(T) or comptime trait.isPtrTo(.Array)(T)) {
96 for (ptr) |*v|
97 try self.deserializeInto(v);
98 return;
99 }
100
101 comptime assert(trait.isSingleItemPtr(T));
102
103 const C = comptime meta.Child(T);
104 const child_type_id = @typeInfo(C);
105
106 //custom deserializer: fn(self: *Self, deserializer: var) !void
107 if (comptime trait.hasFn("deserialize")(C)) return C.deserialize(ptr, self);
108
109 if (comptime trait.isPacked(C) and packing != .Bit) {
110 var packed_deserializer = deserializer(endian, .Bit, self.in_stream);
111 return packed_deserializer.deserializeInto(ptr);
112 }
113
114 switch (child_type_id) {
115 .Void => return,
116 .Bool => ptr.* = (try self.deserializeInt(u1)) > 0,
117 .Float, .Int => ptr.* = try self.deserializeInt(C),
118 .Struct => {
119 const info = @typeInfo(C).Struct;
120
121 inline for (info.fields) |*field_info| {
122 const name = field_info.name;
123 const FieldType = field_info.field_type;
124
125 if (FieldType == void or FieldType == u0) continue;
126
127 //it doesn't make any sense to read pointers
128 if (comptime trait.is(.Pointer)(FieldType)) {
129 @compileError("Will not " ++ "read field " ++ name ++ " of struct " ++
130 @typeName(C) ++ " because it " ++ "is of pointer-type " ++
131 @typeName(FieldType) ++ ".");
132 }
133
134 try self.deserializeInto(&@field(ptr, name));
135 }
136 },
137 .Union => {
138 const info = @typeInfo(C).Union;
139 if (info.tag_type) |TagType| {
140 //we avoid duplicate iteration over the enum tags
141 // by getting the int directly and casting it without
142 // safety. If it is bad, it will be caught anyway.
143 const TagInt = @TagType(TagType);
144 const tag = try self.deserializeInt(TagInt);
145
146 inline for (info.fields) |field_info| {
147 if (field_info.enum_field.?.value == tag) {
148 const name = field_info.name;
149 const FieldType = field_info.field_type;
150 ptr.* = @unionInit(C, name, undefined);
151 try self.deserializeInto(&@field(ptr, name));
152 return;
153 }
154 }
155 //This is reachable if the enum data is bad
156 return error.InvalidEnumTag;
157 }
158 @compileError("Cannot meaningfully deserialize " ++ @typeName(C) ++
159 " because it is an untagged union. Use a custom deserialize().");
160 },
161 .Optional => {
162 const OC = comptime meta.Child(C);
163 const exists = (try self.deserializeInt(u1)) > 0;
164 if (!exists) {
165 ptr.* = null;
166 return;
167 }
168
169 ptr.* = @as(OC, undefined); //make it non-null so the following .? is guaranteed safe
170 const val_ptr = &ptr.*.?;
171 try self.deserializeInto(val_ptr);
172 },
173 .Enum => {
174 var value = try self.deserializeInt(@TagType(C));
175 ptr.* = try meta.intToEnum(C, value);
176 },
177 else => {
178 @compileError("Cannot deserialize " ++ @tagName(child_type_id) ++ " types (unimplemented).");
179 },
180 }
181 }
182 };
183}
184
185pub fn deserializer(
186 comptime endian: builtin.Endian,
187 comptime packing: Packing,
188 in_stream: var,
189) Deserializer(endian, packing, @TypeOf(in_stream)) {
190 return Deserializer(endian, packing, @TypeOf(in_stream)).init(in_stream);
191}
192
193/// Creates a serializer that serializes types to any stream.
194/// If `is_packed` is true, the data will be bit-packed into the stream.
195/// Note that the you must call `serializer.flush()` when you are done
196/// writing bit-packed data in order ensure any unwritten bits are committed.
197/// If `is_packed` is false, data is packed to the smallest byte. In the case
198/// of packed structs, the struct will written bit-packed and with the specified
199/// endianess, after which data will resume being written at the next byte boundary.
200/// Types may implement a custom serialization routine with a
201/// function named `serialize` in the form of:
202/// pub fn serialize(self: Self, serializer: var) !void
203/// which will be called when the serializer is used to serialize that type. It will
204/// pass a const pointer to the type instance to be serialized and a pointer
205/// to the serializer struct.
206pub fn Serializer(comptime endian: builtin.Endian, comptime packing: Packing, comptime OutStreamType: type) type {
207 return struct {
208 out_stream: if (packing == .Bit) BitOutStream(endian, OutStreamType) else OutStreamType,
209
210 const Self = @This();
211 pub const Error = OutStreamType.Error;
212
213 pub fn init(out_stream: OutStreamType) Self {
214 return Self{
215 .out_stream = switch (packing) {
216 .Bit => io.bitOutStream(endian, out_stream),
217 .Byte => out_stream,
218 },
219 };
220 }
221
222 /// Flushes any unwritten bits to the stream
223 pub fn flush(self: *Self) Error!void {
224 if (packing == .Bit) return self.out_stream.flushBits();
225 }
226
227 fn serializeInt(self: *Self, value: var) Error!void {
228 const T = @TypeOf(value);
229 comptime assert(trait.is(.Int)(T) or trait.is(.Float)(T));
230
231 const t_bit_count = comptime meta.bitCount(T);
232 const u8_bit_count = comptime meta.bitCount(u8);
233
234 const U = std.meta.IntType(false, t_bit_count);
235 const Log2U = math.Log2Int(U);
236 const int_size = (U.bit_count + 7) / 8;
237
238 const u_value = @bitCast(U, value);
239
240 if (packing == .Bit) return self.out_stream.writeBits(u_value, t_bit_count);
241
242 var buffer: [int_size]u8 = undefined;
243 if (int_size == 1) buffer[0] = u_value;
244
245 for (buffer) |*byte, i| {
246 const idx = switch (endian) {
247 .Big => int_size - i - 1,
248 .Little => i,
249 };
250 const shift = @intCast(Log2U, idx * u8_bit_count);
251 const v = u_value >> shift;
252 byte.* = if (t_bit_count < u8_bit_count) v else @truncate(u8, v);
253 }
254
255 try self.out_stream.write(&buffer);
256 }
257
258 /// Serializes the passed value into the stream
259 pub fn serialize(self: *Self, value: var) Error!void {
260 const T = comptime @TypeOf(value);
261
262 if (comptime trait.isIndexable(T)) {
263 for (value) |v|
264 try self.serialize(v);
265 return;
266 }
267
268 //custom serializer: fn(self: Self, serializer: var) !void
269 if (comptime trait.hasFn("serialize")(T)) return T.serialize(value, self);
270
271 if (comptime trait.isPacked(T) and packing != .Bit) {
272 var packed_serializer = Serializer(endian, .Bit, Error).init(self.out_stream);
273 try packed_serializer.serialize(value);
274 try packed_serializer.flush();
275 return;
276 }
277
278 switch (@typeInfo(T)) {
279 .Void => return,
280 .Bool => try self.serializeInt(@as(u1, @boolToInt(value))),
281 .Float, .Int => try self.serializeInt(value),
282 .Struct => {
283 const info = @typeInfo(T);
284
285 inline for (info.Struct.fields) |*field_info| {
286 const name = field_info.name;
287 const FieldType = field_info.field_type;
288
289 if (FieldType == void or FieldType == u0) continue;
290
291 //It doesn't make sense to write pointers
292 if (comptime trait.is(.Pointer)(FieldType)) {
293 @compileError("Will not " ++ "serialize field " ++ name ++
294 " of struct " ++ @typeName(T) ++ " because it " ++
295 "is of pointer-type " ++ @typeName(FieldType) ++ ".");
296 }
297 try self.serialize(@field(value, name));
298 }
299 },
300 .Union => {
301 const info = @typeInfo(T).Union;
302 if (info.tag_type) |TagType| {
303 const active_tag = meta.activeTag(value);
304 try self.serialize(active_tag);
305 //This inline loop is necessary because active_tag is a runtime
306 // value, but @field requires a comptime value. Our alternative
307 // is to check each field for a match
308 inline for (info.fields) |field_info| {
309 if (field_info.enum_field.?.value == @enumToInt(active_tag)) {
310 const name = field_info.name;
311 const FieldType = field_info.field_type;
312 try self.serialize(@field(value, name));
313 return;
314 }
315 }
316 unreachable;
317 }
318 @compileError("Cannot meaningfully serialize " ++ @typeName(T) ++
319 " because it is an untagged union. Use a custom serialize().");
320 },
321 .Optional => {
322 if (value == null) {
323 try self.serializeInt(@as(u1, @boolToInt(false)));
324 return;
325 }
326 try self.serializeInt(@as(u1, @boolToInt(true)));
327
328 const OC = comptime meta.Child(T);
329 const val_ptr = &value.?;
330 try self.serialize(val_ptr.*);
331 },
332 .Enum => {
333 try self.serializeInt(@enumToInt(value));
334 },
335 else => @compileError("Cannot serialize " ++ @tagName(@typeInfo(T)) ++ " types (unimplemented)."),
336 }
337 }
338 };
339}
340
341pub fn serializer(
342 comptime endian: builtin.Endian,
343 comptime packing: Packing,
344 out_stream: var,
345) Serializer(endian, packing, @TypeOf(out_stream)) {
346 return Serializer(endian, packing, @TypeOf(out_stream)).init(out_stream);
347}
348
349fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
350 @setEvalBranchQuota(1500);
351 //@NOTE: if this test is taking too long, reduce the maximum tested bitsize
352 const max_test_bitsize = 128;
353
354 const total_bytes = comptime blk: {
355 var bytes = 0;
356 comptime var i = 0;
357 while (i <= max_test_bitsize) : (i += 1) bytes += (i / 8) + @boolToInt(i % 8 > 0);
358 break :blk bytes * 2;
359 };
360
361 var data_mem: [total_bytes]u8 = undefined;
362 var out = io.fixedBufferStream(&data_mem);
363 var serializer = serializer(endian, packing, out.outStream());
364
365 var in = io.fixedBufferStream(&data_mem);
366 var deserializer = Deserializer(endian, packing, in.inStream());
367
368 comptime var i = 0;
369 inline while (i <= max_test_bitsize) : (i += 1) {
370 const U = std.meta.IntType(false, i);
371 const S = std.meta.IntType(true, i);
372 try serializer.serializeInt(@as(U, i));
373 if (i != 0) try serializer.serializeInt(@as(S, -1)) else try serializer.serialize(@as(S, 0));
374 }
375 try serializer.flush();
376
377 i = 0;
378 inline while (i <= max_test_bitsize) : (i += 1) {
379 const U = std.meta.IntType(false, i);
380 const S = std.meta.IntType(true, i);
381 const x = try deserializer.deserializeInt(U);
382 const y = try deserializer.deserializeInt(S);
383 expect(x == @as(U, i));
384 if (i != 0) expect(y == @as(S, -1)) else expect(y == 0);
385 }
386
387 const u8_bit_count = comptime meta.bitCount(u8);
388 //0 + 1 + 2 + ... n = (n * (n + 1)) / 2
389 //and we have each for unsigned and signed, so * 2
390 const total_bits = (max_test_bitsize * (max_test_bitsize + 1));
391 const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);
392 const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;
393
394 expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);
395
396 //Verify that empty error set works with serializer.
397 //deserializer is covered by FixedBufferStream
398 var null_serializer = io.serializer(endian, packing, std.io.null_out_stream);
399 try null_serializer.serialize(data_mem[0..]);
400 try null_serializer.flush();
401}
402
403test "Serializer/Deserializer Int" {
404 try testIntSerializerDeserializer(.Big, .Byte);
405 try testIntSerializerDeserializer(.Little, .Byte);
406 // TODO these tests are disabled due to tripping an LLVM assertion
407 // https://github.com/ziglang/zig/issues/2019
408 //try testIntSerializerDeserializer(builtin.Endian.Big, true);
409 //try testIntSerializerDeserializer(builtin.Endian.Little, true);
410}
411
412fn testIntSerializerDeserializerInfNaN(
413 comptime endian: builtin.Endian,
414 comptime packing: io.Packing,
415) !void {
416 const mem_size = (16 * 2 + 32 * 2 + 64 * 2 + 128 * 2) / comptime meta.bitCount(u8);
417 var data_mem: [mem_size]u8 = undefined;
418
419 var out = io.fixedBufferStream(&data_mem);
420 var serializer = serializer(endian, packing, out.outStream());
421
422 var in = io.fixedBufferStream(&data_mem);
423 var deserializer = deserializer(endian, packing, in.inStream());
424
425 //@TODO: isInf/isNan not currently implemented for f128.
426 try serializer.serialize(std.math.nan(f16));
427 try serializer.serialize(std.math.inf(f16));
428 try serializer.serialize(std.math.nan(f32));
429 try serializer.serialize(std.math.inf(f32));
430 try serializer.serialize(std.math.nan(f64));
431 try serializer.serialize(std.math.inf(f64));
432 //try serializer.serialize(std.math.nan(f128));
433 //try serializer.serialize(std.math.inf(f128));
434 const nan_check_f16 = try deserializer.deserialize(f16);
435 const inf_check_f16 = try deserializer.deserialize(f16);
436 const nan_check_f32 = try deserializer.deserialize(f32);
437 deserializer.alignToByte();
438 const inf_check_f32 = try deserializer.deserialize(f32);
439 const nan_check_f64 = try deserializer.deserialize(f64);
440 const inf_check_f64 = try deserializer.deserialize(f64);
441 //const nan_check_f128 = try deserializer.deserialize(f128);
442 //const inf_check_f128 = try deserializer.deserialize(f128);
443 expect(std.math.isNan(nan_check_f16));
444 expect(std.math.isInf(inf_check_f16));
445 expect(std.math.isNan(nan_check_f32));
446 expect(std.math.isInf(inf_check_f32));
447 expect(std.math.isNan(nan_check_f64));
448 expect(std.math.isInf(inf_check_f64));
449 //expect(std.math.isNan(nan_check_f128));
450 //expect(std.math.isInf(inf_check_f128));
451}
452
453test "Serializer/Deserializer Int: Inf/NaN" {
454 try testIntSerializerDeserializerInfNaN(.Big, .Byte);
455 try testIntSerializerDeserializerInfNaN(.Little, .Byte);
456 try testIntSerializerDeserializerInfNaN(.Big, .Bit);
457 try testIntSerializerDeserializerInfNaN(.Little, .Bit);
458}
459
460fn testAlternateSerializer(self: var, serializer: var) !void {
461 try serializer.serialize(self.f_f16);
462}
463
464fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
465 const ColorType = enum(u4) {
466 RGB8 = 1,
467 RA16 = 2,
468 R32 = 3,
469 };
470
471 const TagAlign = union(enum(u32)) {
472 A: u8,
473 B: u8,
474 C: u8,
475 };
476
477 const Color = union(ColorType) {
478 RGB8: struct {
479 r: u8,
480 g: u8,
481 b: u8,
482 a: u8,
483 },
484 RA16: struct {
485 r: u16,
486 a: u16,
487 },
488 R32: u32,
489 };
490
491 const PackedStruct = packed struct {
492 f_i3: i3,
493 f_u2: u2,
494 };
495
496 //to test custom serialization
497 const Custom = struct {
498 f_f16: f16,
499 f_unused_u32: u32,
500
501 pub fn deserialize(self: *@This(), deserializer: var) !void {
502 try deserializer.deserializeInto(&self.f_f16);
503 self.f_unused_u32 = 47;
504 }
505
506 pub const serialize = testAlternateSerializer;
507 };
508
509 const MyStruct = struct {
510 f_i3: i3,
511 f_u8: u8,
512 f_tag_align: TagAlign,
513 f_u24: u24,
514 f_i19: i19,
515 f_void: void,
516 f_f32: f32,
517 f_f128: f128,
518 f_packed_0: PackedStruct,
519 f_i7arr: [10]i7,
520 f_of64n: ?f64,
521 f_of64v: ?f64,
522 f_color_type: ColorType,
523 f_packed_1: PackedStruct,
524 f_custom: Custom,
525 f_color: Color,
526 };
527
528 const my_inst = MyStruct{
529 .f_i3 = -1,
530 .f_u8 = 8,
531 .f_tag_align = TagAlign{ .B = 148 },
532 .f_u24 = 24,
533 .f_i19 = 19,
534 .f_void = {},
535 .f_f32 = 32.32,
536 .f_f128 = 128.128,
537 .f_packed_0 = PackedStruct{ .f_i3 = -1, .f_u2 = 2 },
538 .f_i7arr = [10]i7{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
539 .f_of64n = null,
540 .f_of64v = 64.64,
541 .f_color_type = ColorType.R32,
542 .f_packed_1 = PackedStruct{ .f_i3 = 1, .f_u2 = 1 },
543 .f_custom = Custom{ .f_f16 = 38.63, .f_unused_u32 = 47 },
544 .f_color = Color{ .R32 = 123822 },
545 };
546
547 var data_mem: [@sizeOf(MyStruct)]u8 = undefined;
548 var out = io.fixedBufferStream(&data_mem);
549 var serializer = serializer(endian, packing, out.outStream());
550
551 var in = io.fixedBufferStream(&data_mem);
552 var deserializer = deserializer(endian, packing, in.inStream());
553
554 try serializer.serialize(my_inst);
555
556 const my_copy = try deserializer.deserialize(MyStruct);
557 expect(meta.eql(my_copy, my_inst));
558}
559
560test "Serializer/Deserializer generic" {
561 try testSerializerDeserializer(builtin.Endian.Big, .Byte);
562 try testSerializerDeserializer(builtin.Endian.Little, .Byte);
563 try testSerializerDeserializer(builtin.Endian.Big, .Bit);
564 try testSerializerDeserializer(builtin.Endian.Little, .Bit);
565}
566
567fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
568 const E = enum(u14) {
569 One = 1,
570 Two = 2,
571 };
572
573 const A = struct {
574 e: E,
575 };
576
577 const C = union(E) {
578 One: u14,
579 Two: f16,
580 };
581
582 var data_mem: [4]u8 = undefined;
583 var out = io.fixedBufferStream.init(&data_mem);
584 var serializer = serializer(endian, packing, out.outStream());
585
586 var in = io.fixedBufferStream(&data_mem);
587 var deserializer = deserializer(endian, packing, in.inStream());
588
589 try serializer.serialize(@as(u14, 3));
590 expectError(error.InvalidEnumTag, deserializer.deserialize(A));
591 out.pos = 0;
592 try serializer.serialize(@as(u14, 3));
593 try serializer.serialize(@as(u14, 88));
594 expectError(error.InvalidEnumTag, deserializer.deserialize(C));
595}
596
597test "Deserializer bad data" {
598 try testBadData(.Big, .Byte);
599 try testBadData(.Little, .Byte);
600 try testBadData(.Big, .Bit);
601 try testBadData(.Little, .Bit);
602}
lib/std/io/stream_source.zig created+90
...@@ -0,0 +1,90 @@
1const std = @import("../std.zig");
2const io = std.io;
3const testing = std.testing;
4
5/// Provides `io.InStream`, `io.OutStream`, and `io.SeekableStream` for in-memory buffers as
6/// well as files.
7/// For memory sources, if the supplied byte buffer is const, then `io.OutStream` is not available.
8/// The error set of the stream functions is the error set of the corresponding file functions.
9pub const StreamSource = union(enum) {
10 buffer: io.FixedBufferStream([]u8),
11 const_buffer: io.FixedBufferStream([]const u8),
12 file: std.fs.File,
13
14 pub const ReadError = std.fs.File.ReadError;
15 pub const WriteError = std.fs.File.WriteError;
16 pub const SeekError = std.fs.File.SeekError;
17 pub const GetSeekPosError = std.fs.File.GetPosError;
18
19 pub const InStream = io.InStream(*StreamSource, ReadError, read);
20 pub const OutStream = io.OutStream(*StreamSource, WriteError, write);
21 pub const SeekableStream = io.SeekableStream(
22 *StreamSource,
23 SeekError,
24 GetSeekPosError,
25 seekTo,
26 seekBy,
27 getPos,
28 getEndPos,
29 );
30
31 pub fn read(self: *StreamSource, dest: []u8) ReadError!usize {
32 switch (self.*) {
33 .buffer => |*x| return x.read(dest),
34 .const_buffer => |*x| return x.read(dest),
35 .file => |x| return x.read(dest),
36 }
37 }
38
39 pub fn write(self: *StreamSource, bytes: []const u8) WriteError!usize {
40 switch (self.*) {
41 .buffer => |*x| return x.write(bytes),
42 .const_buffer => |*x| return x.write(bytes),
43 .file => |x| return x.write(bytes),
44 }
45 }
46
47 pub fn seekTo(self: *StreamSource, pos: u64) SeekError!void {
48 switch (self.*) {
49 .buffer => |*x| return x.seekTo(pos),
50 .const_buffer => |*x| return x.seekTo(pos),
51 .file => |x| return x.seekTo(pos),
52 }
53 }
54
55 pub fn seekBy(self: *StreamSource, amt: i64) SeekError!void {
56 switch (self.*) {
57 .buffer => |*x| return x.seekBy(amt),
58 .const_buffer => |*x| return x.seekBy(amt),
59 .file => |x| return x.seekBy(amt),
60 }
61 }
62
63 pub fn getEndPos(self: *StreamSource) GetSeekPosError!u64 {
64 switch (self.*) {
65 .buffer => |*x| return x.getEndPos(),
66 .const_buffer => |*x| return x.getEndPos(),
67 .file => |x| return x.getEndPos(),
68 }
69 }
70
71 pub fn getPos(self: *StreamSource) GetSeekPosError!u64 {
72 switch (self.*) {
73 .buffer => |*x| return x.getPos(),
74 .const_buffer => |*x| return x.getPos(),
75 .file => |x| return x.getPos(),
76 }
77 }
78
79 pub fn inStream(self: *StreamSource) InStream {
80 return .{ .context = self };
81 }
82
83 pub fn outStream(self: *StreamSource) OutStream {
84 return .{ .context = self };
85 }
86
87 pub fn seekableStream(self: *StreamSource) SeekableStream {
88 return .{ .context = self };
89 }
90};
lib/std/io/test.zig+38-519
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1const builtin = @import("builtin");1const std = @import("std");
2const std = @import("../std.zig");2const builtin = std.builtin;
3const io = std.io;3const io = std.io;
4const meta = std.meta;4const meta = std.meta;
5const trait = std.trait;5const trait = std.trait;
...@@ -22,11 +22,10 @@ test "write a file, read it, then delete it" {...@@ -22,11 +22,10 @@ test "write a file, read it, then delete it" {
22 var file = try cwd.createFile(tmp_file_name, .{});22 var file = try cwd.createFile(tmp_file_name, .{});
23 defer file.close();23 defer file.close();
2424
25 var file_out_stream = file.outStream();25 var buf_stream = io.bufferedOutStream(file.outStream());
26 var buf_stream = io.BufferedOutStream(File.WriteError).init(&file_out_stream.stream);26 const st = buf_stream.outStream();
27 const st = &buf_stream.stream;
28 try st.print("begin", .{});27 try st.print("begin", .{});
29 try st.write(data[0..]);28 try st.writeAll(data[0..]);
30 try st.print("end", .{});29 try st.print("end", .{});
31 try buf_stream.flush();30 try buf_stream.flush();
32 }31 }
...@@ -48,9 +47,8 @@ test "write a file, read it, then delete it" {...@@ -48,9 +47,8 @@ test "write a file, read it, then delete it" {
48 const expected_file_size: u64 = "begin".len + data.len + "end".len;47 const expected_file_size: u64 = "begin".len + data.len + "end".len;
49 expectEqual(expected_file_size, file_size);48 expectEqual(expected_file_size, file_size);
5049
51 var file_in_stream = file.inStream();50 var buf_stream = io.bufferedInStream(file.inStream());
52 var buf_stream = io.BufferedInStream(File.ReadError).init(&file_in_stream.stream);51 const st = buf_stream.inStream();
53 const st = &buf_stream.stream;
54 const contents = try st.readAllAlloc(std.testing.allocator, 2 * 1024);52 const contents = try st.readAllAlloc(std.testing.allocator, 2 * 1024);
55 defer std.testing.allocator.free(contents);53 defer std.testing.allocator.free(contents);
5654
...@@ -61,224 +59,13 @@ test "write a file, read it, then delete it" {...@@ -61,224 +59,13 @@ test "write a file, read it, then delete it" {
61 try cwd.deleteFile(tmp_file_name);59 try cwd.deleteFile(tmp_file_name);
62}60}
6361
64test "BufferOutStream" {
65 var buffer = try std.Buffer.initSize(std.testing.allocator, 0);
66 defer buffer.deinit();
67 var buf_stream = &std.io.BufferOutStream.init(&buffer).stream;
68
69 const x: i32 = 42;
70 const y: i32 = 1234;
71 try buf_stream.print("x: {}\ny: {}\n", .{ x, y });
72
73 expect(mem.eql(u8, buffer.toSlice(), "x: 42\ny: 1234\n"));
74}
75
76test "SliceInStream" {
77 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7 };
78 var ss = io.SliceInStream.init(&bytes);
79
80 var dest: [4]u8 = undefined;
81
82 var read = try ss.stream.read(dest[0..4]);
83 expect(read == 4);
84 expect(mem.eql(u8, dest[0..4], bytes[0..4]));
85
86 read = try ss.stream.read(dest[0..4]);
87 expect(read == 3);
88 expect(mem.eql(u8, dest[0..3], bytes[4..7]));
89
90 read = try ss.stream.read(dest[0..4]);
91 expect(read == 0);
92}
93
94test "PeekStream" {
95 const bytes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8 };
96 var ss = io.SliceInStream.init(&bytes);
97 var ps = io.PeekStream(.{ .Static = 2 }, io.SliceInStream.Error).init(&ss.stream);
98
99 var dest: [4]u8 = undefined;
100
101 try ps.putBackByte(9);
102 try ps.putBackByte(10);
103
104 var read = try ps.stream.read(dest[0..4]);
105 expect(read == 4);
106 expect(dest[0] == 10);
107 expect(dest[1] == 9);
108 expect(mem.eql(u8, dest[2..4], bytes[0..2]));
109
110 read = try ps.stream.read(dest[0..4]);
111 expect(read == 4);
112 expect(mem.eql(u8, dest[0..4], bytes[2..6]));
113
114 read = try ps.stream.read(dest[0..4]);
115 expect(read == 2);
116 expect(mem.eql(u8, dest[0..2], bytes[6..8]));
117
118 try ps.putBackByte(11);
119 try ps.putBackByte(12);
120
121 read = try ps.stream.read(dest[0..4]);
122 expect(read == 2);
123 expect(dest[0] == 12);
124 expect(dest[1] == 11);
125}
126
127test "SliceOutStream" {
128 var buffer: [10]u8 = undefined;
129 var ss = io.SliceOutStream.init(buffer[0..]);
130
131 try ss.stream.write("Hello");
132 expect(mem.eql(u8, ss.getWritten(), "Hello"));
133
134 try ss.stream.write("world");
135 expect(mem.eql(u8, ss.getWritten(), "Helloworld"));
136
137 expectError(error.OutOfMemory, ss.stream.write("!"));
138 expect(mem.eql(u8, ss.getWritten(), "Helloworld"));
139
140 ss.reset();
141 expect(ss.getWritten().len == 0);
142
143 expectError(error.OutOfMemory, ss.stream.write("Hello world!"));
144 expect(mem.eql(u8, ss.getWritten(), "Hello worl"));
145}
146
147test "BitInStream" {
148 const mem_be = [_]u8{ 0b11001101, 0b00001011 };
149 const mem_le = [_]u8{ 0b00011101, 0b10010101 };
150
151 var mem_in_be = io.SliceInStream.init(mem_be[0..]);
152 const InError = io.SliceInStream.Error;
153 var bit_stream_be = io.BitInStream(builtin.Endian.Big, InError).init(&mem_in_be.stream);
154
155 var out_bits: usize = undefined;
156
157 expect(1 == try bit_stream_be.readBits(u2, 1, &out_bits));
158 expect(out_bits == 1);
159 expect(2 == try bit_stream_be.readBits(u5, 2, &out_bits));
160 expect(out_bits == 2);
161 expect(3 == try bit_stream_be.readBits(u128, 3, &out_bits));
162 expect(out_bits == 3);
163 expect(4 == try bit_stream_be.readBits(u8, 4, &out_bits));
164 expect(out_bits == 4);
165 expect(5 == try bit_stream_be.readBits(u9, 5, &out_bits));
166 expect(out_bits == 5);
167 expect(1 == try bit_stream_be.readBits(u1, 1, &out_bits));
168 expect(out_bits == 1);
169
170 mem_in_be.pos = 0;
171 bit_stream_be.bit_count = 0;
172 expect(0b110011010000101 == try bit_stream_be.readBits(u15, 15, &out_bits));
173 expect(out_bits == 15);
174
175 mem_in_be.pos = 0;
176 bit_stream_be.bit_count = 0;
177 expect(0b1100110100001011 == try bit_stream_be.readBits(u16, 16, &out_bits));
178 expect(out_bits == 16);
179
180 _ = try bit_stream_be.readBits(u0, 0, &out_bits);
181
182 expect(0 == try bit_stream_be.readBits(u1, 1, &out_bits));
183 expect(out_bits == 0);
184 expectError(error.EndOfStream, bit_stream_be.readBitsNoEof(u1, 1));
185
186 var mem_in_le = io.SliceInStream.init(mem_le[0..]);
187 var bit_stream_le = io.BitInStream(builtin.Endian.Little, InError).init(&mem_in_le.stream);
188
189 expect(1 == try bit_stream_le.readBits(u2, 1, &out_bits));
190 expect(out_bits == 1);
191 expect(2 == try bit_stream_le.readBits(u5, 2, &out_bits));
192 expect(out_bits == 2);
193 expect(3 == try bit_stream_le.readBits(u128, 3, &out_bits));
194 expect(out_bits == 3);
195 expect(4 == try bit_stream_le.readBits(u8, 4, &out_bits));
196 expect(out_bits == 4);
197 expect(5 == try bit_stream_le.readBits(u9, 5, &out_bits));
198 expect(out_bits == 5);
199 expect(1 == try bit_stream_le.readBits(u1, 1, &out_bits));
200 expect(out_bits == 1);
201
202 mem_in_le.pos = 0;
203 bit_stream_le.bit_count = 0;
204 expect(0b001010100011101 == try bit_stream_le.readBits(u15, 15, &out_bits));
205 expect(out_bits == 15);
206
207 mem_in_le.pos = 0;
208 bit_stream_le.bit_count = 0;
209 expect(0b1001010100011101 == try bit_stream_le.readBits(u16, 16, &out_bits));
210 expect(out_bits == 16);
211
212 _ = try bit_stream_le.readBits(u0, 0, &out_bits);
213
214 expect(0 == try bit_stream_le.readBits(u1, 1, &out_bits));
215 expect(out_bits == 0);
216 expectError(error.EndOfStream, bit_stream_le.readBitsNoEof(u1, 1));
217}
218
219test "BitOutStream" {
220 var mem_be = [_]u8{0} ** 2;
221 var mem_le = [_]u8{0} ** 2;
222
223 var mem_out_be = io.SliceOutStream.init(mem_be[0..]);
224 const OutError = io.SliceOutStream.Error;
225 var bit_stream_be = io.BitOutStream(builtin.Endian.Big, OutError).init(&mem_out_be.stream);
226
227 try bit_stream_be.writeBits(@as(u2, 1), 1);
228 try bit_stream_be.writeBits(@as(u5, 2), 2);
229 try bit_stream_be.writeBits(@as(u128, 3), 3);
230 try bit_stream_be.writeBits(@as(u8, 4), 4);
231 try bit_stream_be.writeBits(@as(u9, 5), 5);
232 try bit_stream_be.writeBits(@as(u1, 1), 1);
233
234 expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
235
236 mem_out_be.pos = 0;
237
238 try bit_stream_be.writeBits(@as(u15, 0b110011010000101), 15);
239 try bit_stream_be.flushBits();
240 expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
241
242 mem_out_be.pos = 0;
243 try bit_stream_be.writeBits(@as(u32, 0b110011010000101), 16);
244 expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
245
246 try bit_stream_be.writeBits(@as(u0, 0), 0);
247
248 var mem_out_le = io.SliceOutStream.init(mem_le[0..]);
249 var bit_stream_le = io.BitOutStream(builtin.Endian.Little, OutError).init(&mem_out_le.stream);
250
251 try bit_stream_le.writeBits(@as(u2, 1), 1);
252 try bit_stream_le.writeBits(@as(u5, 2), 2);
253 try bit_stream_le.writeBits(@as(u128, 3), 3);
254 try bit_stream_le.writeBits(@as(u8, 4), 4);
255 try bit_stream_le.writeBits(@as(u9, 5), 5);
256 try bit_stream_le.writeBits(@as(u1, 1), 1);
257
258 expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
259
260 mem_out_le.pos = 0;
261 try bit_stream_le.writeBits(@as(u15, 0b110011010000101), 15);
262 try bit_stream_le.flushBits();
263 expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
264
265 mem_out_le.pos = 0;
266 try bit_stream_le.writeBits(@as(u32, 0b1100110100001011), 16);
267 expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
268
269 try bit_stream_le.writeBits(@as(u0, 0), 0);
270}
271
272test "BitStreams with File Stream" {62test "BitStreams with File Stream" {
273 const tmp_file_name = "temp_test_file.txt";63 const tmp_file_name = "temp_test_file.txt";
274 {64 {
275 var file = try fs.cwd().createFile(tmp_file_name, .{});65 var file = try fs.cwd().createFile(tmp_file_name, .{});
276 defer file.close();66 defer file.close();
27767
278 var file_out = file.outStream();68 var bit_stream = io.bitOutStream(builtin.endian, file.outStream());
279 var file_out_stream = &file_out.stream;
280 const OutError = File.WriteError;
281 var bit_stream = io.BitOutStream(builtin.endian, OutError).init(file_out_stream);
28269
283 try bit_stream.writeBits(@as(u2, 1), 1);70 try bit_stream.writeBits(@as(u2, 1), 1);
284 try bit_stream.writeBits(@as(u5, 2), 2);71 try bit_stream.writeBits(@as(u5, 2), 2);
...@@ -292,10 +79,7 @@ test "BitStreams with File Stream" {...@@ -292,10 +79,7 @@ test "BitStreams with File Stream" {
292 var file = try fs.cwd().openFile(tmp_file_name, .{});79 var file = try fs.cwd().openFile(tmp_file_name, .{});
293 defer file.close();80 defer file.close();
29481
295 var file_in = file.inStream();82 var bit_stream = io.bitInStream(builtin.endian, file.inStream());
296 var file_in_stream = &file_in.stream;
297 const InError = File.ReadError;
298 var bit_stream = io.BitInStream(builtin.endian, InError).init(file_in_stream);
29983
300 var out_bits: usize = undefined;84 var out_bits: usize = undefined;
30185
...@@ -317,294 +101,6 @@ test "BitStreams with File Stream" {...@@ -317,294 +101,6 @@ test "BitStreams with File Stream" {
317 try fs.cwd().deleteFile(tmp_file_name);101 try fs.cwd().deleteFile(tmp_file_name);
318}102}
319103
320fn testIntSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
321 @setEvalBranchQuota(1500);
322 //@NOTE: if this test is taking too long, reduce the maximum tested bitsize
323 const max_test_bitsize = 128;
324
325 const total_bytes = comptime blk: {
326 var bytes = 0;
327 comptime var i = 0;
328 while (i <= max_test_bitsize) : (i += 1) bytes += (i / 8) + @boolToInt(i % 8 > 0);
329 break :blk bytes * 2;
330 };
331
332 var data_mem: [total_bytes]u8 = undefined;
333 var out = io.SliceOutStream.init(data_mem[0..]);
334 const OutError = io.SliceOutStream.Error;
335 var out_stream = &out.stream;
336 var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
337
338 var in = io.SliceInStream.init(data_mem[0..]);
339 const InError = io.SliceInStream.Error;
340 var in_stream = &in.stream;
341 var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
342
343 comptime var i = 0;
344 inline while (i <= max_test_bitsize) : (i += 1) {
345 const U = std.meta.IntType(false, i);
346 const S = std.meta.IntType(true, i);
347 try serializer.serializeInt(@as(U, i));
348 if (i != 0) try serializer.serializeInt(@as(S, -1)) else try serializer.serialize(@as(S, 0));
349 }
350 try serializer.flush();
351
352 i = 0;
353 inline while (i <= max_test_bitsize) : (i += 1) {
354 const U = std.meta.IntType(false, i);
355 const S = std.meta.IntType(true, i);
356 const x = try deserializer.deserializeInt(U);
357 const y = try deserializer.deserializeInt(S);
358 expect(x == @as(U, i));
359 if (i != 0) expect(y == @as(S, -1)) else expect(y == 0);
360 }
361
362 const u8_bit_count = comptime meta.bitCount(u8);
363 //0 + 1 + 2 + ... n = (n * (n + 1)) / 2
364 //and we have each for unsigned and signed, so * 2
365 const total_bits = (max_test_bitsize * (max_test_bitsize + 1));
366 const extra_packed_byte = @boolToInt(total_bits % u8_bit_count > 0);
367 const total_packed_bytes = (total_bits / u8_bit_count) + extra_packed_byte;
368
369 expect(in.pos == if (packing == .Bit) total_packed_bytes else total_bytes);
370
371 //Verify that empty error set works with serializer.
372 //deserializer is covered by SliceInStream
373 const NullError = io.NullOutStream.Error;
374 var null_out = io.NullOutStream.init();
375 var null_out_stream = &null_out.stream;
376 var null_serializer = io.Serializer(endian, packing, NullError).init(null_out_stream);
377 try null_serializer.serialize(data_mem[0..]);
378 try null_serializer.flush();
379}
380
381test "Serializer/Deserializer Int" {
382 try testIntSerializerDeserializer(.Big, .Byte);
383 try testIntSerializerDeserializer(.Little, .Byte);
384 // TODO these tests are disabled due to tripping an LLVM assertion
385 // https://github.com/ziglang/zig/issues/2019
386 //try testIntSerializerDeserializer(builtin.Endian.Big, true);
387 //try testIntSerializerDeserializer(builtin.Endian.Little, true);
388}
389
390fn testIntSerializerDeserializerInfNaN(
391 comptime endian: builtin.Endian,
392 comptime packing: io.Packing,
393) !void {
394 const mem_size = (16 * 2 + 32 * 2 + 64 * 2 + 128 * 2) / comptime meta.bitCount(u8);
395 var data_mem: [mem_size]u8 = undefined;
396
397 var out = io.SliceOutStream.init(data_mem[0..]);
398 const OutError = io.SliceOutStream.Error;
399 var out_stream = &out.stream;
400 var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
401
402 var in = io.SliceInStream.init(data_mem[0..]);
403 const InError = io.SliceInStream.Error;
404 var in_stream = &in.stream;
405 var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
406
407 //@TODO: isInf/isNan not currently implemented for f128.
408 try serializer.serialize(std.math.nan(f16));
409 try serializer.serialize(std.math.inf(f16));
410 try serializer.serialize(std.math.nan(f32));
411 try serializer.serialize(std.math.inf(f32));
412 try serializer.serialize(std.math.nan(f64));
413 try serializer.serialize(std.math.inf(f64));
414 //try serializer.serialize(std.math.nan(f128));
415 //try serializer.serialize(std.math.inf(f128));
416 const nan_check_f16 = try deserializer.deserialize(f16);
417 const inf_check_f16 = try deserializer.deserialize(f16);
418 const nan_check_f32 = try deserializer.deserialize(f32);
419 deserializer.alignToByte();
420 const inf_check_f32 = try deserializer.deserialize(f32);
421 const nan_check_f64 = try deserializer.deserialize(f64);
422 const inf_check_f64 = try deserializer.deserialize(f64);
423 //const nan_check_f128 = try deserializer.deserialize(f128);
424 //const inf_check_f128 = try deserializer.deserialize(f128);
425 expect(std.math.isNan(nan_check_f16));
426 expect(std.math.isInf(inf_check_f16));
427 expect(std.math.isNan(nan_check_f32));
428 expect(std.math.isInf(inf_check_f32));
429 expect(std.math.isNan(nan_check_f64));
430 expect(std.math.isInf(inf_check_f64));
431 //expect(std.math.isNan(nan_check_f128));
432 //expect(std.math.isInf(inf_check_f128));
433}
434
435test "Serializer/Deserializer Int: Inf/NaN" {
436 try testIntSerializerDeserializerInfNaN(.Big, .Byte);
437 try testIntSerializerDeserializerInfNaN(.Little, .Byte);
438 try testIntSerializerDeserializerInfNaN(.Big, .Bit);
439 try testIntSerializerDeserializerInfNaN(.Little, .Bit);
440}
441
442fn testAlternateSerializer(self: var, serializer: var) !void {
443 try serializer.serialize(self.f_f16);
444}
445
446fn testSerializerDeserializer(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
447 const ColorType = enum(u4) {
448 RGB8 = 1,
449 RA16 = 2,
450 R32 = 3,
451 };
452
453 const TagAlign = union(enum(u32)) {
454 A: u8,
455 B: u8,
456 C: u8,
457 };
458
459 const Color = union(ColorType) {
460 RGB8: struct {
461 r: u8,
462 g: u8,
463 b: u8,
464 a: u8,
465 },
466 RA16: struct {
467 r: u16,
468 a: u16,
469 },
470 R32: u32,
471 };
472
473 const PackedStruct = packed struct {
474 f_i3: i3,
475 f_u2: u2,
476 };
477
478 //to test custom serialization
479 const Custom = struct {
480 f_f16: f16,
481 f_unused_u32: u32,
482
483 pub fn deserialize(self: *@This(), deserializer: var) !void {
484 try deserializer.deserializeInto(&self.f_f16);
485 self.f_unused_u32 = 47;
486 }
487
488 pub const serialize = testAlternateSerializer;
489 };
490
491 const MyStruct = struct {
492 f_i3: i3,
493 f_u8: u8,
494 f_tag_align: TagAlign,
495 f_u24: u24,
496 f_i19: i19,
497 f_void: void,
498 f_f32: f32,
499 f_f128: f128,
500 f_packed_0: PackedStruct,
501 f_i7arr: [10]i7,
502 f_of64n: ?f64,
503 f_of64v: ?f64,
504 f_color_type: ColorType,
505 f_packed_1: PackedStruct,
506 f_custom: Custom,
507 f_color: Color,
508 };
509
510 const my_inst = MyStruct{
511 .f_i3 = -1,
512 .f_u8 = 8,
513 .f_tag_align = TagAlign{ .B = 148 },
514 .f_u24 = 24,
515 .f_i19 = 19,
516 .f_void = {},
517 .f_f32 = 32.32,
518 .f_f128 = 128.128,
519 .f_packed_0 = PackedStruct{ .f_i3 = -1, .f_u2 = 2 },
520 .f_i7arr = [10]i7{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
521 .f_of64n = null,
522 .f_of64v = 64.64,
523 .f_color_type = ColorType.R32,
524 .f_packed_1 = PackedStruct{ .f_i3 = 1, .f_u2 = 1 },
525 .f_custom = Custom{ .f_f16 = 38.63, .f_unused_u32 = 47 },
526 .f_color = Color{ .R32 = 123822 },
527 };
528
529 var data_mem: [@sizeOf(MyStruct)]u8 = undefined;
530 var out = io.SliceOutStream.init(data_mem[0..]);
531 const OutError = io.SliceOutStream.Error;
532 var out_stream = &out.stream;
533 var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
534
535 var in = io.SliceInStream.init(data_mem[0..]);
536 const InError = io.SliceInStream.Error;
537 var in_stream = &in.stream;
538 var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
539
540 try serializer.serialize(my_inst);
541
542 const my_copy = try deserializer.deserialize(MyStruct);
543 expect(meta.eql(my_copy, my_inst));
544}
545
546test "Serializer/Deserializer generic" {
547 try testSerializerDeserializer(builtin.Endian.Big, .Byte);
548 try testSerializerDeserializer(builtin.Endian.Little, .Byte);
549 try testSerializerDeserializer(builtin.Endian.Big, .Bit);
550 try testSerializerDeserializer(builtin.Endian.Little, .Bit);
551}
552
553fn testBadData(comptime endian: builtin.Endian, comptime packing: io.Packing) !void {
554 const E = enum(u14) {
555 One = 1,
556 Two = 2,
557 };
558
559 const A = struct {
560 e: E,
561 };
562
563 const C = union(E) {
564 One: u14,
565 Two: f16,
566 };
567
568 var data_mem: [4]u8 = undefined;
569 var out = io.SliceOutStream.init(data_mem[0..]);
570 const OutError = io.SliceOutStream.Error;
571 var out_stream = &out.stream;
572 var serializer = io.Serializer(endian, packing, OutError).init(out_stream);
573
574 var in = io.SliceInStream.init(data_mem[0..]);
575 const InError = io.SliceInStream.Error;
576 var in_stream = &in.stream;
577 var deserializer = io.Deserializer(endian, packing, InError).init(in_stream);
578
579 try serializer.serialize(@as(u14, 3));
580 expectError(error.InvalidEnumTag, deserializer.deserialize(A));
581 out.pos = 0;
582 try serializer.serialize(@as(u14, 3));
583 try serializer.serialize(@as(u14, 88));
584 expectError(error.InvalidEnumTag, deserializer.deserialize(C));
585}
586
587test "Deserializer bad data" {
588 try testBadData(.Big, .Byte);
589 try testBadData(.Little, .Byte);
590 try testBadData(.Big, .Bit);
591 try testBadData(.Little, .Bit);
592}
593
594test "c out stream" {
595 if (!builtin.link_libc) return error.SkipZigTest;
596
597 const filename = "tmp_io_test_file.txt";
598 const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile;
599 defer {
600 _ = std.c.fclose(out_file);
601 fs.cwd().deleteFileC(filename) catch {};
602 }
603
604 const out_stream = &io.COutStream.init(out_file).stream;
605 try out_stream.print("hi: {}\n", .{@as(i32, 123)});
606}
607
608test "File seek ops" {104test "File seek ops" {
609 const tmp_file_name = "temp_test_file.txt";105 const tmp_file_name = "temp_test_file.txt";
610 var file = try fs.cwd().createFile(tmp_file_name, .{});106 var file = try fs.cwd().createFile(tmp_file_name, .{});
...@@ -617,16 +113,39 @@ test "File seek ops" {...@@ -617,16 +113,39 @@ test "File seek ops" {
617113
618 // Seek to the end114 // Seek to the end
619 try file.seekFromEnd(0);115 try file.seekFromEnd(0);
620 std.testing.expect((try file.getPos()) == try file.getEndPos());116 expect((try file.getPos()) == try file.getEndPos());
621 // Negative delta117 // Negative delta
622 try file.seekBy(-4096);118 try file.seekBy(-4096);
623 std.testing.expect((try file.getPos()) == 4096);119 expect((try file.getPos()) == 4096);
624 // Positive delta120 // Positive delta
625 try file.seekBy(10);121 try file.seekBy(10);
626 std.testing.expect((try file.getPos()) == 4106);122 expect((try file.getPos()) == 4106);
627 // Absolute position123 // Absolute position
628 try file.seekTo(1234);124 try file.seekTo(1234);
629 std.testing.expect((try file.getPos()) == 1234);125 expect((try file.getPos()) == 1234);
126}
127
128test "setEndPos" {
129 const tmp_file_name = "temp_test_file.txt";
130 var file = try fs.cwd().createFile(tmp_file_name, .{});
131 defer {
132 file.close();
133 fs.cwd().deleteFile(tmp_file_name) catch {};
134 }
135
136 // Verify that the file size changes and the file offset is not moved
137 std.testing.expect((try file.getEndPos()) == 0);
138 std.testing.expect((try file.getPos()) == 0);
139 try file.setEndPos(8192);
140 std.testing.expect((try file.getEndPos()) == 8192);
141 std.testing.expect((try file.getPos()) == 0);
142 try file.seekTo(100);
143 try file.setEndPos(4096);
144 std.testing.expect((try file.getEndPos()) == 4096);
145 std.testing.expect((try file.getPos()) == 100);
146 try file.setEndPos(0);
147 std.testing.expect((try file.getEndPos()) == 0);
148 std.testing.expect((try file.getPos()) == 100);
630}149}
631150
632test "updateTimes" {151test "updateTimes" {
...@@ -643,6 +162,6 @@ test "updateTimes" {...@@ -643,6 +162,6 @@ test "updateTimes" {
643 stat_old.mtime - 5 * std.time.ns_per_s,162 stat_old.mtime - 5 * std.time.ns_per_s,
644 );163 );
645 var stat_new = try file.stat();164 var stat_new = try file.stat();
646 std.testing.expect(stat_new.atime < stat_old.atime);165 expect(stat_new.atime < stat_old.atime);
647 std.testing.expect(stat_new.mtime < stat_old.mtime);166 expect(stat_new.mtime < stat_old.mtime);
648}167}
lib/std/json.zig+77-66
...@@ -10,6 +10,7 @@ const mem = std.mem;...@@ -10,6 +10,7 @@ const mem = std.mem;
10const maxInt = std.math.maxInt;10const maxInt = std.math.maxInt;
1111
12pub const WriteStream = @import("json/write_stream.zig").WriteStream;12pub const WriteStream = @import("json/write_stream.zig").WriteStream;
13pub const writeStream = @import("json/write_stream.zig").writeStream;
1314
14const StringEscapes = union(enum) {15const StringEscapes = union(enum) {
15 None,16 None,
...@@ -2107,9 +2108,9 @@ test "import more json tests" {...@@ -2107,9 +2108,9 @@ test "import more json tests" {
2107test "write json then parse it" {2108test "write json then parse it" {
2108 var out_buffer: [1000]u8 = undefined;2109 var out_buffer: [1000]u8 = undefined;
21092110
2110 var slice_out_stream = std.io.SliceOutStream.init(&out_buffer);2111 var fixed_buffer_stream = std.io.fixedBufferStream(&out_buffer);
2111 const out_stream = &slice_out_stream.stream;2112 const out_stream = fixed_buffer_stream.outStream();
2112 var jw = WriteStream(@TypeOf(out_stream).Child, 4).init(out_stream);2113 var jw = writeStream(out_stream, 4);
21132114
2114 try jw.beginObject();2115 try jw.beginObject();
21152116
...@@ -2140,7 +2141,7 @@ test "write json then parse it" {...@@ -2140,7 +2141,7 @@ test "write json then parse it" {
21402141
2141 var parser = Parser.init(testing.allocator, false);2142 var parser = Parser.init(testing.allocator, false);
2142 defer parser.deinit();2143 defer parser.deinit();
2143 var tree = try parser.parse(slice_out_stream.getWritten());2144 var tree = try parser.parse(fixed_buffer_stream.getWritten());
2144 defer tree.deinit();2145 defer tree.deinit();
21452146
2146 testing.expect(tree.root.Object.get("f").?.value.Bool == false);2147 testing.expect(tree.root.Object.get("f").?.value.Bool == false);
...@@ -2251,45 +2252,43 @@ pub const StringifyOptions = struct {...@@ -2251,45 +2252,43 @@ pub const StringifyOptions = struct {
2251pub fn stringify(2252pub fn stringify(
2252 value: var,2253 value: var,
2253 options: StringifyOptions,2254 options: StringifyOptions,
2254 context: var,2255 out_stream: var,
2255 comptime Errors: type,2256) !void {
2256 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
2257) Errors!void {
2258 const T = @TypeOf(value);2257 const T = @TypeOf(value);
2259 switch (@typeInfo(T)) {2258 switch (@typeInfo(T)) {
2260 .Float, .ComptimeFloat => {2259 .Float, .ComptimeFloat => {
2261 return std.fmt.formatFloatScientific(value, std.fmt.FormatOptions{}, context, Errors, output);2260 return std.fmt.formatFloatScientific(value, std.fmt.FormatOptions{}, out_stream);
2262 },2261 },
2263 .Int, .ComptimeInt => {2262 .Int, .ComptimeInt => {
2264 return std.fmt.formatIntValue(value, "", std.fmt.FormatOptions{}, context, Errors, output);2263 return std.fmt.formatIntValue(value, "", std.fmt.FormatOptions{}, out_stream);
2265 },2264 },
2266 .Bool => {2265 .Bool => {
2267 return output(context, if (value) "true" else "false");2266 return out_stream.writeAll(if (value) "true" else "false");
2268 },2267 },
2269 .Optional => {2268 .Optional => {
2270 if (value) |payload| {2269 if (value) |payload| {
2271 return try stringify(payload, options, context, Errors, output);2270 return try stringify(payload, options, out_stream);
2272 } else {2271 } else {
2273 return output(context, "null");2272 return out_stream.writeAll("null");
2274 }2273 }
2275 },2274 },
2276 .Enum => {2275 .Enum => {
2277 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {2276 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
2278 return value.jsonStringify(options, context, Errors, output);2277 return value.jsonStringify(options, out_stream);
2279 }2278 }
22802279
2281 @compileError("Unable to stringify enum '" ++ @typeName(T) ++ "'");2280 @compileError("Unable to stringify enum '" ++ @typeName(T) ++ "'");
2282 },2281 },
2283 .Union => {2282 .Union => {
2284 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {2283 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
2285 return value.jsonStringify(options, context, Errors, output);2284 return value.jsonStringify(options, out_stream);
2286 }2285 }
22872286
2288 const info = @typeInfo(T).Union;2287 const info = @typeInfo(T).Union;
2289 if (info.tag_type) |UnionTagType| {2288 if (info.tag_type) |UnionTagType| {
2290 inline for (info.fields) |u_field| {2289 inline for (info.fields) |u_field| {
2291 if (@enumToInt(@as(UnionTagType, value)) == u_field.enum_field.?.value) {2290 if (@enumToInt(@as(UnionTagType, value)) == u_field.enum_field.?.value) {
2292 return try stringify(@field(value, u_field.name), options, context, Errors, output);2291 return try stringify(@field(value, u_field.name), options, out_stream);
2293 }2292 }
2294 }2293 }
2295 } else {2294 } else {
...@@ -2298,10 +2297,10 @@ pub fn stringify(...@@ -2298,10 +2297,10 @@ pub fn stringify(
2298 },2297 },
2299 .Struct => |S| {2298 .Struct => |S| {
2300 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {2299 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
2301 return value.jsonStringify(options, context, Errors, output);2300 return value.jsonStringify(options, out_stream);
2302 }2301 }
23032302
2304 try output(context, "{");2303 try out_stream.writeAll("{");
2305 comptime var field_output = false;2304 comptime var field_output = false;
2306 inline for (S.fields) |Field, field_i| {2305 inline for (S.fields) |Field, field_i| {
2307 // don't include void fields2306 // don't include void fields
...@@ -2310,39 +2309,39 @@ pub fn stringify(...@@ -2310,39 +2309,39 @@ pub fn stringify(
2310 if (!field_output) {2309 if (!field_output) {
2311 field_output = true;2310 field_output = true;
2312 } else {2311 } else {
2313 try output(context, ",");2312 try out_stream.writeAll(",");
2314 }2313 }
23152314
2316 try stringify(Field.name, options, context, Errors, output);2315 try stringify(Field.name, options, out_stream);
2317 try output(context, ":");2316 try out_stream.writeAll(":");
2318 try stringify(@field(value, Field.name), options, context, Errors, output);2317 try stringify(@field(value, Field.name), options, out_stream);
2319 }2318 }
2320 try output(context, "}");2319 try out_stream.writeAll("}");
2321 return;2320 return;
2322 },2321 },
2323 .Pointer => |ptr_info| switch (ptr_info.size) {2322 .Pointer => |ptr_info| switch (ptr_info.size) {
2324 .One => {2323 .One => {
2325 // TODO: avoid loops?2324 // TODO: avoid loops?
2326 return try stringify(value.*, options, context, Errors, output);2325 return try stringify(value.*, options, out_stream);
2327 },2326 },
2328 // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972)2327 // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972)
2329 .Slice => {2328 .Slice => {
2330 if (ptr_info.child == u8 and std.unicode.utf8ValidateSlice(value)) {2329 if (ptr_info.child == u8 and std.unicode.utf8ValidateSlice(value)) {
2331 try output(context, "\"");2330 try out_stream.writeAll("\"");
2332 var i: usize = 0;2331 var i: usize = 0;
2333 while (i < value.len) : (i += 1) {2332 while (i < value.len) : (i += 1) {
2334 switch (value[i]) {2333 switch (value[i]) {
2335 // normal ascii characters2334 // normal ascii characters
2336 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => try output(context, value[i .. i + 1]),2335 0x20...0x21, 0x23...0x2E, 0x30...0x5B, 0x5D...0x7F => try out_stream.writeAll(value[i .. i + 1]),
2337 // control characters with short escapes2336 // control characters with short escapes
2338 '\\' => try output(context, "\\\\"),2337 '\\' => try out_stream.writeAll("\\\\"),
2339 '\"' => try output(context, "\\\""),2338 '\"' => try out_stream.writeAll("\\\""),
2340 '/' => try output(context, "\\/"),2339 '/' => try out_stream.writeAll("\\/"),
2341 0x8 => try output(context, "\\b"),2340 0x8 => try out_stream.writeAll("\\b"),
2342 0xC => try output(context, "\\f"),2341 0xC => try out_stream.writeAll("\\f"),
2343 '\n' => try output(context, "\\n"),2342 '\n' => try out_stream.writeAll("\\n"),
2344 '\r' => try output(context, "\\r"),2343 '\r' => try out_stream.writeAll("\\r"),
2345 '\t' => try output(context, "\\t"),2344 '\t' => try out_stream.writeAll("\\t"),
2346 else => {2345 else => {
2347 const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;2346 const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;
2348 const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;2347 const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;
...@@ -2350,40 +2349,40 @@ pub fn stringify(...@@ -2350,40 +2349,40 @@ pub fn stringify(
2350 // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),2349 // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),
2351 // then it may be represented as a six-character sequence: a reverse solidus, followed2350 // then it may be represented as a six-character sequence: a reverse solidus, followed
2352 // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.2351 // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.
2353 try output(context, "\\u");2352 try out_stream.writeAll("\\u");
2354 try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, context, Errors, output);2353 try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2355 } else {2354 } else {
2356 // To escape an extended character that is not in the Basic Multilingual Plane,2355 // To escape an extended character that is not in the Basic Multilingual Plane,
2357 // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.2356 // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.
2358 const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;2357 const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
2359 const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;2358 const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
2360 try output(context, "\\u");2359 try out_stream.writeAll("\\u");
2361 try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, context, Errors, output);2360 try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2362 try output(context, "\\u");2361 try out_stream.writeAll("\\u");
2363 try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, context, Errors, output);2362 try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2364 }2363 }
2365 i += ulen - 1;2364 i += ulen - 1;
2366 },2365 },
2367 }2366 }
2368 }2367 }
2369 try output(context, "\"");2368 try out_stream.writeAll("\"");
2370 return;2369 return;
2371 }2370 }
23722371
2373 try output(context, "[");2372 try out_stream.writeAll("[");
2374 for (value) |x, i| {2373 for (value) |x, i| {
2375 if (i != 0) {2374 if (i != 0) {
2376 try output(context, ",");2375 try out_stream.writeAll(",");
2377 }2376 }
2378 try stringify(x, options, context, Errors, output);2377 try stringify(x, options, out_stream);
2379 }2378 }
2380 try output(context, "]");2379 try out_stream.writeAll("]");
2381 return;2380 return;
2382 },2381 },
2383 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),2382 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
2384 },2383 },
2385 .Array => |info| {2384 .Array => |info| {
2386 return try stringify(value[0..], options, context, Errors, output);2385 return try stringify(value[0..], options, out_stream);
2387 },2386 },
2388 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),2387 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
2389 }2388 }
...@@ -2391,10 +2390,26 @@ pub fn stringify(...@@ -2391,10 +2390,26 @@ pub fn stringify(
2391}2390}
23922391
2393fn teststringify(expected: []const u8, value: var) !void {2392fn teststringify(expected: []const u8, value: var) !void {
2394 const TestStringifyContext = struct {2393 const ValidationOutStream = struct {
2394 const Self = @This();
2395 pub const OutStream = std.io.OutStream(*Self, Error, write);
2396 pub const Error = error{
2397 TooMuchData,
2398 DifferentData,
2399 };
2400
2395 expected_remaining: []const u8,2401 expected_remaining: []const u8,
2396 fn testStringifyWrite(context: *@This(), bytes: []const u8) !void {2402
2397 if (context.expected_remaining.len < bytes.len) {2403 fn init(exp: []const u8) Self {
2404 return .{ .expected_remaining = exp };
2405 }
2406
2407 pub fn outStream(self: *Self) OutStream {
2408 return .{ .context = self };
2409 }
2410
2411 fn write(self: *Self, bytes: []const u8) Error!usize {
2412 if (self.expected_remaining.len < bytes.len) {
2398 std.debug.warn(2413 std.debug.warn(
2399 \\====== expected this output: =========2414 \\====== expected this output: =========
2400 \\{}2415 \\{}
...@@ -2402,12 +2417,12 @@ fn teststringify(expected: []const u8, value: var) !void {...@@ -2402,12 +2417,12 @@ fn teststringify(expected: []const u8, value: var) !void {
2402 \\{}2417 \\{}
2403 \\======================================2418 \\======================================
2404 , .{2419 , .{
2405 context.expected_remaining,2420 self.expected_remaining,
2406 bytes,2421 bytes,
2407 });2422 });
2408 return error.TooMuchData;2423 return error.TooMuchData;
2409 }2424 }
2410 if (!mem.eql(u8, context.expected_remaining[0..bytes.len], bytes)) {2425 if (!mem.eql(u8, self.expected_remaining[0..bytes.len], bytes)) {
2411 std.debug.warn(2426 std.debug.warn(
2412 \\====== expected this output: =========2427 \\====== expected this output: =========
2413 \\{}2428 \\{}
...@@ -2415,21 +2430,19 @@ fn teststringify(expected: []const u8, value: var) !void {...@@ -2415,21 +2430,19 @@ fn teststringify(expected: []const u8, value: var) !void {
2415 \\{}2430 \\{}
2416 \\======================================2431 \\======================================
2417 , .{2432 , .{
2418 context.expected_remaining[0..bytes.len],2433 self.expected_remaining[0..bytes.len],
2419 bytes,2434 bytes,
2420 });2435 });
2421 return error.DifferentData;2436 return error.DifferentData;
2422 }2437 }
2423 context.expected_remaining = context.expected_remaining[bytes.len..];2438 self.expected_remaining = self.expected_remaining[bytes.len..];
2439 return bytes.len;
2424 }2440 }
2425 };2441 };
2426 var buf: [100]u8 = undefined;2442
2427 var context = TestStringifyContext{ .expected_remaining = expected };2443 var vos = ValidationOutStream.init(expected);
2428 try stringify(value, StringifyOptions{}, &context, error{2444 try stringify(value, StringifyOptions{}, vos.outStream());
2429 TooMuchData,2445 if (vos.expected_remaining.len > 0) return error.NotEnoughData;
2430 DifferentData,
2431 }, TestStringifyContext.testStringifyWrite);
2432 if (context.expected_remaining.len > 0) return error.NotEnoughData;
2433}2446}
24342447
2435test "stringify basic types" {2448test "stringify basic types" {
...@@ -2497,13 +2510,11 @@ test "stringify struct with custom stringifier" {...@@ -2497,13 +2510,11 @@ test "stringify struct with custom stringifier" {
2497 pub fn jsonStringify(2510 pub fn jsonStringify(
2498 value: Self,2511 value: Self,
2499 options: StringifyOptions,2512 options: StringifyOptions,
2500 context: var,2513 out_stream: var,
2501 comptime Errors: type,
2502 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
2503 ) !void {2514 ) !void {
2504 try output(context, "[\"something special\",");2515 try out_stream.writeAll("[\"something special\",");
2505 try stringify(42, options, context, Errors, output);2516 try stringify(42, options, out_stream);
2506 try output(context, "]");2517 try out_stream.writeAll("]");
2507 }2518 }
2508 }{ .foo = 42 });2519 }{ .foo = 42 });
2509}2520}
lib/std/json/write_stream.zig+26-19
...@@ -30,11 +30,11 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -30,11 +30,11 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
30 /// The string used as spacing.30 /// The string used as spacing.
31 space: []const u8 = " ",31 space: []const u8 = " ",
3232
33 stream: *OutStream,33 stream: OutStream,
34 state_index: usize,34 state_index: usize,
35 state: [max_depth]State,35 state: [max_depth]State,
3636
37 pub fn init(stream: *OutStream) Self {37 pub fn init(stream: OutStream) Self {
38 var self = Self{38 var self = Self{
39 .stream = stream,39 .stream = stream,
40 .state_index = 1,40 .state_index = 1,
...@@ -90,8 +90,8 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -90,8 +90,8 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
90 self.pushState(.Value);90 self.pushState(.Value);
91 try self.indent();91 try self.indent();
92 try self.writeEscapedString(name);92 try self.writeEscapedString(name);
93 try self.stream.write(":");93 try self.stream.writeAll(":");
94 try self.stream.write(self.space);94 try self.stream.writeAll(self.space);
95 },95 },
96 }96 }
97 }97 }
...@@ -134,16 +134,16 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -134,16 +134,16 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
134134
135 pub fn emitNull(self: *Self) !void {135 pub fn emitNull(self: *Self) !void {
136 assert(self.state[self.state_index] == State.Value);136 assert(self.state[self.state_index] == State.Value);
137 try self.stream.write("null");137 try self.stream.writeAll("null");
138 self.popState();138 self.popState();
139 }139 }
140140
141 pub fn emitBool(self: *Self, value: bool) !void {141 pub fn emitBool(self: *Self, value: bool) !void {
142 assert(self.state[self.state_index] == State.Value);142 assert(self.state[self.state_index] == State.Value);
143 if (value) {143 if (value) {
144 try self.stream.write("true");144 try self.stream.writeAll("true");
145 } else {145 } else {
146 try self.stream.write("false");146 try self.stream.writeAll("false");
147 }147 }
148 self.popState();148 self.popState();
149 }149 }
...@@ -188,13 +188,13 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -188,13 +188,13 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
188 try self.stream.writeByte('"');188 try self.stream.writeByte('"');
189 for (string) |s| {189 for (string) |s| {
190 switch (s) {190 switch (s) {
191 '"' => try self.stream.write("\\\""),191 '"' => try self.stream.writeAll("\\\""),
192 '\t' => try self.stream.write("\\t"),192 '\t' => try self.stream.writeAll("\\t"),
193 '\r' => try self.stream.write("\\r"),193 '\r' => try self.stream.writeAll("\\r"),
194 '\n' => try self.stream.write("\\n"),194 '\n' => try self.stream.writeAll("\\n"),
195 8 => try self.stream.write("\\b"),195 8 => try self.stream.writeAll("\\b"),
196 12 => try self.stream.write("\\f"),196 12 => try self.stream.writeAll("\\f"),
197 '\\' => try self.stream.write("\\\\"),197 '\\' => try self.stream.writeAll("\\\\"),
198 else => try self.stream.writeByte(s),198 else => try self.stream.writeByte(s),
199 }199 }
200 }200 }
...@@ -231,10 +231,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -231,10 +231,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
231231
232 fn indent(self: *Self) !void {232 fn indent(self: *Self) !void {
233 assert(self.state_index >= 1);233 assert(self.state_index >= 1);
234 try self.stream.write(self.newline);234 try self.stream.writeAll(self.newline);
235 var i: usize = 0;235 var i: usize = 0;
236 while (i < self.state_index - 1) : (i += 1) {236 while (i < self.state_index - 1) : (i += 1) {
237 try self.stream.write(self.one_indent);237 try self.stream.writeAll(self.one_indent);
238 }238 }
239 }239 }
240240
...@@ -249,15 +249,22 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {...@@ -249,15 +249,22 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
249 };249 };
250}250}
251251
252pub fn writeStream(
253 out_stream: var,
254 comptime max_depth: usize,
255) WriteStream(@TypeOf(out_stream), max_depth) {
256 return WriteStream(@TypeOf(out_stream), max_depth).init(out_stream);
257}
258
252test "json write stream" {259test "json write stream" {
253 var out_buf: [1024]u8 = undefined;260 var out_buf: [1024]u8 = undefined;
254 var slice_stream = std.io.SliceOutStream.init(&out_buf);261 var slice_stream = std.io.fixedBufferStream(&out_buf);
255 const out = &slice_stream.stream;262 const out = slice_stream.outStream();
256263
257 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);264 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
258 defer arena_allocator.deinit();265 defer arena_allocator.deinit();
259266
260 var w = std.json.WriteStream(@TypeOf(out).Child, 10).init(out);267 var w = std.json.writeStream(out, 10);
261 try w.emitJson(try getJson(&arena_allocator.allocator));268 try w.emitJson(try getJson(&arena_allocator.allocator));
262269
263 const result = slice_stream.getWritten();270 const result = slice_stream.getWritten();
lib/std/math/big/int.zig+2-4
...@@ -519,16 +519,14 @@ pub const Int = struct {...@@ -519,16 +519,14 @@ pub const Int = struct {
519 self: Int,519 self: Int,
520 comptime fmt: []const u8,520 comptime fmt: []const u8,
521 options: std.fmt.FormatOptions,521 options: std.fmt.FormatOptions,
522 context: var,522 out_stream: var,
523 comptime FmtError: type,
524 output: fn (@TypeOf(context), []const u8) FmtError!void,
525 ) FmtError!void {523 ) FmtError!void {
526 self.assertWritable();524 self.assertWritable();
527 // TODO look at fmt and support other bases525 // TODO look at fmt and support other bases
528 // TODO support read-only fixed integers526 // TODO support read-only fixed integers
529 const str = self.toString(self.allocator.?, 10) catch @panic("TODO make this non allocating");527 const str = self.toString(self.allocator.?, 10) catch @panic("TODO make this non allocating");
530 defer self.allocator.?.free(str);528 defer self.allocator.?.free(str);
531 return output(context, str);529 return out_stream.print(str);
532 }530 }
533531
534 /// Returns -1, 0, 1 if |a| < |b|, |a| == |b| or |a| > |b| respectively.532 /// Returns -1, 0, 1 if |a| < |b|, |a| == |b| or |a| > |b| respectively.
lib/std/mem.zig+21-1
...@@ -105,6 +105,20 @@ pub const Allocator = struct {...@@ -105,6 +105,20 @@ pub const Allocator = struct {
105 return self.alignedAlloc(T, null, n);105 return self.alignedAlloc(T, null, n);
106 }106 }
107107
108 /// Allocates an array of `n + 1` items of type `T` and sets the first `n`
109 /// items to `undefined` and the last item to `sentinel`. Depending on the
110 /// Allocator implementation, it may be required to call `free` once the
111 /// memory is no longer needed, to avoid a resource leak. If the
112 /// `Allocator` implementation is unknown, then correct code will
113 /// call `free` when done.
114 ///
115 /// For allocating a single item, see `create`.
116 pub fn allocSentinel(self: *Allocator, comptime Elem: type, n: usize, comptime sentinel: Elem) Error![:sentinel]Elem {
117 var ptr = try self.alloc(Elem, n + 1);
118 ptr[n] = sentinel;
119 return ptr[0 .. n :sentinel];
120 }
121
108 pub fn alignedAlloc(122 pub fn alignedAlloc(
109 self: *Allocator,123 self: *Allocator,
110 comptime T: type,124 comptime T: type,
...@@ -921,6 +935,9 @@ pub fn writeInt(comptime T: type, buffer: *[@divExact(T.bit_count, 8)]u8, value:...@@ -921,6 +935,9 @@ pub fn writeInt(comptime T: type, buffer: *[@divExact(T.bit_count, 8)]u8, value:
921pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {935pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {
922 assert(buffer.len >= @divExact(T.bit_count, 8));936 assert(buffer.len >= @divExact(T.bit_count, 8));
923937
938 if (T.bit_count == 0)
939 return set(u8, buffer, 0);
940
924 // TODO I want to call writeIntLittle here but comptime eval facilities aren't good enough941 // TODO I want to call writeIntLittle here but comptime eval facilities aren't good enough
925 const uint = std.meta.IntType(false, T.bit_count);942 const uint = std.meta.IntType(false, T.bit_count);
926 var bits = @truncate(uint, value);943 var bits = @truncate(uint, value);
...@@ -938,6 +955,9 @@ pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {...@@ -938,6 +955,9 @@ pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {
938pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {955pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {
939 assert(buffer.len >= @divExact(T.bit_count, 8));956 assert(buffer.len >= @divExact(T.bit_count, 8));
940957
958 if (T.bit_count == 0)
959 return set(u8, buffer, 0);
960
941 // TODO I want to call writeIntBig here but comptime eval facilities aren't good enough961 // TODO I want to call writeIntBig here but comptime eval facilities aren't good enough
942 const uint = std.meta.IntType(false, T.bit_count);962 const uint = std.meta.IntType(false, T.bit_count);
943 var bits = @truncate(uint, value);963 var bits = @truncate(uint, value);
...@@ -1807,7 +1827,7 @@ test "sliceAsBytes" {...@@ -1807,7 +1827,7 @@ test "sliceAsBytes" {
1807}1827}
18081828
1809test "sliceAsBytes with sentinel slice" {1829test "sliceAsBytes with sentinel slice" {
1810 const empty_string:[:0]const u8 = "";1830 const empty_string: [:0]const u8 = "";
1811 const bytes = sliceAsBytes(empty_string);1831 const bytes = sliceAsBytes(empty_string);
1812 testing.expect(bytes.len == 0);1832 testing.expect(bytes.len == 0);
1813}1833}
lib/std/net.zig+11-13
...@@ -269,15 +269,13 @@ pub const Address = extern union {...@@ -269,15 +269,13 @@ pub const Address = extern union {
269 self: Address,269 self: Address,
270 comptime fmt: []const u8,270 comptime fmt: []const u8,
271 options: std.fmt.FormatOptions,271 options: std.fmt.FormatOptions,
272 context: var,272 out_stream: var,
273 comptime Errors: type,
274 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
275 ) !void {273 ) !void {
276 switch (self.any.family) {274 switch (self.any.family) {
277 os.AF_INET => {275 os.AF_INET => {
278 const port = mem.bigToNative(u16, self.in.port);276 const port = mem.bigToNative(u16, self.in.port);
279 const bytes = @ptrCast(*const [4]u8, &self.in.addr);277 const bytes = @ptrCast(*const [4]u8, &self.in.addr);
280 try std.fmt.format(context, Errors, output, "{}.{}.{}.{}:{}", .{278 try std.fmt.format(out_stream, "{}.{}.{}.{}:{}", .{
281 bytes[0],279 bytes[0],
282 bytes[1],280 bytes[1],
283 bytes[2],281 bytes[2],
...@@ -288,7 +286,7 @@ pub const Address = extern union {...@@ -288,7 +286,7 @@ pub const Address = extern union {
288 os.AF_INET6 => {286 os.AF_INET6 => {
289 const port = mem.bigToNative(u16, self.in6.port);287 const port = mem.bigToNative(u16, self.in6.port);
290 if (mem.eql(u8, self.in6.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {288 if (mem.eql(u8, self.in6.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) {
291 try std.fmt.format(context, Errors, output, "[::ffff:{}.{}.{}.{}]:{}", .{289 try std.fmt.format(out_stream, "[::ffff:{}.{}.{}.{}]:{}", .{
292 self.in6.addr[12],290 self.in6.addr[12],
293 self.in6.addr[13],291 self.in6.addr[13],
294 self.in6.addr[14],292 self.in6.addr[14],
...@@ -308,30 +306,30 @@ pub const Address = extern union {...@@ -308,30 +306,30 @@ pub const Address = extern union {
308 break :blk buf;306 break :blk buf;
309 },307 },
310 };308 };
311 try output(context, "[");309 try out_stream.writeAll("[");
312 var i: usize = 0;310 var i: usize = 0;
313 var abbrv = false;311 var abbrv = false;
314 while (i < native_endian_parts.len) : (i += 1) {312 while (i < native_endian_parts.len) : (i += 1) {
315 if (native_endian_parts[i] == 0) {313 if (native_endian_parts[i] == 0) {
316 if (!abbrv) {314 if (!abbrv) {
317 try output(context, if (i == 0) "::" else ":");315 try out_stream.writeAll(if (i == 0) "::" else ":");
318 abbrv = true;316 abbrv = true;
319 }317 }
320 continue;318 continue;
321 }319 }
322 try std.fmt.format(context, Errors, output, "{x}", .{native_endian_parts[i]});320 try std.fmt.format(out_stream, "{x}", .{native_endian_parts[i]});
323 if (i != native_endian_parts.len - 1) {321 if (i != native_endian_parts.len - 1) {
324 try output(context, ":");322 try out_stream.writeAll(":");
325 }323 }
326 }324 }
327 try std.fmt.format(context, Errors, output, "]:{}", .{port});325 try std.fmt.format(out_stream, "]:{}", .{port});
328 },326 },
329 os.AF_UNIX => {327 os.AF_UNIX => {
330 if (!has_unix_sockets) {328 if (!has_unix_sockets) {
331 unreachable;329 unreachable;
332 }330 }
333331
334 try std.fmt.format(context, Errors, output, "{}", .{&self.un.path});332 try std.fmt.format(out_stream, "{}", .{&self.un.path});
335 },333 },
336 else => unreachable,334 else => unreachable,
337 }335 }
...@@ -816,7 +814,7 @@ fn linuxLookupNameFromHosts(...@@ -816,7 +814,7 @@ fn linuxLookupNameFromHosts(
816 };814 };
817 defer file.close();815 defer file.close();
818816
819 const stream = &std.io.BufferedInStream(fs.File.ReadError).init(&file.inStream().stream).stream;817 const stream = std.io.bufferedInStream(file.inStream()).inStream();
820 var line_buf: [512]u8 = undefined;818 var line_buf: [512]u8 = undefined;
821 while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) {819 while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) {
822 error.StreamTooLong => blk: {820 error.StreamTooLong => blk: {
...@@ -1010,7 +1008,7 @@ fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void {...@@ -1010,7 +1008,7 @@ fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void {
1010 };1008 };
1011 defer file.close();1009 defer file.close();
10121010
1013 const stream = &std.io.BufferedInStream(fs.File.ReadError).init(&file.inStream().stream).stream;1011 const stream = std.io.bufferedInStream(file.inStream()).inStream();
1014 var line_buf: [512]u8 = undefined;1012 var line_buf: [512]u8 = undefined;
1015 while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) {1013 while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) {
1016 error.StreamTooLong => blk: {1014 error.StreamTooLong => blk: {
lib/std/net/test.zig+1-1
...@@ -113,6 +113,6 @@ fn testClient(addr: net.Address) anyerror!void {...@@ -113,6 +113,6 @@ fn testClient(addr: net.Address) anyerror!void {
113fn testServer(server: *net.StreamServer) anyerror!void {113fn testServer(server: *net.StreamServer) anyerror!void {
114 var client = try server.accept();114 var client = try server.accept();
115115
116 const stream = &client.file.outStream().stream;116 const stream = client.file.outStream();
117 try stream.print("hello from server\n", .{});117 try stream.print("hello from server\n", .{});
118}118}
lib/std/os.zig+59-4
...@@ -176,7 +176,7 @@ fn getRandomBytesDevURandom(buf: []u8) !void {...@@ -176,7 +176,7 @@ fn getRandomBytesDevURandom(buf: []u8) !void {
176 .io_mode = .blocking,176 .io_mode = .blocking,
177 .async_block_allowed = std.fs.File.async_block_allowed_yes,177 .async_block_allowed = std.fs.File.async_block_allowed_yes,
178 };178 };
179 const stream = &file.inStream().stream;179 const stream = file.inStream();
180 stream.readNoEof(buf) catch return error.Unexpected;180 stream.readNoEof(buf) catch return error.Unexpected;
181}181}
182182
...@@ -273,10 +273,10 @@ pub fn exit(status: u8) noreturn {...@@ -273,10 +273,10 @@ pub fn exit(status: u8) noreturn {
273 // exit() is only avaliable if exitBootServices() has not been called yet.273 // exit() is only avaliable if exitBootServices() has not been called yet.
274 // This call to exit should not fail, so we don't care about its return value.274 // This call to exit should not fail, so we don't care about its return value.
275 if (uefi.system_table.boot_services) |bs| {275 if (uefi.system_table.boot_services) |bs| {
276 _ = bs.exit(uefi.handle, status, 0, null);276 _ = bs.exit(uefi.handle, @intToEnum(uefi.Status, status), 0, null);
277 }277 }
278 // If we can't exit, reboot the system instead.278 // If we can't exit, reboot the system instead.
279 uefi.system_table.runtime_services.resetSystem(uefi.tables.ResetType.ResetCold, status, 0, null);279 uefi.system_table.runtime_services.resetSystem(uefi.tables.ResetType.ResetCold, @intToEnum(uefi.Status, status), 0, null);
280 }280 }
281 system.exit(status);281 system.exit(status);
282}282}
...@@ -438,6 +438,61 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {...@@ -438,6 +438,61 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
438 return index;438 return index;
439}439}
440440
441pub const TruncateError = error{
442 FileTooBig,
443 InputOutput,
444 CannotTruncate,
445 FileBusy,
446} || UnexpectedError;
447
448pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
449 if (std.Target.current.os.tag == .windows) {
450 var io_status_block: windows.IO_STATUS_BLOCK = undefined;
451 var eof_info = windows.FILE_END_OF_FILE_INFORMATION{
452 .EndOfFile = @bitCast(windows.LARGE_INTEGER, length),
453 };
454
455 const rc = windows.ntdll.NtSetInformationFile(
456 fd,
457 &io_status_block,
458 &eof_info,
459 @sizeOf(windows.FILE_END_OF_FILE_INFORMATION),
460 .FileEndOfFileInformation,
461 );
462
463 switch (rc) {
464 .SUCCESS => {},
465 .INVALID_HANDLE => unreachable, // Handle not open for writing
466 .ACCESS_DENIED => return error.CannotTruncate,
467 else => return windows.unexpectedStatus(rc),
468 }
469
470 return;
471 }
472
473 while (true) {
474 const rc = if (builtin.link_libc)
475 if (std.Target.current.os.tag == .linux)
476 system.ftruncate64(fd, @bitCast(off_t, length))
477 else
478 system.ftruncate(fd, @bitCast(off_t, length))
479 else
480 system.ftruncate(fd, length);
481
482 switch (errno(rc)) {
483 0 => return,
484 EINTR => continue,
485 EFBIG => return error.FileTooBig,
486 EIO => return error.InputOutput,
487 EPERM => return error.CannotTruncate,
488 ETXTBSY => return error.FileBusy,
489 EBADF => unreachable, // Handle not open for writing
490 EINVAL => unreachable, // Handle not open for writing
491 else => |err| return unexpectedErrno(err),
492 }
493 }
494}
495
441/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.496/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
442///497///
443/// Retries when interrupted by a signal.498/// Retries when interrupted by a signal.
...@@ -3077,7 +3132,7 @@ pub fn realpathW(pathname: [*:0]const u16, out_buffer: *[MAX_PATH_BYTES]u8) Real...@@ -3077,7 +3132,7 @@ pub fn realpathW(pathname: [*:0]const u16, out_buffer: *[MAX_PATH_BYTES]u8) Real
3077 windows.FILE_SHARE_READ,3132 windows.FILE_SHARE_READ,
3078 null,3133 null,
3079 windows.OPEN_EXISTING,3134 windows.OPEN_EXISTING,
3080 windows.FILE_ATTRIBUTE_NORMAL,3135 windows.FILE_FLAG_BACKUP_SEMANTICS,
3081 null,3136 null,
3082 );3137 );
3083 defer windows.CloseHandle(h_file);3138 defer windows.CloseHandle(h_file);
lib/std/os/bits/darwin.zig+2-1
...@@ -53,6 +53,7 @@ pub const mach_timebase_info_data = extern struct {...@@ -53,6 +53,7 @@ pub const mach_timebase_info_data = extern struct {
53};53};
5454
55pub const off_t = i64;55pub const off_t = i64;
56pub const ino_t = u64;
5657
57/// Renamed to Stat to not conflict with the stat function.58/// Renamed to Stat to not conflict with the stat function.
58/// atime, mtime, and ctime have functions to return `timespec`,59/// atime, mtime, and ctime have functions to return `timespec`,
...@@ -64,7 +65,7 @@ pub const Stat = extern struct {...@@ -64,7 +65,7 @@ pub const Stat = extern struct {
64 dev: i32,65 dev: i32,
65 mode: u16,66 mode: u16,
66 nlink: u16,67 nlink: u16,
67 ino: u64,68 ino: ino_t,
68 uid: u32,69 uid: u32,
69 gid: u32,70 gid: u32,
70 rdev: i32,71 rdev: i32,
lib/std/os/bits/dragonfly.zig+3-1
...@@ -138,8 +138,10 @@ pub const MAP_SIZEALIGN = 262144;...@@ -138,8 +138,10 @@ pub const MAP_SIZEALIGN = 262144;
138138
139pub const PATH_MAX = 1024;139pub const PATH_MAX = 1024;
140140
141pub const ino_t = c_ulong;
142
141pub const Stat = extern struct {143pub const Stat = extern struct {
142 ino: c_ulong,144 ino: ino_t,
143 nlink: c_uint,145 nlink: c_uint,
144 dev: c_uint,146 dev: c_uint,
145 mode: c_ushort,147 mode: c_ushort,
lib/std/os/bits/freebsd.zig+2-1
...@@ -98,6 +98,7 @@ pub const msghdr_const = extern struct {...@@ -98,6 +98,7 @@ pub const msghdr_const = extern struct {
98};98};
9999
100pub const off_t = i64;100pub const off_t = i64;
101pub const ino_t = u64;
101102
102/// Renamed to Stat to not conflict with the stat function.103/// Renamed to Stat to not conflict with the stat function.
103/// atime, mtime, and ctime have functions to return `timespec`,104/// atime, mtime, and ctime have functions to return `timespec`,
...@@ -107,7 +108,7 @@ pub const off_t = i64;...@@ -107,7 +108,7 @@ pub const off_t = i64;
107/// methods to accomplish this.108/// methods to accomplish this.
108pub const Stat = extern struct {109pub const Stat = extern struct {
109 dev: u64,110 dev: u64,
110 ino: u64,111 ino: ino_t,
111 nlink: usize,112 nlink: usize,
112113
113 mode: u16,114 mode: u16,
lib/std/os/bits/linux.zig+12-6
...@@ -18,6 +18,8 @@ pub usingnamespace switch (builtin.arch) {...@@ -18,6 +18,8 @@ pub usingnamespace switch (builtin.arch) {
18 else => struct {},18 else => struct {},
19};19};
2020
21pub usingnamespace @import("linux/netlink.zig");
22
21const is_mips = builtin.arch.isMIPS();23const is_mips = builtin.arch.isMIPS();
2224
23pub const pid_t = i32;25pub const pid_t = i32;
...@@ -30,6 +32,10 @@ pub const NAME_MAX = 255;...@@ -30,6 +32,10 @@ pub const NAME_MAX = 255;
30pub const PATH_MAX = 4096;32pub const PATH_MAX = 4096;
31pub const IOV_MAX = 1024;33pub const IOV_MAX = 1024;
3234
35/// Largest hardware address length
36/// e.g. a mac address is a type of hardware address
37pub const MAX_ADDR_LEN = 32;
38
33pub const STDIN_FILENO = 0;39pub const STDIN_FILENO = 0;
34pub const STDOUT_FILENO = 1;40pub const STDOUT_FILENO = 1;
35pub const STDERR_FILENO = 2;41pub const STDERR_FILENO = 2;
...@@ -1290,12 +1296,12 @@ pub const io_uring_files_update = struct {...@@ -1290,12 +1296,12 @@ pub const io_uring_files_update = struct {
1290};1296};
12911297
1292pub const utsname = extern struct {1298pub const utsname = extern struct {
1293 sysname: [65]u8,1299 sysname: [64:0]u8,
1294 nodename: [65]u8,1300 nodename: [64:0]u8,
1295 release: [65]u8,1301 release: [64:0]u8,
1296 version: [65]u8,1302 version: [64:0]u8,
1297 machine: [65]u8,1303 machine: [64:0]u8,
1298 domainname: [65]u8,1304 domainname: [64:0]u8,
1299};1305};
1300pub const HOST_NAME_MAX = 64;1306pub const HOST_NAME_MAX = 64;
13011307
lib/std/os/bits/linux/netlink.zig created+498
...@@ -0,0 +1,498 @@
1usingnamespace @import("../linux.zig");
2
3/// Routing/device hook
4pub const NETLINK_ROUTE = 0;
5
6/// Unused number
7pub const NETLINK_UNUSED = 1;
8
9/// Reserved for user mode socket protocols
10pub const NETLINK_USERSOCK = 2;
11
12/// Unused number, formerly ip_queue
13pub const NETLINK_FIREWALL = 3;
14
15/// socket monitoring
16pub const NETLINK_SOCK_DIAG = 4;
17
18/// netfilter/iptables ULOG
19pub const NETLINK_NFLOG = 5;
20
21/// ipsec
22pub const NETLINK_XFRM = 6;
23
24/// SELinux event notifications
25pub const NETLINK_SELINUX = 7;
26
27/// Open-iSCSI
28pub const NETLINK_ISCSI = 8;
29
30/// auditing
31pub const NETLINK_AUDIT = 9;
32
33pub const NETLINK_FIB_LOOKUP = 10;
34
35pub const NETLINK_CONNECTOR = 11;
36
37/// netfilter subsystem
38pub const NETLINK_NETFILTER = 12;
39
40pub const NETLINK_IP6_FW = 13;
41
42/// DECnet routing messages
43pub const NETLINK_DNRTMSG = 14;
44
45/// Kernel messages to userspace
46pub const NETLINK_KOBJECT_UEVENT = 15;
47
48pub const NETLINK_GENERIC = 16;
49
50// leave room for NETLINK_DM (DM Events)
51
52/// SCSI Transports
53pub const NETLINK_SCSITRANSPORT = 18;
54
55pub const NETLINK_ECRYPTFS = 19;
56
57pub const NETLINK_RDMA = 20;
58
59/// Crypto layer
60pub const NETLINK_CRYPTO = 21;
61
62/// SMC monitoring
63pub const NETLINK_SMC = 22;
64
65// Flags values
66
67/// It is request message.
68pub const NLM_F_REQUEST = 0x01;
69
70/// Multipart message, terminated by NLMSG_DONE
71pub const NLM_F_MULTI = 0x02;
72
73/// Reply with ack, with zero or error code
74pub const NLM_F_ACK = 0x04;
75
76/// Echo this request
77pub const NLM_F_ECHO = 0x08;
78
79/// Dump was inconsistent due to sequence change
80pub const NLM_F_DUMP_INTR = 0x10;
81
82/// Dump was filtered as requested
83pub const NLM_F_DUMP_FILTERED = 0x20;
84
85// Modifiers to GET request
86
87/// specify tree root
88pub const NLM_F_ROOT = 0x100;
89
90/// return all matching
91pub const NLM_F_MATCH = 0x200;
92
93/// atomic GET
94pub const NLM_F_ATOMIC = 0x400;
95pub const NLM_F_DUMP = NLM_F_ROOT | NLM_F_MATCH;
96
97// Modifiers to NEW request
98
99/// Override existing
100pub const NLM_F_REPLACE = 0x100;
101
102/// Do not touch, if it exists
103pub const NLM_F_EXCL = 0x200;
104
105/// Create, if it does not exist
106pub const NLM_F_CREATE = 0x400;
107
108/// Add to end of list
109pub const NLM_F_APPEND = 0x800;
110
111// Modifiers to DELETE request
112
113/// Do not delete recursively
114pub const NLM_F_NONREC = 0x100;
115
116// Flags for ACK message
117
118/// request was capped
119pub const NLM_F_CAPPED = 0x100;
120
121/// extended ACK TVLs were included
122pub const NLM_F_ACK_TLVS = 0x200;
123
124pub const NetlinkMessageType = extern enum(u16) {
125 /// Nothing.
126 NOOP = 0x1,
127
128 /// Error
129 ERROR = 0x2,
130
131 /// End of a dump
132 DONE = 0x3,
133
134 /// Data lost
135 OVERRUN = 0x4,
136
137 /// < 0x10: reserved control messages
138 pub const MIN_TYPE = 0x10;
139
140 // rtlink types
141
142 RTM_NEWLINK = 16,
143 RTM_DELLINK,
144 RTM_GETLINK,
145 RTM_SETLINK,
146
147 RTM_NEWADDR = 20,
148 RTM_DELADDR,
149 RTM_GETADDR,
150
151 RTM_NEWROUTE = 24,
152 RTM_DELROUTE,
153 RTM_GETROUTE,
154
155 RTM_NEWNEIGH = 28,
156 RTM_DELNEIGH,
157 RTM_GETNEIGH,
158
159 RTM_NEWRULE = 32,
160 RTM_DELRULE,
161 RTM_GETRULE,
162
163 RTM_NEWQDISC = 36,
164 RTM_DELQDISC,
165 RTM_GETQDISC,
166
167 RTM_NEWTCLASS = 40,
168 RTM_DELTCLASS,
169 RTM_GETTCLASS,
170
171 RTM_NEWTFILTER = 44,
172 RTM_DELTFILTER,
173 RTM_GETTFILTER,
174
175 RTM_NEWACTION = 48,
176 RTM_DELACTION,
177 RTM_GETACTION,
178
179 RTM_NEWPREFIX = 52,
180
181 RTM_GETMULTICAST = 58,
182
183 RTM_GETANYCAST = 62,
184
185 RTM_NEWNEIGHTBL = 64,
186 RTM_GETNEIGHTBL = 66,
187 RTM_SETNEIGHTBL,
188
189 RTM_NEWNDUSEROPT = 68,
190
191 RTM_NEWADDRLABEL = 72,
192 RTM_DELADDRLABEL,
193 RTM_GETADDRLABEL,
194
195 RTM_GETDCB = 78,
196 RTM_SETDCB,
197
198 RTM_NEWNETCONF = 80,
199 RTM_DELNETCONF,
200 RTM_GETNETCONF = 82,
201
202 RTM_NEWMDB = 84,
203 RTM_DELMDB = 85,
204 RTM_GETMDB = 86,
205
206 RTM_NEWNSID = 88,
207 RTM_DELNSID = 89,
208 RTM_GETNSID = 90,
209
210 RTM_NEWSTATS = 92,
211 RTM_GETSTATS = 94,
212
213 RTM_NEWCACHEREPORT = 96,
214
215 RTM_NEWCHAIN = 100,
216 RTM_DELCHAIN,
217 RTM_GETCHAIN,
218
219 RTM_NEWNEXTHOP = 104,
220 RTM_DELNEXTHOP,
221 RTM_GETNEXTHOP,
222
223 _,
224};
225
226/// Netlink socket address
227pub const sockaddr_nl = extern struct {
228 family: sa_family_t = AF_NETLINK,
229 __pad1: c_ushort = 0,
230
231 /// port ID
232 pid: u32,
233
234 /// multicast groups mask
235 groups: u32,
236};
237
238/// Netlink message header
239/// Specified in RFC 3549 Section 2.3.2
240pub const nlmsghdr = extern struct {
241 /// Length of message including header
242 len: u32,
243
244 /// Message content
245 @"type": NetlinkMessageType,
246
247 /// Additional flags
248 flags: u16,
249
250 /// Sequence number
251 seq: u32,
252
253 /// Sending process port ID
254 pid: u32,
255};
256
257pub const ifinfomsg = extern struct {
258 family: u8,
259 __pad1: u8 = 0,
260
261 /// ARPHRD_*
262 @"type": c_ushort,
263
264 /// Link index
265 index: c_int,
266
267 /// IFF_* flags
268 flags: c_uint,
269
270 /// IFF_* change mask
271 /// is reserved for future use and should be always set to 0xFFFFFFFF.
272 change: c_uint = 0xFFFFFFFF,
273};
274
275pub const rtattr = extern struct {
276 /// Length of option
277 len: c_ushort,
278
279 /// Type of option
280 @"type": IFLA,
281
282 pub const ALIGNTO = 4;
283};
284
285pub const IFLA = extern enum(c_ushort) {
286 UNSPEC,
287 ADDRESS,
288 BROADCAST,
289 IFNAME,
290 MTU,
291 LINK,
292 QDISC,
293 STATS,
294 COST,
295 PRIORITY,
296 MASTER,
297
298 /// Wireless Extension event
299 WIRELESS,
300
301 /// Protocol specific information for a link
302 PROTINFO,
303
304 TXQLEN,
305 MAP,
306 WEIGHT,
307 OPERSTATE,
308 LINKMODE,
309 LINKINFO,
310 NET_NS_PID,
311 IFALIAS,
312
313 /// Number of VFs if device is SR-IOV PF
314 NUM_VF,
315
316 VFINFO_LIST,
317 STATS64,
318 VF_PORTS,
319 PORT_SELF,
320 AF_SPEC,
321
322 /// Group the device belongs to
323 GROUP,
324
325 NET_NS_FD,
326
327 /// Extended info mask, VFs, etc
328 EXT_MASK,
329
330 /// Promiscuity count: > 0 means acts PROMISC
331 PROMISCUITY,
332
333 NUM_TX_QUEUES,
334 NUM_RX_QUEUES,
335 CARRIER,
336 PHYS_PORT_ID,
337 CARRIER_CHANGES,
338 PHYS_SWITCH_ID,
339 LINK_NETNSID,
340 PHYS_PORT_NAME,
341 PROTO_DOWN,
342 GSO_MAX_SEGS,
343 GSO_MAX_SIZE,
344 PAD,
345 XDP,
346 EVENT,
347
348 NEW_NETNSID,
349 IF_NETNSID = 46,
350 TARGET_NETNSID = 46, // new alias
351
352 CARRIER_UP_COUNT,
353 CARRIER_DOWN_COUNT,
354 NEW_IFINDEX,
355 MIN_MTU,
356 MAX_MTU,
357
358 _,
359};
360
361pub const rtnl_link_ifmap = extern struct {
362 mem_start: u64,
363 mem_end: u64,
364 base_addr: u64,
365 irq: u16,
366 dma: u8,
367 port: u8,
368};
369
370pub const rtnl_link_stats = extern struct {
371 /// total packets received
372 rx_packets: u32,
373
374 /// total packets transmitted
375 tx_packets: u32,
376
377 /// total bytes received
378 rx_bytes: u32,
379
380 /// total bytes transmitted
381 tx_bytes: u32,
382
383 /// bad packets received
384 rx_errors: u32,
385
386 /// packet transmit problems
387 tx_errors: u32,
388
389 /// no space in linux buffers
390 rx_dropped: u32,
391
392 /// no space available in linux
393 tx_dropped: u32,
394
395 /// multicast packets received
396 multicast: u32,
397
398 collisions: u32,
399
400 // detailed rx_errors
401
402 rx_length_errors: u32,
403
404 /// receiver ring buff overflow
405 rx_over_errors: u32,
406
407 /// recved pkt with crc error
408 rx_crc_errors: u32,
409
410 /// recv'd frame alignment error
411 rx_frame_errors: u32,
412
413 /// recv'r fifo overrun
414 rx_fifo_errors: u32,
415
416 /// receiver missed packet
417 rx_missed_errors: u32,
418
419 // detailed tx_errors
420 tx_aborted_errors: u32,
421 tx_carrier_errors: u32,
422 tx_fifo_errors: u32,
423 tx_heartbeat_errors: u32,
424 tx_window_errors: u32,
425
426 // for cslip etc
427
428 rx_compressed: u32,
429 tx_compressed: u32,
430
431 /// dropped, no handler found
432 rx_nohandler: u32,
433};
434
435pub const rtnl_link_stats64 = extern struct {
436 /// total packets received
437 rx_packets: u64,
438
439 /// total packets transmitted
440 tx_packets: u64,
441
442 /// total bytes received
443 rx_bytes: u64,
444
445 /// total bytes transmitted
446 tx_bytes: u64,
447
448 /// bad packets received
449 rx_errors: u64,
450
451 /// packet transmit problems
452 tx_errors: u64,
453
454 /// no space in linux buffers
455 rx_dropped: u64,
456
457 /// no space available in linux
458 tx_dropped: u64,
459
460 /// multicast packets received
461 multicast: u64,
462
463 collisions: u64,
464
465 // detailed rx_errors
466
467 rx_length_errors: u64,
468
469 /// receiver ring buff overflow
470 rx_over_errors: u64,
471
472 /// recved pkt with crc error
473 rx_crc_errors: u64,
474
475 /// recv'd frame alignment error
476 rx_frame_errors: u64,
477
478 /// recv'r fifo overrun
479 rx_fifo_errors: u64,
480
481 /// receiver missed packet
482 rx_missed_errors: u64,
483
484 // detailed tx_errors
485 tx_aborted_errors: u64,
486 tx_carrier_errors: u64,
487 tx_fifo_errors: u64,
488 tx_heartbeat_errors: u64,
489 tx_window_errors: u64,
490
491 // for cslip etc
492
493 rx_compressed: u64,
494 tx_compressed: u64,
495
496 /// dropped, no handler found
497 rx_nohandler: u64,
498};
lib/std/os/bits/linux/x86_64.zig+2-1
...@@ -481,6 +481,7 @@ pub const msghdr_const = extern struct {...@@ -481,6 +481,7 @@ pub const msghdr_const = extern struct {
481};481};
482482
483pub const off_t = i64;483pub const off_t = i64;
484pub const ino_t = u64;
484485
485/// Renamed to Stat to not conflict with the stat function.486/// Renamed to Stat to not conflict with the stat function.
486/// atime, mtime, and ctime have functions to return `timespec`,487/// atime, mtime, and ctime have functions to return `timespec`,
...@@ -490,7 +491,7 @@ pub const off_t = i64;...@@ -490,7 +491,7 @@ pub const off_t = i64;
490/// methods to accomplish this.491/// methods to accomplish this.
491pub const Stat = extern struct {492pub const Stat = extern struct {
492 dev: u64,493 dev: u64,
493 ino: u64,494 ino: ino_t,
494 nlink: usize,495 nlink: usize,
495496
496 mode: u32,497 mode: u32,
lib/std/os/bits/netbsd.zig+2-1
...@@ -69,6 +69,7 @@ pub const msghdr_const = extern struct {...@@ -69,6 +69,7 @@ pub const msghdr_const = extern struct {
69};69};
7070
71pub const off_t = i64;71pub const off_t = i64;
72pub const ino_t = u64;
7273
73/// Renamed to Stat to not conflict with the stat function.74/// Renamed to Stat to not conflict with the stat function.
74/// atime, mtime, and ctime have functions to return `timespec`,75/// atime, mtime, and ctime have functions to return `timespec`,
...@@ -79,7 +80,7 @@ pub const off_t = i64;...@@ -79,7 +80,7 @@ pub const off_t = i64;
79pub const Stat = extern struct {80pub const Stat = extern struct {
80 dev: u64,81 dev: u64,
81 mode: u32,82 mode: u32,
82 ino: u64,83 ino: ino_t,
83 nlink: usize,84 nlink: usize,
8485
85 uid: u32,86 uid: u32,
lib/std/os/bits/wasi.zig+1
...@@ -178,6 +178,7 @@ pub const FILESTAT_SET_MTIM: fstflags_t = 0x0004;...@@ -178,6 +178,7 @@ pub const FILESTAT_SET_MTIM: fstflags_t = 0x0004;
178pub const FILESTAT_SET_MTIM_NOW: fstflags_t = 0x0008;178pub const FILESTAT_SET_MTIM_NOW: fstflags_t = 0x0008;
179179
180pub const inode_t = u64;180pub const inode_t = u64;
181pub const ino_t = inode_t;
181182
182pub const linkcount_t = u32;183pub const linkcount_t = u32;
183184
lib/std/os/bits/windows.zig+1
...@@ -4,6 +4,7 @@ usingnamespace @import("../windows/bits.zig");...@@ -4,6 +4,7 @@ usingnamespace @import("../windows/bits.zig");
4const ws2_32 = @import("../windows/ws2_32.zig");4const ws2_32 = @import("../windows/ws2_32.zig");
55
6pub const fd_t = HANDLE;6pub const fd_t = HANDLE;
7pub const ino_t = LARGE_INTEGER;
7pub const pid_t = HANDLE;8pub const pid_t = HANDLE;
8pub const mode_t = u0;9pub const mode_t = u0;
910
lib/std/os/linux.zig+64-2
...@@ -350,7 +350,13 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {...@@ -350,7 +350,13 @@ pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: u64) usize {
350 );350 );
351 }351 }
352 } else {352 } else {
353 return syscall4(SYS_pread, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset);353 return syscall4(
354 SYS_pread,
355 @bitCast(usize, @as(isize, fd)),
356 @ptrToInt(buf),
357 count,
358 offset,
359 );
354 }360 }
355}361}
356362
...@@ -384,8 +390,64 @@ pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {...@@ -384,8 +390,64 @@ pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
384 return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);390 return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
385}391}
386392
393pub fn ftruncate(fd: i32, length: u64) usize {
394 if (@hasDecl(@This(), "SYS_ftruncate64")) {
395 if (require_aligned_register_pair) {
396 return syscall4(
397 SYS_ftruncate64,
398 @bitCast(usize, @as(isize, fd)),
399 0,
400 @truncate(usize, length),
401 @truncate(usize, length >> 32),
402 );
403 } else {
404 return syscall3(
405 SYS_ftruncate64,
406 @bitCast(usize, @as(isize, fd)),
407 @truncate(usize, length),
408 @truncate(usize, length >> 32),
409 );
410 }
411 } else {
412 return syscall2(
413 SYS_ftruncate,
414 @bitCast(usize, @as(isize, fd)),
415 @truncate(usize, length),
416 );
417 }
418}
419
387pub 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 {
388 return syscall4(SYS_pwrite, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset);421 if (@hasDecl(@This(), "SYS_pwrite64")) {
422 if (require_aligned_register_pair) {
423 return syscall6(
424 SYS_pwrite64,
425 @bitCast(usize, @as(isize, fd)),
426 @ptrToInt(buf),
427 count,
428 0,
429 @truncate(usize, offset),
430 @truncate(usize, offset >> 32),
431 );
432 } else {
433 return syscall5(
434 SYS_pwrite64,
435 @bitCast(usize, @as(isize, fd)),
436 @ptrToInt(buf),
437 count,
438 @truncate(usize, offset),
439 @truncate(usize, offset >> 32),
440 );
441 }
442 } else {
443 return syscall4(
444 SYS_pwrite,
445 @bitCast(usize, @as(isize, fd)),
446 @ptrToInt(buf),
447 count,
448 offset,
449 );
450 }
389}451}
390452
391pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize {453pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize {
lib/std/os/test.zig+34-9
...@@ -95,15 +95,41 @@ test "sendfile" {...@@ -95,15 +95,41 @@ test "sendfile" {
95 },95 },
96 };96 };
9797
98 var written_buf: [header1.len + header2.len + 10 + trailer1.len + trailer2.len]u8 = undefined;98 var written_buf: [100]u8 = undefined;
99 try dest_file.writeFileAll(src_file, .{99 try dest_file.writeFileAll(src_file, .{
100 .in_offset = 1,100 .in_offset = 1,
101 .in_len = 10,101 .in_len = 10,
102 .headers_and_trailers = &hdtr,102 .headers_and_trailers = &hdtr,
103 .header_count = 2,103 .header_count = 2,
104 });104 });
105 try dest_file.preadAll(&written_buf, 0);105 const amt = try dest_file.preadAll(&written_buf, 0);
106 expect(mem.eql(u8, &written_buf, "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n"));106 expect(mem.eql(u8, written_buf[0..amt], "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n"));
107}
108
109test "fs.copyFile" {
110 const data = "u6wj+JmdF3qHsFPE BUlH2g4gJCmEz0PP";
111 const src_file = "tmp_test_copy_file.txt";
112 const dest_file = "tmp_test_copy_file2.txt";
113 const dest_file2 = "tmp_test_copy_file3.txt";
114
115 try fs.cwd().writeFile(src_file, data);
116 defer fs.cwd().deleteFile(src_file) catch {};
117
118 try fs.copyFile(src_file, dest_file);
119 defer fs.cwd().deleteFile(dest_file) catch {};
120
121 try fs.copyFileMode(src_file, dest_file2, File.default_mode);
122 defer fs.cwd().deleteFile(dest_file2) catch {};
123
124 try expectFileContents(dest_file, data);
125 try expectFileContents(dest_file2, data);
126}
127
128fn expectFileContents(file_path: []const u8, data: []const u8) !void {
129 const contents = try fs.cwd().readFileAlloc(testing.allocator, file_path, 1000);
130 defer testing.allocator.free(contents);
131
132 testing.expectEqualSlices(u8, data, contents);
107}133}
108134
109test "std.Thread.getCurrentId" {135test "std.Thread.getCurrentId" {
...@@ -354,8 +380,7 @@ test "mmap" {...@@ -354,8 +380,7 @@ test "mmap" {
354 const file = try fs.cwd().createFile(test_out_file, .{});380 const file = try fs.cwd().createFile(test_out_file, .{});
355 defer file.close();381 defer file.close();
356382
357 var out_stream = file.outStream();383 const stream = file.outStream();
358 const stream = &out_stream.stream;
359384
360 var i: u32 = 0;385 var i: u32 = 0;
361 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {386 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
...@@ -378,8 +403,8 @@ test "mmap" {...@@ -378,8 +403,8 @@ test "mmap" {
378 );403 );
379 defer os.munmap(data);404 defer os.munmap(data);
380405
381 var mem_stream = io.SliceInStream.init(data);406 var mem_stream = io.fixedBufferStream(data);
382 const stream = &mem_stream.stream;407 const stream = mem_stream.inStream();
383408
384 var i: u32 = 0;409 var i: u32 = 0;
385 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {410 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
...@@ -402,8 +427,8 @@ test "mmap" {...@@ -402,8 +427,8 @@ test "mmap" {
402 );427 );
403 defer os.munmap(data);428 defer os.munmap(data);
404429
405 var mem_stream = io.SliceInStream.init(data);430 var mem_stream = io.fixedBufferStream(data);
406 const stream = &mem_stream.stream;431 const stream = mem_stream.inStream();
407432
408 var i: u32 = alloc_size / 2 / @sizeOf(u32);433 var i: u32 = alloc_size / 2 / @sizeOf(u32);
409 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {434 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
lib/std/os/uefi.zig+7-8
...@@ -2,11 +2,9 @@...@@ -2,11 +2,9 @@
2pub const protocols = @import("uefi/protocols.zig");2pub const protocols = @import("uefi/protocols.zig");
33
4/// Status codes returned by EFI interfaces4/// Status codes returned by EFI interfaces
5pub const status = @import("uefi/status.zig");5pub const Status = @import("uefi/status.zig").Status;
6pub const tables = @import("uefi/tables.zig");6pub const tables = @import("uefi/tables.zig");
77
8const fmt = @import("std").fmt;
9
10/// The EFI image's handle that is passed to its entry point.8/// The EFI image's handle that is passed to its entry point.
11pub var handle: Handle = undefined;9pub var handle: Handle = undefined;
1210
...@@ -29,13 +27,11 @@ pub const Guid = extern struct {...@@ -29,13 +27,11 @@ pub const Guid = extern struct {
29 pub fn format(27 pub fn format(
30 self: @This(),28 self: @This(),
31 comptime f: []const u8,29 comptime f: []const u8,
32 options: fmt.FormatOptions,30 options: std.fmt.FormatOptions,
33 context: var,31 out_stream: var,
34 comptime Errors: type,
35 output: fn (@TypeOf(context), []const u8) Errors!void,
36 ) Errors!void {32 ) Errors!void {
37 if (f.len == 0) {33 if (f.len == 0) {
38 return fmt.format(context, Errors, output, "{x:0>8}-{x:0>4}-{x:0>4}-{x:0>2}{x:0>2}-{x:0>12}", .{34 return std.fmt.format(out_stream, "{x:0>8}-{x:0>4}-{x:0>4}-{x:0>2}{x:0>2}-{x:0>12}", .{
39 self.time_low,35 self.time_low,
40 self.time_mid,36 self.time_mid,
41 self.time_high_and_version,37 self.time_high_and_version,
...@@ -105,3 +101,6 @@ pub const TimeCapabilities = extern struct {...@@ -105,3 +101,6 @@ pub const TimeCapabilities = extern struct {
105 /// If true, a time set operation clears the device's time below the resolution level.101 /// If true, a time set operation clears the device's time below the resolution level.
106 sets_to_zero: bool,102 sets_to_zero: bool,
107};103};
104
105/// File Handle as specified in the EFI Shell Spec
106pub const FileHandle = *@OpaqueType();
lib/std/os/uefi/protocols.zig+15
...@@ -1,6 +1,19 @@...@@ -1,6 +1,19 @@
1pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol;1pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol;
2pub const loaded_image_device_path_protocol_guid = @import("protocols/loaded_image_protocol.zig").loaded_image_device_path_protocol_guid;
23
4pub const AcpiDevicePath = @import("protocols/device_path_protocol.zig").AcpiDevicePath;
5pub const BiosBootSpecificationDevicePath = @import("protocols/device_path_protocol.zig").BiosBootSpecificationDevicePath;
6pub const DevicePath = @import("protocols/device_path_protocol.zig").DevicePath;
3pub const DevicePathProtocol = @import("protocols/device_path_protocol.zig").DevicePathProtocol;7pub const DevicePathProtocol = @import("protocols/device_path_protocol.zig").DevicePathProtocol;
8pub const DevicePathType = @import("protocols/device_path_protocol.zig").DevicePathType;
9pub const EndDevicePath = @import("protocols/device_path_protocol.zig").EndDevicePath;
10pub const HardwareDevicePath = @import("protocols/device_path_protocol.zig").HardwareDevicePath;
11pub const MediaDevicePath = @import("protocols/device_path_protocol.zig").MediaDevicePath;
12pub const MessagingDevicePath = @import("protocols/device_path_protocol.zig").MessagingDevicePath;
13
14pub const SimpleFileSystemProtocol = @import("protocols/simple_file_system_protocol.zig").SimpleFileSystemProtocol;
15pub const FileProtocol = @import("protocols/file_protocol.zig").FileProtocol;
16pub const FileInfo = @import("protocols/file_protocol.zig").FileInfo;
417
5pub const InputKey = @import("protocols/simple_text_input_ex_protocol.zig").InputKey;18pub const InputKey = @import("protocols/simple_text_input_ex_protocol.zig").InputKey;
6pub const KeyData = @import("protocols/simple_text_input_ex_protocol.zig").KeyData;19pub const KeyData = @import("protocols/simple_text_input_ex_protocol.zig").KeyData;
...@@ -82,3 +95,5 @@ pub const HIIPopupType = @import("protocols/hii_popup_protocol.zig").HIIPopupTyp...@@ -82,3 +95,5 @@ pub const HIIPopupType = @import("protocols/hii_popup_protocol.zig").HIIPopupTyp
82pub const HIIPopupSelection = @import("protocols/hii_popup_protocol.zig").HIIPopupSelection;95pub const HIIPopupSelection = @import("protocols/hii_popup_protocol.zig").HIIPopupSelection;
8396
84pub const RNGProtocol = @import("protocols/rng_protocol.zig").RNGProtocol;97pub const RNGProtocol = @import("protocols/rng_protocol.zig").RNGProtocol;
98
99pub const ShellParametersProtocol = @import("protocols/shell_parameters_protocol.zig").ShellParametersProtocol;
lib/std/os/uefi/protocols/absolute_pointer_protocol.zig+5-4
...@@ -1,21 +1,22 @@...@@ -1,21 +1,22 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Event = uefi.Event;2const Event = uefi.Event;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5/// Protocol for touchscreens6/// Protocol for touchscreens
6pub const AbsolutePointerProtocol = extern struct {7pub const AbsolutePointerProtocol = extern struct {
7 _reset: extern fn (*const AbsolutePointerProtocol, bool) usize,8 _reset: extern fn (*const AbsolutePointerProtocol, bool) Status,
8 _get_state: extern fn (*const AbsolutePointerProtocol, *AbsolutePointerState) usize,9 _get_state: extern fn (*const AbsolutePointerProtocol, *AbsolutePointerState) Status,
9 wait_for_input: Event,10 wait_for_input: Event,
10 mode: *AbsolutePointerMode,11 mode: *AbsolutePointerMode,
1112
12 /// Resets the pointer device hardware.13 /// Resets the pointer device hardware.
13 pub fn reset(self: *const AbsolutePointerProtocol, verify: bool) usize {14 pub fn reset(self: *const AbsolutePointerProtocol, verify: bool) Status {
14 return self._reset(self, verify);15 return self._reset(self, verify);
15 }16 }
1617
17 /// Retrieves the current state of a pointer device.18 /// Retrieves the current state of a pointer device.
18 pub fn getState(self: *const AbsolutePointerProtocol, state: *AbsolutePointerState) usize {19 pub fn getState(self: *const AbsolutePointerProtocol, state: *AbsolutePointerState) Status {
19 return self._get_state(self, state);20 return self._get_state(self, state);
20 }21 }
2122
lib/std/os/uefi/protocols/device_path_protocol.zig+338-2
...@@ -1,8 +1,8 @@...@@ -1,8 +1,8 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
33
4pub const DevicePathProtocol = extern struct {4pub const DevicePathProtocol = packed struct {
5 type: u8,5 type: DevicePathType,
6 subtype: u8,6 subtype: u8,
7 length: u16,7 length: u16,
88
...@@ -14,4 +14,340 @@ pub const DevicePathProtocol = extern struct {...@@ -14,4 +14,340 @@ pub const DevicePathProtocol = extern struct {
14 .clock_seq_low = 0x39,14 .clock_seq_low = 0x39,
15 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },15 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
16 };16 };
17
18 pub fn getDevicePath(self: *const DevicePathProtocol) ?DevicePath {
19 return switch (self.type) {
20 .Hardware => blk: {
21 const hardware: ?HardwareDevicePath = switch (@intToEnum(HardwareDevicePath.Subtype, self.subtype)) {
22 .Pci => .{ .Pci = @ptrCast(*const HardwareDevicePath.PciDevicePath, self) },
23 .PcCard => .{ .PcCard = @ptrCast(*const HardwareDevicePath.PcCardDevicePath, self) },
24 .MemoryMapped => .{ .MemoryMapped = @ptrCast(*const HardwareDevicePath.MemoryMappedDevicePath, self) },
25 .Vendor => .{ .Vendor = @ptrCast(*const HardwareDevicePath.VendorDevicePath, self) },
26 .Controller => .{ .Controller = @ptrCast(*const HardwareDevicePath.ControllerDevicePath, self) },
27 .Bmc => .{ .Bmc = @ptrCast(*const HardwareDevicePath.BmcDevicePath, self) },
28 _ => null,
29 };
30 break :blk if (hardware) |h| .{ .Hardware = h } else null;
31 },
32 .Acpi => blk: {
33 const acpi: ?AcpiDevicePath = switch (@intToEnum(AcpiDevicePath.Subtype, self.subtype)) {
34 else => null, // TODO
35 };
36 break :blk if (acpi) |a| .{ .Acpi = a } else null;
37 },
38 .Messaging => blk: {
39 const messaging: ?MessagingDevicePath = switch (@intToEnum(MessagingDevicePath.Subtype, self.subtype)) {
40 else => null, // TODO
41 };
42 break :blk if (messaging) |m| .{ .Messaging = m } else null;
43 },
44 .Media => blk: {
45 const media: ?MediaDevicePath = switch (@intToEnum(MediaDevicePath.Subtype, self.subtype)) {
46 .HardDrive => .{ .HardDrive = @ptrCast(*const MediaDevicePath.HardDriveDevicePath, self) },
47 .Cdrom => .{ .Cdrom = @ptrCast(*const MediaDevicePath.CdromDevicePath, self) },
48 .Vendor => .{ .Vendor = @ptrCast(*const MediaDevicePath.VendorDevicePath, self) },
49 .FilePath => .{ .FilePath = @ptrCast(*const MediaDevicePath.FilePathDevicePath, self) },
50 .MediaProtocol => .{ .MediaProtocol = @ptrCast(*const MediaDevicePath.MediaProtocolDevicePath, self) },
51 .PiwgFirmwareFile => .{ .PiwgFirmwareFile = @ptrCast(*const MediaDevicePath.PiwgFirmwareFileDevicePath, self) },
52 .PiwgFirmwareVolume => .{ .PiwgFirmwareVolume = @ptrCast(*const MediaDevicePath.PiwgFirmwareVolumeDevicePath, self) },
53 .RelativeOffsetRange => .{ .RelativeOffsetRange = @ptrCast(*const MediaDevicePath.RelativeOffsetRangeDevicePath, self) },
54 .RamDisk => .{ .RamDisk = @ptrCast(*const MediaDevicePath.RamDiskDevicePath, self) },
55 _ => null,
56 };
57 break :blk if (media) |m| .{ .Media = m } else null;
58 },
59 .BiosBootSpecification => blk: {
60 const bbs: ?BiosBootSpecificationDevicePath = switch (@intToEnum(BiosBootSpecificationDevicePath.Subtype, self.subtype)) {
61 .BBS101 => .{ .BBS101 = @ptrCast(*const BiosBootSpecificationDevicePath.BBS101DevicePath, self) },
62 _ => null,
63 };
64 break :blk if (bbs) |b| .{ .BiosBootSpecification = b } else null;
65 },
66 .End => blk: {
67 const end: ?EndDevicePath = switch (@intToEnum(EndDevicePath.Subtype, self.subtype)) {
68 .EndEntire => .{ .EndEntire = @ptrCast(*const EndDevicePath.EndEntireDevicePath, self) },
69 .EndThisInstance => .{ .EndThisInstance = @ptrCast(*const EndDevicePath.EndThisInstanceDevicePath, self) },
70 _ => null,
71 };
72 break :blk if (end) |e| .{ .End = e } else null;
73 },
74 _ => null,
75 };
76 }
77};
78
79pub const DevicePath = union(DevicePathType) {
80 Hardware: HardwareDevicePath,
81 Acpi: AcpiDevicePath,
82 Messaging: MessagingDevicePath,
83 Media: MediaDevicePath,
84 BiosBootSpecification: BiosBootSpecificationDevicePath,
85 End: EndDevicePath,
86};
87
88pub const DevicePathType = extern enum(u8) {
89 Hardware = 0x01,
90 Acpi = 0x02,
91 Messaging = 0x03,
92 Media = 0x04,
93 BiosBootSpecification = 0x05,
94 End = 0x7f,
95 _,
96};
97
98pub const HardwareDevicePath = union(Subtype) {
99 Pci: *const PciDevicePath,
100 PcCard: *const PcCardDevicePath,
101 MemoryMapped: *const MemoryMappedDevicePath,
102 Vendor: *const VendorDevicePath,
103 Controller: *const ControllerDevicePath,
104 Bmc: *const BmcDevicePath,
105
106 pub const Subtype = extern enum(u8) {
107 Pci = 1,
108 PcCard = 2,
109 MemoryMapped = 3,
110 Vendor = 4,
111 Controller = 5,
112 Bmc = 6,
113 _,
114 };
115
116 pub const PciDevicePath = packed struct {
117 type: DevicePathType,
118 subtype: Subtype,
119 length: u16,
120 // TODO
121 };
122
123 pub const PcCardDevicePath = packed struct {
124 type: DevicePathType,
125 subtype: Subtype,
126 length: u16,
127 // TODO
128 };
129
130 pub const MemoryMappedDevicePath = packed struct {
131 type: DevicePathType,
132 subtype: Subtype,
133 length: u16,
134 // TODO
135 };
136
137 pub const VendorDevicePath = packed struct {
138 type: DevicePathType,
139 subtype: Subtype,
140 length: u16,
141 // TODO
142 };
143
144 pub const ControllerDevicePath = packed struct {
145 type: DevicePathType,
146 subtype: Subtype,
147 length: u16,
148 // TODO
149 };
150
151 pub const BmcDevicePath = packed struct {
152 type: DevicePathType,
153 subtype: Subtype,
154 length: u16,
155 // TODO
156 };
157};
158
159pub const AcpiDevicePath = union(Subtype) {
160 Acpi: void, // TODO
161 ExpandedAcpi: void, // TODO
162 Adr: void, // TODO
163 Nvdimm: void, // TODO
164
165 pub const Subtype = extern enum(u8) {
166 Acpi = 1,
167 ExpandedAcpi = 2,
168 Adr = 3,
169 Nvdimm = 4,
170 _,
171 };
172};
173
174pub const MessagingDevicePath = union(Subtype) {
175 Atapi: void, // TODO
176 Scsi: void, // TODO
177 FibreChannel: void, // TODO
178 FibreChannelEx: void, // TODO
179 @"1394": void, // TODO
180 Usb: void, // TODO
181 Sata: void, // TODO
182 UsbWwid: void, // TODO
183 Lun: void, // TODO
184 UsbClass: void, // TODO
185 I2o: void, // TODO
186 MacAddress: void, // TODO
187 Ipv4: void, // TODO
188 Ipv6: void, // TODO
189 Vlan: void, // TODO
190 InfiniBand: void, // TODO
191 Uart: void, // TODO
192 Vendor: void, // TODO
193
194 pub const Subtype = extern enum(u8) {
195 Atapi = 1,
196 Scsi = 2,
197 FibreChannel = 3,
198 FibreChannelEx = 21,
199 @"1394" = 4,
200 Usb = 5,
201 Sata = 18,
202 UsbWwid = 16,
203 Lun = 17,
204 UsbClass = 15,
205 I2o = 6,
206 MacAddress = 11,
207 Ipv4 = 12,
208 Ipv6 = 13,
209 Vlan = 20,
210 InfiniBand = 9,
211 Uart = 14,
212 Vendor = 10,
213 _,
214 };
215};
216
217pub const MediaDevicePath = union(Subtype) {
218 HardDrive: *const HardDriveDevicePath,
219 Cdrom: *const CdromDevicePath,
220 Vendor: *const VendorDevicePath,
221 FilePath: *const FilePathDevicePath,
222 MediaProtocol: *const MediaProtocolDevicePath,
223 PiwgFirmwareFile: *const PiwgFirmwareFileDevicePath,
224 PiwgFirmwareVolume: *const PiwgFirmwareVolumeDevicePath,
225 RelativeOffsetRange: *const RelativeOffsetRangeDevicePath,
226 RamDisk: *const RamDiskDevicePath,
227
228 pub const Subtype = extern enum(u8) {
229 HardDrive = 1,
230 Cdrom = 2,
231 Vendor = 3,
232 FilePath = 4,
233 MediaProtocol = 5,
234 PiwgFirmwareFile = 6,
235 PiwgFirmwareVolume = 7,
236 RelativeOffsetRange = 8,
237 RamDisk = 9,
238 _,
239 };
240
241 pub const HardDriveDevicePath = packed struct {
242 type: DevicePathType,
243 subtype: Subtype,
244 length: u16,
245 // TODO
246 };
247
248 pub const CdromDevicePath = packed struct {
249 type: DevicePathType,
250 subtype: Subtype,
251 length: u16,
252 // TODO
253 };
254
255 pub const VendorDevicePath = packed struct {
256 type: DevicePathType,
257 subtype: Subtype,
258 length: u16,
259 // TODO
260 };
261
262 pub const FilePathDevicePath = packed struct {
263 type: DevicePathType,
264 subtype: Subtype,
265 length: u16,
266
267 pub fn getPath(self: *const FilePathDevicePath) [*:0]const u16 {
268 return @ptrCast([*:0]const u16, @alignCast(2, @ptrCast([*]const u8, self)) + @sizeOf(FilePathDevicePath));
269 }
270 };
271
272 pub const MediaProtocolDevicePath = packed struct {
273 type: DevicePathType,
274 subtype: Subtype,
275 length: u16,
276 // TODO
277 };
278
279 pub const PiwgFirmwareFileDevicePath = packed struct {
280 type: DevicePathType,
281 subtype: Subtype,
282 length: u16,
283 };
284
285 pub const PiwgFirmwareVolumeDevicePath = packed struct {
286 type: DevicePathType,
287 subtype: Subtype,
288 length: u16,
289 };
290
291 pub const RelativeOffsetRangeDevicePath = packed struct {
292 type: DevicePathType,
293 subtype: Subtype,
294 length: u16,
295 reserved: u32,
296 start: u64,
297 end: u64,
298 };
299
300 pub const RamDiskDevicePath = packed struct {
301 type: DevicePathType,
302 subtype: Subtype,
303 length: u16,
304 start: u64,
305 end: u64,
306 disk_type: uefi.Guid,
307 instance: u16,
308 };
309};
310
311pub const BiosBootSpecificationDevicePath = union(Subtype) {
312 BBS101: *const BBS101DevicePath,
313
314 pub const Subtype = extern enum(u8) {
315 BBS101 = 1,
316 _,
317 };
318
319 pub const BBS101DevicePath = packed struct {
320 type: DevicePathType,
321 subtype: Subtype,
322 length: u16,
323 device_type: u16,
324 status_flag: u16,
325
326 pub fn getDescription(self: *const BBS101DevicePath) [*:0]const u8 {
327 return @ptrCast([*:0]const u8, self) + @sizeOf(BBS101DevicePath);
328 }
329 };
330};
331
332pub const EndDevicePath = union(Subtype) {
333 EndEntire: *const EndEntireDevicePath,
334 EndThisInstance: *const EndThisInstanceDevicePath,
335
336 pub const Subtype = extern enum(u8) {
337 EndEntire = 0xff,
338 EndThisInstance = 0x01,
339 _,
340 };
341
342 pub const EndEntireDevicePath = packed struct {
343 type: DevicePathType,
344 subtype: Subtype,
345 length: u16,
346 };
347
348 pub const EndThisInstanceDevicePath = packed struct {
349 type: DevicePathType,
350 subtype: Subtype,
351 length: u16,
352 };
17};353};
lib/std/os/uefi/protocols/edid_override_protocol.zig+3-2
...@@ -1,14 +1,15 @@...@@ -1,14 +1,15 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Handle = uefi.Handle;3const Handle = uefi.Handle;
4const Status = uefi.Status;
45
5/// Override EDID information6/// Override EDID information
6pub const EdidOverrideProtocol = extern struct {7pub const EdidOverrideProtocol = extern struct {
7 _get_edid: extern fn (*const EdidOverrideProtocol, Handle, *u32, *usize, *?[*]u8) usize,8 _get_edid: extern fn (*const EdidOverrideProtocol, Handle, *u32, *usize, *?[*]u8) Status,
89
9 /// Returns policy information and potentially a replacement EDID for the specified video output device.10 /// Returns policy information and potentially a replacement EDID for the specified video output device.
10 /// attributes must be align(4)11 /// attributes must be align(4)
11 pub fn getEdid(self: *const EdidOverrideProtocol, handle: Handle, attributes: *EdidOverrideProtocolAttributes, edid_size: *usize, edid: *?[*]u8) usize {12 pub fn getEdid(self: *const EdidOverrideProtocol, handle: Handle, attributes: *EdidOverrideProtocolAttributes, edid_size: *usize, edid: *?[*]u8) Status {
12 return self._get_edid(self, handle, attributes, edid_size, edid);13 return self._get_edid(self, handle, attributes, edid_size, edid);
13 }14 }
1415
lib/std/os/uefi/protocols/file_protocol.zig created+91
...@@ -0,0 +1,91 @@
1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;
3const Time = uefi.Time;
4const Status = uefi.Status;
5
6pub const FileProtocol = extern struct {
7 revision: u64,
8 _open: extern fn (*const FileProtocol, **const FileProtocol, [*:0]const u16, u64, u64) Status,
9 _close: extern fn (*const FileProtocol) Status,
10 _delete: extern fn (*const FileProtocol) Status,
11 _read: extern fn (*const FileProtocol, *usize, [*]u8) Status,
12 _write: extern fn (*const FileProtocol, *usize, [*]const u8) Status,
13 _get_info: extern fn (*const FileProtocol, *Guid, *usize, *c_void) Status,
14 _set_info: extern fn (*const FileProtocol, *Guid, usize, *const c_void) Status,
15 _flush: extern fn (*const FileProtocol) Status,
16
17 pub fn open(self: *const FileProtocol, new_handle: **const FileProtocol, file_name: [*:0]const u16, open_mode: u64, attributes: u64) Status {
18 return self._open(self, new_handle, file_name, open_mode, attributes);
19 }
20
21 pub fn close(self: *const FileProtocol) Status {
22 return self._close(self);
23 }
24
25 pub fn delete(self: *const FileProtocol) Status {
26 return self._delete(self);
27 }
28
29 pub fn read(self: *const FileProtocol, buffer_size: *usize, buffer: [*]u8) Status {
30 return self._read(self, buffer_size, buffer);
31 }
32
33 pub fn write(self: *const FileProtocol, buffer_size: *usize, buffer: [*]const u8) Status {
34 return self._write(self, buffer_size, buffer);
35 }
36
37 pub fn get_info(self: *const FileProtocol, information_type: *Guid, buffer_size: *usize, buffer: *c_void) Status {
38 return self._get_info(self, information_type, buffer_size, buffer);
39 }
40
41 pub fn set_info(self: *const FileProtocol, information_type: *Guid, buffer_size: usize, buffer: *const c_void) Status {
42 return self._set_info(self, information_type, buffer_size, buffer);
43 }
44
45 pub fn flush(self: *const FileProtocol) Status {
46 return self._flush(self);
47 }
48
49 pub const guid align(8) = Guid{
50 .time_low = 0x09576e92,
51 .time_mid = 0x6d3f,
52 .time_high_and_version = 0x11d2,
53 .clock_seq_high_and_reserved = 0x8e,
54 .clock_seq_low = 0x39,
55 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
56 };
57
58 pub const efi_file_mode_read: u64 = 0x0000000000000001;
59 pub const efi_file_mode_write: u64 = 0x0000000000000002;
60 pub const efi_file_mode_create: u64 = 0x8000000000000000;
61
62 pub const efi_file_read_only: u64 = 0x0000000000000001;
63 pub const efi_file_hidden: u64 = 0x0000000000000002;
64 pub const efi_file_system: u64 = 0x0000000000000004;
65 pub const efi_file_reserved: u64 = 0x0000000000000008;
66 pub const efi_file_directory: u64 = 0x0000000000000010;
67 pub const efi_file_archive: u64 = 0x0000000000000020;
68 pub const efi_file_valid_attr: u64 = 0x0000000000000037;
69};
70
71pub const FileInfo = extern struct {
72 size: u64,
73 file_size: u64,
74 physical_size: u64,
75 create_time: Time,
76 last_access_time: Time,
77 modification_time: Time,
78 attribute: u64,
79
80 pub fn getFileName(self: *const FileInfo) [*:0]const u16 {
81 return @ptrCast([*:0]const u16, @ptrCast([*]const u8, self) + @sizeOf(FileInfo));
82 }
83
84 pub const efi_file_read_only: u64 = 0x0000000000000001;
85 pub const efi_file_hidden: u64 = 0x0000000000000002;
86 pub const efi_file_system: u64 = 0x0000000000000004;
87 pub const efi_file_reserved: u64 = 0x0000000000000008;
88 pub const efi_file_directory: u64 = 0x0000000000000010;
89 pub const efi_file_archive: u64 = 0x0000000000000020;
90 pub const efi_file_valid_attr: u64 = 0x0000000000000037;
91};
lib/std/os/uefi/protocols/graphics_output_protocol.zig+7-6
...@@ -1,25 +1,26 @@...@@ -1,25 +1,26 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Status = uefi.Status;
34
4/// Graphics output5/// Graphics output
5pub const GraphicsOutputProtocol = extern struct {6pub const GraphicsOutputProtocol = extern struct {
6 _query_mode: extern fn (*const GraphicsOutputProtocol, u32, *usize, **GraphicsOutputModeInformation) usize,7 _query_mode: extern fn (*const GraphicsOutputProtocol, u32, *usize, **GraphicsOutputModeInformation) Status,
7 _set_mode: extern fn (*const GraphicsOutputProtocol, u32) usize,8 _set_mode: extern fn (*const GraphicsOutputProtocol, u32) Status,
8 _blt: extern fn (*const GraphicsOutputProtocol, ?[*]GraphicsOutputBltPixel, GraphicsOutputBltOperation, usize, usize, usize, usize, usize, usize, usize) usize,9 _blt: extern fn (*const GraphicsOutputProtocol, ?[*]GraphicsOutputBltPixel, GraphicsOutputBltOperation, usize, usize, usize, usize, usize, usize, usize) Status,
9 mode: *GraphicsOutputProtocolMode,10 mode: *GraphicsOutputProtocolMode,
1011
11 /// Returns information for an available graphics mode that the graphics device and the set of active video output devices supports.12 /// Returns information for an available graphics mode that the graphics device and the set of active video output devices supports.
12 pub fn queryMode(self: *const GraphicsOutputProtocol, mode: u32, size_of_info: *usize, info: **GraphicsOutputModeInformation) usize {13 pub fn queryMode(self: *const GraphicsOutputProtocol, mode: u32, size_of_info: *usize, info: **GraphicsOutputModeInformation) Status {
13 return self._query_mode(self, mode, size_of_info, info);14 return self._query_mode(self, mode, size_of_info, info);
14 }15 }
1516
16 /// Set the video device into the specified mode and clears the visible portions of the output display to black.17 /// Set the video device into the specified mode and clears the visible portions of the output display to black.
17 pub fn setMode(self: *const GraphicsOutputProtocol, mode: u32) usize {18 pub fn setMode(self: *const GraphicsOutputProtocol, mode: u32) Status {
18 return self._set_mode(self, mode);19 return self._set_mode(self, mode);
19 }20 }
2021
21 /// Blt a rectangle of pixels on the graphics screen. Blt stands for BLock Transfer.22 /// Blt a rectangle of pixels on the graphics screen. Blt stands for BLock Transfer.
22 pub fn blt(self: *const GraphicsOutputProtocol, blt_buffer: ?[*]GraphicsOutputBltPixel, blt_operation: GraphicsOutputBltOperation, source_x: usize, source_y: usize, destination_x: usize, destination_y: usize, width: usize, height: usize, delta: usize) usize {23 pub fn blt(self: *const GraphicsOutputProtocol, blt_buffer: ?[*]GraphicsOutputBltPixel, blt_operation: GraphicsOutputBltOperation, source_x: usize, source_y: usize, destination_x: usize, destination_y: usize, width: usize, height: usize, delta: usize) Status {
23 return self._blt(self, blt_buffer, blt_operation, source_x, source_y, destination_x, destination_y, width, height, delta);24 return self._blt(self, blt_buffer, blt_operation, source_x, source_y, destination_x, destination_y, width, height, delta);
24 }25 }
2526
lib/std/os/uefi/protocols/hii_database_protocol.zig+16-15
...@@ -1,38 +1,39 @@...@@ -1,38 +1,39 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Status = uefi.Status;
3const hii = uefi.protocols.hii;4const hii = uefi.protocols.hii;
45
5/// Database manager for HII-related data structures.6/// Database manager for HII-related data structures.
6pub const HIIDatabaseProtocol = extern struct {7pub const HIIDatabaseProtocol = extern struct {
7 _new_package_list: usize, // TODO8 _new_package_list: Status, // TODO
8 _remove_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle) usize,9 _remove_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle) Status,
9 _update_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle, *const hii.HIIPackageList) usize,10 _update_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle, *const hii.HIIPackageList) Status,
10 _list_package_lists: extern fn (*const HIIDatabaseProtocol, u8, ?*const Guid, *usize, [*]hii.HIIHandle) usize,11 _list_package_lists: extern fn (*const HIIDatabaseProtocol, u8, ?*const Guid, *usize, [*]hii.HIIHandle) Status,
11 _export_package_lists: extern fn (*const HIIDatabaseProtocol, ?hii.HIIHandle, *usize, *hii.HIIPackageList) usize,12 _export_package_lists: extern fn (*const HIIDatabaseProtocol, ?hii.HIIHandle, *usize, *hii.HIIPackageList) Status,
12 _register_package_notify: usize, // TODO13 _register_package_notify: Status, // TODO
13 _unregister_package_notify: usize, // TODO14 _unregister_package_notify: Status, // TODO
14 _find_keyboard_layouts: usize, // TODO15 _find_keyboard_layouts: Status, // TODO
15 _get_keyboard_layout: usize, // TODO16 _get_keyboard_layout: Status, // TODO
16 _set_keyboard_layout: usize, // TODO17 _set_keyboard_layout: Status, // TODO
17 _get_package_list_handle: usize, // TODO18 _get_package_list_handle: Status, // TODO
1819
19 /// Removes a package list from the HII database.20 /// Removes a package list from the HII database.
20 pub fn removePackageList(self: *const HIIDatabaseProtocol, handle: hii.HIIHandle) usize {21 pub fn removePackageList(self: *const HIIDatabaseProtocol, handle: hii.HIIHandle) Status {
21 return self._remove_package_list(self, handle);22 return self._remove_package_list(self, handle);
22 }23 }
2324
24 /// Update a package list in the HII database.25 /// Update a package list in the HII database.
25 pub fn updatePackageList(self: *const HIIDatabaseProtocol, handle: hii.HIIHandle, buffer: *const hii.HIIPackageList) usize {26 pub fn updatePackageList(self: *const HIIDatabaseProtocol, handle: hii.HIIHandle, buffer: *const hii.HIIPackageList) Status {
26 return self._update_package_list(self, handle, buffer);27 return self._update_package_list(self, handle, buffer);
27 }28 }
2829
29 /// Determines the handles that are currently active in the database.30 /// Determines the handles that are currently active in the database.
30 pub fn listPackageLists(self: *const HIIDatabaseProtocol, package_type: u8, package_guid: ?*const Guid, buffer_length: *usize, handles: [*]hii.HIIHandle) usize {31 pub fn listPackageLists(self: *const HIIDatabaseProtocol, package_type: u8, package_guid: ?*const Guid, buffer_length: *usize, handles: [*]hii.HIIHandle) Status {
31 return self._list_package_lists(self, package_type, package_guid, buffer_length, handles);32 return self._list_package_lists(self, package_type, package_guid, buffer_length, handles);
32 }33 }
3334
34 /// Exports the contents of one or all package lists in the HII database into a buffer.35 /// Exports the contents of one or all package lists in the HII database into a buffer.
35 pub fn exportPackageLists(self: *const HIIDatabaseProtocol, handle: ?hii.HIIHandle, buffer_size: *usize, buffer: *hii.HIIPackageList) usize {36 pub fn exportPackageLists(self: *const HIIDatabaseProtocol, handle: ?hii.HIIHandle, buffer_size: *usize, buffer: *hii.HIIPackageList) Status {
36 return self._export_package_lists(self, handle, buffer_size, buffer);37 return self._export_package_lists(self, handle, buffer_size, buffer);
37 }38 }
3839
lib/std/os/uefi/protocols/hii_popup_protocol.zig+3-2
...@@ -1,14 +1,15 @@...@@ -1,14 +1,15 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Status = uefi.Status;
3const hii = uefi.protocols.hii;4const hii = uefi.protocols.hii;
45
5/// Display a popup window6/// Display a popup window
6pub const HIIPopupProtocol = extern struct {7pub const HIIPopupProtocol = extern struct {
7 revision: u64,8 revision: u64,
8 _create_popup: extern fn (*const HIIPopupProtocol, HIIPopupStyle, HIIPopupType, hii.HIIHandle, u16, ?*HIIPopupSelection) usize,9 _create_popup: extern fn (*const HIIPopupProtocol, HIIPopupStyle, HIIPopupType, hii.HIIHandle, u16, ?*HIIPopupSelection) Status,
910
10 /// Displays a popup window.11 /// Displays a popup window.
11 pub fn createPopup(self: *const HIIPopupProtocol, style: HIIPopupStyle, popup_type: HIIPopupType, handle: hii.HIIHandle, msg: u16, user_selection: ?*HIIPopupSelection) usize {12 pub fn createPopup(self: *const HIIPopupProtocol, style: HIIPopupStyle, popup_type: HIIPopupType, handle: hii.HIIHandle, msg: u16, user_selection: ?*HIIPopupSelection) Status {
12 return self._create_popup(self, style, popup_type, handle, msg, user_selection);13 return self._create_popup(self, style, popup_type, handle, msg, user_selection);
13 }14 }
1415
lib/std/os/uefi/protocols/ip6_config_protocol.zig+9-8
...@@ -1,26 +1,27 @@...@@ -1,26 +1,27 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Event = uefi.Event;3const Event = uefi.Event;
4const Status = uefi.Status;
45
5pub const Ip6ConfigProtocol = extern struct {6pub const Ip6ConfigProtocol = extern struct {
6 _set_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, usize, *const c_void) usize,7 _set_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, usize, *const c_void) Status,
7 _get_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, *usize, ?*const c_void) usize,8 _get_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, *usize, ?*const c_void) Status,
8 _register_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) usize,9 _register_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) Status,
9 _unregister_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) usize,10 _unregister_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) Status,
1011
11 pub fn setData(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, data_size: usize, data: *const c_void) usize {12 pub fn setData(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, data_size: usize, data: *const c_void) Status {
12 return self._set_data(self, data_type, data_size, data);13 return self._set_data(self, data_type, data_size, data);
13 }14 }
1415
15 pub fn getData(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, data_size: *usize, data: ?*const c_void) usize {16 pub fn getData(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, data_size: *usize, data: ?*const c_void) Status {
16 return self._get_data(self, data_type, data_size, data);17 return self._get_data(self, data_type, data_size, data);
17 }18 }
1819
19 pub fn registerDataNotify(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, event: Event) usize {20 pub fn registerDataNotify(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, event: Event) Status {
20 return self._register_data_notify(self, data_type, event);21 return self._register_data_notify(self, data_type, event);
21 }22 }
2223
23 pub fn unregisterDataNotify(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, event: Event) usize {24 pub fn unregisterDataNotify(self: *const Ip6ConfigProtocol, data_type: Ip6ConfigDataType, event: Event) Status {
24 return self._unregister_data_notify(self, data_type, event);25 return self._unregister_data_notify(self, data_type, event);
25 }26 }
2627
lib/std/os/uefi/protocols/ip6_protocol.zig+20-19
...@@ -1,63 +1,64 @@...@@ -1,63 +1,64 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Event = uefi.Event;3const Event = uefi.Event;
4const Status = uefi.Status;
4const MacAddress = uefi.protocols.MacAddress;5const MacAddress = uefi.protocols.MacAddress;
5const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;6const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
6const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;7const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
78
8pub const Ip6Protocol = extern struct {9pub const Ip6Protocol = extern struct {
9 _get_mode_data: extern fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,10 _get_mode_data: extern fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) Status,
10 _configure: extern fn (*const Ip6Protocol, ?*const Ip6ConfigData) usize,11 _configure: extern fn (*const Ip6Protocol, ?*const Ip6ConfigData) Status,
11 _groups: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address) usize,12 _groups: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address) Status,
12 _routes: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) usize,13 _routes: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) Status,
13 _neighbors: extern fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) usize,14 _neighbors: extern fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) Status,
14 _transmit: extern fn (*const Ip6Protocol, *Ip6CompletionToken) usize,15 _transmit: extern fn (*const Ip6Protocol, *Ip6CompletionToken) Status,
15 _receive: extern fn (*const Ip6Protocol, *Ip6CompletionToken) usize,16 _receive: extern fn (*const Ip6Protocol, *Ip6CompletionToken) Status,
16 _cancel: extern fn (*const Ip6Protocol, ?*Ip6CompletionToken) usize,17 _cancel: extern fn (*const Ip6Protocol, ?*Ip6CompletionToken) Status,
17 _poll: extern fn (*const Ip6Protocol) usize,18 _poll: extern fn (*const Ip6Protocol) Status,
1819
19 /// Gets the current operational settings for this instance of the EFI IPv6 Protocol driver.20 /// Gets the current operational settings for this instance of the EFI IPv6 Protocol driver.
20 pub fn getModeData(self: *const Ip6Protocol, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {21 pub fn getModeData(self: *const Ip6Protocol, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status {
21 return self._get_mode_data(self, ip6_mode_data, mnp_config_data, snp_mode_data);22 return self._get_mode_data(self, ip6_mode_data, mnp_config_data, snp_mode_data);
22 }23 }
2324
24 /// Assign IPv6 address and other configuration parameter to this EFI IPv6 Protocol driver instance.25 /// Assign IPv6 address and other configuration parameter to this EFI IPv6 Protocol driver instance.
25 pub fn configure(self: *const Ip6Protocol, ip6_config_data: ?*const Ip6ConfigData) usize {26 pub fn configure(self: *const Ip6Protocol, ip6_config_data: ?*const Ip6ConfigData) Status {
26 return self._configure(self, ip6_config_data);27 return self._configure(self, ip6_config_data);
27 }28 }
2829
29 /// Joins and leaves multicast groups.30 /// Joins and leaves multicast groups.
30 pub fn groups(self: *const Ip6Protocol, join_flag: bool, group_address: ?*const Ip6Address) usize {31 pub fn groups(self: *const Ip6Protocol, join_flag: bool, group_address: ?*const Ip6Address) Status {
31 return self._groups(self, join_flag, group_address);32 return self._groups(self, join_flag, group_address);
32 }33 }
3334
34 /// Adds and deletes routing table entries.35 /// Adds and deletes routing table entries.
35 pub fn routes(self: *const Ip6Protocol, delete_route: bool, destination: ?*const Ip6Address, prefix_length: u8, gateway_address: ?*const Ip6Address) usize {36 pub fn routes(self: *const Ip6Protocol, delete_route: bool, destination: ?*const Ip6Address, prefix_length: u8, gateway_address: ?*const Ip6Address) Status {
36 return self._routes(self, delete_route, destination, prefix_length, gateway_address);37 return self._routes(self, delete_route, destination, prefix_length, gateway_address);
37 }38 }
3839
39 /// Add or delete Neighbor cache entries.40 /// Add or delete Neighbor cache entries.
40 pub fn neighbors(self: *const Ip6Protocol, delete_flag: bool, target_ip6_address: *const Ip6Address, target_link_address: ?*const MacAddress, timeout: u32, override: bool) usize {41 pub fn neighbors(self: *const Ip6Protocol, delete_flag: bool, target_ip6_address: *const Ip6Address, target_link_address: ?*const MacAddress, timeout: u32, override: bool) Status {
41 return self._neighbors(self, delete_flag, target_ip6_address, target_link_address, timeout, override);42 return self._neighbors(self, delete_flag, target_ip6_address, target_link_address, timeout, override);
42 }43 }
4344
44 /// Places outgoing data packets into the transmit queue.45 /// Places outgoing data packets into the transmit queue.
45 pub fn transmit(self: *const Ip6Protocol, token: *Ip6CompletionToken) usize {46 pub fn transmit(self: *const Ip6Protocol, token: *Ip6CompletionToken) Status {
46 return self._transmit(self, token);47 return self._transmit(self, token);
47 }48 }
4849
49 /// Places a receiving request into the receiving queue.50 /// Places a receiving request into the receiving queue.
50 pub fn receive(self: *const Ip6Protocol, token: *Ip6CompletionToken) usize {51 pub fn receive(self: *const Ip6Protocol, token: *Ip6CompletionToken) Status {
51 return self._receive(self, token);52 return self._receive(self, token);
52 }53 }
5354
54 /// Abort an asynchronous transmits or receive request.55 /// Abort an asynchronous transmits or receive request.
55 pub fn cancel(self: *const Ip6Protocol, token: ?*Ip6CompletionToken) usize {56 pub fn cancel(self: *const Ip6Protocol, token: ?*Ip6CompletionToken) Status {
56 return self._cancel(self, token);57 return self._cancel(self, token);
57 }58 }
5859
59 /// Polls for incoming data packets and processes outgoing data packets.60 /// Polls for incoming data packets and processes outgoing data packets.
60 pub fn poll(self: *const Ip6Protocol) usize {61 pub fn poll(self: *const Ip6Protocol) Status {
61 return self._poll(self);62 return self._poll(self);
62 }63 }
6364
...@@ -138,6 +139,6 @@ pub const Ip6IcmpType = extern struct {...@@ -138,6 +139,6 @@ pub const Ip6IcmpType = extern struct {
138139
139pub const Ip6CompletionToken = extern struct {140pub const Ip6CompletionToken = extern struct {
140 event: Event,141 event: Event,
141 status: usize,142 status: Status,
142 packet: *c_void, // union TODO143 packet: *c_void, // union TODO
143};144};
lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig+5-4
...@@ -1,16 +1,17 @@...@@ -1,16 +1,17 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Handle = uefi.Handle;2const Handle = uefi.Handle;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5pub const Ip6ServiceBindingProtocol = extern struct {6pub const Ip6ServiceBindingProtocol = extern struct {
6 _create_child: extern fn (*const Ip6ServiceBindingProtocol, *?Handle) usize,7 _create_child: extern fn (*const Ip6ServiceBindingProtocol, *?Handle) Status,
7 _destroy_child: extern fn (*const Ip6ServiceBindingProtocol, Handle) usize,8 _destroy_child: extern fn (*const Ip6ServiceBindingProtocol, Handle) Status,
89
9 pub fn createChild(self: *const Ip6ServiceBindingProtocol, handle: *?Handle) usize {10 pub fn createChild(self: *const Ip6ServiceBindingProtocol, handle: *?Handle) Status {
10 return self._create_child(self, handle);11 return self._create_child(self, handle);
11 }12 }
1213
13 pub fn destroyChild(self: *const Ip6ServiceBindingProtocol, handle: Handle) usize {14 pub fn destroyChild(self: *const Ip6ServiceBindingProtocol, handle: Handle) Status {
14 return self._destroy_child(self, handle);15 return self._destroy_child(self, handle);
15 }16 }
1617
lib/std/os/uefi/protocols/loaded_image_protocol.zig+13-3
...@@ -1,6 +1,7 @@...@@ -1,6 +1,7 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Handle = uefi.Handle;3const Handle = uefi.Handle;
4const Status = uefi.Status;
4const SystemTable = uefi.tables.SystemTable;5const SystemTable = uefi.tables.SystemTable;
5const MemoryType = uefi.tables.MemoryType;6const MemoryType = uefi.tables.MemoryType;
6const DevicePathProtocol = uefi.protocols.DevicePathProtocol;7const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
...@@ -13,15 +14,15 @@ pub const LoadedImageProtocol = extern struct {...@@ -13,15 +14,15 @@ pub const LoadedImageProtocol = extern struct {
13 file_path: *DevicePathProtocol,14 file_path: *DevicePathProtocol,
14 reserved: *c_void,15 reserved: *c_void,
15 load_options_size: u32,16 load_options_size: u32,
16 load_options: *c_void,17 load_options: ?*c_void,
17 image_base: [*]u8,18 image_base: [*]u8,
18 image_size: u64,19 image_size: u64,
19 image_code_type: MemoryType,20 image_code_type: MemoryType,
20 image_data_type: MemoryType,21 image_data_type: MemoryType,
21 _unload: extern fn (*const LoadedImageProtocol, Handle) usize,22 _unload: extern fn (*const LoadedImageProtocol, Handle) Status,
2223
23 /// Unloads an image from memory.24 /// Unloads an image from memory.
24 pub fn unload(self: *const LoadedImageProtocol, handle: Handle) usize {25 pub fn unload(self: *const LoadedImageProtocol, handle: Handle) Status {
25 return self._unload(self, handle);26 return self._unload(self, handle);
26 }27 }
2728
...@@ -34,3 +35,12 @@ pub const LoadedImageProtocol = extern struct {...@@ -34,3 +35,12 @@ pub const LoadedImageProtocol = extern struct {
34 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },35 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
35 };36 };
36};37};
38
39pub const loaded_image_device_path_protocol_guid align(8) = Guid{
40 .time_low = 0xbc62157e,
41 .time_mid = 0x3e33,
42 .time_high_and_version = 0x4fec,
43 .clock_seq_high_and_reserved = 0x99,
44 .clock_seq_low = 0x20,
45 .node = [_]u8{ 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf },
46};
lib/std/os/uefi/protocols/managed_network_protocol.zig+17-16
...@@ -1,60 +1,61 @@...@@ -1,60 +1,61 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Event = uefi.Event;3const Event = uefi.Event;
4const Status = uefi.Status;
4const Time = uefi.Time;5const Time = uefi.Time;
5const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;6const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
6const MacAddress = uefi.protocols.MacAddress;7const MacAddress = uefi.protocols.MacAddress;
78
8pub const ManagedNetworkProtocol = extern struct {9pub const ManagedNetworkProtocol = extern struct {
9 _get_mode_data: extern fn (*const ManagedNetworkProtocol, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,10 _get_mode_data: extern fn (*const ManagedNetworkProtocol, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) Status,
10 _configure: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkConfigData) usize,11 _configure: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkConfigData) Status,
11 _mcast_ip_to_mac: extern fn (*const ManagedNetworkProtocol, bool, *const c_void, *MacAddress) usize,12 _mcast_ip_to_mac: extern fn (*const ManagedNetworkProtocol, bool, *const c_void, *MacAddress) Status,
12 _groups: extern fn (*const ManagedNetworkProtocol, bool, ?*const MacAddress) usize,13 _groups: extern fn (*const ManagedNetworkProtocol, bool, ?*const MacAddress) Status,
13 _transmit: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) usize,14 _transmit: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) Status,
14 _receive: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) usize,15 _receive: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) Status,
15 _cancel: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkCompletionToken) usize,16 _cancel: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkCompletionToken) Status,
16 _poll: extern fn (*const ManagedNetworkProtocol) usize,17 _poll: extern fn (*const ManagedNetworkProtocol) usize,
1718
18 /// Returns the operational parameters for the current MNP child driver.19 /// Returns the operational parameters for the current MNP child driver.
19 /// May also support returning the underlying SNP driver mode data.20 /// May also support returning the underlying SNP driver mode data.
20 pub fn getModeData(self: *const ManagedNetworkProtocol, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {21 pub fn getModeData(self: *const ManagedNetworkProtocol, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status {
21 return self._get_mode_data(self, mnp_config_data, snp_mode_data);22 return self._get_mode_data(self, mnp_config_data, snp_mode_data);
22 }23 }
2324
24 /// Sets or clears the operational parameters for the MNP child driver.25 /// Sets or clears the operational parameters for the MNP child driver.
25 pub fn configure(self: *const ManagedNetworkProtocol, mnp_config_data: ?*const ManagedNetworkConfigData) usize {26 pub fn configure(self: *const ManagedNetworkProtocol, mnp_config_data: ?*const ManagedNetworkConfigData) Status {
26 return self._configure(self, mnp_config_data);27 return self._configure(self, mnp_config_data);
27 }28 }
2829
29 /// Translates an IP multicast address to a hardware (MAC) multicast address.30 /// Translates an IP multicast address to a hardware (MAC) multicast address.
30 /// This function may be unsupported in some MNP implementations.31 /// This function may be unsupported in some MNP implementations.
31 pub fn mcastIpToMac(self: *const ManagedNetworkProtocol, ipv6flag: bool, ipaddress: *const c_void, mac_address: *MacAddress) usize {32 pub fn mcastIpToMac(self: *const ManagedNetworkProtocol, ipv6flag: bool, ipaddress: *const c_void, mac_address: *MacAddress) Status {
32 return self._mcast_ip_to_mac(self, ipv6flag, ipaddress);33 return self._mcast_ip_to_mac(self, ipv6flag, ipaddress);
33 }34 }
3435
35 /// Enables and disables receive filters for multicast address.36 /// Enables and disables receive filters for multicast address.
36 /// This function may be unsupported in some MNP implementations.37 /// This function may be unsupported in some MNP implementations.
37 pub fn groups(self: *const ManagedNetworkProtocol, join_flag: bool, mac_address: ?*const MacAddress) usiz {38 pub fn groups(self: *const ManagedNetworkProtocol, join_flag: bool, mac_address: ?*const MacAddress) Status {
38 return self._groups(self, join_flag, mac_address);39 return self._groups(self, join_flag, mac_address);
39 }40 }
4041
41 /// Places asynchronous outgoing data packets into the transmit queue.42 /// Places asynchronous outgoing data packets into the transmit queue.
42 pub fn transmit(self: *const ManagedNetworkProtocol, token: *const ManagedNetworkCompletionToken) usize {43 pub fn transmit(self: *const ManagedNetworkProtocol, token: *const ManagedNetworkCompletionToken) Status {
43 return self._transmit(self, token);44 return self._transmit(self, token);
44 }45 }
4546
46 /// Places an asynchronous receiving request into the receiving queue.47 /// Places an asynchronous receiving request into the receiving queue.
47 pub fn receive(self: *const ManagedNetworkProtocol, token: *const ManagedNetworkCompletionToken) usize {48 pub fn receive(self: *const ManagedNetworkProtocol, token: *const ManagedNetworkCompletionToken) Status {
48 return self._receive(self, token);49 return self._receive(self, token);
49 }50 }
5051
51 /// Aborts an asynchronous transmit or receive request.52 /// Aborts an asynchronous transmit or receive request.
52 pub fn cancel(self: *const ManagedNetworkProtocol, token: ?*const ManagedNetworkCompletionToken) usize {53 pub fn cancel(self: *const ManagedNetworkProtocol, token: ?*const ManagedNetworkCompletionToken) Status {
53 return self._cancel(self, token);54 return self._cancel(self, token);
54 }55 }
5556
56 /// Polls for incoming data packets and processes outgoing data packets.57 /// Polls for incoming data packets and processes outgoing data packets.
57 pub fn poll(self: *const ManagedNetworkProtocol) usize {58 pub fn poll(self: *const ManagedNetworkProtocol) Status {
58 return self._poll(self);59 return self._poll(self);
59 }60 }
6061
...@@ -83,7 +84,7 @@ pub const ManagedNetworkConfigData = extern struct {...@@ -83,7 +84,7 @@ pub const ManagedNetworkConfigData = extern struct {
8384
84pub const ManagedNetworkCompletionToken = extern struct {85pub const ManagedNetworkCompletionToken = extern struct {
85 event: Event,86 event: Event,
86 status: usize,87 status: Status,
87 packet: extern union {88 packet: extern union {
88 RxData: *ManagedNetworkReceiveData,89 RxData: *ManagedNetworkReceiveData,
89 TxData: *ManagedNetworkTransmitData,90 TxData: *ManagedNetworkTransmitData,
lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig+5-4
...@@ -1,16 +1,17 @@...@@ -1,16 +1,17 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Handle = uefi.Handle;2const Handle = uefi.Handle;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5pub const ManagedNetworkServiceBindingProtocol = extern struct {6pub const ManagedNetworkServiceBindingProtocol = extern struct {
6 _create_child: extern fn (*const ManagedNetworkServiceBindingProtocol, *?Handle) usize,7 _create_child: extern fn (*const ManagedNetworkServiceBindingProtocol, *?Handle) Status,
7 _destroy_child: extern fn (*const ManagedNetworkServiceBindingProtocol, Handle) usize,8 _destroy_child: extern fn (*const ManagedNetworkServiceBindingProtocol, Handle) Status,
89
9 pub fn createChild(self: *const ManagedNetworkServiceBindingProtocol, handle: *?Handle) usize {10 pub fn createChild(self: *const ManagedNetworkServiceBindingProtocol, handle: *?Handle) Status {
10 return self._create_child(self, handle);11 return self._create_child(self, handle);
11 }12 }
1213
13 pub fn destroyChild(self: *const ManagedNetworkServiceBindingProtocol, handle: Handle) usize {14 pub fn destroyChild(self: *const ManagedNetworkServiceBindingProtocol, handle: Handle) Status {
14 return self._destroy_child(self, handle);15 return self._destroy_child(self, handle);
15 }16 }
1617
lib/std/os/uefi/protocols/rng_protocol.zig+5-4
...@@ -1,18 +1,19 @@...@@ -1,18 +1,19 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Status = uefi.Status;
34
4/// Random Number Generator protocol5/// Random Number Generator protocol
5pub const RNGProtocol = extern struct {6pub const RNGProtocol = extern struct {
6 _get_info: extern fn (*const RNGProtocol, *usize, [*]align(8) Guid) usize,7 _get_info: extern fn (*const RNGProtocol, *usize, [*]align(8) Guid) Status,
7 _get_rng: extern fn (*const RNGProtocol, ?*align(8) const Guid, usize, [*]u8) usize,8 _get_rng: extern fn (*const RNGProtocol, ?*align(8) const Guid, usize, [*]u8) Status,
89
9 /// Returns information about the random number generation implementation.10 /// Returns information about the random number generation implementation.
10 pub fn getInfo(self: *const RNGProtocol, list_size: *usize, list: [*]align(8) Guid) usize {11 pub fn getInfo(self: *const RNGProtocol, list_size: *usize, list: [*]align(8) Guid) Status {
11 return self._get_info(self, list_size, list);12 return self._get_info(self, list_size, list);
12 }13 }
1314
14 /// Produces and returns an RNG value using either the default or specified RNG algorithm.15 /// Produces and returns an RNG value using either the default or specified RNG algorithm.
15 pub fn getRNG(self: *const RNGProtocol, algo: ?*align(8) const Guid, value_length: usize, value: [*]u8) usize {16 pub fn getRNG(self: *const RNGProtocol, algo: ?*align(8) const Guid, value_length: usize, value: [*]u8) Status {
16 return self._get_rng(self, algo, value_length, value);17 return self._get_rng(self, algo, value_length, value);
17 }18 }
1819
lib/std/os/uefi/protocols/shell_parameters_protocol.zig created+20
...@@ -0,0 +1,20 @@
1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;
3const FileHandle = uefi.FileHandle;
4
5pub const ShellParametersProtocol = extern struct {
6 argv: [*][*:0]const u16,
7 argc: usize,
8 stdin: FileHandle,
9 stdout: FileHandle,
10 stderr: FileHandle,
11
12 pub const guid align(8) = Guid{
13 .time_low = 0x752f3136,
14 .time_mid = 0x4e16,
15 .time_high_and_version = 0x4fdc,
16 .clock_seq_high_and_reserved = 0xa2,
17 .clock_seq_low = 0x2a,
18 .node = [_]u8{ 0xe5, 0xf4, 0x68, 0x12, 0xf4, 0xca },
19 };
20};
lib/std/os/uefi/protocols/simple_file_system_protocol.zig created+22
...@@ -0,0 +1,22 @@
1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;
3const FileProtocol = uefi.protocols.FileProtocol;
4const Status = uefi.Status;
5
6pub const SimpleFileSystemProtocol = extern struct {
7 revision: u64,
8 _open_volume: extern fn (*const SimpleFileSystemProtocol, **const FileProtocol) Status,
9
10 pub fn openVolume(self: *const SimpleFileSystemProtocol, root: **const FileProtocol) Status {
11 return self._open_volume(self, root);
12 }
13
14 pub const guid align(8) = Guid{
15 .time_low = 0x0964e5b22,
16 .time_mid = 0x6459,
17 .time_high_and_version = 0x11d2,
18 .clock_seq_high_and_reserved = 0x8e,
19 .clock_seq_low = 0x39,
20 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
21 };
22};
lib/std/os/uefi/protocols/simple_network_protocol.zig+27-26
...@@ -1,87 +1,88 @@...@@ -1,87 +1,88 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Event = uefi.Event;2const Event = uefi.Event;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5pub const SimpleNetworkProtocol = extern struct {6pub const SimpleNetworkProtocol = extern struct {
6 revision: u64,7 revision: u64,
7 _start: extern fn (*const SimpleNetworkProtocol) usize,8 _start: extern fn (*const SimpleNetworkProtocol) Status,
8 _stop: extern fn (*const SimpleNetworkProtocol) usize,9 _stop: extern fn (*const SimpleNetworkProtocol) Status,
9 _initialize: extern fn (*const SimpleNetworkProtocol, usize, usize) usize,10 _initialize: extern fn (*const SimpleNetworkProtocol, usize, usize) Status,
10 _reset: extern fn (*const SimpleNetworkProtocol, bool) usize,11 _reset: extern fn (*const SimpleNetworkProtocol, bool) Status,
11 _shutdown: extern fn (*const SimpleNetworkProtocol) usize,12 _shutdown: extern fn (*const SimpleNetworkProtocol) Status,
12 _receive_filters: extern fn (*const SimpleNetworkProtocol, SimpleNetworkReceiveFilter, SimpleNetworkReceiveFilter, bool, usize, ?[*]const MacAddress) usize,13 _receive_filters: extern fn (*const SimpleNetworkProtocol, SimpleNetworkReceiveFilter, SimpleNetworkReceiveFilter, bool, usize, ?[*]const MacAddress) Status,
13 _station_address: extern fn (*const SimpleNetworkProtocol, bool, ?*const MacAddress) usize,14 _station_address: extern fn (*const SimpleNetworkProtocol, bool, ?*const MacAddress) Status,
14 _statistics: extern fn (*const SimpleNetworkProtocol, bool, ?*usize, ?*NetworkStatistics) usize,15 _statistics: extern fn (*const SimpleNetworkProtocol, bool, ?*usize, ?*NetworkStatistics) Status,
15 _mcast_ip_to_mac: extern fn (*const SimpleNetworkProtocol, bool, *const c_void, *MacAddress) usize,16 _mcast_ip_to_mac: extern fn (*const SimpleNetworkProtocol, bool, *const c_void, *MacAddress) Status,
16 _nvdata: extern fn (*const SimpleNetworkProtocol, bool, usize, usize, [*]u8) usize,17 _nvdata: extern fn (*const SimpleNetworkProtocol, bool, usize, usize, [*]u8) Status,
17 _get_status: extern fn (*const SimpleNetworkProtocol, *SimpleNetworkInterruptStatus, ?*?[*]u8) usize,18 _get_status: extern fn (*const SimpleNetworkProtocol, *SimpleNetworkInterruptStatus, ?*?[*]u8) Status,
18 _transmit: extern fn (*const SimpleNetworkProtocol, usize, usize, [*]const u8, ?*const MacAddress, ?*const MacAddress, ?*const u16) usize,19 _transmit: extern fn (*const SimpleNetworkProtocol, usize, usize, [*]const u8, ?*const MacAddress, ?*const MacAddress, ?*const u16) Status,
19 _receive: extern fn (*const SimpleNetworkProtocol, ?*usize, *usize, [*]u8, ?*MacAddress, ?*MacAddress, ?*u16) usize,20 _receive: extern fn (*const SimpleNetworkProtocol, ?*usize, *usize, [*]u8, ?*MacAddress, ?*MacAddress, ?*u16) Status,
20 wait_for_packet: Event,21 wait_for_packet: Event,
21 mode: *SimpleNetworkMode,22 mode: *SimpleNetworkMode,
2223
23 /// Changes the state of a network interface from "stopped" to "started".24 /// Changes the state of a network interface from "stopped" to "started".
24 pub fn start(self: *const SimpleNetworkProtocol) usize {25 pub fn start(self: *const SimpleNetworkProtocol) Status {
25 return self._start(self);26 return self._start(self);
26 }27 }
2728
28 /// Changes the state of a network interface from "started" to "stopped".29 /// Changes the state of a network interface from "started" to "stopped".
29 pub fn stop(self: *const SimpleNetworkProtocol) usize {30 pub fn stop(self: *const SimpleNetworkProtocol) Status {
30 return self._stop(self);31 return self._stop(self);
31 }32 }
3233
33 /// Resets a network adapter and allocates the transmit and receive buffers required by the network interface.34 /// Resets a network adapter and allocates the transmit and receive buffers required by the network interface.
34 pub fn initialize(self: *const SimpleNetworkProtocol, extra_rx_buffer_size: usize, extra_tx_buffer_size: usize) usize {35 pub fn initialize(self: *const SimpleNetworkProtocol, extra_rx_buffer_size: usize, extra_tx_buffer_size: usize) Status {
35 return self._initialize(self, extra_rx_buffer_size, extra_tx_buffer_size);36 return self._initialize(self, extra_rx_buffer_size, extra_tx_buffer_size);
36 }37 }
3738
38 /// Resets a network adapter and reinitializes it with the parameters that were provided in the previous call to initialize().39 /// Resets a network adapter and reinitializes it with the parameters that were provided in the previous call to initialize().
39 pub fn reset(self: *const SimpleNetworkProtocol, extended_verification: bool) usize {40 pub fn reset(self: *const SimpleNetworkProtocol, extended_verification: bool) Status {
40 return self._reset(self, extended_verification);41 return self._reset(self, extended_verification);
41 }42 }
4243
43 /// Resets a network adapter and leaves it in a state that is safe for another driver to initialize.44 /// Resets a network adapter and leaves it in a state that is safe for another driver to initialize.
44 pub fn shutdown(self: *const SimpleNetworkProtocol) usize {45 pub fn shutdown(self: *const SimpleNetworkProtocol) Status {
45 return self._shutdown(self);46 return self._shutdown(self);
46 }47 }
4748
48 /// Manages the multicast receive filters of a network interface.49 /// Manages the multicast receive filters of a network interface.
49 pub fn receiveFilters(self: *const SimpleNetworkProtocol, enable: SimpleNetworkReceiveFilter, disable: SimpleNetworkReceiveFilter, reset_mcast_filter: bool, mcast_filter_cnt: usize, mcast_filter: ?[*]const MacAddress) usize {50 pub fn receiveFilters(self: *const SimpleNetworkProtocol, enable: SimpleNetworkReceiveFilter, disable: SimpleNetworkReceiveFilter, reset_mcast_filter: bool, mcast_filter_cnt: usize, mcast_filter: ?[*]const MacAddress) Status {
50 return self._receive_filters(self, enable, disable, reset_mcast_filter, mcast_filter_cnt, mcast_filter);51 return self._receive_filters(self, enable, disable, reset_mcast_filter, mcast_filter_cnt, mcast_filter);
51 }52 }
5253
53 /// Modifies or resets the current station address, if supported.54 /// Modifies or resets the current station address, if supported.
54 pub fn stationAddress(self: *const SimpleNetworkProtocol, reset: bool, new: ?*const MacAddress) usize {55 pub fn stationAddress(self: *const SimpleNetworkProtocol, reset: bool, new: ?*const MacAddress) Status {
55 return self._station_address(self, reset, new);56 return self._station_address(self, reset, new);
56 }57 }
5758
58 /// Resets or collects the statistics on a network interface.59 /// Resets or collects the statistics on a network interface.
59 pub fn statistics(self: *const SimpleNetworkProtocol, reset_: bool, statistics_size: ?*usize, statistics_table: ?*NetworkStatistics) usize {60 pub fn statistics(self: *const SimpleNetworkProtocol, reset_: bool, statistics_size: ?*usize, statistics_table: ?*NetworkStatistics) Status {
60 return self._statistics(self, reset_, statistics_size, statistics_table);61 return self._statistics(self, reset_, statistics_size, statistics_table);
61 }62 }
6263
63 /// Converts a multicast IP address to a multicast HW MAC address.64 /// Converts a multicast IP address to a multicast HW MAC address.
64 pub fn mcastIpToMac(self: *const SimpleNetworkProtocol, ipv6: bool, ip: *const c_void, mac: *MacAddress) usize {65 pub fn mcastIpToMac(self: *const SimpleNetworkProtocol, ipv6: bool, ip: *const c_void, mac: *MacAddress) Status {
65 return self._mcast_ip_to_mac(self, ipv6, ip, mac);66 return self._mcast_ip_to_mac(self, ipv6, ip, mac);
66 }67 }
6768
68 /// Performs read and write operations on the NVRAM device attached to a network interface.69 /// Performs read and write operations on the NVRAM device attached to a network interface.
69 pub fn nvdata(self: *const SimpleNetworkProtocol, read_write: bool, offset: usize, buffer_size: usize, buffer: [*]u8) usize {70 pub fn nvdata(self: *const SimpleNetworkProtocol, read_write: bool, offset: usize, buffer_size: usize, buffer: [*]u8) Status {
70 return self._nvdata(self, read_write, offset, buffer_size, buffer);71 return self._nvdata(self, read_write, offset, buffer_size, buffer);
71 }72 }
7273
73 /// Reads the current interrupt status and recycled transmit buffer status from a network interface.74 /// Reads the current interrupt status and recycled transmit buffer status from a network interface.
74 pub fn getStatus(self: *const SimpleNetworkProtocol, interrupt_status: *SimpleNetworkInterruptStatus, tx_buf: ?*?[*]u8) usize {75 pub fn getStatus(self: *const SimpleNetworkProtocol, interrupt_status: *SimpleNetworkInterruptStatus, tx_buf: ?*?[*]u8) Status {
75 return self._get_status(self, interrupt_status, tx_buf);76 return self._get_status(self, interrupt_status, tx_buf);
76 }77 }
7778
78 /// Places a packet in the transmit queue of a network interface.79 /// Places a packet in the transmit queue of a network interface.
79 pub fn transmit(self: *const SimpleNetworkProtocol, header_size: usize, buffer_size: usize, buffer: [*]const u8, src_addr: ?*const MacAddress, dest_addr: ?*const MacAddress, protocol: ?*const u16) usize {80 pub fn transmit(self: *const SimpleNetworkProtocol, header_size: usize, buffer_size: usize, buffer: [*]const u8, src_addr: ?*const MacAddress, dest_addr: ?*const MacAddress, protocol: ?*const u16) Status {
80 return self._transmit(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);81 return self._transmit(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
81 }82 }
8283
83 /// Receives a packet from a network interface.84 /// Receives a packet from a network interface.
84 pub fn receive(self: *const SimpleNetworkProtocol, header_size: ?*usize, buffer_size: *usize, buffer: [*]u8, src_addr: ?*MacAddress, dest_addr: ?*MacAddress, protocol: ?*u16) usize {85 pub fn receive(self: *const SimpleNetworkProtocol, header_size: ?*usize, buffer_size: *usize, buffer: [*]u8, src_addr: ?*MacAddress, dest_addr: ?*MacAddress, protocol: ?*u16) Status {
85 return self._receive(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);86 return self._receive(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
86 }87 }
8788
lib/std/os/uefi/protocols/simple_pointer_protocol.zig+5-4
...@@ -1,21 +1,22 @@...@@ -1,21 +1,22 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Event = uefi.Event;2const Event = uefi.Event;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5/// Protocol for mice6/// Protocol for mice
6pub const SimplePointerProtocol = struct {7pub const SimplePointerProtocol = struct {
7 _reset: extern fn (*const SimplePointerProtocol, bool) usize,8 _reset: extern fn (*const SimplePointerProtocol, bool) Status,
8 _get_state: extern fn (*const SimplePointerProtocol, *SimplePointerState) usize,9 _get_state: extern fn (*const SimplePointerProtocol, *SimplePointerState) Status,
9 wait_for_input: Event,10 wait_for_input: Event,
10 mode: *SimplePointerMode,11 mode: *SimplePointerMode,
1112
12 /// Resets the pointer device hardware.13 /// Resets the pointer device hardware.
13 pub fn reset(self: *const SimplePointerProtocol, verify: bool) usize {14 pub fn reset(self: *const SimplePointerProtocol, verify: bool) Status {
14 return self._reset(self, verify);15 return self._reset(self, verify);
15 }16 }
1617
17 /// Retrieves the current state of a pointer device.18 /// Retrieves the current state of a pointer device.
18 pub fn getState(self: *const SimplePointerProtocol, state: *SimplePointerState) usize {19 pub fn getState(self: *const SimplePointerProtocol, state: *SimplePointerState) Status {
19 return self._get_state(self, state);20 return self._get_state(self, state);
20 }21 }
2122
lib/std/os/uefi/protocols/simple_text_input_ex_protocol.zig+11-10
...@@ -1,38 +1,39 @@...@@ -1,38 +1,39 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Event = uefi.Event;2const Event = uefi.Event;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5/// Character input devices, e.g. Keyboard6/// Character input devices, e.g. Keyboard
6pub const SimpleTextInputExProtocol = extern struct {7pub const SimpleTextInputExProtocol = extern struct {
7 _reset: extern fn (*const SimpleTextInputExProtocol, bool) usize,8 _reset: extern fn (*const SimpleTextInputExProtocol, bool) Status,
8 _read_key_stroke_ex: extern fn (*const SimpleTextInputExProtocol, *KeyData) usize,9 _read_key_stroke_ex: extern fn (*const SimpleTextInputExProtocol, *KeyData) Status,
9 wait_for_key_ex: Event,10 wait_for_key_ex: Event,
10 _set_state: extern fn (*const SimpleTextInputExProtocol, *const u8) usize,11 _set_state: extern fn (*const SimpleTextInputExProtocol, *const u8) Status,
11 _register_key_notify: extern fn (*const SimpleTextInputExProtocol, *const KeyData, extern fn (*const KeyData) usize, **c_void) usize,12 _register_key_notify: extern fn (*const SimpleTextInputExProtocol, *const KeyData, extern fn (*const KeyData) usize, **c_void) Status,
12 _unregister_key_notify: extern fn (*const SimpleTextInputExProtocol, *const c_void) usize,13 _unregister_key_notify: extern fn (*const SimpleTextInputExProtocol, *const c_void) Status,
1314
14 /// Resets the input device hardware.15 /// Resets the input device hardware.
15 pub fn reset(self: *const SimpleTextInputExProtocol, verify: bool) usize {16 pub fn reset(self: *const SimpleTextInputExProtocol, verify: bool) Status {
16 return self._reset(self, verify);17 return self._reset(self, verify);
17 }18 }
1819
19 /// Reads the next keystroke from the input device.20 /// Reads the next keystroke from the input device.
20 pub fn readKeyStrokeEx(self: *const SimpleTextInputExProtocol, key_data: *KeyData) usize {21 pub fn readKeyStrokeEx(self: *const SimpleTextInputExProtocol, key_data: *KeyData) Status {
21 return self._read_key_stroke_ex(self, key_data);22 return self._read_key_stroke_ex(self, key_data);
22 }23 }
2324
24 /// Set certain state for the input device.25 /// Set certain state for the input device.
25 pub fn setState(self: *const SimpleTextInputExProtocol, state: *const u8) usize {26 pub fn setState(self: *const SimpleTextInputExProtocol, state: *const u8) Status {
26 return self._set_state(self, state);27 return self._set_state(self, state);
27 }28 }
2829
29 /// Register a notification function for a particular keystroke for the input device.30 /// Register a notification function for a particular keystroke for the input device.
30 pub fn registerKeyNotify(self: *const SimpleTextInputExProtocol, key_data: *const KeyData, notify: extern fn (*const KeyData) usize, handle: **c_void) usize {31 pub fn registerKeyNotify(self: *const SimpleTextInputExProtocol, key_data: *const KeyData, notify: extern fn (*const KeyData) usize, handle: **c_void) Status {
31 return self._register_key_notify(self, key_data, notify, handle);32 return self._register_key_notify(self, key_data, notify, handle);
32 }33 }
3334
34 /// Remove the notification that was previously registered.35 /// Remove the notification that was previously registered.
35 pub fn unregisterKeyNotify(self: *const SimpleTextInputExProtocol, handle: *const c_void) usize {36 pub fn unregisterKeyNotify(self: *const SimpleTextInputExProtocol, handle: *const c_void) Status {
36 return self._unregister_key_notify(self, handle);37 return self._unregister_key_notify(self, handle);
37 }38 }
3839
lib/std/os/uefi/protocols/simple_text_input_protocol.zig+5-3
...@@ -1,20 +1,22 @@...@@ -1,20 +1,22 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Event = uefi.Event;2const Event = uefi.Event;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const InputKey = uefi.protocols.InputKey;
5const Status = uefi.Status;
46
5/// Character input devices, e.g. Keyboard7/// Character input devices, e.g. Keyboard
6pub const SimpleTextInputProtocol = extern struct {8pub const SimpleTextInputProtocol = extern struct {
7 _reset: extern fn (*const SimpleTextInputProtocol, bool) usize,9 _reset: extern fn (*const SimpleTextInputProtocol, bool) usize,
8 _read_key_stroke: extern fn (*const SimpleTextInputProtocol, *uefi.protocols.InputKey) usize,10 _read_key_stroke: extern fn (*const SimpleTextInputProtocol, *InputKey) Status,
9 wait_for_key: Event,11 wait_for_key: Event,
1012
11 /// Resets the input device hardware.13 /// Resets the input device hardware.
12 pub fn reset(self: *const SimpleTextInputProtocol, verify: bool) usize {14 pub fn reset(self: *const SimpleTextInputProtocol, verify: bool) Status {
13 return self._reset(self, verify);15 return self._reset(self, verify);
14 }16 }
1517
16 /// Reads the next keystroke from the input device.18 /// Reads the next keystroke from the input device.
17 pub fn readKeyStroke(self: *const SimpleTextInputProtocol, input_key: *uefi.protocols.InputKey) usize {19 pub fn readKeyStroke(self: *const SimpleTextInputProtocol, input_key: *InputKey) Status {
18 return self._read_key_stroke(self, input_key);20 return self._read_key_stroke(self, input_key);
19 }21 }
2022
lib/std/os/uefi/protocols/simple_text_output_protocol.zig+19-18
...@@ -1,61 +1,62 @@...@@ -1,61 +1,62 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Status = uefi.Status;
34
4/// Character output devices5/// Character output devices
5pub const SimpleTextOutputProtocol = extern struct {6pub const SimpleTextOutputProtocol = extern struct {
6 _reset: extern fn (*const SimpleTextOutputProtocol, bool) usize,7 _reset: extern fn (*const SimpleTextOutputProtocol, bool) Status,
7 _output_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) usize,8 _output_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) Status,
8 _test_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) usize,9 _test_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) Status,
9 _query_mode: extern fn (*const SimpleTextOutputProtocol, usize, *usize, *usize) usize,10 _query_mode: extern fn (*const SimpleTextOutputProtocol, usize, *usize, *usize) Status,
10 _set_mode: extern fn (*const SimpleTextOutputProtocol, usize) usize,11 _set_mode: extern fn (*const SimpleTextOutputProtocol, usize) Status,
11 _set_attribute: extern fn (*const SimpleTextOutputProtocol, usize) usize,12 _set_attribute: extern fn (*const SimpleTextOutputProtocol, usize) Status,
12 _clear_screen: extern fn (*const SimpleTextOutputProtocol) usize,13 _clear_screen: extern fn (*const SimpleTextOutputProtocol) Status,
13 _set_cursor_position: extern fn (*const SimpleTextOutputProtocol, usize, usize) usize,14 _set_cursor_position: extern fn (*const SimpleTextOutputProtocol, usize, usize) Status,
14 _enable_cursor: extern fn (*const SimpleTextOutputProtocol, bool) usize,15 _enable_cursor: extern fn (*const SimpleTextOutputProtocol, bool) Status,
15 mode: *SimpleTextOutputMode,16 mode: *SimpleTextOutputMode,
1617
17 /// Resets the text output device hardware.18 /// Resets the text output device hardware.
18 pub fn reset(self: *const SimpleTextOutputProtocol, verify: bool) usize {19 pub fn reset(self: *const SimpleTextOutputProtocol, verify: bool) Status {
19 return self._reset(self, verify);20 return self._reset(self, verify);
20 }21 }
2122
22 /// Writes a string to the output device.23 /// Writes a string to the output device.
23 pub fn outputString(self: *const SimpleTextOutputProtocol, msg: [*:0]const u16) usize {24 pub fn outputString(self: *const SimpleTextOutputProtocol, msg: [*:0]const u16) Status {
24 return self._output_string(self, msg);25 return self._output_string(self, msg);
25 }26 }
2627
27 /// Verifies that all characters in a string can be output to the target device.28 /// Verifies that all characters in a string can be output to the target device.
28 pub fn testString(self: *const SimpleTextOutputProtocol, msg: [*:0]const u16) usize {29 pub fn testString(self: *const SimpleTextOutputProtocol, msg: [*:0]const u16) Status {
29 return self._test_string(self, msg);30 return self._test_string(self, msg);
30 }31 }
3132
32 /// Returns information for an available text mode that the output device(s) supports.33 /// Returns information for an available text mode that the output device(s) supports.
33 pub fn queryMode(self: *const SimpleTextOutputProtocol, mode_number: usize, columns: *usize, rows: *usize) usize {34 pub fn queryMode(self: *const SimpleTextOutputProtocol, mode_number: usize, columns: *usize, rows: *usize) Status {
34 return self._query_mode(self, mode_number, columns, rows);35 return self._query_mode(self, mode_number, columns, rows);
35 }36 }
3637
37 /// Sets the output device(s) to a specified mode.38 /// Sets the output device(s) to a specified mode.
38 pub fn setMode(self: *const SimpleTextOutputProtocol, mode_number: usize) usize {39 pub fn setMode(self: *const SimpleTextOutputProtocol, mode_number: usize) Status {
39 return self._set_mode(self, mode_number);40 return self._set_mode(self, mode_number);
40 }41 }
4142
42 /// Sets the background and foreground colors for the outputString() and clearScreen() functions.43 /// Sets the background and foreground colors for the outputString() and clearScreen() functions.
43 pub fn setAttribute(self: *const SimpleTextOutputProtocol, attribute: usize) usize {44 pub fn setAttribute(self: *const SimpleTextOutputProtocol, attribute: usize) Status {
44 return self._set_attribute(self, attribute);45 return self._set_attribute(self, attribute);
45 }46 }
4647
47 /// Clears the output device(s) display to the currently selected background color.48 /// Clears the output device(s) display to the currently selected background color.
48 pub fn clearScreen(self: *const SimpleTextOutputProtocol) usize {49 pub fn clearScreen(self: *const SimpleTextOutputProtocol) Status {
49 return self._clear_screen(self);50 return self._clear_screen(self);
50 }51 }
5152
52 /// Sets the current coordinates of the cursor position.53 /// Sets the current coordinates of the cursor position.
53 pub fn setCursorPosition(self: *const SimpleTextOutputProtocol, column: usize, row: usize) usize {54 pub fn setCursorPosition(self: *const SimpleTextOutputProtocol, column: usize, row: usize) Status {
54 return self._set_cursor_position(self, column, row);55 return self._set_cursor_position(self, column, row);
55 }56 }
5657
57 /// Makes the cursor visible or invisible.58 /// Makes the cursor visible or invisible.
58 pub fn enableCursor(self: *const SimpleTextOutputProtocol, visible: bool) usize {59 pub fn enableCursor(self: *const SimpleTextOutputProtocol, visible: bool) Status {
59 return self._enable_cursor(self, visible);60 return self._enable_cursor(self, visible);
60 }61 }
6162
lib/std/os/uefi/protocols/udp6_protocol.zig+17-16
...@@ -1,6 +1,7 @@...@@ -1,6 +1,7 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Guid = uefi.Guid;2const Guid = uefi.Guid;
3const Event = uefi.Event;3const Event = uefi.Event;
4const Status = uefi.Status;
4const Time = uefi.Time;5const Time = uefi.Time;
5const Ip6ModeData = uefi.protocols.Ip6ModeData;6const Ip6ModeData = uefi.protocols.Ip6ModeData;
6const Ip6Address = uefi.protocols.Ip6Address;7const Ip6Address = uefi.protocols.Ip6Address;
...@@ -8,39 +9,39 @@ const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;...@@ -8,39 +9,39 @@ const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
8const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;9const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
910
10pub const Udp6Protocol = extern struct {11pub const Udp6Protocol = extern struct {
11 _get_mode_data: extern fn (*const Udp6Protocol, ?*Udp6ConfigData, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,12 _get_mode_data: extern fn (*const Udp6Protocol, ?*Udp6ConfigData, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) Status,
12 _configure: extern fn (*const Udp6Protocol, ?*const Udp6ConfigData) usize,13 _configure: extern fn (*const Udp6Protocol, ?*const Udp6ConfigData) Status,
13 _groups: extern fn (*const Udp6Protocol, bool, ?*const Ip6Address) usize,14 _groups: extern fn (*const Udp6Protocol, bool, ?*const Ip6Address) Status,
14 _transmit: extern fn (*const Udp6Protocol, *Udp6CompletionToken) usize,15 _transmit: extern fn (*const Udp6Protocol, *Udp6CompletionToken) Status,
15 _receive: extern fn (*const Udp6Protocol, *Udp6CompletionToken) usize,16 _receive: extern fn (*const Udp6Protocol, *Udp6CompletionToken) Status,
16 _cancel: extern fn (*const Udp6Protocol, ?*Udp6CompletionToken) usize,17 _cancel: extern fn (*const Udp6Protocol, ?*Udp6CompletionToken) Status,
17 _poll: extern fn (*const Udp6Protocol) usize,18 _poll: extern fn (*const Udp6Protocol) Status,
1819
19 pub fn getModeData(self: *const Udp6Protocol, udp6_config_data: ?*Udp6ConfigData, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {20 pub fn getModeData(self: *const Udp6Protocol, udp6_config_data: ?*Udp6ConfigData, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status {
20 return self._get_mode_data(self, udp6_config_data, ip6_mode_data, mnp_config_data, snp_mode_data);21 return self._get_mode_data(self, udp6_config_data, ip6_mode_data, mnp_config_data, snp_mode_data);
21 }22 }
2223
23 pub fn configure(self: *const Udp6Protocol, udp6_config_data: ?*const Udp6ConfigData) usize {24 pub fn configure(self: *const Udp6Protocol, udp6_config_data: ?*const Udp6ConfigData) Status {
24 return self._configure(self, udp6_config_data);25 return self._configure(self, udp6_config_data);
25 }26 }
2627
27 pub fn groups(self: *const Udp6Protocol, join_flag: bool, multicast_address: ?*const Ip6Address) usize {28 pub fn groups(self: *const Udp6Protocol, join_flag: bool, multicast_address: ?*const Ip6Address) Status {
28 return self._groups(self, join_flag, multicast_address);29 return self._groups(self, join_flag, multicast_address);
29 }30 }
3031
31 pub fn transmit(self: *const Udp6Protocol, token: *Udp6CompletionToken) usize {32 pub fn transmit(self: *const Udp6Protocol, token: *Udp6CompletionToken) Status {
32 return self._transmit(self, token);33 return self._transmit(self, token);
33 }34 }
3435
35 pub fn receive(self: *const Udp6Protocol, token: *Udp6CompletionToken) usize {36 pub fn receive(self: *const Udp6Protocol, token: *Udp6CompletionToken) Status {
36 return self._receive(self, token);37 return self._receive(self, token);
37 }38 }
3839
39 pub fn cancel(self: *const Udp6Protocol, token: ?*Udp6CompletionToken) usize {40 pub fn cancel(self: *const Udp6Protocol, token: ?*Udp6CompletionToken) Status {
40 return self._cancel(self, token);41 return self._cancel(self, token);
41 }42 }
4243
43 pub fn poll(self: *const Udp6Protocol) usize {44 pub fn poll(self: *const Udp6Protocol) Status {
44 return self._poll(self);45 return self._poll(self);
45 }46 }
4647
...@@ -70,7 +71,7 @@ pub const Udp6ConfigData = extern struct {...@@ -70,7 +71,7 @@ pub const Udp6ConfigData = extern struct {
7071
71pub const Udp6CompletionToken = extern struct {72pub const Udp6CompletionToken = extern struct {
72 event: Event,73 event: Event,
73 status: usize,74 Status: usize,
74 packet: extern union {75 packet: extern union {
75 RxData: *Udp6ReceiveData,76 RxData: *Udp6ReceiveData,
76 TxData: *Udp6TransmitData,77 TxData: *Udp6TransmitData,
lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig+5-4
...@@ -1,16 +1,17 @@...@@ -1,16 +1,17 @@
1const uefi = @import("std").os.uefi;1const uefi = @import("std").os.uefi;
2const Handle = uefi.Handle;2const Handle = uefi.Handle;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Status = uefi.Status;
45
5pub const Udp6ServiceBindingProtocol = extern struct {6pub const Udp6ServiceBindingProtocol = extern struct {
6 _create_child: extern fn (*const Udp6ServiceBindingProtocol, *?Handle) usize,7 _create_child: extern fn (*const Udp6ServiceBindingProtocol, *?Handle) Status,
7 _destroy_child: extern fn (*const Udp6ServiceBindingProtocol, Handle) usize,8 _destroy_child: extern fn (*const Udp6ServiceBindingProtocol, Handle) Status,
89
9 pub fn createChild(self: *const Udp6ServiceBindingProtocol, handle: *?Handle) usize {10 pub fn createChild(self: *const Udp6ServiceBindingProtocol, handle: *?Handle) Status {
10 return self._create_child(self, handle);11 return self._create_child(self, handle);
11 }12 }
1213
13 pub fn destroyChild(self: *const Udp6ServiceBindingProtocol, handle: Handle) usize {14 pub fn destroyChild(self: *const Udp6ServiceBindingProtocol, handle: Handle) Status {
14 return self._destroy_child(self, handle);15 return self._destroy_child(self, handle);
15 }16 }
1617
lib/std/os/uefi/status.zig+100-82
...@@ -1,124 +1,142 @@...@@ -1,124 +1,142 @@
1const high_bit = 1 << @typeInfo(usize).Int.bits - 1;1const high_bit = 1 << @typeInfo(usize).Int.bits - 1;
22
3/// The operation completed successfully.3pub const Status = extern enum(usize) {
4pub const success: usize = 0;4 /// The operation completed successfully.
5 Success = 0,
56
6/// The image failed to load.7 /// The image failed to load.
7pub const load_error: usize = high_bit | 1;8 LoadError = high_bit | 1,
89
9/// A parameter was incorrect.10 /// A parameter was incorrect.
10pub const invalid_parameter: usize = high_bit | 2;11 InvalidParameter = high_bit | 2,
1112
12/// The operation is not supported.13 /// The operation is not supported.
13pub const unsupported: usize = high_bit | 3;14 Unsupported = high_bit | 3,
1415
15/// The buffer was not the proper size for the request.16 /// The buffer was not the proper size for the request.
16pub const bad_buffer_size: usize = high_bit | 4;17 BadBufferSize = high_bit | 4,
1718
18/// The buffer is not large enough to hold the requested data. The required buffer size is returned in the appropriate parameter when this error occurs.19 /// The buffer is not large enough to hold the requested data. The required buffer size is returned in the appropriate parameter when this error occurs.
19pub const buffer_too_small: usize = high_bit | 5;20 BufferTooSmall = high_bit | 5,
2021
21/// There is no data pending upon return.22 /// There is no data pending upon return.
22pub const not_ready: usize = high_bit | 6;23 NotReady = high_bit | 6,
2324
24/// The physical device reported an error while attempting the operation.25 /// The physical device reported an error while attempting the operation.
25pub const device_error: usize = high_bit | 7;26 DeviceError = high_bit | 7,
2627
27/// The device cannot be written to.28 /// The device cannot be written to.
28pub const write_protected: usize = high_bit | 8;29 WriteProtected = high_bit | 8,
2930
30/// A resource has run out.31 /// A resource has run out.
31pub const out_of_resources: usize = high_bit | 9;32 OutOfResources = high_bit | 9,
3233
33/// An inconstancy was detected on the file system causing the operating to fail.34 /// An inconstancy was detected on the file system causing the operating to fail.
34pub const volume_corrupted: usize = high_bit | 10;35 VolumeCorrupted = high_bit | 10,
3536
36/// There is no more space on the file system.37 /// There is no more space on the file system.
37pub const volume_full: usize = high_bit | 11;38 VolumeFull = high_bit | 11,
3839
39/// The device does not contain any medium to perform the operation.40 /// The device does not contain any medium to perform the operation.
40pub const no_media: usize = high_bit | 12;41 NoMedia = high_bit | 12,
4142
42/// The medium in the device has changed since the last access.43 /// The medium in the device has changed since the last access.
43pub const media_changed: usize = high_bit | 13;44 MediaChanged = high_bit | 13,
4445
45/// The item was not found.46 /// The item was not found.
46pub const not_found: usize = high_bit | 14;47 NotFound = high_bit | 14,
4748
48/// Access was denied.49 /// Access was denied.
49pub const access_denied: usize = high_bit | 15;50 AccessDenied = high_bit | 15,
5051
51/// The server was not found or did not respond to the request.52 /// The server was not found or did not respond to the request.
52pub const no_response: usize = high_bit | 16;53 NoResponse = high_bit | 16,
5354
54/// A mapping to a device does not exist.55 /// A mapping to a device does not exist.
55pub const no_mapping: usize = high_bit | 17;56 NoMapping = high_bit | 17,
5657
57/// The timeout time expired.58 /// The timeout time expired.
58pub const timeout: usize = high_bit | 18;59 Timeout = high_bit | 18,
5960
60/// The protocol has not been started.61 /// The protocol has not been started.
61pub const not_started: usize = high_bit | 19;62 NotStarted = high_bit | 19,
6263
63/// The protocol has already been started.64 /// The protocol has already been started.
64pub const already_started: usize = high_bit | 20;65 AlreadyStarted = high_bit | 20,
6566
66/// The operation was aborted.67 /// The operation was aborted.
67pub const aborted: usize = high_bit | 21;68 Aborted = high_bit | 21,
6869
69/// An ICMP error occurred during the network operation.70 /// An ICMP error occurred during the network operation.
70pub const icmp_error: usize = high_bit | 22;71 IcmpError = high_bit | 22,
7172
72/// A TFTP error occurred during the network operation.73 /// A TFTP error occurred during the network operation.
73pub const tftp_error: usize = high_bit | 23;74 TftpError = high_bit | 23,
7475
75/// A protocol error occurred during the network operation.76 /// A protocol error occurred during the network operation.
76pub const protocol_error: usize = high_bit | 24;77 ProtocolError = high_bit | 24,
7778
78/// The function encountered an internal version that was incompatible with a version requested by the caller.79 /// The function encountered an internal version that was incompatible with a version requested by the caller.
79pub const incompatible_version: usize = high_bit | 25;80 IncompatibleVersion = high_bit | 25,
8081
81/// The function was not performed due to a security violation.82 /// The function was not performed due to a security violation.
82pub const security_violation: usize = high_bit | 26;83 SecurityViolation = high_bit | 26,
8384
84/// A CRC error was detected.85 /// A CRC error was detected.
85pub const crc_error: usize = high_bit | 27;86 CrcError = high_bit | 27,
8687
87/// Beginning or end of media was reached88 /// Beginning or end of media was reached
88pub const end_of_media: usize = high_bit | 28;89 EndOfMedia = high_bit | 28,
8990
90/// The end of the file was reached.91 /// The end of the file was reached.
91pub const end_of_file: usize = high_bit | 31;92 EndOfFile = high_bit | 31,
9293
93/// The language specified was invalid.94 /// The language specified was invalid.
94pub const invalid_language: usize = high_bit | 32;95 InvalidLanguage = high_bit | 32,
9596
96/// The security status of the data is unknown or compromised and the data must be updated or replaced to restore a valid security status.97 /// The security status of the data is unknown or compromised and the data must be updated or replaced to restore a valid security status.
97pub const compromised_data: usize = high_bit | 33;98 CompromisedData = high_bit | 33,
9899
99/// There is an address conflict address allocation100 /// There is an address conflict address allocation
100pub const ip_address_conflict: usize = high_bit | 34;101 IpAddressConflict = high_bit | 34,
101102
102/// A HTTP error occurred during the network operation.103 /// A HTTP error occurred during the network operation.
103pub const http_error: usize = high_bit | 35;104 HttpError = high_bit | 35,
104105
105/// The string contained one or more characters that the device could not render and were skipped.106 NetworkUnreachable = high_bit | 100,
106pub const warn_unknown_glyph: usize = 1;
107107
108/// The handle was closed, but the file was not deleted.108 HostUnreachable = high_bit | 101,
109pub const warn_delete_failure: usize = 2;
110109
111/// The handle was closed, but the data to the file was not flushed properly.110 ProtocolUnreachable = high_bit | 102,
112pub const warn_write_failure: usize = 3;
113111
114/// The resulting buffer was too small, and the data was truncated to the buffer size.112 PortUnreachable = high_bit | 103,
115pub const warn_buffer_too_small: usize = 4;
116113
117/// The data has not been updated within the timeframe set by localpolicy for this type of data.114 ConnectionFin = high_bit | 104,
118pub const warn_stale_data: usize = 5;
119115
120/// The resulting buffer contains UEFI-compliant file system.116 ConnectionReset = high_bit | 105,
121pub const warn_file_system: usize = 6;
122117
123/// The operation will be processed across a system reset.118 ConnectionRefused = high_bit | 106,
124pub const warn_reset_required: usize = 7;119
120 /// The string contained one or more characters that the device could not render and were skipped.
121 WarnUnknownGlyph = 1,
122
123 /// The handle was closed, but the file was not deleted.
124 WarnDeleteFailure = 2,
125
126 /// The handle was closed, but the data to the file was not flushed properly.
127 WarnWriteFailure = 3,
128
129 /// The resulting buffer was too small, and the data was truncated to the buffer size.
130 WarnBufferTooSmall = 4,
131
132 /// The data has not been updated within the timeframe set by localpolicy for this type of data.
133 WarnStaleData = 5,
134
135 /// The resulting buffer contains UEFI-compliant file system.
136 WarnFileSystem = 6,
137
138 /// The operation will be processed across a system reset.
139 WarnResetRequired = 7,
140
141 _,
142};
lib/std/os/uefi/tables.zig+1
...@@ -1,3 +1,4 @@...@@ -1,3 +1,4 @@
1pub const AllocateType = @import("tables/boot_services.zig").AllocateType;
1pub const BootServices = @import("tables/boot_services.zig").BootServices;2pub const BootServices = @import("tables/boot_services.zig").BootServices;
2pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;3pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;
3pub const global_variable align(8) = @import("tables/runtime_services.zig").global_variable;4pub const global_variable align(8) = @import("tables/runtime_services.zig").global_variable;
lib/std/os/uefi/tables/boot_services.zig+76-50
...@@ -2,6 +2,7 @@ const uefi = @import("std").os.uefi;...@@ -2,6 +2,7 @@ const uefi = @import("std").os.uefi;
2const Event = uefi.Event;2const Event = uefi.Event;
3const Guid = uefi.Guid;3const Guid = uefi.Guid;
4const Handle = uefi.Handle;4const Handle = uefi.Handle;
5const Status = uefi.Status;
5const TableHeader = uefi.tables.TableHeader;6const TableHeader = uefi.tables.TableHeader;
6const DevicePathProtocol = uefi.protocols.DevicePathProtocol;7const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
78
...@@ -19,101 +20,120 @@ const DevicePathProtocol = uefi.protocols.DevicePathProtocol;...@@ -19,101 +20,120 @@ const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
19pub const BootServices = extern struct {20pub const BootServices = extern struct {
20 hdr: TableHeader,21 hdr: TableHeader,
2122
22 raiseTpl: usize, // TODO23 /// Raises a task's priority level and returns its previous level.
23 restoreTpl: usize, // TODO24 raiseTpl: extern fn (usize) usize,
24 allocatePages: usize, // TODO25
25 freePages: usize, // TODO26 /// Restores a task's priority level to its previous value.
27 restoreTpl: extern fn (usize) void,
28
29 /// Allocates memory pages from the system.
30 allocatePages: extern fn (AllocateType, MemoryType, usize, *[*]align(4096) u8) Status,
31
32 /// Frees memory pages.
33 freePages: extern fn ([*]align(4096) u8, usize) Status,
2634
27 /// Returns the current memory map.35 /// Returns the current memory map.
28 getMemoryMap: extern fn (*usize, [*]MemoryDescriptor, *usize, *usize, *u32) usize,36 getMemoryMap: extern fn (*usize, [*]MemoryDescriptor, *usize, *usize, *u32) Status,
2937
30 /// Allocates pool memory.38 /// Allocates pool memory.
31 allocatePool: extern fn (MemoryType, usize, *align(8) [*]u8) usize,39 allocatePool: extern fn (MemoryType, usize, *[*]align(8) u8) Status,
3240
33 /// Returns pool memory to the system.41 /// Returns pool memory to the system.
34 freePool: extern fn ([*]align(8) u8) usize,42 freePool: extern fn ([*]align(8) u8) Status,
3543
36 /// Creates an event.44 /// Creates an event.
37 createEvent: extern fn (u32, usize, ?extern fn (Event, ?*c_void) void, ?*const c_void, *Event) usize,45 createEvent: extern fn (u32, usize, ?extern fn (Event, ?*c_void) void, ?*const c_void, *Event) Status,
3846
39 /// Sets the type of timer and the trigger time for a timer event.47 /// Sets the type of timer and the trigger time for a timer event.
40 setTimer: extern fn (Event, TimerDelay, u64) usize,48 setTimer: extern fn (Event, TimerDelay, u64) Status,
4149
42 /// Stops execution until an event is signaled.50 /// Stops execution until an event is signaled.
43 waitForEvent: extern fn (usize, [*]const Event, *usize) usize,51 waitForEvent: extern fn (usize, [*]const Event, *usize) Status,
4452
45 /// Signals an event.53 /// Signals an event.
46 signalEvent: extern fn (Event) usize,54 signalEvent: extern fn (Event) Status,
4755
48 /// Closes an event.56 /// Closes an event.
49 closeEvent: extern fn (Event) usize,57 closeEvent: extern fn (Event) Status,
5058
51 /// Checks whether an event is in the signaled state.59 /// Checks whether an event is in the signaled state.
52 checkEvent: extern fn (Event) usize,60 checkEvent: extern fn (Event) Status,
5361
54 installProtocolInterface: usize, // TODO62 installProtocolInterface: Status, // TODO
55 reinstallProtocolInterface: usize, // TODO63 reinstallProtocolInterface: Status, // TODO
56 uninstallProtocolInterface: usize, // TODO64 uninstallProtocolInterface: Status, // TODO
5765
58 /// Queries a handle to determine if it supports a specified protocol.66 /// Queries a handle to determine if it supports a specified protocol.
59 handleProtocol: extern fn (Handle, *align(8) const Guid, *?*c_void) usize,67 handleProtocol: extern fn (Handle, *align(8) const Guid, *?*c_void) Status,
6068
61 reserved: *c_void,69 reserved: *c_void,
6270
63 registerProtocolNotify: usize, // TODO71 registerProtocolNotify: Status, // TODO
64 locateHandle: usize, // TODO72
65 locateDevicePath: usize, // TODO73 /// Returns an array of handles that support a specified protocol.
66 installConfigurationTable: usize, // TODO74 locateHandle: extern fn (LocateSearchType, ?*align(8) const Guid, ?*const c_void, *usize, [*]Handle) Status,
75
76 locateDevicePath: Status, // TODO
77 installConfigurationTable: Status, // TODO
6778
68 /// Loads an EFI image into memory.79 /// Loads an EFI image into memory.
69 loadImage: extern fn (bool, Handle, ?*const DevicePathProtocol, ?[*]const u8, usize, *?Handle) usize,80 loadImage: extern fn (bool, Handle, ?*const DevicePathProtocol, ?[*]const u8, usize, *?Handle) Status,
7081
71 /// Transfers control to a loaded image's entry point.82 /// Transfers control to a loaded image's entry point.
72 startImage: extern fn (Handle, ?*usize, ?*[*]u16) usize,83 startImage: extern fn (Handle, ?*usize, ?*[*]u16) Status,
7384
74 /// Terminates a loaded EFI image and returns control to boot services.85 /// Terminates a loaded EFI image and returns control to boot services.
75 exit: extern fn (Handle, usize, usize, ?*const c_void) usize,86 exit: extern fn (Handle, Status, usize, ?*const c_void) Status,
7687
77 /// Unloads an image.88 /// Unloads an image.
78 unloadImage: extern fn (Handle) usize,89 unloadImage: extern fn (Handle) Status,
7990
80 /// Terminates all boot services.91 /// Terminates all boot services.
81 exitBootServices: extern fn (Handle, usize) usize,92 exitBootServices: extern fn (Handle, usize) Status,
8293
83 getNextMonotonicCount: usize, // TODO94 /// Returns a monotonically increasing count for the platform.
95 getNextMonotonicCount: extern fn (*u64) Status,
8496
85 /// Induces a fine-grained stall.97 /// Induces a fine-grained stall.
86 stall: extern fn (usize) usize,98 stall: extern fn (usize) Status,
8799
88 /// Sets the system's watchdog timer.100 /// Sets the system's watchdog timer.
89 setWatchdogTimer: extern fn (usize, u64, usize, ?[*]const u16) usize,101 setWatchdogTimer: extern fn (usize, u64, usize, ?[*]const u16) Status,
90102
91 connectController: usize, // TODO103 connectController: Status, // TODO
92 disconnectController: usize, // TODO104 disconnectController: Status, // TODO
93105
94 /// Queries a handle to determine if it supports a specified protocol.106 /// Queries a handle to determine if it supports a specified protocol.
95 openProtocol: extern fn (Handle, *align(8) const Guid, *?*c_void, ?Handle, ?Handle, OpenProtocolAttributes) usize,107 openProtocol: extern fn (Handle, *align(8) const Guid, *?*c_void, ?Handle, ?Handle, OpenProtocolAttributes) Status,
96108
97 /// Closes a protocol on a handle that was opened using openProtocol().109 /// Closes a protocol on a handle that was opened using openProtocol().
98 closeProtocol: extern fn (Handle, *align(8) const Guid, Handle, ?Handle) usize,110 closeProtocol: extern fn (Handle, *align(8) const Guid, Handle, ?Handle) Status,
99111
100 /// Retrieves the list of agents that currently have a protocol interface opened.112 /// Retrieves the list of agents that currently have a protocol interface opened.
101 openProtocolInformation: extern fn (Handle, *align(8) const Guid, *[*]ProtocolInformationEntry, *usize) usize,113 openProtocolInformation: extern fn (Handle, *align(8) const Guid, *[*]ProtocolInformationEntry, *usize) Status,
102114
103 protocolsPerHandle: usize, // TODO115 /// Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated from pool.
116 protocolsPerHandle: extern fn (Handle, *[*]*align(8) const Guid, *usize) Status,
104117
105 /// Returns an array of handles that support the requested protocol in a buffer allocated from pool.118 /// Returns an array of handles that support the requested protocol in a buffer allocated from pool.
106 locateHandleBuffer: extern fn (LocateSearchType, ?*align(8) const Guid, ?*const c_void, *usize, *[*]Handle) usize,119 locateHandleBuffer: extern fn (LocateSearchType, ?*align(8) const Guid, ?*const c_void, *usize, *[*]Handle) Status,
107120
108 /// Returns the first protocol instance that matches the given protocol.121 /// Returns the first protocol instance that matches the given protocol.
109 locateProtocol: extern fn (*align(8) const Guid, ?*const c_void, *?*c_void) usize,122 locateProtocol: extern fn (*align(8) const Guid, ?*const c_void, *?*c_void) Status,
123
124 installMultipleProtocolInterfaces: Status, // TODO
125 uninstallMultipleProtocolInterfaces: Status, // TODO
110126
111 installMultipleProtocolInterfaces: usize, // TODO127 /// Computes and returns a 32-bit CRC for a data buffer.
112 uninstallMultipleProtocolInterfaces: usize, // TODO128 calculateCrc32: extern fn ([*]const u8, usize, *u32) Status,
113 calculateCrc32: usize, // TODO129
114 copyMem: usize, // TODO130 /// Copies the contents of one buffer to another buffer
115 setMem: usize, // TODO131 copyMem: extern fn ([*]u8, [*]const u8, usize) void,
116 createEventEx: usize, // TODO132
133 /// Fills a buffer with a specified value
134 setMem: extern fn ([*]u8, usize, u8) void,
135
136 createEventEx: Status, // TODO
117137
118 pub const signature: u64 = 0x56524553544f4f42;138 pub const signature: u64 = 0x56524553544f4f42;
119139
...@@ -187,13 +207,13 @@ pub const LocateSearchType = extern enum(u32) {...@@ -187,13 +207,13 @@ pub const LocateSearchType = extern enum(u32) {
187};207};
188208
189pub const OpenProtocolAttributes = packed struct {209pub const OpenProtocolAttributes = packed struct {
190 by_handle_protocol: bool,210 by_handle_protocol: bool = false,
191 get_protocol: bool,211 get_protocol: bool = false,
192 test_protocol: bool,212 test_protocol: bool = false,
193 by_child_controller: bool,213 by_child_controller: bool = false,
194 by_driver: bool,214 by_driver: bool = false,
195 exclusive: bool,215 exclusive: bool = false,
196 _pad: u26,216 _pad: u26 = undefined,
197};217};
198218
199pub const ProtocolInformationEntry = extern struct {219pub const ProtocolInformationEntry = extern struct {
...@@ -202,3 +222,9 @@ pub const ProtocolInformationEntry = extern struct {...@@ -202,3 +222,9 @@ pub const ProtocolInformationEntry = extern struct {
202 attributes: OpenProtocolAttributes,222 attributes: OpenProtocolAttributes,
203 open_count: u32,223 open_count: u32,
204};224};
225
226pub const AllocateType = extern enum(u32) {
227 AllocateAnyPages,
228 AllocateMaxAddress,
229 AllocateAddress,
230};
lib/std/os/uefi/tables/runtime_services.zig+15-14
...@@ -3,6 +3,7 @@ const Guid = uefi.Guid;...@@ -3,6 +3,7 @@ const Guid = uefi.Guid;
3const TableHeader = uefi.tables.TableHeader;3const TableHeader = uefi.tables.TableHeader;
4const Time = uefi.Time;4const Time = uefi.Time;
5const TimeCapabilities = uefi.TimeCapabilities;5const TimeCapabilities = uefi.TimeCapabilities;
6const Status = uefi.Status;
67
7/// Runtime services are provided by the firmware before and after exitBootServices has been called.8/// Runtime services are provided by the firmware before and after exitBootServices has been called.
8///9///
...@@ -16,31 +17,31 @@ pub const RuntimeServices = extern struct {...@@ -16,31 +17,31 @@ pub const RuntimeServices = extern struct {
16 hdr: TableHeader,17 hdr: TableHeader,
1718
18 /// Returns the current time and date information, and the time-keeping capabilities of the hardware platform.19 /// Returns the current time and date information, and the time-keeping capabilities of the hardware platform.
19 getTime: extern fn (*uefi.Time, ?*TimeCapabilities) usize,20 getTime: extern fn (*uefi.Time, ?*TimeCapabilities) Status,
2021
21 setTime: usize, // TODO22 setTime: Status, // TODO
22 getWakeupTime: usize, // TODO23 getWakeupTime: Status, // TODO
23 setWakeupTime: usize, // TODO24 setWakeupTime: Status, // TODO
24 setVirtualAddressMap: usize, // TODO25 setVirtualAddressMap: Status, // TODO
25 convertPointer: usize, // TODO26 convertPointer: Status, // TODO
2627
27 /// Returns the value of a variable.28 /// Returns the value of a variable.
28 getVariable: extern fn ([*:0]const u16, *align(8) const Guid, ?*u32, *usize, ?*c_void) usize,29 getVariable: extern fn ([*:0]const u16, *align(8) const Guid, ?*u32, *usize, ?*c_void) Status,
2930
30 /// Enumerates the current variable names.31 /// Enumerates the current variable names.
31 getNextVariableName: extern fn (*usize, [*]u16, *align(8) Guid) usize,32 getNextVariableName: extern fn (*usize, [*:0]u16, *align(8) Guid) Status,
3233
33 /// Sets the value of a variable.34 /// Sets the value of a variable.
34 setVariable: extern fn ([*:0]const u16, *align(8) const Guid, u32, usize, *c_void) usize,35 setVariable: extern fn ([*:0]const u16, *align(8) const Guid, u32, usize, *c_void) Status,
3536
36 getNextHighMonotonicCount: usize, // TODO37 getNextHighMonotonicCount: Status, // TODO
3738
38 /// Resets the entire platform.39 /// Resets the entire platform.
39 resetSystem: extern fn (ResetType, usize, usize, ?*const c_void) noreturn,40 resetSystem: extern fn (ResetType, Status, usize, ?*const c_void) noreturn,
4041
41 updateCapsule: usize, // TODO42 updateCapsule: Status, // TODO
42 queryCapsuleCapabilities: usize, // TODO43 queryCapsuleCapabilities: Status, // TODO
43 queryVariableInfo: usize, // TODO44 queryVariableInfo: Status, // TODO
4445
45 pub const signature: u64 = 0x56524553544e5552;46 pub const signature: u64 = 0x56524553544e5552;
46};47};
lib/std/os/windows.zig+3
...@@ -407,6 +407,7 @@ pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64) ReadFileError!usiz...@@ -407,6 +407,7 @@ pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64) ReadFileError!usiz
407 switch (kernel32.GetLastError()) {407 switch (kernel32.GetLastError()) {
408 .OPERATION_ABORTED => continue,408 .OPERATION_ABORTED => continue,
409 .BROKEN_PIPE => return index,409 .BROKEN_PIPE => return index,
410 .HANDLE_EOF => return index,
410 else => |err| return unexpectedError(err),411 else => |err| return unexpectedError(err),
411 }412 }
412 }413 }
...@@ -591,6 +592,8 @@ pub const CreateDirectoryError = error{...@@ -591,6 +592,8 @@ pub const CreateDirectoryError = error{
591 FileNotFound,592 FileNotFound,
592 NoDevice,593 NoDevice,
593 AccessDenied,594 AccessDenied,
595 InvalidUtf8,
596 BadPathName,
594 Unexpected,597 Unexpected,
595};598};
596599
lib/std/os/windows/bits.zig+4
...@@ -225,6 +225,10 @@ pub const FILE_POSITION_INFORMATION = extern struct {...@@ -225,6 +225,10 @@ pub const FILE_POSITION_INFORMATION = extern struct {
225 CurrentByteOffset: LARGE_INTEGER,225 CurrentByteOffset: LARGE_INTEGER,
226};226};
227227
228pub const FILE_END_OF_FILE_INFORMATION = extern struct {
229 EndOfFile: LARGE_INTEGER,
230};
231
228pub const FILE_MODE_INFORMATION = extern struct {232pub const FILE_MODE_INFORMATION = extern struct {
229 Mode: ULONG,233 Mode: ULONG,
230};234};
lib/std/os/windows/kernel32.zig+1
...@@ -8,6 +8,7 @@ pub extern "kernel32" fn CancelIoEx(hFile: HANDLE, lpOverlapped: LPOVERLAPPED) c...@@ -8,6 +8,7 @@ pub extern "kernel32" fn CancelIoEx(hFile: HANDLE, lpOverlapped: LPOVERLAPPED) c
8pub extern "kernel32" fn CloseHandle(hObject: HANDLE) callconv(.Stdcall) BOOL;8pub extern "kernel32" fn CloseHandle(hObject: HANDLE) callconv(.Stdcall) BOOL;
99
10pub extern "kernel32" fn CreateDirectoryW(lpPathName: [*:0]const u16, lpSecurityAttributes: ?*SECURITY_ATTRIBUTES) callconv(.Stdcall) BOOL;10pub extern "kernel32" fn CreateDirectoryW(lpPathName: [*:0]const u16, lpSecurityAttributes: ?*SECURITY_ATTRIBUTES) callconv(.Stdcall) BOOL;
11pub extern "kernel32" fn SetEndOfFile(hFile: HANDLE) callconv(.Stdcall) BOOL;
1112
12pub extern "kernel32" fn CreateEventExW(13pub extern "kernel32" fn CreateEventExW(
13 lpEventAttributes: ?*SECURITY_ATTRIBUTES,14 lpEventAttributes: ?*SECURITY_ATTRIBUTES,
lib/std/os/windows/ntdll.zig+7
...@@ -16,6 +16,13 @@ pub extern "NtDll" fn NtQueryInformationFile(...@@ -16,6 +16,13 @@ pub extern "NtDll" fn NtQueryInformationFile(
16 Length: ULONG,16 Length: ULONG,
17 FileInformationClass: FILE_INFORMATION_CLASS,17 FileInformationClass: FILE_INFORMATION_CLASS,
18) callconv(.Stdcall) NTSTATUS;18) callconv(.Stdcall) NTSTATUS;
19pub extern "NtDll" fn NtSetInformationFile(
20 FileHandle: HANDLE,
21 IoStatusBlock: *IO_STATUS_BLOCK,
22 FileInformation: PVOID,
23 Length: ULONG,
24 FileInformationClass: FILE_INFORMATION_CLASS,
25) callconv(.Stdcall) NTSTATUS;
1926
20pub extern "NtDll" fn NtQueryAttributesFile(27pub extern "NtDll" fn NtQueryAttributesFile(
21 ObjectAttributes: *OBJECT_ATTRIBUTES,28 ObjectAttributes: *OBJECT_ATTRIBUTES,
lib/std/pdb.zig+8-16
...@@ -495,8 +495,7 @@ const Msf = struct {...@@ -495,8 +495,7 @@ const Msf = struct {
495 streams: []MsfStream,495 streams: []MsfStream,
496496
497 fn openFile(self: *Msf, allocator: *mem.Allocator, file: File) !void {497 fn openFile(self: *Msf, allocator: *mem.Allocator, file: File) !void {
498 var file_stream = file.inStream();498 const in = file.inStream();
499 const in = &file_stream.stream;
500499
501 const superblock = try in.readStruct(SuperBlock);500 const superblock = try in.readStruct(SuperBlock);
502501
...@@ -529,7 +528,7 @@ const Msf = struct {...@@ -529,7 +528,7 @@ const Msf = struct {
529 );528 );
530529
531 const begin = self.directory.pos;530 const begin = self.directory.pos;
532 const stream_count = try self.directory.stream.readIntLittle(u32);531 const stream_count = try self.directory.inStream().readIntLittle(u32);
533 const stream_sizes = try allocator.alloc(u32, stream_count);532 const stream_sizes = try allocator.alloc(u32, stream_count);
534 defer allocator.free(stream_sizes);533 defer allocator.free(stream_sizes);
535534
...@@ -538,7 +537,7 @@ const Msf = struct {...@@ -538,7 +537,7 @@ const Msf = struct {
538 // and must be taken into account when resolving stream indices.537 // and must be taken into account when resolving stream indices.
539 const Nil = 0xFFFFFFFF;538 const Nil = 0xFFFFFFFF;
540 for (stream_sizes) |*s, i| {539 for (stream_sizes) |*s, i| {
541 const size = try self.directory.stream.readIntLittle(u32);540 const size = try self.directory.inStream().readIntLittle(u32);
542 s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize);541 s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize);
543 }542 }
544543
...@@ -553,7 +552,7 @@ const Msf = struct {...@@ -553,7 +552,7 @@ const Msf = struct {
553 var blocks = try allocator.alloc(u32, size);552 var blocks = try allocator.alloc(u32, size);
554 var j: u32 = 0;553 var j: u32 = 0;
555 while (j < size) : (j += 1) {554 while (j < size) : (j += 1) {
556 const block_id = try self.directory.stream.readIntLittle(u32);555 const block_id = try self.directory.inStream().readIntLittle(u32);
557 const n = (block_id % superblock.BlockSize);556 const n = (block_id % superblock.BlockSize);
558 // 0 is for SuperBlock, 1 and 2 for FPMs.557 // 0 is for SuperBlock, 1 and 2 for FPMs.
559 if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.BlockSize > try file.getEndPos())558 if (block_id == 0 or n == 1 or n == 2 or block_id * superblock.BlockSize > try file.getEndPos())
...@@ -632,11 +631,7 @@ const MsfStream = struct {...@@ -632,11 +631,7 @@ const MsfStream = struct {
632 blocks: []u32 = undefined,631 blocks: []u32 = undefined,
633 block_size: u32 = undefined,632 block_size: u32 = undefined,
634633
635 /// Implementation of InStream trait for Pdb.MsfStream
636 stream: Stream = undefined,
637
638 pub const Error = @TypeOf(read).ReturnType.ErrorSet;634 pub const Error = @TypeOf(read).ReturnType.ErrorSet;
639 pub const Stream = io.InStream(Error);
640635
641 fn init(block_size: u32, file: File, blocks: []u32) MsfStream {636 fn init(block_size: u32, file: File, blocks: []u32) MsfStream {
642 const stream = MsfStream{637 const stream = MsfStream{
...@@ -644,7 +639,6 @@ const MsfStream = struct {...@@ -644,7 +639,6 @@ const MsfStream = struct {
644 .pos = 0,639 .pos = 0,
645 .blocks = blocks,640 .blocks = blocks,
646 .block_size = block_size,641 .block_size = block_size,
647 .stream = Stream{ .readFn = readFn },
648 };642 };
649643
650 return stream;644 return stream;
...@@ -653,7 +647,7 @@ const MsfStream = struct {...@@ -653,7 +647,7 @@ const MsfStream = struct {
653 fn readNullTermString(self: *MsfStream, allocator: *mem.Allocator) ![]u8 {647 fn readNullTermString(self: *MsfStream, allocator: *mem.Allocator) ![]u8 {
654 var list = ArrayList(u8).init(allocator);648 var list = ArrayList(u8).init(allocator);
655 while (true) {649 while (true) {
656 const byte = try self.stream.readByte();650 const byte = try self.inStream().readByte();
657 if (byte == 0) {651 if (byte == 0) {
658 return list.toSlice();652 return list.toSlice();
659 }653 }
...@@ -667,8 +661,7 @@ const MsfStream = struct {...@@ -667,8 +661,7 @@ const MsfStream = struct {
667 var offset = self.pos % self.block_size;661 var offset = self.pos % self.block_size;
668662
669 try self.in_file.seekTo(block * self.block_size + offset);663 try self.in_file.seekTo(block * self.block_size + offset);
670 var file_stream = self.in_file.inStream();664 const in = self.in_file.inStream();
671 const in = &file_stream.stream;
672665
673 var size: usize = 0;666 var size: usize = 0;
674 var rem_buffer = buffer;667 var rem_buffer = buffer;
...@@ -715,8 +708,7 @@ const MsfStream = struct {...@@ -715,8 +708,7 @@ const MsfStream = struct {
715 return block * self.block_size + offset;708 return block * self.block_size + offset;
716 }709 }
717710
718 fn readFn(in_stream: *Stream, buffer: []u8) Error!usize {711 fn inStream(self: *MsfStream) std.io.InStream(*MsfStream, Error, read) {
719 const self = @fieldParentPtr(MsfStream, "stream", in_stream);712 return .{ .context = self };
720 return self.read(buffer);
721 }713 }
722};714};
lib/std/progress.zig+2-2
...@@ -177,7 +177,7 @@ pub const Progress = struct {...@@ -177,7 +177,7 @@ pub const Progress = struct {
177 pub fn log(self: *Progress, comptime format: []const u8, args: var) void {177 pub fn log(self: *Progress, comptime format: []const u8, args: var) void {
178 const file = self.terminal orelse return;178 const file = self.terminal orelse return;
179 self.refresh();179 self.refresh();
180 file.outStream().stream.print(format, args) catch {180 file.outStream().print(format, args) catch {
181 self.terminal = null;181 self.terminal = null;
182 return;182 return;
183 };183 };
...@@ -190,7 +190,7 @@ pub const Progress = struct {...@@ -190,7 +190,7 @@ pub const Progress = struct {
190 end.* += amt;190 end.* += amt;
191 self.columns_written += amt;191 self.columns_written += amt;
192 } else |err| switch (err) {192 } else |err| switch (err) {
193 error.BufferTooSmall => {193 error.NoSpaceLeft => {
194 self.columns_written += self.output_buffer.len - end.*;194 self.columns_written += self.output_buffer.len - end.*;
195 end.* = self.output_buffer.len;195 end.* = self.output_buffer.len;
196 },196 },
lib/std/special/build_runner.zig+4-4
...@@ -42,8 +42,8 @@ pub fn main() !void {...@@ -42,8 +42,8 @@ pub fn main() !void {
4242
43 var targets = ArrayList([]const u8).init(allocator);43 var targets = ArrayList([]const u8).init(allocator);
4444
45 const stderr_stream = &io.getStdErr().outStream().stream;45 const stderr_stream = io.getStdErr().outStream();
46 const stdout_stream = &io.getStdOut().outStream().stream;46 const stdout_stream = io.getStdOut().outStream();
4747
48 while (nextArg(args, &arg_idx)) |arg| {48 while (nextArg(args, &arg_idx)) |arg| {
49 if (mem.startsWith(u8, arg, "-D")) {49 if (mem.startsWith(u8, arg, "-D")) {
...@@ -159,7 +159,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {...@@ -159,7 +159,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
159 try out_stream.print(" {s:22} {}\n", .{ name, top_level_step.description });159 try out_stream.print(" {s:22} {}\n", .{ name, top_level_step.description });
160 }160 }
161161
162 try out_stream.write(162 try out_stream.writeAll(
163 \\163 \\
164 \\General Options:164 \\General Options:
165 \\ --help Print this help and exit165 \\ --help Print this help and exit
...@@ -184,7 +184,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {...@@ -184,7 +184,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
184 }184 }
185 }185 }
186186
187 try out_stream.write(187 try out_stream.writeAll(
188 \\188 \\
189 \\Advanced Options:189 \\Advanced Options:
190 \\ --build-file [file] Override path to build.zig190 \\ --build-file [file] Override path to build.zig
lib/std/start.zig+8-9
...@@ -55,25 +55,24 @@ fn wasm_freestanding_start() callconv(.C) void {...@@ -55,25 +55,24 @@ fn wasm_freestanding_start() callconv(.C) void {
55}55}
5656
57fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv(.C) usize {57fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv(.C) usize {
58 const bad_efi_main_ret = "expected return type of main to be 'void', 'noreturn', or 'usize'";
59 uefi.handle = handle;58 uefi.handle = handle;
60 uefi.system_table = system_table;59 uefi.system_table = system_table;
6160
62 switch (@typeInfo(@TypeOf(root.main).ReturnType)) {61 switch (@TypeOf(root.main).ReturnType) {
63 .NoReturn => {62 noreturn => {
64 root.main();63 root.main();
65 },64 },
66 .Void => {65 void => {
67 root.main();66 root.main();
68 return 0;67 return 0;
69 },68 },
70 .Int => |info| {69 usize => {
71 if (info.bits != @typeInfo(usize).Int.bits) {
72 @compileError(bad_efi_main_ret);
73 }
74 return root.main();70 return root.main();
75 },71 },
76 else => @compileError(bad_efi_main_ret),72 uefi.Status => {
73 return @enumToInt(root.main());
74 },
75 else => @compileError("expected return type of main to be 'void', 'noreturn', 'usize', or 'std.os.uefi.Status'"),
77 }76 }
78}77}
7978
lib/std/std.zig-1
...@@ -5,7 +5,6 @@ pub const BloomFilter = @import("bloom_filter.zig").BloomFilter;...@@ -5,7 +5,6 @@ pub const BloomFilter = @import("bloom_filter.zig").BloomFilter;
5pub const BufMap = @import("buf_map.zig").BufMap;5pub const BufMap = @import("buf_map.zig").BufMap;
6pub const BufSet = @import("buf_set.zig").BufSet;6pub const BufSet = @import("buf_set.zig").BufSet;
7pub const Buffer = @import("buffer.zig").Buffer;7pub const Buffer = @import("buffer.zig").Buffer;
8pub const BufferOutStream = @import("io.zig").BufferOutStream;
9pub const ChildProcess = @import("child_process.zig").ChildProcess;8pub const ChildProcess = @import("child_process.zig").ChildProcess;
10pub const DynLib = @import("dynamic_library.zig").DynLib;9pub const DynLib = @import("dynamic_library.zig").DynLib;
11pub const HashMap = @import("hash_map.zig").HashMap;10pub const HashMap = @import("hash_map.zig").HashMap;
lib/std/unicode.zig+68
...@@ -629,3 +629,71 @@ test "utf8ToUtf16LeWithNull" {...@@ -629,3 +629,71 @@ test "utf8ToUtf16LeWithNull" {
629 testing.expect(utf16[2] == 0);629 testing.expect(utf16[2] == 0);
630 }630 }
631}631}
632
633/// Converts a UTF-8 string literal into a UTF-16LE string literal.
634pub fn utf8ToUtf16LeStringLiteral(comptime utf8: []const u8) *const [calcUtf16LeLen(utf8) :0] u16 {
635 comptime {
636 const len: usize = calcUtf16LeLen(utf8);
637 var utf16le: [len :0]u16 = [_ :0]u16{0} ** len;
638 const utf16le_len = utf8ToUtf16Le(&utf16le, utf8[0..]) catch |err| @compileError(err);
639 assert(len == utf16le_len);
640 return &utf16le;
641 }
642}
643
644/// Returns length of a supplied UTF-8 string literal. Asserts that the data is valid UTF-8.
645fn calcUtf16LeLen(utf8: []const u8) usize {
646 var src_i: usize = 0;
647 var dest_len: usize = 0;
648 while (src_i < utf8.len) {
649 const n = utf8ByteSequenceLength(utf8[src_i]) catch unreachable;
650 const next_src_i = src_i + n;
651 const codepoint = utf8Decode(utf8[src_i..next_src_i]) catch unreachable;
652 if (codepoint < 0x10000) {
653 dest_len += 1;
654 } else {
655 dest_len += 2;
656 }
657 src_i = next_src_i;
658 }
659 return dest_len;
660}
661
662test "utf8ToUtf16LeStringLiteral" {
663{
664 const bytes = [_:0]u16{ 0x41 };
665 const utf16 = utf8ToUtf16LeStringLiteral("A");
666 testing.expectEqualSlices(u16, &bytes, utf16);
667 testing.expect(utf16[1] == 0);
668 }
669 {
670 const bytes = [_:0]u16{ 0xD801, 0xDC37 };
671 const utf16 = utf8ToUtf16LeStringLiteral("𐐷");
672 testing.expectEqualSlices(u16, &bytes, utf16);
673 testing.expect(utf16[2] == 0);
674 }
675 {
676 const bytes = [_:0]u16{ 0x02FF };
677 const utf16 = utf8ToUtf16LeStringLiteral("\u{02FF}");
678 testing.expectEqualSlices(u16, &bytes, utf16);
679 testing.expect(utf16[1] == 0);
680 }
681 {
682 const bytes = [_:0]u16{ 0x7FF };
683 const utf16 = utf8ToUtf16LeStringLiteral("\u{7FF}");
684 testing.expectEqualSlices(u16, &bytes, utf16);
685 testing.expect(utf16[1] == 0);
686 }
687 {
688 const bytes = [_:0]u16{ 0x801 };
689 const utf16 = utf8ToUtf16LeStringLiteral("\u{801}");
690 testing.expectEqualSlices(u16, &bytes, utf16);
691 testing.expect(utf16[1] == 0);
692 }
693 {
694 const bytes = [_:0]u16{ 0xDBFF, 0xDFFF };
695 const utf16 = utf8ToUtf16LeStringLiteral("\u{10FFFF}");
696 testing.expectEqualSlices(u16, &bytes, utf16);
697 testing.expect(utf16[2] == 0);
698 }
699}
lib/std/zig/ast.zig+56-30
...@@ -378,7 +378,7 @@ pub const Error = union(enum) {...@@ -378,7 +378,7 @@ pub const Error = union(enum) {
378 token: TokenIndex,378 token: TokenIndex,
379379
380 pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void {380 pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void {
381 return stream.write(msg);381 return stream.writeAll(msg);
382 }382 }
383 };383 };
384 }384 }
...@@ -434,6 +434,7 @@ pub const Node = struct {...@@ -434,6 +434,7 @@ pub const Node = struct {
434 ContainerDecl,434 ContainerDecl,
435 Asm,435 Asm,
436 Comptime,436 Comptime,
437 Noasync,
437 Block,438 Block,
438439
439 // Misc440 // Misc
...@@ -502,68 +503,72 @@ pub const Node = struct {...@@ -502,68 +503,72 @@ pub const Node = struct {
502 var n = base;503 var n = base;
503 while (true) {504 while (true) {
504 switch (n.id) {505 switch (n.id) {
505 Id.Root,506 .Root,
506 Id.ContainerField,507 .ContainerField,
507 Id.ParamDecl,508 .ParamDecl,
508 Id.Block,509 .Block,
509 Id.Payload,510 .Payload,
510 Id.PointerPayload,511 .PointerPayload,
511 Id.PointerIndexPayload,512 .PointerIndexPayload,
512 Id.Switch,513 .Switch,
513 Id.SwitchCase,514 .SwitchCase,
514 Id.SwitchElse,515 .SwitchElse,
515 Id.FieldInitializer,516 .FieldInitializer,
516 Id.DocComment,517 .DocComment,
517 Id.TestDecl,518 .TestDecl,
518 => return false,519 => return false,
519 Id.While => {520 .While => {
520 const while_node = @fieldParentPtr(While, "base", n);521 const while_node = @fieldParentPtr(While, "base", n);
521 if (while_node.@"else") |@"else"| {522 if (while_node.@"else") |@"else"| {
522 n = &@"else".base;523 n = &@"else".base;
523 continue;524 continue;
524 }525 }
525526
526 return while_node.body.id != Id.Block;527 return while_node.body.id != .Block;
527 },528 },
528 Id.For => {529 .For => {
529 const for_node = @fieldParentPtr(For, "base", n);530 const for_node = @fieldParentPtr(For, "base", n);
530 if (for_node.@"else") |@"else"| {531 if (for_node.@"else") |@"else"| {
531 n = &@"else".base;532 n = &@"else".base;
532 continue;533 continue;
533 }534 }
534535
535 return for_node.body.id != Id.Block;536 return for_node.body.id != .Block;
536 },537 },
537 Id.If => {538 .If => {
538 const if_node = @fieldParentPtr(If, "base", n);539 const if_node = @fieldParentPtr(If, "base", n);
539 if (if_node.@"else") |@"else"| {540 if (if_node.@"else") |@"else"| {
540 n = &@"else".base;541 n = &@"else".base;
541 continue;542 continue;
542 }543 }
543544
544 return if_node.body.id != Id.Block;545 return if_node.body.id != .Block;
545 },546 },
546 Id.Else => {547 .Else => {
547 const else_node = @fieldParentPtr(Else, "base", n);548 const else_node = @fieldParentPtr(Else, "base", n);
548 n = else_node.body;549 n = else_node.body;
549 continue;550 continue;
550 },551 },
551 Id.Defer => {552 .Defer => {
552 const defer_node = @fieldParentPtr(Defer, "base", n);553 const defer_node = @fieldParentPtr(Defer, "base", n);
553 return defer_node.expr.id != Id.Block;554 return defer_node.expr.id != .Block;
554 },555 },
555 Id.Comptime => {556 .Comptime => {
556 const comptime_node = @fieldParentPtr(Comptime, "base", n);557 const comptime_node = @fieldParentPtr(Comptime, "base", n);
557 return comptime_node.expr.id != Id.Block;558 return comptime_node.expr.id != .Block;
558 },559 },
559 Id.Suspend => {560 .Suspend => {
560 const suspend_node = @fieldParentPtr(Suspend, "base", n);561 const suspend_node = @fieldParentPtr(Suspend, "base", n);
561 if (suspend_node.body) |body| {562 if (suspend_node.body) |body| {
562 return body.id != Id.Block;563 return body.id != .Block;
563 }564 }
564565
565 return true;566 return true;
566 },567 },
568 .Noasync => {
569 const noasync_node = @fieldParentPtr(Noasync, "base", n);
570 return noasync_node.expr.id != .Block;
571 },
567 else => return true,572 else => return true,
568 }573 }
569 }574 }
...@@ -1081,6 +1086,29 @@ pub const Node = struct {...@@ -1081,6 +1086,29 @@ pub const Node = struct {
1081 }1086 }
1082 };1087 };
10831088
1089 pub const Noasync = struct {
1090 base: Node = Node{ .id = .Noasync },
1091 noasync_token: TokenIndex,
1092 expr: *Node,
1093
1094 pub fn iterate(self: *Noasync, index: usize) ?*Node {
1095 var i = index;
1096
1097 if (i < 1) return self.expr;
1098 i -= 1;
1099
1100 return null;
1101 }
1102
1103 pub fn firstToken(self: *const Noasync) TokenIndex {
1104 return self.noasync_token;
1105 }
1106
1107 pub fn lastToken(self: *const Noasync) TokenIndex {
1108 return self.expr.lastToken();
1109 }
1110 };
1111
1084 pub const Payload = struct {1112 pub const Payload = struct {
1085 base: Node = Node{ .id = .Payload },1113 base: Node = Node{ .id = .Payload },
1086 lpipe: TokenIndex,1114 lpipe: TokenIndex,
...@@ -1563,9 +1591,7 @@ pub const Node = struct {...@@ -1563,9 +1591,7 @@ pub const Node = struct {
1563 pub const Op = union(enum) {1591 pub const Op = union(enum) {
1564 AddressOf,1592 AddressOf,
1565 ArrayType: ArrayInfo,1593 ArrayType: ArrayInfo,
1566 Await: struct {1594 Await,
1567 noasync_token: ?TokenIndex = null,
1568 },
1569 BitNot,1595 BitNot,
1570 BoolNot,1596 BoolNot,
1571 Cancel,1597 Cancel,
lib/std/zig/cross_target.zig+6-6
...@@ -504,22 +504,22 @@ pub const CrossTarget = struct {...@@ -504,22 +504,22 @@ pub const CrossTarget = struct {
504 if (self.os_version_min != null or self.os_version_max != null) {504 if (self.os_version_min != null or self.os_version_max != null) {
505 switch (self.getOsVersionMin()) {505 switch (self.getOsVersionMin()) {
506 .none => {},506 .none => {},
507 .semver => |v| try result.print(".{}", .{v}),507 .semver => |v| try result.outStream().print(".{}", .{v}),
508 .windows => |v| try result.print(".{}", .{@tagName(v)}),508 .windows => |v| try result.outStream().print(".{}", .{@tagName(v)}),
509 }509 }
510 }510 }
511 if (self.os_version_max) |max| {511 if (self.os_version_max) |max| {
512 switch (max) {512 switch (max) {
513 .none => {},513 .none => {},
514 .semver => |v| try result.print("...{}", .{v}),514 .semver => |v| try result.outStream().print("...{}", .{v}),
515 .windows => |v| try result.print("...{}", .{@tagName(v)}),515 .windows => |v| try result.outStream().print("...{}", .{@tagName(v)}),
516 }516 }
517 }517 }
518518
519 if (self.glibc_version) |v| {519 if (self.glibc_version) |v| {
520 try result.print("-{}.{}", .{ @tagName(self.getAbi()), v });520 try result.outStream().print("-{}.{}", .{ @tagName(self.getAbi()), v });
521 } else if (self.abi) |abi| {521 } else if (self.abi) |abi| {
522 try result.print("-{}", .{@tagName(abi)});522 try result.outStream().print("-{}", .{@tagName(abi)});
523 }523 }
524524
525 return result.toOwnedSlice();525 return result.toOwnedSlice();
lib/std/zig/parse.zig+49-25
...@@ -462,6 +462,7 @@ fn parseContainerField(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*No...@@ -462,6 +462,7 @@ fn parseContainerField(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*No
462/// Statement462/// Statement
463/// <- KEYWORD_comptime? VarDecl463/// <- KEYWORD_comptime? VarDecl
464/// / KEYWORD_comptime BlockExprStatement464/// / KEYWORD_comptime BlockExprStatement
465/// / KEYWORD_noasync BlockExprStatement
465/// / KEYWORD_suspend (SEMICOLON / BlockExprStatement)466/// / KEYWORD_suspend (SEMICOLON / BlockExprStatement)
466/// / KEYWORD_defer BlockExprStatement467/// / KEYWORD_defer BlockExprStatement
467/// / KEYWORD_errdefer BlockExprStatement468/// / KEYWORD_errdefer BlockExprStatement
...@@ -493,6 +494,19 @@ fn parseStatement(arena: *Allocator, it: *TokenIterator, tree: *Tree) Error!?*No...@@ -493,6 +494,19 @@ fn parseStatement(arena: *Allocator, it: *TokenIterator, tree: *Tree) Error!?*No
493 return &node.base;494 return &node.base;
494 }495 }
495496
497 if (eatToken(it, .Keyword_noasync)) |noasync_token| {
498 const block_expr = try expectNode(arena, it, tree, parseBlockExprStatement, .{
499 .ExpectedBlockOrAssignment = .{ .token = it.index },
500 });
501
502 const node = try arena.create(Node.Noasync);
503 node.* = .{
504 .noasync_token = noasync_token,
505 .expr = block_expr,
506 };
507 return &node.base;
508 }
509
496 if (eatToken(it, .Keyword_suspend)) |suspend_token| {510 if (eatToken(it, .Keyword_suspend)) |suspend_token| {
497 const semicolon = eatToken(it, .Semicolon);511 const semicolon = eatToken(it, .Semicolon);
498512
...@@ -856,6 +870,7 @@ fn parsePrefixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {...@@ -856,6 +870,7 @@ fn parsePrefixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
856/// / IfExpr870/// / IfExpr
857/// / KEYWORD_break BreakLabel? Expr?871/// / KEYWORD_break BreakLabel? Expr?
858/// / KEYWORD_comptime Expr872/// / KEYWORD_comptime Expr
873/// / KEYWORD_noasync Expr
859/// / KEYWORD_continue BreakLabel?874/// / KEYWORD_continue BreakLabel?
860/// / KEYWORD_resume Expr875/// / KEYWORD_resume Expr
861/// / KEYWORD_return Expr?876/// / KEYWORD_return Expr?
...@@ -870,7 +885,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node...@@ -870,7 +885,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
870 const label = try parseBreakLabel(arena, it, tree);885 const label = try parseBreakLabel(arena, it, tree);
871 const expr_node = try parseExpr(arena, it, tree);886 const expr_node = try parseExpr(arena, it, tree);
872 const node = try arena.create(Node.ControlFlowExpression);887 const node = try arena.create(Node.ControlFlowExpression);
873 node.* = Node.ControlFlowExpression{888 node.* = .{
874 .ltoken = token,889 .ltoken = token,
875 .kind = Node.ControlFlowExpression.Kind{ .Break = label },890 .kind = Node.ControlFlowExpression.Kind{ .Break = label },
876 .rhs = expr_node,891 .rhs = expr_node,
...@@ -883,7 +898,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node...@@ -883,7 +898,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
883 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },898 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },
884 });899 });
885 const node = try arena.create(Node.Comptime);900 const node = try arena.create(Node.Comptime);
886 node.* = Node.Comptime{901 node.* = .{
887 .doc_comments = null,902 .doc_comments = null,
888 .comptime_token = token,903 .comptime_token = token,
889 .expr = expr_node,904 .expr = expr_node,
...@@ -891,10 +906,22 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node...@@ -891,10 +906,22 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
891 return &node.base;906 return &node.base;
892 }907 }
893908
909 if (eatToken(it, .Keyword_noasync)) |token| {
910 const expr_node = try expectNode(arena, it, tree, parseExpr, AstError{
911 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },
912 });
913 const node = try arena.create(Node.Noasync);
914 node.* = .{
915 .noasync_token = token,
916 .expr = expr_node,
917 };
918 return &node.base;
919 }
920
894 if (eatToken(it, .Keyword_continue)) |token| {921 if (eatToken(it, .Keyword_continue)) |token| {
895 const label = try parseBreakLabel(arena, it, tree);922 const label = try parseBreakLabel(arena, it, tree);
896 const node = try arena.create(Node.ControlFlowExpression);923 const node = try arena.create(Node.ControlFlowExpression);
897 node.* = Node.ControlFlowExpression{924 node.* = .{
898 .ltoken = token,925 .ltoken = token,
899 .kind = Node.ControlFlowExpression.Kind{ .Continue = label },926 .kind = Node.ControlFlowExpression.Kind{ .Continue = label },
900 .rhs = null,927 .rhs = null,
...@@ -907,7 +934,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node...@@ -907,7 +934,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
907 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },934 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },
908 });935 });
909 const node = try arena.create(Node.PrefixOp);936 const node = try arena.create(Node.PrefixOp);
910 node.* = Node.PrefixOp{937 node.* = .{
911 .op_token = token,938 .op_token = token,
912 .op = Node.PrefixOp.Op.Resume,939 .op = Node.PrefixOp.Op.Resume,
913 .rhs = expr_node,940 .rhs = expr_node,
...@@ -918,7 +945,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node...@@ -918,7 +945,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
918 if (eatToken(it, .Keyword_return)) |token| {945 if (eatToken(it, .Keyword_return)) |token| {
919 const expr_node = try parseExpr(arena, it, tree);946 const expr_node = try parseExpr(arena, it, tree);
920 const node = try arena.create(Node.ControlFlowExpression);947 const node = try arena.create(Node.ControlFlowExpression);
921 node.* = Node.ControlFlowExpression{948 node.* = .{
922 .ltoken = token,949 .ltoken = token,
923 .kind = Node.ControlFlowExpression.Kind.Return,950 .kind = Node.ControlFlowExpression.Kind.Return,
924 .rhs = expr_node,951 .rhs = expr_node,
...@@ -1126,19 +1153,18 @@ fn parseErrorUnionExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*No...@@ -1126,19 +1153,18 @@ fn parseErrorUnionExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*No
11261153
1127/// SuffixExpr1154/// SuffixExpr
1128/// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments1155/// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
1129/// / KEYWORD_noasync PrimaryTypeExpr SuffixOp* FnCallArguments
1130/// / PrimaryTypeExpr (SuffixOp / FnCallArguments)*1156/// / PrimaryTypeExpr (SuffixOp / FnCallArguments)*
1131fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {1157fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
1132 const maybe_async = eatAnnotatedToken(it, .Keyword_async) orelse eatAnnotatedToken(it, .Keyword_noasync);1158 const maybe_async = eatToken(it, .Keyword_async);
1133 if (maybe_async) |async_token| {1159 if (maybe_async) |async_token| {
1134 const token_fn = eatToken(it, .Keyword_fn);1160 const token_fn = eatToken(it, .Keyword_fn);
1135 if (async_token.ptr.id == .Keyword_async and token_fn != null) {1161 if (token_fn != null) {
1136 // HACK: If we see the keyword `fn`, then we assume that1162 // HACK: If we see the keyword `fn`, then we assume that
1137 // we are parsing an async fn proto, and not a call.1163 // we are parsing an async fn proto, and not a call.
1138 // We therefore put back all tokens consumed by the async1164 // We therefore put back all tokens consumed by the async
1139 // prefix...1165 // prefix...
1140 putBackToken(it, token_fn.?);1166 putBackToken(it, token_fn.?);
1141 putBackToken(it, async_token.index);1167 putBackToken(it, async_token);
1142 return parsePrimaryTypeExpr(arena, it, tree);1168 return parsePrimaryTypeExpr(arena, it, tree);
1143 }1169 }
1144 // TODO: Implement hack for parsing `async fn ...` in ast_parse_suffix_expr1170 // TODO: Implement hack for parsing `async fn ...` in ast_parse_suffix_expr
...@@ -1167,7 +1193,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {...@@ -1167,7 +1193,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
1167 .op = Node.SuffixOp.Op{1193 .op = Node.SuffixOp.Op{
1168 .Call = Node.SuffixOp.Op.Call{1194 .Call = Node.SuffixOp.Op.Call{
1169 .params = params.list,1195 .params = params.list,
1170 .async_token = async_token.index,1196 .async_token = async_token,
1171 },1197 },
1172 },1198 },
1173 .rtoken = params.rparen,1199 .rtoken = params.rparen,
...@@ -1224,6 +1250,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {...@@ -1224,6 +1250,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
1224/// / IfTypeExpr1250/// / IfTypeExpr
1225/// / INTEGER1251/// / INTEGER
1226/// / KEYWORD_comptime TypeExpr1252/// / KEYWORD_comptime TypeExpr
1253/// / KEYWORD_noasync TypeExpr
1227/// / KEYWORD_error DOT IDENTIFIER1254/// / KEYWORD_error DOT IDENTIFIER
1228/// / KEYWORD_false1255/// / KEYWORD_false
1229/// / KEYWORD_null1256/// / KEYWORD_null
...@@ -1255,13 +1282,22 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N...@@ -1255,13 +1282,22 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
1255 if (eatToken(it, .Keyword_comptime)) |token| {1282 if (eatToken(it, .Keyword_comptime)) |token| {
1256 const expr = (try parseTypeExpr(arena, it, tree)) orelse return null;1283 const expr = (try parseTypeExpr(arena, it, tree)) orelse return null;
1257 const node = try arena.create(Node.Comptime);1284 const node = try arena.create(Node.Comptime);
1258 node.* = Node.Comptime{1285 node.* = .{
1259 .doc_comments = null,1286 .doc_comments = null,
1260 .comptime_token = token,1287 .comptime_token = token,
1261 .expr = expr,1288 .expr = expr,
1262 };1289 };
1263 return &node.base;1290 return &node.base;
1264 }1291 }
1292 if (eatToken(it, .Keyword_noasync)) |token| {
1293 const expr = (try parseTypeExpr(arena, it, tree)) orelse return null;
1294 const node = try arena.create(Node.Noasync);
1295 node.* = .{
1296 .noasync_token = token,
1297 .expr = expr,
1298 };
1299 return &node.base;
1300 }
1265 if (eatToken(it, .Keyword_error)) |token| {1301 if (eatToken(it, .Keyword_error)) |token| {
1266 const period = try expectToken(it, tree, .Period);1302 const period = try expectToken(it, tree, .Period);
1267 const identifier = try expectNode(arena, it, tree, parseIdentifier, AstError{1303 const identifier = try expectNode(arena, it, tree, parseIdentifier, AstError{
...@@ -1269,7 +1305,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N...@@ -1269,7 +1305,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
1269 });1305 });
1270 const global_error_set = try createLiteral(arena, Node.ErrorType, token);1306 const global_error_set = try createLiteral(arena, Node.ErrorType, token);
1271 const node = try arena.create(Node.InfixOp);1307 const node = try arena.create(Node.InfixOp);
1272 node.* = Node.InfixOp{1308 node.* = .{
1273 .op_token = period,1309 .op_token = period,
1274 .lhs = global_error_set,1310 .lhs = global_error_set,
1275 .op = Node.InfixOp.Op.Period,1311 .op = Node.InfixOp.Op.Period,
...@@ -1281,7 +1317,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N...@@ -1281,7 +1317,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
1281 if (eatToken(it, .Keyword_null)) |token| return createLiteral(arena, Node.NullLiteral, token);1317 if (eatToken(it, .Keyword_null)) |token| return createLiteral(arena, Node.NullLiteral, token);
1282 if (eatToken(it, .Keyword_anyframe)) |token| {1318 if (eatToken(it, .Keyword_anyframe)) |token| {
1283 const node = try arena.create(Node.AnyFrameType);1319 const node = try arena.create(Node.AnyFrameType);
1284 node.* = Node.AnyFrameType{1320 node.* = .{
1285 .anyframe_token = token,1321 .anyframe_token = token,
1286 .result = null,1322 .result = null,
1287 };1323 };
...@@ -2180,18 +2216,6 @@ fn parsePrefixOp(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {...@@ -2180,18 +2216,6 @@ fn parsePrefixOp(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
2180 .Ampersand => ops{ .AddressOf = {} },2216 .Ampersand => ops{ .AddressOf = {} },
2181 .Keyword_try => ops{ .Try = {} },2217 .Keyword_try => ops{ .Try = {} },
2182 .Keyword_await => ops{ .Await = .{} },2218 .Keyword_await => ops{ .Await = .{} },
2183 .Keyword_noasync => if (eatToken(it, .Keyword_await)) |await_tok| {
2184 const node = try arena.create(Node.PrefixOp);
2185 node.* = Node.PrefixOp{
2186 .op_token = await_tok,
2187 .op = .{ .Await = .{ .noasync_token = token.index } },
2188 .rhs = undefined, // set by caller
2189 };
2190 return &node.base;
2191 } else {
2192 putBackToken(it, token.index);
2193 return null;
2194 },
2195 else => {2219 else => {
2196 putBackToken(it, token.index);2220 putBackToken(it, token.index);
2197 return null;2221 return null;
lib/std/zig/parser_test.zig+16-6
...@@ -1,3 +1,14 @@...@@ -1,3 +1,14 @@
1test "zig fmt: noasync block" {
2 try testCanonical(
3 \\pub fn main() anyerror!void {
4 \\ noasync {
5 \\ var foo: Foo = .{ .bar = 42 };
6 \\ }
7 \\}
8 \\
9 );
10}
11
1test "zig fmt: noasync await" {12test "zig fmt: noasync await" {
2 try testCanonical(13 try testCanonical(
3 \\fn foo() void {14 \\fn foo() void {
...@@ -2798,7 +2809,7 @@ const maxInt = std.math.maxInt;...@@ -2798,7 +2809,7 @@ const maxInt = std.math.maxInt;
2798var fixed_buffer_mem: [100 * 1024]u8 = undefined;2809var fixed_buffer_mem: [100 * 1024]u8 = undefined;
27992810
2800fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {2811fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *bool) ![]u8 {
2801 const stderr = &io.getStdErr().outStream().stream;2812 const stderr = io.getStdErr().outStream();
28022813
2803 const tree = try std.zig.parse(allocator, source);2814 const tree = try std.zig.parse(allocator, source);
2804 defer tree.deinit();2815 defer tree.deinit();
...@@ -2813,17 +2824,17 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b...@@ -2813,17 +2824,17 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
2813 {2824 {
2814 var i: usize = 0;2825 var i: usize = 0;
2815 while (i < loc.column) : (i += 1) {2826 while (i < loc.column) : (i += 1) {
2816 try stderr.write(" ");2827 try stderr.writeAll(" ");
2817 }2828 }
2818 }2829 }
2819 {2830 {
2820 const caret_count = token.end - token.start;2831 const caret_count = token.end - token.start;
2821 var i: usize = 0;2832 var i: usize = 0;
2822 while (i < caret_count) : (i += 1) {2833 while (i < caret_count) : (i += 1) {
2823 try stderr.write("~");2834 try stderr.writeAll("~");
2824 }2835 }
2825 }2836 }
2826 try stderr.write("\n");2837 try stderr.writeAll("\n");
2827 }2838 }
2828 if (tree.errors.len != 0) {2839 if (tree.errors.len != 0) {
2829 return error.ParseError;2840 return error.ParseError;
...@@ -2832,8 +2843,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b...@@ -2832,8 +2843,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
2832 var buffer = try std.Buffer.initSize(allocator, 0);2843 var buffer = try std.Buffer.initSize(allocator, 0);
2833 errdefer buffer.deinit();2844 errdefer buffer.deinit();
28342845
2835 var buffer_out_stream = io.BufferOutStream.init(&buffer);2846 anything_changed.* = try std.zig.render(allocator, buffer.outStream(), tree);
2836 anything_changed.* = try std.zig.render(allocator, &buffer_out_stream.stream, tree);
2837 return buffer.toOwnedSlice();2847 return buffer.toOwnedSlice();
2838}2848}
28392849
lib/std/zig/render.zig+72-76
...@@ -12,64 +12,58 @@ pub const Error = error{...@@ -12,64 +12,58 @@ pub const Error = error{
12};12};
1313
14/// Returns whether anything changed14/// Returns whether anything changed
15pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@TypeOf(stream).Child.Error || Error)!bool {15pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@TypeOf(stream).Error || Error)!bool {
16 comptime assert(@typeInfo(@TypeOf(stream)) == .Pointer);
17
18 var anything_changed: bool = false;
19
20 // make a passthrough stream that checks whether something changed16 // make a passthrough stream that checks whether something changed
21 const MyStream = struct {17 const MyStream = struct {
22 const MyStream = @This();18 const MyStream = @This();
23 const StreamError = @TypeOf(stream).Child.Error;19 const StreamError = @TypeOf(stream).Error;
24 const Stream = std.io.OutStream(StreamError);
2520
26 anything_changed_ptr: *bool,
27 child_stream: @TypeOf(stream),21 child_stream: @TypeOf(stream),
28 stream: Stream,22 anything_changed: bool,
29 source_index: usize,23 source_index: usize,
30 source: []const u8,24 source: []const u8,
3125
32 fn write(iface_stream: *Stream, bytes: []const u8) StreamError!usize {26 fn write(self: *MyStream, bytes: []const u8) StreamError!usize {
33 const self = @fieldParentPtr(MyStream, "stream", iface_stream);27 if (!self.anything_changed) {
34
35 if (!self.anything_changed_ptr.*) {
36 const end = self.source_index + bytes.len;28 const end = self.source_index + bytes.len;
37 if (end > self.source.len) {29 if (end > self.source.len) {
38 self.anything_changed_ptr.* = true;30 self.anything_changed = true;
39 } else {31 } else {
40 const src_slice = self.source[self.source_index..end];32 const src_slice = self.source[self.source_index..end];
41 self.source_index += bytes.len;33 self.source_index += bytes.len;
42 if (!mem.eql(u8, bytes, src_slice)) {34 if (!mem.eql(u8, bytes, src_slice)) {
43 self.anything_changed_ptr.* = true;35 self.anything_changed = true;
44 }36 }
45 }37 }
46 }38 }
4739
48 return self.child_stream.writeOnce(bytes);40 return self.child_stream.write(bytes);
49 }41 }
50 };42 };
51 var my_stream = MyStream{43 var my_stream = MyStream{
52 .stream = MyStream.Stream{ .writeFn = MyStream.write },
53 .child_stream = stream,44 .child_stream = stream,
54 .anything_changed_ptr = &anything_changed,45 .anything_changed = false,
55 .source_index = 0,46 .source_index = 0,
56 .source = tree.source,47 .source = tree.source,
57 };48 };
49 const my_stream_stream: std.io.OutStream(*MyStream, MyStream.StreamError, MyStream.write) = .{
50 .context = &my_stream,
51 };
5852
59 try renderRoot(allocator, &my_stream.stream, tree);53 try renderRoot(allocator, my_stream_stream, tree);
6054
61 if (!anything_changed and my_stream.source_index != my_stream.source.len) {55 if (my_stream.source_index != my_stream.source.len) {
62 anything_changed = true;56 my_stream.anything_changed = true;
63 }57 }
6458
65 return anything_changed;59 return my_stream.anything_changed;
66}60}
6761
68fn renderRoot(62fn renderRoot(
69 allocator: *mem.Allocator,63 allocator: *mem.Allocator,
70 stream: var,64 stream: var,
71 tree: *ast.Tree,65 tree: *ast.Tree,
72) (@TypeOf(stream).Child.Error || Error)!void {66) (@TypeOf(stream).Error || Error)!void {
73 var tok_it = tree.tokens.iterator(0);67 var tok_it = tree.tokens.iterator(0);
7468
75 // render all the line comments at the beginning of the file69 // render all the line comments at the beginning of the file
...@@ -189,7 +183,7 @@ fn renderRoot(...@@ -189,7 +183,7 @@ fn renderRoot(
189 }183 }
190}184}
191185
192fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *ast.Node) @TypeOf(stream).Child.Error!void {186fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *ast.Node) @TypeOf(stream).Error!void {
193 const first_token = node.firstToken();187 const first_token = node.firstToken();
194 var prev_token = first_token;188 var prev_token = first_token;
195 if (prev_token == 0) return;189 if (prev_token == 0) return;
...@@ -204,11 +198,11 @@ fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *as...@@ -204,11 +198,11 @@ fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *as
204 }198 }
205}199}
206200
207fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, indent: usize, start_col: *usize, decl: *ast.Node) (@TypeOf(stream).Child.Error || Error)!void {201fn renderTopLevelDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, indent: usize, start_col: *usize, decl: *ast.Node) (@TypeOf(stream).Error || Error)!void {
208 try renderContainerDecl(allocator, stream, tree, indent, start_col, decl, .Newline);202 try renderContainerDecl(allocator, stream, tree, indent, start_col, decl, .Newline);
209}203}
210204
211fn renderContainerDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, indent: usize, start_col: *usize, decl: *ast.Node, space: Space) (@TypeOf(stream).Child.Error || Error)!void {205fn renderContainerDecl(allocator: *mem.Allocator, stream: var, tree: *ast.Tree, indent: usize, start_col: *usize, decl: *ast.Node, space: Space) (@TypeOf(stream).Error || Error)!void {
212 switch (decl.id) {206 switch (decl.id) {
213 .FnProto => {207 .FnProto => {
214 const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);208 const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);
...@@ -343,7 +337,7 @@ fn renderExpression(...@@ -343,7 +337,7 @@ fn renderExpression(
343 start_col: *usize,337 start_col: *usize,
344 base: *ast.Node,338 base: *ast.Node,
345 space: Space,339 space: Space,
346) (@TypeOf(stream).Child.Error || Error)!void {340) (@TypeOf(stream).Error || Error)!void {
347 switch (base.id) {341 switch (base.id) {
348 .Identifier => {342 .Identifier => {
349 const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base);343 const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base);
...@@ -390,6 +384,12 @@ fn renderExpression(...@@ -390,6 +384,12 @@ fn renderExpression(
390 try renderToken(tree, stream, comptime_node.comptime_token, indent, start_col, Space.Space);384 try renderToken(tree, stream, comptime_node.comptime_token, indent, start_col, Space.Space);
391 return renderExpression(allocator, stream, tree, indent, start_col, comptime_node.expr, space);385 return renderExpression(allocator, stream, tree, indent, start_col, comptime_node.expr, space);
392 },386 },
387 .Noasync => {
388 const noasync_node = @fieldParentPtr(ast.Node.Noasync, "base", base);
389
390 try renderToken(tree, stream, noasync_node.noasync_token, indent, start_col, Space.Space);
391 return renderExpression(allocator, stream, tree, indent, start_col, noasync_node.expr, space);
392 },
393393
394 .Suspend => {394 .Suspend => {
395 const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base);395 const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base);
...@@ -443,9 +443,9 @@ fn renderExpression(...@@ -443,9 +443,9 @@ fn renderExpression(
443 switch (op_tok_id) {443 switch (op_tok_id) {
444 .Asterisk, .AsteriskAsterisk => try stream.writeByte('*'),444 .Asterisk, .AsteriskAsterisk => try stream.writeByte('*'),
445 .LBracket => if (tree.tokens.at(prefix_op_node.op_token + 2).id == .Identifier)445 .LBracket => if (tree.tokens.at(prefix_op_node.op_token + 2).id == .Identifier)
446 try stream.write("[*c")446 try stream.writeAll("[*c")
447 else447 else
448 try stream.write("[*"),448 try stream.writeAll("[*"),
449 else => unreachable,449 else => unreachable,
450 }450 }
451 if (ptr_info.sentinel) |sentinel| {451 if (ptr_info.sentinel) |sentinel| {
...@@ -590,9 +590,6 @@ fn renderExpression(...@@ -590,9 +590,6 @@ fn renderExpression(
590 },590 },
591591
592 .Await => |await_info| {592 .Await => |await_info| {
593 if (await_info.noasync_token) |tok| {
594 try renderToken(tree, stream, tok, indent, start_col, Space.Space);
595 }
596 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space);593 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space);
597 },594 },
598 }595 }
...@@ -754,7 +751,7 @@ fn renderExpression(...@@ -754,7 +751,7 @@ fn renderExpression(
754 while (it.next()) |field_init| {751 while (it.next()) |field_init| {
755 var find_stream = FindByteOutStream.init('\n');752 var find_stream = FindByteOutStream.init('\n');
756 var dummy_col: usize = 0;753 var dummy_col: usize = 0;
757 try renderExpression(allocator, &find_stream.stream, tree, 0, &dummy_col, field_init.*, Space.None);754 try renderExpression(allocator, find_stream.outStream(), tree, 0, &dummy_col, field_init.*, Space.None);
758 if (find_stream.byte_found) break :blk false;755 if (find_stream.byte_found) break :blk false;
759 }756 }
760 break :blk true;757 break :blk true;
...@@ -906,8 +903,7 @@ fn renderExpression(...@@ -906,8 +903,7 @@ fn renderExpression(
906 var column_widths = widths[widths.len - row_size ..];903 var column_widths = widths[widths.len - row_size ..];
907904
908 // Null stream for counting the printed length of each expression905 // Null stream for counting the printed length of each expression
909 var null_stream = std.io.NullOutStream.init();906 var counting_stream = std.io.countingOutStream(std.io.null_out_stream);
910 var counting_stream = std.io.CountingOutStream(std.io.NullOutStream.Error).init(&null_stream.stream);
911907
912 var it = exprs.iterator(0);908 var it = exprs.iterator(0);
913 var i: usize = 0;909 var i: usize = 0;
...@@ -915,7 +911,7 @@ fn renderExpression(...@@ -915,7 +911,7 @@ fn renderExpression(
915 while (it.next()) |expr| : (i += 1) {911 while (it.next()) |expr| : (i += 1) {
916 counting_stream.bytes_written = 0;912 counting_stream.bytes_written = 0;
917 var dummy_col: usize = 0;913 var dummy_col: usize = 0;
918 try renderExpression(allocator, &counting_stream.stream, tree, indent, &dummy_col, expr.*, Space.None);914 try renderExpression(allocator, counting_stream.outStream(), tree, indent, &dummy_col, expr.*, Space.None);
919 const width = @intCast(usize, counting_stream.bytes_written);915 const width = @intCast(usize, counting_stream.bytes_written);
920 const col = i % row_size;916 const col = i % row_size;
921 column_widths[col] = std.math.max(column_widths[col], width);917 column_widths[col] = std.math.max(column_widths[col], width);
...@@ -1333,7 +1329,7 @@ fn renderExpression(...@@ -1333,7 +1329,7 @@ fn renderExpression(
13331329
1334 // TODO: Remove condition after deprecating 'typeOf'. See https://github.com/ziglang/zig/issues/13481330 // TODO: Remove condition after deprecating 'typeOf'. See https://github.com/ziglang/zig/issues/1348
1335 if (mem.eql(u8, tree.tokenSlicePtr(tree.tokens.at(builtin_call.builtin_token)), "@typeOf")) {1331 if (mem.eql(u8, tree.tokenSlicePtr(tree.tokens.at(builtin_call.builtin_token)), "@typeOf")) {
1336 try stream.write("@TypeOf");1332 try stream.writeAll("@TypeOf");
1337 } else {1333 } else {
1338 try renderToken(tree, stream, builtin_call.builtin_token, indent, start_col, Space.None); // @name1334 try renderToken(tree, stream, builtin_call.builtin_token, indent, start_col, Space.None); // @name
1339 }1335 }
...@@ -1502,9 +1498,9 @@ fn renderExpression(...@@ -1502,9 +1498,9 @@ fn renderExpression(
1502 try renderExpression(allocator, stream, tree, indent, start_col, callconv_expr, Space.None);1498 try renderExpression(allocator, stream, tree, indent, start_col, callconv_expr, Space.None);
1503 try renderToken(tree, stream, callconv_rparen, indent, start_col, Space.Space); // )1499 try renderToken(tree, stream, callconv_rparen, indent, start_col, Space.Space); // )
1504 } else if (cc_rewrite_str) |str| {1500 } else if (cc_rewrite_str) |str| {
1505 try stream.write("callconv(");1501 try stream.writeAll("callconv(");
1506 try stream.write(mem.toSliceConst(u8, str));1502 try stream.writeAll(mem.toSliceConst(u8, str));
1507 try stream.write(") ");1503 try stream.writeAll(") ");
1508 }1504 }
15091505
1510 switch (fn_proto.return_type) {1506 switch (fn_proto.return_type) {
...@@ -1994,11 +1990,11 @@ fn renderExpression(...@@ -1994,11 +1990,11 @@ fn renderExpression(
1994 .AsmInput => {1990 .AsmInput => {
1995 const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base);1991 const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base);
19961992
1997 try stream.write("[");1993 try stream.writeAll("[");
1998 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.symbolic_name, Space.None);1994 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.symbolic_name, Space.None);
1999 try stream.write("] ");1995 try stream.writeAll("] ");
2000 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.constraint, Space.None);1996 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.constraint, Space.None);
2001 try stream.write(" (");1997 try stream.writeAll(" (");
2002 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.expr, Space.None);1998 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.expr, Space.None);
2003 return renderToken(tree, stream, asm_input.lastToken(), indent, start_col, space); // )1999 return renderToken(tree, stream, asm_input.lastToken(), indent, start_col, space); // )
2004 },2000 },
...@@ -2006,18 +2002,18 @@ fn renderExpression(...@@ -2006,18 +2002,18 @@ fn renderExpression(
2006 .AsmOutput => {2002 .AsmOutput => {
2007 const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base);2003 const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base);
20082004
2009 try stream.write("[");2005 try stream.writeAll("[");
2010 try renderExpression(allocator, stream, tree, indent, start_col, asm_output.symbolic_name, Space.None);2006 try renderExpression(allocator, stream, tree, indent, start_col, asm_output.symbolic_name, Space.None);
2011 try stream.write("] ");2007 try stream.writeAll("] ");
2012 try renderExpression(allocator, stream, tree, indent, start_col, asm_output.constraint, Space.None);2008 try renderExpression(allocator, stream, tree, indent, start_col, asm_output.constraint, Space.None);
2013 try stream.write(" (");2009 try stream.writeAll(" (");
20142010
2015 switch (asm_output.kind) {2011 switch (asm_output.kind) {
2016 ast.Node.AsmOutput.Kind.Variable => |variable_name| {2012 ast.Node.AsmOutput.Kind.Variable => |variable_name| {
2017 try renderExpression(allocator, stream, tree, indent, start_col, &variable_name.base, Space.None);2013 try renderExpression(allocator, stream, tree, indent, start_col, &variable_name.base, Space.None);
2018 },2014 },
2019 ast.Node.AsmOutput.Kind.Return => |return_type| {2015 ast.Node.AsmOutput.Kind.Return => |return_type| {
2020 try stream.write("-> ");2016 try stream.writeAll("-> ");
2021 try renderExpression(allocator, stream, tree, indent, start_col, return_type, Space.None);2017 try renderExpression(allocator, stream, tree, indent, start_col, return_type, Space.None);
2022 },2018 },
2023 }2019 }
...@@ -2049,7 +2045,7 @@ fn renderVarDecl(...@@ -2049,7 +2045,7 @@ fn renderVarDecl(
2049 indent: usize,2045 indent: usize,
2050 start_col: *usize,2046 start_col: *usize,
2051 var_decl: *ast.Node.VarDecl,2047 var_decl: *ast.Node.VarDecl,
2052) (@TypeOf(stream).Child.Error || Error)!void {2048) (@TypeOf(stream).Error || Error)!void {
2053 if (var_decl.visib_token) |visib_token| {2049 if (var_decl.visib_token) |visib_token| {
2054 try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub2050 try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub
2055 }2051 }
...@@ -2122,7 +2118,7 @@ fn renderParamDecl(...@@ -2122,7 +2118,7 @@ fn renderParamDecl(
2122 start_col: *usize,2118 start_col: *usize,
2123 base: *ast.Node,2119 base: *ast.Node,
2124 space: Space,2120 space: Space,
2125) (@TypeOf(stream).Child.Error || Error)!void {2121) (@TypeOf(stream).Error || Error)!void {
2126 const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base);2122 const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base);
21272123
2128 try renderDocComments(tree, stream, param_decl, indent, start_col);2124 try renderDocComments(tree, stream, param_decl, indent, start_col);
...@@ -2151,7 +2147,7 @@ fn renderStatement(...@@ -2151,7 +2147,7 @@ fn renderStatement(
2151 indent: usize,2147 indent: usize,
2152 start_col: *usize,2148 start_col: *usize,
2153 base: *ast.Node,2149 base: *ast.Node,
2154) (@TypeOf(stream).Child.Error || Error)!void {2150) (@TypeOf(stream).Error || Error)!void {
2155 switch (base.id) {2151 switch (base.id) {
2156 .VarDecl => {2152 .VarDecl => {
2157 const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);2153 const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);
...@@ -2190,7 +2186,7 @@ fn renderTokenOffset(...@@ -2190,7 +2186,7 @@ fn renderTokenOffset(
2190 start_col: *usize,2186 start_col: *usize,
2191 space: Space,2187 space: Space,
2192 token_skip_bytes: usize,2188 token_skip_bytes: usize,
2193) (@TypeOf(stream).Child.Error || Error)!void {2189) (@TypeOf(stream).Error || Error)!void {
2194 if (space == Space.BlockStart) {2190 if (space == Space.BlockStart) {
2195 if (start_col.* < indent + indent_delta)2191 if (start_col.* < indent + indent_delta)
2196 return renderToken(tree, stream, token_index, indent, start_col, Space.Space);2192 return renderToken(tree, stream, token_index, indent, start_col, Space.Space);
...@@ -2201,7 +2197,7 @@ fn renderTokenOffset(...@@ -2201,7 +2197,7 @@ fn renderTokenOffset(
2201 }2197 }
22022198
2203 var token = tree.tokens.at(token_index);2199 var token = tree.tokens.at(token_index);
2204 try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(token)[token_skip_bytes..], " "));2200 try stream.writeAll(mem.trimRight(u8, tree.tokenSlicePtr(token)[token_skip_bytes..], " "));
22052201
2206 if (space == Space.NoComment)2202 if (space == Space.NoComment)
2207 return;2203 return;
...@@ -2211,15 +2207,15 @@ fn renderTokenOffset(...@@ -2211,15 +2207,15 @@ fn renderTokenOffset(
2211 if (space == Space.Comma) switch (next_token.id) {2207 if (space == Space.Comma) switch (next_token.id) {
2212 .Comma => return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline),2208 .Comma => return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline),
2213 .LineComment => {2209 .LineComment => {
2214 try stream.write(", ");2210 try stream.writeAll(", ");
2215 return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline);2211 return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline);
2216 },2212 },
2217 else => {2213 else => {
2218 if (token_index + 2 < tree.tokens.len and tree.tokens.at(token_index + 2).id == .MultilineStringLiteralLine) {2214 if (token_index + 2 < tree.tokens.len and tree.tokens.at(token_index + 2).id == .MultilineStringLiteralLine) {
2219 try stream.write(",");2215 try stream.writeAll(",");
2220 return;2216 return;
2221 } else {2217 } else {
2222 try stream.write(",\n");2218 try stream.writeAll(",\n");
2223 start_col.* = 0;2219 start_col.* = 0;
2224 return;2220 return;
2225 }2221 }
...@@ -2243,7 +2239,7 @@ fn renderTokenOffset(...@@ -2243,7 +2239,7 @@ fn renderTokenOffset(
2243 if (next_token.id == .MultilineStringLiteralLine) {2239 if (next_token.id == .MultilineStringLiteralLine) {
2244 return;2240 return;
2245 } else {2241 } else {
2246 try stream.write("\n");2242 try stream.writeAll("\n");
2247 start_col.* = 0;2243 start_col.* = 0;
2248 return;2244 return;
2249 }2245 }
...@@ -2306,7 +2302,7 @@ fn renderTokenOffset(...@@ -2306,7 +2302,7 @@ fn renderTokenOffset(
2306 if (next_token.id == .MultilineStringLiteralLine) {2302 if (next_token.id == .MultilineStringLiteralLine) {
2307 return;2303 return;
2308 } else {2304 } else {
2309 try stream.write("\n");2305 try stream.writeAll("\n");
2310 start_col.* = 0;2306 start_col.* = 0;
2311 return;2307 return;
2312 }2308 }
...@@ -2324,7 +2320,7 @@ fn renderTokenOffset(...@@ -2324,7 +2320,7 @@ fn renderTokenOffset(
2324 const newline_count = if (loc.line == 1) @as(u8, 1) else @as(u8, 2);2320 const newline_count = if (loc.line == 1) @as(u8, 1) else @as(u8, 2);
2325 try stream.writeByteNTimes('\n', newline_count);2321 try stream.writeByteNTimes('\n', newline_count);
2326 try stream.writeByteNTimes(' ', indent);2322 try stream.writeByteNTimes(' ', indent);
2327 try stream.write(mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "));2323 try stream.writeAll(mem.trimRight(u8, tree.tokenSlicePtr(next_token), " "));
23282324
2329 offset += 1;2325 offset += 1;
2330 token = next_token;2326 token = next_token;
...@@ -2335,7 +2331,7 @@ fn renderTokenOffset(...@@ -2335,7 +2331,7 @@ fn renderTokenOffset(
2335 if (next_token.id == .MultilineStringLiteralLine) {2331 if (next_token.id == .MultilineStringLiteralLine) {
2336 return;2332 return;
2337 } else {2333 } else {
2338 try stream.write("\n");2334 try stream.writeAll("\n");
2339 start_col.* = 0;2335 start_col.* = 0;
2340 return;2336 return;
2341 }2337 }
...@@ -2378,7 +2374,7 @@ fn renderToken(...@@ -2378,7 +2374,7 @@ fn renderToken(
2378 indent: usize,2374 indent: usize,
2379 start_col: *usize,2375 start_col: *usize,
2380 space: Space,2376 space: Space,
2381) (@TypeOf(stream).Child.Error || Error)!void {2377) (@TypeOf(stream).Error || Error)!void {
2382 return renderTokenOffset(tree, stream, token_index, indent, start_col, space, 0);2378 return renderTokenOffset(tree, stream, token_index, indent, start_col, space, 0);
2383}2379}
23842380
...@@ -2388,7 +2384,7 @@ fn renderDocComments(...@@ -2388,7 +2384,7 @@ fn renderDocComments(
2388 node: var,2384 node: var,
2389 indent: usize,2385 indent: usize,
2390 start_col: *usize,2386 start_col: *usize,
2391) (@TypeOf(stream).Child.Error || Error)!void {2387) (@TypeOf(stream).Error || Error)!void {
2392 const comment = node.doc_comments orelse return;2388 const comment = node.doc_comments orelse return;
2393 var it = comment.lines.iterator(0);2389 var it = comment.lines.iterator(0);
2394 const first_token = node.firstToken();2390 const first_token = node.firstToken();
...@@ -2398,7 +2394,7 @@ fn renderDocComments(...@@ -2398,7 +2394,7 @@ fn renderDocComments(
2398 try stream.writeByteNTimes(' ', indent);2394 try stream.writeByteNTimes(' ', indent);
2399 } else {2395 } else {
2400 try renderToken(tree, stream, line_token_index.*, indent, start_col, Space.NoComment);2396 try renderToken(tree, stream, line_token_index.*, indent, start_col, Space.NoComment);
2401 try stream.write("\n");2397 try stream.writeAll("\n");
2402 try stream.writeByteNTimes(' ', indent);2398 try stream.writeByteNTimes(' ', indent);
2403 }2399 }
2404 }2400 }
...@@ -2424,27 +2420,23 @@ fn nodeCausesSliceOpSpace(base: *ast.Node) bool {...@@ -2424,27 +2420,23 @@ fn nodeCausesSliceOpSpace(base: *ast.Node) bool {
2424 };2420 };
2425}2421}
24262422
2427// An OutStream that returns whether the given character has been written to it.2423/// A `std.io.OutStream` that returns whether the given character has been written to it.
2428// The contents are not written to anything.2424/// The contents are not written to anything.
2429const FindByteOutStream = struct {2425const FindByteOutStream = struct {
2430 const Self = FindByteOutStream;
2431 pub const Error = error{};
2432 pub const Stream = std.io.OutStream(Error);
2433
2434 stream: Stream,
2435 byte_found: bool,2426 byte_found: bool,
2436 byte: u8,2427 byte: u8,
24372428
2438 pub fn init(byte: u8) Self {2429 pub const Error = error{};
2439 return Self{2430 pub const OutStream = std.io.OutStream(*FindByteOutStream, Error, write);
2440 .stream = Stream{ .writeFn = writeFn },2431
2432 pub fn init(byte: u8) FindByteOutStream {
2433 return FindByteOutStream{
2441 .byte = byte,2434 .byte = byte,
2442 .byte_found = false,2435 .byte_found = false,
2443 };2436 };
2444 }2437 }
24452438
2446 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {2439 pub fn write(self: *FindByteOutStream, bytes: []const u8) Error!usize {
2447 const self = @fieldParentPtr(Self, "stream", out_stream);
2448 if (self.byte_found) return bytes.len;2440 if (self.byte_found) return bytes.len;
2449 self.byte_found = blk: {2441 self.byte_found = blk: {
2450 for (bytes) |b|2442 for (bytes) |b|
...@@ -2453,11 +2445,15 @@ const FindByteOutStream = struct {...@@ -2453,11 +2445,15 @@ const FindByteOutStream = struct {
2453 };2445 };
2454 return bytes.len;2446 return bytes.len;
2455 }2447 }
2448
2449 pub fn outStream(self: *FindByteOutStream) OutStream {
2450 return .{ .context = self };
2451 }
2456};2452};
24572453
2458fn copyFixingWhitespace(stream: var, slice: []const u8) @TypeOf(stream).Child.Error!void {2454fn copyFixingWhitespace(stream: var, slice: []const u8) @TypeOf(stream).Error!void {
2459 for (slice) |byte| switch (byte) {2455 for (slice) |byte| switch (byte) {
2460 '\t' => try stream.write(" "),2456 '\t' => try stream.writeAll(" "),
2461 '\r' => {},2457 '\r' => {},
2462 else => try stream.writeByte(byte),2458 else => try stream.writeByte(byte),
2463 };2459 };
lib/std/zig/system.zig+25-27
...@@ -201,8 +201,15 @@ pub const NativeTargetInfo = struct {...@@ -201,8 +201,15 @@ 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, @ptrCast([*:0]const u8, &uts.release));204 const release = mem.toSliceConst(u8, &uts.release);
205 if (std.builtin.Version.parse(release)) |ver| {205 // The release field may have several other fields after the
206 // kernel version
207 const kernel_version = if (mem.indexOfScalar(u8, release, '-')) |pos|
208 release[0..pos]
209 else
210 release;
211
212 if (std.builtin.Version.parse(kernel_version)) |ver| {
206 os.version_range.linux.range.min = ver;213 os.version_range.linux.range.min = ver;
207 os.version_range.linux.range.max = ver;214 os.version_range.linux.range.max = ver;
208 } else |err| switch (err) {215 } else |err| switch (err) {
...@@ -318,22 +325,19 @@ pub const NativeTargetInfo = struct {...@@ -318,22 +325,19 @@ pub const NativeTargetInfo = struct {
318 // native CPU architecture as being different than the current target), we use this:325 // native CPU architecture as being different than the current target), we use this:
319 const cpu_arch = cross_target.getCpuArch();326 const cpu_arch = cross_target.getCpuArch();
320327
321 const cpu = switch (cross_target.cpu_model) {328 var cpu = switch (cross_target.cpu_model) {
322 .native => detectNativeCpuAndFeatures(cpu_arch, os, cross_target),329 .native => detectNativeCpuAndFeatures(cpu_arch, os, cross_target),
323 .baseline => baselineCpuAndFeatures(cpu_arch, cross_target),330 .baseline => Target.Cpu.baseline(cpu_arch),
324 .determined_by_cpu_arch => if (cross_target.cpu_arch == null)331 .determined_by_cpu_arch => if (cross_target.cpu_arch == null)
325 detectNativeCpuAndFeatures(cpu_arch, os, cross_target)332 detectNativeCpuAndFeatures(cpu_arch, os, cross_target)
326 else333 else
327 baselineCpuAndFeatures(cpu_arch, cross_target),334 Target.Cpu.baseline(cpu_arch),
328 .explicit => |model| blk: {335 .explicit => |model| model.toCpu(cpu_arch),
329 var adjusted_model = model.toCpu(cpu_arch);
330 cross_target.updateCpuFeatures(&adjusted_model.features);
331 break :blk adjusted_model;
332 },
333 } orelse backup_cpu_detection: {336 } orelse backup_cpu_detection: {
334 cpu_detection_unimplemented = true;337 cpu_detection_unimplemented = true;
335 break :backup_cpu_detection baselineCpuAndFeatures(cpu_arch, cross_target);338 break :backup_cpu_detection Target.Cpu.baseline(cpu_arch);
336 };339 };
340 cross_target.updateCpuFeatures(&cpu.features);
337341
338 var target = try detectAbiAndDynamicLinker(allocator, cpu, os, cross_target);342 var target = try detectAbiAndDynamicLinker(allocator, cpu, os, cross_target);
339 target.cpu_detection_unimplemented = cpu_detection_unimplemented;343 target.cpu_detection_unimplemented = cpu_detection_unimplemented;
...@@ -563,7 +567,7 @@ pub const NativeTargetInfo = struct {...@@ -563,7 +567,7 @@ pub const NativeTargetInfo = struct {
563 cross_target: CrossTarget,567 cross_target: CrossTarget,
564 ) AbiAndDynamicLinkerFromFileError!NativeTargetInfo {568 ) AbiAndDynamicLinkerFromFileError!NativeTargetInfo {
565 var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 align(@alignOf(elf.Elf64_Ehdr)) = undefined;569 var hdr_buf: [@sizeOf(elf.Elf64_Ehdr)]u8 align(@alignOf(elf.Elf64_Ehdr)) = undefined;
566 _ = try preadFull(file, &hdr_buf, 0, hdr_buf.len);570 _ = try preadMin(file, &hdr_buf, 0, hdr_buf.len);
567 const hdr32 = @ptrCast(*elf.Elf32_Ehdr, &hdr_buf);571 const hdr32 = @ptrCast(*elf.Elf32_Ehdr, &hdr_buf);
568 const hdr64 = @ptrCast(*elf.Elf64_Ehdr, &hdr_buf);572 const hdr64 = @ptrCast(*elf.Elf64_Ehdr, &hdr_buf);
569 if (!mem.eql(u8, hdr32.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;573 if (!mem.eql(u8, hdr32.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
...@@ -603,7 +607,7 @@ pub const NativeTargetInfo = struct {...@@ -603,7 +607,7 @@ pub const NativeTargetInfo = struct {
603 // Reserve some bytes so that we can deref the 64-bit struct fields607 // Reserve some bytes so that we can deref the 64-bit struct fields
604 // even when the ELF file is 32-bits.608 // even when the ELF file is 32-bits.
605 const ph_reserve: usize = @sizeOf(elf.Elf64_Phdr) - @sizeOf(elf.Elf32_Phdr);609 const ph_reserve: usize = @sizeOf(elf.Elf64_Phdr) - @sizeOf(elf.Elf32_Phdr);
606 const ph_read_byte_len = try preadFull(file, ph_buf[0 .. ph_buf.len - ph_reserve], phoff, phentsize);610 const ph_read_byte_len = try preadMin(file, ph_buf[0 .. ph_buf.len - ph_reserve], phoff, phentsize);
607 var ph_buf_i: usize = 0;611 var ph_buf_i: usize = 0;
608 while (ph_buf_i < ph_read_byte_len and ph_i < phnum) : ({612 while (ph_buf_i < ph_read_byte_len and ph_i < phnum) : ({
609 ph_i += 1;613 ph_i += 1;
...@@ -618,7 +622,7 @@ pub const NativeTargetInfo = struct {...@@ -618,7 +622,7 @@ pub const NativeTargetInfo = struct {
618 const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);622 const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);
619 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);623 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);
620 if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong;624 if (p_filesz > result.dynamic_linker.buffer.len) return error.NameTooLong;
621 _ = try preadFull(file, result.dynamic_linker.buffer[0..p_filesz], p_offset, p_filesz);625 _ = try preadMin(file, result.dynamic_linker.buffer[0..p_filesz], p_offset, p_filesz);
622 // PT_INTERP includes a null byte in p_filesz.626 // PT_INTERP includes a null byte in p_filesz.
623 const len = p_filesz - 1;627 const len = p_filesz - 1;
624 // dynamic_linker.max_byte is "max", not "len".628 // dynamic_linker.max_byte is "max", not "len".
...@@ -649,7 +653,7 @@ pub const NativeTargetInfo = struct {...@@ -649,7 +653,7 @@ pub const NativeTargetInfo = struct {
649 // Reserve some bytes so that we can deref the 64-bit struct fields653 // Reserve some bytes so that we can deref the 64-bit struct fields
650 // even when the ELF file is 32-bits.654 // even when the ELF file is 32-bits.
651 const dyn_reserve: usize = @sizeOf(elf.Elf64_Dyn) - @sizeOf(elf.Elf32_Dyn);655 const dyn_reserve: usize = @sizeOf(elf.Elf64_Dyn) - @sizeOf(elf.Elf32_Dyn);
652 const dyn_read_byte_len = try preadFull(656 const dyn_read_byte_len = try preadMin(
653 file,657 file,
654 dyn_buf[0 .. dyn_buf.len - dyn_reserve],658 dyn_buf[0 .. dyn_buf.len - dyn_reserve],
655 dyn_off,659 dyn_off,
...@@ -694,14 +698,14 @@ pub const NativeTargetInfo = struct {...@@ -694,14 +698,14 @@ pub const NativeTargetInfo = struct {
694 var sh_buf: [16 * @sizeOf(elf.Elf64_Shdr)]u8 align(@alignOf(elf.Elf64_Shdr)) = undefined;698 var sh_buf: [16 * @sizeOf(elf.Elf64_Shdr)]u8 align(@alignOf(elf.Elf64_Shdr)) = undefined;
695 if (sh_buf.len < shentsize) return error.InvalidElfFile;699 if (sh_buf.len < shentsize) return error.InvalidElfFile;
696700
697 _ = try preadFull(file, &sh_buf, str_section_off, shentsize);701 _ = try preadMin(file, &sh_buf, str_section_off, shentsize);
698 const shstr32 = @ptrCast(*elf.Elf32_Shdr, @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf));702 const shstr32 = @ptrCast(*elf.Elf32_Shdr, @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf));
699 const shstr64 = @ptrCast(*elf.Elf64_Shdr, @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf));703 const shstr64 = @ptrCast(*elf.Elf64_Shdr, @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf));
700 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);704 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);
701 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);705 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);
702 var strtab_buf: [4096:0]u8 = undefined;706 var strtab_buf: [4096:0]u8 = undefined;
703 const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len);707 const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len);
704 const shstrtab_read_len = try preadFull(file, &strtab_buf, shstrtab_off, shstrtab_len);708 const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len);
705 const shstrtab = strtab_buf[0..shstrtab_read_len];709 const shstrtab = strtab_buf[0..shstrtab_read_len];
706710
707 const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum);711 const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum);
...@@ -710,7 +714,7 @@ pub const NativeTargetInfo = struct {...@@ -710,7 +714,7 @@ pub const NativeTargetInfo = struct {
710 // Reserve some bytes so that we can deref the 64-bit struct fields714 // Reserve some bytes so that we can deref the 64-bit struct fields
711 // even when the ELF file is 32-bits.715 // even when the ELF file is 32-bits.
712 const sh_reserve: usize = @sizeOf(elf.Elf64_Shdr) - @sizeOf(elf.Elf32_Shdr);716 const sh_reserve: usize = @sizeOf(elf.Elf64_Shdr) - @sizeOf(elf.Elf32_Shdr);
713 const sh_read_byte_len = try preadFull(717 const sh_read_byte_len = try preadMin(
714 file,718 file,
715 sh_buf[0 .. sh_buf.len - sh_reserve],719 sh_buf[0 .. sh_buf.len - sh_reserve],
716 shoff,720 shoff,
...@@ -744,7 +748,7 @@ pub const NativeTargetInfo = struct {...@@ -744,7 +748,7 @@ pub const NativeTargetInfo = struct {
744748
745 if (dynstr) |ds| {749 if (dynstr) |ds| {
746 const strtab_len = std.math.min(ds.size, strtab_buf.len);750 const strtab_len = std.math.min(ds.size, strtab_buf.len);
747 const strtab_read_len = try preadFull(file, &strtab_buf, ds.offset, shstrtab_len);751 const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, shstrtab_len);
748 const strtab = strtab_buf[0..strtab_read_len];752 const strtab = strtab_buf[0..strtab_read_len];
749 // TODO this pointer cast should not be necessary753 // TODO this pointer cast should not be necessary
750 const rpath_list = mem.toSliceConst(u8, @ptrCast([*:0]u8, strtab[rpoff..].ptr));754 const rpath_list = mem.toSliceConst(u8, @ptrCast([*:0]u8, strtab[rpoff..].ptr));
...@@ -806,7 +810,7 @@ pub const NativeTargetInfo = struct {...@@ -806,7 +810,7 @@ pub const NativeTargetInfo = struct {
806 return result;810 return result;
807 }811 }
808812
809 fn preadFull(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize {813 fn preadMin(file: fs.File, buf: []u8, offset: u64, min_read_len: usize) !usize {
810 var i: u64 = 0;814 var i: u64 = 0;
811 while (i < min_read_len) {815 while (i < min_read_len) {
812 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {816 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {
...@@ -846,7 +850,7 @@ pub const NativeTargetInfo = struct {...@@ -846,7 +850,7 @@ pub const NativeTargetInfo = struct {
846 abi: Target.Abi,850 abi: Target.Abi,
847 };851 };
848852
849 fn elfInt(is_64: bool, need_bswap: bool, int_32: var, int_64: var) @TypeOf(int_64) {853 pub fn elfInt(is_64: bool, need_bswap: bool, int_32: var, int_64: var) @TypeOf(int_64) {
850 if (is_64) {854 if (is_64) {
851 if (need_bswap) {855 if (need_bswap) {
852 return @byteSwap(@TypeOf(int_64), int_64);856 return @byteSwap(@TypeOf(int_64), int_64);
...@@ -877,10 +881,4 @@ pub const NativeTargetInfo = struct {...@@ -877,10 +881,4 @@ pub const NativeTargetInfo = struct {
877 },881 },
878 }882 }
879 }883 }
880
881 fn baselineCpuAndFeatures(cpu_arch: Target.Cpu.Arch, cross_target: CrossTarget) Target.Cpu {
882 var adjusted_baseline = Target.Cpu.baseline(cpu_arch);
883 cross_target.updateCpuFeatures(&adjusted_baseline.features);
884 return adjusted_baseline;
885 }
886};884};
lib/std/zig/system/x86.zig+44-36
...@@ -2,6 +2,12 @@ const std = @import("std");...@@ -2,6 +2,12 @@ const std = @import("std");
2const Target = std.Target;2const Target = std.Target;
3const CrossTarget = std.zig.CrossTarget;3const CrossTarget = std.zig.CrossTarget;
44
5const XCR0_XMM = 0x02;
6const XCR0_YMM = 0x04;
7const XCR0_MASKREG = 0x20;
8const XCR0_ZMM0_15 = 0x40;
9const XCR0_ZMM16_31 = 0x80;
10
5fn setFeature(cpu: *Target.Cpu, feature: Target.x86.Feature, enabled: bool) void {11fn setFeature(cpu: *Target.Cpu, feature: Target.x86.Feature, enabled: bool) void {
6 const idx = @as(Target.Cpu.Feature.Set.Index, @enumToInt(feature));12 const idx = @as(Target.Cpu.Feature.Set.Index, @enumToInt(feature));
713
...@@ -12,6 +18,10 @@ inline fn bit(input: u32, offset: u5) bool {...@@ -12,6 +18,10 @@ inline fn bit(input: u32, offset: u5) bool {
12 return (input >> offset) & 1 != 0;18 return (input >> offset) & 1 != 0;
13}19}
1420
21inline fn hasMask(input: u32, mask: u32) bool {
22 return (input & mask) == mask;
23}
24
15pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_target: CrossTarget) Target.Cpu {25pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_target: CrossTarget) Target.Cpu {
16 var cpu = Target.Cpu{26 var cpu = Target.Cpu{
17 .arch = arch,27 .arch = arch,
...@@ -30,18 +40,15 @@ pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_ta...@@ -30,18 +40,15 @@ pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_ta
30 leaf = cpuid(0x1, 0);40 leaf = cpuid(0x1, 0);
3141
32 const brand_id = leaf.ebx & 0xff;42 const brand_id = leaf.ebx & 0xff;
33 var family: u32 = 0;43
34 var model: u32 = 0;44 // Detect model and family
3545 var family = (leaf.eax >> 8) & 0xf;
36 { // Detect model and family46 var model = (leaf.eax >> 4) & 0xf;
37 family = (leaf.eax >> 8) & 0xf;47 if (family == 6 or family == 0xf) {
38 model = (leaf.eax >> 4) & 0xf;48 if (family == 0xf) {
39 if (family == 6 or family == 0xf) {49 family += (leaf.eax >> 20) & 0xff;
40 if (family == 0xf) {
41 family += (leaf.eax >> 20) & 0xff;
42 }
43 model += ((leaf.eax >> 16) & 0xf) << 4;
44 }50 }
51 model += ((leaf.eax >> 16) & 0xf) << 4;
45 }52 }
4653
47 // Now we detect the model.54 // Now we detect the model.
...@@ -312,7 +319,6 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -312,7 +319,6 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
312319
313 leaf = cpuid(1, 0);320 leaf = cpuid(1, 0);
314321
315 setFeature(cpu, .cx8, bit(leaf.edx, 8));
316 setFeature(cpu, .cx8, bit(leaf.edx, 8));322 setFeature(cpu, .cx8, bit(leaf.edx, 8));
317 setFeature(cpu, .cmov, bit(leaf.edx, 15));323 setFeature(cpu, .cmov, bit(leaf.edx, 15));
318 setFeature(cpu, .mmx, bit(leaf.edx, 23));324 setFeature(cpu, .mmx, bit(leaf.edx, 23));
...@@ -330,11 +336,13 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -330,11 +336,13 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
330 setFeature(cpu, .aes, bit(leaf.ecx, 25));336 setFeature(cpu, .aes, bit(leaf.ecx, 25));
331 setFeature(cpu, .rdrnd, bit(leaf.ecx, 30));337 setFeature(cpu, .rdrnd, bit(leaf.ecx, 30));
332338
333 leaf.eax = getXCR0();339 const has_xsave = bit(leaf.ecx, 27);
340 const has_avx = bit(leaf.ecx, 28);
341
342 // Make sure not to call xgetbv if xsave is not supported
343 const xcr0_eax = if (has_xsave and has_avx) getXCR0() else 0;
334344
335 const has_avx = bit(leaf.ecx, 27) and345 const has_avx_save = hasMask(xcr0_eax, XCR0_XMM | XCR0_YMM);
336 bit(leaf.ecx, 28) and
337 ((leaf.eax & 0x6) == 0x6);
338346
339 // LLVM approaches avx512_save by hardcoding it to true on Darwin,347 // LLVM approaches avx512_save by hardcoding it to true on Darwin,
340 // because the kernel saves the context even if the bit is not set.348 // because the kernel saves the context even if the bit is not set.
...@@ -358,14 +366,14 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -358,14 +366,14 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
358 // set right now.366 // set right now.
359 const has_avx512_save = switch (os_tag.isDarwin()) {367 const has_avx512_save = switch (os_tag.isDarwin()) {
360 true => true,368 true => true,
361 false => has_avx and ((leaf.eax & 0xE0) == 0xE0),369 false => hasMask(xcr0_eax, XCR0_MASKREG | XCR0_ZMM0_15 | XCR0_ZMM16_31),
362 };370 };
363371
364 setFeature(cpu, .avx, has_avx);372 setFeature(cpu, .avx, has_avx_save);
365 setFeature(cpu, .fma, has_avx and bit(leaf.ecx, 12));373 setFeature(cpu, .fma, has_avx_save and bit(leaf.ecx, 12));
366 // Only enable XSAVE if OS has enabled support for saving YMM state.374 // Only enable XSAVE if OS has enabled support for saving YMM state.
367 setFeature(cpu, .xsave, has_avx and bit(leaf.ecx, 26));375 setFeature(cpu, .xsave, has_avx_save and bit(leaf.ecx, 26));
368 setFeature(cpu, .f16c, has_avx and bit(leaf.ecx, 29));376 setFeature(cpu, .f16c, has_avx_save and bit(leaf.ecx, 29));
369377
370 leaf = cpuid(0x80000000, 0);378 leaf = cpuid(0x80000000, 0);
371 const max_ext_level = leaf.eax;379 const max_ext_level = leaf.eax;
...@@ -376,9 +384,9 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -376,9 +384,9 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
376 setFeature(cpu, .lzcnt, bit(leaf.ecx, 5));384 setFeature(cpu, .lzcnt, bit(leaf.ecx, 5));
377 setFeature(cpu, .sse4a, bit(leaf.ecx, 6));385 setFeature(cpu, .sse4a, bit(leaf.ecx, 6));
378 setFeature(cpu, .prfchw, bit(leaf.ecx, 8));386 setFeature(cpu, .prfchw, bit(leaf.ecx, 8));
379 setFeature(cpu, .xop, bit(leaf.ecx, 11) and has_avx);387 setFeature(cpu, .xop, bit(leaf.ecx, 11) and has_avx_save);
380 setFeature(cpu, .lwp, bit(leaf.ecx, 15));388 setFeature(cpu, .lwp, bit(leaf.ecx, 15));
381 setFeature(cpu, .fma4, bit(leaf.ecx, 16) and has_avx);389 setFeature(cpu, .fma4, bit(leaf.ecx, 16) and has_avx_save);
382 setFeature(cpu, .tbm, bit(leaf.ecx, 21));390 setFeature(cpu, .tbm, bit(leaf.ecx, 21));
383 setFeature(cpu, .mwaitx, bit(leaf.ecx, 29));391 setFeature(cpu, .mwaitx, bit(leaf.ecx, 29));
384 setFeature(cpu, .@"64bit", bit(leaf.edx, 29));392 setFeature(cpu, .@"64bit", bit(leaf.edx, 29));
...@@ -409,7 +417,7 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -409,7 +417,7 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
409 setFeature(cpu, .sgx, bit(leaf.ebx, 2));417 setFeature(cpu, .sgx, bit(leaf.ebx, 2));
410 setFeature(cpu, .bmi, bit(leaf.ebx, 3));418 setFeature(cpu, .bmi, bit(leaf.ebx, 3));
411 // AVX2 is only supported if we have the OS save support from AVX.419 // AVX2 is only supported if we have the OS save support from AVX.
412 setFeature(cpu, .avx2, bit(leaf.ebx, 5) and has_avx);420 setFeature(cpu, .avx2, bit(leaf.ebx, 5) and has_avx_save);
413 setFeature(cpu, .bmi2, bit(leaf.ebx, 8));421 setFeature(cpu, .bmi2, bit(leaf.ebx, 8));
414 setFeature(cpu, .invpcid, bit(leaf.ebx, 10));422 setFeature(cpu, .invpcid, bit(leaf.ebx, 10));
415 setFeature(cpu, .rtm, bit(leaf.ebx, 11));423 setFeature(cpu, .rtm, bit(leaf.ebx, 11));
...@@ -435,8 +443,8 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -435,8 +443,8 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
435 setFeature(cpu, .avx512vbmi2, bit(leaf.ecx, 6) and has_avx512_save);443 setFeature(cpu, .avx512vbmi2, bit(leaf.ecx, 6) and has_avx512_save);
436 setFeature(cpu, .shstk, bit(leaf.ecx, 7));444 setFeature(cpu, .shstk, bit(leaf.ecx, 7));
437 setFeature(cpu, .gfni, bit(leaf.ecx, 8));445 setFeature(cpu, .gfni, bit(leaf.ecx, 8));
438 setFeature(cpu, .vaes, bit(leaf.ecx, 9) and has_avx);446 setFeature(cpu, .vaes, bit(leaf.ecx, 9) and has_avx_save);
439 setFeature(cpu, .vpclmulqdq, bit(leaf.ecx, 10) and has_avx);447 setFeature(cpu, .vpclmulqdq, bit(leaf.ecx, 10) and has_avx_save);
440 setFeature(cpu, .avx512vnni, bit(leaf.ecx, 11) and has_avx512_save);448 setFeature(cpu, .avx512vnni, bit(leaf.ecx, 11) and has_avx512_save);
441 setFeature(cpu, .avx512bitalg, bit(leaf.ecx, 12) and has_avx512_save);449 setFeature(cpu, .avx512bitalg, bit(leaf.ecx, 12) and has_avx512_save);
442 setFeature(cpu, .avx512vpopcntdq, bit(leaf.ecx, 14) and has_avx512_save);450 setFeature(cpu, .avx512vpopcntdq, bit(leaf.ecx, 14) and has_avx512_save);
...@@ -487,7 +495,7 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {...@@ -487,7 +495,7 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
487 }495 }
488 }496 }
489497
490 if (max_level >= 0xD and has_avx) {498 if (max_level >= 0xD and has_avx_save) {
491 leaf = cpuid(0xD, 0x1);499 leaf = cpuid(0xD, 0x1);
492 // Only enable XSAVE if OS has enabled support for saving YMM state.500 // Only enable XSAVE if OS has enabled support for saving YMM state.
493 setFeature(cpu, .xsaveopt, bit(leaf.eax, 0));501 setFeature(cpu, .xsaveopt, bit(leaf.eax, 0));
...@@ -518,32 +526,32 @@ fn cpuid(leaf_id: u32, subid: u32) CpuidLeaf {...@@ -518,32 +526,32 @@ fn cpuid(leaf_id: u32, subid: u32) CpuidLeaf {
518 // Workaround for https://github.com/ziglang/zig/issues/215526 // Workaround for https://github.com/ziglang/zig/issues/215
519 // Inline assembly in zig only supports one output,527 // Inline assembly in zig only supports one output,
520 // so we pass a pointer to the struct.528 // so we pass a pointer to the struct.
521 var cpuid_leaf = CpuidLeaf{ .eax = 0, .ebx = 0, .ecx = 0, .edx = 0 };529 var cpuid_leaf: CpuidLeaf = undefined;
522 const leaf_ptr = &cpuid_leaf;
523530
524 // valid for both x86 and x86_64531 // valid for both x86 and x86_64
525 asm volatile (532 asm volatile (
526 \\ cpuid533 \\ cpuid
527 \\ movl %%eax, (%[leaf_ptr])534 \\ movl %%eax, 0(%[leaf_ptr])
528 \\ movl %%ebx, 4(%[leaf_ptr])535 \\ movl %%ebx, 4(%[leaf_ptr])
529 \\ movl %%ecx, 8(%[leaf_ptr])536 \\ movl %%ecx, 8(%[leaf_ptr])
530 \\ movl %%edx, 12(%[leaf_ptr])537 \\ movl %%edx, 12(%[leaf_ptr])
531 :538 :
532 : [leaf_id] "{eax}" (leaf_id),539 : [leaf_id] "{eax}" (leaf_id),
533 [subid] "{ecx}" (subid),540 [subid] "{ecx}" (subid),
534 [leaf_ptr] "r" (leaf_ptr)541 [leaf_ptr] "r" (&cpuid_leaf)
535 : "eax", "ebx", "ecx", "edx"542 : "eax", "ebx", "ecx", "edx"
536 );543 );
544
537 return cpuid_leaf;545 return cpuid_leaf;
538}546}
539547
540// Read control register 0 (XCR0). Used to detect features such as AVX.548// Read control register 0 (XCR0). Used to detect features such as AVX.
541fn getXCR0() u32 {549fn getXCR0() u32 {
542 return asm (550 return asm volatile (
543 \\ .byte 0x0F, 0x01, 0xD0551 \\ xor %%ecx, %%ecx
552 \\ xgetbv
544 : [ret] "={eax}" (-> u32)553 : [ret] "={eax}" (-> u32)
545 : [number] "{eax}" (@as(u32, 0)),554 :
546 [number] "{edx}" (@as(u32, 0)),555 : "eax", "edx", "ecx"
547 [number] "{ecx}" (@as(u32, 0))
548 );556 );
549}557}
src-self-hosted/clang.zig+2
...@@ -787,6 +787,7 @@ pub extern fn ZigClangTagDecl_isThisDeclarationADefinition(self: *const ZigClang...@@ -787,6 +787,7 @@ pub extern fn ZigClangTagDecl_isThisDeclarationADefinition(self: *const ZigClang
787pub extern fn ZigClangEnumType_getDecl(record_ty: ?*const struct_ZigClangEnumType) *const struct_ZigClangEnumDecl;787pub extern fn ZigClangEnumType_getDecl(record_ty: ?*const struct_ZigClangEnumType) *const struct_ZigClangEnumDecl;
788pub extern fn ZigClangRecordDecl_getCanonicalDecl(record_decl: ?*const struct_ZigClangRecordDecl) ?*const struct_ZigClangTagDecl;788pub extern fn ZigClangRecordDecl_getCanonicalDecl(record_decl: ?*const struct_ZigClangRecordDecl) ?*const struct_ZigClangTagDecl;
789pub extern fn ZigClangFieldDecl_getCanonicalDecl(field_decl: ?*const struct_ZigClangFieldDecl) ?*const struct_ZigClangFieldDecl;789pub extern fn ZigClangFieldDecl_getCanonicalDecl(field_decl: ?*const struct_ZigClangFieldDecl) ?*const struct_ZigClangFieldDecl;
790pub extern fn ZigClangFieldDecl_getAlignedAttribute(field_decl: ?*const struct_ZigClangFieldDecl, *const ZigClangASTContext) c_uint;
790pub extern fn ZigClangEnumDecl_getCanonicalDecl(self: ?*const struct_ZigClangEnumDecl) ?*const struct_ZigClangTagDecl;791pub extern fn ZigClangEnumDecl_getCanonicalDecl(self: ?*const struct_ZigClangEnumDecl) ?*const struct_ZigClangTagDecl;
791pub extern fn ZigClangTypedefNameDecl_getCanonicalDecl(self: ?*const struct_ZigClangTypedefNameDecl) ?*const struct_ZigClangTypedefNameDecl;792pub extern fn ZigClangTypedefNameDecl_getCanonicalDecl(self: ?*const struct_ZigClangTypedefNameDecl) ?*const struct_ZigClangTypedefNameDecl;
792pub extern fn ZigClangFunctionDecl_getCanonicalDecl(self: ?*const struct_ZigClangFunctionDecl) ?*const struct_ZigClangFunctionDecl;793pub extern fn ZigClangFunctionDecl_getCanonicalDecl(self: ?*const struct_ZigClangFunctionDecl) ?*const struct_ZigClangFunctionDecl;
...@@ -834,6 +835,7 @@ pub extern fn ZigClangType_getPointeeType(self: ?*const struct_ZigClangType) str...@@ -834,6 +835,7 @@ pub extern fn ZigClangType_getPointeeType(self: ?*const struct_ZigClangType) str
834pub extern fn ZigClangType_isVoidType(self: ?*const struct_ZigClangType) bool;835pub extern fn ZigClangType_isVoidType(self: ?*const struct_ZigClangType) bool;
835pub extern fn ZigClangType_isConstantArrayType(self: ?*const struct_ZigClangType) bool;836pub extern fn ZigClangType_isConstantArrayType(self: ?*const struct_ZigClangType) bool;
836pub extern fn ZigClangType_isRecordType(self: ?*const struct_ZigClangType) bool;837pub extern fn ZigClangType_isRecordType(self: ?*const struct_ZigClangType) bool;
838pub extern fn ZigClangType_isIncompleteOrZeroLengthArrayType(self: ?*const struct_ZigClangType, *const ZigClangASTContext) bool;
837pub extern fn ZigClangType_isArrayType(self: ?*const struct_ZigClangType) bool;839pub extern fn ZigClangType_isArrayType(self: ?*const struct_ZigClangType) bool;
838pub extern fn ZigClangType_isBooleanType(self: ?*const struct_ZigClangType) bool;840pub extern fn ZigClangType_isBooleanType(self: ?*const struct_ZigClangType) bool;
839pub extern fn ZigClangType_getTypeClassName(self: *const struct_ZigClangType) [*:0]const u8;841pub extern fn ZigClangType_getTypeClassName(self: *const struct_ZigClangType) [*:0]const u8;
src-self-hosted/dep_tokenizer.zig+10-12
...@@ -306,12 +306,12 @@ pub const Tokenizer = struct {...@@ -306,12 +306,12 @@ pub const Tokenizer = struct {
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.Buffer.initSize(&self.arena.allocator, 0);
309 std.fmt.format(&buffer, anyerror, std.Buffer.append, fmt, args) catch {};309 try buffer.outStream().print(fmt, args);
310 try buffer.append(" '");310 try buffer.append(" '");
311 var out = makeOutput(std.Buffer.append, &buffer);311 var out = makeOutput(std.Buffer.append, &buffer);
312 try printCharValues(&out, bytes);312 try printCharValues(&out, bytes);
313 try buffer.append("'");313 try buffer.append("'");
314 std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", .{position - (bytes.len - 1)}) catch {};314 try buffer.outStream().print(" at position {}", .{position - (bytes.len - 1)});
315 self.error_text = buffer.toSlice();315 self.error_text = buffer.toSlice();
316 return Error.InvalidInput;316 return Error.InvalidInput;
317 }317 }
...@@ -319,10 +319,9 @@ pub const Tokenizer = struct {...@@ -319,10 +319,9 @@ pub const Tokenizer = struct {
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.Buffer.initSize(&self.arena.allocator, 0);
321 try buffer.append("illegal char ");321 try buffer.append("illegal char ");
322 var out = makeOutput(std.Buffer.append, &buffer);322 try printUnderstandableChar(&buffer, char);
323 try printUnderstandableChar(&out, char);323 try buffer.outStream().print(" at position {}", .{position});
324 std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", .{position}) catch {};324 if (fmt.len != 0) try buffer.outStream().print(": " ++ fmt, args);
325 if (fmt.len != 0) std.fmt.format(&buffer, anyerror, std.Buffer.append, ": " ++ fmt, args) catch {};
326 self.error_text = buffer.toSlice();325 self.error_text = buffer.toSlice();
327 return Error.InvalidInput;326 return Error.InvalidInput;
328 }327 }
...@@ -996,14 +995,13 @@ fn printCharValues(out: var, bytes: []const u8) !void {...@@ -996,14 +995,13 @@ fn printCharValues(out: var, bytes: []const u8) !void {
996 }995 }
997}996}
998997
999fn printUnderstandableChar(out: var, char: u8) !void {998fn printUnderstandableChar(buffer: *std.Buffer, char: u8) !void {
1000 if (!std.ascii.isPrint(char) or char == ' ') {999 if (!std.ascii.isPrint(char) or char == ' ') {
1001 const output = @typeInfo(@TypeOf(out)).Pointer.child.output;1000 try buffer.outStream().print("\\x{X:2}", .{char});
1002 std.fmt.format(out.context, anyerror, output, "\\x{X:2}", .{char}) catch {};
1003 } else {1001 } else {
1004 try out.write("'");1002 try buffer.append("'");
1005 try out.write(&[_]u8{printable_char_tab[char]});1003 try buffer.appendByte(printable_char_tab[char]);
1006 try out.write("'");1004 try buffer.append("'");
1007 }1005 }
1008}1006}
10091007
src-self-hosted/libc_installation.zig+5-30
...@@ -17,7 +17,6 @@ pub const LibCInstallation = struct {...@@ -17,7 +17,6 @@ pub const LibCInstallation = struct {
17 include_dir: ?[:0]const u8 = null,17 include_dir: ?[:0]const u8 = null,
18 sys_include_dir: ?[:0]const u8 = null,18 sys_include_dir: ?[:0]const u8 = null,
19 crt_dir: ?[:0]const u8 = null,19 crt_dir: ?[:0]const u8 = null,
20 static_crt_dir: ?[:0]const u8 = null,
21 msvc_lib_dir: ?[:0]const u8 = null,20 msvc_lib_dir: ?[:0]const u8 = null,
22 kernel32_lib_dir: ?[:0]const u8 = null,21 kernel32_lib_dir: ?[:0]const u8 = null,
2322
...@@ -38,7 +37,7 @@ pub const LibCInstallation = struct {...@@ -38,7 +37,7 @@ pub const LibCInstallation = struct {
38 pub fn parse(37 pub fn parse(
39 allocator: *Allocator,38 allocator: *Allocator,
40 libc_file: []const u8,39 libc_file: []const u8,
41 stderr: *std.io.OutStream(fs.File.WriteError),40 stderr: var,
42 ) !LibCInstallation {41 ) !LibCInstallation {
43 var self: LibCInstallation = .{};42 var self: LibCInstallation = .{};
4443
...@@ -98,13 +97,6 @@ pub const LibCInstallation = struct {...@@ -98,13 +97,6 @@ pub const LibCInstallation = struct {
98 try stderr.print("crt_dir may not be empty for {}\n", .{@tagName(Target.current.os.tag)});97 try stderr.print("crt_dir may not be empty for {}\n", .{@tagName(Target.current.os.tag)});
99 return error.ParseError;98 return error.ParseError;
100 }99 }
101 if (self.static_crt_dir == null and is_windows and is_gnu) {
102 try stderr.print("static_crt_dir may not be empty for {}-{}\n", .{
103 @tagName(Target.current.os.tag),
104 @tagName(Target.current.abi),
105 });
106 return error.ParseError;
107 }
108 if (self.msvc_lib_dir == null and is_windows and !is_gnu) {100 if (self.msvc_lib_dir == null and is_windows and !is_gnu) {
109 try stderr.print("msvc_lib_dir may not be empty for {}-{}\n", .{101 try stderr.print("msvc_lib_dir may not be empty for {}-{}\n", .{
110 @tagName(Target.current.os.tag),102 @tagName(Target.current.os.tag),
...@@ -123,12 +115,11 @@ pub const LibCInstallation = struct {...@@ -123,12 +115,11 @@ pub const LibCInstallation = struct {
123 return self;115 return self;
124 }116 }
125117
126 pub fn render(self: LibCInstallation, out: *std.io.OutStream(fs.File.WriteError)) !void {118 pub fn render(self: LibCInstallation, out: var) !void {
127 @setEvalBranchQuota(4000);119 @setEvalBranchQuota(4000);
128 const include_dir = self.include_dir orelse "";120 const include_dir = self.include_dir orelse "";
129 const sys_include_dir = self.sys_include_dir orelse "";121 const sys_include_dir = self.sys_include_dir orelse "";
130 const crt_dir = self.crt_dir orelse "";122 const crt_dir = self.crt_dir orelse "";
131 const static_crt_dir = self.static_crt_dir orelse "";
132 const msvc_lib_dir = self.msvc_lib_dir orelse "";123 const msvc_lib_dir = self.msvc_lib_dir orelse "";
133 const kernel32_lib_dir = self.kernel32_lib_dir orelse "";124 const kernel32_lib_dir = self.kernel32_lib_dir orelse "";
134125
...@@ -147,11 +138,6 @@ pub const LibCInstallation = struct {...@@ -147,11 +138,6 @@ pub const LibCInstallation = struct {
147 \\# Not needed when targeting MacOS.138 \\# Not needed when targeting MacOS.
148 \\crt_dir={}139 \\crt_dir={}
149 \\140 \\
150 \\# The directory that contains `crtbegin.o`.
151 \\# On POSIX, can be found with `cc -print-file-name=crtbegin.o`.
152 \\# Only needed when targeting MinGW-w64 on Windows.
153 \\static_crt_dir={}
154 \\
155 \\# The directory that contains `vcruntime.lib`.141 \\# The directory that contains `vcruntime.lib`.
156 \\# Only needed when targeting MSVC on Windows.142 \\# Only needed when targeting MSVC on Windows.
157 \\msvc_lib_dir={}143 \\msvc_lib_dir={}
...@@ -164,7 +150,6 @@ pub const LibCInstallation = struct {...@@ -164,7 +150,6 @@ pub const LibCInstallation = struct {
164 include_dir,150 include_dir,
165 sys_include_dir,151 sys_include_dir,
166 crt_dir,152 crt_dir,
167 static_crt_dir,
168 msvc_lib_dir,153 msvc_lib_dir,
169 kernel32_lib_dir,154 kernel32_lib_dir,
170 });155 });
...@@ -186,7 +171,6 @@ pub const LibCInstallation = struct {...@@ -186,7 +171,6 @@ pub const LibCInstallation = struct {
186 var batch = Batch(FindError!void, 3, .auto_async).init();171 var batch = Batch(FindError!void, 3, .auto_async).init();
187 batch.add(&async self.findNativeIncludeDirPosix(args));172 batch.add(&async self.findNativeIncludeDirPosix(args));
188 batch.add(&async self.findNativeCrtDirPosix(args));173 batch.add(&async self.findNativeCrtDirPosix(args));
189 batch.add(&async self.findNativeStaticCrtDirPosix(args));
190 try batch.wait();174 try batch.wait();
191 } else {175 } else {
192 var sdk: *ZigWindowsSDK = undefined;176 var sdk: *ZigWindowsSDK = undefined;
...@@ -348,7 +332,7 @@ pub const LibCInstallation = struct {...@@ -348,7 +332,7 @@ pub const LibCInstallation = struct {
348332
349 for (searches) |search| {333 for (searches) |search| {
350 result_buf.shrink(0);334 result_buf.shrink(0);
351 const stream = &std.io.BufferOutStream.init(&result_buf).stream;335 const stream = result_buf.outStream();
352 try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version });336 try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version });
353337
354 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {338 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {
...@@ -395,7 +379,7 @@ pub const LibCInstallation = struct {...@@ -395,7 +379,7 @@ pub const LibCInstallation = struct {
395379
396 for (searches) |search| {380 for (searches) |search| {
397 result_buf.shrink(0);381 result_buf.shrink(0);
398 const stream = &std.io.BufferOutStream.init(&result_buf).stream;382 const stream = result_buf.outStream();
399 try stream.print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir });383 try stream.print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir });
400384
401 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {385 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {
...@@ -428,15 +412,6 @@ pub const LibCInstallation = struct {...@@ -428,15 +412,6 @@ pub const LibCInstallation = struct {
428 });412 });
429 }413 }
430414
431 fn findNativeStaticCrtDirPosix(self: *LibCInstallation, args: FindNativeOptions) FindError!void {
432 self.static_crt_dir = try ccPrintFileName(.{
433 .allocator = args.allocator,
434 .search_basename = "crtbegin.o",
435 .want_dirname = .only_dir,
436 .verbose = args.verbose,
437 });
438 }
439
440 fn findNativeKernel32LibDir(415 fn findNativeKernel32LibDir(
441 self: *LibCInstallation,416 self: *LibCInstallation,
442 args: FindNativeOptions,417 args: FindNativeOptions,
...@@ -459,7 +434,7 @@ pub const LibCInstallation = struct {...@@ -459,7 +434,7 @@ pub const LibCInstallation = struct {
459434
460 for (searches) |search| {435 for (searches) |search| {
461 result_buf.shrink(0);436 result_buf.shrink(0);
462 const stream = &std.io.BufferOutStream.init(&result_buf).stream;437 const stream = result_buf.outStream();
463 try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir });438 try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir });
464439
465 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {440 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {
src-self-hosted/print_targets.zig+7-6
...@@ -52,7 +52,7 @@ const available_libcs = [_][]const u8{...@@ -52,7 +52,7 @@ const available_libcs = [_][]const u8{
52 "sparc-linux-gnu",52 "sparc-linux-gnu",
53 "sparcv9-linux-gnu",53 "sparcv9-linux-gnu",
54 "wasm32-freestanding-musl",54 "wasm32-freestanding-musl",
55 "x86_64-linux-gnu (native)",55 "x86_64-linux-gnu",
56 "x86_64-linux-gnux32",56 "x86_64-linux-gnux32",
57 "x86_64-linux-musl",57 "x86_64-linux-musl",
58 "x86_64-windows-gnu",58 "x86_64-windows-gnu",
...@@ -61,7 +61,8 @@ const available_libcs = [_][]const u8{...@@ -61,7 +61,8 @@ const available_libcs = [_][]const u8{
61pub fn cmdTargets(61pub fn cmdTargets(
62 allocator: *Allocator,62 allocator: *Allocator,
63 args: []const []const u8,63 args: []const []const u8,
64 stdout: *io.OutStream(fs.File.WriteError),64 /// Output stream
65 stdout: var,
65 native_target: Target,66 native_target: Target,
66) !void {67) !void {
67 const available_glibcs = blk: {68 const available_glibcs = blk: {
...@@ -92,9 +93,9 @@ pub fn cmdTargets(...@@ -92,9 +93,9 @@ pub fn cmdTargets(
92 };93 };
93 defer allocator.free(available_glibcs);94 defer allocator.free(available_glibcs);
9495
95 const BOS = io.BufferedOutStream(fs.File.WriteError);96 var bos = io.bufferedOutStream(stdout);
96 var bos = BOS.init(stdout);97 const bos_stream = bos.outStream();
97 var jws = std.json.WriteStream(BOS.Stream, 6).init(&bos.stream);98 var jws = std.json.WriteStream(@TypeOf(bos_stream), 6).init(bos_stream);
9899
99 try jws.beginObject();100 try jws.beginObject();
100101
...@@ -219,6 +220,6 @@ pub fn cmdTargets(...@@ -219,6 +220,6 @@ pub fn cmdTargets(
219220
220 try jws.endObject();221 try jws.endObject();
221222
222 try bos.stream.writeByte('\n');223 try bos_stream.writeByte('\n');
223 return bos.flush();224 return bos.flush();
224}225}
src-self-hosted/stage2.zig+80-90
...@@ -18,8 +18,8 @@ const assert = std.debug.assert;...@@ -18,8 +18,8 @@ const assert = std.debug.assert;
18const LibCInstallation = @import("libc_installation.zig").LibCInstallation;18const LibCInstallation = @import("libc_installation.zig").LibCInstallation;
1919
20var stderr_file: fs.File = undefined;20var stderr_file: fs.File = undefined;
21var stderr: *io.OutStream(fs.File.WriteError) = undefined;21var stderr: fs.File.OutStream = undefined;
22var stdout: *io.OutStream(fs.File.WriteError) = undefined;22var stdout: fs.File.OutStream = undefined;
2323
24comptime {24comptime {
25 _ = @import("dep_tokenizer.zig");25 _ = @import("dep_tokenizer.zig");
...@@ -146,7 +146,7 @@ export fn stage2_free_clang_errors(errors_ptr: [*]translate_c.ClangErrMsg, error...@@ -146,7 +146,7 @@ export fn stage2_free_clang_errors(errors_ptr: [*]translate_c.ClangErrMsg, error
146}146}
147147
148export fn stage2_render_ast(tree: *ast.Tree, output_file: *FILE) Error {148export fn stage2_render_ast(tree: *ast.Tree, output_file: *FILE) Error {
149 const c_out_stream = &std.io.COutStream.init(output_file).stream;149 const c_out_stream = std.io.cOutStream(output_file);
150 _ = std.zig.render(std.heap.c_allocator, c_out_stream, tree) catch |e| switch (e) {150 _ = std.zig.render(std.heap.c_allocator, c_out_stream, tree) catch |e| switch (e) {
151 error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode151 error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode
152 error.SystemResources => return .SystemResources,152 error.SystemResources => return .SystemResources,
...@@ -186,9 +186,9 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {...@@ -186,9 +186,9 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
186 try args_list.append(mem.toSliceConst(u8, argv[arg_i]));186 try args_list.append(mem.toSliceConst(u8, argv[arg_i]));
187 }187 }
188188
189 stdout = &std.io.getStdOut().outStream().stream;189 stdout = std.io.getStdOut().outStream();
190 stderr_file = std.io.getStdErr();190 stderr_file = std.io.getStdErr();
191 stderr = &stderr_file.outStream().stream;191 stderr = stderr_file.outStream();
192192
193 const args = args_list.toSliceConst()[2..];193 const args = args_list.toSliceConst()[2..];
194194
...@@ -203,11 +203,11 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {...@@ -203,11 +203,11 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
203 const arg = args[i];203 const arg = args[i];
204 if (mem.startsWith(u8, arg, "-")) {204 if (mem.startsWith(u8, arg, "-")) {
205 if (mem.eql(u8, arg, "--help")) {205 if (mem.eql(u8, arg, "--help")) {
206 try stdout.write(self_hosted_main.usage_fmt);206 try stdout.writeAll(self_hosted_main.usage_fmt);
207 process.exit(0);207 process.exit(0);
208 } else if (mem.eql(u8, arg, "--color")) {208 } else if (mem.eql(u8, arg, "--color")) {
209 if (i + 1 >= args.len) {209 if (i + 1 >= args.len) {
210 try stderr.write("expected [auto|on|off] after --color\n");210 try stderr.writeAll("expected [auto|on|off] after --color\n");
211 process.exit(1);211 process.exit(1);
212 }212 }
213 i += 1;213 i += 1;
...@@ -238,14 +238,14 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {...@@ -238,14 +238,14 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
238238
239 if (stdin_flag) {239 if (stdin_flag) {
240 if (input_files.len != 0) {240 if (input_files.len != 0) {
241 try stderr.write("cannot use --stdin with positional arguments\n");241 try stderr.writeAll("cannot use --stdin with positional arguments\n");
242 process.exit(1);242 process.exit(1);
243 }243 }
244244
245 const stdin_file = io.getStdIn();245 const stdin_file = io.getStdIn();
246 var stdin = stdin_file.inStream();246 var stdin = stdin_file.inStream();
247247
248 const source_code = try stdin.stream.readAllAlloc(allocator, self_hosted_main.max_src_size);248 const source_code = try stdin.readAllAlloc(allocator, self_hosted_main.max_src_size);
249 defer allocator.free(source_code);249 defer allocator.free(source_code);
250250
251 const tree = std.zig.parse(allocator, source_code) catch |err| {251 const tree = std.zig.parse(allocator, source_code) catch |err| {
...@@ -272,7 +272,7 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {...@@ -272,7 +272,7 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
272 }272 }
273273
274 if (input_files.len == 0) {274 if (input_files.len == 0) {
275 try stderr.write("expected at least one source file argument\n");275 try stderr.writeAll("expected at least one source file argument\n");
276 process.exit(1);276 process.exit(1);
277 }277 }
278278
...@@ -409,11 +409,11 @@ fn printErrMsgToFile(...@@ -409,11 +409,11 @@ fn printErrMsgToFile(
409 const end_loc = tree.tokenLocationPtr(first_token.end, last_token);409 const end_loc = tree.tokenLocationPtr(first_token.end, last_token);
410410
411 var text_buf = try std.Buffer.initSize(allocator, 0);411 var text_buf = try std.Buffer.initSize(allocator, 0);
412 var out_stream = &std.io.BufferOutStream.init(&text_buf).stream;412 const out_stream = &text_buf.outStream();
413 try parse_error.render(&tree.tokens, out_stream);413 try parse_error.render(&tree.tokens, out_stream);
414 const text = text_buf.toOwnedSlice();414 const text = text_buf.toOwnedSlice();
415415
416 const stream = &file.outStream().stream;416 const stream = &file.outStream();
417 try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text });417 try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text });
418418
419 if (!color_on) return;419 if (!color_on) return;
...@@ -626,22 +626,30 @@ fn detectNativeCpuWithLLVM(...@@ -626,22 +626,30 @@ fn detectNativeCpuWithLLVM(
626}626}
627627
628// ABI warning628// ABI warning
629export fn stage2_cmd_targets(zig_triple: [*:0]const u8) c_int {629export fn stage2_cmd_targets(
630 cmdTargets(zig_triple) catch |err| {630 zig_triple: ?[*:0]const u8,
631 mcpu: ?[*:0]const u8,
632 dynamic_linker: ?[*:0]const u8,
633) c_int {
634 cmdTargets(zig_triple, mcpu, dynamic_linker) catch |err| {
631 std.debug.warn("unable to list targets: {}\n", .{@errorName(err)});635 std.debug.warn("unable to list targets: {}\n", .{@errorName(err)});
632 return -1;636 return -1;
633 };637 };
634 return 0;638 return 0;
635}639}
636640
637fn cmdTargets(zig_triple: [*:0]const u8) !void {641fn cmdTargets(
638 var cross_target = try CrossTarget.parse(.{ .arch_os_abi = mem.toSliceConst(u8, zig_triple) });642 zig_triple_oz: ?[*:0]const u8,
643 mcpu_oz: ?[*:0]const u8,
644 dynamic_linker_oz: ?[*:0]const u8,
645) !void {
646 const cross_target = try stage2CrossTarget(zig_triple_oz, mcpu_oz, dynamic_linker_oz);
639 var dynamic_linker: ?[*:0]u8 = null;647 var dynamic_linker: ?[*:0]u8 = null;
640 const target = try crossTargetToTarget(cross_target, &dynamic_linker);648 const target = try crossTargetToTarget(cross_target, &dynamic_linker);
641 return @import("print_targets.zig").cmdTargets(649 return @import("print_targets.zig").cmdTargets(
642 std.heap.c_allocator,650 std.heap.c_allocator,
643 &[0][]u8{},651 &[0][]u8{},
644 &std.io.getStdOut().outStream().stream,652 std.io.getStdOut().outStream(),
645 target,653 target,
646 );654 );
647}655}
...@@ -673,51 +681,58 @@ export fn stage2_target_parse(...@@ -673,51 +681,58 @@ export fn stage2_target_parse(
673 return .None;681 return .None;
674}682}
675683
684fn stage2CrossTarget(
685 zig_triple_oz: ?[*:0]const u8,
686 mcpu_oz: ?[*:0]const u8,
687 dynamic_linker_oz: ?[*:0]const u8,
688) !CrossTarget {
689 const zig_triple = if (zig_triple_oz) |zig_triple_z| mem.toSliceConst(u8, zig_triple_z) else "native";
690 const mcpu = if (mcpu_oz) |mcpu_z| mem.toSliceConst(u8, mcpu_z) else null;
691 const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.toSliceConst(u8, dl_z) else null;
692 var diags: CrossTarget.ParseOptions.Diagnostics = .{};
693 const target: CrossTarget = CrossTarget.parse(.{
694 .arch_os_abi = zig_triple,
695 .cpu_features = mcpu,
696 .dynamic_linker = dynamic_linker,
697 .diagnostics = &diags,
698 }) catch |err| switch (err) {
699 error.UnknownCpuModel => {
700 std.debug.warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{
701 diags.cpu_name.?,
702 @tagName(diags.arch.?),
703 });
704 for (diags.arch.?.allCpuModels()) |cpu| {
705 std.debug.warn(" {}\n", .{cpu.name});
706 }
707 process.exit(1);
708 },
709 error.UnknownCpuFeature => {
710 std.debug.warn(
711 \\Unknown CPU feature: '{}'
712 \\Available CPU features for architecture '{}':
713 \\
714 , .{
715 diags.unknown_feature_name,
716 @tagName(diags.arch.?),
717 });
718 for (diags.arch.?.allFeaturesList()) |feature| {
719 std.debug.warn(" {}: {}\n", .{ feature.name, feature.description });
720 }
721 process.exit(1);
722 },
723 else => |e| return e,
724 };
725
726 return target;
727}
728
676fn stage2TargetParse(729fn stage2TargetParse(
677 stage1_target: *Stage2Target,730 stage1_target: *Stage2Target,
678 zig_triple_oz: ?[*:0]const u8,731 zig_triple_oz: ?[*:0]const u8,
679 mcpu_oz: ?[*:0]const u8,732 mcpu_oz: ?[*:0]const u8,
680 dynamic_linker_oz: ?[*:0]const u8,733 dynamic_linker_oz: ?[*:0]const u8,
681) !void {734) !void {
682 const target: CrossTarget = if (zig_triple_oz) |zig_triple_z| blk: {735 const target = try stage2CrossTarget(zig_triple_oz, mcpu_oz, dynamic_linker_oz);
683 const zig_triple = mem.toSliceConst(u8, zig_triple_z);
684 const mcpu = if (mcpu_oz) |mcpu_z| mem.toSliceConst(u8, mcpu_z) else null;
685 const dynamic_linker = if (dynamic_linker_oz) |dl_z| mem.toSliceConst(u8, dl_z) else null;
686 var diags: CrossTarget.ParseOptions.Diagnostics = .{};
687 break :blk CrossTarget.parse(.{
688 .arch_os_abi = zig_triple,
689 .cpu_features = mcpu,
690 .dynamic_linker = dynamic_linker,
691 .diagnostics = &diags,
692 }) catch |err| switch (err) {
693 error.UnknownCpuModel => {
694 std.debug.warn("Unknown CPU: '{}'\nAvailable CPUs for architecture '{}':\n", .{
695 diags.cpu_name.?,
696 @tagName(diags.arch.?),
697 });
698 for (diags.arch.?.allCpuModels()) |cpu| {
699 std.debug.warn(" {}\n", .{cpu.name});
700 }
701 process.exit(1);
702 },
703 error.UnknownCpuFeature => {
704 std.debug.warn(
705 \\Unknown CPU feature: '{}'
706 \\Available CPU features for architecture '{}':
707 \\
708 , .{
709 diags.unknown_feature_name,
710 @tagName(diags.arch.?),
711 });
712 for (diags.arch.?.allFeaturesList()) |feature| {
713 std.debug.warn(" {}: {}\n", .{ feature.name, feature.description });
714 }
715 process.exit(1);
716 },
717 else => |e| return e,
718 };
719 } else .{};
720
721 try stage1_target.fromTarget(target);736 try stage1_target.fromTarget(target);
722}737}
723738
...@@ -729,8 +744,6 @@ const Stage2LibCInstallation = extern struct {...@@ -729,8 +744,6 @@ const Stage2LibCInstallation = extern struct {
729 sys_include_dir_len: usize,744 sys_include_dir_len: usize,
730 crt_dir: [*:0]const u8,745 crt_dir: [*:0]const u8,
731 crt_dir_len: usize,746 crt_dir_len: usize,
732 static_crt_dir: [*:0]const u8,
733 static_crt_dir_len: usize,
734 msvc_lib_dir: [*:0]const u8,747 msvc_lib_dir: [*:0]const u8,
735 msvc_lib_dir_len: usize,748 msvc_lib_dir_len: usize,
736 kernel32_lib_dir: [*:0]const u8,749 kernel32_lib_dir: [*:0]const u8,
...@@ -758,13 +771,6 @@ const Stage2LibCInstallation = extern struct {...@@ -758,13 +771,6 @@ const Stage2LibCInstallation = extern struct {
758 self.crt_dir = "";771 self.crt_dir = "";
759 self.crt_dir_len = 0;772 self.crt_dir_len = 0;
760 }773 }
761 if (libc.static_crt_dir) |s| {
762 self.static_crt_dir = s.ptr;
763 self.static_crt_dir_len = s.len;
764 } else {
765 self.static_crt_dir = "";
766 self.static_crt_dir_len = 0;
767 }
768 if (libc.msvc_lib_dir) |s| {774 if (libc.msvc_lib_dir) |s| {
769 self.msvc_lib_dir = s.ptr;775 self.msvc_lib_dir = s.ptr;
770 self.msvc_lib_dir_len = s.len;776 self.msvc_lib_dir_len = s.len;
...@@ -792,9 +798,6 @@ const Stage2LibCInstallation = extern struct {...@@ -792,9 +798,6 @@ const Stage2LibCInstallation = extern struct {
792 if (self.crt_dir_len != 0) {798 if (self.crt_dir_len != 0) {
793 libc.crt_dir = self.crt_dir[0..self.crt_dir_len :0];799 libc.crt_dir = self.crt_dir[0..self.crt_dir_len :0];
794 }800 }
795 if (self.static_crt_dir_len != 0) {
796 libc.static_crt_dir = self.static_crt_dir[0..self.static_crt_dir_len :0];
797 }
798 if (self.msvc_lib_dir_len != 0) {801 if (self.msvc_lib_dir_len != 0) {
799 libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len :0];802 libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len :0];
800 }803 }
...@@ -808,7 +811,7 @@ const Stage2LibCInstallation = extern struct {...@@ -808,7 +811,7 @@ const Stage2LibCInstallation = extern struct {
808// ABI warning811// ABI warning
809export fn stage2_libc_parse(stage1_libc: *Stage2LibCInstallation, libc_file_z: [*:0]const u8) Error {812export fn stage2_libc_parse(stage1_libc: *Stage2LibCInstallation, libc_file_z: [*:0]const u8) Error {
810 stderr_file = std.io.getStdErr();813 stderr_file = std.io.getStdErr();
811 stderr = &stderr_file.outStream().stream;814 stderr = stderr_file.outStream();
812 const libc_file = mem.toSliceConst(u8, libc_file_z);815 const libc_file = mem.toSliceConst(u8, libc_file_z);
813 var libc = LibCInstallation.parse(std.heap.c_allocator, libc_file, stderr) catch |err| switch (err) {816 var libc = LibCInstallation.parse(std.heap.c_allocator, libc_file, stderr) catch |err| switch (err) {
814 error.ParseError => return .SemanticAnalyzeFail,817 error.ParseError => return .SemanticAnalyzeFail,
...@@ -870,7 +873,7 @@ export fn stage2_libc_find_native(stage1_libc: *Stage2LibCInstallation) Error {...@@ -870,7 +873,7 @@ export fn stage2_libc_find_native(stage1_libc: *Stage2LibCInstallation) Error {
870// ABI warning873// ABI warning
871export fn stage2_libc_render(stage1_libc: *Stage2LibCInstallation, output_file: *FILE) Error {874export fn stage2_libc_render(stage1_libc: *Stage2LibCInstallation, output_file: *FILE) Error {
872 var libc = stage1_libc.toStage2();875 var libc = stage1_libc.toStage2();
873 const c_out_stream = &std.io.COutStream.init(output_file).stream;876 const c_out_stream = std.io.cOutStream(output_file);
874 libc.render(c_out_stream) catch |err| switch (err) {877 libc.render(c_out_stream) catch |err| switch (err) {
875 error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode878 error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode
876 error.SystemResources => return .SystemResources,879 error.SystemResources => return .SystemResources,
...@@ -902,26 +905,11 @@ const Stage2Target = extern struct {...@@ -902,26 +905,11 @@ const Stage2Target = extern struct {
902 llvm_cpu_features: ?[*:0]const u8,905 llvm_cpu_features: ?[*:0]const u8,
903 cpu_builtin_str: ?[*:0]const u8,906 cpu_builtin_str: ?[*:0]const u8,
904 cache_hash: ?[*:0]const u8,907 cache_hash: ?[*:0]const u8,
908 cache_hash_len: usize,
905 os_builtin_str: ?[*:0]const u8,909 os_builtin_str: ?[*:0]const u8,
906910
907 dynamic_linker: ?[*:0]const u8,911 dynamic_linker: ?[*:0]const u8,
908912
909 fn toTarget(in_target: Stage2Target) CrossTarget {
910 if (in_target.is_native) return .{};
911
912 const in_arch = in_target.arch - 1; // skip over ZigLLVM_UnknownArch
913 const in_os = in_target.os;
914 const in_abi = in_target.abi;
915
916 return .{
917 .Cross = .{
918 .cpu = Target.Cpu.baseline(enumInt(Target.Cpu.Arch, in_arch)),
919 .os = Target.Os.defaultVersionRange(enumInt(Target.Os.Tag, in_os)),
920 .abi = enumInt(Target.Abi, in_abi),
921 },
922 };
923 }
924
925 fn fromTarget(self: *Stage2Target, cross_target: CrossTarget) !void {913 fn fromTarget(self: *Stage2Target, cross_target: CrossTarget) !void {
926 const allocator = std.heap.c_allocator;914 const allocator = std.heap.c_allocator;
927915
...@@ -1031,7 +1019,7 @@ const Stage2Target = extern struct {...@@ -1031,7 +1019,7 @@ const Stage2Target = extern struct {
1031 .macosx,1019 .macosx,
1032 .netbsd,1020 .netbsd,
1033 .openbsd,1021 .openbsd,
1034 => try os_builtin_str_buffer.print(1022 => try os_builtin_str_buffer.outStream().print(
1035 \\ .semver = .{{1023 \\ .semver = .{{
1036 \\ .min = .{{1024 \\ .min = .{{
1037 \\ .major = {},1025 \\ .major = {},
...@@ -1055,7 +1043,7 @@ const Stage2Target = extern struct {...@@ -1055,7 +1043,7 @@ const Stage2Target = extern struct {
1055 target.os.version_range.semver.max.patch,1043 target.os.version_range.semver.max.patch,
1056 }),1044 }),
10571045
1058 .linux => try os_builtin_str_buffer.print(1046 .linux => try os_builtin_str_buffer.outStream().print(
1059 \\ .linux = .{{1047 \\ .linux = .{{
1060 \\ .range = .{{1048 \\ .range = .{{
1061 \\ .min = .{{1049 \\ .min = .{{
...@@ -1090,7 +1078,7 @@ const Stage2Target = extern struct {...@@ -1090,7 +1078,7 @@ const Stage2Target = extern struct {
1090 target.os.version_range.linux.glibc.patch,1078 target.os.version_range.linux.glibc.patch,
1091 }),1079 }),
10921080
1093 .windows => try os_builtin_str_buffer.print(1081 .windows => try os_builtin_str_buffer.outStream().print(
1094 \\ .windows = .{{1082 \\ .windows = .{{
1095 \\ .min = .{},1083 \\ .min = .{},
1096 \\ .max = .{},1084 \\ .max = .{},
...@@ -1131,6 +1119,7 @@ const Stage2Target = extern struct {...@@ -1131,6 +1119,7 @@ const Stage2Target = extern struct {
1131 }1119 }
1132 };1120 };
11331121
1122 const cache_hash_slice = cache_hash.toOwnedSlice();
1134 self.* = .{1123 self.* = .{
1135 .arch = @enumToInt(target.cpu.arch) + 1, // skip over ZigLLVM_UnknownArch1124 .arch = @enumToInt(target.cpu.arch) + 1, // skip over ZigLLVM_UnknownArch
1136 .vendor = 0,1125 .vendor = 0,
...@@ -1140,7 +1129,8 @@ const Stage2Target = extern struct {...@@ -1140,7 +1129,8 @@ const Stage2Target = extern struct {
1140 .llvm_cpu_features = llvm_features_buffer.toOwnedSlice().ptr,1129 .llvm_cpu_features = llvm_features_buffer.toOwnedSlice().ptr,
1141 .cpu_builtin_str = cpu_builtin_str_buffer.toOwnedSlice().ptr,1130 .cpu_builtin_str = cpu_builtin_str_buffer.toOwnedSlice().ptr,
1142 .os_builtin_str = os_builtin_str_buffer.toOwnedSlice().ptr,1131 .os_builtin_str = os_builtin_str_buffer.toOwnedSlice().ptr,
1143 .cache_hash = cache_hash.toOwnedSlice().ptr,1132 .cache_hash = cache_hash_slice.ptr,
1133 .cache_hash_len = cache_hash_slice.len,
1144 .is_native = cross_target.isNative(),1134 .is_native = cross_target.isNative(),
1145 .glibc_or_darwin_version = glibc_or_darwin_version,1135 .glibc_or_darwin_version = glibc_or_darwin_version,
1146 .dynamic_linker = dynamic_linker,1136 .dynamic_linker = dynamic_linker,
src-self-hosted/translate_c.zig+120-53
...@@ -560,7 +560,7 @@ fn visitVarDecl(c: *Context, var_decl: *const ZigClangVarDecl) Error!void {...@@ -560,7 +560,7 @@ fn visitVarDecl(c: *Context, var_decl: *const ZigClangVarDecl) Error!void {
560560
561 // TODO https://github.com/ziglang/zig/issues/3756561 // TODO https://github.com/ziglang/zig/issues/3756
562 // TODO https://github.com/ziglang/zig/issues/1802562 // TODO https://github.com/ziglang/zig/issues/1802
563 const checked_name = if (isZigPrimitiveType(var_name)) try std.fmt.allocPrint(c.a(), "_{}", .{var_name}) else var_name;563 const checked_name = if (isZigPrimitiveType(var_name)) try std.fmt.allocPrint(c.a(), "{}_{}", .{ var_name, c.getMangle() }) else var_name;
564 const var_decl_loc = ZigClangVarDecl_getLocation(var_decl);564 const var_decl_loc = ZigClangVarDecl_getLocation(var_decl);
565565
566 const qual_type = ZigClangVarDecl_getTypeSourceInfo_getType(var_decl);566 const qual_type = ZigClangVarDecl_getTypeSourceInfo_getType(var_decl);
...@@ -632,7 +632,7 @@ fn visitVarDecl(c: *Context, var_decl: *const ZigClangVarDecl) Error!void {...@@ -632,7 +632,7 @@ fn visitVarDecl(c: *Context, var_decl: *const ZigClangVarDecl) Error!void {
632 const align_expr = blk: {632 const align_expr = blk: {
633 const alignment = ZigClangVarDecl_getAlignedAttribute(var_decl, rp.c.clang_context);633 const alignment = ZigClangVarDecl_getAlignedAttribute(var_decl, rp.c.clang_context);
634 if (alignment != 0) {634 if (alignment != 0) {
635 _ = try appendToken(rp.c, .Keyword_linksection, "align");635 _ = try appendToken(rp.c, .Keyword_align, "align");
636 _ = try appendToken(rp.c, .LParen, "(");636 _ = try appendToken(rp.c, .LParen, "(");
637 // Clang reports the alignment in bits637 // Clang reports the alignment in bits
638 const expr = try transCreateNodeInt(rp.c, alignment / 8);638 const expr = try transCreateNodeInt(rp.c, alignment / 8);
...@@ -677,7 +677,7 @@ fn transTypeDef(c: *Context, typedef_decl: *const ZigClangTypedefNameDecl, top_l...@@ -677,7 +677,7 @@ fn transTypeDef(c: *Context, typedef_decl: *const ZigClangTypedefNameDecl, top_l
677677
678 // TODO https://github.com/ziglang/zig/issues/3756678 // TODO https://github.com/ziglang/zig/issues/3756
679 // TODO https://github.com/ziglang/zig/issues/1802679 // TODO https://github.com/ziglang/zig/issues/1802
680 const checked_name = if (isZigPrimitiveType(typedef_name)) try std.fmt.allocPrint(c.a(), "_{}", .{typedef_name}) else typedef_name;680 const checked_name = if (isZigPrimitiveType(typedef_name)) try std.fmt.allocPrint(c.a(), "{}_{}", .{ typedef_name, c.getMangle() }) else typedef_name;
681681
682 if (mem.eql(u8, checked_name, "uint8_t"))682 if (mem.eql(u8, checked_name, "uint8_t"))
683 return transTypeDefAsBuiltin(c, typedef_decl, "u8")683 return transTypeDefAsBuiltin(c, typedef_decl, "u8")
...@@ -793,6 +793,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*...@@ -793,6 +793,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
793 while (ZigClangRecordDecl_field_iterator_neq(it, end_it)) : (it = ZigClangRecordDecl_field_iterator_next(it)) {793 while (ZigClangRecordDecl_field_iterator_neq(it, end_it)) : (it = ZigClangRecordDecl_field_iterator_next(it)) {
794 const field_decl = ZigClangRecordDecl_field_iterator_deref(it);794 const field_decl = ZigClangRecordDecl_field_iterator_deref(it);
795 const field_loc = ZigClangFieldDecl_getLocation(field_decl);795 const field_loc = ZigClangFieldDecl_getLocation(field_decl);
796 const field_qt = ZigClangFieldDecl_getType(field_decl);
796797
797 if (ZigClangFieldDecl_isBitField(field_decl)) {798 if (ZigClangFieldDecl_isBitField(field_decl)) {
798 const opaque = try transCreateNodeOpaqueType(c);799 const opaque = try transCreateNodeOpaqueType(c);
...@@ -801,6 +802,13 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*...@@ -801,6 +802,13 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
801 break :blk opaque;802 break :blk opaque;
802 }803 }
803804
805 if (ZigClangType_isIncompleteOrZeroLengthArrayType(qualTypeCanon(field_qt), c.clang_context)) {
806 const opaque = try transCreateNodeOpaqueType(c);
807 semicolon = try appendToken(c, .Semicolon, ";");
808 try emitWarning(c, field_loc, "{} demoted to opaque type - has variable length array", .{container_kind_name});
809 break :blk opaque;
810 }
811
804 var is_anon = false;812 var is_anon = false;
805 var raw_name = try c.str(ZigClangNamedDecl_getName_bytes_begin(@ptrCast(*const ZigClangNamedDecl, field_decl)));813 var raw_name = try c.str(ZigClangNamedDecl_getName_bytes_begin(@ptrCast(*const ZigClangNamedDecl, field_decl)));
806 if (ZigClangFieldDecl_isAnonymousStructOrUnion(field_decl)) {814 if (ZigClangFieldDecl_isAnonymousStructOrUnion(field_decl)) {
...@@ -809,7 +817,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*...@@ -809,7 +817,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
809 }817 }
810 const field_name = try appendIdentifier(c, raw_name);818 const field_name = try appendIdentifier(c, raw_name);
811 _ = try appendToken(c, .Colon, ":");819 _ = try appendToken(c, .Colon, ":");
812 const field_type = transQualType(rp, ZigClangFieldDecl_getType(field_decl), field_loc) catch |err| switch (err) {820 const field_type = transQualType(rp, field_qt, field_loc) catch |err| switch (err) {
813 error.UnsupportedType => {821 error.UnsupportedType => {
814 const opaque = try transCreateNodeOpaqueType(c);822 const opaque = try transCreateNodeOpaqueType(c);
815 semicolon = try appendToken(c, .Semicolon, ";");823 semicolon = try appendToken(c, .Semicolon, ";");
...@@ -819,6 +827,20 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*...@@ -819,6 +827,20 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
819 else => |e| return e,827 else => |e| return e,
820 };828 };
821829
830 const align_expr = blk: {
831 const alignment = ZigClangFieldDecl_getAlignedAttribute(field_decl, rp.c.clang_context);
832 if (alignment != 0) {
833 _ = try appendToken(rp.c, .Keyword_align, "align");
834 _ = try appendToken(rp.c, .LParen, "(");
835 // Clang reports the alignment in bits
836 const expr = try transCreateNodeInt(rp.c, alignment / 8);
837 _ = try appendToken(rp.c, .RParen, ")");
838
839 break :blk expr;
840 }
841 break :blk null;
842 };
843
822 const field_node = try c.a().create(ast.Node.ContainerField);844 const field_node = try c.a().create(ast.Node.ContainerField);
823 field_node.* = .{845 field_node.* = .{
824 .doc_comments = null,846 .doc_comments = null,
...@@ -826,7 +848,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*...@@ -826,7 +848,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
826 .name_token = field_name,848 .name_token = field_name,
827 .type_expr = field_type,849 .type_expr = field_type,
828 .value_expr = null,850 .value_expr = null,
829 .align_expr = null,851 .align_expr = align_expr,
830 };852 };
831853
832 if (is_anon) {854 if (is_anon) {
...@@ -4599,7 +4621,7 @@ fn finishTransFnProto(...@@ -4599,7 +4621,7 @@ fn finishTransFnProto(
4599 if (fn_decl) |decl| {4621 if (fn_decl) |decl| {
4600 const alignment = ZigClangFunctionDecl_getAlignedAttribute(decl, rp.c.clang_context);4622 const alignment = ZigClangFunctionDecl_getAlignedAttribute(decl, rp.c.clang_context);
4601 if (alignment != 0) {4623 if (alignment != 0) {
4602 _ = try appendToken(rp.c, .Keyword_linksection, "align");4624 _ = try appendToken(rp.c, .Keyword_align, "align");
4603 _ = try appendToken(rp.c, .LParen, "(");4625 _ = try appendToken(rp.c, .LParen, "(");
4604 // Clang reports the alignment in bits4626 // Clang reports the alignment in bits
4605 const expr = try transCreateNodeInt(rp.c, alignment / 8);4627 const expr = try transCreateNodeInt(rp.c, alignment / 8);
...@@ -4731,15 +4753,10 @@ fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenInd...@@ -4731,15 +4753,10 @@ fn appendToken(c: *Context, token_id: Token.Id, bytes: []const u8) !ast.TokenInd
47314753
4732fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex {4754fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex {
4733 assert(token_id != .Invalid);4755 assert(token_id != .Invalid);
4734 const S = struct {
4735 fn callback(context: *Context, bytes: []const u8) error{OutOfMemory}!void {
4736 return context.source_buffer.append(bytes);
4737 }
4738 };
4739 const start_index = c.source_buffer.len();4756 const start_index = c.source_buffer.len();
4740 errdefer c.source_buffer.shrink(start_index);4757 errdefer c.source_buffer.shrink(start_index);
47414758
4742 try std.fmt.format(c, error{OutOfMemory}, S.callback, format, args);4759 try c.source_buffer.outStream().print(format, args);
4743 const end_index = c.source_buffer.len();4760 const end_index = c.source_buffer.len();
4744 const token_index = c.tree.tokens.len;4761 const token_index = c.tree.tokens.len;
4745 const new_token = try c.tree.tokens.addOne();4762 const new_token = try c.tree.tokens.addOne();
...@@ -4850,7 +4867,7 @@ fn transPreprocessorEntities(c: *Context, unit: *ZigClangASTUnit) Error!void {...@@ -4850,7 +4867,7 @@ fn transPreprocessorEntities(c: *Context, unit: *ZigClangASTUnit) Error!void {
4850 const name = try c.str(raw_name);4867 const name = try c.str(raw_name);
4851 // TODO https://github.com/ziglang/zig/issues/37564868 // TODO https://github.com/ziglang/zig/issues/3756
4852 // TODO https://github.com/ziglang/zig/issues/18024869 // TODO https://github.com/ziglang/zig/issues/1802
4853 const mangled_name = if (isZigPrimitiveType(name)) try std.fmt.allocPrint(c.a(), "_{}", .{name}) else name;4870 const mangled_name = if (isZigPrimitiveType(name)) try std.fmt.allocPrint(c.a(), "{}_{}", .{ name, c.getMangle() }) else name;
4854 if (scope.containsNow(mangled_name)) {4871 if (scope.containsNow(mangled_name)) {
4855 continue;4872 continue;
4856 }4873 }
...@@ -5354,7 +5371,7 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5354,7 +5371,7 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5354 const first_tok = it.list.at(0);5371 const first_tok = it.list.at(0);
5355 const token = try appendToken(c, .CharLiteral, try zigifyEscapeSequences(c, source[tok.start..tok.end], source[first_tok.start..first_tok.end], source_loc));5372 const token = try appendToken(c, .CharLiteral, try zigifyEscapeSequences(c, source[tok.start..tok.end], source[first_tok.start..first_tok.end], source_loc));
5356 const node = try c.a().create(ast.Node.CharLiteral);5373 const node = try c.a().create(ast.Node.CharLiteral);
5357 node.* = ast.Node.CharLiteral{5374 node.* = .{
5358 .token = token,5375 .token = token,
5359 };5376 };
5360 return &node.base;5377 return &node.base;
...@@ -5363,7 +5380,7 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5363,7 +5380,7 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5363 const first_tok = it.list.at(0);5380 const first_tok = it.list.at(0);
5364 const token = try appendToken(c, .StringLiteral, try zigifyEscapeSequences(c, source[tok.start..tok.end], source[first_tok.start..first_tok.end], source_loc));5381 const token = try appendToken(c, .StringLiteral, try zigifyEscapeSequences(c, source[tok.start..tok.end], source[first_tok.start..first_tok.end], source_loc));
5365 const node = try c.a().create(ast.Node.StringLiteral);5382 const node = try c.a().create(ast.Node.StringLiteral);
5366 node.* = ast.Node.StringLiteral{5383 node.* = .{
5367 .token = token,5384 .token = token,
5368 };5385 };
5369 return &node.base;5386 return &node.base;
...@@ -5428,15 +5445,14 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5428,15 +5445,14 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5428 return error.ParseError;5445 return error.ParseError;
5429 }5446 }
54305447
5431 // TODO: It might be nice if we only did the alignCasting for opaque types5448 //if (@typeInfo(@TypeOf(x)) == .Pointer)
5432 //( if (@typeInfo(@TypeOf(x)) == .Pointer)5449 // @ptrCast(dest, x)
5433 // @ptrCast(dest, @alignCast(@alignOf(dest.Child), x))5450 //else if (@typeInfo(@TypeOf(x)) == .Int and @typeInfo(dest) == .Pointer)
5434 //else if (@typeInfo(@TypeOf(x)) == .Integer)
5435 // @intToPtr(dest, x)5451 // @intToPtr(dest, x)
5436 //else5452 //else
5437 // @as(dest, x) )5453 // @as(dest, x)
54385454
5439 const group_lparen = try appendToken(c, .LParen, "(");5455 const lparen = try appendToken(c, .LParen, "(");
54405456
5441 const if_1 = try transCreateNodeIf(c);5457 const if_1 = try transCreateNodeIf(c);
5442 const type_id_1 = try transCreateNodeBuiltinFnCall(c, "@typeInfo");5458 const type_id_1 = try transCreateNodeBuiltinFnCall(c, "@typeInfo");
...@@ -5456,30 +5472,9 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5456,30 +5472,9 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5456 if_1.condition = &cmp_1.base;5472 if_1.condition = &cmp_1.base;
5457 _ = try appendToken(c, .RParen, ")");5473 _ = try appendToken(c, .RParen, ")");
54585474
5459 const period_tok = try appendToken(c, .Period, ".");
5460 const child_ident = try transCreateNodeIdentifier(c, "Child");
5461 const inner_node_child = try c.a().create(ast.Node.InfixOp);
5462 inner_node_child.* = .{
5463 .op_token = period_tok,
5464 .lhs = inner_node,
5465 .op = .Period,
5466 .rhs = child_ident,
5467 };
5468
5469 const align_of = try transCreateNodeBuiltinFnCall(c, "@alignOf");
5470 try align_of.params.push(&inner_node_child.base);
5471 align_of.rparen_token = try appendToken(c, .RParen, ")");
5472 // hack to get zig fmt to render a comma in builtin calls
5473 _ = try appendToken(c, .Comma, ",");
5474
5475 const align_cast = try transCreateNodeBuiltinFnCall(c, "@alignCast");
5476 try align_cast.params.push(&align_of.base);
5477 try align_cast.params.push(node_to_cast);
5478 align_cast.rparen_token = try appendToken(c, .RParen, ")");
5479
5480 const ptr_cast = try transCreateNodeBuiltinFnCall(c, "@ptrCast");5475 const ptr_cast = try transCreateNodeBuiltinFnCall(c, "@ptrCast");
5481 try ptr_cast.params.push(inner_node);5476 try ptr_cast.params.push(inner_node);
5482 try ptr_cast.params.push(&align_cast.base);5477 try ptr_cast.params.push(node_to_cast);
5483 ptr_cast.rparen_token = try appendToken(c, .RParen, ")");5478 ptr_cast.rparen_token = try appendToken(c, .RParen, ")");
5484 if_1.body = &ptr_cast.base;5479 if_1.body = &ptr_cast.base;
54855480
...@@ -5502,6 +5497,25 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5502,6 +5497,25 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5502 .rhs = try transCreateNodeEnumLiteral(c, "Int"),5497 .rhs = try transCreateNodeEnumLiteral(c, "Int"),
5503 };5498 };
5504 if_2.condition = &cmp_2.base;5499 if_2.condition = &cmp_2.base;
5500 const cmp_4 = try c.a().create(ast.Node.InfixOp);
5501 cmp_4.* = .{
5502 .op_token = try appendToken(c, .Keyword_and, "and"),
5503 .lhs = &cmp_2.base,
5504 .op = .BoolAnd,
5505 .rhs = undefined,
5506 };
5507 const type_id_3 = try transCreateNodeBuiltinFnCall(c, "@typeInfo");
5508 try type_id_3.params.push(inner_node);
5509 type_id_3.rparen_token = try appendToken(c, .LParen, ")");
5510 const cmp_3 = try c.a().create(ast.Node.InfixOp);
5511 cmp_3.* = .{
5512 .op_token = try appendToken(c, .EqualEqual, "=="),
5513 .lhs = &type_id_3.base,
5514 .op = .EqualEqual,
5515 .rhs = try transCreateNodeEnumLiteral(c, "Pointer"),
5516 };
5517 cmp_4.rhs = &cmp_3.base;
5518 if_2.condition = &cmp_4.base;
5505 else_1.body = &if_2.base;5519 else_1.body = &if_2.base;
5506 _ = try appendToken(c, .RParen, ")");5520 _ = try appendToken(c, .RParen, ")");
55075521
...@@ -5520,14 +5534,13 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5520,14 +5534,13 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5520 as.rparen_token = try appendToken(c, .RParen, ")");5534 as.rparen_token = try appendToken(c, .RParen, ")");
5521 else_2.body = &as.base;5535 else_2.body = &as.base;
55225536
5523 const group_rparen = try appendToken(c, .RParen, ")");5537 const group_node = try c.a().create(ast.Node.GroupedExpression);
5524 const grouped_expr = try c.a().create(ast.Node.GroupedExpression);5538 group_node.* = .{
5525 grouped_expr.* = .{5539 .lparen = lparen,
5526 .lparen = group_lparen,
5527 .expr = &if_1.base,5540 .expr = &if_1.base,
5528 .rparen = group_rparen,5541 .rparen = try appendToken(c, .RParen, ")"),
5529 };5542 };
5530 return &grouped_expr.base;5543 return &group_node.base;
5531 },5544 },
5532 else => {5545 else => {
5533 const first_tok = it.list.at(0);5546 const first_tok = it.list.at(0);
...@@ -5543,12 +5556,63 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5543,12 +5556,63 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5543 }5556 }
5544}5557}
55455558
5559fn macroBoolToInt(c: *Context, node: *ast.Node) !*ast.Node {
5560 if (!isBoolRes(node)) {
5561 if (node.id != .InfixOp) return node;
5562
5563 const group_node = try c.a().create(ast.Node.GroupedExpression);
5564 group_node.* = .{
5565 .lparen = try appendToken(c, .LParen, "("),
5566 .expr = node,
5567 .rparen = try appendToken(c, .RParen, ")"),
5568 };
5569 return &group_node.base;
5570 }
5571
5572 const builtin_node = try transCreateNodeBuiltinFnCall(c, "@boolToInt");
5573 try builtin_node.params.push(node);
5574 builtin_node.rparen_token = try appendToken(c, .RParen, ")");
5575 return &builtin_node.base;
5576}
5577
5578fn macroIntToBool(c: *Context, node: *ast.Node) !*ast.Node {
5579 if (isBoolRes(node)) {
5580 if (node.id != .InfixOp) return node;
5581
5582 const group_node = try c.a().create(ast.Node.GroupedExpression);
5583 group_node.* = .{
5584 .lparen = try appendToken(c, .LParen, "("),
5585 .expr = node,
5586 .rparen = try appendToken(c, .RParen, ")"),
5587 };
5588 return &group_node.base;
5589 }
5590
5591 const op_token = try appendToken(c, .BangEqual, "!=");
5592 const zero = try transCreateNodeInt(c, 0);
5593 const res = try c.a().create(ast.Node.InfixOp);
5594 res.* = .{
5595 .op_token = op_token,
5596 .lhs = node,
5597 .op = .BangEqual,
5598 .rhs = zero,
5599 };
5600 const group_node = try c.a().create(ast.Node.GroupedExpression);
5601 group_node.* = .{
5602 .lparen = try appendToken(c, .LParen, "("),
5603 .expr = &res.base,
5604 .rparen = try appendToken(c, .RParen, ")"),
5605 };
5606 return &group_node.base;
5607}
5608
5546fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8, source_loc: ZigClangSourceLocation, scope: *Scope) ParseError!*ast.Node {5609fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8, source_loc: ZigClangSourceLocation, scope: *Scope) ParseError!*ast.Node {
5547 var node = try parseCPrimaryExpr(c, it, source, source_loc, scope);5610 var node = try parseCPrimaryExpr(c, it, source, source_loc, scope);
5548 while (true) {5611 while (true) {
5549 const tok = it.next().?;5612 const tok = it.next().?;
5550 var op_token: ast.TokenIndex = undefined;5613 var op_token: ast.TokenIndex = undefined;
5551 var op_id: ast.Node.InfixOp.Op = undefined;5614 var op_id: ast.Node.InfixOp.Op = undefined;
5615 var bool_op = false;
5552 switch (tok.id) {5616 switch (tok.id) {
5553 .Period => {5617 .Period => {
5554 const name_tok = it.next().?;5618 const name_tok = it.next().?;
...@@ -5637,10 +5701,12 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5637,10 +5701,12 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5637 .AmpersandAmpersand => {5701 .AmpersandAmpersand => {
5638 op_token = try appendToken(c, .Keyword_and, "and");5702 op_token = try appendToken(c, .Keyword_and, "and");
5639 op_id = .BoolAnd;5703 op_id = .BoolAnd;
5704 bool_op = true;
5640 },5705 },
5641 .PipePipe => {5706 .PipePipe => {
5642 op_token = try appendToken(c, .Keyword_or, "or");5707 op_token = try appendToken(c, .Keyword_or, "or");
5643 op_id = .BoolOr;5708 op_id = .BoolOr;
5709 bool_op = true;
5644 },5710 },
5645 .AngleBracketRight => {5711 .AngleBracketRight => {
5646 op_token = try appendToken(c, .AngleBracketRight, ">");5712 op_token = try appendToken(c, .AngleBracketRight, ">");
...@@ -5711,12 +5777,10 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5711,12 +5777,10 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5711 op_id = .EqualEqual;5777 op_id = .EqualEqual;
5712 },5778 },
5713 .Slash => {5779 .Slash => {
5714 // unsigned/float division uses the operator
5715 op_id = .Div;5780 op_id = .Div;
5716 op_token = try appendToken(c, .Slash, "/");5781 op_token = try appendToken(c, .Slash, "/");
5717 },5782 },
5718 .Percent => {5783 .Percent => {
5719 // unsigned/float division uses the operator
5720 op_id = .Mod;5784 op_id = .Mod;
5721 op_token = try appendToken(c, .Percent, "%");5785 op_token = try appendToken(c, .Percent, "%");
5722 },5786 },
...@@ -5725,12 +5789,15 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,...@@ -5725,12 +5789,15 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
5725 return node;5789 return node;
5726 },5790 },
5727 }5791 }
5792 const cast_fn = if (bool_op) macroIntToBool else macroBoolToInt;
5793 const lhs_node = try cast_fn(c, node);
5794 const rhs_node = try parseCPrefixOpExpr(c, it, source, source_loc, scope);
5728 const op_node = try c.a().create(ast.Node.InfixOp);5795 const op_node = try c.a().create(ast.Node.InfixOp);
5729 op_node.* = .{5796 op_node.* = .{
5730 .op_token = op_token,5797 .op_token = op_token,
5731 .lhs = node,5798 .lhs = lhs_node,
5732 .op = op_id,5799 .op = op_id,
5733 .rhs = try parseCPrefixOpExpr(c, it, source, source_loc, scope),5800 .rhs = try cast_fn(c, rhs_node),
5734 };5801 };
5735 node = &op_node.base;5802 node = &op_node.base;
5736 }5803 }
src/all_types.hpp+13-1
...@@ -651,6 +651,7 @@ enum NodeType {...@@ -651,6 +651,7 @@ enum NodeType {
651 NodeTypeSwitchProng,651 NodeTypeSwitchProng,
652 NodeTypeSwitchRange,652 NodeTypeSwitchRange,
653 NodeTypeCompTime,653 NodeTypeCompTime,
654 NodeTypeNoAsync,
654 NodeTypeBreak,655 NodeTypeBreak,
655 NodeTypeContinue,656 NodeTypeContinue,
656 NodeTypeAsmExpr,657 NodeTypeAsmExpr,
...@@ -991,6 +992,10 @@ struct AstNodeCompTime {...@@ -991,6 +992,10 @@ struct AstNodeCompTime {
991 AstNode *expr;992 AstNode *expr;
992};993};
993994
995struct AstNodeNoAsync {
996 AstNode *expr;
997};
998
994struct AsmOutput {999struct AsmOutput {
995 Buf *asm_symbolic_name;1000 Buf *asm_symbolic_name;
996 Buf *constraint;1001 Buf *constraint;
...@@ -1148,7 +1153,6 @@ struct AstNodeErrorType {...@@ -1148,7 +1153,6 @@ struct AstNodeErrorType {
1148};1153};
11491154
1150struct AstNodeAwaitExpr {1155struct AstNodeAwaitExpr {
1151 Token *noasync_token;
1152 AstNode *expr;1156 AstNode *expr;
1153};1157};
11541158
...@@ -1199,6 +1203,7 @@ struct AstNode {...@@ -1199,6 +1203,7 @@ struct AstNode {
1199 AstNodeSwitchProng switch_prong;1203 AstNodeSwitchProng switch_prong;
1200 AstNodeSwitchRange switch_range;1204 AstNodeSwitchRange switch_range;
1201 AstNodeCompTime comptime_expr;1205 AstNodeCompTime comptime_expr;
1206 AstNodeNoAsync noasync_expr;
1202 AstNodeAsmExpr asm_expr;1207 AstNodeAsmExpr asm_expr;
1203 AstNodeFieldAccessExpr field_access_expr;1208 AstNodeFieldAccessExpr field_access_expr;
1204 AstNodePtrDerefExpr ptr_deref_expr;1209 AstNodePtrDerefExpr ptr_deref_expr;
...@@ -1828,6 +1833,7 @@ enum PanicMsgId {...@@ -1828,6 +1833,7 @@ enum PanicMsgId {
1828 PanicMsgIdBadNoAsyncCall,1833 PanicMsgIdBadNoAsyncCall,
1829 PanicMsgIdResumeNotSuspendedFn,1834 PanicMsgIdResumeNotSuspendedFn,
1830 PanicMsgIdBadSentinel,1835 PanicMsgIdBadSentinel,
1836 PanicMsgIdShxTooBigRhs,
18311837
1832 PanicMsgIdCount,1838 PanicMsgIdCount,
1833};1839};
...@@ -2324,6 +2330,7 @@ enum ScopeId {...@@ -2324,6 +2330,7 @@ enum ScopeId {
2324 ScopeIdRuntime,2330 ScopeIdRuntime,
2325 ScopeIdTypeOf,2331 ScopeIdTypeOf,
2326 ScopeIdExpr,2332 ScopeIdExpr,
2333 ScopeIdNoAsync,
2327};2334};
23282335
2329struct Scope {2336struct Scope {
...@@ -2456,6 +2463,11 @@ struct ScopeCompTime {...@@ -2456,6 +2463,11 @@ struct ScopeCompTime {
2456 Scope base;2463 Scope base;
2457};2464};
24582465
2466// This scope is created for a noasync expression.
2467// NodeTypeNoAsync
2468struct ScopeNoAsync {
2469 Scope base;
2470};
24592471
2460// This scope is created for a function definition.2472// This scope is created for a function definition.
2461// NodeTypeFnDef2473// NodeTypeFnDef
src/analyze.cpp+65-24
...@@ -106,6 +106,7 @@ static ScopeExpr *find_expr_scope(Scope *scope) {...@@ -106,6 +106,7 @@ static ScopeExpr *find_expr_scope(Scope *scope) {
106 case ScopeIdDecls:106 case ScopeIdDecls:
107 case ScopeIdFnDef:107 case ScopeIdFnDef:
108 case ScopeIdCompTime:108 case ScopeIdCompTime:
109 case ScopeIdNoAsync:
109 case ScopeIdVarDecl:110 case ScopeIdVarDecl:
110 case ScopeIdCImport:111 case ScopeIdCImport:
111 case ScopeIdSuspend:112 case ScopeIdSuspend:
...@@ -226,6 +227,12 @@ Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent) {...@@ -226,6 +227,12 @@ Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent) {
226 return &scope->base;227 return &scope->base;
227}228}
228229
230Scope *create_noasync_scope(CodeGen *g, AstNode *node, Scope *parent) {
231 ScopeNoAsync *scope = heap::c_allocator.create<ScopeNoAsync>();
232 init_scope(g, &scope->base, ScopeIdNoAsync, node, parent);
233 return &scope->base;
234}
235
229Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent) {236Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent) {
230 ScopeTypeOf *scope = heap::c_allocator.create<ScopeTypeOf>();237 ScopeTypeOf *scope = heap::c_allocator.create<ScopeTypeOf>();
231 init_scope(g, &scope->base, ScopeIdTypeOf, node, parent);238 init_scope(g, &scope->base, ScopeIdTypeOf, node, parent);
...@@ -1955,29 +1962,14 @@ static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_sc...@@ -1955,29 +1962,14 @@ static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_sc
1955 return g->builtin_types.entry_invalid;1962 return g->builtin_types.entry_invalid;
1956 }1963 }
19571964
1958 switch (specified_return_type->id) {1965 if(!is_valid_return_type(specified_return_type)){
1959 case ZigTypeIdInvalid:1966 ErrorMsg* msg = add_node_error(g, fn_proto->return_type,
1960 zig_unreachable();1967 buf_sprintf("%s return type '%s' not allowed", type_id_name(specified_return_type->id), buf_ptr(&specified_return_type->name)));
19611968 Tld *tld = find_decl(g, &fn_entry->fndef_scope->base, &specified_return_type->name);
1962 case ZigTypeIdUndefined:1969 if (tld != nullptr) {
1963 case ZigTypeIdNull:1970 add_error_note(g, msg, tld->source_node, buf_sprintf("type declared here"));
1964 add_node_error(g, fn_proto->return_type,
1965 buf_sprintf("return type '%s' not allowed", buf_ptr(&specified_return_type->name)));
1966 return g->builtin_types.entry_invalid;
1967
1968 case ZigTypeIdOpaque:
1969 {
1970 ErrorMsg* msg = add_node_error(g, fn_proto->return_type,
1971 buf_sprintf("opaque return type '%s' not allowed", buf_ptr(&specified_return_type->name)));
1972 Tld *tld = find_decl(g, &fn_entry->fndef_scope->base, &specified_return_type->name);
1973 if (tld != nullptr) {
1974 add_error_note(g, msg, tld->source_node, buf_sprintf("declared here"));
1975 }
1976 return g->builtin_types.entry_invalid;
1977 }1971 }
19781972 return g->builtin_types.entry_invalid;
1979 default:
1980 break;
1981 }1973 }
19821974
1983 if (fn_proto->auto_err_set) {1975 if (fn_proto->auto_err_set) {
...@@ -2049,6 +2041,19 @@ static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_sc...@@ -2049,6 +2041,19 @@ static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_sc
2049 return get_fn_type(g, &fn_type_id);2041 return get_fn_type(g, &fn_type_id);
2050}2042}
20512043
2044bool is_valid_return_type(ZigType* type) {
2045 switch (type->id) {
2046 case ZigTypeIdInvalid:
2047 case ZigTypeIdUndefined:
2048 case ZigTypeIdNull:
2049 case ZigTypeIdOpaque:
2050 return false;
2051 default:
2052 return true;
2053 }
2054 zig_unreachable();
2055}
2056
2052bool type_is_invalid(ZigType *type_entry) {2057bool type_is_invalid(ZigType *type_entry) {
2053 switch (type_entry->id) {2058 switch (type_entry->id) {
2054 case ZigTypeIdInvalid:2059 case ZigTypeIdInvalid:
...@@ -2893,7 +2898,7 @@ static Error resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type) {...@@ -2893,7 +2898,7 @@ static Error resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type) {
2893 return ErrorSemanticAnalyzeFail;2898 return ErrorSemanticAnalyzeFail;
2894 }2899 }
2895 if (field_is_opaque_type) {2900 if (field_is_opaque_type) {
2896 add_node_error(g, field_node->data.struct_field.type,2901 add_node_error(g, field_node,
2897 buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in structs"));2902 buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in structs"));
2898 struct_type->data.structure.resolve_status = ResolveStatusInvalid;2903 struct_type->data.structure.resolve_status = ResolveStatusInvalid;
2899 return ErrorSemanticAnalyzeFail;2904 return ErrorSemanticAnalyzeFail;
...@@ -3185,7 +3190,7 @@ static Error resolve_union_zero_bits(CodeGen *g, ZigType *union_type) {...@@ -3185,7 +3190,7 @@ static Error resolve_union_zero_bits(CodeGen *g, ZigType *union_type) {
3185 return ErrorSemanticAnalyzeFail;3190 return ErrorSemanticAnalyzeFail;
3186 }3191 }
3187 if (field_is_opaque_type) {3192 if (field_is_opaque_type) {
3188 add_node_error(g, field_node->data.struct_field.type,3193 add_node_error(g, field_node,
3189 buf_create_from_str(3194 buf_create_from_str(
3190 "opaque types have unknown size and therefore cannot be directly embedded in unions"));3195 "opaque types have unknown size and therefore cannot be directly embedded in unions"));
3191 union_type->data.unionation.resolve_status = ResolveStatusInvalid;3196 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
...@@ -3755,6 +3760,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {...@@ -3755,6 +3760,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
3755 case NodeTypeCompTime:3760 case NodeTypeCompTime:
3756 preview_comptime_decl(g, node, decls_scope);3761 preview_comptime_decl(g, node, decls_scope);
3757 break;3762 break;
3763 case NodeTypeNoAsync:
3758 case NodeTypeParamDecl:3764 case NodeTypeParamDecl:
3759 case NodeTypeReturnExpr:3765 case NodeTypeReturnExpr:
3760 case NodeTypeDefer:3766 case NodeTypeDefer:
...@@ -5789,6 +5795,7 @@ ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) {...@@ -5789,6 +5795,7 @@ ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) {
5789 ZigValue *result = g->pass1_arena->create<ZigValue>();5795 ZigValue *result = g->pass1_arena->create<ZigValue>();
5790 result->type = type_entry;5796 result->type = type_entry;
5791 result->special = ConstValSpecialStatic;5797 result->special = ConstValSpecialStatic;
5798
5792 if (result->type->id == ZigTypeIdStruct) {5799 if (result->type->id == ZigTypeIdStruct) {
5793 // The fields array cannot be left unpopulated5800 // The fields array cannot be left unpopulated
5794 const ZigType *struct_type = result->type;5801 const ZigType *struct_type = result->type;
...@@ -5800,6 +5807,22 @@ ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) {...@@ -5800,6 +5807,22 @@ ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) {
5800 assert(field_type != nullptr);5807 assert(field_type != nullptr);
5801 result->data.x_struct.fields[i] = get_the_one_possible_value(g, field_type);5808 result->data.x_struct.fields[i] = get_the_one_possible_value(g, field_type);
5802 }5809 }
5810 } else if (result->type->id == ZigTypeIdArray) {
5811 // The elements array cannot be left unpopulated
5812 ZigType *array_type = result->type;
5813 ZigType *elem_type = array_type->data.array.child_type;
5814 ZigValue *sentinel_value = array_type->data.array.sentinel;
5815 const size_t elem_count = array_type->data.array.len + (sentinel_value != nullptr);
5816
5817 result->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(elem_count);
5818 for (size_t i = 0; i < elem_count; i += 1) {
5819 ZigValue *elem_val = &result->data.x_array.data.s_none.elements[i];
5820 copy_const_val(g, elem_val, get_the_one_possible_value(g, elem_type));
5821 }
5822 if (sentinel_value != nullptr) {
5823 ZigValue *last_elem_val = &result->data.x_array.data.s_none.elements[elem_count - 1];
5824 copy_const_val(g, last_elem_val, sentinel_value);
5825 }
5803 } else if (result->type->id == ZigTypeIdPointer) {5826 } else if (result->type->id == ZigTypeIdPointer) {
5804 result->data.x_ptr.special = ConstPtrSpecialRef;5827 result->data.x_ptr.special = ConstPtrSpecialRef;
5805 result->data.x_ptr.data.ref.pointee = get_the_one_possible_value(g, result->type->data.pointer.child_type);5828 result->data.x_ptr.data.ref.pointee = get_the_one_possible_value(g, result->type->data.pointer.child_type);
...@@ -6176,6 +6199,7 @@ static void mark_suspension_point(Scope *scope) {...@@ -6176,6 +6199,7 @@ static void mark_suspension_point(Scope *scope) {
6176 case ScopeIdDecls:6199 case ScopeIdDecls:
6177 case ScopeIdFnDef:6200 case ScopeIdFnDef:
6178 case ScopeIdCompTime:6201 case ScopeIdCompTime:
6202 case ScopeIdNoAsync:
6179 case ScopeIdCImport:6203 case ScopeIdCImport:
6180 case ScopeIdSuspend:6204 case ScopeIdSuspend:
6181 case ScopeIdTypeOf:6205 case ScopeIdTypeOf:
...@@ -9528,6 +9552,23 @@ void copy_const_val(CodeGen *g, ZigValue *dest, ZigValue *src) {...@@ -9528,6 +9552,23 @@ void copy_const_val(CodeGen *g, ZigValue *dest, ZigValue *src) {
9528 }9552 }
9529}9553}
95309554
9555bool optional_value_is_null(ZigValue *val) {
9556 assert(val->special == ConstValSpecialStatic);
9557 if (get_src_ptr_type(val->type) != nullptr) {
9558 if (val->data.x_ptr.special == ConstPtrSpecialNull) {
9559 return true;
9560 } else if (val->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) {
9561 return val->data.x_ptr.data.hard_coded_addr.addr == 0;
9562 } else {
9563 return false;
9564 }
9565 } else if (is_opt_err_set(val->type)) {
9566 return val->data.x_err_set == nullptr;
9567 } else {
9568 return val->data.x_optional == nullptr;
9569 }
9570}
9571
9531bool type_is_numeric(ZigType *ty) {9572bool type_is_numeric(ZigType *ty) {
9532 switch (ty->id) {9573 switch (ty->id) {
9533 case ZigTypeIdInvalid:9574 case ZigTypeIdInvalid:
src/analyze.hpp+3
...@@ -125,6 +125,7 @@ ScopeLoop *create_loop_scope(CodeGen *g, AstNode *node, Scope *parent);...@@ -125,6 +125,7 @@ ScopeLoop *create_loop_scope(CodeGen *g, AstNode *node, Scope *parent);
125ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent);125ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent);
126ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn *fn_entry);126ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn *fn_entry);
127Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent);127Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent);
128Scope *create_noasync_scope(CodeGen *g, AstNode *node, Scope *parent);
128Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstSrc *is_comptime);129Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstSrc *is_comptime);
129Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent);130Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent);
130ScopeExpr *create_expr_scope(CodeGen *g, AstNode *node, Scope *parent);131ScopeExpr *create_expr_scope(CodeGen *g, AstNode *node, Scope *parent);
...@@ -197,6 +198,7 @@ size_t type_id_index(ZigType *entry);...@@ -197,6 +198,7 @@ size_t type_id_index(ZigType *entry);
197ZigType *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id);198ZigType *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id);
198LinkLib *create_link_lib(Buf *name);199LinkLib *create_link_lib(Buf *name);
199LinkLib *add_link_lib(CodeGen *codegen, Buf *lib);200LinkLib *add_link_lib(CodeGen *codegen, Buf *lib);
201bool optional_value_is_null(ZigValue *val);
200202
201uint32_t get_abi_alignment(CodeGen *g, ZigType *type_entry);203uint32_t get_abi_alignment(CodeGen *g, ZigType *type_entry);
202ZigType *get_align_amt_type(CodeGen *g);204ZigType *get_align_amt_type(CodeGen *g);
...@@ -265,6 +267,7 @@ ZigValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *...@@ -265,6 +267,7 @@ ZigValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *
265void resolve_llvm_types_fn(CodeGen *g, ZigFn *fn);267void resolve_llvm_types_fn(CodeGen *g, ZigFn *fn);
266bool fn_is_async(ZigFn *fn);268bool fn_is_async(ZigFn *fn);
267CallingConvention cc_from_fn_proto(AstNodeFnProto *fn_proto);269CallingConvention cc_from_fn_proto(AstNodeFnProto *fn_proto);
270bool is_valid_return_type(ZigType* type);
268271
269Error type_val_resolve_abi_align(CodeGen *g, AstNode *source_node, ZigValue *type_val, uint32_t *abi_align);272Error type_val_resolve_abi_align(CodeGen *g, AstNode *source_node, ZigValue *type_val, uint32_t *abi_align);
270Error type_val_resolve_abi_size(CodeGen *g, AstNode *source_node, ZigValue *type_val,273Error type_val_resolve_abi_size(CodeGen *g, AstNode *source_node, ZigValue *type_val,
src/ast_render.cpp+8
...@@ -220,6 +220,8 @@ static const char *node_type_str(NodeType node_type) {...@@ -220,6 +220,8 @@ static const char *node_type_str(NodeType node_type) {
220 return "SwitchRange";220 return "SwitchRange";
221 case NodeTypeCompTime:221 case NodeTypeCompTime:
222 return "CompTime";222 return "CompTime";
223 case NodeTypeNoAsync:
224 return "NoAsync";
223 case NodeTypeBreak:225 case NodeTypeBreak:
224 return "Break";226 return "Break";
225 case NodeTypeContinue:227 case NodeTypeContinue:
...@@ -1091,6 +1093,12 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {...@@ -1091,6 +1093,12 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
1091 render_node_grouped(ar, node->data.comptime_expr.expr);1093 render_node_grouped(ar, node->data.comptime_expr.expr);
1092 break;1094 break;
1093 }1095 }
1096 case NodeTypeNoAsync:
1097 {
1098 fprintf(ar->f, "noasync ");
1099 render_node_grouped(ar, node->data.noasync_expr.expr);
1100 break;
1101 }
1094 case NodeTypeForExpr:1102 case NodeTypeForExpr:
1095 {1103 {
1096 if (node->data.for_expr.name != nullptr) {1104 if (node->data.for_expr.name != nullptr) {
src/cache_hash.cpp+6-2
...@@ -24,11 +24,15 @@ void cache_init(CacheHash *ch, Buf *manifest_dir) {...@@ -24,11 +24,15 @@ void cache_init(CacheHash *ch, Buf *manifest_dir) {
24 ch->b64_digest = BUF_INIT;24 ch->b64_digest = BUF_INIT;
25}25}
2626
27void cache_str(CacheHash *ch, const char *ptr) {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 byte30 // + 1 to include the null byte
31 blake2b_update(&ch->blake, ptr, strlen(ptr) + 1);31 blake2b_update(&ch->blake, ptr, len);
32}
33
34void cache_str(CacheHash *ch, const char *ptr) {
35 cache_mem(ch, ptr, strlen(ptr) + 1);
32}36}
3337
34void cache_int(CacheHash *ch, int x) {38void cache_int(CacheHash *ch, int x) {
src/cache_hash.hpp+1
...@@ -35,6 +35,7 @@ struct CacheHash {...@@ -35,6 +35,7 @@ struct CacheHash {
35void cache_init(CacheHash *ch, Buf *manifest_dir);35void 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_str(CacheHash *ch, const char *ptr);39void cache_str(CacheHash *ch, const char *ptr);
39void cache_int(CacheHash *ch, int x);40void cache_int(CacheHash *ch, int x);
40void cache_bool(CacheHash *ch, bool x);41void cache_bool(CacheHash *ch, bool x);
src/codegen.cpp+137-4
...@@ -686,6 +686,7 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {...@@ -686,6 +686,7 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
686 case ScopeIdLoop:686 case ScopeIdLoop:
687 case ScopeIdSuspend:687 case ScopeIdSuspend:
688 case ScopeIdCompTime:688 case ScopeIdCompTime:
689 case ScopeIdNoAsync:
689 case ScopeIdRuntime:690 case ScopeIdRuntime:
690 case ScopeIdTypeOf:691 case ScopeIdTypeOf:
691 case ScopeIdExpr:692 case ScopeIdExpr:
...@@ -967,11 +968,13 @@ static Buf *panic_msg_buf(PanicMsgId msg_id) {...@@ -967,11 +968,13 @@ static Buf *panic_msg_buf(PanicMsgId msg_id) {
967 case PanicMsgIdResumedFnPendingAwait:968 case PanicMsgIdResumedFnPendingAwait:
968 return buf_create_from_str("resumed an async function which can only be awaited");969 return buf_create_from_str("resumed an async function which can only be awaited");
969 case PanicMsgIdBadNoAsyncCall:970 case PanicMsgIdBadNoAsyncCall:
970 return buf_create_from_str("async function called with noasync suspended");971 return buf_create_from_str("async function called in noasync scope suspended");
971 case PanicMsgIdResumeNotSuspendedFn:972 case PanicMsgIdResumeNotSuspendedFn:
972 return buf_create_from_str("resumed a non-suspended function");973 return buf_create_from_str("resumed a non-suspended function");
973 case PanicMsgIdBadSentinel:974 case PanicMsgIdBadSentinel:
974 return buf_create_from_str("sentinel mismatch");975 return buf_create_from_str("sentinel mismatch");
976 case PanicMsgIdShxTooBigRhs:
977 return buf_create_from_str("shift amount is greater than the type size");
975 }978 }
976 zig_unreachable();979 zig_unreachable();
977}980}
...@@ -2836,6 +2839,26 @@ static LLVMValueRef gen_rem(CodeGen *g, bool want_runtime_safety, bool want_fast...@@ -2836,6 +2839,26 @@ static LLVMValueRef gen_rem(CodeGen *g, bool want_runtime_safety, bool want_fast
28362839
2837}2840}
28382841
2842static void gen_shift_rhs_check(CodeGen *g, ZigType *lhs_type, ZigType *rhs_type, LLVMValueRef value) {
2843 // We only check if the rhs value of the shift expression is greater or
2844 // equal to the number of bits of the lhs if it's not a power of two,
2845 // otherwise the check is useful as the allowed values are limited by the
2846 // operand type itself
2847 if (!is_power_of_2(lhs_type->data.integral.bit_count)) {
2848 LLVMValueRef bit_count_value = LLVMConstInt(get_llvm_type(g, rhs_type),
2849 lhs_type->data.integral.bit_count, false);
2850 LLVMValueRef less_than_bit = LLVMBuildICmp(g->builder, LLVMIntULT, value, bit_count_value, "");
2851 LLVMBasicBlockRef fail_block = LLVMAppendBasicBlock(g->cur_fn_val, "CheckFail");
2852 LLVMBasicBlockRef ok_block = LLVMAppendBasicBlock(g->cur_fn_val, "CheckOk");
2853 LLVMBuildCondBr(g->builder, less_than_bit, ok_block, fail_block);
2854
2855 LLVMPositionBuilderAtEnd(g->builder, fail_block);
2856 gen_safety_crash(g, PanicMsgIdShxTooBigRhs);
2857
2858 LLVMPositionBuilderAtEnd(g->builder, ok_block);
2859 }
2860}
2861
2839static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,2862static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,
2840 IrInstGenBinOp *bin_op_instruction)2863 IrInstGenBinOp *bin_op_instruction)
2841{2864{
...@@ -2944,6 +2967,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,...@@ -2944,6 +2967,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,
2944 {2967 {
2945 assert(scalar_type->id == ZigTypeIdInt);2968 assert(scalar_type->id == ZigTypeIdInt);
2946 LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, op2->value->type, scalar_type, op2_value);2969 LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, op2->value->type, scalar_type, op2_value);
2970
2971 if (want_runtime_safety) {
2972 gen_shift_rhs_check(g, scalar_type, op2->value->type, op2_value);
2973 }
2974
2947 bool is_sloppy = (op_id == IrBinOpBitShiftLeftLossy);2975 bool is_sloppy = (op_id == IrBinOpBitShiftLeftLossy);
2948 if (is_sloppy) {2976 if (is_sloppy) {
2949 return LLVMBuildShl(g->builder, op1_value, op2_casted, "");2977 return LLVMBuildShl(g->builder, op1_value, op2_casted, "");
...@@ -2960,6 +2988,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,...@@ -2960,6 +2988,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,
2960 {2988 {
2961 assert(scalar_type->id == ZigTypeIdInt);2989 assert(scalar_type->id == ZigTypeIdInt);
2962 LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, op2->value->type, scalar_type, op2_value);2990 LLVMValueRef op2_casted = gen_widen_or_shorten(g, false, op2->value->type, scalar_type, op2_value);
2991
2992 if (want_runtime_safety) {
2993 gen_shift_rhs_check(g, scalar_type, op2->value->type, op2_value);
2994 }
2995
2963 bool is_sloppy = (op_id == IrBinOpBitShiftRightLossy);2996 bool is_sloppy = (op_id == IrBinOpBitShiftRightLossy);
2964 if (is_sloppy) {2997 if (is_sloppy) {
2965 if (scalar_type->data.integral.is_signed) {2998 if (scalar_type->data.integral.is_signed) {
...@@ -3930,6 +3963,7 @@ static void render_async_var_decls(CodeGen *g, Scope *scope) {...@@ -3930,6 +3963,7 @@ static void render_async_var_decls(CodeGen *g, Scope *scope) {
3930 case ScopeIdLoop:3963 case ScopeIdLoop:
3931 case ScopeIdSuspend:3964 case ScopeIdSuspend:
3932 case ScopeIdCompTime:3965 case ScopeIdCompTime:
3966 case ScopeIdNoAsync:
3933 case ScopeIdRuntime:3967 case ScopeIdRuntime:
3934 case ScopeIdTypeOf:3968 case ScopeIdTypeOf:
3935 case ScopeIdExpr:3969 case ScopeIdExpr:
...@@ -5212,11 +5246,55 @@ static enum ZigLLVM_AtomicRMWBinOp to_ZigLLVMAtomicRMWBinOp(AtomicRmwOp op, bool...@@ -5212,11 +5246,55 @@ static enum ZigLLVM_AtomicRMWBinOp to_ZigLLVMAtomicRMWBinOp(AtomicRmwOp op, bool
5212 zig_unreachable();5246 zig_unreachable();
5213}5247}
52145248
5249static LLVMTypeRef get_atomic_abi_type(CodeGen *g, IrInstGen *instruction) {
5250 // If the operand type of an atomic operation is not a power of two sized
5251 // we need to widen it before using it and then truncate the result.
5252
5253 ir_assert(instruction->value->type->id == ZigTypeIdPointer, instruction);
5254 ZigType *operand_type = instruction->value->type->data.pointer.child_type;
5255 if (operand_type->id == ZigTypeIdInt || operand_type->id == ZigTypeIdEnum) {
5256 if (operand_type->id == ZigTypeIdEnum) {
5257 operand_type = operand_type->data.enumeration.tag_int_type;
5258 }
5259 auto bit_count = operand_type->data.integral.bit_count;
5260 bool is_signed = operand_type->data.integral.is_signed;
5261
5262 ir_assert(bit_count != 0, instruction);
5263 if (bit_count == 1 || !is_power_of_2(bit_count)) {
5264 return get_llvm_type(g, get_int_type(g, is_signed, operand_type->abi_size * 8));
5265 } else {
5266 return nullptr;
5267 }
5268 } else if (operand_type->id == ZigTypeIdFloat) {
5269 return nullptr;
5270 } else if (operand_type->id == ZigTypeIdBool) {
5271 return g->builtin_types.entry_u8->llvm_type;
5272 } else {
5273 ir_assert(get_codegen_ptr_type_bail(g, operand_type) != nullptr, instruction);
5274 return nullptr;
5275 }
5276}
5277
5215static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, IrInstGenCmpxchg *instruction) {5278static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, IrInstGenCmpxchg *instruction) {
5216 LLVMValueRef ptr_val = ir_llvm_value(g, instruction->ptr);5279 LLVMValueRef ptr_val = ir_llvm_value(g, instruction->ptr);
5217 LLVMValueRef cmp_val = ir_llvm_value(g, instruction->cmp_value);5280 LLVMValueRef cmp_val = ir_llvm_value(g, instruction->cmp_value);
5218 LLVMValueRef new_val = ir_llvm_value(g, instruction->new_value);5281 LLVMValueRef new_val = ir_llvm_value(g, instruction->new_value);
52195282
5283 ZigType *operand_type = instruction->new_value->value->type;
5284 LLVMTypeRef actual_abi_type = get_atomic_abi_type(g, instruction->ptr);
5285 if (actual_abi_type != nullptr) {
5286 // operand needs widening and truncating
5287 ptr_val = LLVMBuildBitCast(g->builder, ptr_val,
5288 LLVMPointerType(actual_abi_type, 0), "");
5289 if (operand_type->data.integral.is_signed) {
5290 cmp_val = LLVMBuildSExt(g->builder, cmp_val, actual_abi_type, "");
5291 new_val = LLVMBuildSExt(g->builder, new_val, actual_abi_type, "");
5292 } else {
5293 cmp_val = LLVMBuildZExt(g->builder, cmp_val, actual_abi_type, "");
5294 new_val = LLVMBuildZExt(g->builder, new_val, actual_abi_type, "");
5295 }
5296 }
5297
5220 LLVMAtomicOrdering success_order = to_LLVMAtomicOrdering(instruction->success_order);5298 LLVMAtomicOrdering success_order = to_LLVMAtomicOrdering(instruction->success_order);
5221 LLVMAtomicOrdering failure_order = to_LLVMAtomicOrdering(instruction->failure_order);5299 LLVMAtomicOrdering failure_order = to_LLVMAtomicOrdering(instruction->failure_order);
52225300
...@@ -5229,6 +5307,9 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, I...@@ -5229,6 +5307,9 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, I
52295307
5230 if (!handle_is_ptr(g, optional_type)) {5308 if (!handle_is_ptr(g, optional_type)) {
5231 LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");5309 LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");
5310 if (actual_abi_type != nullptr) {
5311 payload_val = LLVMBuildTrunc(g->builder, payload_val, get_llvm_type(g, operand_type), "");
5312 }
5232 LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");5313 LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");
5233 return LLVMBuildSelect(g->builder, success_bit, LLVMConstNull(get_llvm_type(g, child_type)), payload_val, "");5314 return LLVMBuildSelect(g->builder, success_bit, LLVMConstNull(get_llvm_type(g, child_type)), payload_val, "");
5234 }5315 }
...@@ -5243,6 +5324,9 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, I...@@ -5243,6 +5324,9 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, I
5243 ir_assert(type_has_bits(g, child_type), &instruction->base);5324 ir_assert(type_has_bits(g, child_type), &instruction->base);
52445325
5245 LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");5326 LLVMValueRef payload_val = LLVMBuildExtractValue(g->builder, result_val, 0, "");
5327 if (actual_abi_type != nullptr) {
5328 payload_val = LLVMBuildTrunc(g->builder, payload_val, get_llvm_type(g, operand_type), "");
5329 }
5246 LLVMValueRef val_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_child_index, "");5330 LLVMValueRef val_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_child_index, "");
5247 gen_assign_raw(g, val_ptr, get_pointer_to_type(g, child_type, false), payload_val);5331 gen_assign_raw(g, val_ptr, get_pointer_to_type(g, child_type, false), payload_val);
52485332
...@@ -5820,6 +5904,22 @@ static LLVMValueRef ir_render_atomic_rmw(CodeGen *g, IrExecutableGen *executable...@@ -5820,6 +5904,22 @@ static LLVMValueRef ir_render_atomic_rmw(CodeGen *g, IrExecutableGen *executable
5820 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);5904 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
5821 LLVMValueRef operand = ir_llvm_value(g, instruction->operand);5905 LLVMValueRef operand = ir_llvm_value(g, instruction->operand);
58225906
5907 LLVMTypeRef actual_abi_type = get_atomic_abi_type(g, instruction->ptr);
5908 if (actual_abi_type != nullptr) {
5909 // operand needs widening and truncating
5910 LLVMValueRef casted_ptr = LLVMBuildBitCast(g->builder, ptr,
5911 LLVMPointerType(actual_abi_type, 0), "");
5912 LLVMValueRef casted_operand;
5913 if (operand_type->data.integral.is_signed) {
5914 casted_operand = LLVMBuildSExt(g->builder, operand, actual_abi_type, "");
5915 } else {
5916 casted_operand = LLVMBuildZExt(g->builder, operand, actual_abi_type, "");
5917 }
5918 LLVMValueRef uncasted_result = ZigLLVMBuildAtomicRMW(g->builder, op, casted_ptr, casted_operand, ordering,
5919 g->is_single_threaded);
5920 return LLVMBuildTrunc(g->builder, uncasted_result, get_llvm_type(g, operand_type), "");
5921 }
5922
5823 if (get_codegen_ptr_type_bail(g, operand_type) == nullptr) {5923 if (get_codegen_ptr_type_bail(g, operand_type) == nullptr) {
5824 return ZigLLVMBuildAtomicRMW(g->builder, op, ptr, operand, ordering, g->is_single_threaded);5924 return ZigLLVMBuildAtomicRMW(g->builder, op, ptr, operand, ordering, g->is_single_threaded);
5825 }5925 }
...@@ -5838,6 +5938,17 @@ static LLVMValueRef ir_render_atomic_load(CodeGen *g, IrExecutableGen *executabl...@@ -5838,6 +5938,17 @@ static LLVMValueRef ir_render_atomic_load(CodeGen *g, IrExecutableGen *executabl
5838{5938{
5839 LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->ordering);5939 LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->ordering);
5840 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);5940 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
5941
5942 ZigType *operand_type = instruction->ptr->value->type->data.pointer.child_type;
5943 LLVMTypeRef actual_abi_type = get_atomic_abi_type(g, instruction->ptr);
5944 if (actual_abi_type != nullptr) {
5945 // operand needs widening and truncating
5946 ptr = LLVMBuildBitCast(g->builder, ptr,
5947 LLVMPointerType(actual_abi_type, 0), "");
5948 LLVMValueRef load_inst = gen_load(g, ptr, instruction->ptr->value->type, "");
5949 LLVMSetOrdering(load_inst, ordering);
5950 return LLVMBuildTrunc(g->builder, load_inst, get_llvm_type(g, operand_type), "");
5951 }
5841 LLVMValueRef load_inst = gen_load(g, ptr, instruction->ptr->value->type, "");5952 LLVMValueRef load_inst = gen_load(g, ptr, instruction->ptr->value->type, "");
5842 LLVMSetOrdering(load_inst, ordering);5953 LLVMSetOrdering(load_inst, ordering);
5843 return load_inst;5954 return load_inst;
...@@ -5849,6 +5960,18 @@ static LLVMValueRef ir_render_atomic_store(CodeGen *g, IrExecutableGen *executab...@@ -5849,6 +5960,18 @@ static LLVMValueRef ir_render_atomic_store(CodeGen *g, IrExecutableGen *executab
5849 LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->ordering);5960 LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->ordering);
5850 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);5961 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
5851 LLVMValueRef value = ir_llvm_value(g, instruction->value);5962 LLVMValueRef value = ir_llvm_value(g, instruction->value);
5963
5964 LLVMTypeRef actual_abi_type = get_atomic_abi_type(g, instruction->ptr);
5965 if (actual_abi_type != nullptr) {
5966 // operand needs widening
5967 ptr = LLVMBuildBitCast(g->builder, ptr,
5968 LLVMPointerType(actual_abi_type, 0), "");
5969 if (instruction->value->value->type->data.integral.is_signed) {
5970 value = LLVMBuildSExt(g->builder, value, actual_abi_type, "");
5971 } else {
5972 value = LLVMBuildZExt(g->builder, value, actual_abi_type, "");
5973 }
5974 }
5852 LLVMValueRef store_inst = gen_store(g, value, ptr, instruction->ptr->value->type);5975 LLVMValueRef store_inst = gen_store(g, value, ptr, instruction->ptr->value->type);
5853 LLVMSetOrdering(store_inst, ordering);5976 LLVMSetOrdering(store_inst, ordering);
5854 return nullptr;5977 return nullptr;
...@@ -6895,8 +7018,18 @@ check: switch (const_val->special) {...@@ -6895,8 +7018,18 @@ check: switch (const_val->special) {
6895 case ZigTypeIdOptional:7018 case ZigTypeIdOptional:
6896 {7019 {
6897 ZigType *child_type = type_entry->data.maybe.child_type;7020 ZigType *child_type = type_entry->data.maybe.child_type;
7021
6898 if (get_src_ptr_type(type_entry) != nullptr) {7022 if (get_src_ptr_type(type_entry) != nullptr) {
6899 return gen_const_val_ptr(g, const_val, name);7023 bool has_bits;
7024 if ((err = type_has_bits2(g, child_type, &has_bits)))
7025 codegen_report_errors_and_exit(g);
7026
7027 if (has_bits)
7028 return gen_const_val_ptr(g, const_val, name);
7029
7030 // No bits, treat this value as a boolean
7031 const unsigned bool_val = optional_value_is_null(const_val) ? 0 : 1;
7032 return LLVMConstInt(LLVMInt1Type(), bool_val, false);
6900 } else if (child_type->id == ZigTypeIdErrorSet) {7033 } else if (child_type->id == ZigTypeIdErrorSet) {
6901 return gen_const_val_err_set(g, const_val, name);7034 return gen_const_val_err_set(g, const_val, name);
6902 } else if (!type_has_bits(g, child_type)) {7035 } else if (!type_has_bits(g, child_type)) {
...@@ -8614,7 +8747,7 @@ static Error define_builtin_compile_vars(CodeGen *g) {...@@ -8614,7 +8747,7 @@ static Error define_builtin_compile_vars(CodeGen *g) {
8614 cache_int(&cache_hash, g->zig_target->os);8747 cache_int(&cache_hash, g->zig_target->os);
8615 cache_int(&cache_hash, g->zig_target->abi);8748 cache_int(&cache_hash, g->zig_target->abi);
8616 if (g->zig_target->cache_hash != nullptr) {8749 if (g->zig_target->cache_hash != nullptr) {
8617 cache_str(&cache_hash, g->zig_target->cache_hash);8750 cache_mem(&cache_hash, g->zig_target->cache_hash, g->zig_target->cache_hash_len);
8618 }8751 }
8619 if (g->zig_target->glibc_or_darwin_version != nullptr) {8752 if (g->zig_target->glibc_or_darwin_version != nullptr) {
8620 cache_int(&cache_hash, g->zig_target->glibc_or_darwin_version->major);8753 cache_int(&cache_hash, g->zig_target->glibc_or_darwin_version->major);
...@@ -10259,7 +10392,7 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {...@@ -10259,7 +10392,7 @@ static Error check_cache(CodeGen *g, Buf *manifest_dir, Buf *digest) {
10259 cache_int(ch, g->zig_target->os);10392 cache_int(ch, g->zig_target->os);
10260 cache_int(ch, g->zig_target->abi);10393 cache_int(ch, g->zig_target->abi);
10261 if (g->zig_target->cache_hash != nullptr) {10394 if (g->zig_target->cache_hash != nullptr) {
10262 cache_str(ch, g->zig_target->cache_hash);10395 cache_mem(ch, g->zig_target->cache_hash, g->zig_target->cache_hash_len);
10263 }10396 }
10264 if (g->zig_target->glibc_or_darwin_version != nullptr) {10397 if (g->zig_target->glibc_or_darwin_version != nullptr) {
10265 cache_int(ch, g->zig_target->glibc_or_darwin_version->major);10398 cache_int(ch, g->zig_target->glibc_or_darwin_version->major);
src/install_files.h+79-81
...@@ -80,7 +80,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -80,7 +80,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
80"musl/src/crypt/crypt.c",80"musl/src/crypt/crypt.c",
81"musl/src/crypt/crypt_blowfish.c",81"musl/src/crypt/crypt_blowfish.c",
82"musl/src/crypt/crypt_des.c",82"musl/src/crypt/crypt_des.c",
83"musl/src/crypt/crypt_des.h",
84"musl/src/crypt/crypt_md5.c",83"musl/src/crypt/crypt_md5.c",
85"musl/src/crypt/crypt_r.c",84"musl/src/crypt/crypt_r.c",
86"musl/src/crypt/crypt_sha256.c",85"musl/src/crypt/crypt_sha256.c",
...@@ -90,7 +89,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -90,7 +89,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
90"musl/src/ctype/__ctype_get_mb_cur_max.c",89"musl/src/ctype/__ctype_get_mb_cur_max.c",
91"musl/src/ctype/__ctype_tolower_loc.c",90"musl/src/ctype/__ctype_tolower_loc.c",
92"musl/src/ctype/__ctype_toupper_loc.c",91"musl/src/ctype/__ctype_toupper_loc.c",
93"musl/src/ctype/alpha.h",
94"musl/src/ctype/isalnum.c",92"musl/src/ctype/isalnum.c",
95"musl/src/ctype/isalpha.c",93"musl/src/ctype/isalpha.c",
96"musl/src/ctype/isascii.c",94"musl/src/ctype/isascii.c",
...@@ -117,8 +115,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -117,8 +115,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
117"musl/src/ctype/iswupper.c",115"musl/src/ctype/iswupper.c",
118"musl/src/ctype/iswxdigit.c",116"musl/src/ctype/iswxdigit.c",
119"musl/src/ctype/isxdigit.c",117"musl/src/ctype/isxdigit.c",
120"musl/src/ctype/nonspacing.h",
121"musl/src/ctype/punct.h",
122"musl/src/ctype/toascii.c",118"musl/src/ctype/toascii.c",
123"musl/src/ctype/tolower.c",119"musl/src/ctype/tolower.c",
124"musl/src/ctype/toupper.c",120"musl/src/ctype/toupper.c",
...@@ -126,8 +122,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -126,8 +122,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
126"musl/src/ctype/wcswidth.c",122"musl/src/ctype/wcswidth.c",
127"musl/src/ctype/wctrans.c",123"musl/src/ctype/wctrans.c",
128"musl/src/ctype/wcwidth.c",124"musl/src/ctype/wcwidth.c",
129"musl/src/ctype/wide.h",
130"musl/src/dirent/__dirent.h",
131"musl/src/dirent/alphasort.c",125"musl/src/dirent/alphasort.c",
132"musl/src/dirent/closedir.c",126"musl/src/dirent/closedir.c",
133"musl/src/dirent/dirfd.c",127"musl/src/dirent/dirfd.c",
...@@ -152,7 +146,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -152,7 +146,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
152"musl/src/env/setenv.c",146"musl/src/env/setenv.c",
153"musl/src/env/unsetenv.c",147"musl/src/env/unsetenv.c",
154"musl/src/errno/__errno_location.c",148"musl/src/errno/__errno_location.c",
155"musl/src/errno/__strerror.h",
156"musl/src/errno/strerror.c",149"musl/src/errno/strerror.c",
157"musl/src/exit/_Exit.c",150"musl/src/exit/_Exit.c",
158"musl/src/exit/abort.c",151"musl/src/exit/abort.c",
...@@ -196,55 +189,18 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -196,55 +189,18 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
196"musl/src/fenv/sh/fenv.S",189"musl/src/fenv/sh/fenv.S",
197"musl/src/fenv/x32/fenv.s",190"musl/src/fenv/x32/fenv.s",
198"musl/src/fenv/x86_64/fenv.s",191"musl/src/fenv/x86_64/fenv.s",
199"musl/src/include/arpa/inet.h",
200"musl/src/include/crypt.h",
201"musl/src/include/errno.h",
202"musl/src/include/features.h",
203"musl/src/include/langinfo.h",
204"musl/src/include/pthread.h",
205"musl/src/include/resolv.h",
206"musl/src/include/signal.h",
207"musl/src/include/stdio.h",
208"musl/src/include/stdlib.h",
209"musl/src/include/string.h",
210"musl/src/include/sys/auxv.h",
211"musl/src/include/sys/membarrier.h",
212"musl/src/include/sys/mman.h",
213"musl/src/include/sys/sysinfo.h",
214"musl/src/include/sys/time.h",
215"musl/src/include/time.h",
216"musl/src/include/unistd.h",
217"musl/src/include/wchar.h",
218"musl/src/internal/atomic.h",
219"musl/src/internal/complex_impl.h",
220"musl/src/internal/defsysinfo.c",192"musl/src/internal/defsysinfo.c",
221"musl/src/internal/dynlink.h",
222"musl/src/internal/fdpic_crt.h",
223"musl/src/internal/floatscan.c",193"musl/src/internal/floatscan.c",
224"musl/src/internal/floatscan.h",
225"musl/src/internal/futex.h",
226"musl/src/internal/i386/defsysinfo.s",194"musl/src/internal/i386/defsysinfo.s",
227"musl/src/internal/intscan.c",195"musl/src/internal/intscan.c",
228"musl/src/internal/intscan.h",
229"musl/src/internal/ksigaction.h",
230"musl/src/internal/libc.c",196"musl/src/internal/libc.c",
231"musl/src/internal/libc.h",
232"musl/src/internal/libm.h",
233"musl/src/internal/locale_impl.h",
234"musl/src/internal/lock.h",
235"musl/src/internal/malloc_impl.h",
236"musl/src/internal/procfdname.c",197"musl/src/internal/procfdname.c",
237"musl/src/internal/pthread_impl.h",
238"musl/src/internal/sh/__shcall.c",198"musl/src/internal/sh/__shcall.c",
239"musl/src/internal/shgetc.c",199"musl/src/internal/shgetc.c",
240"musl/src/internal/shgetc.h",
241"musl/src/internal/stdio_impl.h",
242"musl/src/internal/syscall.h",
243"musl/src/internal/syscall_ret.c",200"musl/src/internal/syscall_ret.c",
244"musl/src/internal/vdso.c",201"musl/src/internal/vdso.c",
245"musl/src/internal/version.c",202"musl/src/internal/version.c",
246"musl/src/ipc/ftok.c",203"musl/src/ipc/ftok.c",
247"musl/src/ipc/ipc.h",
248"musl/src/ipc/msgctl.c",204"musl/src/ipc/msgctl.c",
249"musl/src/ipc/msgget.c",205"musl/src/ipc/msgget.c",
250"musl/src/ipc/msgrcv.c",206"musl/src/ipc/msgrcv.c",
...@@ -261,6 +217,7 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -261,6 +217,7 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
261"musl/src/ldso/aarch64/dlsym.s",217"musl/src/ldso/aarch64/dlsym.s",
262"musl/src/ldso/aarch64/tlsdesc.s",218"musl/src/ldso/aarch64/tlsdesc.s",
263"musl/src/ldso/arm/dlsym.s",219"musl/src/ldso/arm/dlsym.s",
220"musl/src/ldso/arm/dlsym_time64.S",
264"musl/src/ldso/arm/find_exidx.c",221"musl/src/ldso/arm/find_exidx.c",
265"musl/src/ldso/arm/tlsdesc.S",222"musl/src/ldso/arm/tlsdesc.S",
266"musl/src/ldso/dl_iterate_phdr.c",223"musl/src/ldso/dl_iterate_phdr.c",
...@@ -271,18 +228,26 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -271,18 +228,26 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
271"musl/src/ldso/dlopen.c",228"musl/src/ldso/dlopen.c",
272"musl/src/ldso/dlsym.c",229"musl/src/ldso/dlsym.c",
273"musl/src/ldso/i386/dlsym.s",230"musl/src/ldso/i386/dlsym.s",
231"musl/src/ldso/i386/dlsym_time64.S",
274"musl/src/ldso/i386/tlsdesc.s",232"musl/src/ldso/i386/tlsdesc.s",
275"musl/src/ldso/m68k/dlsym.s",233"musl/src/ldso/m68k/dlsym.s",
234"musl/src/ldso/m68k/dlsym_time64.S",
276"musl/src/ldso/microblaze/dlsym.s",235"musl/src/ldso/microblaze/dlsym.s",
236"musl/src/ldso/microblaze/dlsym_time64.S",
277"musl/src/ldso/mips/dlsym.s",237"musl/src/ldso/mips/dlsym.s",
238"musl/src/ldso/mips/dlsym_time64.S",
278"musl/src/ldso/mips64/dlsym.s",239"musl/src/ldso/mips64/dlsym.s",
279"musl/src/ldso/mipsn32/dlsym.s",240"musl/src/ldso/mipsn32/dlsym.s",
241"musl/src/ldso/mipsn32/dlsym_time64.S",
280"musl/src/ldso/or1k/dlsym.s",242"musl/src/ldso/or1k/dlsym.s",
243"musl/src/ldso/or1k/dlsym_time64.S",
281"musl/src/ldso/powerpc/dlsym.s",244"musl/src/ldso/powerpc/dlsym.s",
245"musl/src/ldso/powerpc/dlsym_time64.S",
282"musl/src/ldso/powerpc64/dlsym.s",246"musl/src/ldso/powerpc64/dlsym.s",
283"musl/src/ldso/riscv64/dlsym.s",247"musl/src/ldso/riscv64/dlsym.s",
284"musl/src/ldso/s390x/dlsym.s",248"musl/src/ldso/s390x/dlsym.s",
285"musl/src/ldso/sh/dlsym.s",249"musl/src/ldso/sh/dlsym.s",
250"musl/src/ldso/sh/dlsym_time64.S",
286"musl/src/ldso/tlsdesc.c",251"musl/src/ldso/tlsdesc.c",
287"musl/src/ldso/x32/dlsym.s",252"musl/src/ldso/x32/dlsym.s",
288"musl/src/ldso/x86_64/dlsym.s",253"musl/src/ldso/x86_64/dlsym.s",
...@@ -369,30 +334,21 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -369,30 +334,21 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
369"musl/src/linux/xattr.c",334"musl/src/linux/xattr.c",
370"musl/src/locale/__lctrans.c",335"musl/src/locale/__lctrans.c",
371"musl/src/locale/__mo_lookup.c",336"musl/src/locale/__mo_lookup.c",
372"musl/src/locale/big5.h",
373"musl/src/locale/bind_textdomain_codeset.c",337"musl/src/locale/bind_textdomain_codeset.c",
374"musl/src/locale/c_locale.c",338"musl/src/locale/c_locale.c",
375"musl/src/locale/catclose.c",339"musl/src/locale/catclose.c",
376"musl/src/locale/catgets.c",340"musl/src/locale/catgets.c",
377"musl/src/locale/catopen.c",341"musl/src/locale/catopen.c",
378"musl/src/locale/codepages.h",
379"musl/src/locale/dcngettext.c",342"musl/src/locale/dcngettext.c",
380"musl/src/locale/duplocale.c",343"musl/src/locale/duplocale.c",
381"musl/src/locale/freelocale.c",344"musl/src/locale/freelocale.c",
382"musl/src/locale/gb18030.h",
383"musl/src/locale/hkscs.h",
384"musl/src/locale/iconv.c",345"musl/src/locale/iconv.c",
385"musl/src/locale/iconv_close.c",346"musl/src/locale/iconv_close.c",
386"musl/src/locale/jis0208.h",
387"musl/src/locale/ksc.h",
388"musl/src/locale/langinfo.c",347"musl/src/locale/langinfo.c",
389"musl/src/locale/legacychars.h",
390"musl/src/locale/locale_map.c",348"musl/src/locale/locale_map.c",
391"musl/src/locale/localeconv.c",349"musl/src/locale/localeconv.c",
392"musl/src/locale/newlocale.c",350"musl/src/locale/newlocale.c",
393"musl/src/locale/pleval.c",351"musl/src/locale/pleval.c",
394"musl/src/locale/pleval.h",
395"musl/src/locale/revjis.h",
396"musl/src/locale/setlocale.c",352"musl/src/locale/setlocale.c",
397"musl/src/locale/strcoll.c",353"musl/src/locale/strcoll.c",
398"musl/src/locale/strfmon.c",354"musl/src/locale/strfmon.c",
...@@ -401,7 +357,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -401,7 +357,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
401"musl/src/locale/uselocale.c",357"musl/src/locale/uselocale.c",
402"musl/src/locale/wcscoll.c",358"musl/src/locale/wcscoll.c",
403"musl/src/locale/wcsxfrm.c",359"musl/src/locale/wcsxfrm.c",
404"musl/src/malloc/DESIGN",
405"musl/src/malloc/aligned_alloc.c",360"musl/src/malloc/aligned_alloc.c",
406"musl/src/malloc/expand_heap.c",361"musl/src/malloc/expand_heap.c",
407"musl/src/malloc/lite_malloc.c",362"musl/src/malloc/lite_malloc.c",
...@@ -418,7 +373,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -418,7 +373,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
418"musl/src/math/__fpclassifyf.c",373"musl/src/math/__fpclassifyf.c",
419"musl/src/math/__fpclassifyl.c",374"musl/src/math/__fpclassifyl.c",
420"musl/src/math/__invtrigl.c",375"musl/src/math/__invtrigl.c",
421"musl/src/math/__invtrigl.h",
422"musl/src/math/__math_divzero.c",376"musl/src/math/__math_divzero.c",
423"musl/src/math/__math_divzerof.c",377"musl/src/math/__math_divzerof.c",
424"musl/src/math/__math_invalid.c",378"musl/src/math/__math_invalid.c",
...@@ -525,10 +479,8 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -525,10 +479,8 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
525"musl/src/math/exp2.c",479"musl/src/math/exp2.c",
526"musl/src/math/exp2f.c",480"musl/src/math/exp2f.c",
527"musl/src/math/exp2f_data.c",481"musl/src/math/exp2f_data.c",
528"musl/src/math/exp2f_data.h",
529"musl/src/math/exp2l.c",482"musl/src/math/exp2l.c",
530"musl/src/math/exp_data.c",483"musl/src/math/exp_data.c",
531"musl/src/math/exp_data.h",
532"musl/src/math/expf.c",484"musl/src/math/expf.c",
533"musl/src/math/expl.c",485"musl/src/math/expl.c",
534"musl/src/math/expm1.c",486"musl/src/math/expm1.c",
...@@ -579,14 +531,9 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -579,14 +531,9 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
579"musl/src/math/i386/ceil.s",531"musl/src/math/i386/ceil.s",
580"musl/src/math/i386/ceilf.s",532"musl/src/math/i386/ceilf.s",
581"musl/src/math/i386/ceill.s",533"musl/src/math/i386/ceill.s",
582"musl/src/math/i386/exp.s",
583"musl/src/math/i386/exp2.s",
584"musl/src/math/i386/exp2f.s",
585"musl/src/math/i386/exp2l.s",534"musl/src/math/i386/exp2l.s",
586"musl/src/math/i386/expf.s",535"musl/src/math/i386/exp_ld.s",
587"musl/src/math/i386/expl.s",536"musl/src/math/i386/expl.s",
588"musl/src/math/i386/expm1.s",
589"musl/src/math/i386/expm1f.s",
590"musl/src/math/i386/expm1l.s",537"musl/src/math/i386/expm1l.s",
591"musl/src/math/i386/fabs.s",538"musl/src/math/i386/fabs.s",
592"musl/src/math/i386/fabsf.s",539"musl/src/math/i386/fabsf.s",
...@@ -673,19 +620,15 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -673,19 +620,15 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
673"musl/src/math/log1pl.c",620"musl/src/math/log1pl.c",
674"musl/src/math/log2.c",621"musl/src/math/log2.c",
675"musl/src/math/log2_data.c",622"musl/src/math/log2_data.c",
676"musl/src/math/log2_data.h",
677"musl/src/math/log2f.c",623"musl/src/math/log2f.c",
678"musl/src/math/log2f_data.c",624"musl/src/math/log2f_data.c",
679"musl/src/math/log2f_data.h",
680"musl/src/math/log2l.c",625"musl/src/math/log2l.c",
681"musl/src/math/log_data.c",626"musl/src/math/log_data.c",
682"musl/src/math/log_data.h",
683"musl/src/math/logb.c",627"musl/src/math/logb.c",
684"musl/src/math/logbf.c",628"musl/src/math/logbf.c",
685"musl/src/math/logbl.c",629"musl/src/math/logbl.c",
686"musl/src/math/logf.c",630"musl/src/math/logf.c",
687"musl/src/math/logf_data.c",631"musl/src/math/logf_data.c",
688"musl/src/math/logf_data.h",
689"musl/src/math/logl.c",632"musl/src/math/logl.c",
690"musl/src/math/lrint.c",633"musl/src/math/lrint.c",
691"musl/src/math/lrintf.c",634"musl/src/math/lrintf.c",
...@@ -693,6 +636,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -693,6 +636,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
693"musl/src/math/lround.c",636"musl/src/math/lround.c",
694"musl/src/math/lroundf.c",637"musl/src/math/lroundf.c",
695"musl/src/math/lroundl.c",638"musl/src/math/lroundl.c",
639"musl/src/math/mips/fabs.c",
640"musl/src/math/mips/fabsf.c",
641"musl/src/math/mips/sqrt.c",
642"musl/src/math/mips/sqrtf.c",
696"musl/src/math/modf.c",643"musl/src/math/modf.c",
697"musl/src/math/modff.c",644"musl/src/math/modff.c",
698"musl/src/math/modfl.c",645"musl/src/math/modfl.c",
...@@ -710,7 +657,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -710,7 +657,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
710"musl/src/math/nexttowardl.c",657"musl/src/math/nexttowardl.c",
711"musl/src/math/pow.c",658"musl/src/math/pow.c",
712"musl/src/math/pow_data.c",659"musl/src/math/pow_data.c",
713"musl/src/math/pow_data.h",
714"musl/src/math/powerpc/fabs.c",660"musl/src/math/powerpc/fabs.c",
715"musl/src/math/powerpc/fabsf.c",661"musl/src/math/powerpc/fabsf.c",
716"musl/src/math/powerpc/fma.c",662"musl/src/math/powerpc/fma.c",
...@@ -741,7 +687,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -741,7 +687,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
741"musl/src/math/powerpc64/truncf.c",687"musl/src/math/powerpc64/truncf.c",
742"musl/src/math/powf.c",688"musl/src/math/powf.c",
743"musl/src/math/powf_data.c",689"musl/src/math/powf_data.c",
744"musl/src/math/powf_data.h",
745"musl/src/math/powl.c",690"musl/src/math/powl.c",
746"musl/src/math/remainder.c",691"musl/src/math/remainder.c",
747"musl/src/math/remainderf.c",692"musl/src/math/remainderf.c",
...@@ -958,7 +903,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -958,7 +903,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
958"musl/src/multibyte/c16rtomb.c",903"musl/src/multibyte/c16rtomb.c",
959"musl/src/multibyte/c32rtomb.c",904"musl/src/multibyte/c32rtomb.c",
960"musl/src/multibyte/internal.c",905"musl/src/multibyte/internal.c",
961"musl/src/multibyte/internal.h",
962"musl/src/multibyte/mblen.c",906"musl/src/multibyte/mblen.c",
963"musl/src/multibyte/mbrlen.c",907"musl/src/multibyte/mbrlen.c",
964"musl/src/multibyte/mbrtoc16.c",908"musl/src/multibyte/mbrtoc16.c",
...@@ -1021,12 +965,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1021,12 +965,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1021"musl/src/network/inet_ntop.c",965"musl/src/network/inet_ntop.c",
1022"musl/src/network/inet_pton.c",966"musl/src/network/inet_pton.c",
1023"musl/src/network/listen.c",967"musl/src/network/listen.c",
1024"musl/src/network/lookup.h",
1025"musl/src/network/lookup_ipliteral.c",968"musl/src/network/lookup_ipliteral.c",
1026"musl/src/network/lookup_name.c",969"musl/src/network/lookup_name.c",
1027"musl/src/network/lookup_serv.c",970"musl/src/network/lookup_serv.c",
1028"musl/src/network/netlink.c",971"musl/src/network/netlink.c",
1029"musl/src/network/netlink.h",
1030"musl/src/network/netname.c",972"musl/src/network/netname.c",
1031"musl/src/network/ns_parse.c",973"musl/src/network/ns_parse.c",
1032"musl/src/network/ntohl.c",974"musl/src/network/ntohl.c",
...@@ -1070,12 +1012,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1070,12 +1012,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1070"musl/src/passwd/getspnam.c",1012"musl/src/passwd/getspnam.c",
1071"musl/src/passwd/getspnam_r.c",1013"musl/src/passwd/getspnam_r.c",
1072"musl/src/passwd/lckpwdf.c",1014"musl/src/passwd/lckpwdf.c",
1073"musl/src/passwd/nscd.h",
1074"musl/src/passwd/nscd_query.c",1015"musl/src/passwd/nscd_query.c",
1075"musl/src/passwd/putgrent.c",1016"musl/src/passwd/putgrent.c",
1076"musl/src/passwd/putpwent.c",1017"musl/src/passwd/putpwent.c",
1077"musl/src/passwd/putspent.c",1018"musl/src/passwd/putspent.c",
1078"musl/src/passwd/pwf.h",
1079"musl/src/prng/__rand48_step.c",1019"musl/src/prng/__rand48_step.c",
1080"musl/src/prng/__seed48.c",1020"musl/src/prng/__seed48.c",
1081"musl/src/prng/drand48.c",1021"musl/src/prng/drand48.c",
...@@ -1083,7 +1023,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1083,7 +1023,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1083"musl/src/prng/lrand48.c",1023"musl/src/prng/lrand48.c",
1084"musl/src/prng/mrand48.c",1024"musl/src/prng/mrand48.c",
1085"musl/src/prng/rand.c",1025"musl/src/prng/rand.c",
1086"musl/src/prng/rand48.h",
1087"musl/src/prng/rand_r.c",1026"musl/src/prng/rand_r.c",
1088"musl/src/prng/random.c",1027"musl/src/prng/random.c",
1089"musl/src/prng/seed48.c",1028"musl/src/prng/seed48.c",
...@@ -1095,7 +1034,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1095,7 +1034,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1095"musl/src/process/execv.c",1034"musl/src/process/execv.c",
1096"musl/src/process/execve.c",1035"musl/src/process/execve.c",
1097"musl/src/process/execvp.c",1036"musl/src/process/execvp.c",
1098"musl/src/process/fdop.h",
1099"musl/src/process/fexecve.c",1037"musl/src/process/fexecve.c",
1100"musl/src/process/fork.c",1038"musl/src/process/fork.c",
1101"musl/src/process/i386/vfork.s",1039"musl/src/process/i386/vfork.s",
...@@ -1134,7 +1072,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1134,7 +1072,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1134"musl/src/regex/regerror.c",1072"musl/src/regex/regerror.c",
1135"musl/src/regex/regexec.c",1073"musl/src/regex/regexec.c",
1136"musl/src/regex/tre-mem.c",1074"musl/src/regex/tre-mem.c",
1137"musl/src/regex/tre.h",
1138"musl/src/sched/affinity.c",1075"musl/src/sched/affinity.c",
1139"musl/src/sched/sched_cpucount.c",1076"musl/src/sched/sched_cpucount.c",
1140"musl/src/sched/sched_get_priority_max.c",1077"musl/src/sched/sched_get_priority_max.c",
...@@ -1152,7 +1089,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1152,7 +1089,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1152"musl/src/search/tdestroy.c",1089"musl/src/search/tdestroy.c",
1153"musl/src/search/tfind.c",1090"musl/src/search/tfind.c",
1154"musl/src/search/tsearch.c",1091"musl/src/search/tsearch.c",
1155"musl/src/search/tsearch.h",
1156"musl/src/search/twalk.c",1092"musl/src/search/twalk.c",
1157"musl/src/select/poll.c",1093"musl/src/select/poll.c",
1158"musl/src/select/pselect.c",1094"musl/src/select/pselect.c",
...@@ -1335,7 +1271,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1335,7 +1271,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1335"musl/src/stdio/fwrite.c",1271"musl/src/stdio/fwrite.c",
1336"musl/src/stdio/fwscanf.c",1272"musl/src/stdio/fwscanf.c",
1337"musl/src/stdio/getc.c",1273"musl/src/stdio/getc.c",
1338"musl/src/stdio/getc.h",
1339"musl/src/stdio/getc_unlocked.c",1274"musl/src/stdio/getc_unlocked.c",
1340"musl/src/stdio/getchar.c",1275"musl/src/stdio/getchar.c",
1341"musl/src/stdio/getchar_unlocked.c",1276"musl/src/stdio/getchar_unlocked.c",
...@@ -1354,7 +1289,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1354,7 +1289,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1354"musl/src/stdio/popen.c",1289"musl/src/stdio/popen.c",
1355"musl/src/stdio/printf.c",1290"musl/src/stdio/printf.c",
1356"musl/src/stdio/putc.c",1291"musl/src/stdio/putc.c",
1357"musl/src/stdio/putc.h",
1358"musl/src/stdio/putc_unlocked.c",1292"musl/src/stdio/putc_unlocked.c",
1359"musl/src/stdio/putchar.c",1293"musl/src/stdio/putchar.c",
1360"musl/src/stdio/putchar_unlocked.c",1294"musl/src/stdio/putchar_unlocked.c",
...@@ -1746,7 +1680,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1746,7 +1680,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1746"musl/src/time/strftime.c",1680"musl/src/time/strftime.c",
1747"musl/src/time/strptime.c",1681"musl/src/time/strptime.c",
1748"musl/src/time/time.c",1682"musl/src/time/time.c",
1749"musl/src/time/time_impl.h",
1750"musl/src/time/timegm.c",1683"musl/src/time/timegm.c",
1751"musl/src/time/timer_create.c",1684"musl/src/time/timer_create.c",
1752"musl/src/time/timer_delete.c",1685"musl/src/time/timer_delete.c",
...@@ -1843,4 +1776,69 @@ static const char *ZIG_MUSL_SRC_FILES[] = {...@@ -1843,4 +1776,69 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1843"musl/src/unistd/writev.c",1776"musl/src/unistd/writev.c",
1844"musl/src/unistd/x32/lseek.c",1777"musl/src/unistd/x32/lseek.c",
1845};1778};
1779static const char *ZIG_MUSL_COMPAT_TIME32_FILES[] = {
1780"musl/compat/time32/__xstat.c",
1781"musl/compat/time32/adjtime32.c",
1782"musl/compat/time32/adjtimex_time32.c",
1783"musl/compat/time32/aio_suspend_time32.c",
1784"musl/compat/time32/clock_adjtime32.c",
1785"musl/compat/time32/clock_getres_time32.c",
1786"musl/compat/time32/clock_gettime32.c",
1787"musl/compat/time32/clock_nanosleep_time32.c",
1788"musl/compat/time32/clock_settime32.c",
1789"musl/compat/time32/cnd_timedwait_time32.c",
1790"musl/compat/time32/ctime32.c",
1791"musl/compat/time32/ctime32_r.c",
1792"musl/compat/time32/difftime32.c",
1793"musl/compat/time32/fstat_time32.c",
1794"musl/compat/time32/fstatat_time32.c",
1795"musl/compat/time32/ftime32.c",
1796"musl/compat/time32/futimens_time32.c",
1797"musl/compat/time32/futimes_time32.c",
1798"musl/compat/time32/futimesat_time32.c",
1799"musl/compat/time32/getitimer_time32.c",
1800"musl/compat/time32/getrusage_time32.c",
1801"musl/compat/time32/gettimeofday_time32.c",
1802"musl/compat/time32/gmtime32.c",
1803"musl/compat/time32/gmtime32_r.c",
1804"musl/compat/time32/localtime32.c",
1805"musl/compat/time32/localtime32_r.c",
1806"musl/compat/time32/lstat_time32.c",
1807"musl/compat/time32/lutimes_time32.c",
1808"musl/compat/time32/mktime32.c",
1809"musl/compat/time32/mq_timedreceive_time32.c",
1810"musl/compat/time32/mq_timedsend_time32.c",
1811"musl/compat/time32/mtx_timedlock_time32.c",
1812"musl/compat/time32/nanosleep_time32.c",
1813"musl/compat/time32/ppoll_time32.c",
1814"musl/compat/time32/pselect_time32.c",
1815"musl/compat/time32/pthread_cond_timedwait_time32.c",
1816"musl/compat/time32/pthread_mutex_timedlock_time32.c",
1817"musl/compat/time32/pthread_rwlock_timedrdlock_time32.c",
1818"musl/compat/time32/pthread_rwlock_timedwrlock_time32.c",
1819"musl/compat/time32/pthread_timedjoin_np_time32.c",
1820"musl/compat/time32/recvmmsg_time32.c",
1821"musl/compat/time32/sched_rr_get_interval_time32.c",
1822"musl/compat/time32/select_time32.c",
1823"musl/compat/time32/sem_timedwait_time32.c",
1824"musl/compat/time32/semtimedop_time32.c",
1825"musl/compat/time32/setitimer_time32.c",
1826"musl/compat/time32/settimeofday_time32.c",
1827"musl/compat/time32/sigtimedwait_time32.c",
1828"musl/compat/time32/stat_time32.c",
1829"musl/compat/time32/stime32.c",
1830"musl/compat/time32/thrd_sleep_time32.c",
1831"musl/compat/time32/time32.c",
1832"musl/compat/time32/time32gm.c",
1833"musl/compat/time32/timer_gettime32.c",
1834"musl/compat/time32/timer_settime32.c",
1835"musl/compat/time32/timerfd_gettime32.c",
1836"musl/compat/time32/timerfd_settime32.c",
1837"musl/compat/time32/timespec_get_time32.c",
1838"musl/compat/time32/utime_time32.c",
1839"musl/compat/time32/utimensat_time32.c",
1840"musl/compat/time32/utimes_time32.c",
1841"musl/compat/time32/wait3_time32.c",
1842"musl/compat/time32/wait4_time32.c",
1843};
1846#endif1844#endif
src/ir.cpp+299-99
...@@ -4978,6 +4978,7 @@ static void ir_count_defers(IrBuilderSrc *irb, Scope *inner_scope, Scope *outer_...@@ -4978,6 +4978,7 @@ static void ir_count_defers(IrBuilderSrc *irb, Scope *inner_scope, Scope *outer_
4978 case ScopeIdLoop:4978 case ScopeIdLoop:
4979 case ScopeIdSuspend:4979 case ScopeIdSuspend:
4980 case ScopeIdCompTime:4980 case ScopeIdCompTime:
4981 case ScopeIdNoAsync:
4981 case ScopeIdRuntime:4982 case ScopeIdRuntime:
4982 case ScopeIdTypeOf:4983 case ScopeIdTypeOf:
4983 case ScopeIdExpr:4984 case ScopeIdExpr:
...@@ -5033,6 +5034,7 @@ static bool ir_gen_defers_for_block(IrBuilderSrc *irb, Scope *inner_scope, Scope...@@ -5033,6 +5034,7 @@ static bool ir_gen_defers_for_block(IrBuilderSrc *irb, Scope *inner_scope, Scope
5033 case ScopeIdLoop:5034 case ScopeIdLoop:
5034 case ScopeIdSuspend:5035 case ScopeIdSuspend:
5035 case ScopeIdCompTime:5036 case ScopeIdCompTime:
5037 case ScopeIdNoAsync:
5036 case ScopeIdRuntime:5038 case ScopeIdRuntime:
5037 case ScopeIdTypeOf:5039 case ScopeIdTypeOf:
5038 case ScopeIdExpr:5040 case ScopeIdExpr:
...@@ -5910,10 +5912,18 @@ static IrInstSrc *ir_gen_array_access(IrBuilderSrc *irb, Scope *scope, AstNode *...@@ -5910,10 +5912,18 @@ static IrInstSrc *ir_gen_array_access(IrBuilderSrc *irb, Scope *scope, AstNode *
5910 if (array_ref_instruction == irb->codegen->invalid_inst_src)5912 if (array_ref_instruction == irb->codegen->invalid_inst_src)
5911 return array_ref_instruction;5913 return array_ref_instruction;
59125914
5915 // Create an usize-typed result location to hold the subscript value, this
5916 // makes it possible for the compiler to infer the subscript expression type
5917 // if needed
5918 IrInstSrc *usize_type_inst = ir_build_const_type(irb, scope, node, irb->codegen->builtin_types.entry_usize);
5919 ResultLocCast *result_loc_cast = ir_build_cast_result_loc(irb, usize_type_inst, no_result_loc());
5920
5913 AstNode *subscript_node = node->data.array_access_expr.subscript;5921 AstNode *subscript_node = node->data.array_access_expr.subscript;
5914 IrInstSrc *subscript_instruction = ir_gen_node(irb, subscript_node, scope);5922 IrInstSrc *subscript_value = ir_gen_node_extra(irb, subscript_node, scope, LValNone, &result_loc_cast->base);
5915 if (subscript_instruction == irb->codegen->invalid_inst_src)5923 if (subscript_value == irb->codegen->invalid_inst_src)
5916 return subscript_instruction;5924 return irb->codegen->invalid_inst_src;
5925
5926 IrInstSrc *subscript_instruction = ir_build_implicit_cast(irb, scope, subscript_node, subscript_value, result_loc_cast);
59175927
5918 IrInstSrc *ptr_instruction = ir_build_elem_ptr(irb, scope, node, array_ref_instruction,5928 IrInstSrc *ptr_instruction = ir_build_elem_ptr(irb, scope, node, array_ref_instruction,
5919 subscript_instruction, true, PtrLenSingle, nullptr);5929 subscript_instruction, true, PtrLenSingle, nullptr);
...@@ -7266,6 +7276,18 @@ static IrInstSrc *ir_gen_builtin_fn_call(IrBuilderSrc *irb, Scope *scope, AstNod...@@ -7266,6 +7276,18 @@ static IrInstSrc *ir_gen_builtin_fn_call(IrBuilderSrc *irb, Scope *scope, AstNod
7266 zig_unreachable();7276 zig_unreachable();
7267}7277}
72687278
7279static ScopeNoAsync *get_scope_noasync(Scope *scope) {
7280 while (scope) {
7281 if (scope->id == ScopeIdNoAsync)
7282 return (ScopeNoAsync *)scope;
7283 if (scope->id == ScopeIdFnDef)
7284 return nullptr;
7285
7286 scope = scope->parent;
7287 }
7288 return nullptr;
7289}
7290
7269static IrInstSrc *ir_gen_fn_call(IrBuilderSrc *irb, Scope *scope, AstNode *node, LVal lval,7291static IrInstSrc *ir_gen_fn_call(IrBuilderSrc *irb, Scope *scope, AstNode *node, LVal lval,
7270 ResultLoc *result_loc)7292 ResultLoc *result_loc)
7271{7293{
...@@ -7274,8 +7296,19 @@ static IrInstSrc *ir_gen_fn_call(IrBuilderSrc *irb, Scope *scope, AstNode *node,...@@ -7274,8 +7296,19 @@ static IrInstSrc *ir_gen_fn_call(IrBuilderSrc *irb, Scope *scope, AstNode *node,
7274 if (node->data.fn_call_expr.modifier == CallModifierBuiltin)7296 if (node->data.fn_call_expr.modifier == CallModifierBuiltin)
7275 return ir_gen_builtin_fn_call(irb, scope, node, lval, result_loc);7297 return ir_gen_builtin_fn_call(irb, scope, node, lval, result_loc);
72767298
7299 bool is_noasync = get_scope_noasync(scope) != nullptr;
7300 CallModifier modifier = node->data.fn_call_expr.modifier;
7301 if (is_noasync) {
7302 if (modifier == CallModifierAsync) {
7303 add_node_error(irb->codegen, node,
7304 buf_sprintf("async call in noasync scope"));
7305 return irb->codegen->invalid_inst_src;
7306 }
7307 modifier = CallModifierNoAsync;
7308 }
7309
7277 AstNode *fn_ref_node = node->data.fn_call_expr.fn_ref_expr;7310 AstNode *fn_ref_node = node->data.fn_call_expr.fn_ref_expr;
7278 return ir_gen_fn_call_with_args(irb, scope, node, fn_ref_node, node->data.fn_call_expr.modifier,7311 return ir_gen_fn_call_with_args(irb, scope, node, fn_ref_node, modifier,
7279 nullptr, node->data.fn_call_expr.params.items, node->data.fn_call_expr.params.length, lval, result_loc);7312 nullptr, node->data.fn_call_expr.params.items, node->data.fn_call_expr.params.length, lval, result_loc);
7280}7313}
72817314
...@@ -8981,7 +9014,7 @@ static IrInstSrc *ir_gen_switch_expr(IrBuilderSrc *irb, Scope *scope, AstNode *n...@@ -8981,7 +9014,7 @@ static IrInstSrc *ir_gen_switch_expr(IrBuilderSrc *irb, Scope *scope, AstNode *n
8981 return irb->codegen->invalid_inst_src;9014 return irb->codegen->invalid_inst_src;
8982 }9015 }
8983 else_prong = prong_node;9016 else_prong = prong_node;
8984 } else if (prong_item_count == 1 && 9017 } else if (prong_item_count == 1 &&
8985 prong_node->data.switch_prong.items.at(0)->type == NodeTypeSymbol &&9018 prong_node->data.switch_prong.items.at(0)->type == NodeTypeSymbol &&
8986 buf_eql_str(prong_node->data.switch_prong.items.at(0)->data.symbol_expr.symbol, "_")) {9019 buf_eql_str(prong_node->data.switch_prong.items.at(0)->data.symbol_expr.symbol, "_")) {
8987 if (underscore_prong) {9020 if (underscore_prong) {
...@@ -9129,6 +9162,14 @@ static IrInstSrc *ir_gen_comptime(IrBuilderSrc *irb, Scope *parent_scope, AstNod...@@ -9129,6 +9162,14 @@ static IrInstSrc *ir_gen_comptime(IrBuilderSrc *irb, Scope *parent_scope, AstNod
9129 return ir_gen_node_extra(irb, node->data.comptime_expr.expr, child_scope, lval, nullptr);9162 return ir_gen_node_extra(irb, node->data.comptime_expr.expr, child_scope, lval, nullptr);
9130}9163}
91319164
9165static IrInstSrc *ir_gen_noasync(IrBuilderSrc *irb, Scope *parent_scope, AstNode *node, LVal lval) {
9166 assert(node->type == NodeTypeNoAsync);
9167
9168 Scope *child_scope = create_noasync_scope(irb->codegen, node, parent_scope);
9169 // purposefully pass null for result_loc and let EndExpr handle it
9170 return ir_gen_node_extra(irb, node->data.comptime_expr.expr, child_scope, lval, nullptr);
9171}
9172
9132static IrInstSrc *ir_gen_return_from_block(IrBuilderSrc *irb, Scope *break_scope, AstNode *node, ScopeBlock *block_scope) {9173static IrInstSrc *ir_gen_return_from_block(IrBuilderSrc *irb, Scope *break_scope, AstNode *node, ScopeBlock *block_scope) {
9133 IrInstSrc *is_comptime;9174 IrInstSrc *is_comptime;
9134 if (ir_should_inline(irb->exec, break_scope)) {9175 if (ir_should_inline(irb->exec, break_scope)) {
...@@ -9709,6 +9750,10 @@ static IrInstSrc *ir_gen_fn_proto(IrBuilderSrc *irb, Scope *parent_scope, AstNod...@@ -9709,6 +9750,10 @@ static IrInstSrc *ir_gen_fn_proto(IrBuilderSrc *irb, Scope *parent_scope, AstNod
97099750
9710static IrInstSrc *ir_gen_resume(IrBuilderSrc *irb, Scope *scope, AstNode *node) {9751static IrInstSrc *ir_gen_resume(IrBuilderSrc *irb, Scope *scope, AstNode *node) {
9711 assert(node->type == NodeTypeResume);9752 assert(node->type == NodeTypeResume);
9753 if (get_scope_noasync(scope) != nullptr) {
9754 add_node_error(irb->codegen, node, buf_sprintf("resume in noasync scope"));
9755 return irb->codegen->invalid_inst_src;
9756 }
97129757
9713 IrInstSrc *target_inst = ir_gen_node_extra(irb, node->data.resume_expr.expr, scope, LValPtr, nullptr);9758 IrInstSrc *target_inst = ir_gen_node_extra(irb, node->data.resume_expr.expr, scope, LValPtr, nullptr);
9714 if (target_inst == irb->codegen->invalid_inst_src)9759 if (target_inst == irb->codegen->invalid_inst_src)
...@@ -9722,7 +9767,7 @@ static IrInstSrc *ir_gen_await_expr(IrBuilderSrc *irb, Scope *scope, AstNode *no...@@ -9722,7 +9767,7 @@ static IrInstSrc *ir_gen_await_expr(IrBuilderSrc *irb, Scope *scope, AstNode *no
9722{9767{
9723 assert(node->type == NodeTypeAwaitExpr);9768 assert(node->type == NodeTypeAwaitExpr);
97249769
9725 bool is_noasync = node->data.await_expr.noasync_token != nullptr;9770 bool is_noasync = get_scope_noasync(scope) != nullptr;
97269771
9727 AstNode *expr_node = node->data.await_expr.expr;9772 AstNode *expr_node = node->data.await_expr.expr;
9728 if (expr_node->type == NodeTypeFnCallExpr && expr_node->data.fn_call_expr.modifier == CallModifierBuiltin) {9773 if (expr_node->type == NodeTypeFnCallExpr && expr_node->data.fn_call_expr.modifier == CallModifierBuiltin) {
...@@ -9768,6 +9813,11 @@ static IrInstSrc *ir_gen_suspend(IrBuilderSrc *irb, Scope *parent_scope, AstNode...@@ -9768,6 +9813,11 @@ static IrInstSrc *ir_gen_suspend(IrBuilderSrc *irb, Scope *parent_scope, AstNode
9768 add_node_error(irb->codegen, node, buf_sprintf("suspend outside function definition"));9813 add_node_error(irb->codegen, node, buf_sprintf("suspend outside function definition"));
9769 return irb->codegen->invalid_inst_src;9814 return irb->codegen->invalid_inst_src;
9770 }9815 }
9816 if (get_scope_noasync(parent_scope) != nullptr) {
9817 add_node_error(irb->codegen, node, buf_sprintf("suspend in noasync scope"));
9818 return irb->codegen->invalid_inst_src;
9819 }
9820
9771 ScopeSuspend *existing_suspend_scope = get_scope_suspend(parent_scope);9821 ScopeSuspend *existing_suspend_scope = get_scope_suspend(parent_scope);
9772 if (existing_suspend_scope) {9822 if (existing_suspend_scope) {
9773 if (!existing_suspend_scope->reported_err) {9823 if (!existing_suspend_scope->reported_err) {
...@@ -9897,6 +9947,8 @@ static IrInstSrc *ir_gen_node_raw(IrBuilderSrc *irb, AstNode *node, Scope *scope...@@ -9897,6 +9947,8 @@ static IrInstSrc *ir_gen_node_raw(IrBuilderSrc *irb, AstNode *node, Scope *scope
9897 return ir_gen_switch_expr(irb, scope, node, lval, result_loc);9947 return ir_gen_switch_expr(irb, scope, node, lval, result_loc);
9898 case NodeTypeCompTime:9948 case NodeTypeCompTime:
9899 return ir_expr_wrap(irb, scope, ir_gen_comptime(irb, scope, node, lval), result_loc);9949 return ir_expr_wrap(irb, scope, ir_gen_comptime(irb, scope, node, lval), result_loc);
9950 case NodeTypeNoAsync:
9951 return ir_expr_wrap(irb, scope, ir_gen_noasync(irb, scope, node, lval), result_loc);
9900 case NodeTypeErrorType:9952 case NodeTypeErrorType:
9901 return ir_lval_wrap(irb, scope, ir_gen_error_type(irb, scope, node), lval, result_loc);9953 return ir_lval_wrap(irb, scope, ir_gen_error_type(irb, scope, node), lval, result_loc);
9902 case NodeTypeBreak:9954 case NodeTypeBreak:
...@@ -15393,23 +15445,6 @@ static bool resolve_cmp_op_id(IrBinOp op_id, Cmp cmp) {...@@ -15393,23 +15445,6 @@ static bool resolve_cmp_op_id(IrBinOp op_id, Cmp cmp) {
15393 }15445 }
15394}15446}
1539515447
15396static bool optional_value_is_null(ZigValue *val) {
15397 assert(val->special == ConstValSpecialStatic);
15398 if (get_src_ptr_type(val->type) != nullptr) {
15399 if (val->data.x_ptr.special == ConstPtrSpecialNull) {
15400 return true;
15401 } else if (val->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) {
15402 return val->data.x_ptr.data.hard_coded_addr.addr == 0;
15403 } else {
15404 return false;
15405 }
15406 } else if (is_opt_err_set(val->type)) {
15407 return val->data.x_err_set == nullptr;
15408 } else {
15409 return val->data.x_optional == nullptr;
15410 }
15411}
15412
15413static void set_optional_value_to_null(ZigValue *val) {15448static void set_optional_value_to_null(ZigValue *val) {
15414 assert(val->special == ConstValSpecialStatic);15449 assert(val->special == ConstValSpecialStatic);
15415 if (val->type->id == ZigTypeIdNull) return; // nothing to do15450 if (val->type->id == ZigTypeIdNull) return; // nothing to do
...@@ -15524,9 +15559,20 @@ static Error lazy_cmp_zero(CodeGen *codegen, AstNode *source_node, ZigValue *val...@@ -15524,9 +15559,20 @@ static Error lazy_cmp_zero(CodeGen *codegen, AstNode *source_node, ZigValue *val
15524 switch (val->data.x_lazy->id) {15559 switch (val->data.x_lazy->id) {
15525 case LazyValueIdInvalid:15560 case LazyValueIdInvalid:
15526 zig_unreachable();15561 zig_unreachable();
15527 case LazyValueIdAlignOf:15562 case LazyValueIdAlignOf: {
15528 *result = CmpGT;15563 LazyValueAlignOf *lazy_align_of = reinterpret_cast<LazyValueAlignOf *>(val->data.x_lazy);
15564 IrAnalyze *ira = lazy_align_of->ira;
15565
15566 bool is_zero_bits;
15567 if ((err = type_val_resolve_zero_bits(ira->codegen, lazy_align_of->target_type->value,
15568 nullptr, nullptr, &is_zero_bits)))
15569 {
15570 return err;
15571 }
15572
15573 *result = is_zero_bits ? CmpEQ : CmpGT;
15529 return ErrorNone;15574 return ErrorNone;
15575 }
15530 case LazyValueIdSizeOf: {15576 case LazyValueIdSizeOf: {
15531 LazyValueSizeOf *lazy_size_of = reinterpret_cast<LazyValueSizeOf *>(val->data.x_lazy);15577 LazyValueSizeOf *lazy_size_of = reinterpret_cast<LazyValueSizeOf *>(val->data.x_lazy);
15532 IrAnalyze *ira = lazy_size_of->ira;15578 IrAnalyze *ira = lazy_size_of->ira;
...@@ -16556,49 +16602,69 @@ static IrInstGen *ir_analyze_bit_shift(IrAnalyze *ira, IrInstSrcBinOp *bin_op_in...@@ -16556,49 +16602,69 @@ static IrInstGen *ir_analyze_bit_shift(IrAnalyze *ira, IrInstSrcBinOp *bin_op_in
16556 IrInstGen *casted_op2;16602 IrInstGen *casted_op2;
16557 IrBinOp op_id = bin_op_instruction->op_id;16603 IrBinOp op_id = bin_op_instruction->op_id;
16558 if (op1->value->type->id == ZigTypeIdComptimeInt) {16604 if (op1->value->type->id == ZigTypeIdComptimeInt) {
16605 // comptime_int has no finite bit width
16559 casted_op2 = op2;16606 casted_op2 = op2;
1656016607
16561 if (op_id == IrBinOpBitShiftLeftLossy) {16608 if (op_id == IrBinOpBitShiftLeftLossy) {
16562 op_id = IrBinOpBitShiftLeftExact;16609 op_id = IrBinOpBitShiftLeftExact;
16563 }16610 }
1656416611
16565 if (casted_op2->value->data.x_bigint.is_negative) {16612 if (!instr_is_comptime(op2)) {
16613 ir_add_error(ira, &bin_op_instruction->base.base,
16614 buf_sprintf("LHS of shift must be an integer type, or RHS must be compile-time known"));
16615 return ira->codegen->invalid_inst_gen;
16616 }
16617
16618 ZigValue *op2_val = ir_resolve_const(ira, casted_op2, UndefBad);
16619 if (op2_val == nullptr)
16620 return ira->codegen->invalid_inst_gen;
16621
16622 if (op2_val->data.x_bigint.is_negative) {
16566 Buf *val_buf = buf_alloc();16623 Buf *val_buf = buf_alloc();
16567 bigint_append_buf(val_buf, &casted_op2->value->data.x_bigint, 10);16624 bigint_append_buf(val_buf, &op2_val->data.x_bigint, 10);
16568 ir_add_error(ira, &casted_op2->base, buf_sprintf("shift by negative value %s", buf_ptr(val_buf)));16625 ir_add_error(ira, &casted_op2->base,
16626 buf_sprintf("shift by negative value %s", buf_ptr(val_buf)));
16569 return ira->codegen->invalid_inst_gen;16627 return ira->codegen->invalid_inst_gen;
16570 }16628 }
16571 } else {16629 } else {
16630 const unsigned bit_count = op1->value->type->data.integral.bit_count;
16572 ZigType *shift_amt_type = get_smallest_unsigned_int_type(ira->codegen,16631 ZigType *shift_amt_type = get_smallest_unsigned_int_type(ira->codegen,
16573 op1->value->type->data.integral.bit_count - 1);16632 bit_count > 0 ? bit_count - 1 : 0);
16574 if (bin_op_instruction->op_id == IrBinOpBitShiftLeftLossy &&
16575 op2->value->type->id == ZigTypeIdComptimeInt) {
1657616633
16577 ZigValue *op2_val = ir_resolve_const(ira, op2, UndefBad);16634 casted_op2 = ir_implicit_cast(ira, op2, shift_amt_type);
16635 if (type_is_invalid(casted_op2->value->type))
16636 return ira->codegen->invalid_inst_gen;
16637
16638 // This check is only valid iff op1 has at least one bit
16639 if (bit_count > 0 && instr_is_comptime(casted_op2)) {
16640 ZigValue *op2_val = ir_resolve_const(ira, casted_op2, UndefBad);
16578 if (op2_val == nullptr)16641 if (op2_val == nullptr)
16579 return ira->codegen->invalid_inst_gen;16642 return ira->codegen->invalid_inst_gen;
16580 if (!bigint_fits_in_bits(&op2_val->data.x_bigint,16643
16581 shift_amt_type->data.integral.bit_count,16644 BigInt bit_count_value = {0};
16582 op2_val->data.x_bigint.is_negative)) {16645 bigint_init_unsigned(&bit_count_value, bit_count);
16583 Buf *val_buf = buf_alloc();16646
16584 bigint_append_buf(val_buf, &op2_val->data.x_bigint, 10);16647 if (bigint_cmp(&op2_val->data.x_bigint, &bit_count_value) != CmpLT) {
16585 ErrorMsg* msg = ir_add_error(ira,16648 ErrorMsg* msg = ir_add_error(ira,
16586 &bin_op_instruction->base.base,16649 &bin_op_instruction->base.base,
16587 buf_sprintf("RHS of shift is too large for LHS type"));16650 buf_sprintf("RHS of shift is too large for LHS type"));
16588 add_error_note(16651 add_error_note(ira->codegen, msg, op1->base.source_node,
16589 ira->codegen,16652 buf_sprintf("type %s has only %u bits",
16590 msg,16653 buf_ptr(&op1->value->type->name), bit_count));
16591 op2->base.source_node,16654
16592 buf_sprintf("value %s cannot fit into type %s",
16593 buf_ptr(val_buf),
16594 buf_ptr(&shift_amt_type->name)));
16595 return ira->codegen->invalid_inst_gen;16655 return ira->codegen->invalid_inst_gen;
16596 }16656 }
16597 }16657 }
16658 }
1659816659
16599 casted_op2 = ir_implicit_cast(ira, op2, shift_amt_type);16660 // Fast path for zero RHS
16600 if (type_is_invalid(casted_op2->value->type))16661 if (instr_is_comptime(casted_op2)) {
16662 ZigValue *op2_val = ir_resolve_const(ira, casted_op2, UndefBad);
16663 if (op2_val == nullptr)
16601 return ira->codegen->invalid_inst_gen;16664 return ira->codegen->invalid_inst_gen;
16665
16666 if (bigint_cmp_zero(&op2_val->data.x_bigint) == CmpEQ)
16667 return ir_analyze_cast(ira, &bin_op_instruction->base.base, op1->value->type, op1);
16602 }16668 }
1660316669
16604 if (instr_is_comptime(op1) && instr_is_comptime(casted_op2)) {16670 if (instr_is_comptime(op1) && instr_is_comptime(casted_op2)) {
...@@ -16611,12 +16677,6 @@ static IrInstGen *ir_analyze_bit_shift(IrAnalyze *ira, IrInstSrcBinOp *bin_op_in...@@ -16611,12 +16677,6 @@ static IrInstGen *ir_analyze_bit_shift(IrAnalyze *ira, IrInstSrcBinOp *bin_op_in
16611 return ira->codegen->invalid_inst_gen;16677 return ira->codegen->invalid_inst_gen;
1661216678
16613 return ir_analyze_math_op(ira, &bin_op_instruction->base.base, op1->value->type, op1_val, op_id, op2_val);16679 return ir_analyze_math_op(ira, &bin_op_instruction->base.base, op1->value->type, op1_val, op_id, op2_val);
16614 } else if (op1->value->type->id == ZigTypeIdComptimeInt) {
16615 ir_add_error(ira, &bin_op_instruction->base.base,
16616 buf_sprintf("LHS of shift must be an integer type, or RHS must be compile-time known"));
16617 return ira->codegen->invalid_inst_gen;
16618 } else if (instr_is_comptime(casted_op2) && bigint_cmp_zero(&casted_op2->value->data.x_bigint) == CmpEQ) {
16619 return ir_build_cast(ira, &bin_op_instruction->base.base, op1->value->type, op1, CastOpNoop);
16620 }16680 }
1662116681
16622 return ir_build_bin_op_gen(ira, &bin_op_instruction->base.base, op1->value->type,16682 return ir_build_bin_op_gen(ira, &bin_op_instruction->base.base, op1->value->type,
...@@ -17498,7 +17558,14 @@ static IrInstGen *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstSrcDeclV...@@ -17498,7 +17558,14 @@ static IrInstGen *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstSrcDeclV
1749817558
17499 ZigValue *init_val = nullptr;17559 ZigValue *init_val = nullptr;
17500 if (instr_is_comptime(var_ptr) && var_ptr->value->data.x_ptr.mut != ConstPtrMutRuntimeVar) {17560 if (instr_is_comptime(var_ptr) && var_ptr->value->data.x_ptr.mut != ConstPtrMutRuntimeVar) {
17501 init_val = const_ptr_pointee(ira, ira->codegen, var_ptr->value, decl_var_instruction->base.base.source_node);17561 ZigValue *ptr_val = ir_resolve_const(ira, var_ptr, UndefBad);
17562 if (ptr_val == nullptr)
17563 return ira->codegen->invalid_inst_gen;
17564
17565 init_val = const_ptr_pointee(ira, ira->codegen, ptr_val, decl_var_instruction->base.base.source_node);
17566 if (init_val == nullptr)
17567 return ira->codegen->invalid_inst_gen;
17568
17502 if (is_comptime_var) {17569 if (is_comptime_var) {
17503 if (var->gen_is_const) {17570 if (var->gen_is_const) {
17504 var->const_value = init_val;17571 var->const_value = init_val;
...@@ -19306,6 +19373,19 @@ static IrInstGen *ir_analyze_fn_call(IrAnalyze *ira, IrInst* source_instr,...@@ -19306,6 +19373,19 @@ static IrInstGen *ir_analyze_fn_call(IrAnalyze *ira, IrInst* source_instr,
19306 ZigType *specified_return_type = ir_analyze_type_expr(ira, impl_fn->child_scope, return_type_node);19373 ZigType *specified_return_type = ir_analyze_type_expr(ira, impl_fn->child_scope, return_type_node);
19307 if (type_is_invalid(specified_return_type))19374 if (type_is_invalid(specified_return_type))
19308 return ira->codegen->invalid_inst_gen;19375 return ira->codegen->invalid_inst_gen;
19376
19377 if(!is_valid_return_type(specified_return_type)){
19378 ErrorMsg *msg = ir_add_error(ira, source_instr,
19379 buf_sprintf("call to generic function with %s return type '%s' not allowed", type_id_name(specified_return_type->id), buf_ptr(&specified_return_type->name)));
19380 add_error_note(ira->codegen, msg, fn_proto_node, buf_sprintf("function declared here"));
19381
19382 Tld *tld = find_decl(ira->codegen, &fn_entry->fndef_scope->base, &specified_return_type->name);
19383 if (tld != nullptr) {
19384 add_error_note(ira->codegen, msg, tld->source_node, buf_sprintf("type declared here"));
19385 }
19386 return ira->codegen->invalid_inst_gen;
19387 }
19388
19309 if (fn_proto_node->data.fn_proto.auto_err_set) {19389 if (fn_proto_node->data.fn_proto.auto_err_set) {
19310 ZigType *inferred_err_set_type = get_auto_err_set_type(ira->codegen, impl_fn);19390 ZigType *inferred_err_set_type = get_auto_err_set_type(ira->codegen, impl_fn);
19311 if ((err = type_resolve(ira->codegen, specified_return_type, ResolveStatusSizeKnown)))19391 if ((err = type_resolve(ira->codegen, specified_return_type, ResolveStatusSizeKnown)))
...@@ -25095,12 +25175,50 @@ static IrInstGen *ir_analyze_instruction_cmpxchg(IrAnalyze *ira, IrInstSrcCmpxch...@@ -25095,12 +25175,50 @@ static IrInstGen *ir_analyze_instruction_cmpxchg(IrAnalyze *ira, IrInstSrcCmpxch
25095 return ira->codegen->invalid_inst_gen;25175 return ira->codegen->invalid_inst_gen;
25096 }25176 }
2509725177
25178 ZigType *result_type = get_optional_type(ira->codegen, operand_type);
25179
25180 // special case zero bit types
25181 switch (type_has_one_possible_value(ira->codegen, operand_type)) {
25182 case OnePossibleValueInvalid:
25183 return ira->codegen->invalid_inst_gen;
25184 case OnePossibleValueYes: {
25185 IrInstGen *result = ir_const(ira, &instruction->base.base, result_type);
25186 set_optional_value_to_null(result->value);
25187 return result;
25188 }
25189 case OnePossibleValueNo:
25190 break;
25191 }
25192
25098 if (instr_is_comptime(casted_ptr) && casted_ptr->value->data.x_ptr.mut != ConstPtrMutRuntimeVar &&25193 if (instr_is_comptime(casted_ptr) && casted_ptr->value->data.x_ptr.mut != ConstPtrMutRuntimeVar &&
25099 instr_is_comptime(casted_cmp_value) && instr_is_comptime(casted_new_value)) {25194 instr_is_comptime(casted_cmp_value) && instr_is_comptime(casted_new_value)) {
25100 zig_panic("TODO compile-time execution of cmpxchg");25195 ZigValue *ptr_val = ir_resolve_const(ira, casted_ptr, UndefBad);
25196 if (ptr_val == nullptr)
25197 return ira->codegen->invalid_inst_gen;
25198
25199 ZigValue *stored_val = const_ptr_pointee(ira, ira->codegen, ptr_val, instruction->base.base.source_node);
25200 if (stored_val == nullptr)
25201 return ira->codegen->invalid_inst_gen;
25202
25203 ZigValue *expected_val = ir_resolve_const(ira, casted_cmp_value, UndefBad);
25204 if (expected_val == nullptr)
25205 return ira->codegen->invalid_inst_gen;
25206
25207 ZigValue *new_val = ir_resolve_const(ira, casted_new_value, UndefBad);
25208 if (new_val == nullptr)
25209 return ira->codegen->invalid_inst_gen;
25210
25211 bool eql = const_values_equal(ira->codegen, stored_val, expected_val);
25212 IrInstGen *result = ir_const(ira, &instruction->base.base, result_type);
25213 if (eql) {
25214 copy_const_val(ira->codegen, stored_val, new_val);
25215 set_optional_value_to_null(result->value);
25216 } else {
25217 set_optional_payload(result->value, stored_val);
25218 }
25219 return result;
25101 }25220 }
2510225221
25103 ZigType *result_type = get_optional_type(ira->codegen, operand_type);
25104 IrInstGen *result_loc;25222 IrInstGen *result_loc;
25105 if (handle_is_ptr(ira->codegen, result_type)) {25223 if (handle_is_ptr(ira->codegen, result_type)) {
25106 result_loc = ir_resolve_result(ira, &instruction->base.base, instruction->result_loc,25224 result_loc = ir_resolve_result(ira, &instruction->base.base, instruction->result_loc,
...@@ -26035,7 +26153,7 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i...@@ -26035,7 +26153,7 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
26035 if (array_type->data.pointer.ptr_len == PtrLenC) {26153 if (array_type->data.pointer.ptr_len == PtrLenC) {
26036 array_type = adjust_ptr_len(ira->codegen, array_type, PtrLenUnknown);26154 array_type = adjust_ptr_len(ira->codegen, array_type, PtrLenUnknown);
2603726155
26038 // C pointers are allowzero by default. 26156 // C pointers are allowzero by default.
26039 // However, we want to be able to slice them without generating an allowzero slice (see issue #4401).26157 // However, we want to be able to slice them without generating an allowzero slice (see issue #4401).
26040 // To achieve this, we generate a runtime safety check and make the slice type non-allowzero.26158 // To achieve this, we generate a runtime safety check and make the slice type non-allowzero.
26041 if (array_type->data.pointer.allow_zero) {26159 if (array_type->data.pointer.allow_zero) {
...@@ -26330,7 +26448,7 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i...@@ -26330,7 +26448,7 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
2633026448
26331 if (type_is_invalid(ptr_val->value->type))26449 if (type_is_invalid(ptr_val->value->type))
26332 return ira->codegen->invalid_inst_gen;26450 return ira->codegen->invalid_inst_gen;
26333 26451
26334 ir_build_assert_non_null(ira, &instruction->base.base, ptr_val);26452 ir_build_assert_non_null(ira, &instruction->base.base, ptr_val);
26335 }26453 }
2633626454
...@@ -28211,43 +28329,20 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op) {...@@ -28211,43 +28329,20 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op) {
28211 if (type_is_invalid(operand_type))28329 if (type_is_invalid(operand_type))
28212 return ira->codegen->builtin_types.entry_invalid;28330 return ira->codegen->builtin_types.entry_invalid;
2821328331
28214 if (operand_type->id == ZigTypeIdInt) {28332 if (operand_type->id == ZigTypeIdInt || operand_type->id == ZigTypeIdEnum) {
28215 if (operand_type->data.integral.bit_count < 8) {28333 ZigType *int_type;
28216 ir_add_error(ira, &op->base,28334 if (operand_type->id == ZigTypeIdEnum) {
28217 buf_sprintf("expected integer type 8 bits or larger, found %" PRIu32 "-bit integer type",28335 int_type = operand_type->data.enumeration.tag_int_type;
28218 operand_type->data.integral.bit_count));28336 } else {
28219 return ira->codegen->builtin_types.entry_invalid;28337 int_type = operand_type;
28220 }28338 }
28339 auto bit_count = int_type->data.integral.bit_count;
28221 uint32_t max_atomic_bits = target_arch_largest_atomic_bits(ira->codegen->zig_target->arch);28340 uint32_t max_atomic_bits = target_arch_largest_atomic_bits(ira->codegen->zig_target->arch);
28222 if (operand_type->data.integral.bit_count > max_atomic_bits) {28341
28342 if (bit_count > max_atomic_bits) {
28223 ir_add_error(ira, &op->base,28343 ir_add_error(ira, &op->base,
28224 buf_sprintf("expected %" PRIu32 "-bit integer type or smaller, found %" PRIu32 "-bit integer type",28344 buf_sprintf("expected %" PRIu32 "-bit integer type or smaller, found %" PRIu32 "-bit integer type",
28225 max_atomic_bits, operand_type->data.integral.bit_count));28345 max_atomic_bits, bit_count));
28226 return ira->codegen->builtin_types.entry_invalid;
28227 }
28228 if (!is_power_of_2(operand_type->data.integral.bit_count)) {
28229 ir_add_error(ira, &op->base,
28230 buf_sprintf("%" PRIu32 "-bit integer type is not a power of 2", operand_type->data.integral.bit_count));
28231 return ira->codegen->builtin_types.entry_invalid;
28232 }
28233 } else if (operand_type->id == ZigTypeIdEnum) {
28234 ZigType *int_type = operand_type->data.enumeration.tag_int_type;
28235 if (int_type->data.integral.bit_count < 8) {
28236 ir_add_error(ira, &op->base,
28237 buf_sprintf("expected enum tag type 8 bits or larger, found %" PRIu32 "-bit tag type",
28238 int_type->data.integral.bit_count));
28239 return ira->codegen->builtin_types.entry_invalid;
28240 }
28241 uint32_t max_atomic_bits = target_arch_largest_atomic_bits(ira->codegen->zig_target->arch);
28242 if (int_type->data.integral.bit_count > max_atomic_bits) {
28243 ir_add_error(ira, &op->base,
28244 buf_sprintf("expected %" PRIu32 "-bit enum tag type or smaller, found %" PRIu32 "-bit tag type",
28245 max_atomic_bits, int_type->data.integral.bit_count));
28246 return ira->codegen->builtin_types.entry_invalid;
28247 }
28248 if (!is_power_of_2(int_type->data.integral.bit_count)) {
28249 ir_add_error(ira, &op->base,
28250 buf_sprintf("%" PRIu32 "-bit enum tag type is not a power of 2", int_type->data.integral.bit_count));
28251 return ira->codegen->builtin_types.entry_invalid;28346 return ira->codegen->builtin_types.entry_invalid;
28252 }28347 }
28253 } else if (operand_type->id == ZigTypeIdFloat) {28348 } else if (operand_type->id == ZigTypeIdFloat) {
...@@ -28258,6 +28353,8 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op) {...@@ -28258,6 +28353,8 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op) {
28258 max_atomic_bits, (uint32_t) operand_type->data.floating.bit_count));28353 max_atomic_bits, (uint32_t) operand_type->data.floating.bit_count));
28259 return ira->codegen->builtin_types.entry_invalid;28354 return ira->codegen->builtin_types.entry_invalid;
28260 }28355 }
28356 } else if (operand_type->id == ZigTypeIdBool) {
28357 // will be treated as u8
28261 } else {28358 } else {
28262 Error err;28359 Error err;
28263 ZigType *operand_ptr_type;28360 ZigType *operand_ptr_type;
...@@ -28296,11 +28393,15 @@ static IrInstGen *ir_analyze_instruction_atomic_rmw(IrAnalyze *ira, IrInstSrcAto...@@ -28296,11 +28393,15 @@ static IrInstGen *ir_analyze_instruction_atomic_rmw(IrAnalyze *ira, IrInstSrcAto
2829628393
28297 if (operand_type->id == ZigTypeIdEnum && op != AtomicRmwOp_xchg) {28394 if (operand_type->id == ZigTypeIdEnum && op != AtomicRmwOp_xchg) {
28298 ir_add_error(ira, &instruction->op->base,28395 ir_add_error(ira, &instruction->op->base,
28299 buf_sprintf("@atomicRmw on enum only works with .Xchg"));28396 buf_sprintf("@atomicRmw with enum only allowed with .Xchg"));
28397 return ira->codegen->invalid_inst_gen;
28398 } else if (operand_type->id == ZigTypeIdBool && op != AtomicRmwOp_xchg) {
28399 ir_add_error(ira, &instruction->op->base,
28400 buf_sprintf("@atomicRmw with bool only allowed with .Xchg"));
28300 return ira->codegen->invalid_inst_gen;28401 return ira->codegen->invalid_inst_gen;
28301 } else if (operand_type->id == ZigTypeIdFloat && op > AtomicRmwOp_sub) {28402 } else if (operand_type->id == ZigTypeIdFloat && op > AtomicRmwOp_sub) {
28302 ir_add_error(ira, &instruction->op->base,28403 ir_add_error(ira, &instruction->op->base,
28303 buf_sprintf("@atomicRmw with float only works with .Xchg, .Add and .Sub"));28404 buf_sprintf("@atomicRmw with float only allowed with .Xchg, .Add and .Sub"));
28304 return ira->codegen->invalid_inst_gen;28405 return ira->codegen->invalid_inst_gen;
28305 }28406 }
2830628407
...@@ -28321,14 +28422,103 @@ static IrInstGen *ir_analyze_instruction_atomic_rmw(IrAnalyze *ira, IrInstSrcAto...@@ -28321,14 +28422,103 @@ static IrInstGen *ir_analyze_instruction_atomic_rmw(IrAnalyze *ira, IrInstSrcAto
28321 return ira->codegen->invalid_inst_gen;28422 return ira->codegen->invalid_inst_gen;
28322 }28423 }
2832328424
28324 if (instr_is_comptime(casted_operand) && instr_is_comptime(casted_ptr) && casted_ptr->value->data.x_ptr.mut == ConstPtrMutComptimeVar)28425 // special case zero bit types
28325 {28426 switch (type_has_one_possible_value(ira->codegen, operand_type)) {
28326 ir_add_error(ira, &instruction->base.base,28427 case OnePossibleValueInvalid:
28327 buf_sprintf("compiler bug: TODO compile-time execution of @atomicRmw"));28428 return ira->codegen->invalid_inst_gen;
28328 return ira->codegen->invalid_inst_gen;28429 case OnePossibleValueYes:
28430 return ir_const_move(ira, &instruction->base.base, get_the_one_possible_value(ira->codegen, operand_type));
28431 case OnePossibleValueNo:
28432 break;
28329 }28433 }
2833028434
28331 return ir_build_atomic_rmw_gen(ira, &instruction->base.base, casted_ptr, casted_operand, op,28435 IrInst *source_inst = &instruction->base.base;
28436 if (instr_is_comptime(casted_operand) && instr_is_comptime(casted_ptr) && casted_ptr->value->data.x_ptr.mut == ConstPtrMutComptimeVar) {
28437 ZigValue *ptr_val = ir_resolve_const(ira, casted_ptr, UndefBad);
28438 if (ptr_val == nullptr)
28439 return ira->codegen->invalid_inst_gen;
28440
28441 ZigValue *op1_val = const_ptr_pointee(ira, ira->codegen, ptr_val, instruction->base.base.source_node);
28442 if (op1_val == nullptr)
28443 return ira->codegen->invalid_inst_gen;
28444
28445 ZigValue *op2_val = ir_resolve_const(ira, casted_operand, UndefBad);
28446 if (op2_val == nullptr)
28447 return ira->codegen->invalid_inst_gen;
28448
28449 IrInstGen *result = ir_const(ira, source_inst, operand_type);
28450 copy_const_val(ira->codegen, result->value, op1_val);
28451 if (op == AtomicRmwOp_xchg) {
28452 copy_const_val(ira->codegen, op1_val, op2_val);
28453 return result;
28454 }
28455
28456 if (operand_type->id == ZigTypeIdPointer || operand_type->id == ZigTypeIdOptional) {
28457 ir_add_error(ira, &instruction->ordering->base,
28458 buf_sprintf("TODO comptime @atomicRmw with pointers other than .Xchg"));
28459 return ira->codegen->invalid_inst_gen;
28460 }
28461
28462 ErrorMsg *msg;
28463 if (op == AtomicRmwOp_min || op == AtomicRmwOp_max) {
28464 IrBinOp bin_op;
28465 if (op == AtomicRmwOp_min)
28466 // store op2 if op2 < op1
28467 bin_op = IrBinOpCmpGreaterThan;
28468 else
28469 // store op2 if op2 > op1
28470 bin_op = IrBinOpCmpLessThan;
28471
28472 IrInstGen *dummy_value = ir_const(ira, source_inst, operand_type);
28473 msg = ir_eval_bin_op_cmp_scalar(ira, source_inst, op1_val, bin_op, op2_val, dummy_value->value);
28474 if (msg != nullptr) {
28475 return ira->codegen->invalid_inst_gen;
28476 }
28477 if (dummy_value->value->data.x_bool)
28478 copy_const_val(ira->codegen, op1_val, op2_val);
28479 } else {
28480 IrBinOp bin_op;
28481 switch (op) {
28482 case AtomicRmwOp_xchg:
28483 case AtomicRmwOp_max:
28484 case AtomicRmwOp_min:
28485 zig_unreachable();
28486 case AtomicRmwOp_add:
28487 if (operand_type->id == ZigTypeIdFloat)
28488 bin_op = IrBinOpAdd;
28489 else
28490 bin_op = IrBinOpAddWrap;
28491 break;
28492 case AtomicRmwOp_sub:
28493 if (operand_type->id == ZigTypeIdFloat)
28494 bin_op = IrBinOpSub;
28495 else
28496 bin_op = IrBinOpSubWrap;
28497 break;
28498 case AtomicRmwOp_and:
28499 case AtomicRmwOp_nand:
28500 bin_op = IrBinOpBinAnd;
28501 break;
28502 case AtomicRmwOp_or:
28503 bin_op = IrBinOpBinOr;
28504 break;
28505 case AtomicRmwOp_xor:
28506 bin_op = IrBinOpBinXor;
28507 break;
28508 }
28509 msg = ir_eval_math_op_scalar(ira, source_inst, operand_type, op1_val, bin_op, op2_val, op1_val);
28510 if (msg != nullptr) {
28511 return ira->codegen->invalid_inst_gen;
28512 }
28513 if (op == AtomicRmwOp_nand) {
28514 bigint_not(&op1_val->data.x_bigint, &op1_val->data.x_bigint,
28515 operand_type->data.integral.bit_count, operand_type->data.integral.is_signed);
28516 }
28517 }
28518 return result;
28519 }
28520
28521 return ir_build_atomic_rmw_gen(ira, source_inst, casted_ptr, casted_operand, op,
28332 ordering, operand_type);28522 ordering, operand_type);
28333}28523}
2833428524
...@@ -28400,6 +28590,16 @@ static IrInstGen *ir_analyze_instruction_atomic_store(IrAnalyze *ira, IrInstSrcA...@@ -28400,6 +28590,16 @@ static IrInstGen *ir_analyze_instruction_atomic_store(IrAnalyze *ira, IrInstSrcA
28400 return ira->codegen->invalid_inst_gen;28590 return ira->codegen->invalid_inst_gen;
28401 }28591 }
2840228592
28593 // special case zero bit types
28594 switch (type_has_one_possible_value(ira->codegen, operand_type)) {
28595 case OnePossibleValueInvalid:
28596 return ira->codegen->invalid_inst_gen;
28597 case OnePossibleValueYes:
28598 return ir_const_void(ira, &instruction->base.base);
28599 case OnePossibleValueNo:
28600 break;
28601 }
28602
28403 if (instr_is_comptime(casted_value) && instr_is_comptime(casted_ptr)) {28603 if (instr_is_comptime(casted_value) && instr_is_comptime(casted_ptr)) {
28404 IrInstGen *result = ir_analyze_store_ptr(ira, &instruction->base.base, casted_ptr, value, false);28604 IrInstGen *result = ir_analyze_store_ptr(ira, &instruction->base.base, casted_ptr, value, false);
28405 result->value->type = ira->codegen->builtin_types.entry_void;28605 result->value->type = ira->codegen->builtin_types.entry_void;
...@@ -30213,7 +30413,7 @@ static Error ir_resolve_lazy_raw(AstNode *source_node, ZigValue *val) {...@@ -30213,7 +30413,7 @@ static Error ir_resolve_lazy_raw(AstNode *source_node, ZigValue *val) {
30213 return ErrorSemanticAnalyzeFail;30413 return ErrorSemanticAnalyzeFail;
30214 } else if (elem_type->id == ZigTypeIdOpaque) {30414 } else if (elem_type->id == ZigTypeIdOpaque) {
30215 ir_add_error(ira, &lazy_ptr_type->elem_type->base,30415 ir_add_error(ira, &lazy_ptr_type->elem_type->base,
30216 buf_sprintf("C pointers cannot point opaque types"));30416 buf_sprintf("C pointers cannot point to opaque types"));
30217 return ErrorSemanticAnalyzeFail;30417 return ErrorSemanticAnalyzeFail;
30218 } else if (lazy_ptr_type->is_allowzero) {30418 } else if (lazy_ptr_type->is_allowzero) {
30219 ir_add_error(ira, &lazy_ptr_type->elem_type->base,30419 ir_add_error(ira, &lazy_ptr_type->elem_type->base,
src/link.cpp+39-24
...@@ -983,44 +983,59 @@ static bool is_musl_arch_name(const char *name) {...@@ -983,44 +983,59 @@ static bool is_musl_arch_name(const char *name) {
983 return false;983 return false;
984}984}
985985
986enum MuslSrc {
987 MuslSrcAsm,
988 MuslSrcNormal,
989 MuslSrcO3,
990};
991
992static void add_musl_src_file(HashMap<Buf *, MuslSrc, buf_hash, buf_eql_buf> &source_table,
993 const char *file_path)
994{
995 Buf *src_file = buf_create_from_str(file_path);
996
997 MuslSrc src_kind;
998 if (buf_ends_with_str(src_file, ".c")) {
999 bool want_O3 = buf_starts_with_str(src_file, "musl/src/malloc/") ||
1000 buf_starts_with_str(src_file, "musl/src/string/") ||
1001 buf_starts_with_str(src_file, "musl/src/internal/");
1002 src_kind = want_O3 ? MuslSrcO3 : MuslSrcNormal;
1003 } else if (buf_ends_with_str(src_file, ".s") || buf_ends_with_str(src_file, ".S")) {
1004 src_kind = MuslSrcAsm;
1005 } else {
1006 zig_unreachable();
1007 }
1008 if (ZIG_OS_SEP_CHAR != '/') {
1009 buf_replace(src_file, '/', ZIG_OS_SEP_CHAR);
1010 }
1011 source_table.put_unique(src_file, src_kind);
1012}
1013
986static const char *build_musl(CodeGen *parent, Stage2ProgressNode *progress_node) {1014static const char *build_musl(CodeGen *parent, Stage2ProgressNode *progress_node) {
987 CodeGen *child_gen = create_child_codegen(parent, nullptr, OutTypeLib, nullptr, "c", progress_node);1015 CodeGen *child_gen = create_child_codegen(parent, nullptr, OutTypeLib, nullptr, "c", progress_node);
9881016
989 // When there is a src/<arch>/foo.* then it should substitute for src/foo.*1017 // When there is a src/<arch>/foo.* then it should substitute for src/foo.*
990 // Even a .s file can substitute for a .c file.1018 // Even a .s file can substitute for a .c file.
9911019
992 enum MuslSrc {
993 MuslSrcAsm,
994 MuslSrcNormal,
995 MuslSrcO3,
996 };
997
998 const char *target_musl_arch_name = target_arch_musl_name(parent->zig_target->arch);1020 const char *target_musl_arch_name = target_arch_musl_name(parent->zig_target->arch);
9991021
1000 HashMap<Buf *, MuslSrc, buf_hash, buf_eql_buf> source_table = {};1022 HashMap<Buf *, MuslSrc, buf_hash, buf_eql_buf> source_table = {};
1001 source_table.init(1800);1023 source_table.init(2000);
10021024
1003 for (size_t i = 0; i < array_length(ZIG_MUSL_SRC_FILES); i += 1) {1025 for (size_t i = 0; i < array_length(ZIG_MUSL_SRC_FILES); i += 1) {
1004 Buf *src_file = buf_create_from_str(ZIG_MUSL_SRC_FILES[i]);1026 add_musl_src_file(source_table, ZIG_MUSL_SRC_FILES[i]);
10051027 }
1006 MuslSrc src_kind;1028
1007 if (buf_ends_with_str(src_file, ".c")) {1029 static const char *time32_compat_arch_list[] = {"arm", "i386", "mips", "powerpc"};
1008 assert(buf_starts_with_str(src_file, "musl/src/"));1030 for (size_t arch_i = 0; arch_i < array_length(time32_compat_arch_list); arch_i += 1) {
1009 bool want_O3 = buf_starts_with_str(src_file, "musl/src/malloc/") ||1031 if (strcmp(target_musl_arch_name, time32_compat_arch_list[arch_i]) == 0) {
1010 buf_starts_with_str(src_file, "musl/src/string/") ||1032 for (size_t i = 0; i < array_length(ZIG_MUSL_COMPAT_TIME32_FILES); i += 1) {
1011 buf_starts_with_str(src_file, "musl/src/internal/");1033 add_musl_src_file(source_table, ZIG_MUSL_COMPAT_TIME32_FILES[i]);
1012 src_kind = want_O3 ? MuslSrcO3 : MuslSrcNormal;1034 }
1013 } else if (buf_ends_with_str(src_file, ".s") || buf_ends_with_str(src_file, ".S")) {
1014 src_kind = MuslSrcAsm;
1015 } else {
1016 continue;
1017 }
1018 if (ZIG_OS_SEP_CHAR != '/') {
1019 buf_replace(src_file, '/', ZIG_OS_SEP_CHAR);
1020 }1035 }
1021 source_table.put_unique(src_file, src_kind);
1022 }1036 }
10231037
1038
1024 ZigList<CFile *> c_source_files = {0};1039 ZigList<CFile *> c_source_files = {0};
10251040
1026 Buf dirname = BUF_INIT;1041 Buf dirname = BUF_INIT;
src/main.cpp+1-1
...@@ -1392,7 +1392,7 @@ static int main0(int argc, char **argv) {...@@ -1392,7 +1392,7 @@ static int main0(int argc, char **argv) {
1392 return main_exit(root_progress_node, EXIT_SUCCESS);1392 return main_exit(root_progress_node, EXIT_SUCCESS);
1393 }1393 }
1394 case CmdTargets:1394 case CmdTargets:
1395 return stage2_cmd_targets(buf_ptr(&zig_triple_buf));1395 return stage2_cmd_targets(target_string, mcpu, dynamic_linker);
1396 case CmdNone:1396 case CmdNone:
1397 return print_full_usage(arg0, stderr, EXIT_FAILURE);1397 return print_full_usage(arg0, stderr, EXIT_FAILURE);
1398 }1398 }
src/parser.cpp+34-11
...@@ -876,6 +876,7 @@ static AstNode *ast_parse_container_field(ParseContext *pc) {...@@ -876,6 +876,7 @@ static AstNode *ast_parse_container_field(ParseContext *pc) {
876// Statement876// Statement
877// <- KEYWORD_comptime? VarDecl877// <- KEYWORD_comptime? VarDecl
878// / KEYWORD_comptime BlockExprStatement878// / KEYWORD_comptime BlockExprStatement
879// / KEYWORD_noasync BlockExprStatement
879// / KEYWORD_suspend (SEMICOLON / BlockExprStatement)880// / KEYWORD_suspend (SEMICOLON / BlockExprStatement)
880// / KEYWORD_defer BlockExprStatement881// / KEYWORD_defer BlockExprStatement
881// / KEYWORD_errdefer BlockExprStatement882// / KEYWORD_errdefer BlockExprStatement
...@@ -899,6 +900,14 @@ static AstNode *ast_parse_statement(ParseContext *pc) {...@@ -899,6 +900,14 @@ static AstNode *ast_parse_statement(ParseContext *pc) {
899 return res;900 return res;
900 }901 }
901902
903 Token *noasync = eat_token_if(pc, TokenIdKeywordNoAsync);
904 if (noasync != nullptr) {
905 AstNode *statement = ast_expect(pc, ast_parse_block_expr_statement);
906 AstNode *res = ast_create_node(pc, NodeTypeNoAsync, noasync);
907 res->data.noasync_expr.expr = statement;
908 return res;
909 }
910
902 Token *suspend = eat_token_if(pc, TokenIdKeywordSuspend);911 Token *suspend = eat_token_if(pc, TokenIdKeywordSuspend);
903 if (suspend != nullptr) {912 if (suspend != nullptr) {
904 AstNode *statement = nullptr;913 AstNode *statement = nullptr;
...@@ -1237,6 +1246,7 @@ static AstNode *ast_parse_prefix_expr(ParseContext *pc) {...@@ -1237,6 +1246,7 @@ static AstNode *ast_parse_prefix_expr(ParseContext *pc) {
1237// / IfExpr1246// / IfExpr
1238// / KEYWORD_break BreakLabel? Expr?1247// / KEYWORD_break BreakLabel? Expr?
1239// / KEYWORD_comptime Expr1248// / KEYWORD_comptime Expr
1249// / KEYWORD_noasync Expr
1240// / KEYWORD_continue BreakLabel?1250// / KEYWORD_continue BreakLabel?
1241// / KEYWORD_resume Expr1251// / KEYWORD_resume Expr
1242// / KEYWORD_return Expr?1252// / KEYWORD_return Expr?
...@@ -1271,6 +1281,14 @@ static AstNode *ast_parse_primary_expr(ParseContext *pc) {...@@ -1271,6 +1281,14 @@ static AstNode *ast_parse_primary_expr(ParseContext *pc) {
1271 return res;1281 return res;
1272 }1282 }
12731283
1284 Token *noasync = eat_token_if(pc, TokenIdKeywordNoAsync);
1285 if (noasync != nullptr) {
1286 AstNode *expr = ast_expect(pc, ast_parse_expr);
1287 AstNode *res = ast_create_node(pc, NodeTypeNoAsync, noasync);
1288 res->data.noasync_expr.expr = expr;
1289 return res;
1290 }
1291
1274 Token *continue_token = eat_token_if(pc, TokenIdKeywordContinue);1292 Token *continue_token = eat_token_if(pc, TokenIdKeywordContinue);
1275 if (continue_token != nullptr) {1293 if (continue_token != nullptr) {
1276 Token *label = ast_parse_break_label(pc);1294 Token *label = ast_parse_break_label(pc);
...@@ -1459,13 +1477,11 @@ static AstNode *ast_parse_error_union_expr(ParseContext *pc) {...@@ -1459,13 +1477,11 @@ static AstNode *ast_parse_error_union_expr(ParseContext *pc) {
14591477
1460// SuffixExpr1478// SuffixExpr
1461// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments1479// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
1462// / KEYWORD_noasync PrimaryTypeExpr SuffixOp* FnCallArguments
1463// / PrimaryTypeExpr (SuffixOp / FnCallArguments)*1480// / PrimaryTypeExpr (SuffixOp / FnCallArguments)*
1464static AstNode *ast_parse_suffix_expr(ParseContext *pc) {1481static AstNode *ast_parse_suffix_expr(ParseContext *pc) {
1465 Token *async_token = eat_token(pc);1482 Token *async_token = eat_token_if(pc, TokenIdKeywordAsync);
1466 bool is_async = async_token->id == TokenIdKeywordAsync;1483 if (async_token) {
1467 if (is_async || async_token->id == TokenIdKeywordNoAsync) {1484 if (eat_token_if(pc, TokenIdKeywordFn) != nullptr) {
1468 if (is_async && eat_token_if(pc, TokenIdKeywordFn) != nullptr) {
1469 // HACK: If we see the keyword `fn`, then we assume that1485 // HACK: If we see the keyword `fn`, then we assume that
1470 // we are parsing an async fn proto, and not a call.1486 // we are parsing an async fn proto, and not a call.
1471 // We therefore put back all tokens consumed by the async1487 // We therefore put back all tokens consumed by the async
...@@ -1515,13 +1531,12 @@ static AstNode *ast_parse_suffix_expr(ParseContext *pc) {...@@ -1515,13 +1531,12 @@ static AstNode *ast_parse_suffix_expr(ParseContext *pc) {
1515 assert(args->type == NodeTypeFnCallExpr);1531 assert(args->type == NodeTypeFnCallExpr);
15161532
1517 AstNode *res = ast_create_node(pc, NodeTypeFnCallExpr, async_token);1533 AstNode *res = ast_create_node(pc, NodeTypeFnCallExpr, async_token);
1518 res->data.fn_call_expr.modifier = is_async ? CallModifierAsync : CallModifierNoAsync;1534 res->data.fn_call_expr.modifier = CallModifierAsync;
1519 res->data.fn_call_expr.seen = false;1535 res->data.fn_call_expr.seen = false;
1520 res->data.fn_call_expr.fn_ref_expr = child;1536 res->data.fn_call_expr.fn_ref_expr = child;
1521 res->data.fn_call_expr.params = args->data.fn_call_expr.params;1537 res->data.fn_call_expr.params = args->data.fn_call_expr.params;
1522 return res;1538 return res;
1523 }1539 }
1524 put_back_token(pc);
15251540
1526 AstNode *res = ast_parse_primary_type_expr(pc);1541 AstNode *res = ast_parse_primary_type_expr(pc);
1527 if (res == nullptr)1542 if (res == nullptr)
...@@ -1582,6 +1597,7 @@ static AstNode *ast_parse_suffix_expr(ParseContext *pc) {...@@ -1582,6 +1597,7 @@ static AstNode *ast_parse_suffix_expr(ParseContext *pc) {
1582// / IfTypeExpr1597// / IfTypeExpr
1583// / INTEGER1598// / INTEGER
1584// / KEYWORD_comptime TypeExpr1599// / KEYWORD_comptime TypeExpr
1600// / KEYWORD_noasync TypeExpr
1585// / KEYWORD_error DOT IDENTIFIER1601// / KEYWORD_error DOT IDENTIFIER
1586// / KEYWORD_false1602// / KEYWORD_false
1587// / KEYWORD_null1603// / KEYWORD_null
...@@ -1683,6 +1699,14 @@ static AstNode *ast_parse_primary_type_expr(ParseContext *pc) {...@@ -1683,6 +1699,14 @@ static AstNode *ast_parse_primary_type_expr(ParseContext *pc) {
1683 return res;1699 return res;
1684 }1700 }
16851701
1702 Token *noasync = eat_token_if(pc, TokenIdKeywordNoAsync);
1703 if (noasync != nullptr) {
1704 AstNode *expr = ast_expect(pc, ast_parse_type_expr);
1705 AstNode *res = ast_create_node(pc, NodeTypeNoAsync, noasync);
1706 res->data.noasync_expr.expr = expr;
1707 return res;
1708 }
1709
1686 Token *error = eat_token_if(pc, TokenIdKeywordError);1710 Token *error = eat_token_if(pc, TokenIdKeywordError);
1687 if (error != nullptr) {1711 if (error != nullptr) {
1688 Token *dot = expect_token(pc, TokenIdDot);1712 Token *dot = expect_token(pc, TokenIdDot);
...@@ -2599,14 +2623,10 @@ static AstNode *ast_parse_prefix_op(ParseContext *pc) {...@@ -2599,14 +2623,10 @@ static AstNode *ast_parse_prefix_op(ParseContext *pc) {
2599 return res;2623 return res;
2600 }2624 }
26012625
2602 Token *noasync_token = eat_token_if(pc, TokenIdKeywordNoAsync);
2603 Token *await = eat_token_if(pc, TokenIdKeywordAwait);2626 Token *await = eat_token_if(pc, TokenIdKeywordAwait);
2604 if (await != nullptr) {2627 if (await != nullptr) {
2605 AstNode *res = ast_create_node(pc, NodeTypeAwaitExpr, await);2628 AstNode *res = ast_create_node(pc, NodeTypeAwaitExpr, await);
2606 res->data.await_expr.noasync_token = noasync_token;
2607 return res;2629 return res;
2608 } else if (noasync_token != nullptr) {
2609 put_back_token(pc);
2610 }2630 }
26112631
2612 return nullptr;2632 return nullptr;
...@@ -3125,6 +3145,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont...@@ -3125,6 +3145,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
3125 case NodeTypeCompTime:3145 case NodeTypeCompTime:
3126 visit_field(&node->data.comptime_expr.expr, visit, context);3146 visit_field(&node->data.comptime_expr.expr, visit, context);
3127 break;3147 break;
3148 case NodeTypeNoAsync:
3149 visit_field(&node->data.comptime_expr.expr, visit, context);
3150 break;
3128 case NodeTypeBreak:3151 case NodeTypeBreak:
3129 // none3152 // none
3130 break;3153 break;
src/stage2.cpp+4-3
...@@ -251,13 +251,16 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons...@@ -251,13 +251,16 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons
251 target->cache_hash = "\n\n";251 target->cache_hash = "\n\n";
252 }252 }
253253
254 target->cache_hash_len = strlen(target->cache_hash);
255
254 if (dynamic_linker != nullptr) {256 if (dynamic_linker != nullptr) {
255 target->dynamic_linker = dynamic_linker;257 target->dynamic_linker = dynamic_linker;
256 }258 }
259
257 return ErrorNone;260 return ErrorNone;
258}261}
259262
260int stage2_cmd_targets(const char *zig_triple) {263int stage2_cmd_targets(const char *zig_triple, const char *mcpu, const char *dynamic_linker) {
261 const char *msg = "stage0 called stage2_cmd_targets";264 const char *msg = "stage0 called stage2_cmd_targets";
262 stage2_panic(msg, strlen(msg));265 stage2_panic(msg, strlen(msg));
263}266}
...@@ -269,8 +272,6 @@ enum Error stage2_libc_parse(struct Stage2LibCInstallation *libc, const char *li...@@ -269,8 +272,6 @@ enum Error stage2_libc_parse(struct Stage2LibCInstallation *libc, const char *li
269 libc->sys_include_dir_len = strlen(libc->sys_include_dir);272 libc->sys_include_dir_len = strlen(libc->sys_include_dir);
270 libc->crt_dir = "";273 libc->crt_dir = "";
271 libc->crt_dir_len = strlen(libc->crt_dir);274 libc->crt_dir_len = strlen(libc->crt_dir);
272 libc->static_crt_dir = "";
273 libc->static_crt_dir_len = strlen(libc->static_crt_dir);
274 libc->msvc_lib_dir = "";275 libc->msvc_lib_dir = "";
275 libc->msvc_lib_dir_len = strlen(libc->msvc_lib_dir);276 libc->msvc_lib_dir_len = strlen(libc->msvc_lib_dir);
276 libc->kernel32_lib_dir = "";277 libc->kernel32_lib_dir = "";
src/stage2.h+4-5
...@@ -201,9 +201,6 @@ ZIG_EXTERN_C void stage2_progress_complete_one(Stage2ProgressNode *node);...@@ -201,9 +201,6 @@ ZIG_EXTERN_C void stage2_progress_complete_one(Stage2ProgressNode *node);
201ZIG_EXTERN_C void stage2_progress_update_node(Stage2ProgressNode *node,201ZIG_EXTERN_C void stage2_progress_update_node(Stage2ProgressNode *node,
202 size_t completed_count, size_t estimated_total_items);202 size_t completed_count, size_t estimated_total_items);
203203
204// ABI warning
205ZIG_EXTERN_C int stage2_cmd_targets(const char *zig_triple);
206
207// ABI warning204// ABI warning
208struct Stage2LibCInstallation {205struct Stage2LibCInstallation {
209 const char *include_dir;206 const char *include_dir;
...@@ -212,8 +209,6 @@ struct Stage2LibCInstallation {...@@ -212,8 +209,6 @@ struct Stage2LibCInstallation {
212 size_t sys_include_dir_len;209 size_t sys_include_dir_len;
213 const char *crt_dir;210 const char *crt_dir;
214 size_t crt_dir_len;211 size_t crt_dir_len;
215 const char *static_crt_dir;
216 size_t static_crt_dir_len;
217 const char *msvc_lib_dir;212 const char *msvc_lib_dir;
218 size_t msvc_lib_dir_len;213 size_t msvc_lib_dir_len;
219 const char *kernel32_lib_dir;214 const char *kernel32_lib_dir;
...@@ -293,6 +288,7 @@ struct ZigTarget {...@@ -293,6 +288,7 @@ struct ZigTarget {
293 const char *llvm_cpu_features;288 const char *llvm_cpu_features;
294 const char *cpu_builtin_str;289 const char *cpu_builtin_str;
295 const char *cache_hash;290 const char *cache_hash;
291 size_t cache_hash_len;
296 const char *os_builtin_str;292 const char *os_builtin_str;
297 const char *dynamic_linker;293 const char *dynamic_linker;
298};294};
...@@ -301,6 +297,9 @@ struct ZigTarget {...@@ -301,6 +297,9 @@ struct ZigTarget {
301ZIG_EXTERN_C enum Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu,297ZIG_EXTERN_C enum Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu,
302 const char *dynamic_linker);298 const char *dynamic_linker);
303299
300// ABI warning
301ZIG_EXTERN_C int stage2_cmd_targets(const char *zig_triple, const char *mcpu, const char *dynamic_linker);
302
304303
305// ABI warning304// ABI warning
306struct Stage2NativePaths {305struct Stage2NativePaths {
src/zig_clang.cpp+30
...@@ -1662,6 +1662,16 @@ unsigned ZigClangVarDecl_getAlignedAttribute(const struct ZigClangVarDecl *self,...@@ -1662,6 +1662,16 @@ unsigned ZigClangVarDecl_getAlignedAttribute(const struct ZigClangVarDecl *self,
1662 return 0;1662 return 0;
1663}1663}
16641664
1665unsigned ZigClangFieldDecl_getAlignedAttribute(const struct ZigClangFieldDecl *self, const ZigClangASTContext* ctx) {
1666 auto casted_self = reinterpret_cast<const clang::FieldDecl *>(self);
1667 auto casted_ctx = const_cast<clang::ASTContext *>(reinterpret_cast<const clang::ASTContext *>(ctx));
1668 if (const clang::AlignedAttr *AA = casted_self->getAttr<clang::AlignedAttr>()) {
1669 return AA->getAlignment(*casted_ctx);
1670 }
1671 // Zero means no explicit alignment factor was specified
1672 return 0;
1673}
1674
1665unsigned ZigClangFunctionDecl_getAlignedAttribute(const struct ZigClangFunctionDecl *self, const ZigClangASTContext* ctx) {1675unsigned ZigClangFunctionDecl_getAlignedAttribute(const struct ZigClangFunctionDecl *self, const ZigClangASTContext* ctx) {
1666 auto casted_self = reinterpret_cast<const clang::FunctionDecl *>(self);1676 auto casted_self = reinterpret_cast<const clang::FunctionDecl *>(self);
1667 auto casted_ctx = const_cast<clang::ASTContext *>(reinterpret_cast<const clang::ASTContext *>(ctx));1677 auto casted_ctx = const_cast<clang::ASTContext *>(reinterpret_cast<const clang::ASTContext *>(ctx));
...@@ -1928,6 +1938,26 @@ bool ZigClangType_isRecordType(const ZigClangType *self) {...@@ -1928,6 +1938,26 @@ bool ZigClangType_isRecordType(const ZigClangType *self) {
1928 return casted->isRecordType();1938 return casted->isRecordType();
1929}1939}
19301940
1941bool ZigClangType_isIncompleteOrZeroLengthArrayType(const ZigClangQualType *self,
1942 const struct ZigClangASTContext *ctx)
1943{
1944 auto casted_ctx = reinterpret_cast<const clang::ASTContext *>(ctx);
1945 auto casted = reinterpret_cast<const clang::QualType *>(self);
1946 auto casted_type = reinterpret_cast<const clang::Type *>(self);
1947 if (casted_type->isIncompleteArrayType())
1948 return true;
1949
1950 clang::QualType elem_type = *casted;
1951 while (const clang::ConstantArrayType *ArrayT = casted_ctx->getAsConstantArrayType(elem_type)) {
1952 if (ArrayT->getSize() == 0)
1953 return true;
1954
1955 elem_type = ArrayT->getElementType();
1956 }
1957
1958 return false;
1959}
1960
1931bool ZigClangType_isConstantArrayType(const ZigClangType *self) {1961bool ZigClangType_isConstantArrayType(const ZigClangType *self) {
1932 auto casted = reinterpret_cast<const clang::Type *>(self);1962 auto casted = reinterpret_cast<const clang::Type *>(self);
1933 return casted->isConstantArrayType();1963 return casted->isConstantArrayType();
src/zig_clang.h+2
...@@ -887,6 +887,7 @@ ZIG_EXTERN_C const struct ZigClangVarDecl *ZigClangVarDecl_getCanonicalDecl(cons...@@ -887,6 +887,7 @@ ZIG_EXTERN_C const struct ZigClangVarDecl *ZigClangVarDecl_getCanonicalDecl(cons
887ZIG_EXTERN_C const char* ZigClangVarDecl_getSectionAttribute(const struct ZigClangVarDecl *self, size_t *len);887ZIG_EXTERN_C const char* ZigClangVarDecl_getSectionAttribute(const struct ZigClangVarDecl *self, size_t *len);
888ZIG_EXTERN_C unsigned ZigClangVarDecl_getAlignedAttribute(const struct ZigClangVarDecl *self, const ZigClangASTContext* ctx);888ZIG_EXTERN_C unsigned ZigClangVarDecl_getAlignedAttribute(const struct ZigClangVarDecl *self, const ZigClangASTContext* ctx);
889ZIG_EXTERN_C unsigned ZigClangFunctionDecl_getAlignedAttribute(const struct ZigClangFunctionDecl *self, const ZigClangASTContext* ctx);889ZIG_EXTERN_C unsigned ZigClangFunctionDecl_getAlignedAttribute(const struct ZigClangFunctionDecl *self, const ZigClangASTContext* ctx);
890ZIG_EXTERN_C unsigned ZigClangFieldDecl_getAlignedAttribute(const struct ZigClangFieldDecl *self, const ZigClangASTContext* ctx);
890891
891ZIG_EXTERN_C struct ZigClangQualType ZigClangParmVarDecl_getOriginalType(const struct ZigClangParmVarDecl *self);892ZIG_EXTERN_C struct ZigClangQualType ZigClangParmVarDecl_getOriginalType(const struct ZigClangParmVarDecl *self);
892893
...@@ -969,6 +970,7 @@ ZIG_EXTERN_C bool ZigClangType_isBooleanType(const struct ZigClangType *self);...@@ -969,6 +970,7 @@ ZIG_EXTERN_C bool ZigClangType_isBooleanType(const struct ZigClangType *self);
969ZIG_EXTERN_C bool ZigClangType_isVoidType(const struct ZigClangType *self);970ZIG_EXTERN_C bool ZigClangType_isVoidType(const struct ZigClangType *self);
970ZIG_EXTERN_C bool ZigClangType_isArrayType(const struct ZigClangType *self);971ZIG_EXTERN_C bool ZigClangType_isArrayType(const struct ZigClangType *self);
971ZIG_EXTERN_C bool ZigClangType_isRecordType(const struct ZigClangType *self);972ZIG_EXTERN_C bool ZigClangType_isRecordType(const struct ZigClangType *self);
973ZIG_EXTERN_C bool ZigClangType_isIncompleteOrZeroLengthArrayType(const ZigClangQualType *self, const struct ZigClangASTContext *ctx);
972ZIG_EXTERN_C bool ZigClangType_isConstantArrayType(const ZigClangType *self);974ZIG_EXTERN_C bool ZigClangType_isConstantArrayType(const ZigClangType *self);
973ZIG_EXTERN_C const char *ZigClangType_getTypeClassName(const struct ZigClangType *self);975ZIG_EXTERN_C const char *ZigClangType_getTypeClassName(const struct ZigClangType *self);
974ZIG_EXTERN_C const struct ZigClangArrayType *ZigClangType_getAsArrayTypeUnsafe(const struct ZigClangType *self);976ZIG_EXTERN_C const struct ZigClangArrayType *ZigClangType_getAsArrayTypeUnsafe(const struct ZigClangType *self);
test/compare_output.zig+15-19
...@@ -22,7 +22,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -22,7 +22,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
22 \\22 \\
23 \\pub fn main() void {23 \\pub fn main() void {
24 \\ privateFunction();24 \\ privateFunction();
25 \\ const stdout = &getStdOut().outStream().stream;25 \\ const stdout = getStdOut().outStream();
26 \\ stdout.print("OK 2\n", .{}) catch unreachable;26 \\ stdout.print("OK 2\n", .{}) catch unreachable;
27 \\}27 \\}
28 \\28 \\
...@@ -37,7 +37,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -37,7 +37,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
37 \\// purposefully conflicting function with main.zig37 \\// purposefully conflicting function with main.zig
38 \\// but it's private so it should be OK38 \\// but it's private so it should be OK
39 \\fn privateFunction() void {39 \\fn privateFunction() void {
40 \\ const stdout = &getStdOut().outStream().stream;40 \\ const stdout = getStdOut().outStream();
41 \\ stdout.print("OK 1\n", .{}) catch unreachable;41 \\ stdout.print("OK 1\n", .{}) catch unreachable;
42 \\}42 \\}
43 \\43 \\
...@@ -63,7 +63,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -63,7 +63,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
63 tc.addSourceFile("foo.zig",63 tc.addSourceFile("foo.zig",
64 \\usingnamespace @import("std").io;64 \\usingnamespace @import("std").io;
65 \\pub fn foo_function() void {65 \\pub fn foo_function() void {
66 \\ const stdout = &getStdOut().outStream().stream;66 \\ const stdout = getStdOut().outStream();
67 \\ stdout.print("OK\n", .{}) catch unreachable;67 \\ stdout.print("OK\n", .{}) catch unreachable;
68 \\}68 \\}
69 );69 );
...@@ -74,7 +74,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -74,7 +74,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
74 \\74 \\
75 \\pub fn bar_function() void {75 \\pub fn bar_function() void {
76 \\ if (foo_function()) {76 \\ if (foo_function()) {
77 \\ const stdout = &getStdOut().outStream().stream;77 \\ const stdout = getStdOut().outStream();
78 \\ stdout.print("OK\n", .{}) catch unreachable;78 \\ stdout.print("OK\n", .{}) catch unreachable;
79 \\ }79 \\ }
80 \\}80 \\}
...@@ -106,7 +106,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -106,7 +106,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
106 \\pub const a_text = "OK\n";106 \\pub const a_text = "OK\n";
107 \\107 \\
108 \\pub fn ok() void {108 \\pub fn ok() void {
109 \\ const stdout = &io.getStdOut().outStream().stream;109 \\ const stdout = io.getStdOut().outStream();
110 \\ stdout.print(b_text, .{}) catch unreachable;110 \\ stdout.print(b_text, .{}) catch unreachable;
111 \\}111 \\}
112 );112 );
...@@ -124,7 +124,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -124,7 +124,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
124 \\const io = @import("std").io;124 \\const io = @import("std").io;
125 \\125 \\
126 \\pub fn main() void {126 \\pub fn main() void {
127 \\ const stdout = &io.getStdOut().outStream().stream;127 \\ const stdout = io.getStdOut().outStream();
128 \\ stdout.print("Hello, world!\n{d:4} {x:3} {c}\n", .{@as(u32, 12), @as(u16, 0x12), @as(u8, 'a')}) catch unreachable;128 \\ stdout.print("Hello, world!\n{d:4} {x:3} {c}\n", .{@as(u32, 12), @as(u16, 0x12), @as(u8, 'a')}) catch unreachable;
129 \\}129 \\}
130 , "Hello, world!\n 12 12 a\n");130 , "Hello, world!\n 12 12 a\n");
...@@ -267,7 +267,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -267,7 +267,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
267 \\ var x_local : i32 = print_ok(x);267 \\ var x_local : i32 = print_ok(x);
268 \\}268 \\}
269 \\fn print_ok(val: @TypeOf(x)) @TypeOf(foo) {269 \\fn print_ok(val: @TypeOf(x)) @TypeOf(foo) {
270 \\ const stdout = &io.getStdOut().outStream().stream;270 \\ const stdout = io.getStdOut().outStream();
271 \\ stdout.print("OK\n", .{}) catch unreachable;271 \\ stdout.print("OK\n", .{}) catch unreachable;
272 \\ return 0;272 \\ return 0;
273 \\}273 \\}
...@@ -349,7 +349,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -349,7 +349,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
349 \\pub fn main() void {349 \\pub fn main() void {
350 \\ const bar = Bar {.field2 = 13,};350 \\ const bar = Bar {.field2 = 13,};
351 \\ const foo = Foo {.field1 = bar,};351 \\ const foo = Foo {.field1 = bar,};
352 \\ const stdout = &io.getStdOut().outStream().stream;352 \\ const stdout = io.getStdOut().outStream();
353 \\ if (!foo.method()) {353 \\ if (!foo.method()) {
354 \\ stdout.print("BAD\n", .{}) catch unreachable;354 \\ stdout.print("BAD\n", .{}) catch unreachable;
355 \\ }355 \\ }
...@@ -363,7 +363,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -363,7 +363,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
363 cases.add("defer with only fallthrough",363 cases.add("defer with only fallthrough",
364 \\const io = @import("std").io;364 \\const io = @import("std").io;
365 \\pub fn main() void {365 \\pub fn main() void {
366 \\ const stdout = &io.getStdOut().outStream().stream;366 \\ const stdout = io.getStdOut().outStream();
367 \\ stdout.print("before\n", .{}) catch unreachable;367 \\ stdout.print("before\n", .{}) catch unreachable;
368 \\ defer stdout.print("defer1\n", .{}) catch unreachable;368 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
369 \\ defer stdout.print("defer2\n", .{}) catch unreachable;369 \\ defer stdout.print("defer2\n", .{}) catch unreachable;
...@@ -376,7 +376,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -376,7 +376,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
376 \\const io = @import("std").io;376 \\const io = @import("std").io;
377 \\const os = @import("std").os;377 \\const os = @import("std").os;
378 \\pub fn main() void {378 \\pub fn main() void {
379 \\ const stdout = &io.getStdOut().outStream().stream;379 \\ const stdout = io.getStdOut().outStream();
380 \\ stdout.print("before\n", .{}) catch unreachable;380 \\ stdout.print("before\n", .{}) catch unreachable;
381 \\ defer stdout.print("defer1\n", .{}) catch unreachable;381 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
382 \\ defer stdout.print("defer2\n", .{}) catch unreachable;382 \\ defer stdout.print("defer2\n", .{}) catch unreachable;
...@@ -393,7 +393,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -393,7 +393,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
393 \\ do_test() catch return;393 \\ do_test() catch return;
394 \\}394 \\}
395 \\fn do_test() !void {395 \\fn do_test() !void {
396 \\ const stdout = &io.getStdOut().outStream().stream;396 \\ const stdout = io.getStdOut().outStream();
397 \\ stdout.print("before\n", .{}) catch unreachable;397 \\ stdout.print("before\n", .{}) catch unreachable;
398 \\ defer stdout.print("defer1\n", .{}) catch unreachable;398 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
399 \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;399 \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;
...@@ -412,7 +412,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -412,7 +412,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
412 \\ do_test() catch return;412 \\ do_test() catch return;
413 \\}413 \\}
414 \\fn do_test() !void {414 \\fn do_test() !void {
415 \\ const stdout = &io.getStdOut().outStream().stream;415 \\ const stdout = io.getStdOut().outStream();
416 \\ stdout.print("before\n", .{}) catch unreachable;416 \\ stdout.print("before\n", .{}) catch unreachable;
417 \\ defer stdout.print("defer1\n", .{}) catch unreachable;417 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
418 \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;418 \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;
...@@ -429,7 +429,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -429,7 +429,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
429 \\const io = @import("std").io;429 \\const io = @import("std").io;
430 \\430 \\
431 \\pub fn main() void {431 \\pub fn main() void {
432 \\ const stdout = &io.getStdOut().outStream().stream;432 \\ const stdout = io.getStdOut().outStream();
433 \\ stdout.print(foo_txt, .{}) catch unreachable;433 \\ stdout.print(foo_txt, .{}) catch unreachable;
434 \\}434 \\}
435 , "1234\nabcd\n");435 , "1234\nabcd\n");
...@@ -448,9 +448,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -448,9 +448,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
448 \\448 \\
449 \\pub fn main() !void {449 \\pub fn main() !void {
450 \\ var args_it = std.process.args();450 \\ var args_it = std.process.args();
451 \\ var stdout_file = io.getStdOut();451 \\ const stdout = io.getStdOut().outStream();
452 \\ var stdout_adapter = stdout_file.outStream();
453 \\ const stdout = &stdout_adapter.stream;
454 \\ var index: usize = 0;452 \\ var index: usize = 0;
455 \\ _ = args_it.skip();453 \\ _ = args_it.skip();
456 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {454 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {
...@@ -489,9 +487,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {...@@ -489,9 +487,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
489 \\487 \\
490 \\pub fn main() !void {488 \\pub fn main() !void {
491 \\ var args_it = std.process.args();489 \\ var args_it = std.process.args();
492 \\ var stdout_file = io.getStdOut();490 \\ const stdout = io.getStdOut().outStream();
493 \\ var stdout_adapter = stdout_file.outStream();
494 \\ const stdout = &stdout_adapter.stream;
495 \\ var index: usize = 0;491 \\ var index: usize = 0;
496 \\ _ = args_it.skip();492 \\ _ = args_it.skip();
497 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {493 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {
test/compile_errors.zig+103-11
...@@ -2,6 +2,62 @@ const tests = @import("tests.zig");...@@ -2,6 +2,62 @@ 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("shift on type with non-power-of-two size",
6 \\export fn entry() void {
7 \\ const S = struct {
8 \\ fn a() void {
9 \\ var x: u24 = 42;
10 \\ _ = x >> 24;
11 \\ }
12 \\ fn b() void {
13 \\ var x: u24 = 42;
14 \\ _ = x << 24;
15 \\ }
16 \\ fn c() void {
17 \\ var x: u24 = 42;
18 \\ _ = @shlExact(x, 24);
19 \\ }
20 \\ fn d() void {
21 \\ var x: u24 = 42;
22 \\ _ = @shrExact(x, 24);
23 \\ }
24 \\ };
25 \\ S.a();
26 \\ S.b();
27 \\ S.c();
28 \\ S.d();
29 \\}
30 , &[_][]const u8{
31 "tmp.zig:5:19: error: RHS of shift is too large for LHS type",
32 "tmp.zig:9:19: error: RHS of shift is too large for LHS type",
33 "tmp.zig:13:17: error: RHS of shift is too large for LHS type",
34 "tmp.zig:17:17: error: RHS of shift is too large for LHS type",
35 });
36
37 cases.addTest("combination of noasync and async",
38 \\export fn entry() void {
39 \\ noasync {
40 \\ const bar = async foo();
41 \\ suspend;
42 \\ resume bar;
43 \\ }
44 \\}
45 \\fn foo() void {}
46 , &[_][]const u8{
47 "tmp.zig:3:21: error: async call in noasync scope",
48 "tmp.zig:4:9: error: suspend in noasync scope",
49 "tmp.zig:5:9: error: resume in noasync scope",
50 });
51
52 cases.add("atomicrmw with bool op not .Xchg",
53 \\export fn entry() void {
54 \\ var x = false;
55 \\ _ = @atomicRmw(bool, &x, .Add, true, .SeqCst);
56 \\}
57 , &[_][]const u8{
58 "tmp.zig:3:30: error: @atomicRmw with bool only allowed with .Xchg",
59 });
60
5 cases.addTest("@TypeOf with no arguments",61 cases.addTest("@TypeOf with no arguments",
6 \\export fn entry() void {62 \\export fn entry() void {
7 \\ _ = @TypeOf();63 \\ _ = @TypeOf();
...@@ -310,7 +366,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -310,7 +366,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
310 \\ _ = @atomicRmw(f32, &x, .And, 2, .SeqCst);366 \\ _ = @atomicRmw(f32, &x, .And, 2, .SeqCst);
311 \\}367 \\}
312 , &[_][]const u8{368 , &[_][]const u8{
313 "tmp.zig:3:29: error: @atomicRmw with float only works with .Xchg, .Add and .Sub",369 "tmp.zig:3:29: error: @atomicRmw with float only allowed with .Xchg, .Add and .Sub",
314 });370 });
315371
316 cases.add("intToPtr with misaligned address",372 cases.add("intToPtr with misaligned address",
...@@ -527,7 +583,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -527,7 +583,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
527 \\ _ = @atomicRmw(E, &x, .Add, .b, .SeqCst);583 \\ _ = @atomicRmw(E, &x, .Add, .b, .SeqCst);
528 \\}584 \\}
529 , &[_][]const u8{585 , &[_][]const u8{
530 "tmp.zig:9:27: error: @atomicRmw on enum only works with .Xchg",586 "tmp.zig:9:27: error: @atomicRmw with enum only allowed with .Xchg",
531 });587 });
532588
533 cases.add("disallow coercion from non-null-terminated pointer to null-terminated pointer",589 cases.add("disallow coercion from non-null-terminated pointer to null-terminated pointer",
...@@ -1592,7 +1648,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -1592,7 +1648,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
1592 \\ var y: [*c]c_void = x;1648 \\ var y: [*c]c_void = x;
1593 \\}1649 \\}
1594 , &[_][]const u8{1650 , &[_][]const u8{
1595 "tmp.zig:3:16: error: C pointers cannot point opaque types",1651 "tmp.zig:3:16: error: C pointers cannot point to opaque types",
1596 });1652 });
15971653
1598 cases.add("directly embedding opaque type in struct and union",1654 cases.add("directly embedding opaque type in struct and union",
...@@ -1610,9 +1666,14 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -1610,9 +1666,14 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
1610 \\export fn b() void {1666 \\export fn b() void {
1611 \\ var bar: Bar = undefined;1667 \\ var bar: Bar = undefined;
1612 \\}1668 \\}
1669 \\export fn c() void {
1670 \\ var baz: *@OpaqueType() = undefined;
1671 \\ const qux = .{baz.*};
1672 \\}
1613 , &[_][]const u8{1673 , &[_][]const u8{
1614 "tmp.zig:3:8: error: opaque types have unknown size and therefore cannot be directly embedded in structs",1674 "tmp.zig:3:5: error: opaque types have unknown size and therefore cannot be directly embedded in structs",
1615 "tmp.zig:7:10: error: opaque types have unknown size and therefore cannot be directly embedded in unions",1675 "tmp.zig:7:5: error: opaque types have unknown size and therefore cannot be directly embedded in unions",
1676 "tmp.zig:17:22: error: opaque types have unknown size and therefore cannot be directly embedded in structs",
1616 });1677 });
16171678
1618 cases.add("implicit cast between C pointer and Zig pointer - bad const/align/child",1679 cases.add("implicit cast between C pointer and Zig pointer - bad const/align/child",
...@@ -3605,11 +3666,11 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -3605,11 +3666,11 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
3605 cases.add("array access of non array",3666 cases.add("array access of non array",
3606 \\export fn f() void {3667 \\export fn f() void {
3607 \\ var bad : bool = undefined;3668 \\ var bad : bool = undefined;
3608 \\ bad[bad] = bad[bad];3669 \\ bad[0] = bad[0];
3609 \\}3670 \\}
3610 \\export fn g() void {3671 \\export fn g() void {
3611 \\ var bad : bool = undefined;3672 \\ var bad : bool = undefined;
3612 \\ _ = bad[bad];3673 \\ _ = bad[0];
3613 \\}3674 \\}
3614 , &[_][]const u8{3675 , &[_][]const u8{
3615 "tmp.zig:3:8: error: array access of non-array type 'bool'",3676 "tmp.zig:3:8: error: array access of non-array type 'bool'",
...@@ -4009,8 +4070,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -4009,8 +4070,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
4009 \\}4070 \\}
4010 \\export fn entry() u16 { return f(); }4071 \\export fn entry() u16 { return f(); }
4011 , &[_][]const u8{4072 , &[_][]const u8{
4012 "tmp.zig:3:14: error: RHS of shift is too large for LHS type",4073 "tmp.zig:3:17: error: integer value 8 cannot be coerced to type 'u3'",
4013 "tmp.zig:3:17: note: value 8 cannot fit into type u3",
4014 });4074 });
40154075
4016 cases.add("missing function call param",4076 cases.add("missing function call param",
...@@ -6538,9 +6598,41 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {...@@ -6538,9 +6598,41 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
6538 \\export fn bar() !FooType {6598 \\export fn bar() !FooType {
6539 \\ return error.InvalidValue;6599 \\ return error.InvalidValue;
6540 \\}6600 \\}
6601 \\export fn bav() !@TypeOf(null) {
6602 \\ return error.InvalidValue;
6603 \\}
6604 \\export fn baz() !@TypeOf(undefined) {
6605 \\ return error.InvalidValue;
6606 \\}
6541 , &[_][]const u8{6607 , &[_][]const u8{
6542 "tmp.zig:2:18: error: opaque return type 'FooType' not allowed",6608 "tmp.zig:2:18: error: Opaque return type 'FooType' not allowed",
6543 "tmp.zig:1:1: note: declared here",6609 "tmp.zig:1:1: note: type declared here",
6610 "tmp.zig:5:18: error: Null return type '(null)' not allowed",
6611 "tmp.zig:8:18: error: Undefined return type '(undefined)' not allowed",
6612 });
6613
6614 cases.add("generic function returning opaque type",
6615 \\const FooType = @OpaqueType();
6616 \\fn generic(comptime T: type) !T {
6617 \\ return undefined;
6618 \\}
6619 \\export fn bar() void {
6620 \\ _ = generic(FooType);
6621 \\}
6622 \\export fn bav() void {
6623 \\ _ = generic(@TypeOf(null));
6624 \\}
6625 \\export fn baz() void {
6626 \\ _ = generic(@TypeOf(undefined));
6627 \\}
6628 , &[_][]const u8{
6629 "tmp.zig:6:16: error: call to generic function with Opaque return type 'FooType' not allowed",
6630 "tmp.zig:2:1: note: function declared here",
6631 "tmp.zig:1:1: note: type declared here",
6632 "tmp.zig:9:16: error: call to generic function with Null return type '(null)' not allowed",
6633 "tmp.zig:2:1: note: function declared here",
6634 "tmp.zig:12:16: error: call to generic function with Undefined return type '(undefined)' not allowed",
6635 "tmp.zig:2:1: note: function declared here",
6544 });6636 });
65456637
6546 cases.add( // fixed bug #20326638 cases.add( // fixed bug #2032
test/run_translated_c.zig-18
...@@ -195,22 +195,4 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {...@@ -195,22 +195,4 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
195 \\ return 0;195 \\ return 0;
196 \\}196 \\}
197 , "");197 , "");
198
199 cases.add("cast from pointer to opaque type to struct",
200 \\#include <stdio.h>
201 \\typedef struct
202 \\{
203 \\ int i;
204 \\}
205 \\StructType,*StructPtrType;
206 \\
207 \\typedef struct OpaqueStruct OpaqueStructTypedef;
208 \\#define Macro(opaquePtr) (((StructPtrType)(opaquePtr))->i)
209 \\int main(int argc, char **argv) {
210 \\ StructType localStruct = {88};
211 \\ OpaqueStructTypedef *opaquePtrToLocal = &localStruct;
212 \\ printf("%d!\n", Macro(opaquePtrToLocal));
213 \\ return 0;
214 \\}
215 , "88!\n");
216}198}
test/runtime_safety.zig+30
...@@ -1,6 +1,36 @@...@@ -1,6 +1,36 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
22
3pub fn addCases(cases: *tests.CompareOutputContext) void {3pub fn addCases(cases: *tests.CompareOutputContext) void {
4 cases.addRuntimeSafety("shift left by huge amount",
5 \\const std = @import("std");
6 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
7 \\ if (std.mem.eql(u8, message, "shift amount is greater than the type size")) {
8 \\ std.process.exit(126); // good
9 \\ }
10 \\ std.process.exit(0); // test failed
11 \\}
12 \\pub fn main() void {
13 \\ var x: u24 = 42;
14 \\ var y: u5 = 24;
15 \\ var z = x >> y;
16 \\}
17 );
18
19 cases.addRuntimeSafety("shift right by huge amount",
20 \\const std = @import("std");
21 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
22 \\ if (std.mem.eql(u8, message, "shift amount is greater than the type size")) {
23 \\ std.process.exit(126); // good
24 \\ }
25 \\ std.process.exit(0); // test failed
26 \\}
27 \\pub fn main() void {
28 \\ var x: u24 = 42;
29 \\ var y: u5 = 24;
30 \\ var z = x << y;
31 \\}
32 );
33
4 cases.addRuntimeSafety("slice sentinel mismatch - optional pointers",34 cases.addRuntimeSafety("slice sentinel mismatch - optional pointers",
5 \\const std = @import("std");35 \\const std = @import("std");
6 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {36 \\pub fn panic(message: []const u8, stack_trace: ?*@import("builtin").StackTrace) noreturn {
test/stage1/behavior/alignof.zig+21
...@@ -15,3 +15,24 @@ test "@alignOf(T) before referencing T" {...@@ -15,3 +15,24 @@ test "@alignOf(T) before referencing T" {
15 comptime expect(@alignOf(Foo) == 4);15 comptime expect(@alignOf(Foo) == 4);
16 }16 }
17}17}
18
19test "comparison of @alignOf(T) against zero" {
20 {
21 const T = struct { x: u32 };
22 expect(!(@alignOf(T) == 0));
23 expect(@alignOf(T) != 0);
24 expect(!(@alignOf(T) < 0));
25 expect(!(@alignOf(T) <= 0));
26 expect(@alignOf(T) > 0);
27 expect(@alignOf(T) >= 0);
28 }
29 {
30 const T = struct {};
31 expect(@alignOf(T) == 0);
32 expect(!(@alignOf(T) != 0));
33 expect(!(@alignOf(T) < 0));
34 expect(@alignOf(T) <= 0);
35 expect(!(@alignOf(T) > 0));
36 expect(@alignOf(T) >= 0);
37 }
38}
test/stage1/behavior/array.zig+17-1
...@@ -1,6 +1,8 @@...@@ -1,6 +1,8 @@
1const std = @import("std");1const std = @import("std");
2const expect = std.testing.expect;2const testing = std.testing;
3const mem = std.mem;3const mem = std.mem;
4const expect = testing.expect;
5const expectEqual = testing.expectEqual;
46
5test "arrays" {7test "arrays" {
6 var array: [5]u32 = undefined;8 var array: [5]u32 = undefined;
...@@ -360,3 +362,17 @@ test "access the null element of a null terminated array" {...@@ -360,3 +362,17 @@ test "access the null element of a null terminated array" {
360 S.doTheTest();362 S.doTheTest();
361 comptime S.doTheTest();363 comptime S.doTheTest();
362}364}
365
366test "type deduction for array subscript expression" {
367 const S = struct {
368 fn doTheTest() void {
369 var array = [_]u8{ 0x55, 0xAA };
370 var v0 = true;
371 expectEqual(@as(u8, 0xAA), array[if (v0) 1 else 0]);
372 var v1 = false;
373 expectEqual(@as(u8, 0x55), array[if (v1) 1 else 0]);
374 }
375 };
376 S.doTheTest();
377 comptime S.doTheTest();
378}
test/stage1/behavior/async_fn.zig+16
...@@ -1531,3 +1531,19 @@ test "noasync await" {...@@ -1531,3 +1531,19 @@ test "noasync await" {
1531 S.doTheTest();1531 S.doTheTest();
1532 expect(S.finished);1532 expect(S.finished);
1533}1533}
1534
1535test "noasync on function calls" {
1536 const S0 = struct {
1537 b: i32 = 42,
1538 };
1539 const S1 = struct {
1540 fn c() S0 {
1541 return S0{};
1542 }
1543 fn d() !S0 {
1544 return S0{};
1545 }
1546 };
1547 expectEqual(@as(i32, 42), noasync S1.c().b);
1548 expectEqual(@as(i32, 42), (try noasync S1.d()).b);
1549}
test/stage1/behavior/atomics.zig+68-13
...@@ -2,29 +2,32 @@ const std = @import("std");...@@ -2,29 +2,32 @@ const std = @import("std");
2const expect = std.testing.expect;2const expect = std.testing.expect;
3const expectEqual = std.testing.expectEqual;3const expectEqual = std.testing.expectEqual;
4const builtin = @import("builtin");4const builtin = @import("builtin");
5const AtomicRmwOp = builtin.AtomicRmwOp;
6const AtomicOrder = builtin.AtomicOrder;
75
8test "cmpxchg" {6test "cmpxchg" {
7 testCmpxchg();
8 comptime testCmpxchg();
9}
10
11fn testCmpxchg() void {
9 var x: i32 = 1234;12 var x: i32 = 1234;
10 if (@cmpxchgWeak(i32, &x, 99, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {13 if (@cmpxchgWeak(i32, &x, 99, 5678, .SeqCst, .SeqCst)) |x1| {
11 expect(x1 == 1234);14 expect(x1 == 1234);
12 } else {15 } else {
13 @panic("cmpxchg should have failed");16 @panic("cmpxchg should have failed");
14 }17 }
1518
16 while (@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {19 while (@cmpxchgWeak(i32, &x, 1234, 5678, .SeqCst, .SeqCst)) |x1| {
17 expect(x1 == 1234);20 expect(x1 == 1234);
18 }21 }
19 expect(x == 5678);22 expect(x == 5678);
2023
21 expect(@cmpxchgStrong(i32, &x, 5678, 42, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);24 expect(@cmpxchgStrong(i32, &x, 5678, 42, .SeqCst, .SeqCst) == null);
22 expect(x == 42);25 expect(x == 42);
23}26}
2427
25test "fence" {28test "fence" {
26 var x: i32 = 1234;29 var x: i32 = 1234;
27 @fence(AtomicOrder.SeqCst);30 @fence(.SeqCst);
28 x = 5678;31 x = 5678;
29}32}
3033
...@@ -36,18 +39,18 @@ test "atomicrmw and atomicload" {...@@ -36,18 +39,18 @@ test "atomicrmw and atomicload" {
36}39}
3740
38fn testAtomicRmw(ptr: *u8) void {41fn testAtomicRmw(ptr: *u8) void {
39 const prev_value = @atomicRmw(u8, ptr, AtomicRmwOp.Xchg, 42, AtomicOrder.SeqCst);42 const prev_value = @atomicRmw(u8, ptr, .Xchg, 42, .SeqCst);
40 expect(prev_value == 200);43 expect(prev_value == 200);
41 comptime {44 comptime {
42 var x: i32 = 1234;45 var x: i32 = 1234;
43 const y: i32 = 12345;46 const y: i32 = 12345;
44 expect(@atomicLoad(i32, &x, AtomicOrder.SeqCst) == 1234);47 expect(@atomicLoad(i32, &x, .SeqCst) == 1234);
45 expect(@atomicLoad(i32, &y, AtomicOrder.SeqCst) == 12345);48 expect(@atomicLoad(i32, &y, .SeqCst) == 12345);
46 }49 }
47}50}
4851
49fn testAtomicLoad(ptr: *u8) void {52fn testAtomicLoad(ptr: *u8) void {
50 const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst);53 const x = @atomicLoad(u8, ptr, .SeqCst);
51 expect(x == 42);54 expect(x == 42);
52}55}
5356
...@@ -56,18 +59,18 @@ test "cmpxchg with ptr" {...@@ -56,18 +59,18 @@ test "cmpxchg with ptr" {
56 var data2: i32 = 5678;59 var data2: i32 = 5678;
57 var data3: i32 = 9101;60 var data3: i32 = 9101;
58 var x: *i32 = &data1;61 var x: *i32 = &data1;
59 if (@cmpxchgWeak(*i32, &x, &data2, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {62 if (@cmpxchgWeak(*i32, &x, &data2, &data3, .SeqCst, .SeqCst)) |x1| {
60 expect(x1 == &data1);63 expect(x1 == &data1);
61 } else {64 } else {
62 @panic("cmpxchg should have failed");65 @panic("cmpxchg should have failed");
63 }66 }
6467
65 while (@cmpxchgWeak(*i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {68 while (@cmpxchgWeak(*i32, &x, &data1, &data3, .SeqCst, .SeqCst)) |x1| {
66 expect(x1 == &data1);69 expect(x1 == &data1);
67 }70 }
68 expect(x == &data3);71 expect(x == &data3);
6972
70 expect(@cmpxchgStrong(*i32, &x, &data3, &data2, AtomicOrder.SeqCst, AtomicOrder.SeqCst) == null);73 expect(@cmpxchgStrong(*i32, &x, &data3, &data2, .SeqCst, .SeqCst) == null);
71 expect(x == &data2);74 expect(x == &data2);
72}75}
7376
...@@ -151,6 +154,7 @@ test "atomicrmw with floats" {...@@ -151,6 +154,7 @@ test "atomicrmw with floats" {
151 return error.SkipZigTest;154 return error.SkipZigTest;
152 }155 }
153 testAtomicRmwFloat();156 testAtomicRmwFloat();
157 comptime testAtomicRmwFloat();
154}158}
155159
156fn testAtomicRmwFloat() void {160fn testAtomicRmwFloat() void {
...@@ -163,3 +167,54 @@ fn testAtomicRmwFloat() void {...@@ -163,3 +167,54 @@ fn testAtomicRmwFloat() void {
163 _ = @atomicRmw(f32, &x, .Sub, 2, .SeqCst);167 _ = @atomicRmw(f32, &x, .Sub, 2, .SeqCst);
164 expect(x == 4);168 expect(x == 4);
165}169}
170
171test "atomicrmw with ints" {
172 testAtomicRmwInt();
173 comptime testAtomicRmwInt();
174}
175
176fn testAtomicRmwInt() void {
177 var x: u8 = 1;
178 var res = @atomicRmw(u8, &x, .Xchg, 3, .SeqCst);
179 expect(x == 3 and res == 1);
180 _ = @atomicRmw(u8, &x, .Add, 3, .SeqCst);
181 expect(x == 6);
182 _ = @atomicRmw(u8, &x, .Sub, 1, .SeqCst);
183 expect(x == 5);
184 _ = @atomicRmw(u8, &x, .And, 4, .SeqCst);
185 expect(x == 4);
186 _ = @atomicRmw(u8, &x, .Nand, 4, .SeqCst);
187 expect(x == 0xfb);
188 _ = @atomicRmw(u8, &x, .Or, 6, .SeqCst);
189 expect(x == 0xff);
190 _ = @atomicRmw(u8, &x, .Xor, 2, .SeqCst);
191 expect(x == 0xfd);
192
193 // TODO https://github.com/ziglang/zig/issues/4724
194 if (builtin.arch == .mipsel) return;
195 _ = @atomicRmw(u8, &x, .Max, 1, .SeqCst);
196 expect(x == 0xfd);
197 _ = @atomicRmw(u8, &x, .Min, 1, .SeqCst);
198 expect(x == 1);
199}
200
201test "atomics with different types" {
202 testAtomicsWithType(bool, true, false);
203 inline for (.{ u1, i5, u15 }) |T| {
204 var x: T = 0;
205 testAtomicsWithType(T, 0, 1);
206 }
207 testAtomicsWithType(u0, 0, 0);
208 testAtomicsWithType(i0, 0, 0);
209}
210
211fn testAtomicsWithType(comptime T: type, a: T, b: T) void {
212 var x: T = b;
213 @atomicStore(T, &x, a, .SeqCst);
214 expect(x == a);
215 expect(@atomicLoad(T, &x, .SeqCst) == a);
216 expect(@atomicRmw(T, &x, .Xchg, b, .SeqCst) == a);
217 expect(@cmpxchgStrong(T, &x, b, a, .SeqCst, .SeqCst) == null);
218 if (@sizeOf(T) != 0)
219 expect(@cmpxchgStrong(T, &x, b, a, .SeqCst, .SeqCst).? == a);
220}
test/stage1/behavior/math.zig+19
...@@ -449,6 +449,25 @@ fn testShrExact(x: u8) void {...@@ -449,6 +449,25 @@ fn testShrExact(x: u8) void {
449 expect(shifted == 0b00101101);449 expect(shifted == 0b00101101);
450}450}
451451
452test "shift left/right on u0 operand" {
453 const S = struct {
454 fn doTheTest() void {
455 var x: u0 = 0;
456 var y: u0 = 0;
457 expectEqual(@as(u0, 0), x << 0);
458 expectEqual(@as(u0, 0), x >> 0);
459 expectEqual(@as(u0, 0), x << y);
460 expectEqual(@as(u0, 0), x >> y);
461 expectEqual(@as(u0, 0), @shlExact(x, 0));
462 expectEqual(@as(u0, 0), @shrExact(x, 0));
463 expectEqual(@as(u0, 0), @shlExact(x, y));
464 expectEqual(@as(u0, 0), @shrExact(x, y));
465 }
466 };
467 S.doTheTest();
468 comptime S.doTheTest();
469}
470
452test "comptime_int addition" {471test "comptime_int addition" {
453 comptime {472 comptime {
454 expect(35361831660712422535336160538497375248 + 101752735581729509668353361206450473702 == 137114567242441932203689521744947848950);473 expect(35361831660712422535336160538497375248 + 101752735581729509668353361206450473702 == 137114567242441932203689521744947848950);
test/stage1/behavior/optional.zig+23
...@@ -175,3 +175,26 @@ test "0-bit child type coerced to optional return ptr result location" {...@@ -175,3 +175,26 @@ test "0-bit child type coerced to optional return ptr result location" {
175 S.doTheTest();175 S.doTheTest();
176 comptime S.doTheTest();176 comptime S.doTheTest();
177}177}
178
179test "0-bit child type coerced to optional" {
180 const S = struct {
181 fn doTheTest() void {
182 var it: Foo = .{
183 .list = undefined,
184 };
185 expect(it.foo() != null);
186 }
187
188 const Empty = struct {};
189 const Foo = struct {
190 list: [10]Empty,
191
192 fn foo(self: *Foo) ?*Empty {
193 const data = &self.list[0];
194 return data;
195 }
196 };
197 };
198 S.doTheTest();
199 comptime S.doTheTest();
200}
test/standalone/guess_number/main.zig+1-1
...@@ -4,7 +4,7 @@ const io = std.io;...@@ -4,7 +4,7 @@ const io = std.io;
4const fmt = std.fmt;4const fmt = std.fmt;
55
6pub fn main() !void {6pub fn main() !void {
7 const stdout = &io.getStdOut().outStream().stream;7 const stdout = io.getStdOut().outStream();
8 const stdin = io.getStdIn();8 const stdin = io.getStdIn();
99
10 try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{});10 try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{});
test/tests.zig+4-10
...@@ -594,12 +594,9 @@ pub const StackTracesContext = struct {...@@ -594,12 +594,9 @@ pub const StackTracesContext = struct {
594 }594 }
595 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) });595 child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) });
596596
597 var stdout_file_in_stream = child.stdout.?.inStream();597 const stdout = child.stdout.?.inStream().readAllAlloc(b.allocator, max_stdout_size) catch unreachable;
598 var stderr_file_in_stream = child.stderr.?.inStream();
599
600 const stdout = stdout_file_in_stream.stream.readAllAlloc(b.allocator, max_stdout_size) catch unreachable;
601 defer b.allocator.free(stdout);598 defer b.allocator.free(stdout);
602 const stderr = stderr_file_in_stream.stream.readAllAlloc(b.allocator, max_stdout_size) catch unreachable;599 const stderr = child.stderr.?.inStream().readAllAlloc(b.allocator, max_stdout_size) catch unreachable;
603 defer b.allocator.free(stderr);600 defer b.allocator.free(stderr);
604601
605 const term = child.wait() catch |err| {602 const term = child.wait() catch |err| {
...@@ -826,11 +823,8 @@ pub const CompileErrorContext = struct {...@@ -826,11 +823,8 @@ pub const CompileErrorContext = struct {
826 var stdout_buf = Buffer.initNull(b.allocator);823 var stdout_buf = Buffer.initNull(b.allocator);
827 var stderr_buf = Buffer.initNull(b.allocator);824 var stderr_buf = Buffer.initNull(b.allocator);
828825
829 var stdout_file_in_stream = child.stdout.?.inStream();826 child.stdout.?.inStream().readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable;
830 var stderr_file_in_stream = child.stderr.?.inStream();827 child.stderr.?.inStream().readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable;
831
832 stdout_file_in_stream.stream.readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable;
833 stderr_file_in_stream.stream.readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable;
834828
835 const term = child.wait() catch |err| {829 const term = child.wait() catch |err| {
836 debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });830 debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });
test/translate_c.zig+43-20
...@@ -3,6 +3,44 @@ const std = @import("std");...@@ -3,6 +3,44 @@ const std = @import("std");
3const CrossTarget = std.zig.CrossTarget;3const CrossTarget = std.zig.CrossTarget;
44
5pub fn addCases(cases: *tests.TranslateCContext) void {5pub fn addCases(cases: *tests.TranslateCContext) void {
6 cases.add("correct semicolon after infixop",
7 \\#define __ferror_unlocked_body(_fp) (((_fp)->_flags & _IO_ERR_SEEN) != 0)
8 , &[_][]const u8{
9 \\pub inline fn __ferror_unlocked_body(_fp: var) @TypeOf(((_fp.*._flags) & _IO_ERR_SEEN) != 0) {
10 \\ return ((_fp.*._flags) & _IO_ERR_SEEN) != 0;
11 \\}
12 });
13
14 cases.add("c booleans are just ints",
15 \\#define FOO(x) ((x >= 0) + (x >= 0))
16 \\#define BAR 1 && 2 > 4
17 , &[_][]const u8{
18 \\pub inline fn FOO(x: var) @TypeOf(@boolToInt(x >= 0) + @boolToInt(x >= 0)) {
19 \\ return @boolToInt(x >= 0) + @boolToInt(x >= 0);
20 \\}
21 ,
22 \\pub const BAR = (1 != 0) and (2 > 4);
23 });
24
25 cases.add("struct with aligned fields",
26 \\struct foo {
27 \\ __attribute__((aligned(1))) short bar;
28 \\};
29 , &[_][]const u8{
30 \\pub const struct_foo = extern struct {
31 \\ bar: c_short align(1),
32 \\};
33 });
34
35 cases.add("structs with VLAs are rejected",
36 \\struct foo { int x; int y[]; };
37 \\struct bar { int x; int y[0]; };
38 , &[_][]const u8{
39 \\pub const struct_foo = @OpaqueType();
40 ,
41 \\pub const struct_bar = @OpaqueType();
42 });
43
6 cases.add("nested loops without blocks",44 cases.add("nested loops without blocks",
7 \\void foo() {45 \\void foo() {
8 \\ while (0) while (0) {}46 \\ while (0) while (0) {}
...@@ -1420,7 +1458,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1420,7 +1458,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1420 cases.add("macro pointer cast",1458 cases.add("macro pointer cast",
1421 \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)1459 \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)
1422 , &[_][]const u8{1460 , &[_][]const u8{
1423 \\pub const NRF_GPIO = (if (@typeInfo(@TypeOf(NRF_GPIO_BASE)) == .Pointer) @ptrCast([*c]NRF_GPIO_Type, @alignCast(@alignOf([*c]NRF_GPIO_Type.Child), NRF_GPIO_BASE)) else if (@typeInfo(@TypeOf(NRF_GPIO_BASE)) == .Int) @intToPtr([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else @as([*c]NRF_GPIO_Type, NRF_GPIO_BASE));1461 \\pub const NRF_GPIO = (if (@typeInfo(@TypeOf(NRF_GPIO_BASE)) == .Pointer) @ptrCast([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else if (@typeInfo(@TypeOf(NRF_GPIO_BASE)) == .Int and @typeInfo([*c]NRF_GPIO_Type) == .Pointer) @intToPtr([*c]NRF_GPIO_Type, NRF_GPIO_BASE) else @as([*c]NRF_GPIO_Type, NRF_GPIO_BASE));
1424 });1462 });
14251463
1426 cases.add("basic macro function",1464 cases.add("basic macro function",
...@@ -1592,7 +1630,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -1592,7 +1630,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
1592 cases.add("shadowing primitive types",1630 cases.add("shadowing primitive types",
1593 \\unsigned anyerror = 2;1631 \\unsigned anyerror = 2;
1594 , &[_][]const u8{1632 , &[_][]const u8{
1595 \\pub export var _anyerror: c_uint = @bitCast(c_uint, @as(c_int, 2));1633 \\pub export var anyerror_1: c_uint = @bitCast(c_uint, @as(c_int, 2));
1596 });1634 });
15971635
1598 cases.add("floats",1636 cases.add("floats",
...@@ -2604,11 +2642,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -2604,11 +2642,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
2604 \\#define FOO(bar) baz((void *)(baz))2642 \\#define FOO(bar) baz((void *)(baz))
2605 \\#define BAR (void*) a2643 \\#define BAR (void*) a
2606 , &[_][]const u8{2644 , &[_][]const u8{
2607 \\pub inline fn FOO(bar: var) @TypeOf(baz((if (@typeInfo(@TypeOf(baz)) == .Pointer) @ptrCast(*c_void, @alignCast(@alignOf(*c_void.Child), baz)) else if (@typeInfo(@TypeOf(baz)) == .Int) @intToPtr(*c_void, baz) else @as(*c_void, baz)))) {2645 \\pub inline fn FOO(bar: var) @TypeOf(baz((if (@typeInfo(@TypeOf(baz)) == .Pointer) @ptrCast(*c_void, baz) else if (@typeInfo(@TypeOf(baz)) == .Int and @typeInfo(*c_void) == .Pointer) @intToPtr(*c_void, baz) else @as(*c_void, baz)))) {
2608 \\ return baz((if (@typeInfo(@TypeOf(baz)) == .Pointer) @ptrCast(*c_void, @alignCast(@alignOf(*c_void.Child), baz)) else if (@typeInfo(@TypeOf(baz)) == .Int) @intToPtr(*c_void, baz) else @as(*c_void, baz)));2646 \\ return baz((if (@typeInfo(@TypeOf(baz)) == .Pointer) @ptrCast(*c_void, baz) else if (@typeInfo(@TypeOf(baz)) == .Int and @typeInfo(*c_void) == .Pointer) @intToPtr(*c_void, baz) else @as(*c_void, baz)));
2609 \\}2647 \\}
2610 ,2648 ,
2611 \\pub const BAR = (if (@typeInfo(@TypeOf(a)) == .Pointer) @ptrCast(*c_void, @alignCast(@alignOf(*c_void.Child), a)) else if (@typeInfo(@TypeOf(a)) == .Int) @intToPtr(*c_void, a) else @as(*c_void, a));2649 \\pub const BAR = (if (@typeInfo(@TypeOf(a)) == .Pointer) @ptrCast(*c_void, a) else if (@typeInfo(@TypeOf(a)) == .Int and @typeInfo(*c_void) == .Pointer) @intToPtr(*c_void, a) else @as(*c_void, a));
2612 });2650 });
26132651
2614 cases.add("macro conditional operator",2652 cases.add("macro conditional operator",
...@@ -2770,19 +2808,4 @@ pub fn addCases(cases: *tests.TranslateCContext) void {...@@ -2770,19 +2808,4 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
2770 \\ return if (x > y) x else y;2808 \\ return if (x > y) x else y;
2771 \\}2809 \\}
2772 });2810 });
2773
2774 cases.add("Make sure casts are grouped",
2775 \\typedef struct
2776 \\{
2777 \\ int i;
2778 \\}
2779 \\*_XPrivDisplay;
2780 \\typedef struct _XDisplay Display;
2781 \\#define DefaultScreen(dpy) (((_XPrivDisplay)(dpy))->default_screen)
2782 \\
2783 , &[_][]const u8{
2784 \\pub inline fn DefaultScreen(dpy: var) @TypeOf((if (@typeInfo(@TypeOf(dpy)) == .Pointer) @ptrCast(_XPrivDisplay, @alignCast(@alignOf(_XPrivDisplay.Child), dpy)) else if (@typeInfo(@TypeOf(dpy)) == .Int) @intToPtr(_XPrivDisplay, dpy) else @as(_XPrivDisplay, dpy)).*.default_screen) {
2785 \\ return (if (@typeInfo(@TypeOf(dpy)) == .Pointer) @ptrCast(_XPrivDisplay, @alignCast(@alignOf(_XPrivDisplay.Child), dpy)) else if (@typeInfo(@TypeOf(dpy)) == .Int) @intToPtr(_XPrivDisplay, dpy) else @as(_XPrivDisplay, dpy)).*.default_screen;
2786 \\}
2787 });
2788}2811}