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
signature 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 @@
33set -x
44set -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
136sudo pkg update -fq
147sudo pkg install -y cmake py27-s3cmd wget curl jq
158
doc/docgen.zig+44-51
......@@ -40,12 +40,9 @@ pub fn main() !void {
4040 var out_file = try fs.cwd().createFile(out_file_name, .{});
4141 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);
46
47 var file_out_stream = out_file.outStream();
48 var buffered_out_stream = io.BufferedOutStream(fs.File.WriteError).init(&file_out_stream.stream);
45 var buffered_out_stream = io.bufferedOutStream(out_file.outStream());
4946
5047 var tokenizer = Tokenizer.init(in_file_name, input_file_bytes);
5148 var toc = try genToc(allocator, &tokenizer);
......@@ -53,7 +50,7 @@ pub fn main() !void {
5350 try fs.cwd().makePath(tmp_dir_name);
5451 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);
5754 try buffered_out_stream.flush();
5855}
5956
......@@ -327,8 +324,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
327324 var toc_buf = try std.Buffer.initSize(allocator, 0);
328325 defer toc_buf.deinit();
329326
330 var toc_buf_adapter = io.BufferOutStream.init(&toc_buf);
331 var toc = &toc_buf_adapter.stream;
327 var toc = toc_buf.outStream();
332328
333329 var nodes = std.ArrayList(Node).init(allocator);
334330 defer nodes.deinit();
......@@ -342,7 +338,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
342338 if (header_stack_size != 0) {
343339 return parseError(tokenizer, token, "unbalanced headers", .{});
344340 }
345 try toc.write(" </ul>\n");
341 try toc.writeAll(" </ul>\n");
346342 break;
347343 },
348344 Token.Id.Content => {
......@@ -407,7 +403,7 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
407403 if (last_columns) |n| {
408404 try toc.print("<ul style=\"columns: {}\">\n", .{n});
409405 } else {
410 try toc.write("<ul>\n");
406 try toc.writeAll("<ul>\n");
411407 }
412408 } else {
413409 last_action = Action.Open;
......@@ -424,9 +420,9 @@ fn genToc(allocator: *mem.Allocator, tokenizer: *Tokenizer) !Toc {
424420
425421 if (last_action == Action.Close) {
426422 try toc.writeByteNTimes(' ', 8 + header_stack_size * 4);
427 try toc.write("</ul></li>\n");
423 try toc.writeAll("</ul></li>\n");
428424 } else {
429 try toc.write("</li>\n");
425 try toc.writeAll("</li>\n");
430426 last_action = Action.Close;
431427 }
432428 } else if (mem.eql(u8, tag_name, "see_also")) {
......@@ -614,8 +610,7 @@ fn urlize(allocator: *mem.Allocator, input: []const u8) ![]u8 {
614610 var buf = try std.Buffer.initSize(allocator, 0);
615611 defer buf.deinit();
616612
617 var buf_adapter = io.BufferOutStream.init(&buf);
618 var out = &buf_adapter.stream;
613 const out = buf.outStream();
619614 for (input) |c| {
620615 switch (c) {
621616 'a'...'z', 'A'...'Z', '_', '-', '0'...'9' => {
......@@ -634,8 +629,7 @@ fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
634629 var buf = try std.Buffer.initSize(allocator, 0);
635630 defer buf.deinit();
636631
637 var buf_adapter = io.BufferOutStream.init(&buf);
638 var out = &buf_adapter.stream;
632 const out = buf.outStream();
639633 try writeEscaped(out, input);
640634 return buf.toOwnedSlice();
641635}
......@@ -643,10 +637,10 @@ fn escapeHtml(allocator: *mem.Allocator, input: []const u8) ![]u8 {
643637fn writeEscaped(out: var, input: []const u8) !void {
644638 for (input) |c| {
645639 try switch (c) {
646 '&' => out.write("&amp;"),
647 '<' => out.write("&lt;"),
648 '>' => out.write("&gt;"),
649 '"' => out.write("&quot;"),
640 '&' => out.writeAll("&amp;"),
641 '<' => out.writeAll("&lt;"),
642 '>' => out.writeAll("&gt;"),
643 '"' => out.writeAll("&quot;"),
650644 else => out.writeByte(c),
651645 };
652646 }
......@@ -681,8 +675,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
681675 var buf = try std.Buffer.initSize(allocator, 0);
682676 defer buf.deinit();
683677
684 var buf_adapter = io.BufferOutStream.init(&buf);
685 var out = &buf_adapter.stream;
678 var out = buf.outStream();
686679 var number_start_index: usize = undefined;
687680 var first_number: usize = undefined;
688681 var second_number: usize = undefined;
......@@ -743,7 +736,7 @@ fn termColor(allocator: *mem.Allocator, input: []const u8) ![]u8 {
743736 'm' => {
744737 state = TermState.Start;
745738 while (open_span_count != 0) : (open_span_count -= 1) {
746 try out.write("</span>");
739 try out.writeAll("</span>");
747740 }
748741 if (first_number != 0 or second_number != 0) {
749742 try out.print("<span class=\"t{}_{}\">", .{ first_number, second_number });
......@@ -774,7 +767,7 @@ fn isType(name: []const u8) bool {
774767
775768fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Token, raw_src: []const u8) !void {
776769 const src = mem.trim(u8, raw_src, " \n");
777 try out.write("<code class=\"zig\">");
770 try out.writeAll("<code class=\"zig\">");
778771 var tokenizer = std.zig.Tokenizer.init(src);
779772 var index: usize = 0;
780773 var next_tok_is_fn = false;
......@@ -835,15 +828,15 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
835828 .Keyword_allowzero,
836829 .Keyword_while,
837830 => {
838 try out.write("<span class=\"tok-kw\">");
831 try out.writeAll("<span class=\"tok-kw\">");
839832 try writeEscaped(out, src[token.start..token.end]);
840 try out.write("</span>");
833 try out.writeAll("</span>");
841834 },
842835
843836 .Keyword_fn => {
844 try out.write("<span class=\"tok-kw\">");
837 try out.writeAll("<span class=\"tok-kw\">");
845838 try writeEscaped(out, src[token.start..token.end]);
846 try out.write("</span>");
839 try out.writeAll("</span>");
847840 next_tok_is_fn = true;
848841 },
849842
......@@ -852,24 +845,24 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
852845 .Keyword_true,
853846 .Keyword_false,
854847 => {
855 try out.write("<span class=\"tok-null\">");
848 try out.writeAll("<span class=\"tok-null\">");
856849 try writeEscaped(out, src[token.start..token.end]);
857 try out.write("</span>");
850 try out.writeAll("</span>");
858851 },
859852
860853 .StringLiteral,
861854 .MultilineStringLiteralLine,
862855 .CharLiteral,
863856 => {
864 try out.write("<span class=\"tok-str\">");
857 try out.writeAll("<span class=\"tok-str\">");
865858 try writeEscaped(out, src[token.start..token.end]);
866 try out.write("</span>");
859 try out.writeAll("</span>");
867860 },
868861
869862 .Builtin => {
870 try out.write("<span class=\"tok-builtin\">");
863 try out.writeAll("<span class=\"tok-builtin\">");
871864 try writeEscaped(out, src[token.start..token.end]);
872 try out.write("</span>");
865 try out.writeAll("</span>");
873866 },
874867
875868 .LineComment,
......@@ -877,16 +870,16 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
877870 .ContainerDocComment,
878871 .ShebangLine,
879872 => {
880 try out.write("<span class=\"tok-comment\">");
873 try out.writeAll("<span class=\"tok-comment\">");
881874 try writeEscaped(out, src[token.start..token.end]);
882 try out.write("</span>");
875 try out.writeAll("</span>");
883876 },
884877
885878 .Identifier => {
886879 if (prev_tok_was_fn) {
887 try out.write("<span class=\"tok-fn\">");
880 try out.writeAll("<span class=\"tok-fn\">");
888881 try writeEscaped(out, src[token.start..token.end]);
889 try out.write("</span>");
882 try out.writeAll("</span>");
890883 } else {
891884 const is_int = blk: {
892885 if (src[token.start] != 'i' and src[token.start] != 'u')
......@@ -901,9 +894,9 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
901894 break :blk true;
902895 };
903896 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\">");
905898 try writeEscaped(out, src[token.start..token.end]);
906 try out.write("</span>");
899 try out.writeAll("</span>");
907900 } else {
908901 try writeEscaped(out, src[token.start..token.end]);
909902 }
......@@ -913,9 +906,9 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
913906 .IntegerLiteral,
914907 .FloatLiteral,
915908 => {
916 try out.write("<span class=\"tok-number\">");
909 try out.writeAll("<span class=\"tok-number\">");
917910 try writeEscaped(out, src[token.start..token.end]);
918 try out.write("</span>");
911 try out.writeAll("</span>");
919912 },
920913
921914 .Bang,
......@@ -983,7 +976,7 @@ fn tokenizeAndPrintRaw(docgen_tokenizer: *Tokenizer, out: var, source_token: Tok
983976 }
984977 index = token.end;
985978 }
986 try out.write("</code>");
979 try out.writeAll("</code>");
987980}
988981
989982fn 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
1002995 for (toc.nodes) |node| {
1003996 switch (node) {
1004997 .Content => |data| {
1005 try out.write(data);
998 try out.writeAll(data);
1006999 },
10071000 .Link => |info| {
10081001 if (!toc.urls.contains(info.url)) {
......@@ -1011,12 +1004,12 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
10111004 try out.print("<a href=\"#{}\">{}</a>", .{ info.url, info.name });
10121005 },
10131006 .Nav => {
1014 try out.write(toc.toc);
1007 try out.writeAll(toc.toc);
10151008 },
10161009 .Builtin => |tok| {
1017 try out.write("<pre>");
1010 try out.writeAll("<pre>");
10181011 try tokenizeAndPrintRaw(tokenizer, out, tok, builtin_code);
1019 try out.write("</pre>");
1012 try out.writeAll("</pre>");
10201013 },
10211014 .HeaderOpen => |info| {
10221015 try out.print(
......@@ -1025,7 +1018,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
10251018 );
10261019 },
10271020 .SeeAlso => |items| {
1028 try out.write("<p>See also:</p><ul>\n");
1021 try out.writeAll("<p>See also:</p><ul>\n");
10291022 for (items) |item| {
10301023 const url = try urlize(allocator, item.name);
10311024 if (!toc.urls.contains(url)) {
......@@ -1033,7 +1026,7 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
10331026 }
10341027 try out.print("<li><a href=\"#{}\">{}</a></li>\n", .{ url, item.name });
10351028 }
1036 try out.write("</ul>\n");
1029 try out.writeAll("</ul>\n");
10371030 },
10381031 .Syntax => |content_tok| {
10391032 try tokenizeAndPrint(tokenizer, out, content_tok);
......@@ -1047,9 +1040,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: var
10471040 if (!code.is_inline) {
10481041 try out.print("<p class=\"file\">{}.zig</p>", .{code.name});
10491042 }
1050 try out.write("<pre>");
1043 try out.writeAll("<pre>");
10511044 try tokenizeAndPrint(tokenizer, out, code.source_token);
1052 try out.write("</pre>");
1045 try out.writeAll("</pre>");
10531046 const name_plus_ext = try std.fmt.allocPrint(allocator, "{}.zig", .{code.name});
10541047 const tmp_source_file_name = try fs.path.join(
10551048 allocator,
doc/langref.html.in+11-36
......@@ -230,7 +230,7 @@
230230const std = @import("std");
231231
232232pub fn main() !void {
233 const stdout = &std.io.getStdOut().outStream().stream;
233 const stdout = std.io.getStdOut().outStream();
234234 try stdout.print("Hello, {}!\n", .{"world"});
235235}
236236 {#code_end#}
......@@ -6728,17 +6728,8 @@ async fn func(y: *i32) void {
67286728 This builtin function atomically dereferences a pointer and returns the value.
67296729 </p>
67306730 <p>
6731 {#syntax#}T{#endsyntax#} must be a pointer type, a {#syntax#}bool{#endsyntax#}, a float,
6732 an integer whose bit count meets these requirements:
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
6731 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
6732 an integer or an enum.
67426733 </p>
67436734 {#header_close#}
67446735 {#header_open|@atomicRmw#}
......@@ -6747,17 +6738,8 @@ async fn func(y: *i32) void {
67476738 This builtin function atomically modifies memory and then returns the previous value.
67486739 </p>
67496740 <p>
6750 {#syntax#}T{#endsyntax#} must be a pointer type, a {#syntax#}bool{#endsyntax#},
6751 or an integer whose bit count meets these requirements:
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
6741 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
6742 an integer or an enum.
67616743 </p>
67626744 <p>
67636745 Supported operations:
......@@ -6782,17 +6764,8 @@ async fn func(y: *i32) void {
67826764 This builtin function atomically stores a value.
67836765 </p>
67846766 <p>
6785 {#syntax#}T{#endsyntax#} must be a pointer type, a {#syntax#}bool{#endsyntax#}, a float,
6786 an integer whose bit count meets these requirements:
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
6767 {#syntax#}T{#endsyntax#} must be a {#syntax#}bool{#endsyntax#}, a float,
6768 an integer or an enum.
67966769 </p>
67976770 {#header_close#}
67986771 {#header_open|@bitCast#}
......@@ -7074,7 +7047,8 @@ fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_v
70747047 more efficiently in machine instructions.
70757048 </p>
70767049 <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.
70787052 </p>
70797053 <p>{#syntax#}@TypeOf(ptr).alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>
70807054 {#see_also|Compile Variables|cmpxchgWeak#}
......@@ -7102,7 +7076,8 @@ fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_val
71027076 However if you need a stronger guarantee, use {#link|@cmpxchgStrong#}.
71037077 </p>
71047078 <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.
71067081 </p>
71077082 <p>{#syntax#}@TypeOf(ptr).alignment{#endsyntax#} must be {#syntax#}>= @sizeOf(T).{#endsyntax#}</p>
71087083 {#see_also|Compile Variables|cmpxchgStrong#}
lib/libc/include/aarch64-linux-musl/bits/alltypes.h+66-55
......@@ -2,16 +2,13 @@
22#define _Int64 long
33#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
5#if __AARCH64EB__
6#define __BYTE_ORDER 4321
7#else
8#define __BYTE_ORDER 1234
139#endif
1410
11#define __LONG_MAX 0x7fffffffffffffffL
1512
1613#ifndef __cplusplus
1714#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -53,52 +50,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
5350#define __DEFINED_max_align_t
5451#endif
5552
56
57#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
58typedef long time_t;
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
53#define __LITTLE_ENDIAN 1234
54#define __BIG_ENDIAN 4321
55#define __USE_TIME_BITS64 1
10256
10357#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
10458typedef unsigned _Addr size_t;
......@@ -135,6 +89,16 @@ typedef _Reg register_t;
13589#define __DEFINED_register_t
13690#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
139103#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
140104typedef signed char int8_t;
......@@ -270,7 +234,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
270234#endif
271235
272236#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); };
274238#define __DEFINED_struct_timespec
275239#endif
276240
......@@ -366,6 +330,17 @@ typedef struct _IO_FILE FILE;
366330#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
369344#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
370345typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
371346#define __DEFINED_mbstate_t
......@@ -401,6 +376,42 @@ typedef unsigned short sa_family_t;
401376#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
404415#undef _Addr
405416#undef _Int64
406417#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 @@
287287#define __NR_fsconfig 431
288288#define __NR_fsmount 432
289289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
291293#define SYS_io_setup 0
292294#define SYS_io_destroy 1
......@@ -576,4 +578,6 @@
576578#define SYS_fsopen 430
577579#define SYS_fsconfig 431
578580#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#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
6#if __ARMEB__
7#define __BYTE_ORDER 4321
8#else
9#define __BYTE_ORDER 1234
1310#endif
1411
12#define __LONG_MAX 0x7fffffffL
1513
1614#ifndef __cplusplus
1715#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -37,52 +35,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
3735#define __DEFINED_max_align_t
3836#endif
3937
40
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_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
38#define __LITTLE_ENDIAN 1234
39#define __BIG_ENDIAN 4321
40#define __USE_TIME_BITS64 1
8641
8742#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
8843typedef unsigned _Addr size_t;
......@@ -119,6 +74,16 @@ typedef _Reg register_t;
11974#define __DEFINED_register_t
12075#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
12388#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
12489typedef signed char int8_t;
......@@ -254,7 +219,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254219#endif
255220
256221#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); };
258223#define __DEFINED_struct_timespec
259224#endif
260225
......@@ -350,6 +315,17 @@ typedef struct _IO_FILE FILE;
350315#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
353329#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354330typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355331#define __DEFINED_mbstate_t
......@@ -385,6 +361,42 @@ typedef unsigned short sa_family_t;
385361#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
388400#undef _Addr
389401#undef _Int64
390402#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
3 time_t msg_stime;
4 int __unused1;
5 time_t msg_rtime;
6 int __unused2;
7 time_t msg_ctime;
8 int __unused3;
3 unsigned long __msg_stime_lo;
4 unsigned long __msg_stime_hi;
5 unsigned long __msg_rtime_lo;
6 unsigned long __msg_rtime_hi;
7 unsigned long __msg_ctime_lo;
8 unsigned long __msg_ctime_hi;
99 unsigned long msg_cbytes;
1010 msgqnum_t msg_qnum;
1111 msglen_t msg_qbytes;
1212 pid_t msg_lspid;
1313 pid_t msg_lrpid;
1414 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
1518};
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/sem.h+6-4
......@@ -1,9 +1,9 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 time_t sem_otime;
4 long __unused1;
5 time_t sem_ctime;
6 long __unused2;
3 unsigned long __sem_otime_lo;
4 unsigned long __sem_otime_hi;
5 unsigned long __sem_ctime_lo;
6 unsigned long __sem_ctime_hi;
77#if __BYTE_ORDER == __LITTLE_ENDIAN
88 unsigned short sem_nsems;
99 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
......@@ -13,4 +13,6 @@ struct semid_ds {
1313#endif
1414 long __unused3;
1515 long __unused4;
16 time_t sem_otime;
17 time_t sem_ctime;
1618};
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/shm.h+10-6
......@@ -3,17 +3,21 @@
33struct shmid_ds {
44 struct ipc_perm shm_perm;
55 size_t shm_segsz;
6 time_t shm_atime;
7 int __unused1;
8 time_t shm_dtime;
9 int __unused2;
10 time_t shm_ctime;
11 int __unused3;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_atime_hi;
8 unsigned long __shm_dtime_lo;
9 unsigned long __shm_dtime_hi;
10 unsigned long __shm_ctime_lo;
11 unsigned long __shm_ctime_hi;
1212 pid_t shm_cpid;
1313 pid_t shm_lpid;
1414 unsigned long shm_nattch;
1515 unsigned long __pad1;
1616 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
1721};
1822
1923struct shminfo {
lib/libc/include/arm-linux-musl/bits/stat.h+5-1
......@@ -14,8 +14,12 @@ struct stat {
1414 off_t st_size;
1515 blksize_t st_blksize;
1616 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;
1722 struct timespec st_atim;
1823 struct timespec st_mtim;
1924 struct timespec st_ctim;
20 ino_t st_ino;
2125};
\ No newline at end of file
lib/libc/include/arm-linux-musl/bits/syscall.h+25-21
......@@ -55,8 +55,8 @@
5555#define __NR_sethostname 74
5656#define __NR_setrlimit 75
5757#define __NR_getrusage 77
58#define __NR_gettimeofday 78
59#define __NR_settimeofday 79
58#define __NR_gettimeofday_time32 78
59#define __NR_settimeofday_time32 79
6060#define __NR_getgroups 80
6161#define __NR_setgroups 81
6262#define __NR_symlink 83
......@@ -211,14 +211,14 @@
211211#define __NR_remap_file_pages 253
212212#define __NR_set_tid_address 256
213213#define __NR_timer_create 257
214#define __NR_timer_settime 258
215#define __NR_timer_gettime 259
214#define __NR_timer_settime32 258
215#define __NR_timer_gettime32 259
216216#define __NR_timer_getoverrun 260
217217#define __NR_timer_delete 261
218#define __NR_clock_settime 262
219#define __NR_clock_gettime 263
220#define __NR_clock_getres 264
221#define __NR_clock_nanosleep 265
218#define __NR_clock_settime32 262
219#define __NR_clock_gettime32 263
220#define __NR_clock_getres_time32 264
221#define __NR_clock_nanosleep_time32 265
222222#define __NR_statfs64 266
223223#define __NR_fstatfs64 267
224224#define __NR_tgkill 268
......@@ -308,8 +308,8 @@
308308#define __NR_timerfd_create 350
309309#define __NR_eventfd 351
310310#define __NR_fallocate 352
311#define __NR_timerfd_settime 353
312#define __NR_timerfd_gettime 354
311#define __NR_timerfd_settime32 353
312#define __NR_timerfd_gettime32 354
313313#define __NR_signalfd4 355
314314#define __NR_eventfd2 356
315315#define __NR_epoll_create1 357
......@@ -387,6 +387,8 @@
387387#define __NR_fsconfig 431
388388#define __NR_fsmount 432
389389#define __NR_fspick 433
390#define __NR_pidfd_open 434
391#define __NR_clone3 435
390392
391393#define __ARM_NR_breakpoint 0x0f0001
392394#define __ARM_NR_cacheflush 0x0f0002
......@@ -452,8 +454,8 @@
452454#define SYS_sethostname 74
453455#define SYS_setrlimit 75
454456#define SYS_getrusage 77
455#define SYS_gettimeofday 78
456#define SYS_settimeofday 79
457#define SYS_gettimeofday_time32 78
458#define SYS_settimeofday_time32 79
457459#define SYS_getgroups 80
458460#define SYS_setgroups 81
459461#define SYS_symlink 83
......@@ -608,14 +610,14 @@
608610#define SYS_remap_file_pages 253
609611#define SYS_set_tid_address 256
610612#define SYS_timer_create 257
611#define SYS_timer_settime 258
612#define SYS_timer_gettime 259
613#define SYS_timer_settime32 258
614#define SYS_timer_gettime32 259
613615#define SYS_timer_getoverrun 260
614616#define SYS_timer_delete 261
615#define SYS_clock_settime 262
616#define SYS_clock_gettime 263
617#define SYS_clock_getres 264
618#define SYS_clock_nanosleep 265
617#define SYS_clock_settime32 262
618#define SYS_clock_gettime32 263
619#define SYS_clock_getres_time32 264
620#define SYS_clock_nanosleep_time32 265
619621#define SYS_statfs64 266
620622#define SYS_fstatfs64 267
621623#define SYS_tgkill 268
......@@ -705,8 +707,8 @@
705707#define SYS_timerfd_create 350
706708#define SYS_eventfd 351
707709#define SYS_fallocate 352
708#define SYS_timerfd_settime 353
709#define SYS_timerfd_gettime 354
710#define SYS_timerfd_settime32 353
711#define SYS_timerfd_gettime32 354
710712#define SYS_signalfd4 355
711713#define SYS_eventfd2 356
712714#define SYS_epoll_create1 357
......@@ -783,4 +785,6 @@
783785#define SYS_fsopen 430
784786#define SYS_fsconfig 431
785787#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
6262#define off64_t off_t
6363#endif
6464
65#if _REDIR_TIME64
66__REDIR(aio_suspend, __aio_suspend_time64);
67#endif
68
6569#ifdef __cplusplus
6670}
6771#endif
lib/libc/include/generic-musl/alloca.h-2
......@@ -10,9 +10,7 @@ extern "C" {
1010
1111void *alloca(size_t);
1212
13#ifdef __GNUC__
1413#define alloca __builtin_alloca
15#endif
1614
1715#ifdef __cplusplus
1816}
lib/libc/include/generic-musl/arpa/nameser.h-1
......@@ -7,7 +7,6 @@ extern "C" {
77
88#include <stddef.h>
99#include <stdint.h>
10#include <endian.h>
1110
1211#define __NAMESER 19991006
1312#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 @@
104104#define FIOGETOWN 0x8903
105105#define SIOCGPGRP 0x8904
106106#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
107111#define SIOCGSTAMP 0x8906
108112#define SIOCGSTAMPNS 0x8907
113#endif
109114
110115#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#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 @@
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" {
1515
1616#include <bits/alltypes.h>
1717
18typedef struct __dirstream DIR;
19
20#define _DIRENT_HAVE_D_RECLEN
21#define _DIRENT_HAVE_D_OFF
22#define _DIRENT_HAVE_D_TYPE
18#include <bits/dirent.h>
2319
24struct dirent {
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};
20typedef struct __dirstream DIR;
3121
3222#define d_fileno d_ino
3323
lib/libc/include/generic-musl/dlfcn.h+4
......@@ -35,6 +35,10 @@ int dladdr(const void *, Dl_info *);
3535int dlinfo(void *, int, void *);
3636#endif
3737
38#if _REDIR_TIME64
39__REDIR(dlsym, __dlsym_time64);
40#endif
41
3842#ifdef __cplusplus
3943}
4044#endif
lib/libc/include/generic-musl/endian.h+21-23
......@@ -3,25 +3,19 @@
33
44#include <features.h>
55
6#define __LITTLE_ENDIAN 1234
7#define __BIG_ENDIAN 4321
8#define __PDP_ENDIAN 3412
6#define __NEED_uint16_t
7#define __NEED_uint32_t
8#define __NEED_uint64_t
99
10#if defined(__GNUC__) && defined(__BYTE_ORDER__)
11#define __BYTE_ORDER __BYTE_ORDER__
12#else
13#include <bits/endian.h>
14#endif
10#include <bits/alltypes.h>
1511
16#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
12#define __PDP_ENDIAN 3412
1713
1814#define BIG_ENDIAN __BIG_ENDIAN
1915#define LITTLE_ENDIAN __LITTLE_ENDIAN
2016#define PDP_ENDIAN __PDP_ENDIAN
2117#define BYTE_ORDER __BYTE_ORDER
2218
23#include <stdint.h>
24
2519static __inline uint16_t __bswap16(uint16_t __x)
2620{
2721 return __x<<8 | __x>>8;
......@@ -40,43 +34,47 @@ static __inline uint64_t __bswap64(uint64_t __x)
4034#if __BYTE_ORDER == __LITTLE_ENDIAN
4135#define htobe16(x) __bswap16(x)
4236#define be16toh(x) __bswap16(x)
43#define betoh16(x) __bswap16(x)
4437#define htobe32(x) __bswap32(x)
4538#define be32toh(x) __bswap32(x)
46#define betoh32(x) __bswap32(x)
4739#define htobe64(x) __bswap64(x)
4840#define be64toh(x) __bswap64(x)
49#define betoh64(x) __bswap64(x)
5041#define htole16(x) (uint16_t)(x)
5142#define le16toh(x) (uint16_t)(x)
52#define letoh16(x) (uint16_t)(x)
5343#define htole32(x) (uint32_t)(x)
5444#define le32toh(x) (uint32_t)(x)
55#define letoh32(x) (uint32_t)(x)
5645#define htole64(x) (uint64_t)(x)
5746#define le64toh(x) (uint64_t)(x)
58#define letoh64(x) (uint64_t)(x)
5947#else
6048#define htobe16(x) (uint16_t)(x)
6149#define be16toh(x) (uint16_t)(x)
62#define betoh16(x) (uint16_t)(x)
6350#define htobe32(x) (uint32_t)(x)
6451#define be32toh(x) (uint32_t)(x)
65#define betoh32(x) (uint32_t)(x)
6652#define htobe64(x) (uint64_t)(x)
6753#define be64toh(x) (uint64_t)(x)
68#define betoh64(x) (uint64_t)(x)
6954#define htole16(x) __bswap16(x)
7055#define le16toh(x) __bswap16(x)
71#define letoh16(x) __bswap16(x)
7256#define htole32(x) __bswap32(x)
7357#define le32toh(x) __bswap32(x)
74#define letoh32(x) __bswap32(x)
7558#define htole64(x) __bswap64(x)
7659#define le64toh(x) __bswap64(x)
77#define letoh64(x) __bswap64(x)
7860#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
8078#endif
8179
8280#endif
\ No newline at end of file
lib/libc/include/generic-musl/features.h+2
......@@ -35,4 +35,6 @@
3535#define _Noreturn
3636#endif
3737
38#define __REDIR(x,y) __typeof__(x) x __asm__(#y)
39
3840#endif
\ No newline at end of file
lib/libc/include/generic-musl/limits.h+13-5
......@@ -3,9 +3,7 @@
33
44#include <features.h>
55
6/* Most limits are system-specific */
7
8#include <bits/limits.h>
6#include <bits/alltypes.h> /* __LONG_MAX */
97
108/* Support signed or unsigned plain-char */
119
......@@ -17,8 +15,6 @@
1715#define CHAR_MAX 127
1816#endif
1917
20/* Some universal constants... */
21
2218#define CHAR_BIT 8
2319#define SCHAR_MIN (-128)
2420#define SCHAR_MAX 127
......@@ -30,8 +26,10 @@
3026#define INT_MAX 0x7fffffff
3127#define UINT_MAX 0xffffffffU
3228#define LONG_MIN (-LONG_MAX-1)
29#define LONG_MAX __LONG_MAX
3330#define ULONG_MAX (2UL*LONG_MAX+1)
3431#define LLONG_MIN (-LLONG_MAX-1)
32#define LLONG_MAX 0x7fffffffffffffffLL
3533#define ULLONG_MAX (2ULL*LLONG_MAX+1)
3634
3735#define MB_LEN_MAX 4
......@@ -39,9 +37,13 @@
3937#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
4038 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
4139
40#include <bits/limits.h>
41
4242#define PIPE_BUF 4096
4343#define FILESIZEBITS 64
44#ifndef NAME_MAX
4445#define NAME_MAX 255
46#endif
4547#define PATH_MAX 4096
4648#define NGROUPS_MAX 32
4749#define ARG_MAX 131072
......@@ -53,6 +55,12 @@
5355#define TTY_NAME_MAX 32
5456#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
5664/* Implementation choices... */
5765
5866#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
3030int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *);
3131int 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
3338#ifdef __cplusplus
3439}
3540#endif
lib/libc/include/generic-musl/netinet/icmp6.h-1
......@@ -9,7 +9,6 @@ extern "C" {
99#include <string.h>
1010#include <sys/types.h>
1111#include <netinet/in.h>
12#include <endian.h>
1312
1413#define ICMP6_FILTER 1
1514
lib/libc/include/generic-musl/netinet/if_ether.h+1
......@@ -58,6 +58,7 @@
5858#define ETH_P_ERSPAN 0x88BE
5959#define ETH_P_PREAUTH 0x88C7
6060#define ETH_P_TIPC 0x88CA
61#define ETH_P_LLDP 0x88CC
6162#define ETH_P_MACSEC 0x88E5
6263#define ETH_P_8021AH 0x88E7
6364#define ETH_P_MVRP 0x88F5
lib/libc/include/generic-musl/netinet/ip.h+2-1
......@@ -7,7 +7,6 @@ extern "C" {
77
88#include <stdint.h>
99#include <netinet/in.h>
10#include <endian.h>
1110
1211struct timestamp {
1312 uint8_t len;
......@@ -191,6 +190,8 @@ struct ip_timestamp {
191190
192191#define IP_MSS 576
193192
193#define __UAPI_DEF_IPHDR 0
194
194195#ifdef __cplusplus
195196}
196197#endif
lib/libc/include/generic-musl/netinet/ip6.h-1
......@@ -7,7 +7,6 @@ extern "C" {
77
88#include <stdint.h>
99#include <netinet/in.h>
10#include <endian.h>
1110
1211struct ip6_hdr {
1312 union {
lib/libc/include/generic-musl/netinet/tcp.h+3-1
......@@ -38,6 +38,7 @@
3838#define TCP_FASTOPEN_NO_COOKIE 34
3939#define TCP_ZEROCOPY_RECEIVE 35
4040#define TCP_INQ 36
41#define TCP_TX_DELAY 37
4142
4243#define TCP_CM_INQ TCP_INQ
4344
......@@ -97,7 +98,6 @@ enum {
9798#include <sys/types.h>
9899#include <sys/socket.h>
99100#include <stdint.h>
100#include <endian.h>
101101
102102typedef uint32_t tcp_seq;
103103
......@@ -234,6 +234,8 @@ struct tcp_info {
234234 uint64_t tcpi_bytes_retrans;
235235 uint32_t tcpi_dsack_dups;
236236 uint32_t tcpi_reord_seen;
237 uint32_t tcpi_rcv_ooopack;
238 uint32_t tcpi_snd_wnd;
237239};
238240
239241#define TCP_MD5SIG_MAXKEYLEN 80
lib/libc/include/generic-musl/poll.h+6
......@@ -44,6 +44,12 @@ int poll (struct pollfd *, nfds_t, int);
4444int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);
4545#endif
4646
47#if _REDIR_TIME64
48#ifdef _GNU_SOURCE
49__REDIR(ppoll, __ppoll_time64);
50#endif
51#endif
52
4753#ifdef __cplusplus
4854}
4955#endif
lib/libc/include/generic-musl/pthread.h+10
......@@ -224,6 +224,16 @@ int pthread_tryjoin_np(pthread_t, void **);
224224int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);
225225#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
227237#ifdef __cplusplus
228238}
229239#endif
lib/libc/include/generic-musl/sched.h+8
......@@ -19,10 +19,14 @@ extern "C" {
1919struct sched_param {
2020 int sched_priority;
2121 int __reserved1;
22#if _REDIR_TIME64
23 long __reserved2[4];
24#else
2225 struct {
2326 time_t __reserved1;
2427 long __reserved2;
2528 } __reserved2[2];
29#endif
2630 int __reserved3;
2731};
2832
......@@ -133,6 +137,10 @@ __CPU_op_func_S(XOR, ^)
133137
134138#endif
135139
140#if _REDIR_TIME64
141__REDIR(sched_rr_get_interval, __sched_rr_get_interval_time64);
142#endif
143
136144#ifdef __cplusplus
137145}
138146#endif
lib/libc/include/generic-musl/semaphore.h+4
......@@ -29,6 +29,10 @@ int sem_trywait(sem_t *);
2929int sem_unlink(const char *);
3030int sem_wait(sem_t *);
3131
32#if _REDIR_TIME64
33__REDIR(sem_timedwait, __sem_timedwait_time64);
34#endif
35
3236#ifdef __cplusplus
3337}
3438#endif
lib/libc/include/generic-musl/signal.h+8
......@@ -271,6 +271,14 @@ typedef int sig_atomic_t;
271271void (*signal(int, void (*)(int)))(int);
272272int 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
274282#ifdef __cplusplus
275283}
276284#endif
lib/libc/include/generic-musl/sys/acct.h-1
......@@ -6,7 +6,6 @@ extern "C" {
66#endif
77
88#include <features.h>
9#include <endian.h>
109#include <time.h>
1110#include <stdint.h>
1211
lib/libc/include/generic-musl/sys/ioctl.h+1
......@@ -4,6 +4,7 @@
44extern "C" {
55#endif
66
7#include <bits/alltypes.h>
78#include <bits/ioctl.h>
89
910#define N_TTY 0
lib/libc/include/generic-musl/sys/mman.h+2
......@@ -92,6 +92,8 @@ extern "C" {
9292#define MADV_DODUMP 17
9393#define MADV_WIPEONFORK 18
9494#define MADV_KEEPONFORK 19
95#define MADV_COLD 20
96#define MADV_PAGEOUT 21
9597#define MADV_HWPOISON 100
9698#define MADV_SOFT_OFFLINE 101
9799#endif
lib/libc/include/generic-musl/sys/prctl.h+4
......@@ -154,6 +154,10 @@ struct prctl_mm_map {
154154#define PR_PAC_APDBKEY (1UL << 3)
155155#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
157161int prctl (int, ...);
158162
159163#ifdef __cplusplus
lib/libc/include/generic-musl/sys/procfs.h+3-4
......@@ -23,10 +23,9 @@ struct elf_prstatus {
2323 pid_t pr_ppid;
2424 pid_t pr_pgrp;
2525 pid_t pr_sid;
26 struct timeval pr_utime;
27 struct timeval pr_stime;
28 struct timeval pr_cutime;
29 struct timeval pr_cstime;
26 struct {
27 long tv_sec, tv_usec;
28 } pr_utime, pr_stime, pr_cutime, pr_cstime;
3029 elf_gregset_t pr_reg;
3130 int pr_fpvalid;
3231};
lib/libc/include/generic-musl/sys/ptrace.h+29
......@@ -41,6 +41,7 @@ extern "C" {
4141#define PTRACE_SETSIGMASK 0x420b
4242#define PTRACE_SECCOMP_GET_FILTER 0x420c
4343#define PTRACE_SECCOMP_GET_METADATA 0x420d
44#define PTRACE_GET_SYSCALL_INFO 0x420e
4445
4546#define PT_READ_I PTRACE_PEEKTEXT
4647#define PT_READ_D PTRACE_PEEKDATA
......@@ -88,6 +89,11 @@ extern "C" {
8889
8990#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
9197#include <bits/ptrace.h>
9298
9399struct __ptrace_peeksiginfo_args {
......@@ -101,6 +107,29 @@ struct __ptrace_seccomp_metadata {
101107 uint64_t flags;
102108};
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
104133long ptrace(int, ...);
105134
106135#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 *);
9090#define RLIMIT_MSGQUEUE 12
9191#define RLIMIT_NICE 13
9292#define RLIMIT_RTPRIO 14
93#define RLIMIT_NLIMITS 15
93#define RLIMIT_RTTIME 15
94#define RLIMIT_NLIMITS 16
9495
9596#define RLIM_NLIMITS RLIMIT_NLIMITS
9697
......@@ -104,6 +105,10 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);
104105#define rlim64_t rlim_t
105106#endif
106107
108#if _REDIR_TIME64
109__REDIR(getrusage, __getrusage_time64);
110#endif
111
107112#ifdef __cplusplus
108113}
109114#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
3535#define NFDBITS (8*(int)sizeof(long))
3636#endif
3737
38#if _REDIR_TIME64
39__REDIR(select, __select_time64);
40__REDIR(pselect, __pselect_time64);
41#endif
42
3843#ifdef __cplusplus
3944}
4045#endif
lib/libc/include/generic-musl/sys/sem.h+6-2
......@@ -25,8 +25,6 @@ extern "C" {
2525#define SETVAL 16
2626#define SETALL 17
2727
28#include <endian.h>
29
3028#include <bits/sem.h>
3129
3230#define _SEM_SEMUN_UNDEFINED 1
......@@ -62,6 +60,12 @@ int semop(int, struct sembuf *, size_t);
6260int semtimedop(int, struct sembuf *, size_t, const struct timespec *);
6361#endif
6462
63#if _REDIR_TIME64
64#ifdef _GNU_SOURCE
65__REDIR(semtimedop, __semtimedop_time64);
66#endif
67#endif
68
6569#ifdef __cplusplus
6670}
6771#endif
lib/libc/include/generic-musl/sys/socket.h+63-6
......@@ -19,6 +19,40 @@ extern "C" {
1919
2020#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
2256#ifdef _GNU_SOURCE
2357struct ucred {
2458 pid_t pid;
......@@ -182,8 +216,6 @@ struct linger {
182216#define SO_PEERCRED 17
183217#define SO_RCVLOWAT 18
184218#define SO_SNDLOWAT 19
185#define SO_RCVTIMEO 20
186#define SO_SNDTIMEO 21
187219#define SO_ACCEPTCONN 30
188220#define SO_PEERSEC 31
189221#define SO_SNDBUFFORCE 32
......@@ -192,6 +224,28 @@ struct linger {
192224#define SO_DOMAIN 39
193225#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
195249#define SO_SECURITY_AUTHENTICATION 22
196250#define SO_SECURITY_ENCRYPTION_TRANSPORT 23
197251#define SO_SECURITY_ENCRYPTION_NETWORK 24
......@@ -203,14 +257,10 @@ struct linger {
203257#define SO_GET_FILTER SO_ATTACH_FILTER
204258
205259#define SO_PEERNAME 28
206#define SO_TIMESTAMP 29
207260#define SCM_TIMESTAMP SO_TIMESTAMP
208
209261#define SO_PASSSEC 34
210#define SO_TIMESTAMPNS 35
211262#define SCM_TIMESTAMPNS SO_TIMESTAMPNS
212263#define SO_MARK 36
213#define SO_TIMESTAMPING 37
214264#define SCM_TIMESTAMPING SO_TIMESTAMPING
215265#define SO_RXQ_OVFL 40
216266#define SO_WIFI_STATUS 41
......@@ -238,6 +288,7 @@ struct linger {
238288#define SO_TXTIME 61
239289#define SCM_TXTIME SO_TXTIME
240290#define SO_BINDTOIFINDEX 62
291#define SO_DETACH_REUSEPORT_BPF 68
241292
242293#ifndef SOL_SOCKET
243294#define SOL_SOCKET 1
......@@ -350,6 +401,12 @@ int setsockopt (int, int, int, const void *, socklen_t);
350401
351402int sockatmark (int);
352403
404#if _REDIR_TIME64
405#ifdef _GNU_SOURCE
406__REDIR(recvmmsg, __recvmmsg_time64);
407#endif
408#endif
409
353410#ifdef __cplusplus
354411}
355412#endif
lib/libc/include/generic-musl/sys/stat.h+9
......@@ -110,6 +110,15 @@ int lchmod(const char *, mode_t);
110110#define off64_t off_t
111111#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
113122#ifdef __cplusplus
114123}
115124#endif
lib/libc/include/generic-musl/sys/statvfs.h-2
......@@ -11,8 +11,6 @@ extern "C" {
1111#define __NEED_fsfilcnt_t
1212#include <bits/alltypes.h>
1313
14#include <endian.h>
15
1614struct statvfs {
1715 unsigned long f_bsize, f_frsize;
1816 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 *);
5656 (void)0 )
5757#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
5973#ifdef __cplusplus
6074}
6175#endif
lib/libc/include/generic-musl/sys/timeb.h+6
......@@ -4,6 +4,8 @@
44extern "C" {
55#endif
66
7#include <features.h>
8
79#define __NEED_time_t
810
911#include <bits/alltypes.h>
......@@ -16,6 +18,10 @@ struct timeb {
1618
1719int ftime(struct timeb *);
1820
21#if _REDIR_TIME64
22__REDIR(ftime, __ftime64);
23#endif
24
1925#ifdef __cplusplus
2026}
2127#endif
lib/libc/include/generic-musl/sys/timerfd.h+5
......@@ -20,6 +20,11 @@ int timerfd_create(int, int);
2020int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *);
2121int 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
2328#ifdef __cplusplus
2429}
2530#endif
lib/libc/include/generic-musl/sys/timex.h+5
......@@ -91,6 +91,11 @@ struct timex {
9191int adjtimex(struct timex *);
9292int 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
9499#ifdef __cplusplus
95100}
96101#endif
lib/libc/include/generic-musl/sys/ttydefaults.h+1-6
......@@ -6,16 +6,11 @@
66#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL)
77#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL)
88#define TTYDEF_SPEED (B9600)
9#define CTRL(x) (x&037)
9#define CTRL(x) ((x)&037)
1010#define CEOF CTRL('d')
1111
12#ifdef _POSIX_VDISABLE
13#define CEOL _POSIX_VDISABLE
14#define CSTATUS _POSIX_VDISABLE
15#else
1612#define CEOL '\0'
1713#define CSTATUS '\0'
18#endif
1914
2015#define CERASE 0177
2116#define CINTR CTRL('c')
lib/libc/include/generic-musl/sys/wait.h+9-1
......@@ -13,7 +13,8 @@ extern "C" {
1313typedef enum {
1414 P_ALL = 0,
1515 P_PID = 1,
16 P_PGID = 2
16 P_PGID = 2,
17 P_PIDFD = 3
1718} idtype_t;
1819
1920pid_t wait (int *);
......@@ -53,6 +54,13 @@ pid_t wait4 (pid_t, int *, int, struct rusage *);
5354#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu)
5455#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
5664#ifdef __cplusplus
5765}
5866#endif
lib/libc/include/generic-musl/threads.h+6
......@@ -80,6 +80,12 @@ void tss_delete(tss_t);
8080int tss_set(tss_t, void *);
8181void *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
8389#ifdef __cplusplus
8490}
8591#endif
lib/libc/include/generic-musl/time.h+28
......@@ -130,6 +130,34 @@ int stime(const time_t *);
130130time_t timegm(struct tm *);
131131#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
133161#ifdef __cplusplus
134162}
135163#endif
lib/libc/include/generic-musl/utime.h+6
......@@ -5,6 +5,8 @@
55extern "C" {
66#endif
77
8#include <features.h>
9
810#define __NEED_time_t
911
1012#include <bits/alltypes.h>
......@@ -16,6 +18,10 @@ struct utimbuf {
1618
1719int utime (const char *, const struct utimbuf *);
1820
21#if _REDIR_TIME64
22__REDIR(utime, __utime64);
23#endif
24
1925#ifdef __cplusplus
2026}
2127#endif
lib/libc/include/generic-musl/utmpx.h+6-1
......@@ -16,6 +16,7 @@ extern "C" {
1616
1717struct utmpx {
1818 short ut_type;
19 short __ut_pad1;
1920 pid_t ut_pid;
2021 char ut_line[32];
2122 char ut_id[4];
......@@ -25,7 +26,11 @@ struct utmpx {
2526 short __e_termination;
2627 short __e_exit;
2728 } 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
2934 struct timeval ut_tv;
3035 unsigned ut_addr_v6[4];
3136 char __unused[20];
lib/libc/include/i386-linux-musl/bits/alltypes.h+64-70
......@@ -1,30 +1,10 @@
1#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5#if __GNUC__ >= 3
6#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
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
6#define __BYTE_ORDER 1234
7#define __LONG_MAX 0x7fffffffL
288
299#ifndef __cplusplus
3010#ifdef __WCHAR_TYPE__
......@@ -85,52 +65,9 @@ typedef struct { alignas(8) long long __ll; long double __ld; } max_align_t;
8565#endif
8666
8767#endif
88
89#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
90typedef long time_t;
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
68#define __LITTLE_ENDIAN 1234
69#define __BIG_ENDIAN 4321
70#define __USE_TIME_BITS64 1
13471
13572#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
13673typedef unsigned _Addr size_t;
......@@ -167,6 +104,16 @@ typedef _Reg register_t;
167104#define __DEFINED_register_t
168105#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
171118#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
172119typedef signed char int8_t;
......@@ -302,7 +249,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
302249#endif
303250
304251#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); };
306253#define __DEFINED_struct_timespec
307254#endif
308255
......@@ -398,6 +345,17 @@ typedef struct _IO_FILE FILE;
398345#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
401359#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
402360typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
403361#define __DEFINED_mbstate_t
......@@ -433,6 +391,42 @@ typedef unsigned short sa_family_t;
433391#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
436430#undef _Addr
437431#undef _Int64
438432#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#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
3 time_t msg_stime;
4 int __unused1;
5 time_t msg_rtime;
6 int __unused2;
7 time_t msg_ctime;
8 int __unused3;
3 unsigned long __msg_stime_lo;
4 unsigned long __msg_stime_hi;
5 unsigned long __msg_rtime_lo;
6 unsigned long __msg_rtime_hi;
7 unsigned long __msg_ctime_lo;
8 unsigned long __msg_ctime_hi;
99 unsigned long msg_cbytes;
1010 msgqnum_t msg_qnum;
1111 msglen_t msg_qbytes;
1212 pid_t msg_lspid;
1313 pid_t msg_lrpid;
1414 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
1518};
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/sem.h+6-4
......@@ -1,11 +1,13 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 time_t sem_otime;
4 long __unused1;
5 time_t sem_ctime;
6 long __unused2;
3 unsigned long __sem_otime_lo;
4 unsigned long __sem_otime_hi;
5 unsigned long __sem_ctime_lo;
6 unsigned long __sem_ctime_hi;
77 unsigned short sem_nsems;
88 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
99 long __unused3;
1010 long __unused4;
11 time_t sem_otime;
12 time_t sem_ctime;
1113};
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/shm.h+10-6
......@@ -3,17 +3,21 @@
33struct shmid_ds {
44 struct ipc_perm shm_perm;
55 size_t shm_segsz;
6 time_t shm_atime;
7 int __unused1;
8 time_t shm_dtime;
9 int __unused2;
10 time_t shm_ctime;
11 int __unused3;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_atime_hi;
8 unsigned long __shm_dtime_lo;
9 unsigned long __shm_dtime_hi;
10 unsigned long __shm_ctime_lo;
11 unsigned long __shm_ctime_hi;
1212 pid_t shm_cpid;
1313 pid_t shm_lpid;
1414 unsigned long shm_nattch;
1515 unsigned long __pad1;
1616 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
1721};
1822
1923struct shminfo {
lib/libc/include/i386-linux-musl/bits/stat.h+5-1
......@@ -14,8 +14,12 @@ struct stat {
1414 off_t st_size;
1515 blksize_t st_blksize;
1616 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;
1722 struct timespec st_atim;
1823 struct timespec st_mtim;
1924 struct timespec st_ctim;
20 ino_t st_ino;
2125};
\ No newline at end of file
lib/libc/include/i386-linux-musl/bits/syscall.h+25-21
......@@ -76,8 +76,8 @@
7676#define __NR_setrlimit 75
7777#define __NR_getrlimit 76 /* Back compatible 2Gig limited rlimit */
7878#define __NR_getrusage 77
79#define __NR_gettimeofday 78
80#define __NR_settimeofday 79
79#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday_time32 79
8181#define __NR_getgroups 80
8282#define __NR_setgroups 81
8383#define __NR_select 82
......@@ -257,14 +257,14 @@
257257#define __NR_remap_file_pages 257
258258#define __NR_set_tid_address 258
259259#define __NR_timer_create 259
260#define __NR_timer_settime (__NR_timer_create+1)
261#define __NR_timer_gettime (__NR_timer_create+2)
260#define __NR_timer_settime32 (__NR_timer_create+1)
261#define __NR_timer_gettime32 (__NR_timer_create+2)
262262#define __NR_timer_getoverrun (__NR_timer_create+3)
263263#define __NR_timer_delete (__NR_timer_create+4)
264#define __NR_clock_settime (__NR_timer_create+5)
265#define __NR_clock_gettime (__NR_timer_create+6)
266#define __NR_clock_getres (__NR_timer_create+7)
267#define __NR_clock_nanosleep (__NR_timer_create+8)
264#define __NR_clock_settime32 (__NR_timer_create+5)
265#define __NR_clock_gettime32 (__NR_timer_create+6)
266#define __NR_clock_getres_time32 (__NR_timer_create+7)
267#define __NR_clock_nanosleep_time32 (__NR_timer_create+8)
268268#define __NR_statfs64 268
269269#define __NR_fstatfs64 269
270270#define __NR_tgkill 270
......@@ -322,8 +322,8 @@
322322#define __NR_timerfd_create 322
323323#define __NR_eventfd 323
324324#define __NR_fallocate 324
325#define __NR_timerfd_settime 325
326#define __NR_timerfd_gettime 326
325#define __NR_timerfd_settime32 325
326#define __NR_timerfd_gettime32 326
327327#define __NR_signalfd4 327
328328#define __NR_eventfd2 328
329329#define __NR_epoll_create1 329
......@@ -424,6 +424,8 @@
424424#define __NR_fsconfig 431
425425#define __NR_fsmount 432
426426#define __NR_fspick 433
427#define __NR_pidfd_open 434
428#define __NR_clone3 435
427429
428430#define SYS_restart_syscall 0
429431#define SYS_exit 1
......@@ -503,8 +505,8 @@
503505#define SYS_setrlimit 75
504506#define SYS_getrlimit 76 /* Back compatible 2Gig limited rlimit */
505507#define SYS_getrusage 77
506#define SYS_gettimeofday 78
507#define SYS_settimeofday 79
508#define SYS_gettimeofday_time32 78
509#define SYS_settimeofday_time32 79
508510#define SYS_getgroups 80
509511#define SYS_setgroups 81
510512#define SYS_select 82
......@@ -682,14 +684,14 @@
682684#define SYS_remap_file_pages 257
683685#define SYS_set_tid_address 258
684686#define SYS_timer_create 259
685#define SYS_timer_settime (__NR_timer_create+1)
686#define SYS_timer_gettime (__NR_timer_create+2)
687#define SYS_timer_settime32 (__NR_timer_create+1)
688#define SYS_timer_gettime32 (__NR_timer_create+2)
687689#define SYS_timer_getoverrun (__NR_timer_create+3)
688690#define SYS_timer_delete (__NR_timer_create+4)
689#define SYS_clock_settime (__NR_timer_create+5)
690#define SYS_clock_gettime (__NR_timer_create+6)
691#define SYS_clock_getres (__NR_timer_create+7)
692#define SYS_clock_nanosleep (__NR_timer_create+8)
691#define SYS_clock_settime32 (__NR_timer_create+5)
692#define SYS_clock_gettime32 (__NR_timer_create+6)
693#define SYS_clock_getres_time32 (__NR_timer_create+7)
694#define SYS_clock_nanosleep_time32 (__NR_timer_create+8)
693695#define SYS_statfs64 268
694696#define SYS_fstatfs64 269
695697#define SYS_tgkill 270
......@@ -747,8 +749,8 @@
747749#define SYS_timerfd_create 322
748750#define SYS_eventfd 323
749751#define SYS_fallocate 324
750#define SYS_timerfd_settime 325
751#define SYS_timerfd_gettime 326
752#define SYS_timerfd_settime32 325
753#define SYS_timerfd_gettime32 326
752754#define SYS_signalfd4 327
753755#define SYS_eventfd2 328
754756#define SYS_epoll_create1 329
......@@ -848,4 +850,6 @@
848850#define SYS_fsopen 430
849851#define SYS_fsconfig 431
850852#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#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
6#if _MIPSEL || __MIPSEL || __MIPSEL__
7#define __BYTE_ORDER 1234
8#else
9#define __BYTE_ORDER 4321
1310#endif
1411
12#define __LONG_MAX 0x7fffffffL
1513
1614#ifndef __cplusplus
1715#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -37,52 +35,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
3735#define __DEFINED_max_align_t
3836#endif
3937
40
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_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
38#define __LITTLE_ENDIAN 1234
39#define __BIG_ENDIAN 4321
40#define __USE_TIME_BITS64 1
8641
8742#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
8843typedef unsigned _Addr size_t;
......@@ -119,6 +74,16 @@ typedef _Reg register_t;
11974#define __DEFINED_register_t
12075#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
12388#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
12489typedef signed char int8_t;
......@@ -254,7 +219,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254219#endif
255220
256221#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); };
258223#define __DEFINED_struct_timespec
259224#endif
260225
......@@ -350,6 +315,17 @@ typedef struct _IO_FILE FILE;
350315#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
353329#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354330typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355331#define __DEFINED_mbstate_t
......@@ -385,6 +361,42 @@ typedef unsigned short sa_family_t;
385361#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
388400#undef _Addr
389401#undef _Int64
390402#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 @@
11#define HWCAP_MIPS_R6 (1 << 0)
22#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 @@
110110#define SIOCATMARK _IOR('s', 7, int)
111111#define SIOCSPGRP _IOW('s', 8, pid_t)
112112#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
33#if _MIPSEL || __MIPSEL || __MIPSEL__
4 time_t msg_stime;
5 int __unused1;
6 time_t msg_rtime;
7 int __unused2;
8 time_t msg_ctime;
9 int __unused3;
4 unsigned long __msg_stime_lo;
5 unsigned long __msg_stime_hi;
6 unsigned long __msg_rtime_lo;
7 unsigned long __msg_rtime_hi;
8 unsigned long __msg_ctime_lo;
9 unsigned long __msg_ctime_hi;
1010#else
11 int __unused1;
12 time_t msg_stime;
13 int __unused2;
14 time_t msg_rtime;
15 int __unused3;
16 time_t msg_ctime;
11 unsigned long __msg_stime_hi;
12 unsigned long __msg_stime_lo;
13 unsigned long __msg_rtime_hi;
14 unsigned long __msg_rtime_lo;
15 unsigned long __msg_ctime_hi;
16 unsigned long __msg_ctime_lo;
1717#endif
1818 unsigned long msg_cbytes;
1919 msgqnum_t msg_qnum;
......@@ -21,4 +21,7 @@ struct msqid_ds {
2121 pid_t msg_lspid;
2222 pid_t msg_lrpid;
2323 unsigned long __unused[2];
24 time_t msg_stime;
25 time_t msg_rtime;
26 time_t msg_ctime;
2427};
\ 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 {
1919} fpregset_t;
2020struct sigcontext {
2121 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;
2325 unsigned sc_ownedfp, sc_fpc_csr, sc_fpc_eir, sc_used_math, sc_dsp;
2426 unsigned long long sc_mdhi, sc_mdlo;
2527 unsigned long sc_hi1, sc_lo1, sc_hi2, sc_lo2, sc_hi3, sc_lo3;
2628};
2729typedef struct {
2830 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;
3034 unsigned ownedfp, fpc_csr, fpc_eir, used_math, dsp;
3135 unsigned long long mdhi, mdlo;
3236 unsigned long hi1, lo1, hi2, lo2, hi3, lo3;
lib/libc/include/mips-linux-musl/bits/socket.h-18
......@@ -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
171#define SOCK_STREAM 2
182#define SOCK_DGRAM 1
193
......@@ -32,8 +16,6 @@ struct cmsghdr {
3216#define SO_RCVBUF 0x1002
3317#define SO_SNDLOWAT 0x1003
3418#define SO_RCVLOWAT 0x1004
35#define SO_RCVTIMEO 0x1006
36#define SO_SNDTIMEO 0x1005
3719#define SO_ERROR 0x1007
3820#define SO_TYPE 0x1008
3921#define SO_ACCEPTCONN 0x1009
lib/libc/include/mips-linux-musl/bits/stat.h+8-4
......@@ -12,11 +12,15 @@ struct stat {
1212 dev_t st_rdev;
1313 long __st_padding2[2];
1414 off_t st_size;
15 struct timespec st_atim;
16 struct timespec st_mtim;
17 struct timespec st_ctim;
15 struct {
16 long tv_sec;
17 long tv_nsec;
18 } __st_atim32, __st_mtim32, __st_ctim32;
1819 blksize_t st_blksize;
1920 long __st_padding3;
2021 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];
2226};
\ No newline at end of file
lib/libc/include/mips-linux-musl/bits/syscall.h+25-21
......@@ -76,8 +76,8 @@
7676#define __NR_setrlimit 4075
7777#define __NR_getrlimit 4076
7878#define __NR_getrusage 4077
79#define __NR_gettimeofday 4078
80#define __NR_settimeofday 4079
79#define __NR_gettimeofday_time32 4078
80#define __NR_settimeofday_time32 4079
8181#define __NR_getgroups 4080
8282#define __NR_setgroups 4081
8383#define __NR_reserved82 4082
......@@ -256,14 +256,14 @@
256256#define __NR_statfs64 4255
257257#define __NR_fstatfs64 4256
258258#define __NR_timer_create 4257
259#define __NR_timer_settime 4258
260#define __NR_timer_gettime 4259
259#define __NR_timer_settime32 4258
260#define __NR_timer_gettime32 4259
261261#define __NR_timer_getoverrun 4260
262262#define __NR_timer_delete 4261
263#define __NR_clock_settime 4262
264#define __NR_clock_gettime 4263
265#define __NR_clock_getres 4264
266#define __NR_clock_nanosleep 4265
263#define __NR_clock_settime32 4262
264#define __NR_clock_gettime32 4263
265#define __NR_clock_getres_time32 4264
266#define __NR_clock_nanosleep_time32 4265
267267#define __NR_tgkill 4266
268268#define __NR_utimes 4267
269269#define __NR_mbind 4268
......@@ -319,8 +319,8 @@
319319#define __NR_eventfd 4319
320320#define __NR_fallocate 4320
321321#define __NR_timerfd_create 4321
322#define __NR_timerfd_gettime 4322
323#define __NR_timerfd_settime 4323
322#define __NR_timerfd_gettime32 4322
323#define __NR_timerfd_settime32 4323
324324#define __NR_signalfd4 4324
325325#define __NR_eventfd2 4325
326326#define __NR_epoll_create1 4326
......@@ -406,6 +406,8 @@
406406#define __NR_fsconfig 4431
407407#define __NR_fsmount 4432
408408#define __NR_fspick 4433
409#define __NR_pidfd_open 4434
410#define __NR_clone3 4435
409411
410412#define SYS_syscall 4000
411413#define SYS_exit 4001
......@@ -485,8 +487,8 @@
485487#define SYS_setrlimit 4075
486488#define SYS_getrlimit 4076
487489#define SYS_getrusage 4077
488#define SYS_gettimeofday 4078
489#define SYS_settimeofday 4079
490#define SYS_gettimeofday_time32 4078
491#define SYS_settimeofday_time32 4079
490492#define SYS_getgroups 4080
491493#define SYS_setgroups 4081
492494#define SYS_reserved82 4082
......@@ -665,14 +667,14 @@
665667#define SYS_statfs64 4255
666668#define SYS_fstatfs64 4256
667669#define SYS_timer_create 4257
668#define SYS_timer_settime 4258
669#define SYS_timer_gettime 4259
670#define SYS_timer_settime32 4258
671#define SYS_timer_gettime32 4259
670672#define SYS_timer_getoverrun 4260
671673#define SYS_timer_delete 4261
672#define SYS_clock_settime 4262
673#define SYS_clock_gettime 4263
674#define SYS_clock_getres 4264
675#define SYS_clock_nanosleep 4265
674#define SYS_clock_settime32 4262
675#define SYS_clock_gettime32 4263
676#define SYS_clock_getres_time32 4264
677#define SYS_clock_nanosleep_time32 4265
676678#define SYS_tgkill 4266
677679#define SYS_utimes 4267
678680#define SYS_mbind 4268
......@@ -728,8 +730,8 @@
728730#define SYS_eventfd 4319
729731#define SYS_fallocate 4320
730732#define SYS_timerfd_create 4321
731#define SYS_timerfd_gettime 4322
732#define SYS_timerfd_settime 4323
733#define SYS_timerfd_gettime32 4322
734#define SYS_timerfd_settime32 4323
733735#define SYS_signalfd4 4324
734736#define SYS_eventfd2 4325
735737#define SYS_epoll_create1 4326
......@@ -814,4 +816,6 @@
814816#define SYS_fsopen 4430
815817#define SYS_fsconfig 4431
816818#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 @@
22#define _Int64 long
33#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
5#if _MIPSEL || __MIPSEL || __MIPSEL__
6#define __BYTE_ORDER 1234
7#else
8#define __BYTE_ORDER 4321
139#endif
1410
11#define __LONG_MAX 0x7fffffffffffffffL
1512
1613#ifndef __cplusplus
1714#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -38,57 +35,14 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
3835#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
5238#if defined(__NEED_nlink_t) && !defined(__DEFINED_nlink_t)
5339typedef unsigned nlink_t;
5440#define __DEFINED_nlink_t
5541#endif
5642
57
58#if defined(__NEED_pthread_attr_t) && !defined(__DEFINED_pthread_attr_t)
59typedef struct { union { int __i[14]; volatile int __vi[14]; unsigned long __s[7]; } __u; } pthread_attr_t;
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
43#define __LITTLE_ENDIAN 1234
44#define __BIG_ENDIAN 4321
45#define __USE_TIME_BITS64 1
9246
9347#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
9448typedef unsigned _Addr size_t;
......@@ -125,6 +79,16 @@ typedef _Reg register_t;
12579#define __DEFINED_register_t
12680#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
12993#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
13094typedef signed char int8_t;
......@@ -260,7 +224,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
260224#endif
261225
262226#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); };
264228#define __DEFINED_struct_timespec
265229#endif
266230
......@@ -356,6 +320,17 @@ typedef struct _IO_FILE FILE;
356320#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
359334#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
360335typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
361336#define __DEFINED_mbstate_t
......@@ -391,6 +366,42 @@ typedef unsigned short sa_family_t;
391366#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
394405#undef _Addr
395406#undef _Int64
396407#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#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
351#define SOCK_STREAM 2
362#define SOCK_DGRAM 1
373#define SOL_SOCKET 65535
lib/libc/include/mips64-linux-musl/bits/syscall.h+5-1
......@@ -336,6 +336,8 @@
336336#define __NR_fsconfig 5431
337337#define __NR_fsmount 5432
338338#define __NR_fspick 5433
339#define __NR_pidfd_open 5434
340#define __NR_clone3 5435
339341
340342#define SYS_read 5000
341343#define SYS_write 5001
......@@ -674,4 +676,6 @@
674676#define SYS_fsopen 5430
675677#define SYS_fsconfig 5431
676678#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#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
6#define __BYTE_ORDER 4321
7#define __LONG_MAX 0x7fffffffL
158
169#ifndef __cplusplus
1710#ifdef __WCHAR_TYPE__
......@@ -45,52 +38,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
4538#define __DEFINED_max_align_t
4639#endif
4740
48
49#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
50typedef long time_t;
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
41#define __LITTLE_ENDIAN 1234
42#define __BIG_ENDIAN 4321
43#define __USE_TIME_BITS64 1
9444
9545#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
9646typedef unsigned _Addr size_t;
......@@ -127,6 +77,16 @@ typedef _Reg register_t;
12777#define __DEFINED_register_t
12878#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
13191#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
13292typedef signed char int8_t;
......@@ -262,7 +222,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
262222#endif
263223
264224#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); };
266226#define __DEFINED_struct_timespec
267227#endif
268228
......@@ -358,6 +318,17 @@ typedef struct _IO_FILE FILE;
358318#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
361332#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
362333typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
363334#define __DEFINED_mbstate_t
......@@ -393,6 +364,42 @@ typedef unsigned short sa_family_t;
393364#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
396403#undef _Addr
397404#undef _Int64
398405#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 @@
116116#define FIOGETOWN 0x8903
117117#define SIOCGPGRP 0x8904
118118#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
3 int __unused1;
4 time_t msg_stime;
5 int __unused2;
6 time_t msg_rtime;
7 int __unused3;
8 time_t msg_ctime;
3 unsigned long __msg_stime_hi;
4 unsigned long __msg_stime_lo;
5 unsigned long __msg_rtime_hi;
6 unsigned long __msg_rtime_lo;
7 unsigned long __msg_ctime_hi;
8 unsigned long __msg_ctime_lo;
99 unsigned long msg_cbytes;
1010 msgqnum_t msg_qnum;
1111 msglen_t msg_qbytes;
1212 pid_t msg_lspid;
1313 pid_t msg_lrpid;
1414 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
1518};
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/sem.h+6-4
......@@ -1,10 +1,12 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 int __unused1;
4 time_t sem_otime;
5 int __unused2;
6 time_t sem_ctime;
3 unsigned long __sem_otime_hi;
4 unsigned long __sem_otime_lo;
5 unsigned long __sem_ctime_hi;
6 unsigned long __sem_ctime_lo;
77 unsigned short __sem_nsems_pad, sem_nsems;
88 long __unused3;
99 long __unused4;
10 time_t sem_otime;
11 time_t sem_ctime;
1012};
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/shm.h+9-7
......@@ -2,19 +2,21 @@
22
33struct shmid_ds {
44 struct ipc_perm shm_perm;
5 int __unused1;
6 time_t shm_atime;
7 int __unused2;
8 time_t shm_dtime;
9 int __unused3;
10 time_t shm_ctime;
11 int __unused4;
5 unsigned long __shm_atime_hi;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_dtime_hi;
8 unsigned long __shm_dtime_lo;
9 unsigned long __shm_ctime_hi;
10 unsigned long __shm_ctime_lo;
1211 size_t shm_segsz;
1312 pid_t shm_cpid;
1413 pid_t shm_lpid;
1514 unsigned long shm_nattch;
1615 unsigned long __pad1;
1716 unsigned long __pad2;
17 time_t shm_atime;
18 time_t shm_dtime;
19 time_t shm_ctime;
1820};
1921
2022struct shminfo {
lib/libc/include/powerpc-linux-musl/bits/signal.h+1-1
......@@ -28,7 +28,7 @@ struct sigcontext {
2828 int signal;
2929 unsigned long handler;
3030 unsigned long oldmask;
31 void *regs;
31 struct pt_regs *regs;
3232};
3333
3434typedef struct {
lib/libc/include/powerpc-linux-musl/bits/socket.h-18
......@@ -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
171#define SO_DEBUG 1
182#define SO_REUSEADDR 2
193#define SO_TYPE 3
......@@ -31,8 +15,6 @@ struct cmsghdr {
3115#define SO_REUSEPORT 15
3216#define SO_RCVLOWAT 16
3317#define SO_SNDLOWAT 17
34#define SO_RCVTIMEO 18
35#define SO_SNDTIMEO 19
3618#define SO_PASSCRED 20
3719#define SO_PEERCRED 21
3820#define SO_ACCEPTCONN 30
lib/libc/include/powerpc-linux-musl/bits/stat.h+5-1
......@@ -13,8 +13,12 @@ struct stat {
1313 off_t st_size;
1414 blksize_t st_blksize;
1515 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];
1621 struct timespec st_atim;
1722 struct timespec st_mtim;
1823 struct timespec st_ctim;
19 unsigned __unused[2];
2024};
\ No newline at end of file
lib/libc/include/powerpc-linux-musl/bits/syscall.h+25-21
......@@ -76,8 +76,8 @@
7676#define __NR_setrlimit 75
7777#define __NR_getrlimit 76
7878#define __NR_getrusage 77
79#define __NR_gettimeofday 78
80#define __NR_settimeofday 79
79#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday_time32 79
8181#define __NR_getgroups 80
8282#define __NR_setgroups 81
8383#define __NR_select 82
......@@ -238,14 +238,14 @@
238238#define __NR_epoll_wait 238
239239#define __NR_remap_file_pages 239
240240#define __NR_timer_create 240
241#define __NR_timer_settime 241
242#define __NR_timer_gettime 242
241#define __NR_timer_settime32 241
242#define __NR_timer_gettime32 242
243243#define __NR_timer_getoverrun 243
244244#define __NR_timer_delete 244
245#define __NR_clock_settime 245
246#define __NR_clock_gettime 246
247#define __NR_clock_getres 247
248#define __NR_clock_nanosleep 248
245#define __NR_clock_settime32 245
246#define __NR_clock_gettime32 246
247#define __NR_clock_getres_time32 247
248#define __NR_clock_nanosleep_time32 248
249249#define __NR_swapcontext 249
250250#define __NR_tgkill 250
251251#define __NR_utimes 251
......@@ -307,8 +307,8 @@
307307#define __NR_sync_file_range2 308
308308#define __NR_fallocate 309
309309#define __NR_subpage_prot 310
310#define __NR_timerfd_settime 311
311#define __NR_timerfd_gettime 312
310#define __NR_timerfd_settime32 311
311#define __NR_timerfd_gettime32 312
312312#define __NR_signalfd4 313
313313#define __NR_eventfd2 314
314314#define __NR_epoll_create1 315
......@@ -413,6 +413,8 @@
413413#define __NR_fsconfig 431
414414#define __NR_fsmount 432
415415#define __NR_fspick 433
416#define __NR_pidfd_open 434
417#define __NR_clone3 435
416418
417419#define SYS_restart_syscall 0
418420#define SYS_exit 1
......@@ -492,8 +494,8 @@
492494#define SYS_setrlimit 75
493495#define SYS_getrlimit 76
494496#define SYS_getrusage 77
495#define SYS_gettimeofday 78
496#define SYS_settimeofday 79
497#define SYS_gettimeofday_time32 78
498#define SYS_settimeofday_time32 79
497499#define SYS_getgroups 80
498500#define SYS_setgroups 81
499501#define SYS_select 82
......@@ -654,14 +656,14 @@
654656#define SYS_epoll_wait 238
655657#define SYS_remap_file_pages 239
656658#define SYS_timer_create 240
657#define SYS_timer_settime 241
658#define SYS_timer_gettime 242
659#define SYS_timer_settime32 241
660#define SYS_timer_gettime32 242
659661#define SYS_timer_getoverrun 243
660662#define SYS_timer_delete 244
661#define SYS_clock_settime 245
662#define SYS_clock_gettime 246
663#define SYS_clock_getres 247
664#define SYS_clock_nanosleep 248
663#define SYS_clock_settime32 245
664#define SYS_clock_gettime32 246
665#define SYS_clock_getres_time32 247
666#define SYS_clock_nanosleep_time32 248
665667#define SYS_swapcontext 249
666668#define SYS_tgkill 250
667669#define SYS_utimes 251
......@@ -723,8 +725,8 @@
723725#define SYS_sync_file_range2 308
724726#define SYS_fallocate 309
725727#define SYS_subpage_prot 310
726#define SYS_timerfd_settime 311
727#define SYS_timerfd_gettime 312
728#define SYS_timerfd_settime32 311
729#define SYS_timerfd_gettime32 312
728730#define SYS_signalfd4 313
729731#define SYS_eventfd2 314
730732#define SYS_epoll_create1 315
......@@ -828,4 +830,6 @@
828830#define SYS_fsopen 430
829831#define SYS_fsconfig 431
830832#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 @@
22#define _Int64 long
33#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
5#if __BIG_ENDIAN__
6#define __BYTE_ORDER 4321
7#else
8#define __BYTE_ORDER 1234
139#endif
1410
11#define __LONG_MAX 0x7fffffffffffffffL
1512
1613#ifndef __cplusplus
1714#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -37,52 +34,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
3734#define __DEFINED_max_align_t
3835#endif
3936
40
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_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
37#define __LITTLE_ENDIAN 1234
38#define __BIG_ENDIAN 4321
39#define __USE_TIME_BITS64 1
8640
8741#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
8842typedef unsigned _Addr size_t;
......@@ -119,6 +73,16 @@ typedef _Reg register_t;
11973#define __DEFINED_register_t
12074#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
12387#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
12488typedef signed char int8_t;
......@@ -254,7 +218,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254218#endif
255219
256220#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); };
258222#define __DEFINED_struct_timespec
259223#endif
260224
......@@ -350,6 +314,17 @@ typedef struct _IO_FILE FILE;
350314#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
353328#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354329typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355330#define __DEFINED_mbstate_t
......@@ -385,6 +360,42 @@ typedef unsigned short sa_family_t;
385360#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
388399#undef _Addr
389400#undef _Int64
390401#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 @@
99#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
1010
1111typedef unsigned long greg_t, gregset_t[48];
12
13typedef struct {
14 double fpregs[32];
15 double fpscr;
16} fpregset_t;
12typedef double fpregset_t[33];
1713
1814typedef struct {
1915#ifdef __GNUC__
......@@ -36,7 +32,7 @@ typedef struct sigcontext {
3632 int _pad0;
3733 unsigned long handler;
3834 unsigned long oldmask;
39 void *regs;
35 struct pt_regs *regs;
4036 gregset_t gp_regs;
4137 fpregset_t fp_regs;
4238 vrregset_t *v_regs;
lib/libc/include/powerpc64-linux-musl/bits/socket.h-34
......@@ -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
351#define SO_DEBUG 1
362#define SO_REUSEADDR 2
373#define SO_TYPE 3
lib/libc/include/powerpc64-linux-musl/bits/syscall.h+5-1
......@@ -385,6 +385,8 @@
385385#define __NR_fsconfig 431
386386#define __NR_fsmount 432
387387#define __NR_fspick 433
388#define __NR_pidfd_open 434
389#define __NR_clone3 435
388390
389391#define SYS_restart_syscall 0
390392#define SYS_exit 1
......@@ -772,4 +774,6 @@
772774#define SYS_fsopen 430
773775#define SYS_fsconfig 431
774776#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 @@
22#define _Int64 long
33#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
5#define __BYTE_ORDER 1234
6#define __LONG_MAX 0x7fffffffffffffffL
157
168#ifndef __cplusplus
179#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -48,52 +40,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
4840#define __DEFINED_max_align_t
4941#endif
5042
51
52#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
53typedef long time_t;
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
43#define __LITTLE_ENDIAN 1234
44#define __BIG_ENDIAN 4321
45#define __USE_TIME_BITS64 1
9746
9847#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
9948typedef unsigned _Addr size_t;
......@@ -130,6 +79,16 @@ typedef _Reg register_t;
13079#define __DEFINED_register_t
13180#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
13493#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
13594typedef signed char int8_t;
......@@ -265,7 +224,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
265224#endif
266225
267226#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); };
269228#define __DEFINED_struct_timespec
270229#endif
271230
......@@ -361,6 +320,17 @@ typedef struct _IO_FILE FILE;
361320#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
364334#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
365335typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
366336#define __DEFINED_mbstate_t
......@@ -396,6 +366,42 @@ typedef unsigned short sa_family_t;
396366#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
399405#undef _Addr
400406#undef _Int64
401407#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 {
3535 union __riscv_mc_fp_state __fpregs;
3636} 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
3847#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3948typedef unsigned long greg_t;
4049typedef 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 @@
287287#define __NR_fsconfig 431
288288#define __NR_fsmount 432
289289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
291293#define __NR_sysriscv __NR_arch_specific_syscall
292294#define __NR_riscv_flush_icache (__NR_sysriscv + 15)
......@@ -579,5 +581,7 @@
579581#define SYS_fsconfig 431
580582#define SYS_fsmount 432
581583#define SYS_fspick 433
584#define SYS_pidfd_open 434
585#define SYS_clone3 435
582586#define SYS_sysriscv __NR_arch_specific_syscall
583587#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 @@
22#define _Int64 long
33#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
5#define __BYTE_ORDER 4321
6#define __LONG_MAX 0x7fffffffffffffffL
157
168#ifndef __cplusplus
179#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -37,52 +29,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
3729#define __DEFINED_max_align_t
3830#endif
3931
40
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_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
32#define __LITTLE_ENDIAN 1234
33#define __BIG_ENDIAN 4321
34#define __USE_TIME_BITS64 1
8635
8736#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
8837typedef unsigned _Addr size_t;
......@@ -119,6 +68,16 @@ typedef _Reg register_t;
11968#define __DEFINED_register_t
12069#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
12382#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
12483typedef signed char int8_t;
......@@ -254,7 +213,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
254213#endif
255214
256215#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); };
258217#define __DEFINED_struct_timespec
259218#endif
260219
......@@ -350,6 +309,17 @@ typedef struct _IO_FILE FILE;
350309#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
353323#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
354324typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
355325#define __DEFINED_mbstate_t
......@@ -385,6 +355,42 @@ typedef unsigned short sa_family_t;
385355#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
388394#undef _Addr
389395#undef _Int64
390396#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#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 @@
350350#define __NR_fsconfig 431
351351#define __NR_fsmount 432
352352#define __NR_fspick 433
353#define __NR_pidfd_open 434
354#define __NR_clone3 435
353355
354356#define SYS_exit 1
355357#define SYS_fork 2
......@@ -702,4 +704,6 @@
702704#define SYS_fsopen 430
703705#define SYS_fsconfig 431
704706#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 @@
22#define _Int64 long
33#define _Reg long
44
5#if defined(__NEED_va_list) && !defined(__DEFINED_va_list)
6typedef __builtin_va_list va_list;
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
5#define __BYTE_ORDER 1234
6#define __LONG_MAX 0x7fffffffffffffffL
157
168#ifndef __cplusplus
179#if defined(__NEED_wchar_t) && !defined(__DEFINED_wchar_t)
......@@ -50,52 +42,9 @@ typedef struct { long long __ll; long double __ld; } max_align_t;
5042#define __DEFINED_max_align_t
5143#endif
5244
53
54#if defined(__NEED_time_t) && !defined(__DEFINED_time_t)
55typedef long time_t;
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
45#define __LITTLE_ENDIAN 1234
46#define __BIG_ENDIAN 4321
47#define __USE_TIME_BITS64 1
9948
10049#if defined(__NEED_size_t) && !defined(__DEFINED_size_t)
10150typedef unsigned _Addr size_t;
......@@ -132,6 +81,16 @@ typedef _Reg register_t;
13281#define __DEFINED_register_t
13382#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
13695#if defined(__NEED_int8_t) && !defined(__DEFINED_int8_t)
13796typedef signed char int8_t;
......@@ -267,7 +226,7 @@ struct timeval { time_t tv_sec; suseconds_t tv_usec; };
267226#endif
268227
269228#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); };
271230#define __DEFINED_struct_timespec
272231#endif
273232
......@@ -363,6 +322,17 @@ typedef struct _IO_FILE FILE;
363322#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
366336#if defined(__NEED_mbstate_t) && !defined(__DEFINED_mbstate_t)
367337typedef struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
368338#define __DEFINED_mbstate_t
......@@ -398,6 +368,42 @@ typedef unsigned short sa_family_t;
398368#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
401407#undef _Addr
402408#undef _Int64
403409#undef _Reg
\ No newline at end of file
lib/libc/include/x86_64-linux-musl/bits/limits.h+1-8
......@@ -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 @@
343343#define __NR_fsconfig 431
344344#define __NR_fsmount 432
345345#define __NR_fspick 433
346#define __NR_pidfd_open 434
347#define __NR_clone3 435
346348
347349#define SYS_read 0
348350#define SYS_write 1
......@@ -688,4 +690,6 @@
688690#define SYS_fsopen 430
689691#define SYS_fsconfig 431
690692#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 @@
11musl as a whole is licensed under the following standard MIT license:
22
33----------------------------------------------------------------------
4Copyright © 2005-2019 Rich Felker, et al.
4Copyright © 2005-2020 Rich Felker, et al.
55
66Permission is hereby granted, free of charge, to any person obtaining
77a copy of this software and associated documentation files (the
......@@ -26,6 +26,7 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2626Authors/contributors include:
2727
2828A. Wilcox
29Ada Worcester
2930Alex Dowad
3031Alex Suykov
3132Alexander Monakov
......@@ -65,7 +66,6 @@ Jeremy Huntwork
6566Jo-Philipp Wich
6667Joakim Sindholt
6768John Spencer
68Josiah Worcester
6969Julien Ramseier
7070Justin Cormack
7171Kaarle Ritvanen
lib/libc/musl/arch/aarch64/bits/alltypes.h.in+7-13
......@@ -2,8 +2,13 @@
22#define _Int64 long
33#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
5#if __AARCH64EB__
6#define __BYTE_ORDER 4321
7#else
8#define __BYTE_ORDER 1234
9#endif
10
11#define __LONG_MAX 0x7fffffffffffffffL
712
813#ifndef __cplusplus
914TYPEDEF unsigned wchar_t;
......@@ -17,14 +22,3 @@ TYPEDEF float float_t;
1722TYPEDEF double double_t;
1823
1924TYPEDEF 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 @@
287287#define __NR_fsconfig 431
288288#define __NR_fsmount 432
289289#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#include <endian.h>
2
31#if __BYTE_ORDER == __BIG_ENDIAN
42#define ENDIAN_SUFFIX "_be"
53#else
lib/libc/musl/arch/arm/bits/alltypes.h.in+8-13
......@@ -1,9 +1,15 @@
1#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
6#if __ARMEB__
7#define __BYTE_ORDER 4321
8#else
9#define __BYTE_ORDER 1234
10#endif
11
12#define __LONG_MAX 0x7fffffffL
713
814#ifndef __cplusplus
915TYPEDEF unsigned wchar_t;
......@@ -13,14 +19,3 @@ TYPEDEF float float_t;
1319TYPEDEF double double_t;
1420
1521TYPEDEF 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#define IPC_STAT 2
1#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
3 time_t msg_stime;
4 int __unused1;
5 time_t msg_rtime;
6 int __unused2;
7 time_t msg_ctime;
8 int __unused3;
3 unsigned long __msg_stime_lo;
4 unsigned long __msg_stime_hi;
5 unsigned long __msg_rtime_lo;
6 unsigned long __msg_rtime_hi;
7 unsigned long __msg_ctime_lo;
8 unsigned long __msg_ctime_hi;
99 unsigned long msg_cbytes;
1010 msgqnum_t msg_qnum;
1111 msglen_t msg_qbytes;
1212 pid_t msg_lspid;
1313 pid_t msg_lrpid;
1414 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
1518};
lib/libc/musl/arch/arm/bits/sem.h+6-4
......@@ -1,9 +1,9 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 time_t sem_otime;
4 long __unused1;
5 time_t sem_ctime;
6 long __unused2;
3 unsigned long __sem_otime_lo;
4 unsigned long __sem_otime_hi;
5 unsigned long __sem_ctime_lo;
6 unsigned long __sem_ctime_hi;
77#if __BYTE_ORDER == __LITTLE_ENDIAN
88 unsigned short sem_nsems;
99 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
......@@ -13,4 +13,6 @@ struct semid_ds {
1313#endif
1414 long __unused3;
1515 long __unused4;
16 time_t sem_otime;
17 time_t sem_ctime;
1618};
lib/libc/musl/arch/arm/bits/shm.h+10-6
......@@ -3,17 +3,21 @@
33struct shmid_ds {
44 struct ipc_perm shm_perm;
55 size_t shm_segsz;
6 time_t shm_atime;
7 int __unused1;
8 time_t shm_dtime;
9 int __unused2;
10 time_t shm_ctime;
11 int __unused3;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_atime_hi;
8 unsigned long __shm_dtime_lo;
9 unsigned long __shm_dtime_hi;
10 unsigned long __shm_ctime_lo;
11 unsigned long __shm_ctime_hi;
1212 pid_t shm_cpid;
1313 pid_t shm_lpid;
1414 unsigned long shm_nattch;
1515 unsigned long __pad1;
1616 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
1721};
1822
1923struct shminfo {
lib/libc/musl/arch/arm/bits/stat.h+5-1
......@@ -14,8 +14,12 @@ struct stat {
1414 off_t st_size;
1515 blksize_t st_blksize;
1616 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;
1722 struct timespec st_atim;
1823 struct timespec st_mtim;
1924 struct timespec st_ctim;
20 ino_t st_ino;
2125};
lib/libc/musl/arch/arm/bits/syscall.h.in+12-10
......@@ -55,8 +55,8 @@
5555#define __NR_sethostname 74
5656#define __NR_setrlimit 75
5757#define __NR_getrusage 77
58#define __NR_gettimeofday 78
59#define __NR_settimeofday 79
58#define __NR_gettimeofday_time32 78
59#define __NR_settimeofday_time32 79
6060#define __NR_getgroups 80
6161#define __NR_setgroups 81
6262#define __NR_symlink 83
......@@ -211,14 +211,14 @@
211211#define __NR_remap_file_pages 253
212212#define __NR_set_tid_address 256
213213#define __NR_timer_create 257
214#define __NR_timer_settime 258
215#define __NR_timer_gettime 259
214#define __NR_timer_settime32 258
215#define __NR_timer_gettime32 259
216216#define __NR_timer_getoverrun 260
217217#define __NR_timer_delete 261
218#define __NR_clock_settime 262
219#define __NR_clock_gettime 263
220#define __NR_clock_getres 264
221#define __NR_clock_nanosleep 265
218#define __NR_clock_settime32 262
219#define __NR_clock_gettime32 263
220#define __NR_clock_getres_time32 264
221#define __NR_clock_nanosleep_time32 265
222222#define __NR_statfs64 266
223223#define __NR_fstatfs64 267
224224#define __NR_tgkill 268
......@@ -308,8 +308,8 @@
308308#define __NR_timerfd_create 350
309309#define __NR_eventfd 351
310310#define __NR_fallocate 352
311#define __NR_timerfd_settime 353
312#define __NR_timerfd_gettime 354
311#define __NR_timerfd_settime32 353
312#define __NR_timerfd_gettime32 354
313313#define __NR_signalfd4 355
314314#define __NR_eventfd2 356
315315#define __NR_epoll_create1 357
......@@ -387,6 +387,8 @@
387387#define __NR_fsconfig 431
388388#define __NR_fsmount 432
389389#define __NR_fspick 433
390#define __NR_pidfd_open 434
391#define __NR_clone3 435
390392
391393#define __ARM_NR_breakpoint 0x0f0001
392394#define __ARM_NR_cacheflush 0x0f0002
lib/libc/musl/arch/arm/reloc.h-2
......@@ -1,5 +1,3 @@
1#include <endian.h>
2
31#if __BYTE_ORDER == __BIG_ENDIAN
42#define ENDIAN_SUFFIX "eb"
53#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
9999}
100100
101101#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"
103105#define VDSO_CGT_VER "LINUX_2.6"
104106
105107#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 @@
104104#define FIOGETOWN 0x8903
105105#define SIOCGPGRP 0x8904
106106#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
107111#define SIOCGSTAMP 0x8906
108112#define SIOCGSTAMPNS 0x8907
113#endif
109114
110115#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 @@
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#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5#if __GNUC__ >= 3
6TYPEDEF __builtin_va_list va_list;
7TYPEDEF __builtin_va_list __isoc_va_list;
8#else
9TYPEDEF struct __va_list * va_list;
10TYPEDEF struct __va_list * __isoc_va_list;
11#endif
6#define __BYTE_ORDER 1234
7#define __LONG_MAX 0x7fffffffL
128
139#ifndef __cplusplus
1410#ifdef __WCHAR_TYPE__
......@@ -33,14 +29,3 @@ TYPEDEF struct { __attribute__((__aligned__(8))) long long __ll; long double __l
3329#else
3430TYPEDEF struct { alignas(8) long long __ll; long double __ld; } max_align_t;
3531#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#define IPC_STAT 2
1#define IPC_STAT 0x102
lib/libc/musl/arch/i386/bits/limits.h-7
......@@ -1,8 +1 @@
1#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
31#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
3 time_t msg_stime;
4 int __unused1;
5 time_t msg_rtime;
6 int __unused2;
7 time_t msg_ctime;
8 int __unused3;
3 unsigned long __msg_stime_lo;
4 unsigned long __msg_stime_hi;
5 unsigned long __msg_rtime_lo;
6 unsigned long __msg_rtime_hi;
7 unsigned long __msg_ctime_lo;
8 unsigned long __msg_ctime_hi;
99 unsigned long msg_cbytes;
1010 msgqnum_t msg_qnum;
1111 msglen_t msg_qbytes;
1212 pid_t msg_lspid;
1313 pid_t msg_lrpid;
1414 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
1518};
lib/libc/musl/arch/i386/bits/sem.h+6-4
......@@ -1,11 +1,13 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 time_t sem_otime;
4 long __unused1;
5 time_t sem_ctime;
6 long __unused2;
3 unsigned long __sem_otime_lo;
4 unsigned long __sem_otime_hi;
5 unsigned long __sem_ctime_lo;
6 unsigned long __sem_ctime_hi;
77 unsigned short sem_nsems;
88 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
99 long __unused3;
1010 long __unused4;
11 time_t sem_otime;
12 time_t sem_ctime;
1113};
lib/libc/musl/arch/i386/bits/shm.h+10-6
......@@ -3,17 +3,21 @@
33struct shmid_ds {
44 struct ipc_perm shm_perm;
55 size_t shm_segsz;
6 time_t shm_atime;
7 int __unused1;
8 time_t shm_dtime;
9 int __unused2;
10 time_t shm_ctime;
11 int __unused3;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_atime_hi;
8 unsigned long __shm_dtime_lo;
9 unsigned long __shm_dtime_hi;
10 unsigned long __shm_ctime_lo;
11 unsigned long __shm_ctime_hi;
1212 pid_t shm_cpid;
1313 pid_t shm_lpid;
1414 unsigned long shm_nattch;
1515 unsigned long __pad1;
1616 unsigned long __pad2;
17 unsigned long __pad3;
18 time_t shm_atime;
19 time_t shm_dtime;
20 time_t shm_ctime;
1721};
1822
1923struct shminfo {
lib/libc/musl/arch/i386/bits/stat.h+5-1
......@@ -14,8 +14,12 @@ struct stat {
1414 off_t st_size;
1515 blksize_t st_blksize;
1616 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;
1722 struct timespec st_atim;
1823 struct timespec st_mtim;
1924 struct timespec st_ctim;
20 ino_t st_ino;
2125};
lib/libc/musl/arch/i386/bits/syscall.h.in+12-10
......@@ -76,8 +76,8 @@
7676#define __NR_setrlimit 75
7777#define __NR_getrlimit 76 /* Back compatible 2Gig limited rlimit */
7878#define __NR_getrusage 77
79#define __NR_gettimeofday 78
80#define __NR_settimeofday 79
79#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday_time32 79
8181#define __NR_getgroups 80
8282#define __NR_setgroups 81
8383#define __NR_select 82
......@@ -257,14 +257,14 @@
257257#define __NR_remap_file_pages 257
258258#define __NR_set_tid_address 258
259259#define __NR_timer_create 259
260#define __NR_timer_settime (__NR_timer_create+1)
261#define __NR_timer_gettime (__NR_timer_create+2)
260#define __NR_timer_settime32 (__NR_timer_create+1)
261#define __NR_timer_gettime32 (__NR_timer_create+2)
262262#define __NR_timer_getoverrun (__NR_timer_create+3)
263263#define __NR_timer_delete (__NR_timer_create+4)
264#define __NR_clock_settime (__NR_timer_create+5)
265#define __NR_clock_gettime (__NR_timer_create+6)
266#define __NR_clock_getres (__NR_timer_create+7)
267#define __NR_clock_nanosleep (__NR_timer_create+8)
264#define __NR_clock_settime32 (__NR_timer_create+5)
265#define __NR_clock_gettime32 (__NR_timer_create+6)
266#define __NR_clock_getres_time32 (__NR_timer_create+7)
267#define __NR_clock_nanosleep_time32 (__NR_timer_create+8)
268268#define __NR_statfs64 268
269269#define __NR_fstatfs64 269
270270#define __NR_tgkill 270
......@@ -322,8 +322,8 @@
322322#define __NR_timerfd_create 322
323323#define __NR_eventfd 323
324324#define __NR_fallocate 324
325#define __NR_timerfd_settime 325
326#define __NR_timerfd_gettime 326
325#define __NR_timerfd_settime32 325
326#define __NR_timerfd_gettime32 326
327327#define __NR_signalfd4 327
328328#define __NR_eventfd2 328
329329#define __NR_epoll_create1 329
......@@ -424,4 +424,6 @@
424424#define __NR_fsconfig 431
425425#define __NR_fsmount 432
426426#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
8383}
8484
8585#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"
8789#define VDSO_CGT_VER "LINUX_2.6"
8890
8991#define SYSCALL_USE_SOCKETCALL
lib/libc/musl/arch/mips/bits/alltypes.h.in+8-13
......@@ -1,9 +1,15 @@
1#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
6#if _MIPSEL || __MIPSEL || __MIPSEL__
7#define __BYTE_ORDER 1234
8#else
9#define __BYTE_ORDER 4321
10#endif
11
12#define __LONG_MAX 0x7fffffffL
713
814#ifndef __cplusplus
915TYPEDEF int wchar_t;
......@@ -13,14 +19,3 @@ TYPEDEF float float_t;
1319TYPEDEF double double_t;
1420
1521TYPEDEF 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 @@
11#define HWCAP_MIPS_R6 (1 << 0)
22#define HWCAP_MIPS_MSA (1 << 1)
33#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 @@
110110#define SIOCATMARK _IOR('s', 7, int)
111111#define SIOCSPGRP _IOW('s', 8, pid_t)
112112#define SIOCGPGRP _IOR('s', 9, pid_t)
113#define SIOCGSTAMP 0x8906
114#define SIOCGSTAMPNS 0x8907
113#define SIOCGSTAMP _IOR(0x89, 6, char[16])
114#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
lib/libc/musl/arch/mips/bits/ipcstat.h+1-1
......@@ -1 +1 @@
1#define IPC_STAT 2
1#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
33#if _MIPSEL || __MIPSEL || __MIPSEL__
4 time_t msg_stime;
5 int __unused1;
6 time_t msg_rtime;
7 int __unused2;
8 time_t msg_ctime;
9 int __unused3;
4 unsigned long __msg_stime_lo;
5 unsigned long __msg_stime_hi;
6 unsigned long __msg_rtime_lo;
7 unsigned long __msg_rtime_hi;
8 unsigned long __msg_ctime_lo;
9 unsigned long __msg_ctime_hi;
1010#else
11 int __unused1;
12 time_t msg_stime;
13 int __unused2;
14 time_t msg_rtime;
15 int __unused3;
16 time_t msg_ctime;
11 unsigned long __msg_stime_hi;
12 unsigned long __msg_stime_lo;
13 unsigned long __msg_rtime_hi;
14 unsigned long __msg_rtime_lo;
15 unsigned long __msg_ctime_hi;
16 unsigned long __msg_ctime_lo;
1717#endif
1818 unsigned long msg_cbytes;
1919 msgqnum_t msg_qnum;
......@@ -21,4 +21,7 @@ struct msqid_ds {
2121 pid_t msg_lspid;
2222 pid_t msg_lrpid;
2323 unsigned long __unused[2];
24 time_t msg_stime;
25 time_t msg_rtime;
26 time_t msg_ctime;
2427};
lib/libc/musl/arch/mips/bits/sem.h+6-4
......@@ -1,7 +1,7 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 time_t sem_otime;
4 time_t sem_ctime;
3 unsigned long __sem_otime_lo;
4 unsigned long __sem_ctime_lo;
55#if __BYTE_ORDER == __LITTLE_ENDIAN
66 unsigned short sem_nsems;
77 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
......@@ -9,6 +9,8 @@ struct semid_ds {
99 char __sem_nsems_pad[sizeof(long)-sizeof(short)];
1010 unsigned short sem_nsems;
1111#endif
12 long __unused3;
13 long __unused4;
12 unsigned long __sem_otime_hi;
13 unsigned long __sem_ctime_hi;
14 time_t sem_otime;
15 time_t sem_ctime;
1416};
lib/libc/musl/arch/mips/bits/shm.h+10-5
......@@ -3,14 +3,19 @@
33struct shmid_ds {
44 struct ipc_perm shm_perm;
55 size_t shm_segsz;
6 time_t shm_atime;
7 time_t shm_dtime;
8 time_t shm_ctime;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_dtime_lo;
8 unsigned long __shm_ctime_lo;
99 pid_t shm_cpid;
1010 pid_t shm_lpid;
1111 unsigned long shm_nattch;
12 unsigned long __pad1;
13 unsigned long __pad2;
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;
1419};
1520
1621struct shminfo {
lib/libc/musl/arch/mips/bits/signal.h+6-2
......@@ -19,14 +19,18 @@ typedef struct {
1919} fpregset_t;
2020struct sigcontext {
2121 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;
2325 unsigned sc_ownedfp, sc_fpc_csr, sc_fpc_eir, sc_used_math, sc_dsp;
2426 unsigned long long sc_mdhi, sc_mdlo;
2527 unsigned long sc_hi1, sc_lo1, sc_hi2, sc_lo2, sc_hi3, sc_lo3;
2628};
2729typedef struct {
2830 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;
3034 unsigned ownedfp, fpc_csr, fpc_eir, used_math, dsp;
3135 unsigned long long mdhi, mdlo;
3236 unsigned long hi1, lo1, hi2, lo2, hi3, lo3;
lib/libc/musl/arch/mips/bits/socket.h-18
......@@ -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
171#define SOCK_STREAM 2
182#define SOCK_DGRAM 1
193
......@@ -32,8 +16,6 @@ struct cmsghdr {
3216#define SO_RCVBUF 0x1002
3317#define SO_SNDLOWAT 0x1003
3418#define SO_RCVLOWAT 0x1004
35#define SO_RCVTIMEO 0x1006
36#define SO_SNDTIMEO 0x1005
3719#define SO_ERROR 0x1007
3820#define SO_TYPE 0x1008
3921#define SO_ACCEPTCONN 0x1009
lib/libc/musl/arch/mips/bits/stat.h+8-4
......@@ -12,11 +12,15 @@ struct stat {
1212 dev_t st_rdev;
1313 long __st_padding2[2];
1414 off_t st_size;
15 struct timespec st_atim;
16 struct timespec st_mtim;
17 struct timespec st_ctim;
15 struct {
16 long tv_sec;
17 long tv_nsec;
18 } __st_atim32, __st_mtim32, __st_ctim32;
1819 blksize_t st_blksize;
1920 long __st_padding3;
2021 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];
2226};
lib/libc/musl/arch/mips/bits/syscall.h.in+12-10
......@@ -76,8 +76,8 @@
7676#define __NR_setrlimit 4075
7777#define __NR_getrlimit 4076
7878#define __NR_getrusage 4077
79#define __NR_gettimeofday 4078
80#define __NR_settimeofday 4079
79#define __NR_gettimeofday_time32 4078
80#define __NR_settimeofday_time32 4079
8181#define __NR_getgroups 4080
8282#define __NR_setgroups 4081
8383#define __NR_reserved82 4082
......@@ -256,14 +256,14 @@
256256#define __NR_statfs64 4255
257257#define __NR_fstatfs64 4256
258258#define __NR_timer_create 4257
259#define __NR_timer_settime 4258
260#define __NR_timer_gettime 4259
259#define __NR_timer_settime32 4258
260#define __NR_timer_gettime32 4259
261261#define __NR_timer_getoverrun 4260
262262#define __NR_timer_delete 4261
263#define __NR_clock_settime 4262
264#define __NR_clock_gettime 4263
265#define __NR_clock_getres 4264
266#define __NR_clock_nanosleep 4265
263#define __NR_clock_settime32 4262
264#define __NR_clock_gettime32 4263
265#define __NR_clock_getres_time32 4264
266#define __NR_clock_nanosleep_time32 4265
267267#define __NR_tgkill 4266
268268#define __NR_utimes 4267
269269#define __NR_mbind 4268
......@@ -319,8 +319,8 @@
319319#define __NR_eventfd 4319
320320#define __NR_fallocate 4320
321321#define __NR_timerfd_create 4321
322#define __NR_timerfd_gettime 4322
323#define __NR_timerfd_settime 4323
322#define __NR_timerfd_gettime32 4322
323#define __NR_timerfd_settime32 4323
324324#define __NR_signalfd4 4324
325325#define __NR_eventfd2 4325
326326#define __NR_epoll_create1 4326
......@@ -406,4 +406,6 @@
406406#define __NR_fsconfig 4431
407407#define __NR_fsmount 4432
408408#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#include <endian.h>
2
31#if __mips_isa_rev >= 6
42#define ISA_SUFFIX "r6"
53#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
142142}
143143
144144#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"
146148#define VDSO_CGT_VER "LINUX_2.6"
147149
148150#define SO_SNDTIMEO_OLD 0x1005
lib/libc/musl/arch/mips64/bits/alltypes.h.in+7-13
......@@ -2,8 +2,13 @@
22#define _Int64 long
33#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
5#if _MIPSEL || __MIPSEL || __MIPSEL__
6#define __BYTE_ORDER 1234
7#else
8#define __BYTE_ORDER 4321
9#endif
10
11#define __LONG_MAX 0x7fffffffffffffffL
712
813#ifndef __cplusplus
914TYPEDEF int wchar_t;
......@@ -14,15 +19,4 @@ TYPEDEF double double_t;
1419
1520TYPEDEF struct { long long __ll; long double __ld; } max_align_t;
1621
17TYPEDEF long time_t;
18TYPEDEF long suseconds_t;
19
2022TYPEDEF 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#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
351#define SOCK_STREAM 2
362#define SOCK_DGRAM 1
373#define SOL_SOCKET 65535
lib/libc/musl/arch/mips64/bits/syscall.h.in+2
......@@ -336,4 +336,6 @@
336336#define __NR_fsconfig 5431
337337#define __NR_fsmount 5432
338338#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#ifndef __RELOC_H__
2#define __RELOC_H__
3
4#define _GNU_SOURCE
5#include <endian.h>
6
71#if __mips_isa_rev >= 6
82#define ISA_SUFFIX "r6"
93#else
......@@ -33,6 +27,8 @@
3327#define REL_DTPOFF R_MIPS_TLS_DTPREL64
3428#define REL_TPOFF R_MIPS_TLS_TPREL64
3529
30#include <endian.h>
31
3632#undef R_TYPE
3733#undef R_SYM
3834#undef R_INFO
......@@ -62,5 +58,3 @@
6258 " daddu %0, %0, $ra \n" \
6359 ".set pop \n" \
6460 : "=r"(*(fp)) : : "memory", "ra" )
65
66#endif
lib/libc/musl/arch/powerpc/bits/alltypes.h.in+3-13
......@@ -1,9 +1,10 @@
1#define _REDIR_TIME64 1
12#define _Addr int
23#define _Int64 long long
34#define _Reg int
45
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
6#define __BYTE_ORDER 4321
7#define __LONG_MAX 0x7fffffffL
78
89#ifndef __cplusplus
910#ifdef __WCHAR_TYPE__
......@@ -17,14 +18,3 @@ TYPEDEF float float_t;
1718TYPEDEF double double_t;
1819
1920TYPEDEF 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 @@
116116#define FIOGETOWN 0x8903
117117#define SIOCGPGRP 0x8904
118118#define SIOCATMARK 0x8905
119#define SIOCGSTAMP 0x8906
120#define SIOCGSTAMPNS 0x8907
119#define SIOCGSTAMP _IOR(0x89, 6, char[16])
120#define SIOCGSTAMPNS _IOR(0x89, 7, char[16])
lib/libc/musl/arch/powerpc/bits/ipcstat.h+1-1
......@@ -1 +1 @@
1#define IPC_STAT 2
1#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 @@
11struct msqid_ds {
22 struct ipc_perm msg_perm;
3 int __unused1;
4 time_t msg_stime;
5 int __unused2;
6 time_t msg_rtime;
7 int __unused3;
8 time_t msg_ctime;
3 unsigned long __msg_stime_hi;
4 unsigned long __msg_stime_lo;
5 unsigned long __msg_rtime_hi;
6 unsigned long __msg_rtime_lo;
7 unsigned long __msg_ctime_hi;
8 unsigned long __msg_ctime_lo;
99 unsigned long msg_cbytes;
1010 msgqnum_t msg_qnum;
1111 msglen_t msg_qbytes;
1212 pid_t msg_lspid;
1313 pid_t msg_lrpid;
1414 unsigned long __unused[2];
15 time_t msg_stime;
16 time_t msg_rtime;
17 time_t msg_ctime;
1518};
lib/libc/musl/arch/powerpc/bits/sem.h+6-4
......@@ -1,10 +1,12 @@
11struct semid_ds {
22 struct ipc_perm sem_perm;
3 int __unused1;
4 time_t sem_otime;
5 int __unused2;
6 time_t sem_ctime;
3 unsigned long __sem_otime_hi;
4 unsigned long __sem_otime_lo;
5 unsigned long __sem_ctime_hi;
6 unsigned long __sem_ctime_lo;
77 unsigned short __sem_nsems_pad, sem_nsems;
88 long __unused3;
99 long __unused4;
10 time_t sem_otime;
11 time_t sem_ctime;
1012};
lib/libc/musl/arch/powerpc/bits/shm.h+9-7
......@@ -2,19 +2,21 @@
22
33struct shmid_ds {
44 struct ipc_perm shm_perm;
5 int __unused1;
6 time_t shm_atime;
7 int __unused2;
8 time_t shm_dtime;
9 int __unused3;
10 time_t shm_ctime;
11 int __unused4;
5 unsigned long __shm_atime_hi;
6 unsigned long __shm_atime_lo;
7 unsigned long __shm_dtime_hi;
8 unsigned long __shm_dtime_lo;
9 unsigned long __shm_ctime_hi;
10 unsigned long __shm_ctime_lo;
1211 size_t shm_segsz;
1312 pid_t shm_cpid;
1413 pid_t shm_lpid;
1514 unsigned long shm_nattch;
1615 unsigned long __pad1;
1716 unsigned long __pad2;
17 time_t shm_atime;
18 time_t shm_dtime;
19 time_t shm_ctime;
1820};
1921
2022struct shminfo {
lib/libc/musl/arch/powerpc/bits/signal.h+1-1
......@@ -28,7 +28,7 @@ struct sigcontext {
2828 int signal;
2929 unsigned long handler;
3030 unsigned long oldmask;
31 void *regs;
31 struct pt_regs *regs;
3232};
3333
3434typedef struct {
lib/libc/musl/arch/powerpc/bits/socket.h-18
......@@ -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
171#define SO_DEBUG 1
182#define SO_REUSEADDR 2
193#define SO_TYPE 3
......@@ -31,8 +15,6 @@ struct cmsghdr {
3115#define SO_REUSEPORT 15
3216#define SO_RCVLOWAT 16
3317#define SO_SNDLOWAT 17
34#define SO_RCVTIMEO 18
35#define SO_SNDTIMEO 19
3618#define SO_PASSCRED 20
3719#define SO_PEERCRED 21
3820#define SO_ACCEPTCONN 30
lib/libc/musl/arch/powerpc/bits/stat.h+5-1
......@@ -13,8 +13,12 @@ struct stat {
1313 off_t st_size;
1414 blksize_t st_blksize;
1515 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];
1621 struct timespec st_atim;
1722 struct timespec st_mtim;
1823 struct timespec st_ctim;
19 unsigned __unused[2];
2024};
lib/libc/musl/arch/powerpc/bits/syscall.h.in+12-10
......@@ -76,8 +76,8 @@
7676#define __NR_setrlimit 75
7777#define __NR_getrlimit 76
7878#define __NR_getrusage 77
79#define __NR_gettimeofday 78
80#define __NR_settimeofday 79
79#define __NR_gettimeofday_time32 78
80#define __NR_settimeofday_time32 79
8181#define __NR_getgroups 80
8282#define __NR_setgroups 81
8383#define __NR_select 82
......@@ -238,14 +238,14 @@
238238#define __NR_epoll_wait 238
239239#define __NR_remap_file_pages 239
240240#define __NR_timer_create 240
241#define __NR_timer_settime 241
242#define __NR_timer_gettime 242
241#define __NR_timer_settime32 241
242#define __NR_timer_gettime32 242
243243#define __NR_timer_getoverrun 243
244244#define __NR_timer_delete 244
245#define __NR_clock_settime 245
246#define __NR_clock_gettime 246
247#define __NR_clock_getres 247
248#define __NR_clock_nanosleep 248
245#define __NR_clock_settime32 245
246#define __NR_clock_gettime32 246
247#define __NR_clock_getres_time32 247
248#define __NR_clock_nanosleep_time32 248
249249#define __NR_swapcontext 249
250250#define __NR_tgkill 250
251251#define __NR_utimes 251
......@@ -307,8 +307,8 @@
307307#define __NR_sync_file_range2 308
308308#define __NR_fallocate 309
309309#define __NR_subpage_prot 310
310#define __NR_timerfd_settime 311
311#define __NR_timerfd_gettime 312
310#define __NR_timerfd_settime32 311
311#define __NR_timerfd_gettime32 312
312312#define __NR_signalfd4 313
313313#define __NR_eventfd2 314
314314#define __NR_epoll_create1 315
......@@ -413,4 +413,6 @@
413413#define __NR_fsconfig 431
414414#define __NR_fsmount 432
415415#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 @@
22#define _Int64 long
33#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
5#if __BIG_ENDIAN__
6#define __BYTE_ORDER 4321
7#else
8#define __BYTE_ORDER 1234
9#endif
10
11#define __LONG_MAX 0x7fffffffffffffffL
712
813#ifndef __cplusplus
914TYPEDEF int wchar_t;
......@@ -13,14 +18,3 @@ TYPEDEF float float_t;
1318TYPEDEF double double_t;
1419
1520TYPEDEF 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 @@
99#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
1010
1111typedef unsigned long greg_t, gregset_t[48];
12
13typedef struct {
14 double fpregs[32];
15 double fpscr;
16} fpregset_t;
12typedef double fpregset_t[33];
1713
1814typedef struct {
1915#ifdef __GNUC__
......@@ -36,7 +32,7 @@ typedef struct sigcontext {
3632 int _pad0;
3733 unsigned long handler;
3834 unsigned long oldmask;
39 void *regs;
35 struct pt_regs *regs;
4036 gregset_t gp_regs;
4137 fpregset_t fp_regs;
4238 vrregset_t *v_regs;
lib/libc/musl/arch/powerpc64/bits/socket.h-34
......@@ -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
351#define SO_DEBUG 1
362#define SO_REUSEADDR 2
373#define SO_TYPE 3
lib/libc/musl/arch/powerpc64/bits/syscall.h.in+2
......@@ -385,4 +385,6 @@
385385#define __NR_fsconfig 431
386386#define __NR_fsmount 432
387387#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#include <endian.h>
2
31#if __BYTE_ORDER == __LITTLE_ENDIAN
42#define ENDIAN_SUFFIX "le"
53#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)
1515 " bnez %1, 1b\n"
1616 "1:"
1717 : "=&r"(old), "=&r"(tmp)
18 : "r"(p), "r"(t), "r"(s)
18 : "r"(p), "r"((long)t), "r"((long)s)
1919 : "memory");
2020 return old;
2121}
lib/libc/musl/arch/riscv64/bits/alltypes.h.in+2-13
......@@ -2,8 +2,8 @@
22#define _Int64 long
33#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
5#define __BYTE_ORDER 1234
6#define __LONG_MAX 0x7fffffffffffffffL
77
88#ifndef __cplusplus
99TYPEDEF int wchar_t;
......@@ -16,14 +16,3 @@ TYPEDEF float float_t;
1616TYPEDEF double double_t;
1717
1818TYPEDEF 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 @@
11#undef __WORDSIZE
22#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 {
3535 union __riscv_mc_fp_state __fpregs;
3636} 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
3847#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
3948typedef unsigned long greg_t;
4049typedef 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 @@
287287#define __NR_fsconfig 431
288288#define __NR_fsmount 432
289289#define __NR_fspick 433
290#define __NR_pidfd_open 434
291#define __NR_clone3 435
290292
291293#define __NR_sysriscv __NR_arch_specific_syscall
292294#define __NR_riscv_flush_icache (__NR_sysriscv + 15)
lib/libc/musl/arch/s390x/bits/alltypes.h.in+2-13
......@@ -2,8 +2,8 @@
22#define _Int64 long
33#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
5#define __BYTE_ORDER 4321
6#define __LONG_MAX 0x7fffffffffffffffL
77
88#ifndef __cplusplus
99TYPEDEF int wchar_t;
......@@ -13,14 +13,3 @@ TYPEDEF double float_t;
1313TYPEDEF double double_t;
1414
1515TYPEDEF 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#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
31#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 @@
350350#define __NR_fsconfig 431
351351#define __NR_fsmount 432
352352#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#include <endian.h>
2
31#define LDSO_ARCH "s390x"
42
53#define REL_SYMBOLIC R_390_64
lib/libc/musl/arch/x86_64/bits/alltypes.h.in+2-13
......@@ -2,8 +2,8 @@
22#define _Int64 long
33#define _Reg long
44
5TYPEDEF __builtin_va_list va_list;
6TYPEDEF __builtin_va_list __isoc_va_list;
5#define __BYTE_ORDER 1234
6#define __LONG_MAX 0x7fffffffffffffffL
77
88#ifndef __cplusplus
99TYPEDEF int wchar_t;
......@@ -18,14 +18,3 @@ TYPEDEF double double_t;
1818#endif
1919
2020TYPEDEF 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#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
2 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
31#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 @@
343343#define __NR_fsconfig 431
344344#define __NR_fsmount 432
345345#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
6262#define off64_t off_t
6363#endif
6464
65#if _REDIR_TIME64
66__REDIR(aio_suspend, __aio_suspend_time64);
67#endif
68
6569#ifdef __cplusplus
6670}
6771#endif
lib/libc/musl/include/alloca.h-2
......@@ -10,9 +10,7 @@ extern "C" {
1010
1111void *alloca(size_t);
1212
13#ifdef __GNUC__
1413#define alloca __builtin_alloca
15#endif
1614
1715#ifdef __cplusplus
1816}
lib/libc/musl/include/alltypes.h.in+18-1
......@@ -1,3 +1,7 @@
1#define __LITTLE_ENDIAN 1234
2#define __BIG_ENDIAN 4321
3#define __USE_TIME_BITS64 1
4
15TYPEDEF unsigned _Addr size_t;
26TYPEDEF unsigned _Addr uintptr_t;
37TYPEDEF _Addr ptrdiff_t;
......@@ -5,6 +9,8 @@ TYPEDEF _Addr ssize_t;
59TYPEDEF _Addr intptr_t;
610TYPEDEF _Addr regoff_t;
711TYPEDEF _Reg register_t;
12TYPEDEF _Int64 time_t;
13TYPEDEF _Int64 suseconds_t;
814
915TYPEDEF signed char int8_t;
1016TYPEDEF signed short int16_t;
......@@ -35,7 +41,7 @@ TYPEDEF void * timer_t;
3541TYPEDEF int clockid_t;
3642TYPEDEF long clock_t;
3743STRUCT 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
4046TYPEDEF int pid_t;
4147TYPEDEF unsigned id_t;
......@@ -60,6 +66,9 @@ TYPEDEF struct { unsigned __attr[2]; } pthread_rwlockattr_t;
6066STRUCT _IO_FILE { char __x; };
6167TYPEDEF struct _IO_FILE FILE;
6268
69TYPEDEF __builtin_va_list va_list;
70TYPEDEF __builtin_va_list __isoc_va_list;
71
6372TYPEDEF struct __mbstate_t { unsigned __opaque1, __opaque2; } mbstate_t;
6473
6574TYPEDEF struct __locale_struct * locale_t;
......@@ -71,6 +80,14 @@ STRUCT iovec { void *iov_base; size_t iov_len; };
7180TYPEDEF unsigned socklen_t;
7281TYPEDEF 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
7491#undef _Addr
7592#undef _Int64
7693#undef _Reg
lib/libc/musl/include/arpa/nameser.h-1
......@@ -7,7 +7,6 @@ extern "C" {
77
88#include <stddef.h>
99#include <stdint.h>
10#include <endian.h>
1110
1211#define __NAMESER 19991006
1312#define NS_PACKETSZ 512
lib/libc/musl/include/dirent.h+2-12
......@@ -15,19 +15,9 @@ extern "C" {
1515
1616#include <bits/alltypes.h>
1717
18typedef struct __dirstream DIR;
19
20#define _DIRENT_HAVE_D_RECLEN
21#define _DIRENT_HAVE_D_OFF
22#define _DIRENT_HAVE_D_TYPE
18#include <bits/dirent.h>
2319
24struct dirent {
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};
20typedef struct __dirstream DIR;
3121
3222#define d_fileno d_ino
3323
lib/libc/musl/include/dlfcn.h+4
......@@ -35,6 +35,10 @@ int dladdr(const void *, Dl_info *);
3535int dlinfo(void *, int, void *);
3636#endif
3737
38#if _REDIR_TIME64
39__REDIR(dlsym, __dlsym_time64);
40#endif
41
3842#ifdef __cplusplus
3943}
4044#endif
lib/libc/musl/include/endian.h+21-23
......@@ -3,25 +3,19 @@
33
44#include <features.h>
55
6#define __LITTLE_ENDIAN 1234
7#define __BIG_ENDIAN 4321
8#define __PDP_ENDIAN 3412
6#define __NEED_uint16_t
7#define __NEED_uint32_t
8#define __NEED_uint64_t
99
10#if defined(__GNUC__) && defined(__BYTE_ORDER__)
11#define __BYTE_ORDER __BYTE_ORDER__
12#else
13#include <bits/endian.h>
14#endif
10#include <bits/alltypes.h>
1511
16#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
12#define __PDP_ENDIAN 3412
1713
1814#define BIG_ENDIAN __BIG_ENDIAN
1915#define LITTLE_ENDIAN __LITTLE_ENDIAN
2016#define PDP_ENDIAN __PDP_ENDIAN
2117#define BYTE_ORDER __BYTE_ORDER
2218
23#include <stdint.h>
24
2519static __inline uint16_t __bswap16(uint16_t __x)
2620{
2721 return __x<<8 | __x>>8;
......@@ -40,43 +34,47 @@ static __inline uint64_t __bswap64(uint64_t __x)
4034#if __BYTE_ORDER == __LITTLE_ENDIAN
4135#define htobe16(x) __bswap16(x)
4236#define be16toh(x) __bswap16(x)
43#define betoh16(x) __bswap16(x)
4437#define htobe32(x) __bswap32(x)
4538#define be32toh(x) __bswap32(x)
46#define betoh32(x) __bswap32(x)
4739#define htobe64(x) __bswap64(x)
4840#define be64toh(x) __bswap64(x)
49#define betoh64(x) __bswap64(x)
5041#define htole16(x) (uint16_t)(x)
5142#define le16toh(x) (uint16_t)(x)
52#define letoh16(x) (uint16_t)(x)
5343#define htole32(x) (uint32_t)(x)
5444#define le32toh(x) (uint32_t)(x)
55#define letoh32(x) (uint32_t)(x)
5645#define htole64(x) (uint64_t)(x)
5746#define le64toh(x) (uint64_t)(x)
58#define letoh64(x) (uint64_t)(x)
5947#else
6048#define htobe16(x) (uint16_t)(x)
6149#define be16toh(x) (uint16_t)(x)
62#define betoh16(x) (uint16_t)(x)
6350#define htobe32(x) (uint32_t)(x)
6451#define be32toh(x) (uint32_t)(x)
65#define betoh32(x) (uint32_t)(x)
6652#define htobe64(x) (uint64_t)(x)
6753#define be64toh(x) (uint64_t)(x)
68#define betoh64(x) (uint64_t)(x)
6954#define htole16(x) __bswap16(x)
7055#define le16toh(x) __bswap16(x)
71#define letoh16(x) __bswap16(x)
7256#define htole32(x) __bswap32(x)
7357#define le32toh(x) __bswap32(x)
74#define letoh32(x) __bswap32(x)
7558#define htole64(x) __bswap64(x)
7659#define le64toh(x) __bswap64(x)
77#define letoh64(x) __bswap64(x)
7860#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
8078#endif
8179
8280#endif
lib/libc/musl/include/features.h+2
......@@ -35,4 +35,6 @@
3535#define _Noreturn
3636#endif
3737
38#define __REDIR(x,y) __typeof__(x) x __asm__(#y)
39
3840#endif
lib/libc/musl/include/limits.h+13-5
......@@ -3,9 +3,7 @@
33
44#include <features.h>
55
6/* Most limits are system-specific */
7
8#include <bits/limits.h>
6#include <bits/alltypes.h> /* __LONG_MAX */
97
108/* Support signed or unsigned plain-char */
119
......@@ -17,8 +15,6 @@
1715#define CHAR_MAX 127
1816#endif
1917
20/* Some universal constants... */
21
2218#define CHAR_BIT 8
2319#define SCHAR_MIN (-128)
2420#define SCHAR_MAX 127
......@@ -30,8 +26,10 @@
3026#define INT_MAX 0x7fffffff
3127#define UINT_MAX 0xffffffffU
3228#define LONG_MIN (-LONG_MAX-1)
29#define LONG_MAX __LONG_MAX
3330#define ULONG_MAX (2UL*LONG_MAX+1)
3431#define LLONG_MIN (-LLONG_MAX-1)
32#define LLONG_MAX 0x7fffffffffffffffLL
3533#define ULLONG_MAX (2ULL*LLONG_MAX+1)
3634
3735#define MB_LEN_MAX 4
......@@ -39,9 +37,13 @@
3937#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
4038 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
4139
40#include <bits/limits.h>
41
4242#define PIPE_BUF 4096
4343#define FILESIZEBITS 64
44#ifndef NAME_MAX
4445#define NAME_MAX 255
46#endif
4547#define PATH_MAX 4096
4648#define NGROUPS_MAX 32
4749#define ARG_MAX 131072
......@@ -53,6 +55,12 @@
5355#define TTY_NAME_MAX 32
5456#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
5664/* Implementation choices... */
5765
5866#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
3030int mq_timedsend(mqd_t, const char *, size_t, unsigned, const struct timespec *);
3131int 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
3338#ifdef __cplusplus
3439}
3540#endif
lib/libc/musl/include/netinet/icmp6.h-1
......@@ -9,7 +9,6 @@ extern "C" {
99#include <string.h>
1010#include <sys/types.h>
1111#include <netinet/in.h>
12#include <endian.h>
1312
1413#define ICMP6_FILTER 1
1514
lib/libc/musl/include/netinet/if_ether.h+1
......@@ -58,6 +58,7 @@
5858#define ETH_P_ERSPAN 0x88BE
5959#define ETH_P_PREAUTH 0x88C7
6060#define ETH_P_TIPC 0x88CA
61#define ETH_P_LLDP 0x88CC
6162#define ETH_P_MACSEC 0x88E5
6263#define ETH_P_8021AH 0x88E7
6364#define ETH_P_MVRP 0x88F5
lib/libc/musl/include/netinet/ip.h+2-1
......@@ -7,7 +7,6 @@ extern "C" {
77
88#include <stdint.h>
99#include <netinet/in.h>
10#include <endian.h>
1110
1211struct timestamp {
1312 uint8_t len;
......@@ -191,6 +190,8 @@ struct ip_timestamp {
191190
192191#define IP_MSS 576
193192
193#define __UAPI_DEF_IPHDR 0
194
194195#ifdef __cplusplus
195196}
196197#endif
lib/libc/musl/include/netinet/ip6.h-1
......@@ -7,7 +7,6 @@ extern "C" {
77
88#include <stdint.h>
99#include <netinet/in.h>
10#include <endian.h>
1110
1211struct ip6_hdr {
1312 union {
lib/libc/musl/include/netinet/tcp.h+3-1
......@@ -38,6 +38,7 @@
3838#define TCP_FASTOPEN_NO_COOKIE 34
3939#define TCP_ZEROCOPY_RECEIVE 35
4040#define TCP_INQ 36
41#define TCP_TX_DELAY 37
4142
4243#define TCP_CM_INQ TCP_INQ
4344
......@@ -97,7 +98,6 @@ enum {
9798#include <sys/types.h>
9899#include <sys/socket.h>
99100#include <stdint.h>
100#include <endian.h>
101101
102102typedef uint32_t tcp_seq;
103103
......@@ -234,6 +234,8 @@ struct tcp_info {
234234 uint64_t tcpi_bytes_retrans;
235235 uint32_t tcpi_dsack_dups;
236236 uint32_t tcpi_reord_seen;
237 uint32_t tcpi_rcv_ooopack;
238 uint32_t tcpi_snd_wnd;
237239};
238240
239241#define TCP_MD5SIG_MAXKEYLEN 80
lib/libc/musl/include/poll.h+6
......@@ -44,6 +44,12 @@ int poll (struct pollfd *, nfds_t, int);
4444int ppoll(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *);
4545#endif
4646
47#if _REDIR_TIME64
48#ifdef _GNU_SOURCE
49__REDIR(ppoll, __ppoll_time64);
50#endif
51#endif
52
4753#ifdef __cplusplus
4854}
4955#endif
lib/libc/musl/include/pthread.h+10
......@@ -224,6 +224,16 @@ int pthread_tryjoin_np(pthread_t, void **);
224224int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);
225225#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
227237#ifdef __cplusplus
228238}
229239#endif
lib/libc/musl/include/sched.h+8
......@@ -19,10 +19,14 @@ extern "C" {
1919struct sched_param {
2020 int sched_priority;
2121 int __reserved1;
22#if _REDIR_TIME64
23 long __reserved2[4];
24#else
2225 struct {
2326 time_t __reserved1;
2427 long __reserved2;
2528 } __reserved2[2];
29#endif
2630 int __reserved3;
2731};
2832
......@@ -133,6 +137,10 @@ __CPU_op_func_S(XOR, ^)
133137
134138#endif
135139
140#if _REDIR_TIME64
141__REDIR(sched_rr_get_interval, __sched_rr_get_interval_time64);
142#endif
143
136144#ifdef __cplusplus
137145}
138146#endif
lib/libc/musl/include/semaphore.h+4
......@@ -29,6 +29,10 @@ int sem_trywait(sem_t *);
2929int sem_unlink(const char *);
3030int sem_wait(sem_t *);
3131
32#if _REDIR_TIME64
33__REDIR(sem_timedwait, __sem_timedwait_time64);
34#endif
35
3236#ifdef __cplusplus
3337}
3438#endif
lib/libc/musl/include/signal.h+8
......@@ -271,6 +271,14 @@ typedef int sig_atomic_t;
271271void (*signal(int, void (*)(int)))(int);
272272int 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
274282#ifdef __cplusplus
275283}
276284#endif
lib/libc/musl/include/sys/acct.h-1
......@@ -6,7 +6,6 @@ extern "C" {
66#endif
77
88#include <features.h>
9#include <endian.h>
109#include <time.h>
1110#include <stdint.h>
1211
lib/libc/musl/include/sys/ioctl.h+1
......@@ -4,6 +4,7 @@
44extern "C" {
55#endif
66
7#include <bits/alltypes.h>
78#include <bits/ioctl.h>
89
910#define N_TTY 0
lib/libc/musl/include/sys/mman.h+2
......@@ -92,6 +92,8 @@ extern "C" {
9292#define MADV_DODUMP 17
9393#define MADV_WIPEONFORK 18
9494#define MADV_KEEPONFORK 19
95#define MADV_COLD 20
96#define MADV_PAGEOUT 21
9597#define MADV_HWPOISON 100
9698#define MADV_SOFT_OFFLINE 101
9799#endif
lib/libc/musl/include/sys/prctl.h+4
......@@ -154,6 +154,10 @@ struct prctl_mm_map {
154154#define PR_PAC_APDBKEY (1UL << 3)
155155#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
157161int prctl (int, ...);
158162
159163#ifdef __cplusplus
lib/libc/musl/include/sys/procfs.h+3-4
......@@ -23,10 +23,9 @@ struct elf_prstatus {
2323 pid_t pr_ppid;
2424 pid_t pr_pgrp;
2525 pid_t pr_sid;
26 struct timeval pr_utime;
27 struct timeval pr_stime;
28 struct timeval pr_cutime;
29 struct timeval pr_cstime;
26 struct {
27 long tv_sec, tv_usec;
28 } pr_utime, pr_stime, pr_cutime, pr_cstime;
3029 elf_gregset_t pr_reg;
3130 int pr_fpvalid;
3231};
lib/libc/musl/include/sys/ptrace.h+29
......@@ -41,6 +41,7 @@ extern "C" {
4141#define PTRACE_SETSIGMASK 0x420b
4242#define PTRACE_SECCOMP_GET_FILTER 0x420c
4343#define PTRACE_SECCOMP_GET_METADATA 0x420d
44#define PTRACE_GET_SYSCALL_INFO 0x420e
4445
4546#define PT_READ_I PTRACE_PEEKTEXT
4647#define PT_READ_D PTRACE_PEEKDATA
......@@ -88,6 +89,11 @@ extern "C" {
8889
8990#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
9197#include <bits/ptrace.h>
9298
9399struct __ptrace_peeksiginfo_args {
......@@ -101,6 +107,29 @@ struct __ptrace_seccomp_metadata {
101107 uint64_t flags;
102108};
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
104133long ptrace(int, ...);
105134
106135#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 *);
9090#define RLIMIT_MSGQUEUE 12
9191#define RLIMIT_NICE 13
9292#define RLIMIT_RTPRIO 14
93#define RLIMIT_NLIMITS 15
93#define RLIMIT_RTTIME 15
94#define RLIMIT_NLIMITS 16
9495
9596#define RLIM_NLIMITS RLIMIT_NLIMITS
9697
......@@ -104,6 +105,10 @@ int prlimit(pid_t, int, const struct rlimit *, struct rlimit *);
104105#define rlim64_t rlim_t
105106#endif
106107
108#if _REDIR_TIME64
109__REDIR(getrusage, __getrusage_time64);
110#endif
111
107112#ifdef __cplusplus
108113}
109114#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
3535#define NFDBITS (8*(int)sizeof(long))
3636#endif
3737
38#if _REDIR_TIME64
39__REDIR(select, __select_time64);
40__REDIR(pselect, __pselect_time64);
41#endif
42
3843#ifdef __cplusplus
3944}
4045#endif
lib/libc/musl/include/sys/sem.h+6-2
......@@ -25,8 +25,6 @@ extern "C" {
2525#define SETVAL 16
2626#define SETALL 17
2727
28#include <endian.h>
29
3028#include <bits/sem.h>
3129
3230#define _SEM_SEMUN_UNDEFINED 1
......@@ -62,6 +60,12 @@ int semop(int, struct sembuf *, size_t);
6260int semtimedop(int, struct sembuf *, size_t, const struct timespec *);
6361#endif
6462
63#if _REDIR_TIME64
64#ifdef _GNU_SOURCE
65__REDIR(semtimedop, __semtimedop_time64);
66#endif
67#endif
68
6569#ifdef __cplusplus
6670}
6771#endif
lib/libc/musl/include/sys/socket.h+63-6
......@@ -19,6 +19,40 @@ extern "C" {
1919
2020#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
2256#ifdef _GNU_SOURCE
2357struct ucred {
2458 pid_t pid;
......@@ -182,8 +216,6 @@ struct linger {
182216#define SO_PEERCRED 17
183217#define SO_RCVLOWAT 18
184218#define SO_SNDLOWAT 19
185#define SO_RCVTIMEO 20
186#define SO_SNDTIMEO 21
187219#define SO_ACCEPTCONN 30
188220#define SO_PEERSEC 31
189221#define SO_SNDBUFFORCE 32
......@@ -192,6 +224,28 @@ struct linger {
192224#define SO_DOMAIN 39
193225#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
195249#define SO_SECURITY_AUTHENTICATION 22
196250#define SO_SECURITY_ENCRYPTION_TRANSPORT 23
197251#define SO_SECURITY_ENCRYPTION_NETWORK 24
......@@ -203,14 +257,10 @@ struct linger {
203257#define SO_GET_FILTER SO_ATTACH_FILTER
204258
205259#define SO_PEERNAME 28
206#define SO_TIMESTAMP 29
207260#define SCM_TIMESTAMP SO_TIMESTAMP
208
209261#define SO_PASSSEC 34
210#define SO_TIMESTAMPNS 35
211262#define SCM_TIMESTAMPNS SO_TIMESTAMPNS
212263#define SO_MARK 36
213#define SO_TIMESTAMPING 37
214264#define SCM_TIMESTAMPING SO_TIMESTAMPING
215265#define SO_RXQ_OVFL 40
216266#define SO_WIFI_STATUS 41
......@@ -238,6 +288,7 @@ struct linger {
238288#define SO_TXTIME 61
239289#define SCM_TXTIME SO_TXTIME
240290#define SO_BINDTOIFINDEX 62
291#define SO_DETACH_REUSEPORT_BPF 68
241292
242293#ifndef SOL_SOCKET
243294#define SOL_SOCKET 1
......@@ -350,6 +401,12 @@ int setsockopt (int, int, int, const void *, socklen_t);
350401
351402int sockatmark (int);
352403
404#if _REDIR_TIME64
405#ifdef _GNU_SOURCE
406__REDIR(recvmmsg, __recvmmsg_time64);
407#endif
408#endif
409
353410#ifdef __cplusplus
354411}
355412#endif
lib/libc/musl/include/sys/stat.h+9
......@@ -110,6 +110,15 @@ int lchmod(const char *, mode_t);
110110#define off64_t off_t
111111#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
113122#ifdef __cplusplus
114123}
115124#endif
lib/libc/musl/include/sys/statvfs.h-2
......@@ -11,8 +11,6 @@ extern "C" {
1111#define __NEED_fsfilcnt_t
1212#include <bits/alltypes.h>
1313
14#include <endian.h>
15
1614struct statvfs {
1715 unsigned long f_bsize, f_frsize;
1816 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 *);
5656 (void)0 )
5757#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
5973#ifdef __cplusplus
6074}
6175#endif
lib/libc/musl/include/sys/timeb.h+6
......@@ -4,6 +4,8 @@
44extern "C" {
55#endif
66
7#include <features.h>
8
79#define __NEED_time_t
810
911#include <bits/alltypes.h>
......@@ -16,6 +18,10 @@ struct timeb {
1618
1719int ftime(struct timeb *);
1820
21#if _REDIR_TIME64
22__REDIR(ftime, __ftime64);
23#endif
24
1925#ifdef __cplusplus
2026}
2127#endif
lib/libc/musl/include/sys/timerfd.h+5
......@@ -20,6 +20,11 @@ int timerfd_create(int, int);
2020int timerfd_settime(int, int, const struct itimerspec *, struct itimerspec *);
2121int 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
2328#ifdef __cplusplus
2429}
2530#endif
lib/libc/musl/include/sys/timex.h+5
......@@ -91,6 +91,11 @@ struct timex {
9191int adjtimex(struct timex *);
9292int 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
9499#ifdef __cplusplus
95100}
96101#endif
lib/libc/musl/include/sys/ttydefaults.h+1-6
......@@ -6,16 +6,11 @@
66#define TTYDEF_LFLAG (ECHO | ICANON | ISIG | IEXTEN | ECHOE|ECHOKE|ECHOCTL)
77#define TTYDEF_CFLAG (CREAD | CS7 | PARENB | HUPCL)
88#define TTYDEF_SPEED (B9600)
9#define CTRL(x) (x&037)
9#define CTRL(x) ((x)&037)
1010#define CEOF CTRL('d')
1111
12#ifdef _POSIX_VDISABLE
13#define CEOL _POSIX_VDISABLE
14#define CSTATUS _POSIX_VDISABLE
15#else
1612#define CEOL '\0'
1713#define CSTATUS '\0'
18#endif
1914
2015#define CERASE 0177
2116#define CINTR CTRL('c')
lib/libc/musl/include/sys/wait.h+9-1
......@@ -13,7 +13,8 @@ extern "C" {
1313typedef enum {
1414 P_ALL = 0,
1515 P_PID = 1,
16 P_PGID = 2
16 P_PGID = 2,
17 P_PIDFD = 3
1718} idtype_t;
1819
1920pid_t wait (int *);
......@@ -53,6 +54,13 @@ pid_t wait4 (pid_t, int *, int, struct rusage *);
5354#define WIFSIGNALED(s) (((s)&0xffff)-1U < 0xffu)
5455#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
5664#ifdef __cplusplus
5765}
5866#endif
lib/libc/musl/include/threads.h+6
......@@ -80,6 +80,12 @@ void tss_delete(tss_t);
8080int tss_set(tss_t, void *);
8181void *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
8389#ifdef __cplusplus
8490}
8591#endif
lib/libc/musl/include/time.h+28
......@@ -130,6 +130,34 @@ int stime(const time_t *);
130130time_t timegm(struct tm *);
131131#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
133161#ifdef __cplusplus
134162}
135163#endif
lib/libc/musl/include/utime.h+6
......@@ -5,6 +5,8 @@
55extern "C" {
66#endif
77
8#include <features.h>
9
810#define __NEED_time_t
911
1012#include <bits/alltypes.h>
......@@ -16,6 +18,10 @@ struct utimbuf {
1618
1719int utime (const char *, const struct utimbuf *);
1820
21#if _REDIR_TIME64
22__REDIR(utime, __utime64);
23#endif
24
1925#ifdef __cplusplus
2026}
2127#endif
lib/libc/musl/include/utmpx.h+6-1
......@@ -16,6 +16,7 @@ extern "C" {
1616
1717struct utmpx {
1818 short ut_type;
19 short __ut_pad1;
1920 pid_t ut_pid;
2021 char ut_line[32];
2122 char ut_id[4];
......@@ -25,7 +26,11 @@ struct utmpx {
2526 short __e_termination;
2627 short __e_exit;
2728 } 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
2934 struct timeval ut_tv;
3035 unsigned ut_addr_v6[4];
3136 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
7373 }
7474}
7575
76#if !_REDIR_TIME64
7677weak_alias(aio_suspend, aio_suspend64);
78#endif
lib/libc/musl/src/complex/cacosh.c+4-1
......@@ -4,6 +4,9 @@
44
55double complex cacosh(double complex z)
66{
7 int zineg = signbit(cimag(z));
8
79 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));
912}
lib/libc/musl/src/complex/cacoshf.c+4-1
......@@ -2,6 +2,9 @@
22
33float complex cacoshf(float complex z)
44{
5 int zineg = signbit(cimagf(z));
6
57 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));
710}
lib/libc/musl/src/complex/cacoshl.c+4-1
......@@ -8,7 +8,10 @@ long double complex cacoshl(long double complex z)
88#else
99long double complex cacoshl(long double complex z)
1010{
11 int zineg = signbit(cimagl(z));
12
1113 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));
1316}
1417#endif
lib/libc/musl/src/complex/catanf.c+1-13
......@@ -87,29 +87,17 @@ float complex catanf(float complex z)
8787 x = crealf(z);
8888 y = cimagf(z);
8989
90 if ((x == 0.0f) && (y > 1.0f))
91 goto ovrf;
92
9390 x2 = x * x;
9491 a = 1.0f - x2 - (y * y);
95 if (a == 0.0f)
96 goto ovrf;
9792
9893 t = 0.5f * atan2f(2.0f * x, a);
9994 w = _redupif(t);
10095
10196 t = y - 1.0f;
10297 a = x2 + (t * t);
103 if (a == 0.0f)
104 goto ovrf;
10598
10699 t = y + 1.0f;
107100 a = (x2 + (t * t))/a;
108 w = w + (0.25f * logf (a)) * I;
109 return w;
110
111ovrf:
112 // FIXME
113 w = MAXNUMF + MAXNUMF * I;
101 w = CMPLXF(w, 0.25f * logf(a));
114102 return w;
115103}
lib/libc/musl/src/complex/catanl.c+1-13
......@@ -97,30 +97,18 @@ long double complex catanl(long double complex z)
9797 x = creall(z);
9898 y = cimagl(z);
9999
100 if ((x == 0.0L) && (y > 1.0L))
101 goto ovrf;
102
103100 x2 = x * x;
104101 a = 1.0L - x2 - (y * y);
105 if (a == 0.0L)
106 goto ovrf;
107102
108103 t = atan2l(2.0L * x, a) * 0.5L;
109104 w = redupil(t);
110105
111106 t = y - 1.0L;
112107 a = x2 + (t * t);
113 if (a == 0.0L)
114 goto ovrf;
115108
116109 t = y + 1.0L;
117110 a = (x2 + (t * t)) / a;
118 w = w + (0.25L * logl(a)) * I;
119 return w;
120
121ovrf:
122 // FIXME
123 w = LDBL_MAX + LDBL_MAX * I;
111 w = CMPLXF(w, 0.25L * logl(a));
124112 return w;
125113}
126114#endif
lib/libc/musl/src/ctype/alpha.h+84-75
......@@ -8,17 +8,17 @@
8817,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,
9917,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,
101016,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,
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,
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,
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,
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,100,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,101,16,16,16,16,16,
141416,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,
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,
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,
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,
1916,16,16,16,16,16,16,16,16,106,107,108,109,16,16,16,16,16,16,16,16,110,16,16,
2016,16,16,16,16,111,112,16,16,16,16,113,16,16,114,16,16,16,16,16,16,16,16,16,
2116,16,16,16,
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,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,16,16,17,
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,16,111,112,113,114,16,16,16,16,16,16,16,16,115,116,
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,16,
222216,0,0,0,0,0,0,0,0,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,
2323255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
2424255,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 @@
2727255,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,
2828251,255,255,255,255,255,255,255,255,255,191,255,255,255,255,255,255,255,255,
2929255,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,
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,
30255,255,255,255,255,255,255,255,255,255,255,254,255,255,255,127,2,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,
3232255,255,255,254,255,195,255,255,255,255,255,255,255,255,255,255,255,255,239,
333331,254,225,255,
3434159,0,0,255,255,255,255,255,255,0,224,255,255,255,255,255,255,255,255,255,255,
......@@ -42,54 +42,55 @@
4242255,0,0,239,223,253,255,255,253,239,227,223,29,96,64,207,255,6,0,239,223,253,
4343255,255,255,255,231,223,93,240,128,207,255,0,252,236,255,127,252,255,255,251,
444447,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,
46460,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,
48255,127,64,255,51,255,255,255,255,191,32,255,255,255,255,255,247,255,255,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,255,255,255,63,255,255,255,255,191,32,255,255,255,255,255,247,255,255,255,
4949255,255,255,255,255,255,61,127,61,255,255,255,255,255,61,255,255,255,255,61,
5050127,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,
5252255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
5353255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
5454255,255,255,255,255,159,255,255,254,255,255,7,255,255,255,255,255,255,255,255,
5555255,199,255,1,255,223,15,0,255,255,15,0,255,255,15,0,255,223,13,0,255,255,255,
5656255,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,
585863,
59590,255,255,255,127,255,15,255,1,192,255,255,255,255,63,31,0,255,255,255,255,
6060255,15,255,255,255,3,255,3,0,0,0,0,255,255,255,15,255,255,255,255,255,255,255,
6161127,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,
6262255,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,
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,
65255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,128,255,31,0,
66255,255,63,63,255,255,255,255,63,63,255,170,255,255,255,63,255,255,255,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,
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,
69255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
63255,191,255,3,0,255,255,255,255,255,255,127,0,255,227,255,255,255,255,255,63,
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,255,255,255,0,0,0,0,
66128,255,31,0,255,255,63,63,255,255,255,255,63,63,255,170,255,255,255,63,255,
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,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,
69224,67,0,0,255,255,255,255,255,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
70700,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,
71710,255,255,255,255,255,127,255,255,255,255,255,127,255,255,255,255,255,255,255,
7272255,255,255,255,255,255,255,255,255,31,120,12,0,255,255,255,255,191,32,255,
7373255,255,255,255,255,255,128,0,0,255,255,127,0,127,127,127,127,127,127,127,127,
7474255,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,
75750,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,
7777255,255,255,255,255,255,255,255,255,127,0,0,255,255,255,7,0,0,0,0,0,0,255,255,
7878255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
7979255,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,
81810,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,0,
82820,0,0,0,0,0,255,255,255,255,255,63,255,31,255,255,255,15,0,0,255,255,255,255,
8383255,127,240,143,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,
84840,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,
86255,15,0,255,255,255,255,255,255,255,255,47,0,255,3,0,0,252,40,255,255,255,
87255,255,7,255,255,255,255,7,0,255,255,255,31,255,255,255,255,255,255,247,255,
880,128,255,3,223,255,255,127,255,255,255,255,255,255,127,0,255,63,255,3,255,
89255,127,196,255,255,255,255,255,255,255,127,5,0,0,56,255,255,60,0,126,126,126,
900,127,127,255,255,255,255,255,247,63,0,255,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,
92255,255,255,255,255,255,255,255,255,15,0,255,255,127,248,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,255,15,0,255,255,255,255,255,255,255,255,47,0,255,3,0,0,252,232,255,255,
87255,255,255,7,255,255,255,255,7,0,255,255,255,31,255,255,255,255,255,255,247,
88255,0,128,255,3,255,255,255,127,255,255,255,255,255,255,127,0,255,63,255,3,
89255,255,127,252,255,255,255,255,255,255,255,127,5,0,0,56,255,255,60,0,126,126,
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,255,7,255,3,255,255,255,255,255,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,
939415,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255,255,255,
9495255,255,255,255,255,255,255,255,3,0,0,0,0,127,0,248,224,255,253,127,95,219,
9596255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,0,248,255,255,255,
......@@ -109,55 +110,63 @@
1091100,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,
110111127,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,
1111120,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,
113114255,31,0,0,0,255,255,255,255,255,255,63,0,255,255,63,0,255,255,7,0,255,255,3,
1141150,0,0,0,0,0,0,0,0,0,0,0,
1151160,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,
117255,0,0,252,255,255,255,255,255,255,1,0,0,255,255,255,1,255,3,255,255,255,255,
118255,255,199,255,0,0,255,255,255,255,71,0,255,255,255,255,255,255,255,255,30,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,
120255,1,255,255,255,255,255,255,255,1,255,3,239,159,249,255,255,253,237,227,159,
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,255,187,7,255,3,0,0,0,0,255,255,255,255,255,255,255,255,179,0,255,3,0,0,0,
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,
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,
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,
120192,255,0,0,252,255,255,255,255,255,255,1,0,0,255,255,255,1,255,3,255,255,255,
121255,255,255,199,255,112,0,255,255,255,255,71,0,255,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,
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,
1231270,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,
1241280,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,
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,
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,
1280,128,255,255,255,255,255,255,231,127,0,0,255,255,255,255,255,255,207,255,255,
1290,0,0,0,0,255,255,255,255,255,255,255,1,255,253,255,255,255,255,127,127,1,0,
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,
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,
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,
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,
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,
1320,0,0,0,255,252,255,255,255,255,255,252,26,0,0,0,255,255,255,255,255,255,231,
133127,0,0,255,255,255,255,255,255,255,255,255,32,0,0,0,0,255,255,255,255,255,
134255,255,1,255,253,255,255,255,255,127,127,1,0,255,3,0,0,252,255,255,255,252,
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,
132138255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,3,0,0,
1331390,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,127,0,
1341400,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,
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,
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,
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,
1390,255,255,255,63,0,0,255,255,255,255,255,255,127,0,15,0,255,3,248,255,255,224,
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,
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,
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,
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,
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,
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,
145255,255,63,0,0,255,255,255,255,255,255,0,0,15,0,255,3,248,255,255,224,255,255,
1460,0,0,0,0,0,0,0,0,0,0,0,0,
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,
142150255,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,
144255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7,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,
146255,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,
152255,255,255,255,255,255,255,255,255,255,255,255,7,0,255,255,255,127,0,0,0,0,0,
1530,7,0,240,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
147154255,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,
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,
150255,255,255,255,255,255,255,255,255,255,223,255,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,
152255,123,95,252,253,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
155255,255,255,255,255,255,255,255,255,255,255,255,255,255,15,255,255,255,255,
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,
1570,0,255,255,255,255,255,255,255,255,255,255,223,255,255,255,255,255,255,255,
158255,223,100,222,255,235,239,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,
153160255,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,
155247,255,255,223,255,255,255,223,255,255,127,255,255,255,127,255,255,255,253,
156255,255,255,253,255,255,247,207,255,255,255,255,255,255,127,255,255,249,219,7,
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,
158255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,
1590,0,0,0,0,
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,
1610,0,0,0,239,255,255,255,150,254,247,10,132,234,150,170,150,247,247,94,255,251,
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,
163255,255,255,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
161255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,63,255,255,255,
162253,255,255,247,255,255,255,247,255,255,223,255,255,255,223,255,255,127,255,
163255,255,127,255,255,255,253,255,255,255,253,255,255,247,207,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,
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,
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,
16715,255,3,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
168255,255,255,255,255,255,255,31,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,
169143,8,255,3,0,0,0,0,0,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 @@
8816,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,
9916,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,
101016,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,
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,
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,
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,
131416,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,
141616,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,
161716,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,70,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
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,
2076,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,
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,
2084,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
212116,0,0,0,0,0,0,0,0,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,
2222255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
2323255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
......@@ -25,16 +25,16 @@
25250,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,
26260,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,
2727255,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,
290,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,240,255,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,32,0,0,192,251,239,62,0,0,
290,0,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,248,255,255,255,255,
3030255,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,
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,
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,
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,
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,
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,
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,
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,
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,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,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,
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,
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,
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,
38380,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,
39390,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,
40400,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 @@
48480,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,
49490,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,
50500,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,
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,
5316,0,0,0,0,0,0,157,193,2,0,0,0,0,48,64,
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,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,
530,16,0,0,0,0,0,0,157,193,2,0,0,0,0,48,64,
54540,0,0,0,0,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,
55550,0,0,0,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,
56560,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 @@
58580,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,
59590,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,
60600,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,
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,
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,
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,
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,
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,
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,
680,0,0,0,0,0,0,0,0,0,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,
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,
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,
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,
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,
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,
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,
760,60,0,0,0,0,0,0,0,0,0,
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,
78255,255,255,255,127,248,255,255,255,255,255,31,32,0,16,0,0,248,254,255,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,
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,
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,
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,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,
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,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,
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,
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,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,60,176,1,0,0,48,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,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,
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,240,12,1,0,0,0,254,7,0,0,0,0,248,121,128,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,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,
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,0,0,0,0,0,0,0,0,0,0,0,0,0,24,
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,
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,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,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,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 @@
8816,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,
9916,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,
101016,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,
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,
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,
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,
131416,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,
141616,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,
161716,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,96,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,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,104,105,16,16,16,16,106,16,107,108,109,17,17,17,110,111,112,113,16,16,16,
2116,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,
1916,16,16,103,104,105,106,16,16,107,108,17,17,109,16,16,16,16,16,16,110,111,16,
2016,16,16,16,112,113,16,16,114,115,116,16,117,118,119,17,17,17,120,121,122,123,
21124,16,16,16,16,
222216,0,0,0,0,0,0,0,0,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,
2323255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
2424255,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 @@
28280,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,
29290,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,
30300,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,
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,
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,
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,
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,
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,
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,
380,0,0,0,0,0,0,0,0,0,0,31,0,0,0,0,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,
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,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,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,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,
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,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,12,0,0,0,0,0,0,0,0,0,0,0,4,0,31,0,0,0,0,0,
39390,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,
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,
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,
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,
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,
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,
460,0,0,0,0,0,0,0,0,0,0,0,0,196,255,255,255,
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,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,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,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,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,14,49,0,0,0,0,0,0,0,
460,0,0,0,0,0,0,0,0,0,0,196,255,255,255,
4747255,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,
48480,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,
5050255,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,
5151127,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,
5252224,0,96,128,248,255,255,255,252,255,255,255,255,255,127,223,255,241,127,255,
......@@ -55,22 +55,23 @@
5555255,255,255,255,255,127,0,0,0,255,7,0,0,255,255,255,255,255,255,255,255,255,
5656255,63,0,0,0,0,0,0,252,255,
5757255,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,
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,
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,
61255,255,255,251,255,255,255,255,255,255,255,255,255,255,15,0,255,255,255,255,
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,0,0,0,0,0,224,135,3,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
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,
610,0,0,0,0,255,255,255,251,255,255,255,255,255,255,255,255,255,255,15,0,255,
6262255,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,
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,
650,0,255,255,255,255,15,0,0,0,255,255,255,127,255,255,255,255,255,255,255,255,
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,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,
65255,255,0,0,0,0,255,255,255,255,15,0,0,0,255,255,255,127,255,255,255,255,255,
6666255,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,
6869255,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,
69700,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,
7071255,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,
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,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,
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,
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,
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,
74750,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,
75760,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,
76770,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 @@
84850,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,
8586128,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,
8687128,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,
88890,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,
89900,0,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,
90910,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,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,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,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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
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,
981410,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#include <ctype.h>
2#include <stddef.h>
31#include <wctype.h>
42
5#define CASEMAP(u1,u2,l) { (u1), (l)-(u1), (u2)-(u1)+1 }
6#define CASELACE(u1,u2) CASEMAP((u1),(u2),(u1)+1)
3static const unsigned char tab[];
74
8static const struct {
9 unsigned short upper;
10 signed char lower;
11 unsigned char len;
12} casemaps[] = {
13 CASEMAP(0xc0,0xde,0xe0),
5static const unsigned char rulebases[512];
6static const int rules[];
147
15 CASELACE(0x0100,0x012e),
16 CASELACE(0x0132,0x0136),
17 CASELACE(0x0139,0x0147),
18 CASELACE(0x014a,0x0176),
19 CASELACE(0x0179,0x017d),
8static const unsigned char exceptions[][2];
209
21 CASELACE(0x370,0x372),
22 CASEMAP(0x391,0x3a1,0x3b1),
23 CASEMAP(0x3a3,0x3ab,0x3c3),
24 CASEMAP(0x400,0x40f,0x450),
25 CASEMAP(0x410,0x42f,0x430),
10#include "casemap.h"
2611
27 CASELACE(0x460,0x480),
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)
12static int casemap(unsigned c, int dir)
25013{
251 int i;
252 int lmul = 2*lower-1;
253 int lmask = lower-1;
254 /* no letters with case in these large ranges */
255 if (!iswalpha(wc)
256 || (unsigned)wc - 0x0600 <= 0x0fff-0x0600
257 || (unsigned)wc - 0x2e00 <= 0xa63f-0x2e00
258 || (unsigned)wc - 0xa800 <= 0xab52-0xa800
259 || (unsigned)wc - 0xabc0 <= 0xfeff-0xabc0)
260 return wc;
261 /* special case because the diff between upper/lower is too big */
262 if (lower && (unsigned)wc - 0x10a0 < 0x2e)
263 if (wc>0x10c5 && wc != 0x10c7 && wc != 0x10cd) return wc;
264 else return wc + 0x2d00 - 0x10a0;
265 if (!lower && (unsigned)wc - 0x2d00 < 0x26)
266 if (wc>0x2d25 && wc != 0x2d27 && wc != 0x2d2d) return wc;
267 else return wc + 0x10a0 - 0x2d00;
268 if (lower && (unsigned)wc - 0x13a0 < 0x50)
269 return wc + 0xab70 - 0x13a0;
270 if (!lower && (unsigned)wc - 0xab70 < 0x50)
271 return wc + 0x13a0 - 0xab70;
272 for (i=0; casemaps[i].len; i++) {
273 int base = casemaps[i].upper + (lmask & casemaps[i].lower);
274 if ((unsigned)wc-base < casemaps[i].len) {
275 if (casemaps[i].lower == 1)
276 return wc + lower - ((wc-casemaps[i].upper)&1);
277 return wc + lmul*casemaps[i].lower;
14 unsigned b, x, y, v, rt, xb, xn;
15 int r, rd, c0 = c;
16
17 if (c >= 0x20000) return c;
18
19 b = c>>8;
20 c &= 255;
21 x = c/3;
22 y = c%3;
23
24 /* lookup entry in two-level base-6 table */
25 v = tab[tab[b]*86+x];
26 static const int mt[] = { 2048, 342, 57 };
27 v = (v*mt[y]>>11)%6;
28
29 /* use the bit vector out of the tables as an index into
30 * a block-specific set of rules and decode the rule into
31 * a type and a case-mapping delta. */
32 r = rules[rulebases[b]+v];
33 rt = r & 255;
34 rd = r >> 8;
35
36 /* rules 0/1 are simple lower/upper case with a delta.
37 * apply according to desired mapping direction. */
38 if (rt < 2) return c0 + (rd & -(rt^dir));
39
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;
27858 }
27959 }
280 for (i=0; pairs[i][1-lower]; i++) {
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;
60 return c0;
29561}
29662
297wint_t towupper(wint_t wc)
63wint_t towlower(wint_t wc)
29864{
299 return (unsigned)wc < 128 ? toupper(wc) : __towcase(wc, 0);
65 return casemap(wc, 0);
30066}
30167
302wint_t towlower(wint_t wc)
68wint_t towupper(wint_t wc)
30369{
304 return (unsigned)wc < 128 ? tolower(wc) : __towcase(wc, 1);
70 return casemap(wc, 1);
30571}
30672
30773wint_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)
2323 return -1;
2424 if (wc-0x20000U < 0x20000)
2525 return 2;
26 if (wc == 0xe0001 || wc-0xe0020U < 0x5f || wc-0xe0100 < 0xef)
26 if (wc == 0xe0001 || wc-0xe0020U < 0x5f || wc-0xe0100U < 0xef)
2727 return 0;
2828 return 1;
2929}
lib/libc/musl/src/ctype/wide.h+14-12
......@@ -17,7 +17,7 @@
171716,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,
181816,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,
191916,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,
212116,0,0,0,0,0,0,0,0,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,
2222255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
2323255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
......@@ -31,10 +31,10 @@
3131255,255,255,15,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
3232255,255,255,255,255,255,255,255,255,255,255,63,0,0,0,255,15,255,255,255,255,
3333255,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,
3535255,255,255,255,255,255,255,127,255,255,255,255,255,7,255,255,255,255,15,0,
3636255,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,
3838255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,
39390,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
4040255,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 @@
4343255,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,
44440,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,
4545255,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,
47255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,31,0,
480,255,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,
500,0,0,255,255,255,255,255,255,255,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,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,255,7,0,255,255,255,127,0,0,0,0,0,
500,7,0,240,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
5151255,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,
535315,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,
54540,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,
5555255,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 @@
5858255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
5959159,255,255,255,255,255,255,255,63,0,120,255,255,255,0,0,4,0,0,96,0,16,0,0,0,
60600,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,
6231,255,255,255,15,0,0,255,255,255,0,0,0,0,0,1,0,255,255,127,0,0,
630,
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,
620,0,0,0,0,0,0,0,0,0,0,0,255,15,0,
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:
4545.global fesetenv
4646.type fesetenv, %function
4747fesetenv:
48 li t2, -1
49 li t1, 0
50 beq a0, t2, 1f
4851 lw t1, 0(a0)
49 fscsr t0, t1
521: fscsr t1
5053 li a0, 0
5154 ret
5255
lib/libc/musl/src/internal/dynlink.h-1
......@@ -96,7 +96,6 @@ struct fdpic_dummy_loadmap {
9696#define DYN_CNT 32
9797
9898typedef void (*stage2_func)(unsigned char *, size_t *);
99typedef void (*stage3_func)(size_t *);
10099
101100hidden void *__dlsym(void *restrict, const char *restrict, void *restrict);
102101
lib/libc/musl/src/internal/floatscan.c+1-4
......@@ -33,9 +33,6 @@
3333
3434#define MASK (KMAX-1)
3535
36#define CONCAT2(x,y) x ## y
37#define CONCAT(x,y) CONCAT2(x,y)
38
3936static long long scanexp(FILE *f, int pok)
4037{
4138 int c;
......@@ -301,7 +298,7 @@ static long double decfloat(FILE *f, int c, int bits, int emin, int sign, int po
301298 y -= bias;
302299
303300 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) {
305302 if (denormal && bits==LDBL_MANT_DIG+e2-emin)
306303 denormal = 0;
307304 y *= 0.5;
lib/libc/musl/src/internal/syscall.h+46
......@@ -193,6 +193,45 @@ hidden long __syscall_ret(unsigned long),
193193#define SYS_sendfile SYS_sendfile64
194194#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
197236/* Ensure that the plain syscall names are defined even for "time64-only"
198237 * archs. These facilitate callers passing null time arguments, and make
......@@ -306,6 +345,13 @@ hidden long __syscall_ret(unsigned long),
306345#define SO_SNDTIMEO_OLD 21
307346#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
309355#ifndef SIOCGSTAMP_OLD
310356#define SIOCGSTAMP_OLD 0x8906
311357#endif
lib/libc/musl/src/internal/version.h+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
88}
99
1010weak_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)
9494 return __syscall_ret(-ENOTSUP);
9595#endif
9696 if (sizeof(time_t) > sizeof(long)) {
97 union {
98 struct timex utx;
99 struct ktimex ktx;
100 } u = { *utx };
101 u.ktx.time_sec = utx->time.tv_sec;
102 u.ktx.time_usec = utx->time.tv_usec;
97 struct ktimex ktx = {
98 .modes = utx->modes,
99 .offset = utx->offset,
100 .freq = utx->freq,
101 .maxerror = utx->maxerror,
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 };
103120#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);
105122 else
106123#endif
107 r = __syscall(SYS_clock_adjtime, clock_id, &u);
124 r = __syscall(SYS_clock_adjtime, clock_id, &ktx);
108125 if (r>=0) {
109 *utx = u.utx;
110 utx->time.tv_sec = u.ktx.time_sec;
111 utx->time.tv_usec = u.ktx.time_usec;
126 utx->modes = ktx.modes;
127 utx->offset = ktx.offset;
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;
112147 }
113148 return __syscall_ret(r);
114149 }
lib/libc/musl/src/linux/wait4.c+32-2
......@@ -1,9 +1,39 @@
11#define _GNU_SOURCE
22#include <sys/wait.h>
33#include <sys/resource.h>
4#include <string.h>
5#include <errno.h>
46#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)
79{
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);
939}
lib/libc/musl/src/math/i386/acos.s+3-13
......@@ -1,22 +1,10 @@
11# 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
153.global acos
164.type acos,@function
175acos:
186 fldl 4(%esp)
191: fld %st(0)
7 fld %st(0)
208 fld1
219 fsub %st(0),%st(1)
2210 fadd %st(2)
......@@ -25,4 +13,6 @@ acos:
2513 fabs # fix sign of zero (matters in downward rounding mode)
2614 fxch %st(1)
2715 fpatan
16 fstpl 4(%esp)
17 fldl 4(%esp)
2818 ret
lib/libc/musl/src/math/i386/acosf.s+16-1
......@@ -1 +1,16 @@
1# see acos.s
1.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# see acos.s
1.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.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
211.global asin
222.type asin,@function
233asin:
......@@ -25,15 +5,17 @@ asin:
255 mov 8(%esp),%eax
266 add %eax,%eax
277 cmp $0x00200000,%eax
28 jae 1f
29 # subnormal x, return x with underflow
30 fsts 4(%esp)
31 ret
321: fld %st(0)
8 jb 1f
9 fld %st(0)
3310 fld1
3411 fsub %st(0),%st(1)
3512 fadd %st(2)
3613 fmulp
3714 fsqrt
3815 fpatan
16 fstpl 4(%esp)
17 fldl 4(%esp)
18 ret
19 # subnormal x, return x with underflow
201: fsts 4(%esp)
3921 ret
lib/libc/musl/src/math/i386/asinf.s+23-1
......@@ -1 +1,23 @@
1# see asin.s
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 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# see asin.s
1.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:
88 jb 1f
99 fld1
1010 fpatan
11 fstpl 4(%esp)
12 fldl 4(%esp)
1113 ret
1214 # subnormal x, return x with underflow
13151: fsts 4(%esp)
lib/libc/musl/src/math/i386/atan2.s+2-1
......@@ -4,7 +4,8 @@ atan2:
44 fldl 4(%esp)
55 fldl 12(%esp)
66 fpatan
7 fstl 4(%esp)
7 fstpl 4(%esp)
8 fldl 4(%esp)
89 mov 8(%esp),%eax
910 add %eax,%eax
1011 cmp $0x00200000,%eax
lib/libc/musl/src/math/i386/atan2f.s+2-1
......@@ -4,7 +4,8 @@ atan2f:
44 flds 4(%esp)
55 flds 8(%esp)
66 fpatan
7 fsts 4(%esp)
7 fstps 4(%esp)
8 flds 4(%esp)
89 mov 4(%esp),%eax
910 add %eax,%eax
1011 cmp $0x01000000,%eax
lib/libc/musl/src/math/i386/atanf.s+2
......@@ -8,6 +8,8 @@ atanf:
88 jb 1f
99 fld1
1010 fpatan
11 fstps 4(%esp)
12 flds 4(%esp)
1113 ret
1214 # subnormal x, return x with underflow
13151: 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# see exp.s
1# 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# see exp.s
1# see exp_ld.s
lib/libc/musl/src/math/i386/log.s+2
......@@ -4,4 +4,6 @@ log:
44 fldln2
55 fldl 4(%esp)
66 fyl2x
7 fstpl 4(%esp)
8 fldl 4(%esp)
79 ret
lib/libc/musl/src/math/i386/log10.s+2
......@@ -4,4 +4,6 @@ log10:
44 fldlg2
55 fldl 4(%esp)
66 fyl2x
7 fstpl 4(%esp)
8 fldl 4(%esp)
79 ret
lib/libc/musl/src/math/i386/log10f.s+2
......@@ -4,4 +4,6 @@ log10f:
44 fldlg2
55 flds 4(%esp)
66 fyl2x
7 fstps 4(%esp)
8 flds 4(%esp)
79 ret
lib/libc/musl/src/math/i386/log1p.s+4
......@@ -10,10 +10,14 @@ log1p:
1010 cmp $0x00100000,%eax
1111 jb 2f
1212 fyl2xp1
13 fstpl 4(%esp)
14 fldl 4(%esp)
1315 ret
14161: fld1
1517 faddp
1618 fyl2x
19 fstpl 4(%esp)
20 fldl 4(%esp)
1721 ret
1822 # subnormal x, return x with underflow
19232: fsts 4(%esp)
lib/libc/musl/src/math/i386/log1pf.s+4
......@@ -10,10 +10,14 @@ log1pf:
1010 cmp $0x00800000,%eax
1111 jb 2f
1212 fyl2xp1
13 fstps 4(%esp)
14 flds 4(%esp)
1315 ret
14161: fld1
1517 faddp
1618 fyl2x
19 fstps 4(%esp)
20 flds 4(%esp)
1721 ret
1822 # subnormal x, return x with underflow
19232: fxch
lib/libc/musl/src/math/i386/log2.s+2
......@@ -4,4 +4,6 @@ log2:
44 fld1
55 fldl 4(%esp)
66 fyl2x
7 fstpl 4(%esp)
8 fldl 4(%esp)
79 ret
lib/libc/musl/src/math/i386/log2f.s+2
......@@ -4,4 +4,6 @@ log2f:
44 fld1
55 flds 4(%esp)
66 fyl2x
7 fstps 4(%esp)
8 flds 4(%esp)
79 ret
lib/libc/musl/src/math/i386/logf.s+2
......@@ -4,4 +4,6 @@ logf:
44 fldln2
55 flds 4(%esp)
66 fyl2x
7 fstps 4(%esp)
8 flds 4(%esp)
79 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 @@
11#include <math.h>
22
3#ifdef _SOFT_FLOAT
3#if defined(_SOFT_FLOAT) || defined(BROKEN_PPC_D_ASM)
44
55#include "../fabs.c"
66
lib/libc/musl/src/math/powerpc/fma.c+1-1
......@@ -1,6 +1,6 @@
11#include <math.h>
22
3#ifdef _SOFT_FLOAT
3#if defined(_SOFT_FLOAT) || defined(BROKEN_PPC_D_ASM)
44
55#include "../fma.c"
66
lib/libc/musl/src/math/x32/lrintl.s+2-2
......@@ -2,6 +2,6 @@
22.type lrintl,@function
33lrintl:
44 fldt 8(%esp)
5 fistpll 8(%esp)
6 mov 8(%esp),%rax
5 fistpl 8(%esp)
6 movl 8(%esp),%eax
77 ret
lib/libc/musl/src/misc/getrusage.c+29-1
......@@ -1,7 +1,35 @@
11#include <sys/resource.h>
2#include <string.h>
3#include <errno.h>
24#include "syscall.h"
35
46int getrusage(int who, struct rusage *ru)
57{
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);
735}
lib/libc/musl/src/misc/ioctl.c+119-17
......@@ -3,8 +3,115 @@
33#include <errno.h>
44#include <time.h>
55#include <sys/time.h>
6#include <stddef.h>
7#include <string.h>
68#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
8115int ioctl(int fd, int req, ...)
9116{
10117 void *arg;
......@@ -13,23 +120,18 @@ int ioctl(int fd, int req, ...)
13120 arg = va_arg(ap, void *);
14121 va_end(ap);
15122 int r = __syscall(SYS_ioctl, fd, req, arg);
16 if (r==-ENOTTY) switch (req) {
17 case SIOCGSTAMP:
18 case SIOCGSTAMPNS:
19 if (SIOCGSTAMP==SIOCGSTAMP_OLD) break;
20 if (req==SIOCGSTAMP) req=SIOCGSTAMP_OLD;
21 if (req==SIOCGSTAMPNS) req=SIOCGSTAMPNS_OLD;
22 long t32[2];
23 r = __syscall(SYS_ioctl, fd, req, t32);
24 if (r<0) break;
25 if (req==SIOCGSTAMP_OLD) {
26 struct timeval *tv = arg;
27 tv->tv_sec = t32[0];
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];
123 if (SIOCGSTAMP != SIOCGSTAMP_OLD && req && r==-ENOTTY) {
124 for (int i=0; i<sizeof compat_map/sizeof *compat_map; i++) {
125 if (compat_map[i].new_req != req) continue;
126 union {
127 long long align;
128 char buf[256];
129 } u;
130 convert_ioctl_struct(&compat_map[i], u.buf, arg, W);
131 r = __syscall(SYS_ioctl, fd, compat_map[i].old_req, u.buf);
132 if (r<0) break;
133 convert_ioctl_struct(&compat_map[i], u.buf, arg, R);
134 break;
33135 }
34136 }
35137 return __syscall_ret(r);
lib/libc/musl/src/misc/pty.c+3-1
......@@ -7,7 +7,9 @@
77
88int posix_openpt(int flags)
99{
10 return open("/dev/ptmx", flags);
10 int r = open("/dev/ptmx", flags);
11 if (r < 0 && errno == ENOSPC) errno = EAGAIN;
12 return r;
1113}
1214
1315int 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
2626 tv->tv_sec = tv32[0];
2727 tv->tv_usec = tv32[1];
2828 *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;
2938 }
3039 }
3140 return __syscall_ret(r);
lib/libc/musl/src/network/recvmmsg.c+10-4
......@@ -8,6 +8,8 @@
88#define IS32BIT(x) !((x)+0x80000000ULL>>32)
99#define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63))
1010
11hidden void __convert_scm_timestamps(struct msghdr *, socklen_t);
12
1113int recvmmsg(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int flags, struct timespec *timeout)
1214{
1315#if LONG_MAX > INT_MAX
......@@ -19,14 +21,18 @@ int recvmmsg(int fd, struct mmsghdr *msgvec, unsigned int vlen, unsigned int fla
1921#ifdef SYS_recvmmsg_time64
2022 time_t s = timeout ? timeout->tv_sec : 0;
2123 long ns = timeout ? timeout->tv_nsec : 0;
22 int r = -ENOSYS;
23 if (SYS_recvmmsg == SYS_recvmmsg_time64 || !IS32BIT(s))
24 r = __syscall_cp(SYS_recvmmsg_time64, fd, msgvec, vlen, flags,
24 int r = __syscall_cp(SYS_recvmmsg_time64, fd, msgvec, vlen, flags,
2525 timeout ? ((long long[]){s, ns}) : 0);
2626 if (SYS_recvmmsg == SYS_recvmmsg_time64 || r!=-ENOSYS)
2727 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,
2932 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);
3036#else
3137 return syscall_cp(SYS_recvmmsg, fd, msgvec, vlen, flags, timeout);
3238#endif
lib/libc/musl/src/network/recvmsg.c+47
......@@ -1,10 +1,56 @@
11#include <sys/socket.h>
22#include <limits.h>
3#include <time.h>
4#include <sys/time.h>
5#include <string.h>
36#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
550ssize_t recvmsg(int fd, struct msghdr *msg, int flags)
651{
752 ssize_t r;
53 socklen_t orig_controllen = msg->msg_controllen;
854#if LONG_MAX > INT_MAX
955 struct msghdr h, *orig = msg;
1056 if (msg) {
......@@ -14,6 +60,7 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags)
1460 }
1561#endif
1662 r = socketcall_cp(recvmsg, fd, msg, flags, 0, 0, 0);
63 if (r >= 0) __convert_scm_timestamps(msg, orig_controllen);
1764#if LONG_MAX > INT_MAX
1865 if (orig) *orig = h;
1966#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
3131
3232 r = __socketcall(setsockopt, fd, level, optname,
3333 ((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;
3443 }
3544 }
3645 return __syscall_ret(r);
lib/libc/musl/src/signal/arm/sigsetjmp.s+3-2
......@@ -6,9 +6,10 @@
66sigsetjmp:
77__sigsetjmp:
88 tst r1,r1
9 beq setjmp
9 bne 1f
10 b setjmp
1011
11 str lr,[r0,#256]
121: str lr,[r0,#256]
1213 str r4,[r0,#260+8]
1314 mov r4,r0
1415
lib/libc/musl/src/stat/__xstat.c+4
......@@ -1,5 +1,7 @@
11#include <sys/stat.h>
22
3#if !_REDIR_TIME64
4
35int __fxstat(int ver, int fd, struct stat *buf)
46{
57 return fstat(fd, buf);
......@@ -25,6 +27,8 @@ weak_alias(__fxstatat, __fxstatat64);
2527weak_alias(__lxstat, __lxstat64);
2628weak_alias(__xstat, __xstat64);
2729
30#endif
31
2832int __xmknod(int ver, const char *path, mode_t mode, dev_t *dev)
2933{
3034 return mknod(path, mode, *dev);
lib/libc/musl/src/stat/fchmodat.c+2-1
......@@ -2,6 +2,7 @@
22#include <fcntl.h>
33#include <errno.h>
44#include "syscall.h"
5#include "kstat.h"
56
67int fchmodat(int fd, const char *path, mode_t mode, int flag)
78{
......@@ -10,7 +11,7 @@ int fchmodat(int fd, const char *path, mode_t mode, int flag)
1011 if (flag != AT_SYMLINK_NOFOLLOW)
1112 return __syscall_ret(-EINVAL);
1213
13 struct stat st;
14 struct kstat st;
1415 int ret, fd2;
1516 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)
1010 return fstatat(fd, "", st, AT_EMPTY_PATH);
1111}
1212
13#if !_REDIR_TIME64
1314weak_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
5757 .st_mtim.tv_nsec = stx.stx_mtime.tv_nsec,
5858 .st_ctim.tv_sec = stx.stx_ctime.tv_sec,
5959 .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
6068 };
6169 return 0;
6270}
......@@ -110,6 +118,14 @@ static int fstatat_kstat(int fd, const char *restrict path, struct stat *restric
110118 .st_mtim.tv_nsec = kst.st_mtime_nsec,
111119 .st_ctim.tv_sec = kst.st_ctime_sec,
112120 .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
113129 };
114130
115131 return 0;
......@@ -126,4 +142,6 @@ int fstatat(int fd, const char *restrict path, struct stat *restrict st, int fla
126142 return __syscall_ret(ret);
127143}
128144
145#if !_REDIR_TIME64
129146weak_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)
66 return fstatat(AT_FDCWD, path, buf, AT_SYMLINK_NOFOLLOW);
77}
88
9#if !_REDIR_TIME64
910weak_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)
66 return fstatat(AT_FDCWD, path, buf, 0);
77}
88
9#if !_REDIR_TIME64
910weak_alias(stat, stat64);
11#endif
lib/libc/musl/src/stdio/tempnam.c+3-2
......@@ -6,6 +6,7 @@
66#include <string.h>
77#include <stdlib.h>
88#include "syscall.h"
9#include "kstat.h"
910
1011#define MAXTRIES 100
1112
......@@ -37,10 +38,10 @@ char *tempnam(const char *dir, const char *pfx)
3738 for (try=0; try<MAXTRIES; try++) {
3839 __randname(s+l-6);
3940#ifdef SYS_lstat
40 r = __syscall(SYS_lstat, s, &(struct stat){0});
41 r = __syscall(SYS_lstat, s, &(struct kstat){0});
4142#else
4243 r = __syscall(SYS_fstatat, AT_FDCWD, s,
43 &(struct stat){0}, AT_SYMLINK_NOFOLLOW);
44 &(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
4445#endif
4546 if (r == -ENOENT) return strdup(s);
4647 }
lib/libc/musl/src/stdio/tmpnam.c+3-2
......@@ -5,6 +5,7 @@
55#include <string.h>
66#include <stdlib.h>
77#include "syscall.h"
8#include "kstat.h"
89
910#define MAXTRIES 100
1011
......@@ -17,10 +18,10 @@ char *tmpnam(char *buf)
1718 for (try=0; try<MAXTRIES; try++) {
1819 __randname(s+12);
1920#ifdef SYS_lstat
20 r = __syscall(SYS_lstat, s, &(struct stat){0});
21 r = __syscall(SYS_lstat, s, &(struct kstat){0});
2122#else
2223 r = __syscall(SYS_fstatat, AT_FDCWD, s,
23 &(struct stat){0}, AT_SYMLINK_NOFOLLOW);
24 &(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
2425#endif
2526 if (r == -ENOENT) return strcpy(buf ? buf : internal, s);
2627 }
lib/libc/musl/src/stdio/ungetc.c+1-1
......@@ -16,5 +16,5 @@ int ungetc(int c, FILE *f)
1616 f->flags &= ~F_EOF;
1717
1818 FUNLOCK(f);
19 return c;
19 return (unsigned char)c;
2020}
lib/libc/musl/src/string/arm/memcpy.c+1-1
......@@ -1,3 +1,3 @@
1#if __ARMEB__ || __thumb__
1#if __ARMEB__
22#include "../memcpy.c"
33#endif
lib/libc/musl/src/string/arm/memcpy_le.S+8-5
......@@ -1,4 +1,4 @@
1#if !__ARMEB__ && !__thumb__
1#if !__ARMEB__
22
33/*
44 * Copyright (C) 2008 The Android Open Source Project
......@@ -40,8 +40,9 @@
4040 * This file has been modified from the original for use in musl libc.
4141 * The main changes are: addition of .type memcpy,%function to make the
4242 * code safely callable from thumb mode, adjusting the return
43 * instructions to be compatible with pre-thumb ARM cpus, and removal
44 * of prefetch code that is not compatible with older cpus.
43 * instructions to be compatible with pre-thumb ARM cpus, removal of
44 * prefetch code that is not compatible with older cpus and support for
45 * building as thumb 2.
4546 */
4647
4748.syntax unified
......@@ -241,7 +242,8 @@ non_congruent:
241242 beq 2f
242243 ldr r5, [r1], #4
243244 sub r2, r2, #4
244 orr r4, r3, r5, lsl lr
245 mov r4, r5, lsl lr
246 orr r4, r4, r3
245247 mov r3, r5, lsr r12
246248 str r4, [r0], #4
247249 cmp r2, #4
......@@ -348,7 +350,8 @@ less_than_thirtytwo:
348350
3493511: ldr r5, [r1], #4
350352 sub r2, r2, #4
351 orr r4, r3, r5, lsl lr
353 mov r4, r5, lsl lr
354 orr r4, r4, r3
352355 mov r3, r5, lsr r12
353356 str r4, [r0], #4
354357 cmp r2, #4
lib/libc/musl/src/time/__map_file.c+2-1
......@@ -2,10 +2,11 @@
22#include <fcntl.h>
33#include <sys/stat.h>
44#include "syscall.h"
5#include "kstat.h"
56
67const char unsigned *__map_file(const char *pathname, size_t *size)
78{
8 struct stat st;
9 struct kstat st;
910 const unsigned char *map = MAP_FAILED;
1011 int fd = sys_open(pathname, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
1112 if (fd < 0) return 0;
lib/std/atomic/int.zig+5-8
......@@ -1,6 +1,3 @@
1const builtin = @import("builtin");
2const AtomicOrder = builtin.AtomicOrder;
3
41/// Thread-safe, lock-free integer
52pub fn Int(comptime T: type) type {
63 return struct {
......@@ -14,16 +11,16 @@ pub fn Int(comptime T: type) type {
1411
1512 /// Returns previous value
1613 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);
1815 }
1916
2017 /// Returns previous value
2118 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);
2320 }
2421
2522 pub fn get(self: *Self) T {
26 return @atomicLoad(T, &self.unprotected_value, AtomicOrder.SeqCst);
23 return @atomicLoad(T, &self.unprotected_value, .SeqCst);
2724 }
2825
2926 pub fn set(self: *Self, new_value: T) void {
......@@ -31,11 +28,11 @@ pub fn Int(comptime T: type) type {
3128 }
3229
3330 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);
3532 }
3633
3734 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);
3936 }
4037 };
4138}
lib/std/atomic/queue.zig+23-30
......@@ -1,7 +1,5 @@
11const std = @import("../std.zig");
22const builtin = @import("builtin");
3const AtomicOrder = builtin.AtomicOrder;
4const AtomicRmwOp = builtin.AtomicRmwOp;
53const assert = std.debug.assert;
64const expect = std.testing.expect;
75
......@@ -104,21 +102,17 @@ pub fn Queue(comptime T: type) type {
104102 }
105103
106104 pub fn dump(self: *Self) void {
107 var stderr_file = std.io.getStdErr() 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;
105 self.dumpToStream(std.io.getStdErr().outStream()) catch return;
112106 }
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 {
115109 const S = struct {
116110 fn dumpRecursive(
117 s: *std.io.OutStream(Error),
111 s: var,
118112 optional_node: ?*Node,
119113 indent: usize,
120114 comptime depth: comptime_int,
121 ) Error!void {
115 ) !void {
122116 try s.writeByteNTimes(' ', indent);
123117 if (optional_node) |node| {
124118 try s.print("0x{x}={}\n", .{ @ptrToInt(node), node.data });
......@@ -149,7 +143,7 @@ const Context = struct {
149143 put_sum: isize,
150144 get_sum: isize,
151145 get_count: usize,
152 puts_done: u8, // TODO make this a bool
146 puts_done: bool,
153147};
154148
155149// TODO add lazy evaluated build options and then put puts_per_thread behind
......@@ -173,7 +167,7 @@ test "std.atomic.Queue" {
173167 .queue = &queue,
174168 .put_sum = 0,
175169 .get_sum = 0,
176 .puts_done = 0,
170 .puts_done = false,
177171 .get_count = 0,
178172 };
179173
......@@ -186,7 +180,7 @@ test "std.atomic.Queue" {
186180 }
187181 }
188182 expect(!context.queue.isEmpty());
189 context.puts_done = 1;
183 context.puts_done = true;
190184 {
191185 var i: usize = 0;
192186 while (i < put_thread_count) : (i += 1) {
......@@ -208,7 +202,7 @@ test "std.atomic.Queue" {
208202
209203 for (putters) |t|
210204 t.wait();
211 @atomicStore(u8, &context.puts_done, 1, AtomicOrder.SeqCst);
205 @atomicStore(bool, &context.puts_done, true, .SeqCst);
212206 for (getters) |t|
213207 t.wait();
214208
......@@ -235,25 +229,25 @@ fn startPuts(ctx: *Context) u8 {
235229 std.time.sleep(1); // let the os scheduler be our fuzz
236230 const x = @bitCast(i32, r.random.scalar(u32));
237231 const node = ctx.allocator.create(Queue(i32).Node) catch unreachable;
238 node.* = Queue(i32).Node{
232 node.* = .{
239233 .prev = undefined,
240234 .next = undefined,
241235 .data = x,
242236 };
243237 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);
245239 }
246240 return 0;
247241}
248242
249243fn startGets(ctx: *Context) u8 {
250244 while (true) {
251 const last = @atomicLoad(u8, &ctx.puts_done, builtin.AtomicOrder.SeqCst) == 1;
245 const last = @atomicLoad(bool, &ctx.puts_done, .SeqCst);
252246
253247 while (ctx.queue.get()) |node| {
254248 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);
256 _ = @atomicRmw(usize, &ctx.get_count, builtin.AtomicRmwOp.Add, 1, builtin.AtomicOrder.SeqCst);
249 _ = @atomicRmw(isize, &ctx.get_sum, .Add, node.data, .SeqCst);
250 _ = @atomicRmw(usize, &ctx.get_count, .Add, 1, .SeqCst);
257251 }
258252
259253 if (last) return 0;
......@@ -326,17 +320,16 @@ test "std.atomic.Queue single-threaded" {
326320
327321test "std.atomic.Queue dump" {
328322 const mem = std.mem;
329 const SliceOutStream = std.io.SliceOutStream;
330323 var buffer: [1024]u8 = undefined;
331324 var expected_buffer: [1024]u8 = undefined;
332 var sos = SliceOutStream.init(buffer[0..]);
325 var fbs = std.io.fixedBufferStream(&buffer);
333326
334327 var queue = Queue(i32).init();
335328
336329 // Test empty stream
337 sos.reset();
338 try queue.dumpToStream(SliceOutStream.Error, &sos.stream);
339 expect(mem.eql(u8, buffer[0..sos.pos],
330 fbs.reset();
331 try queue.dumpToStream(fbs.outStream());
332 expect(mem.eql(u8, buffer[0..fbs.pos],
340333 \\head: (null)
341334 \\tail: (null)
342335 \\
......@@ -350,8 +343,8 @@ test "std.atomic.Queue dump" {
350343 };
351344 queue.put(&node_0);
352345
353 sos.reset();
354 try queue.dumpToStream(SliceOutStream.Error, &sos.stream);
346 fbs.reset();
347 try queue.dumpToStream(fbs.outStream());
355348
356349 var expected = try std.fmt.bufPrint(expected_buffer[0..],
357350 \\head: 0x{x}=1
......@@ -360,7 +353,7 @@ test "std.atomic.Queue dump" {
360353 \\ (null)
361354 \\
362355 , .{ @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
365358 // Test a stream with two elements
366359 var node_1 = Queue(i32).Node{
......@@ -370,8 +363,8 @@ test "std.atomic.Queue dump" {
370363 };
371364 queue.put(&node_1);
372365
373 sos.reset();
374 try queue.dumpToStream(SliceOutStream.Error, &sos.stream);
366 fbs.reset();
367 try queue.dumpToStream(fbs.outStream());
375368
376369 expected = try std.fmt.bufPrint(expected_buffer[0..],
377370 \\head: 0x{x}=1
......@@ -381,5 +374,5 @@ test "std.atomic.Queue dump" {
381374 \\ (null)
382375 \\
383376 , .{ @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));
385378}
lib/std/atomic/stack.zig+15-16
......@@ -1,6 +1,5 @@
11const assert = std.debug.assert;
22const builtin = @import("builtin");
3const AtomicOrder = builtin.AtomicOrder;
43const expect = std.testing.expect;
54
65/// Many reader, many writer, non-allocating, thread-safe
......@@ -11,7 +10,7 @@ pub fn Stack(comptime T: type) type {
1110 root: ?*Node,
1211 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
1615 pub const Self = @This();
1716
......@@ -31,7 +30,7 @@ pub fn Stack(comptime T: type) type {
3130 /// being the first item in the stack, returns the other item that was there.
3231 pub fn pushFirst(self: *Self, node: *Node) ?*Node {
3332 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);
3534 }
3635
3736 pub fn push(self: *Self, node: *Node) void {
......@@ -39,8 +38,8 @@ pub fn Stack(comptime T: type) type {
3938 node.next = self.root;
4039 self.root = node;
4140 } else {
42 while (@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) != 0) {}
43 defer assert(@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 1);
41 while (@atomicRmw(bool, &self.lock, .Xchg, true, .SeqCst)) {}
42 defer assert(@atomicRmw(bool, &self.lock, .Xchg, false, .SeqCst));
4443
4544 node.next = self.root;
4645 self.root = node;
......@@ -53,8 +52,8 @@ pub fn Stack(comptime T: type) type {
5352 self.root = root.next;
5453 return root;
5554 } else {
56 while (@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst) != 0) {}
57 defer assert(@atomicRmw(u8, &self.lock, builtin.AtomicRmwOp.Xchg, 0, AtomicOrder.SeqCst) == 1);
55 while (@atomicRmw(bool, &self.lock, .Xchg, true, .SeqCst)) {}
56 defer assert(@atomicRmw(bool, &self.lock, .Xchg, false, .SeqCst));
5857
5958 const root = self.root orelse return null;
6059 self.root = root.next;
......@@ -63,7 +62,7 @@ pub fn Stack(comptime T: type) type {
6362 }
6463
6564 pub fn isEmpty(self: *Self) bool {
66 return @atomicLoad(?*Node, &self.root, AtomicOrder.SeqCst) == null;
65 return @atomicLoad(?*Node, &self.root, .SeqCst) == null;
6766 }
6867 };
6968}
......@@ -75,7 +74,7 @@ const Context = struct {
7574 put_sum: isize,
7675 get_sum: isize,
7776 get_count: usize,
78 puts_done: u8, // TODO make this a bool
77 puts_done: bool,
7978};
8079// TODO add lazy evaluated build options and then put puts_per_thread behind
8180// some option such as: "AggressiveMultithreadedFuzzTest". In the AppVeyor
......@@ -98,7 +97,7 @@ test "std.atomic.stack" {
9897 .stack = &stack,
9998 .put_sum = 0,
10099 .get_sum = 0,
101 .puts_done = 0,
100 .puts_done = false,
102101 .get_count = 0,
103102 };
104103
......@@ -109,7 +108,7 @@ test "std.atomic.stack" {
109108 expect(startPuts(&context) == 0);
110109 }
111110 }
112 context.puts_done = 1;
111 context.puts_done = true;
113112 {
114113 var i: usize = 0;
115114 while (i < put_thread_count) : (i += 1) {
......@@ -128,7 +127,7 @@ test "std.atomic.stack" {
128127
129128 for (putters) |t|
130129 t.wait();
131 @atomicStore(u8, &context.puts_done, 1, AtomicOrder.SeqCst);
130 @atomicStore(bool, &context.puts_done, true, .SeqCst);
132131 for (getters) |t|
133132 t.wait();
134133 }
......@@ -158,19 +157,19 @@ fn startPuts(ctx: *Context) u8 {
158157 .data = x,
159158 };
160159 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);
162161 }
163162 return 0;
164163}
165164
166165fn startGets(ctx: *Context) u8 {
167166 while (true) {
168 const last = @atomicLoad(u8, &ctx.puts_done, builtin.AtomicOrder.SeqCst) == 1;
167 const last = @atomicLoad(bool, &ctx.puts_done, .SeqCst);
169168
170169 while (ctx.stack.pop()) |node| {
171170 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);
173 _ = @atomicRmw(usize, &ctx.get_count, builtin.AtomicRmwOp.Add, 1, builtin.AtomicOrder.SeqCst);
171 _ = @atomicRmw(isize, &ctx.get_sum, .Add, node.data, .SeqCst);
172 _ = @atomicRmw(usize, &ctx.get_count, .Add, 1, .SeqCst);
174173 }
175174
176175 if (last) return 0;
lib/std/buffer.zig+25-10
......@@ -65,13 +65,9 @@ pub const Buffer = struct {
6565 }
6666
6767 pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer {
68 const countSize = struct {
69 fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
70 size.* += bytes.len;
71 }
72 }.countSize;
73 var size: usize = 0;
74 std.fmt.format(&size, error{}, countSize, format, args) catch |err| switch (err) {};
68 const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) {
69 error.Overflow => return error.OutOfMemory,
70 };
7571 var self = try Buffer.initSize(allocator, size);
7672 assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size);
7773 return self;
......@@ -154,8 +150,15 @@ pub const Buffer = struct {
154150 mem.copy(u8, self.list.toSlice(), m);
155151 }
156152
157 pub fn print(self: *Buffer, comptime fmt: []const u8, args: var) !void {
158 return std.fmt.format(self, error{OutOfMemory}, Buffer.append, fmt, args);
153 pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) {
154 return .{ .context = self };
155 }
156
157 /// Same as `append` except it returns the number of bytes written, which is always the same
158 /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
159 pub fn appendWrite(self: *Buffer, m: []const u8) !usize {
160 try self.append(m);
161 return m.len;
159162 }
160163};
161164
......@@ -205,6 +208,18 @@ test "Buffer.print" {
205208 var buf = try Buffer.init(testing.allocator, "");
206209 defer buf.deinit();
207210
208 try buf.print("Hello {} the {}", .{ 2, "world" });
211 try buf.outStream().print("Hello {} the {}", .{ 2, "world" });
209212 testing.expect(buf.eql("Hello 2 the world"));
210213}
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 {
926926
927927 try child.spawn();
928928
929 var stdout_file_in_stream = child.stdout.?.inStream();
930 const stdout = try stdout_file_in_stream.stream.readAllAlloc(self.allocator, max_output_size);
929 const stdout = try child.stdout.?.inStream().readAllAlloc(self.allocator, max_output_size);
931930 errdefer self.allocator.free(stdout);
932931
933932 const term = try child.wait();
lib/std/build/emit_raw.zig+36-74
......@@ -14,11 +14,6 @@ const io = std.io;
1414const sort = std.sort;
1515const 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
2217const BinaryElfSection = struct {
2318 elfOffset: u64,
2419 binaryOffset: u64,
......@@ -41,22 +36,19 @@ const BinaryElfOutput = struct {
4136
4237 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
5139 pub fn deinit(self: *Self) void {
5240 self.sections.deinit();
5341 self.segments.deinit();
5442 }
5543
56 pub fn parseElf(self: *Self, elfFile: elf.Elf) !void {
57 const allocator = self.segments.allocator;
44 pub fn parse(allocator: *Allocator, elf_file: File) !Self {
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| {
6052 if (sectionValidForOutput(section)) {
6153 const newSection = try allocator.create(BinaryElfSection);
6254
......@@ -69,19 +61,19 @@ const BinaryElfOutput = struct {
6961 }
7062 }
7163
72 for (elfFile.program_headers) |programHeader, i| {
73 if (programHeader.p_type == elf.PT_LOAD) {
64 for (elf_hdrs.program_headers) |phdr, i| {
65 if (phdr.p_type == elf.PT_LOAD) {
7466 const newSegment = try allocator.create(BinaryElfSegment);
7567
76 newSegment.physicalAddress = if (programHeader.p_paddr != 0) programHeader.p_paddr else programHeader.p_vaddr;
77 newSegment.virtualAddress = programHeader.p_vaddr;
78 newSegment.fileSize = @intCast(usize, programHeader.p_filesz);
79 newSegment.elfOffset = programHeader.p_offset;
68 newSegment.physicalAddress = if (phdr.p_paddr != 0) phdr.p_paddr else phdr.p_vaddr;
69 newSegment.virtualAddress = phdr.p_vaddr;
70 newSegment.fileSize = @intCast(usize, phdr.p_filesz);
71 newSegment.elfOffset = phdr.p_offset;
8072 newSegment.binaryOffset = 0;
8173 newSegment.firstSection = null;
8274
8375 for (self.sections.toSlice()) |section| {
84 if (sectionWithinSegment(section, programHeader)) {
76 if (sectionWithinSegment(section, phdr)) {
8577 if (section.segment) |sectionSegment| {
8678 if (sectionSegment.elfOffset > newSegment.elfOffset) {
8779 section.segment = newSegment;
......@@ -126,14 +118,17 @@ const BinaryElfOutput = struct {
126118 }
127119
128120 sort.sort(*BinaryElfSection, self.sections.toSlice(), sectionSortCompare);
121
122 return self;
129123 }
130124
131 fn sectionWithinSegment(section: *BinaryElfSection, segment: elf.ProgramHeader) bool {
125 fn sectionWithinSegment(section: *BinaryElfSection, segment: elf.Elf64_Phdr) bool {
132126 return segment.p_offset <= section.elfOffset and (segment.p_offset + segment.p_filesz) >= (section.elfOffset + section.fileSize);
133127 }
134128
135 fn sectionValidForOutput(section: elf.SectionHeader) bool {
136 return section.sh_size > 0 and section.sh_type != elf.SHT_NOBITS and ((section.sh_flags & elf.SHF_ALLOC) == elf.SHF_ALLOC);
129 fn sectionValidForOutput(shdr: var) bool {
130 return shdr.sh_size > 0 and shdr.sh_type != elf.SHT_NOBITS and
131 ((shdr.sh_flags & elf.SHF_ALLOC) == elf.SHF_ALLOC);
137132 }
138133
139134 fn segmentSortCompare(left: *BinaryElfSegment, right: *BinaryElfSegment) bool {
......@@ -151,60 +146,27 @@ const BinaryElfOutput = struct {
151146 }
152147};
153148
154const WriteContext = struct {
155 inStream: *ElfInStream,
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);
149fn writeBinaryElfSection(elf_file: File, out_file: File, section: *BinaryElfSection) !void {
150 try out_file.seekTo(section.binaryOffset);
167151
168 try context.outSeekStream.seekTo(section.binaryOffset);
169 try context.outStream.write(readBuffer);
152 try out_file.writeFileAll(elf_file, .{
153 .in_offset = section.elfOffset,
154 .in_len = section.fileSize,
155 });
170156}
171157
172fn emit_raw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !void {
173 var arenaAlloc = ArenaAllocator.init(allocator);
174 errdefer arenaAlloc.deinit();
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 };
158fn emitRaw(allocator: *Allocator, elf_path: []const u8, raw_path: []const u8) !void {
159 var elf_file = try fs.cwd().openFile(elf_path, .{});
160 defer elf_file.close();
200161
201 var binaryElfOutput = BinaryElfOutput.init(arena_allocator);
202 defer binaryElfOutput.deinit();
162 var out_file = try fs.cwd().createFile(raw_path, .{});
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| {
207 try writeBinaryElfSection(allocator, writeContext, section);
168 for (binary_elf_output.sections.toSlice()) |section| {
169 try writeBinaryElfSection(elf_file, out_file, section);
208170 }
209171}
210172
......@@ -250,6 +212,6 @@ pub const InstallRawStep = struct {
250212 const full_dest_path = builder.getInstallPath(self.dest_dir, self.dest_filename);
251213
252214 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);
254216 }
255217};
lib/std/build/run.zig+2-4
......@@ -175,8 +175,7 @@ pub const RunStep = struct {
175175
176176 switch (self.stdout_action) {
177177 .expect_exact, .expect_matches => {
178 var stdout_file_in_stream = child.stdout.?.inStream();
179 stdout = stdout_file_in_stream.stream.readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
178 stdout = child.stdout.?.inStream().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
180179 },
181180 .inherit, .ignore => {},
182181 }
......@@ -186,8 +185,7 @@ pub const RunStep = struct {
186185
187186 switch (self.stderr_action) {
188187 .expect_exact, .expect_matches => {
189 var stderr_file_in_stream = child.stderr.?.inStream();
190 stderr = stderr_file_in_stream.stream.readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
188 stderr = child.stderr.?.inStream().readAllAlloc(self.builder.allocator, max_stdout_size) catch unreachable;
191189 },
192190 .inherit, .ignore => {},
193191 }
lib/std/builtin.zig+5-7
......@@ -436,19 +436,17 @@ pub const Version = struct {
436436 self: Version,
437437 comptime fmt: []const u8,
438438 options: std.fmt.FormatOptions,
439 context: var,
440 comptime Error: type,
441 comptime output: fn (@TypeOf(context), []const u8) Error!void,
442 ) Error!void {
439 out_stream: var,
440 ) !void {
443441 if (fmt.len == 0) {
444442 if (self.patch == 0) {
445443 if (self.minor == 0) {
446 return std.fmt.format(context, Error, output, "{}", .{self.major});
444 return std.fmt.format(out_stream, "{}", .{self.major});
447445 } else {
448 return std.fmt.format(context, Error, output, "{}.{}", .{ self.major, self.minor });
446 return std.fmt.format(out_stream, "{}.{}", .{ self.major, self.minor });
449447 }
450448 } 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 });
452450 }
453451 } else {
454452 @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
7979pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t;
8080pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int;
8181pub 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;
8283pub extern "c" fn raise(sig: c_int) c_int;
8384pub extern "c" fn read(fd: fd_t, buf: [*]u8, nbyte: usize) isize;
8485pub 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;
8282
8383pub 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
8587pub extern "c" fn sendfile(
8688 out_fd: fd_t,
8789 in_fd: fd_t,
lib/std/child_process.zig+7-9
......@@ -217,13 +217,13 @@ pub const ChildProcess = struct {
217217
218218 try child.spawn();
219219
220 var stdout_file_in_stream = child.stdout.?.inStream();
221 var stderr_file_in_stream = child.stderr.?.inStream();
220 const stdout_in = child.stdout.?.inStream();
221 const stderr_in = child.stderr.?.inStream();
222222
223223 // 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);
225225 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);
227227 errdefer args.allocator.free(stderr);
228228
229229 return ExecResult{
......@@ -780,7 +780,7 @@ fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8)
780780 var buf = try Buffer.initSize(allocator, 0);
781781 defer buf.deinit();
782782
783 var buf_stream = &io.BufferOutStream.init(&buf).stream;
783 var buf_stream = buf.outStream();
784784
785785 for (argv) |arg, arg_i| {
786786 if (arg_i != 0) try buf.appendByte(' ');
......@@ -857,8 +857,7 @@ fn writeIntFd(fd: i32, value: ErrInt) !void {
857857 .io_mode = .blocking,
858858 .async_block_allowed = File.async_block_allowed_yes,
859859 };
860 const stream = &file.outStream().stream;
861 stream.writeIntNative(u64, @intCast(u64, value)) catch return error.SystemResources;
860 file.outStream().writeIntNative(u64, @intCast(u64, value)) catch return error.SystemResources;
862861}
863862
864863fn readIntFd(fd: i32) !ErrInt {
......@@ -867,8 +866,7 @@ fn readIntFd(fd: i32) !ErrInt {
867866 .io_mode = .blocking,
868867 .async_block_allowed = File.async_block_allowed_yes,
869868 };
870 const stream = &file.inStream().stream;
871 return @intCast(ErrInt, stream.readIntNative(u64) catch return error.SystemResources);
869 return @intCast(ErrInt, file.inStream().readIntNative(u64) catch return error.SystemResources);
872870}
873871
874872/// Caller must free result.
lib/std/coff.zig+6-9
......@@ -56,8 +56,7 @@ pub const Coff = struct {
5656 pub fn loadHeader(self: *Coff) !void {
5757 const pe_pointer_offset = 0x3C;
5858
59 var file_stream = self.in_file.inStream();
60 const in = &file_stream.stream;
59 const in = self.in_file.inStream();
6160
6261 var magic: [2]u8 = undefined;
6362 try in.readNoEof(magic[0..]);
......@@ -89,11 +88,11 @@ pub const Coff = struct {
8988 else => return error.InvalidMachine,
9089 }
9190
92 try self.loadOptionalHeader(&file_stream);
91 try self.loadOptionalHeader();
9392 }
9493
95 fn loadOptionalHeader(self: *Coff, file_stream: *File.InStream) !void {
96 const in = &file_stream.stream;
94 fn loadOptionalHeader(self: *Coff) !void {
95 const in = self.in_file.inStream();
9796 self.pe_header.magic = try in.readIntLittle(u16);
9897 // For now we're only interested in finding the reference to the .pdb,
9998 // so we'll skip most of this header, which size is different in 32
......@@ -136,8 +135,7 @@ pub const Coff = struct {
136135 const debug_dir = &self.pe_header.data_directory[DEBUG_DIRECTORY];
137136 const file_offset = debug_dir.virtual_address - header.virtual_address + header.pointer_to_raw_data;
138137
139 var file_stream = self.in_file.inStream();
140 const in = &file_stream.stream;
138 const in = self.in_file.inStream();
141139 try self.in_file.seekTo(file_offset);
142140
143141 // Find the correct DebugDirectoryEntry, and where its data is stored.
......@@ -188,8 +186,7 @@ pub const Coff = struct {
188186
189187 try self.sections.ensureCapacity(self.coff_header.number_of_sections);
190188
191 var file_stream = self.in_file.inStream();
192 const in = &file_stream.stream;
189 const in = self.in_file.inStream();
193190
194191 var name: [8]u8 = undefined;
195192
lib/std/debug.zig+156-124
......@@ -55,7 +55,7 @@ pub const LineInfo = struct {
5555var stderr_file: File = undefined;
5656var stderr_file_out_stream: File.OutStream = undefined;
5757
58var stderr_stream: ?*io.OutStream(File.WriteError) = null;
58var stderr_stream: ?*File.OutStream = null;
5959var stderr_mutex = std.Mutex.init();
6060
6161pub fn warn(comptime fmt: []const u8, args: var) void {
......@@ -65,13 +65,13 @@ pub fn warn(comptime fmt: []const u8, args: var) void {
6565 noasync stderr.print(fmt, args) catch return;
6666}
6767
68pub fn getStderrStream() *io.OutStream(File.WriteError) {
68pub fn getStderrStream() *File.OutStream {
6969 if (stderr_stream) |st| {
7070 return st;
7171 } else {
7272 stderr_file = io.getStdErr();
7373 stderr_file_out_stream = stderr_file.outStream();
74 const st = &stderr_file_out_stream.stream;
74 const st = &stderr_file_out_stream;
7575 stderr_stream = st;
7676 return st;
7777 }
......@@ -408,15 +408,15 @@ pub const TTY = struct {
408408 windows_api,
409409
410410 fn setColor(conf: Config, out_stream: var, color: Color) void {
411 switch (conf) {
411 noasync switch (conf) {
412412 .no_color => return,
413413 .escape_codes => switch (color) {
414 .Red => noasync out_stream.write(RED) catch return,
415 .Green => noasync out_stream.write(GREEN) catch return,
416 .Cyan => noasync out_stream.write(CYAN) catch return,
417 .White, .Bold => noasync out_stream.write(WHITE) catch return,
418 .Dim => noasync out_stream.write(DIM) catch return,
419 .Reset => noasync out_stream.write(RESET) catch return,
414 .Red => out_stream.writeAll(RED) catch return,
415 .Green => out_stream.writeAll(GREEN) catch return,
416 .Cyan => out_stream.writeAll(CYAN) catch return,
417 .White, .Bold => out_stream.writeAll(WHITE) catch return,
418 .Dim => out_stream.writeAll(DIM) catch return,
419 .Reset => out_stream.writeAll(RESET) catch return,
420420 },
421421 .windows_api => if (builtin.os.tag == .windows) {
422422 const S = struct {
......@@ -455,7 +455,7 @@ pub const TTY = struct {
455455 } else {
456456 unreachable;
457457 },
458 }
458 };
459459 }
460460 };
461461};
......@@ -475,15 +475,15 @@ fn populateModule(di: *ModuleDebugInfo, mod: *Module) !void {
475475
476476 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);
479479 if (signature != 4)
480480 return error.InvalidDebugInfo;
481481
482482 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
485485 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
488488 var sect_offset: usize = 0;
489489 var skip_len: usize = undefined;
......@@ -565,38 +565,40 @@ fn printLineInfo(
565565 tty_config: TTY.Config,
566566 comptime printLineFromFile: var,
567567) !void {
568 tty_config.setColor(out_stream, .White);
568 noasync {
569 tty_config.setColor(out_stream, .White);
569570
570 if (line_info) |*li| {
571 try noasync out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column });
572 } else {
573 try noasync out_stream.write("???:?:?");
574 }
571 if (line_info) |*li| {
572 try out_stream.print("{}:{}:{}", .{ li.file_name, li.line, li.column });
573 } else {
574 try out_stream.writeAll("???:?:?");
575 }
575576
576 tty_config.setColor(out_stream, .Reset);
577 try noasync out_stream.write(": ");
578 tty_config.setColor(out_stream, .Dim);
579 try noasync out_stream.print("0x{x} in {} ({})", .{ address, symbol_name, compile_unit_name });
580 tty_config.setColor(out_stream, .Reset);
581 try noasync out_stream.write("\n");
582
583 // Show the matching source code line if possible
584 if (line_info) |li| {
585 if (noasync printLineFromFile(out_stream, li)) {
586 if (li.column > 0) {
587 // The caret already takes one char
588 const space_needed = @intCast(usize, li.column - 1);
589
590 try noasync out_stream.writeByteNTimes(' ', space_needed);
591 tty_config.setColor(out_stream, .Green);
592 try noasync out_stream.write("^");
593 tty_config.setColor(out_stream, .Reset);
577 tty_config.setColor(out_stream, .Reset);
578 try out_stream.writeAll(": ");
579 tty_config.setColor(out_stream, .Dim);
580 try out_stream.print("0x{x} in {} ({})", .{ address, symbol_name, compile_unit_name });
581 tty_config.setColor(out_stream, .Reset);
582 try out_stream.writeAll("\n");
583
584 // Show the matching source code line if possible
585 if (line_info) |li| {
586 if (printLineFromFile(out_stream, li)) {
587 if (li.column > 0) {
588 // The caret already takes one char
589 const space_needed = @intCast(usize, li.column - 1);
590
591 try out_stream.writeByteNTimes(' ', space_needed);
592 tty_config.setColor(out_stream, .Green);
593 try out_stream.writeAll("^");
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,
594601 }
595 try noasync out_stream.write("\n");
596 } else |err| switch (err) {
597 error.EndOfFile, error.FileNotFound => {},
598 error.BadPathName => {},
599 else => return err,
600602 }
601603 }
602604}
......@@ -609,21 +611,21 @@ pub const OpenSelfDebugInfoError = error{
609611};
610612
611613/// 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.
614614pub fn openSelfDebugInfo(allocator: *mem.Allocator) anyerror!DebugInfo {
615 if (builtin.strip_debug_info)
616 return error.MissingDebugInfo;
617 if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {
618 return noasync root.os.debug.openSelfDebugInfo(allocator);
619 }
620 switch (builtin.os.tag) {
621 .linux,
622 .freebsd,
623 .macosx,
624 .windows,
625 => return DebugInfo.init(allocator),
626 else => @compileError("openSelfDebugInfo unsupported for this platform"),
615 noasync {
616 if (builtin.strip_debug_info)
617 return error.MissingDebugInfo;
618 if (@hasDecl(root, "os") and @hasDecl(root.os, "debug") and @hasDecl(root.os.debug, "openSelfDebugInfo")) {
619 return root.os.debug.openSelfDebugInfo(allocator);
620 }
621 switch (builtin.os.tag) {
622 .linux,
623 .freebsd,
624 .macosx,
625 .windows,
626 => return DebugInfo.init(allocator),
627 else => @compileError("openSelfDebugInfo unsupported for this platform"),
628 }
627629 }
628630}
629631
......@@ -654,11 +656,11 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
654656 try di.pdb.openFile(di.coff, path);
655657
656658 var pdb_stream = di.pdb.getStream(pdb.StreamType.Pdb) orelse return error.InvalidDebugInfo;
657 const version = try pdb_stream.stream.readIntLittle(u32);
658 const signature = try pdb_stream.stream.readIntLittle(u32);
659 const age = try pdb_stream.stream.readIntLittle(u32);
659 const version = try pdb_stream.inStream().readIntLittle(u32);
660 const signature = try pdb_stream.inStream().readIntLittle(u32);
661 const age = try pdb_stream.inStream().readIntLittle(u32);
660662 var guid: [16]u8 = undefined;
661 try pdb_stream.stream.readNoEof(&guid);
663 try pdb_stream.inStream().readNoEof(&guid);
662664 if (version != 20000404) // VC70, only value observed by LLVM team
663665 return error.UnknownPDBVersion;
664666 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) !
666668 // We validated the executable and pdb match.
667669
668670 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);
670672 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
673675 const HashTableHeader = packed struct {
674676 Size: u32,
......@@ -678,17 +680,17 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
678680 return cap * 2 / 3 + 1;
679681 }
680682 };
681 const hash_tbl_hdr = try pdb_stream.stream.readStruct(HashTableHeader);
683 const hash_tbl_hdr = try pdb_stream.inStream().readStruct(HashTableHeader);
682684 if (hash_tbl_hdr.Capacity == 0)
683685 return error.InvalidDebugInfo;
684686
685687 if (hash_tbl_hdr.Size > HashTableHeader.maxLoad(hash_tbl_hdr.Capacity))
686688 return error.InvalidDebugInfo;
687689
688 const present = try readSparseBitVector(&pdb_stream.stream, allocator);
690 const present = try readSparseBitVector(&pdb_stream.inStream(), allocator);
689691 if (present.len != hash_tbl_hdr.Size)
690692 return error.InvalidDebugInfo;
691 const deleted = try readSparseBitVector(&pdb_stream.stream, allocator);
693 const deleted = try readSparseBitVector(&pdb_stream.inStream(), allocator);
692694
693695 const Bucket = struct {
694696 first: u32,
......@@ -696,8 +698,8 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
696698 };
697699 const bucket_list = try allocator.alloc(Bucket, present.len);
698700 for (present) |_| {
699 const name_offset = try pdb_stream.stream.readIntLittle(u32);
700 const name_index = try pdb_stream.stream.readIntLittle(u32);
701 const name_offset = try pdb_stream.inStream().readIntLittle(u32);
702 const name_index = try pdb_stream.inStream().readIntLittle(u32);
701703 const name = mem.toSlice(u8, @ptrCast([*:0]u8, name_bytes.ptr + name_offset));
702704 if (mem.eql(u8, name, "/names")) {
703705 break :str_tab_index name_index;
......@@ -712,7 +714,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
712714 const dbi = di.pdb.dbi;
713715
714716 // Dbi Header
715 const dbi_stream_header = try dbi.stream.readStruct(pdb.DbiStreamHeader);
717 const dbi_stream_header = try dbi.inStream().readStruct(pdb.DbiStreamHeader);
716718 if (dbi_stream_header.VersionHeader != 19990903) // V70, only value observed by LLVM team
717719 return error.UnknownPDBVersion;
718720 if (dbi_stream_header.Age != age)
......@@ -726,7 +728,7 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
726728 // Module Info Substream
727729 var mod_info_offset: usize = 0;
728730 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);
730732 var this_record_len: usize = @sizeOf(pdb.ModInfo);
731733
732734 const module_name = try dbi.readNullTermString(allocator);
......@@ -764,14 +766,14 @@ fn openCoffDebugInfo(allocator: *mem.Allocator, coff_file_path: [:0]const u16) !
764766 var sect_contribs = ArrayList(pdb.SectionContribEntry).init(allocator);
765767 var sect_cont_offset: usize = 0;
766768 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));
768770 if (ver != pdb.SectionContrSubstreamVersion.Ver60)
769771 return error.InvalidDebugInfo;
770772 sect_cont_offset += @sizeOf(u32);
771773 }
772774 while (sect_cont_offset != section_contrib_size) {
773775 const entry = try sect_contribs.addOne();
774 entry.* = try dbi.stream.readStruct(pdb.SectionContribEntry);
776 entry.* = try dbi.inStream().readStruct(pdb.SectionContribEntry);
775777 sect_cont_offset += @sizeOf(pdb.SectionContribEntry);
776778
777779 if (sect_cont_offset > section_contrib_size)
......@@ -808,45 +810,71 @@ fn chopSlice(ptr: []const u8, offset: u64, size: u64) ![]const u8 {
808810
809811/// TODO resources https://github.com/ziglang/zig/issues/4353
810812pub fn openElfDebugInfo(allocator: *mem.Allocator, elf_file_path: []const u8) !ModuleDebugInfo {
811 const mapped_mem = try mapWholeFile(elf_file_path);
812
813 var seekable_stream = io.SliceSeekableInStream.init(mapped_mem);
814 var efile = try noasync elf.Elf.openStream(
815 allocator,
816 @ptrCast(*DW.DwarfSeekableStream, &seekable_stream.seekable_stream),
817 @ptrCast(*DW.DwarfInStream, &seekable_stream.stream),
818 );
819 defer noasync efile.close();
813 noasync {
814 const mapped_mem = try mapWholeFile(elf_file_path);
815 const hdr = @ptrCast(*const elf.Ehdr, &mapped_mem[0]);
816 if (!mem.eql(u8, hdr.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
817 if (hdr.e_ident[elf.EI_VERSION] != 1) return error.InvalidElfVersion;
818
819 const endian: builtin.Endian = switch (hdr.e_ident[elf.EI_DATA]) {
820 elf.ELFDATA2LSB => .Little,
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")) orelse
822 return error.MissingDebugInfo;
823 const debug_abbrev = (try noasync efile.findSection(".debug_abbrev")) orelse
824 return error.MissingDebugInfo;
825 const debug_str = (try noasync efile.findSection(".debug_str")) orelse
826 return error.MissingDebugInfo;
827 const debug_line = (try noasync efile.findSection(".debug_line")) orelse
828 return error.MissingDebugInfo;
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 };
861 var di = DW.DwarfInfo{
862 .endian = endian,
863 .debug_info = opt_debug_info orelse return error.MissingDebugInfo,
864 .debug_abbrev = opt_debug_abbrev orelse return error.MissingDebugInfo,
865 .debug_str = opt_debug_str orelse return error.MissingDebugInfo,
866 .debug_line = opt_debug_line orelse return error.MissingDebugInfo,
867 .debug_ranges = opt_debug_ranges,
868 };
842869
843 try noasync DW.openDwarfDebugInfo(&di, allocator);
870 try DW.openDwarfDebugInfo(&di, allocator);
844871
845 return ModuleDebugInfo{
846 .base_address = undefined,
847 .dwarf = di,
848 .mapped_memory = mapped_mem,
849 };
872 return ModuleDebugInfo{
873 .base_address = undefined,
874 .dwarf = di,
875 .mapped_memory = mapped_mem,
876 };
877 }
850878}
851879
852880/// TODO resources https://github.com/ziglang/zig/issues/4353
......@@ -936,7 +964,9 @@ fn openMachODebugInfo(allocator: *mem.Allocator, macho_file_path: []const u8) !M
936964}
937965
938966fn 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 });
940970 defer f.close();
941971 // TODO fstat and make sure that the file has the correct size
942972
......@@ -982,22 +1012,24 @@ const MachoSymbol = struct {
9821012 }
9831013};
9841014
985fn mapWholeFile(path: []const u8) ![]const u8 {
986 const file = try noasync fs.openFileAbsolute(path, .{ .always_blocking = true });
987 defer noasync file.close();
988
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);
1015fn mapWholeFile(path: []const u8) ![]align(mem.page_size) const u8 {
1016 noasync {
1017 const file = try fs.openFileAbsolute(path, .{ .always_blocking = true });
1018 defer file.close();
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 }
10011033}
10021034
10031035pub const DebugInfo = struct {
lib/std/debug/leb128.zig+12-12
......@@ -121,18 +121,18 @@ pub fn readILEB128Mem(comptime T: type, ptr: *[*]const u8) !T {
121121}
122122
123123fn test_read_stream_ileb128(comptime T: type, encoded: []const u8) !T {
124 var in_stream = std.io.SliceInStream.init(encoded);
125 return try readILEB128(T, &in_stream.stream);
124 var in_stream = std.io.fixedBufferStream(encoded);
125 return try readILEB128(T, in_stream.inStream());
126126}
127127
128128fn test_read_stream_uleb128(comptime T: type, encoded: []const u8) !T {
129 var in_stream = std.io.SliceInStream.init(encoded);
130 return try readULEB128(T, &in_stream.stream);
129 var in_stream = std.io.fixedBufferStream(encoded);
130 return try readULEB128(T, in_stream.inStream());
131131}
132132
133133fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
134 var in_stream = std.io.SliceInStream.init(encoded);
135 const v1 = readILEB128(T, &in_stream.stream);
134 var in_stream = std.io.fixedBufferStream(encoded);
135 const v1 = readILEB128(T, in_stream.inStream());
136136 var in_ptr = encoded.ptr;
137137 const v2 = readILEB128Mem(T, &in_ptr);
138138 testing.expectEqual(v1, v2);
......@@ -140,8 +140,8 @@ fn test_read_ileb128(comptime T: type, encoded: []const u8) !T {
140140}
141141
142142fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
143 var in_stream = std.io.SliceInStream.init(encoded);
144 const v1 = readULEB128(T, &in_stream.stream);
143 var in_stream = std.io.fixedBufferStream(encoded);
144 const v1 = readULEB128(T, in_stream.inStream());
145145 var in_ptr = encoded.ptr;
146146 const v2 = readULEB128Mem(T, &in_ptr);
147147 testing.expectEqual(v1, v2);
......@@ -149,22 +149,22 @@ fn test_read_uleb128(comptime T: type, encoded: []const u8) !T {
149149}
150150
151151fn 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);
153153 var in_ptr = encoded.ptr;
154154 var i: usize = 0;
155155 while (i < N) : (i += 1) {
156 const v1 = readILEB128(T, &in_stream.stream);
156 const v1 = readILEB128(T, in_stream.inStream());
157157 const v2 = readILEB128Mem(T, &in_ptr);
158158 testing.expectEqual(v1, v2);
159159 }
160160}
161161
162162fn 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);
164164 var in_ptr = encoded.ptr;
165165 var i: usize = 0;
166166 while (i < N) : (i += 1) {
167 const v1 = readULEB128(T, &in_stream.stream);
167 const v1 = readULEB128(T, in_stream.inStream());
168168 const v2 = readULEB128Mem(T, &in_ptr);
169169 testing.expectEqual(v1, v2);
170170 }
lib/std/dwarf.zig+84-77
......@@ -11,9 +11,6 @@ const ArrayList = std.ArrayList;
1111
1212usingnamespace @import("dwarf_bits.zig");
1313
14pub const DwarfSeekableStream = io.SeekableStream(anyerror, anyerror);
15pub const DwarfInStream = io.InStream(anyerror);
16
1714const PcRange = struct {
1815 start: u64,
1916 end: u64,
......@@ -239,7 +236,7 @@ const LineNumberProgram = struct {
239236 }
240237};
241238
242fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 {
239fn readInitialLength(in_stream: var, is_64: *bool) !u64 {
243240 const first_32_bits = try in_stream.readIntLittle(u32);
244241 is_64.* = (first_32_bits == 0xffffffff);
245242 if (is_64.*) {
......@@ -414,40 +411,42 @@ pub const DwarfInfo = struct {
414411 }
415412
416413 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();
418417 var this_unit_offset: u64 = 0;
419418
420 while (this_unit_offset < try s.seekable_stream.getEndPos()) {
421 s.seekable_stream.seekTo(this_unit_offset) catch |err| switch (err) {
419 while (this_unit_offset < try seekable.getEndPos()) {
420 seekable.seekTo(this_unit_offset) catch |err| switch (err) {
422421 error.EndOfStream => unreachable,
423422 else => return err,
424423 };
425424
426425 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);
428427 if (unit_length == 0) return;
429428 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);
432431 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();
437436 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();
440439 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
444443 const next_unit_pos = this_unit_offset + next_offset;
445444
446 while ((try s.seekable_stream.getPos()) < next_unit_pos) {
447 const die_obj = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse continue;
445 while ((try seekable.getPos()) < next_unit_pos) {
446 const die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse continue;
448447 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
452451 switch (die_obj.tag_id) {
453452 TAG_subprogram, TAG_inlined_subroutine, TAG_subroutine, TAG_entry_point => {
......@@ -463,14 +462,14 @@ pub const DwarfInfo = struct {
463462 // Follow the DIE it points to and repeat
464463 const ref_offset = try this_die_obj.getAttrRef(AT_abstract_origin);
465464 if (ref_offset > next_offset) return error.InvalidDebugInfo;
466 try s.seekable_stream.seekTo(this_unit_offset + ref_offset);
467 this_die_obj = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
465 try seekable.seekTo(this_unit_offset + ref_offset);
466 this_die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
468467 } else if (this_die_obj.getAttr(AT_specification)) |ref| {
469468 // Follow the DIE it points to and repeat
470469 const ref_offset = try this_die_obj.getAttrRef(AT_specification);
471470 if (ref_offset > next_offset) return error.InvalidDebugInfo;
472 try s.seekable_stream.seekTo(this_unit_offset + ref_offset);
473 this_die_obj = (try di.parseDie(&s.stream, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
471 try seekable.seekTo(this_unit_offset + ref_offset);
472 this_die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse return error.InvalidDebugInfo;
474473 } else {
475474 break :x null;
476475 }
......@@ -511,7 +510,7 @@ pub const DwarfInfo = struct {
511510 else => {},
512511 }
513512
514 try s.seekable_stream.seekTo(after_die_offset);
513 try seekable.seekTo(after_die_offset);
515514 }
516515
517516 this_unit_offset += next_offset;
......@@ -519,35 +518,37 @@ pub const DwarfInfo = struct {
519518 }
520519
521520 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();
523524 var this_unit_offset: u64 = 0;
524525
525 while (this_unit_offset < try s.seekable_stream.getEndPos()) {
526 s.seekable_stream.seekTo(this_unit_offset) catch |err| switch (err) {
526 while (this_unit_offset < try seekable.getEndPos()) {
527 seekable.seekTo(this_unit_offset) catch |err| switch (err) {
527528 error.EndOfStream => unreachable,
528529 else => return err,
529530 };
530531
531532 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);
533534 if (unit_length == 0) return;
534535 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);
537538 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();
542543 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();
545546 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
549550 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
552553 if (compile_unit_die.tag_id != TAG_compile_unit) return error.InvalidDebugInfo;
553554
......@@ -593,7 +594,9 @@ pub const DwarfInfo = struct {
593594 }
594595 if (di.debug_ranges) |debug_ranges| {
595596 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
598601 // All the addresses in the list are relative to the value
599602 // specified by DW_AT_low_pc or to some other value encoded
......@@ -604,11 +607,11 @@ pub const DwarfInfo = struct {
604607 else => return err,
605608 };
606609
607 try s.seekable_stream.seekTo(ranges_offset);
610 try seekable.seekTo(ranges_offset);
608611
609612 while (true) {
610 const begin_addr = try s.stream.readIntLittle(usize);
611 const end_addr = try s.stream.readIntLittle(usize);
613 const begin_addr = try in.readIntLittle(usize);
614 const end_addr = try in.readIntLittle(usize);
612615 if (begin_addr == 0 and end_addr == 0) {
613616 break;
614617 }
......@@ -646,25 +649,27 @@ pub const DwarfInfo = struct {
646649 }
647650
648651 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);
652657 var result = AbbrevTable.init(di.allocator());
653658 errdefer result.deinit();
654659 while (true) {
655 const abbrev_code = try leb.readULEB128(u64, &s.stream);
660 const abbrev_code = try leb.readULEB128(u64, in);
656661 if (abbrev_code == 0) return result;
657662 try result.append(AbbrevTableEntry{
658663 .abbrev_code = abbrev_code,
659 .tag_id = try leb.readULEB128(u64, &s.stream),
660 .has_children = (try s.stream.readByte()) == CHILDREN_yes,
664 .tag_id = try leb.readULEB128(u64, in),
665 .has_children = (try in.readByte()) == CHILDREN_yes,
661666 .attrs = ArrayList(AbbrevAttr).init(di.allocator()),
662667 });
663668 const attrs = &result.items[result.len - 1].attrs;
664669
665670 while (true) {
666 const attr_id = try leb.readULEB128(u64, &s.stream);
667 const form_id = try leb.readULEB128(u64, &s.stream);
671 const attr_id = try leb.readULEB128(u64, in);
672 const form_id = try leb.readULEB128(u64, in);
668673 if (attr_id == 0 and form_id == 0) break;
669674 try attrs.append(AbbrevAttr{
670675 .attr_id = attr_id,
......@@ -695,42 +700,44 @@ pub const DwarfInfo = struct {
695700 }
696701
697702 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
700707 const compile_unit_cwd = try compile_unit.die.getAttrString(di, AT_comp_dir);
701708 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
705712 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);
707714 if (unit_length == 0) {
708715 return error.MissingDebugInfo;
709716 }
710717 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);
713720 // TODO support 3 and 5
714721 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);
717 const prog_start_offset = (try s.seekable_stream.getPos()) + prologue_length;
723 const prologue_length = if (is_64) try in.readInt(u64, di.endian) else try in.readInt(u32, di.endian);
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();
720727 if (minimum_instruction_length == 0) return error.InvalidDebugInfo;
721728
722729 if (version >= 4) {
723730 // maximum_operations_per_instruction
724 _ = try s.stream.readByte();
731 _ = try in.readByte();
725732 }
726733
727 const default_is_stmt = (try s.stream.readByte()) != 0;
728 const line_base = try s.stream.readByteSigned();
734 const default_is_stmt = (try in.readByte()) != 0;
735 const line_base = try in.readByteSigned();
729736
730 const line_range = try s.stream.readByte();
737 const line_range = try in.readByte();
731738 if (line_range == 0) return error.InvalidDebugInfo;
732739
733 const opcode_base = try s.stream.readByte();
740 const opcode_base = try in.readByte();
734741
735742 const standard_opcode_lengths = try di.allocator().alloc(u8, opcode_base - 1);
736743 defer di.allocator().free(standard_opcode_lengths);
......@@ -738,14 +745,14 @@ pub const DwarfInfo = struct {
738745 {
739746 var i: usize = 0;
740747 while (i < opcode_base - 1) : (i += 1) {
741 standard_opcode_lengths[i] = try s.stream.readByte();
748 standard_opcode_lengths[i] = try in.readByte();
742749 }
743750 }
744751
745752 var include_directories = ArrayList([]const u8).init(di.allocator());
746753 try include_directories.append(compile_unit_cwd);
747754 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));
749756 if (dir.len == 0) break;
750757 try include_directories.append(dir);
751758 }
......@@ -754,11 +761,11 @@ pub const DwarfInfo = struct {
754761 var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address);
755762
756763 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));
758765 if (file_name.len == 0) break;
759 const dir_index = try leb.readULEB128(usize, &s.stream);
760 const mtime = try leb.readULEB128(usize, &s.stream);
761 const len_bytes = try leb.readULEB128(usize, &s.stream);
766 const dir_index = try leb.readULEB128(usize, in);
767 const mtime = try leb.readULEB128(usize, in);
768 const len_bytes = try leb.readULEB128(usize, in);
762769 try file_entries.append(FileEntry{
763770 .file_name = file_name,
764771 .dir_index = dir_index,
......@@ -767,17 +774,17 @@ pub const DwarfInfo = struct {
767774 });
768775 }
769776
770 try s.seekable_stream.seekTo(prog_start_offset);
777 try seekable.seekTo(prog_start_offset);
771778
772779 const next_unit_pos = line_info_offset + next_offset;
773780
774 while ((try s.seekable_stream.getPos()) < next_unit_pos) {
775 const opcode = try s.stream.readByte();
781 while ((try seekable.getPos()) < next_unit_pos) {
782 const opcode = try in.readByte();
776783
777784 if (opcode == LNS_extended_op) {
778 const op_size = try leb.readULEB128(u64, &s.stream);
785 const op_size = try leb.readULEB128(u64, in);
779786 if (op_size < 1) return error.InvalidDebugInfo;
780 var sub_op = try s.stream.readByte();
787 var sub_op = try in.readByte();
781788 switch (sub_op) {
782789 LNE_end_sequence => {
783790 prog.end_sequence = true;
......@@ -785,14 +792,14 @@ pub const DwarfInfo = struct {
785792 prog.reset();
786793 },
787794 LNE_set_address => {
788 const addr = try s.stream.readInt(usize, di.endian);
795 const addr = try in.readInt(usize, di.endian);
789796 prog.address = addr;
790797 },
791798 LNE_define_file => {
792 const file_name = try s.stream.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));
793 const dir_index = try leb.readULEB128(usize, &s.stream);
794 const mtime = try leb.readULEB128(usize, &s.stream);
795 const len_bytes = try leb.readULEB128(usize, &s.stream);
799 const file_name = try in.readUntilDelimiterAlloc(di.allocator(), 0, math.maxInt(usize));
800 const dir_index = try leb.readULEB128(usize, in);
801 const mtime = try leb.readULEB128(usize, in);
802 const len_bytes = try leb.readULEB128(usize, in);
796803 try file_entries.append(FileEntry{
797804 .file_name = file_name,
798805 .dir_index = dir_index,
......@@ -802,7 +809,7 @@ pub const DwarfInfo = struct {
802809 },
803810 else => {
804811 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);
806813 },
807814 }
808815 } else if (opcode >= opcode_base) {
......@@ -821,19 +828,19 @@ pub const DwarfInfo = struct {
821828 prog.basic_block = false;
822829 },
823830 LNS_advance_pc => {
824 const arg = try leb.readULEB128(usize, &s.stream);
831 const arg = try leb.readULEB128(usize, in);
825832 prog.address += arg * minimum_instruction_length;
826833 },
827834 LNS_advance_line => {
828 const arg = try leb.readILEB128(i64, &s.stream);
835 const arg = try leb.readILEB128(i64, in);
829836 prog.line += arg;
830837 },
831838 LNS_set_file => {
832 const arg = try leb.readULEB128(usize, &s.stream);
839 const arg = try leb.readULEB128(usize, in);
833840 prog.file = arg;
834841 },
835842 LNS_set_column => {
836 const arg = try leb.readULEB128(u64, &s.stream);
843 const arg = try leb.readULEB128(u64, in);
837844 prog.column = arg;
838845 },
839846 LNS_negate_stmt => {
......@@ -847,14 +854,14 @@ pub const DwarfInfo = struct {
847854 prog.address += inc_addr;
848855 },
849856 LNS_fixed_advance_pc => {
850 const arg = try s.stream.readInt(u16, di.endian);
857 const arg = try in.readInt(u16, di.endian);
851858 prog.address += arg;
852859 },
853860 LNS_set_prologue_end => {},
854861 else => {
855862 if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo;
856863 const len_bytes = standard_opcode_lengths[opcode - 1];
857 try s.seekable_stream.seekBy(len_bytes);
864 try seekable.seekBy(len_bytes);
858865 },
859866 }
860867 }
lib/std/elf.zig+207-193
......@@ -1,5 +1,5 @@
1const builtin = @import("builtin");
21const std = @import("std.zig");
2const builtin = std.builtin;
33const io = std.io;
44const os = std.os;
55const math = std.math;
......@@ -330,218 +330,232 @@ pub const ET = extern enum(u16) {
330330 pub const HIPROC = 0xffff;
331331};
332332
333pub const SectionHeader = Elf64_Shdr;
334pub const ProgramHeader = Elf64_Phdr;
335
336pub const Elf = struct {
337 seekable_stream: *io.SeekableStream(anyerror, anyerror),
338 in_stream: *io.InStream(anyerror),
339 is_64: bool,
333/// All integers are native endian.
334const Header = struct {
340335 endian: builtin.Endian,
341 file_type: ET,
342 arch: EM,
343 entry_addr: u64,
344 program_header_offset: u64,
345 section_header_offset: u64,
346 string_section_index: usize,
347 string_section: *SectionHeader,
348 section_headers: []SectionHeader,
349 program_headers: []ProgramHeader,
350 allocator: *mem.Allocator,
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);
336 is_64: bool,
337 entry: u64,
338 phoff: u64,
339 shoff: u64,
340 phentsize: u16,
341 phnum: u16,
342 shentsize: u16,
343 shnum: u16,
344 shstrndx: u16,
345};
383346
384 elf.file_type = try in.readEnum(ET, elf.endian);
385 elf.arch = try in.readEnum(EM, elf.endian);
347pub fn readHeader(file: File) !Header {
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);
388 if (elf_version != 1) return error.InvalidFormat;
382/// All integers are native endian.
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) {
391 elf.entry_addr = try in.readInt(u64, elf.endian);
392 elf.program_header_offset = try in.readInt(u64, elf.endian);
393 elf.section_header_offset = try in.readInt(u64, elf.endian);
394 } else {
395 elf.entry_addr = @as(u64, try in.readInt(u32, elf.endian));
396 elf.program_header_offset = @as(u64, try in.readInt(u32, elf.endian));
397 elf.section_header_offset = @as(u64, try in.readInt(u32, elf.endian));
390pub fn readAllHeaders(allocator: *mem.Allocator, file: File) !AllHeaders {
391 var hdrs: AllHeaders = .{
392 .allocator = allocator,
393 .header = try readHeader(file),
394 .section_headers = undefined,
395 .program_headers = undefined,
396 };
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 }
398442 }
399443
400 // skip over flags
401 try seekable_stream.seekBy(4);
444 return hdrs;
445 }
402446
403 const header_size = try in.readInt(u16, elf.endian);
404 if ((elf.is_64 and header_size != @sizeOf(Elf64_Ehdr)) or (!elf.is_64 and header_size != @sizeOf(Elf32_Ehdr))) {
405 return error.InvalidFormat;
447 const shdrs_32 = try allocator.alloc(Elf32_Shdr, hdrs.header.shnum);
448 defer allocator.free(shdrs_32);
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 };
406473 }
407
408 const ph_entry_size = try in.readInt(u16, elf.endian);
409 const ph_entry_count = try in.readInt(u16, elf.endian);
410
411 if ((elf.is_64 and ph_entry_size != @sizeOf(Elf64_Phdr)) or (!elf.is_64 and ph_entry_size != @sizeOf(Elf32_Phdr))) {
412 return error.InvalidFormat;
474 for (hdrs.program_headers) |*phdr, i| {
475 const o = phdrs_32[i];
476 phdr.* = .{
477 .p_type = @byteSwap(@TypeOf(o.p_type), o.p_type),
478 .p_offset = @byteSwap(@TypeOf(o.p_offset), o.p_offset),
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 };
413486 }
414
415 const sh_entry_size = try in.readInt(u16, elf.endian);
416 const sh_entry_count = try in.readInt(u16, elf.endian);
417
418 if ((elf.is_64 and sh_entry_size != @sizeOf(Elf64_Shdr)) or (!elf.is_64 and sh_entry_size != @sizeOf(Elf32_Shdr))) {
419 return error.InvalidFormat;
487 } else {
488 for (hdrs.section_headers) |*shdr, i| {
489 const o = shdrs_32[i];
490 shdr.* = .{
491 .sh_name = o.sh_name,
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 };
420502 }
421
422 elf.string_section_index = @as(usize, try in.readInt(u16, elf.endian));
423
424 if (elf.string_section_index >= sh_entry_count) return error.InvalidFormat;
425
426 const sh_byte_count = @as(u64, sh_entry_size) * @as(u64, sh_entry_count);
427 const end_sh = try math.add(u64, elf.section_header_offset, sh_byte_count);
428 const ph_byte_count = @as(u64, ph_entry_size) * @as(u64, ph_entry_count);
429 const end_ph = try math.add(u64, elf.program_header_offset, ph_byte_count);
430
431 const stream_end = try seekable_stream.getEndPos();
432 if (stream_end < end_sh or stream_end < end_ph) {
433 return error.InvalidFormat;
503 for (hdrs.program_headers) |*phdr, i| {
504 const o = phdrs_32[i];
505 phdr.* = .{
506 .p_type = o.p_type,
507 .p_offset = o.p_offset,
508 .p_vaddr = o.p_vaddr,
509 .p_paddr = o.p_paddr,
510 .p_filesz = o.p_filesz,
511 .p_memsz = o.p_memsz,
512 .p_flags = o.p_flags,
513 .p_align = o.p_align,
514 };
434515 }
516 }
435517
436 try seekable_stream.seekTo(elf.program_header_offset);
437
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 }
518 return hdrs;
519}
464520
465 try seekable_stream.seekTo(elf.section_header_offset);
466
467 elf.section_headers = try elf.allocator.alloc(SectionHeader, sh_entry_count);
468 errdefer elf.allocator.free(elf.section_headers);
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 }
521pub fn int(is_64: bool, need_bswap: bool, int_32: var, int_64: var) @TypeOf(int_64) {
522 if (is_64) {
523 if (need_bswap) {
524 return @byteSwap(@TypeOf(int_64), int_64);
483525 } else {
484 for (elf.section_headers) |*elf_section| {
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 }
526 return int_64;
497527 }
498
499 for (elf.section_headers) |*elf_section| {
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;
528 } else {
529 return int32(need_bswap, int_32, @TypeOf(int_64));
513530 }
531}
514532
515 pub fn close(elf: *Elf) void {
516 elf.allocator.free(elf.section_headers);
517 elf.allocator.free(elf.program_headers);
518 }
519
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;
533pub fn int32(need_bswap: bool, int_32: var, comptime Int64: var) Int64 {
534 if (need_bswap) {
535 return @byteSwap(@TypeOf(int_32), int_32);
536 } else {
537 return int_32;
539538 }
539}
540540
541 pub fn seekToSection(elf: *Elf, elf_section: *SectionHeader) !void {
542 try elf.seekable_stream.seekTo(elf_section.sh_offset);
541fn preadNoEof(file: std.fs.File, buf: []u8, offset: u64) !void {
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;
543557 }
544};
558}
545559
546560pub const EI_NIDENT = 16;
547561
lib/std/event/channel.zig+10-13
......@@ -14,8 +14,8 @@ pub fn Channel(comptime T: type) type {
1414 putters: std.atomic.Queue(PutNode),
1515 get_count: usize,
1616 put_count: usize,
17 dispatch_lock: u8, // TODO make this a bool
18 need_dispatch: u8, // TODO make this a bool
17 dispatch_lock: bool,
18 need_dispatch: bool,
1919
2020 // simple fixed size ring buffer
2121 buffer_nodes: []T,
......@@ -62,8 +62,8 @@ pub fn Channel(comptime T: type) type {
6262 .buffer_len = 0,
6363 .buffer_nodes = buffer,
6464 .buffer_index = 0,
65 .dispatch_lock = 0,
66 .need_dispatch = 0,
65 .dispatch_lock = false,
66 .need_dispatch = false,
6767 .getters = std.atomic.Queue(GetNode).init(),
6868 .putters = std.atomic.Queue(PutNode).init(),
6969 .or_null_queue = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).init(),
......@@ -165,15 +165,14 @@ pub fn Channel(comptime T: type) type {
165165
166166 fn dispatch(self: *SelfChannel) void {
167167 // set the "need dispatch" flag
168 @atomicStore(u8, &self.need_dispatch, 1, .SeqCst);
168 @atomicStore(bool, &self.need_dispatch, true, .SeqCst);
169169
170170 lock: while (true) {
171171 // set the lock flag
172 const prev_lock = @atomicRmw(u8, &self.dispatch_lock, .Xchg, 1, .SeqCst);
173 if (prev_lock != 0) return;
172 if (@atomicRmw(bool, &self.dispatch_lock, .Xchg, true, .SeqCst)) return;
174173
175174 // 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
178177 while (true) {
179178 one_dispatch: {
......@@ -250,14 +249,12 @@ pub fn Channel(comptime T: type) type {
250249 }
251250
252251 // clear need-dispatch flag
253 const need_dispatch = @atomicRmw(u8, &self.need_dispatch, .Xchg, 0, .SeqCst);
254 if (need_dispatch != 0) continue;
252 if (@atomicRmw(bool, &self.need_dispatch, .Xchg, false, .SeqCst)) continue;
255253
256 const my_lock = @atomicRmw(u8, &self.dispatch_lock, .Xchg, 0, .SeqCst);
257 assert(my_lock != 0);
254 assert(@atomicRmw(bool, &self.dispatch_lock, .Xchg, false, .SeqCst));
258255
259256 // 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
262259 return;
263260 }
lib/std/event/group.zig+3-1
......@@ -120,9 +120,11 @@ test "std.event.Group" {
120120 // https://github.com/ziglang/zig/issues/1908
121121 if (builtin.single_threaded) return error.SkipZigTest;
122122
123 // TODO provide a way to run tests in evented I/O mode
124123 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
126128 const handle = async testGroup(std.heap.page_allocator);
127129}
128130
lib/std/event/lock.zig+20-19
......@@ -11,9 +11,9 @@ const Loop = std.event.Loop;
1111/// Allows only one actor to hold the lock.
1212/// TODO: make this API also work in blocking I/O mode.
1313pub const Lock = struct {
14 shared_bit: u8, // TODO make this a bool
14 shared: bool,
1515 queue: Queue,
16 queue_empty_bit: u8, // TODO make this a bool
16 queue_empty: bool,
1717
1818 const Queue = std.atomic.Queue(anyframe);
1919
......@@ -31,20 +31,19 @@ pub const Lock = struct {
3131 }
3232
3333 // We need to release the lock.
34 @atomicStore(u8, &self.lock.queue_empty_bit, 1, .SeqCst);
35 @atomicStore(u8, &self.lock.shared_bit, 0, .SeqCst);
34 @atomicStore(bool, &self.lock.queue_empty, true, .SeqCst);
35 @atomicStore(bool, &self.lock.shared, false, .SeqCst);
3636
3737 // There might be a queue item. If we know the queue is empty, we can be done,
3838 // because the other actor will try to obtain the lock.
3939 // But if there's a queue item, we are the actor which must loop and attempt
4040 // 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)) {
4242 return;
4343 }
4444
4545 while (true) {
46 const old_bit = @atomicRmw(u8, &self.lock.shared_bit, .Xchg, 1, .SeqCst);
47 if (old_bit != 0) {
46 if (@atomicRmw(bool, &self.lock.shared, .Xchg, true, .SeqCst)) {
4847 // We did not obtain the lock. Great, the queue is someone else's problem.
4948 return;
5049 }
......@@ -56,11 +55,11 @@ pub const Lock = struct {
5655 }
5756
5857 // Release the lock again.
59 @atomicStore(u8, &self.lock.queue_empty_bit, 1, .SeqCst);
60 @atomicStore(u8, &self.lock.shared_bit, 0, .SeqCst);
58 @atomicStore(bool, &self.lock.queue_empty, true, .SeqCst);
59 @atomicStore(bool, &self.lock.shared, false, .SeqCst);
6160
6261 // 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)) {
6463 return;
6564 }
6665 }
......@@ -69,24 +68,24 @@ pub const Lock = struct {
6968
7069 pub fn init() Lock {
7170 return Lock{
72 .shared_bit = 0,
71 .shared = false,
7372 .queue = Queue.init(),
74 .queue_empty_bit = 1,
73 .queue_empty = true,
7574 };
7675 }
7776
7877 pub fn initLocked() Lock {
7978 return Lock{
80 .shared_bit = 1,
79 .shared = true,
8180 .queue = Queue.init(),
82 .queue_empty_bit = 1,
81 .queue_empty = true,
8382 };
8483 }
8584
8685 /// Must be called when not locked. Not thread safe.
8786 /// All calls to acquire() and release() must complete before calling deinit().
8887 pub fn deinit(self: *Lock) void {
89 assert(self.shared_bit == 0);
88 assert(!self.shared);
9089 while (self.queue.get()) |node| resume node.data;
9190 }
9291
......@@ -99,12 +98,11 @@ pub const Lock = struct {
9998
10099 // 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 actor
101 // We set this bit so that later we can rely on the fact, that if queue_empty == true, some actor
103102 // 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);
107 if (old_bit == 0) {
105 if (!@atomicRmw(bool, &self.shared, .Xchg, true, .SeqCst)) {
108106 if (self.queue.get()) |node| {
109107 // Whether this node is us or someone else, we tail resume it.
110108 resume node.data;
......@@ -125,6 +123,9 @@ test "std.event.Lock" {
125123 // TODO https://github.com/ziglang/zig/issues/3251
126124 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
128129 var lock = Lock.init();
129130 defer lock.deinit();
130131
lib/std/event/loop.zig+78
......@@ -809,6 +809,28 @@ pub const Loop = struct {
809809 return req_node.data.msg.readv.result;
810810 }
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
812834 /// Performs an async `os.preadv` using a separate thread.
813835 /// `fd` must block and not return EAGAIN.
814836 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 {
895917 return req_node.data.msg.pwritev.result;
896918 }
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
898949 fn workerRun(self: *Loop) void {
899950 while (true) {
900951 while (true) {
......@@ -1038,6 +1089,9 @@ pub const Loop = struct {
10381089 .pwritev => |*msg| {
10391090 msg.result = noasync os.pwritev(msg.fd, msg.iov, msg.offset);
10401091 },
1092 .pread => |*msg| {
1093 msg.result = noasync os.pread(msg.fd, msg.buf, msg.offset);
1094 },
10411095 .preadv => |*msg| {
10421096 msg.result = noasync os.preadv(msg.fd, msg.iov, msg.offset);
10431097 },
......@@ -1047,6 +1101,9 @@ pub const Loop = struct {
10471101 .openat => |*msg| {
10481102 msg.result = noasync os.openatC(msg.fd, msg.path, msg.flags, msg.mode);
10491103 },
1104 .faccessat => |*msg| {
1105 msg.result = noasync os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags);
1106 },
10501107 .close => |*msg| noasync os.close(msg.fd),
10511108 }
10521109 switch (node.data.finish) {
......@@ -1120,10 +1177,12 @@ pub const Loop = struct {
11201177 write: Write,
11211178 writev: WriteV,
11221179 pwritev: PWriteV,
1180 pread: PRead,
11231181 preadv: PReadV,
11241182 open: Open,
11251183 openat: OpenAt,
11261184 close: Close,
1185 faccessat: FAccessAt,
11271186
11281187 /// special - means the fs thread should exit
11291188 end,
......@@ -1161,6 +1220,15 @@ pub const Loop = struct {
11611220 pub const Error = os.PWriteError;
11621221 };
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
11641232 pub const PReadV = struct {
11651233 fd: os.fd_t,
11661234 iov: []const os.iovec,
......@@ -1192,6 +1260,16 @@ pub const Loop = struct {
11921260 pub const Close = struct {
11931261 fd: os.fd_t,
11941262 };
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 };
11951273 };
11961274 };
11971275};
lib/std/event/rwlock.zig+16-16
......@@ -16,8 +16,8 @@ pub const RwLock = struct {
1616 shared_state: State,
1717 writer_queue: Queue,
1818 reader_queue: Queue,
19 writer_queue_empty_bit: u8, // TODO make this a bool
20 reader_queue_empty_bit: u8, // TODO make this a bool
19 writer_queue_empty: bool,
20 reader_queue_empty: bool,
2121 reader_lock_count: usize,
2222
2323 const State = enum(u8) {
......@@ -40,7 +40,7 @@ pub const RwLock = struct {
4040 return;
4141 }
4242
43 @atomicStore(u8, &self.lock.reader_queue_empty_bit, 1, .SeqCst);
43 @atomicStore(bool, &self.lock.reader_queue_empty, true, .SeqCst);
4444 if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
4545 // Didn't unlock. Someone else's problem.
4646 return;
......@@ -62,7 +62,7 @@ pub const RwLock = struct {
6262 }
6363
6464 // 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)) {
6666 // Switch to a read lock.
6767 @atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst);
6868 while (self.lock.reader_queue.get()) |node| {
......@@ -71,7 +71,7 @@ pub const RwLock = struct {
7171 return;
7272 }
7373
74 @atomicStore(u8, &self.lock.writer_queue_empty_bit, 1, .SeqCst);
74 @atomicStore(bool, &self.lock.writer_queue_empty, true, .SeqCst);
7575 @atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst);
7676
7777 self.lock.commonPostUnlock();
......@@ -79,12 +79,12 @@ pub const RwLock = struct {
7979 };
8080
8181 pub fn init() RwLock {
82 return RwLock{
82 return .{
8383 .shared_state = .Unlocked,
8484 .writer_queue = Queue.init(),
85 .writer_queue_empty_bit = 1,
85 .writer_queue_empty = true,
8686 .reader_queue = Queue.init(),
87 .reader_queue_empty_bit = 1,
87 .reader_queue_empty = true,
8888 .reader_lock_count = 0,
8989 };
9090 }
......@@ -111,9 +111,9 @@ pub const RwLock = struct {
111111
112112 // 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,
115115 // 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
118118 // Here we don't care if we are the one to do the locking or if it was already locked for reading.
119119 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 {
142142
143143 // 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,
146146 // 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
149149 // Here we must be the one to acquire the write lock. It cannot already be locked.
150150 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) {
......@@ -165,7 +165,7 @@ pub const RwLock = struct {
165165 // obtain the lock.
166166 // But if there's a writer_queue item or a reader_queue item,
167167 // 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)) {
169169 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) {
170170 // We did not obtain the lock. Great, the queues are someone else's problem.
171171 return;
......@@ -176,12 +176,12 @@ pub const RwLock = struct {
176176 return;
177177 }
178178 // Release the lock again.
179 @atomicStore(u8, &self.writer_queue_empty_bit, 1, .SeqCst);
179 @atomicStore(bool, &self.writer_queue_empty, true, .SeqCst);
180180 @atomicStore(State, &self.shared_state, .Unlocked, .SeqCst);
181181 continue;
182182 }
183183
184 if (@atomicLoad(u8, &self.reader_queue_empty_bit, .SeqCst) == 0) {
184 if (!@atomicLoad(bool, &self.reader_queue_empty, .SeqCst)) {
185185 if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) {
186186 // We did not obtain the lock. Great, the queues are someone else's problem.
187187 return;
......@@ -195,7 +195,7 @@ pub const RwLock = struct {
195195 return;
196196 }
197197 // Release the lock again.
198 @atomicStore(u8, &self.reader_queue_empty_bit, 1, .SeqCst);
198 @atomicStore(bool, &self.reader_queue_empty, true, .SeqCst);
199199 if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) {
200200 // Didn't unlock. Someone else's problem.
201201 return;
lib/std/fifo.zig+13-3
......@@ -293,8 +293,18 @@ pub fn LinearFifo(
293293
294294 pub usingnamespace if (T == u8)
295295 struct {
296 pub fn print(self: *Self, comptime format: []const u8, args: var) !void {
297 return std.fmt.format(self, error{OutOfMemory}, Self.write, format, args);
296 const OutStream = std.io.OutStream(*Self, Error, appendWrite);
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 };
298308 }
299309 }
300310 else
......@@ -407,7 +417,7 @@ test "LinearFifo(u8, .Dynamic)" {
407417 fifo.shrink(0);
408418
409419 {
410 try fifo.print("{}, {}!", .{ "Hello", "World" });
420 try fifo.outStream().print("{}, {}!", .{ "Hello", "World" });
411421 var result: [30]u8 = undefined;
412422 testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);
413423 testing.expectEqual(@as(usize, 0), fifo.readableLength());
lib/std/fmt.zig+225-301
......@@ -69,19 +69,17 @@ fn peekIsAlign(comptime fmt: []const u8) bool {
6969///
7070/// If a formatted user type contains a function of the type
7171/// ```
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!void
72/// fn format(value: ?, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void
7373/// ```
7474/// with `?` being the type formatted, this function will be called instead of the default implementation.
7575/// This allows user types to be formatted in a logical manner instead of dumping all fields of the type.
7676///
7777/// A user type may be a `struct`, `vector`, `union` or `enum` type.
7878pub fn format(
79 context: var,
80 comptime Errors: type,
81 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
79 out_stream: var,
8280 comptime fmt: []const u8,
8381 args: var,
84) Errors!void {
82) !void {
8583 const ArgSetType = u32;
8684 if (@typeInfo(@TypeOf(args)) != .Struct) {
8785 @compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));
......@@ -138,7 +136,7 @@ pub fn format(
138136 .Start => switch (c) {
139137 '{' => {
140138 if (start_index < i) {
141 try output(context, fmt[start_index..i]);
139 try out_stream.writeAll(fmt[start_index..i]);
142140 }
143141
144142 start_index = i;
......@@ -150,7 +148,7 @@ pub fn format(
150148 },
151149 '}' => {
152150 if (start_index < i) {
153 try output(context, fmt[start_index..i]);
151 try out_stream.writeAll(fmt[start_index..i]);
154152 }
155153 state = .CloseBrace;
156154 },
......@@ -185,9 +183,7 @@ pub fn format(
185183 args[arg_to_print],
186184 fmt[0..0],
187185 options,
188 context,
189 Errors,
190 output,
186 out_stream,
191187 default_max_depth,
192188 );
193189
......@@ -218,9 +214,7 @@ pub fn format(
218214 args[arg_to_print],
219215 fmt[specifier_start..i],
220216 options,
221 context,
222 Errors,
223 output,
217 out_stream,
224218 default_max_depth,
225219 );
226220 state = .Start;
......@@ -265,9 +259,7 @@ pub fn format(
265259 args[arg_to_print],
266260 fmt[specifier_start..specifier_end],
267261 options,
268 context,
269 Errors,
270 output,
262 out_stream,
271263 default_max_depth,
272264 );
273265 state = .Start;
......@@ -293,9 +285,7 @@ pub fn format(
293285 args[arg_to_print],
294286 fmt[specifier_start..specifier_end],
295287 options,
296 context,
297 Errors,
298 output,
288 out_stream,
299289 default_max_depth,
300290 );
301291 state = .Start;
......@@ -316,7 +306,7 @@ pub fn format(
316306 }
317307 }
318308 if (start_index < fmt.len) {
319 try output(context, fmt[start_index..]);
309 try out_stream.writeAll(fmt[start_index..]);
320310 }
321311}
322312
......@@ -324,141 +314,131 @@ pub fn formatType(
324314 value: var,
325315 comptime fmt: []const u8,
326316 options: FormatOptions,
327 context: var,
328 comptime Errors: type,
329 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
317 out_stream: var,
330318 max_depth: usize,
331) Errors!void {
319) @TypeOf(out_stream).Error!void {
332320 if (comptime std.mem.eql(u8, fmt, "*")) {
333 try output(context, @typeName(@TypeOf(value).Child));
334 try output(context, "@");
335 try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, context, Errors, output);
321 try out_stream.writeAll(@typeName(@TypeOf(value).Child));
322 try out_stream.writeAll("@");
323 try formatInt(@ptrToInt(value), 16, false, FormatOptions{}, out_stream);
336324 return;
337325 }
338326
339327 const T = @TypeOf(value);
328 if (comptime std.meta.trait.hasFn("format")(T)) {
329 return try value.format(fmt, options, out_stream);
330 }
331
340332 switch (@typeInfo(T)) {
341333 .ComptimeInt, .Int, .Float => {
342 return formatValue(value, fmt, options, context, Errors, output);
334 return formatValue(value, fmt, options, out_stream);
343335 },
344336 .Void => {
345 return output(context, "void");
337 return out_stream.writeAll("void");
346338 },
347339 .Bool => {
348 return output(context, if (value) "true" else "false");
340 return out_stream.writeAll(if (value) "true" else "false");
349341 },
350342 .Optional => {
351343 if (value) |payload| {
352 return formatType(payload, fmt, options, context, Errors, output, max_depth);
344 return formatType(payload, fmt, options, out_stream, max_depth);
353345 } else {
354 return output(context, "null");
346 return out_stream.writeAll("null");
355347 }
356348 },
357349 .ErrorUnion => {
358350 if (value) |payload| {
359 return formatType(payload, fmt, options, context, Errors, output, max_depth);
351 return formatType(payload, fmt, options, out_stream, max_depth);
360352 } else |err| {
361 return formatType(err, fmt, options, context, Errors, output, max_depth);
353 return formatType(err, fmt, options, out_stream, max_depth);
362354 }
363355 },
364356 .ErrorSet => {
365 try output(context, "error.");
366 return output(context, @errorName(value));
357 try out_stream.writeAll("error.");
358 return out_stream.writeAll(@errorName(value));
367359 },
368360 .Enum => |enumInfo| {
369 if (comptime std.meta.trait.hasFn("format")(T)) {
370 return value.format(fmt, options, context, Errors, output);
371 }
372
373 try output(context, @typeName(T));
361 try out_stream.writeAll(@typeName(T));
374362 if (enumInfo.is_exhaustive) {
375 try output(context, ".");
376 try output(context, @tagName(value));
363 try out_stream.writeAll(".");
364 try out_stream.writeAll(@tagName(value));
377365 } else {
378366 // TODO: when @tagName works on exhaustive enums print known enum strings
379 try output(context, "(");
380 try formatType(@enumToInt(value), fmt, options, context, Errors, output, max_depth);
381 try output(context, ")");
367 try out_stream.writeAll("(");
368 try formatType(@enumToInt(value), fmt, options, out_stream, max_depth);
369 try out_stream.writeAll(")");
382370 }
383371 },
384372 .Union => {
385 if (comptime std.meta.trait.hasFn("format")(T)) {
386 return value.format(fmt, options, context, Errors, output);
387 }
388
389 try output(context, @typeName(T));
373 try out_stream.writeAll(@typeName(T));
390374 if (max_depth == 0) {
391 return output(context, "{ ... }");
375 return out_stream.writeAll("{ ... }");
392376 }
393377 const info = @typeInfo(T).Union;
394378 if (info.tag_type) |UnionTagType| {
395 try output(context, "{ .");
396 try output(context, @tagName(@as(UnionTagType, value)));
397 try output(context, " = ");
379 try out_stream.writeAll("{ .");
380 try out_stream.writeAll(@tagName(@as(UnionTagType, value)));
381 try out_stream.writeAll(" = ");
398382 inline for (info.fields) |u_field| {
399383 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);
401385 }
402386 }
403 try output(context, " }");
387 try out_stream.writeAll(" }");
404388 } else {
405 try format(context, Errors, output, "@{x}", .{@ptrToInt(&value)});
389 try format(out_stream, "@{x}", .{@ptrToInt(&value)});
406390 }
407391 },
408392 .Struct => |StructT| {
409 if (comptime std.meta.trait.hasFn("format")(T)) {
410 return value.format(fmt, options, context, Errors, output);
411 }
412
413 try output(context, @typeName(T));
393 try out_stream.writeAll(@typeName(T));
414394 if (max_depth == 0) {
415 return output(context, "{ ... }");
395 return out_stream.writeAll("{ ... }");
416396 }
417 try output(context, "{");
397 try out_stream.writeAll("{");
418398 inline for (StructT.fields) |f, i| {
419399 if (i == 0) {
420 try output(context, " .");
400 try out_stream.writeAll(" .");
421401 } else {
422 try output(context, ", .");
402 try out_stream.writeAll(", .");
423403 }
424 try output(context, f.name);
425 try output(context, " = ");
426 try formatType(@field(value, f.name), fmt, options, context, Errors, output, max_depth - 1);
404 try out_stream.writeAll(f.name);
405 try out_stream.writeAll(" = ");
406 try formatType(@field(value, f.name), fmt, options, out_stream, max_depth - 1);
427407 }
428 try output(context, " }");
408 try out_stream.writeAll(" }");
429409 },
430410 .Pointer => |ptr_info| switch (ptr_info.size) {
431411 .One => switch (@typeInfo(ptr_info.child)) {
432412 .Array => |info| {
433413 if (info.child == u8) {
434 return formatText(value, fmt, options, context, Errors, output);
414 return formatText(value, fmt, options, out_stream);
435415 }
436 return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
416 return format(out_stream, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
437417 },
438418 .Enum, .Union, .Struct => {
439 return formatType(value.*, fmt, options, context, Errors, output, max_depth);
419 return formatType(value.*, fmt, options, out_stream, max_depth);
440420 },
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) }),
442422 },
443423 .Many, .C => {
444424 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);
446426 }
447427 if (ptr_info.child == u8) {
448428 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);
450430 }
451431 }
452 return format(context, Errors, output, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
432 return format(out_stream, "{}@{x}", .{ @typeName(T.Child), @ptrToInt(value) });
453433 },
454434 .Slice => {
455435 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);
457437 }
458438 if (ptr_info.child == u8) {
459 return formatText(value, fmt, options, context, Errors, output);
439 return formatText(value, fmt, options, out_stream);
460440 }
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) });
462442 },
463443 },
464444 .Array => |info| {
......@@ -473,30 +453,27 @@ pub fn formatType(
473453 .sentinel = null,
474454 },
475455 });
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);
477457 },
478458 .Vector => {
479459 const len = @typeInfo(T).Vector.len;
480 try output(context, "{ ");
460 try out_stream.writeAll("{ ");
481461 var i: usize = 0;
482462 while (i < len) : (i += 1) {
483 try formatValue(value[i], fmt, options, context, Errors, output);
463 try formatValue(value[i], fmt, options, out_stream);
484464 if (i < len - 1) {
485 try output(context, ", ");
465 try out_stream.writeAll(", ");
486466 }
487467 }
488 try output(context, " }");
468 try out_stream.writeAll(" }");
489469 },
490470 .Fn => {
491 return format(context, Errors, output, "{}@{x}", .{ @typeName(T), @ptrToInt(value) });
471 return format(out_stream, "{}@{x}", .{ @typeName(T), @ptrToInt(value) });
492472 },
493 .Type => return output(context, @typeName(T)),
473 .Type => return out_stream.writeAll(@typeName(T)),
494474 .EnumLiteral => {
495 const name = @tagName(value);
496 var buffer: [name.len + 1]u8 = undefined;
497 buffer[0] = '.';
498 std.mem.copy(u8, buffer[1..], name);
499 return formatType(buffer, fmt, options, context, Errors, output, max_depth);
475 const buffer = [_]u8{'.'} ++ @tagName(value);
476 return formatType(buffer, fmt, options, out_stream, max_depth);
500477 },
501478 else => @compileError("Unable to format type '" ++ @typeName(T) ++ "'"),
502479 }
......@@ -506,21 +483,19 @@ fn formatValue(
506483 value: var,
507484 comptime fmt: []const u8,
508485 options: FormatOptions,
509 context: var,
510 comptime Errors: type,
511 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
512) Errors!void {
486 out_stream: var,
487) !void {
513488 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);
515490 } 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);
517492 }
518493
519494 const T = @TypeOf(value);
520495 switch (@typeInfo(T)) {
521 .Float => return formatFloatValue(value, fmt, options, context, Errors, output),
522 .Int, .ComptimeInt => return formatIntValue(value, fmt, options, context, Errors, output),
523 .Bool => return output(context, if (value) "true" else "false"),
496 .Float => return formatFloatValue(value, fmt, options, out_stream),
497 .Int, .ComptimeInt => return formatIntValue(value, fmt, options, out_stream),
498 .Bool => return out_stream.writeAll(if (value) "true" else "false"),
524499 else => comptime unreachable,
525500 }
526501}
......@@ -529,10 +504,8 @@ pub fn formatIntValue(
529504 value: var,
530505 comptime fmt: []const u8,
531506 options: FormatOptions,
532 context: var,
533 comptime Errors: type,
534 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
535) Errors!void {
507 out_stream: var,
508) !void {
536509 comptime var radix = 10;
537510 comptime var uppercase = false;
538511
......@@ -547,7 +520,7 @@ pub fn formatIntValue(
547520 uppercase = false;
548521 } else if (comptime std.mem.eql(u8, fmt, "c")) {
549522 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);
551524 } else {
552525 @compileError("Cannot print integer that is larger than 8 bits as a ascii");
553526 }
......@@ -564,21 +537,19 @@ pub fn formatIntValue(
564537 @compileError("Unknown format string: '" ++ fmt ++ "'");
565538 }
566539
567 return formatInt(int_value, radix, uppercase, options, context, Errors, output);
540 return formatInt(int_value, radix, uppercase, options, out_stream);
568541}
569542
570543fn formatFloatValue(
571544 value: var,
572545 comptime fmt: []const u8,
573546 options: FormatOptions,
574 context: var,
575 comptime Errors: type,
576 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
577) Errors!void {
547 out_stream: var,
548) !void {
578549 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);
580551 } else if (comptime std.mem.eql(u8, fmt, "d")) {
581 return formatFloatDecimal(value, options, context, Errors, output);
552 return formatFloatDecimal(value, options, out_stream);
582553 } else {
583554 @compileError("Unknown format string: '" ++ fmt ++ "'");
584555 }
......@@ -588,17 +559,15 @@ pub fn formatText(
588559 bytes: []const u8,
589560 comptime fmt: []const u8,
590561 options: FormatOptions,
591 context: var,
592 comptime Errors: type,
593 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
594) Errors!void {
562 out_stream: var,
563) !void {
595564 if (fmt.len == 0) {
596 return output(context, bytes);
565 return out_stream.writeAll(bytes);
597566 } else if (comptime std.mem.eql(u8, fmt, "s")) {
598 return formatBuf(bytes, options, context, Errors, output);
567 return formatBuf(bytes, options, out_stream);
599568 } else if (comptime (std.mem.eql(u8, fmt, "x") or std.mem.eql(u8, fmt, "X"))) {
600569 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);
602571 }
603572 return;
604573 } else {
......@@ -609,27 +578,23 @@ pub fn formatText(
609578pub fn formatAsciiChar(
610579 c: u8,
611580 options: FormatOptions,
612 context: var,
613 comptime Errors: type,
614 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
615) Errors!void {
616 return output(context, @as(*const [1]u8, &c)[0..]);
581 out_stream: var,
582) !void {
583 return out_stream.writeAll(@as(*const [1]u8, &c));
617584}
618585
619586pub fn formatBuf(
620587 buf: []const u8,
621588 options: FormatOptions,
622 context: var,
623 comptime Errors: type,
624 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
625) Errors!void {
626 try output(context, buf);
589 out_stream: var,
590) !void {
591 try out_stream.writeAll(buf);
627592
628593 const width = options.width orelse 0;
629594 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};
631596 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);
633598 }
634599}
635600
......@@ -639,40 +604,38 @@ pub fn formatBuf(
639604pub fn formatFloatScientific(
640605 value: var,
641606 options: FormatOptions,
642 context: var,
643 comptime Errors: type,
644 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
645) Errors!void {
607 out_stream: var,
608) !void {
646609 var x = @floatCast(f64, value);
647610
648611 // Errol doesn't handle these special cases.
649612 if (math.signbit(x)) {
650 try output(context, "-");
613 try out_stream.writeAll("-");
651614 x = -x;
652615 }
653616
654617 if (math.isNan(x)) {
655 return output(context, "nan");
618 return out_stream.writeAll("nan");
656619 }
657620 if (math.isPositiveInf(x)) {
658 return output(context, "inf");
621 return out_stream.writeAll("inf");
659622 }
660623 if (x == 0.0) {
661 try output(context, "0");
624 try out_stream.writeAll("0");
662625
663626 if (options.precision) |precision| {
664627 if (precision != 0) {
665 try output(context, ".");
628 try out_stream.writeAll(".");
666629 var i: usize = 0;
667630 while (i < precision) : (i += 1) {
668 try output(context, "0");
631 try out_stream.writeAll("0");
669632 }
670633 }
671634 } else {
672 try output(context, ".0");
635 try out_stream.writeAll(".0");
673636 }
674637
675 try output(context, "e+00");
638 try out_stream.writeAll("e+00");
676639 return;
677640 }
678641
......@@ -682,50 +645,50 @@ pub fn formatFloatScientific(
682645 if (options.precision) |precision| {
683646 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
687650 // {e0} case prints no `.`
688651 if (precision != 0) {
689 try output(context, ".");
652 try out_stream.writeAll(".");
690653
691654 var printed: usize = 0;
692655 if (float_decimal.digits.len > 1) {
693656 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]);
695658 printed += num_digits - 1;
696659 }
697660
698661 while (printed < precision) : (printed += 1) {
699 try output(context, "0");
662 try out_stream.writeAll("0");
700663 }
701664 }
702665 } else {
703 try output(context, float_decimal.digits[0..1]);
704 try output(context, ".");
666 try out_stream.writeAll(float_decimal.digits[0..1]);
667 try out_stream.writeAll(".");
705668 if (float_decimal.digits.len > 1) {
706669 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]);
709672 } else {
710 try output(context, "0");
673 try out_stream.writeAll("0");
711674 }
712675 }
713676
714 try output(context, "e");
677 try out_stream.writeAll("e");
715678 const exp = float_decimal.exp - 1;
716679
717680 if (exp >= 0) {
718 try output(context, "+");
681 try out_stream.writeAll("+");
719682 if (exp > -10 and exp < 10) {
720 try output(context, "0");
683 try out_stream.writeAll("0");
721684 }
722 try formatInt(exp, 10, false, FormatOptions{ .width = 0 }, context, Errors, output);
685 try formatInt(exp, 10, false, FormatOptions{ .width = 0 }, out_stream);
723686 } else {
724 try output(context, "-");
687 try out_stream.writeAll("-");
725688 if (exp > -10 and exp < 10) {
726 try output(context, "0");
689 try out_stream.writeAll("0");
727690 }
728 try formatInt(-exp, 10, false, FormatOptions{ .width = 0 }, context, Errors, output);
691 try formatInt(-exp, 10, false, FormatOptions{ .width = 0 }, out_stream);
729692 }
730693}
731694
......@@ -734,36 +697,34 @@ pub fn formatFloatScientific(
734697pub fn formatFloatDecimal(
735698 value: var,
736699 options: FormatOptions,
737 context: var,
738 comptime Errors: type,
739 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
740) Errors!void {
700 out_stream: var,
701) !void {
741702 var x = @as(f64, value);
742703
743704 // Errol doesn't handle these special cases.
744705 if (math.signbit(x)) {
745 try output(context, "-");
706 try out_stream.writeAll("-");
746707 x = -x;
747708 }
748709
749710 if (math.isNan(x)) {
750 return output(context, "nan");
711 return out_stream.writeAll("nan");
751712 }
752713 if (math.isPositiveInf(x)) {
753 return output(context, "inf");
714 return out_stream.writeAll("inf");
754715 }
755716 if (x == 0.0) {
756 try output(context, "0");
717 try out_stream.writeAll("0");
757718
758719 if (options.precision) |precision| {
759720 if (precision != 0) {
760 try output(context, ".");
721 try out_stream.writeAll(".");
761722 var i: usize = 0;
762723 while (i < precision) : (i += 1) {
763 try output(context, "0");
724 try out_stream.writeAll("0");
764725 }
765726 } else {
766 try output(context, ".0");
727 try out_stream.writeAll(".0");
767728 }
768729 }
769730
......@@ -785,14 +746,14 @@ pub fn formatFloatDecimal(
785746
786747 if (num_digits_whole > 0) {
787748 // 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
790751 var i = num_digits_whole_no_pad;
791752 while (i < num_digits_whole) : (i += 1) {
792 try output(context, "0");
753 try out_stream.writeAll("0");
793754 }
794755 } else {
795 try output(context, "0");
756 try out_stream.writeAll("0");
796757 }
797758
798759 // {.0} special case doesn't want a trailing '.'
......@@ -800,7 +761,7 @@ pub fn formatFloatDecimal(
800761 return;
801762 }
802763
803 try output(context, ".");
764 try out_stream.writeAll(".");
804765
805766 // Keep track of fractional count printed for case where we pre-pad then post-pad with 0's.
806767 var printed: usize = 0;
......@@ -812,7 +773,7 @@ pub fn formatFloatDecimal(
812773
813774 var i: usize = 0;
814775 while (i < zeros_to_print) : (i += 1) {
815 try output(context, "0");
776 try out_stream.writeAll("0");
816777 printed += 1;
817778 }
818779
......@@ -824,14 +785,14 @@ pub fn formatFloatDecimal(
824785 // Remaining fractional portion, zero-padding if insufficient.
825786 assert(precision >= printed);
826787 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]);
828789 return;
829790 } 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..]);
831792 printed += float_decimal.digits.len - num_digits_whole_no_pad;
832793
833794 while (printed < precision) : (printed += 1) {
834 try output(context, "0");
795 try out_stream.writeAll("0");
835796 }
836797 }
837798 } else {
......@@ -843,14 +804,14 @@ pub fn formatFloatDecimal(
843804
844805 if (num_digits_whole > 0) {
845806 // 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
848809 var i = num_digits_whole_no_pad;
849810 while (i < num_digits_whole) : (i += 1) {
850 try output(context, "0");
811 try out_stream.writeAll("0");
851812 }
852813 } else {
853 try output(context, "0");
814 try out_stream.writeAll("0");
854815 }
855816
856817 // Omit `.` if no fractional portion
......@@ -858,7 +819,7 @@ pub fn formatFloatDecimal(
858819 return;
859820 }
860821
861 try output(context, ".");
822 try out_stream.writeAll(".");
862823
863824 // Zero-fill until we reach significant digits or run out of precision.
864825 if (float_decimal.exp < 0) {
......@@ -866,11 +827,11 @@ pub fn formatFloatDecimal(
866827
867828 var i: usize = 0;
868829 while (i < zero_digit_count) : (i += 1) {
869 try output(context, "0");
830 try out_stream.writeAll("0");
870831 }
871832 }
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..]);
874835 }
875836}
876837
......@@ -878,12 +839,10 @@ pub fn formatBytes(
878839 value: var,
879840 options: FormatOptions,
880841 comptime radix: usize,
881 context: var,
882 comptime Errors: type,
883 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
884) Errors!void {
842 out_stream: var,
843) !void {
885844 if (value == 0) {
886 return output(context, "0B");
845 return out_stream.writeAll("0B");
887846 }
888847
889848 const mags_si = " kMGTPEZY";
......@@ -900,10 +859,10 @@ pub fn formatBytes(
900859 else => unreachable,
901860 };
902861
903 try formatFloatDecimal(new_value, options, context, Errors, output);
862 try formatFloatDecimal(new_value, options, out_stream);
904863
905864 if (suffix == ' ') {
906 return output(context, "B");
865 return out_stream.writeAll("B");
907866 }
908867
909868 const buf = switch (radix) {
......@@ -911,7 +870,7 @@ pub fn formatBytes(
911870 1024 => &[_]u8{ suffix, 'i', 'B' },
912871 else => unreachable,
913872 };
914 return output(context, buf);
873 return out_stream.writeAll(buf);
915874}
916875
917876pub fn formatInt(
......@@ -919,10 +878,8 @@ pub fn formatInt(
919878 base: u8,
920879 uppercase: bool,
921880 options: FormatOptions,
922 context: var,
923 comptime Errors: type,
924 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
925) Errors!void {
881 out_stream: var,
882) !void {
926883 const int_value = if (@TypeOf(value) == comptime_int) blk: {
927884 const Int = math.IntFittingRange(value, value);
928885 break :blk @as(Int, value);
......@@ -930,9 +887,9 @@ pub fn formatInt(
930887 value;
931888
932889 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);
934891 } else {
935 return formatIntUnsigned(int_value, base, uppercase, options, context, Errors, output);
892 return formatIntUnsigned(int_value, base, uppercase, options, out_stream);
936893 }
937894}
938895
......@@ -941,10 +898,8 @@ fn formatIntSigned(
941898 base: u8,
942899 uppercase: bool,
943900 options: FormatOptions,
944 context: var,
945 comptime Errors: type,
946 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
947) Errors!void {
901 out_stream: var,
902) !void {
948903 const new_options = FormatOptions{
949904 .width = if (options.width) |w| (if (w == 0) 0 else w - 1) else null,
950905 .precision = options.precision,
......@@ -953,15 +908,15 @@ fn formatIntSigned(
953908 const bit_count = @typeInfo(@TypeOf(value)).Int.bits;
954909 const Uint = std.meta.IntType(false, bit_count);
955910 if (value < 0) {
956 try output(context, "-");
911 try out_stream.writeAll("-");
957912 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);
959914 } 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);
961916 } else {
962 try output(context, "+");
917 try out_stream.writeAll("+");
963918 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);
965920 }
966921}
967922
......@@ -970,10 +925,8 @@ fn formatIntUnsigned(
970925 base: u8,
971926 uppercase: bool,
972927 options: FormatOptions,
973 context: var,
974 comptime Errors: type,
975 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
976) Errors!void {
928 out_stream: var,
929) !void {
977930 assert(base >= 2);
978931 var buf: [math.max(@TypeOf(value).bit_count, 1)]u8 = undefined;
979932 const min_int_bits = comptime math.max(@TypeOf(value).bit_count, @TypeOf(base).bit_count);
......@@ -997,34 +950,23 @@ fn formatIntUnsigned(
997950 const zero_byte: u8 = options.fill;
998951 var leftover_padding = padding - index;
999952 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..]);
1001954 leftover_padding -= 1;
1002955 if (leftover_padding == 0) break;
1003956 }
1004957 mem.set(u8, buf[0..index], options.fill);
1005 return output(context, &buf);
958 return out_stream.writeAll(&buf);
1006959 } else {
1007960 const padded_buf = buf[index - padding ..];
1008961 mem.set(u8, padded_buf[0..padding], options.fill);
1009 return output(context, padded_buf);
962 return out_stream.writeAll(padded_buf);
1010963 }
1011964}
1012965
1013966pub fn formatIntBuf(out_buf: []u8, value: var, base: u8, uppercase: bool, options: FormatOptions) usize {
1014 var context = FormatIntBuf{
1015 .out_buf = out_buf,
1016 .index = 0,
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;
967 var fbs = std.io.fixedBufferStream(out_buf);
968 formatInt(value, base, uppercase, options, fbs.outStream()) catch unreachable;
969 return fbs.pos;
1028970}
1029971
1030972pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) !T {
......@@ -1124,44 +1066,36 @@ fn digitToChar(digit: u8, uppercase: bool) u8 {
11241066 };
11251067}
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
11401069pub const BufPrintError = error{
11411070 /// As much as possible was written to the buffer, but it was too small to fit all the printed bytes.
1142 BufferTooSmall,
1071 NoSpaceLeft,
11431072};
11441073pub fn bufPrint(buf: []u8, comptime fmt: []const u8, args: var) BufPrintError![]u8 {
1145 var context = BufPrintContext{ .remaining = buf };
1146 try format(&context, BufPrintError, bufPrintWrite, fmt, args);
1147 return buf[0 .. buf.len - context.remaining.len];
1074 var fbs = std.io.fixedBufferStream(buf);
1075 try format(fbs.outStream(), fmt, args);
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;
11481084}
11491085
11501086pub const AllocPrintError = error{OutOfMemory};
11511087
11521088pub fn allocPrint(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![]u8 {
1153 var size: usize = 0;
1154 format(&size, error{}, countSize, fmt, args) catch |err| switch (err) {};
1089 const size = math.cast(usize, count(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 };
11551093 const buf = try allocator.alloc(u8, size);
11561094 return bufPrint(buf, fmt, args) catch |err| switch (err) {
1157 error.BufferTooSmall => unreachable, // we just counted the size above
1095 error.NoSpaceLeft => unreachable, // we just counted the size above
11581096 };
11591097}
11601098
1161fn countSize(size: *usize, bytes: []const u8) (error{}!void) {
1162 size.* += bytes.len;
1163}
1164
11651099pub fn allocPrint0(allocator: *mem.Allocator, comptime fmt: []const u8, args: var) AllocPrintError![:0]u8 {
11661100 const result = try allocPrint(allocator, fmt ++ "\x00", args);
11671101 return result[0 .. result.len - 1 :0];
......@@ -1254,20 +1188,17 @@ test "int.padded" {
12541188test "buffer" {
12551189 {
12561190 var buf1: [32]u8 = undefined;
1257 var context = BufPrintContext{ .remaining = buf1[0..] };
1258 try formatType(1234, "", FormatOptions{}, &context, error{BufferTooSmall}, bufPrintWrite, default_max_depth);
1259 var res = buf1[0 .. buf1.len - context.remaining.len];
1260 std.testing.expect(mem.eql(u8, res, "1234"));
1261
1262 context = BufPrintContext{ .remaining = buf1[0..] };
1263 try formatType('a', "c", FormatOptions{}, &context, error{BufferTooSmall}, bufPrintWrite, default_max_depth);
1264 res = buf1[0 .. buf1.len - context.remaining.len];
1265 std.testing.expect(mem.eql(u8, res, "a"));
1266
1267 context = BufPrintContext{ .remaining = buf1[0..] };
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"));
1191 var fbs = std.io.fixedBufferStream(&buf1);
1192 try formatType(1234, "", FormatOptions{}, fbs.outStream(), default_max_depth);
1193 std.testing.expect(mem.eql(u8, fbs.getWritten(), "1234"));
1194
1195 fbs.reset();
1196 try formatType('a', "c", FormatOptions{}, fbs.outStream(), default_max_depth);
1197 std.testing.expect(mem.eql(u8, fbs.getWritten(), "a"));
1198
1199 fbs.reset();
1200 try formatType(0b1100, "b", FormatOptions{}, fbs.outStream(), default_max_depth);
1201 std.testing.expect(mem.eql(u8, fbs.getWritten(), "1100"));
12711202 }
12721203}
12731204
......@@ -1452,14 +1383,12 @@ test "custom" {
14521383 self: SelfType,
14531384 comptime fmt: []const u8,
14541385 options: FormatOptions,
1455 context: var,
1456 comptime Errors: type,
1457 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
1458 ) Errors!void {
1386 out_stream: var,
1387 ) !void {
14591388 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 });
14611390 } 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 });
14631392 } else {
14641393 @compileError("Unknown format character: '" ++ fmt ++ "'");
14651394 }
......@@ -1643,10 +1572,10 @@ test "hexToBytes" {
16431572test "formatIntValue with comptime_int" {
16441573 const value: comptime_int = 123456789123456789;
16451574
1646 var buf = std.ArrayList(u8).init(std.testing.allocator);
1647 defer buf.deinit();
1648 try formatIntValue(value, "", FormatOptions{}, &buf, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice);
1649 std.testing.expect(mem.eql(u8, buf.toSliceConst(), "123456789123456789"));
1575 var buf: [20]u8 = undefined;
1576 var fbs = std.io.fixedBufferStream(&buf);
1577 try formatIntValue(value, "", FormatOptions{}, fbs.outStream());
1578 std.testing.expect(mem.eql(u8, fbs.getWritten(), "123456789123456789"));
16501579}
16511580
16521581test "formatType max_depth" {
......@@ -1659,12 +1588,10 @@ test "formatType max_depth" {
16591588 self: SelfType,
16601589 comptime fmt: []const u8,
16611590 options: FormatOptions,
1662 context: var,
1663 comptime Errors: type,
1664 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
1665 ) Errors!void {
1591 out_stream: var,
1592 ) !void {
16661593 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 });
16681595 } else {
16691596 @compileError("Unknown format string: '" ++ fmt ++ "'");
16701597 }
......@@ -1698,25 +1625,22 @@ test "formatType max_depth" {
16981625 inst.a = &inst;
16991626 inst.tu.ptr = &inst.tu;
17001627
1701 var buf0 = std.ArrayList(u8).init(std.testing.allocator);
1702 defer buf0.deinit();
1703 try formatType(inst, "", FormatOptions{}, &buf0, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 0);
1704 std.testing.expect(mem.eql(u8, buf0.toSlice(), "S{ ... }"));
1705
1706 var buf1 = std.ArrayList(u8).init(std.testing.allocator);
1707 defer buf1.deinit();
1708 try formatType(inst, "", FormatOptions{}, &buf1, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 1);
1709 std.testing.expect(mem.eql(u8, buf1.toSlice(), "S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }"));
1710
1711 var buf2 = std.ArrayList(u8).init(std.testing.allocator);
1712 defer buf2.deinit();
1713 try formatType(inst, "", FormatOptions{}, &buf2, @TypeOf(std.ArrayList(u8).appendSlice).ReturnType.ErrorSet, std.ArrayList(u8).appendSlice, 2);
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) }"));
1715
1716 var buf3 = std.ArrayList(u8).init(std.testing.allocator);
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) }"));
1628 var buf: [1000]u8 = undefined;
1629 var fbs = std.io.fixedBufferStream(&buf);
1630 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 0);
1631 std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ ... }"));
1632
1633 fbs.reset();
1634 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 1);
1635 std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }"));
1636
1637 fbs.reset();
1638 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 2);
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) }"));
1640
1641 fbs.reset();
1642 try formatType(inst, "", FormatOptions{}, fbs.outStream(), 3);
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) }"));
17201644}
17211645
17221646test "positional" {
lib/std/fs.zig+17-24
......@@ -96,6 +96,7 @@ pub fn updateFile(source_path: []const u8, dest_path: []const u8) !PrevStatus {
9696/// atime, and mode of the source file so that the next call to `updateFile` will not need a copy.
9797/// Returns the previous status of the file before updating.
9898/// If any of the directories do not exist for dest_path, they are created.
99/// TODO rework this to integrate with Dir
99100pub fn updateFileMode(source_path: []const u8, dest_path: []const u8, mode: ?File.Mode) !PrevStatus {
100101 const my_cwd = cwd();
101102
......@@ -141,29 +142,25 @@ pub fn updateFileMode(source_path: []const u8, dest_path: []const u8, mode: ?Fil
141142/// there is a possibility of power loss or application termination leaving temporary files present
142143/// in the same directory as dest_path.
143144/// Destination file will have the same mode as the source file.
145/// TODO rework this to integrate with Dir
144146pub fn copyFile(source_path: []const u8, dest_path: []const u8) !void {
145147 var in_file = try cwd().openFile(source_path, .{});
146148 defer in_file.close();
147149
148 const mode = try in_file.mode();
149 const in_stream = &in_file.inStream().stream;
150 const stat = try in_file.stat();
150151
151 var atomic_file = try AtomicFile.init(dest_path, mode);
152 var atomic_file = try AtomicFile.init(dest_path, stat.mode);
152153 defer atomic_file.deinit();
153154
154 var buf: [mem.page_size]u8 = undefined;
155 while (true) {
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 }
155 try atomic_file.file.writeFileAll(in_file, .{ .in_len = stat.size });
156 return atomic_file.finish();
162157}
163158
164/// Guaranteed to be atomic. However until https://patchwork.kernel.org/patch/9636735/ is
165/// merged and readily available,
159/// Guaranteed to be atomic.
160/// On Linux, until https://patchwork.kernel.org/patch/9636735/ is merged and readily available,
166161/// 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
167164pub fn copyFileMode(source_path: []const u8, dest_path: []const u8, mode: File.Mode) !void {
168165 var in_file = try cwd().openFile(source_path, .{});
169166 defer in_file.close();
......@@ -171,14 +168,8 @@ pub fn copyFileMode(source_path: []const u8, dest_path: []const u8, mode: File.M
171168 var atomic_file = try AtomicFile.init(dest_path, mode);
172169 defer atomic_file.deinit();
173170
174 var buf: [mem.page_size * 6]u8 = undefined;
175 while (true) {
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 }
171 try atomic_file.file.writeFileAll(in_file, .{});
172 return atomic_file.finish();
182173}
183174
184175/// TODO update this API to avoid a getrandom syscall for every operation. It
......@@ -266,7 +257,7 @@ const default_new_dir_mode = 0o755;
266257/// Asserts that the path is absolute. See `Dir.makeDir` for a function that operates
267258/// on both absolute and relative paths.
268259pub fn makeDirAbsolute(absolute_path: []const u8) !void {
269 assert(path.isAbsoluteC(absolute_path));
260 assert(path.isAbsolute(absolute_path));
270261 return os.mkdir(absolute_path, default_new_dir_mode);
271262}
272263
......@@ -1150,7 +1141,7 @@ pub const Dir = struct {
11501141 const buf = try allocator.alignedAlloc(u8, A, size);
11511142 errdefer allocator.free(buf);
11521143
1153 try file.inStream().stream.readNoEof(buf);
1144 try file.inStream().readNoEof(buf);
11541145 return buf;
11551146 }
11561147
......@@ -1365,7 +1356,7 @@ pub const Dir = struct {
13651356 else
13661357 @as(u32, os.F_OK);
13671358 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)
13691360 else
13701361 os.faccessatZ(self.fd, sub_path, os_mode, 0);
13711362 return result;
......@@ -1669,6 +1660,8 @@ pub fn realpathAlloc(allocator: *Allocator, pathname: []const u8) ![]u8 {
16691660}
16701661
16711662test "" {
1663 _ = makeDirAbsolute;
1664 _ = makeDirAbsoluteZ;
16721665 _ = @import("fs/path.zig");
16731666 _ = @import("fs/file.zig");
16741667 _ = @import("fs/get_app_data_dir.zig");
lib/std/fs/file.zig+72-84
......@@ -71,7 +71,7 @@ pub const File = struct {
7171 if (need_async_thread and self.io_mode == .blocking and !self.async_block_allowed) {
7272 std.event.Loop.instance.?.close(self.handle);
7373 } else {
74 return os.close(self.handle);
74 os.close(self.handle);
7575 }
7676 }
7777
......@@ -99,6 +99,14 @@ pub const File = struct {
9999 return false;
100100 }
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
102110 pub const SeekError = os.SeekError;
103111
104112 /// Repositions read/write file offset relative to the current offset.
......@@ -145,6 +153,16 @@ pub const File = struct {
145153 }
146154
147155 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
148166 size: u64,
149167 mode: Mode,
150168
......@@ -174,6 +192,7 @@ pub const File = struct {
174192 else => return windows.unexpectedStatus(rc),
175193 }
176194 return Stat{
195 .inode = info.InternalInformation.IndexNumber,
177196 .size = @bitCast(u64, info.StandardInformation.EndOfFile),
178197 .mode = 0,
179198 .atime = windows.fromSysTime(info.BasicInformation.LastAccessTime),
......@@ -187,6 +206,7 @@ pub const File = struct {
187206 const mtime = st.mtime();
188207 const ctime = st.ctime();
189208 return Stat{
209 .inode = st.ino,
190210 .size = @bitCast(u64, st.size),
191211 .mode = st.mode,
192212 .atime = @as(i64, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,
......@@ -238,11 +258,16 @@ pub const File = struct {
238258 }
239259 }
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 {
242264 var index: usize = 0;
243 while (index < buffer.len) {
244 index += try self.read(buffer[index..]);
265 while (index != buffer.len) {
266 const amt = try self.read(buffer[index..]);
267 if (amt == 0) break;
268 index += amt;
245269 }
270 return index;
246271 }
247272
248273 pub fn pread(self: File, buffer: []u8, offset: u64) PReadError!usize {
......@@ -253,11 +278,16 @@ pub const File = struct {
253278 }
254279 }
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 {
257284 var index: usize = 0;
258 while (index < buffer.len) {
259 index += try self.pread(buffer[index..], offset + index);
285 while (index != buffer.len) {
286 const amt = try self.pread(buffer[index..], offset + index);
287 if (amt == 0) break;
288 index += amt;
260289 }
290 return index;
261291 }
262292
263293 pub fn readv(self: File, iovecs: []const os.iovec) ReadError!usize {
......@@ -268,19 +298,27 @@ pub const File = struct {
268298 }
269299 }
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.
271304 /// The `iovecs` parameter is mutable because this function needs to mutate the fields in
272305 /// 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 {
274307 if (iovecs.len == 0) return;
275308
276309 var i: usize = 0;
310 var off: usize = 0;
277311 while (true) {
278312 var amt = try self.readv(iovecs[i..]);
313 var eof = amt == 0;
314 off += amt;
279315 while (amt >= iovecs[i].iov_len) {
280316 amt -= iovecs[i].iov_len;
281317 i += 1;
282 if (i >= iovecs.len) return;
318 if (i >= iovecs.len) return off;
319 eof = false;
283320 }
321 if (eof) return off;
284322 iovecs[i].iov_base += amt;
285323 iovecs[i].iov_len -= amt;
286324 }
......@@ -294,6 +332,9 @@ pub const File = struct {
294332 }
295333 }
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.
297338 /// The `iovecs` parameter is mutable because this function needs to mutate the fields in
298339 /// order to handle partial reads from the underlying OS layer.
299340 pub fn preadvAll(self: File, iovecs: []const os.iovec, offset: u64) PReadError!void {
......@@ -303,12 +344,15 @@ pub const File = struct {
303344 var off: usize = 0;
304345 while (true) {
305346 var amt = try self.preadv(iovecs[i..], offset + off);
347 var eof = amt == 0;
306348 off += amt;
307349 while (amt >= iovecs[i].iov_len) {
308350 amt -= iovecs[i].iov_len;
309351 i += 1;
310 if (i >= iovecs.len) return;
352 if (i >= iovecs.len) return off;
353 eof = false;
311354 }
355 if (eof) return off;
312356 iovecs[i].iov_base += amt;
313357 iovecs[i].iov_len -= amt;
314358 }
......@@ -484,85 +528,29 @@ pub const File = struct {
484528 }
485529 }
486530
487 pub fn inStream(file: File) InStream {
488 return InStream{
489 .file = file,
490 .stream = InStream.Stream{ .readFn = InStream.readFn },
491 };
531 pub const InStream = io.InStream(File, ReadError, read);
532
533 pub fn inStream(file: File) io.InStream(File, ReadError, read) {
534 return .{ .context = file };
492535 }
493536
537 pub const OutStream = io.OutStream(File, WriteError, write);
538
494539 pub fn outStream(file: File) OutStream {
495 return OutStream{
496 .file = file,
497 .stream = OutStream.Stream{ .writeFn = OutStream.writeFn },
498 };
540 return .{ .context = file };
499541 }
500542
543 pub const SeekableStream = io.SeekableStream(
544 File,
545 SeekError,
546 GetPosError,
547 seekTo,
548 seekBy,
549 getPos,
550 getEndPos,
551 );
552
501553 pub fn seekableStream(file: File) SeekableStream {
502 return SeekableStream{
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 };
554 return .{ .context = file };
511555 }
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 };
568556};
lib/std/heap.zig+1
......@@ -10,6 +10,7 @@ const c = std.c;
1010const maxInt = std.math.maxInt;
1111
1212pub const LoggingAllocator = @import("heap/logging_allocator.zig").LoggingAllocator;
13pub const loggingAllocator = @import("heap/logging_allocator.zig").loggingAllocator;
1314
1415const Allocator = mem.Allocator;
1516
lib/std/heap/logging_allocator.zig+51-45
......@@ -1,63 +1,69 @@
11const std = @import("../std.zig");
22const Allocator = std.mem.Allocator;
33
4const AnyErrorOutStream = std.io.OutStream(anyerror);
5
64/// This allocator is used in front of another allocator and logs to the provided stream
75/// on every call to the allocator. Stream errors are ignored.
86/// If https://github.com/ziglang/zig/issues/2586 is implemented, this API can be improved.
9pub const LoggingAllocator = struct {
10 allocator: Allocator,
11 parent_allocator: *Allocator,
12 out_stream: *AnyErrorOutStream,
7pub fn LoggingAllocator(comptime OutStreamType: type) type {
8 return struct {
9 allocator: Allocator,
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 {
17 return Self{
18 .allocator = Allocator{
19 .reallocFn = realloc,
20 .shrinkFn = shrink,
21 },
22 .parent_allocator = parent_allocator,
23 .out_stream = out_stream,
24 };
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 {};
15 pub fn init(parent_allocator: *Allocator, out_stream: OutStreamType) Self {
16 return Self{
17 .allocator = Allocator{
18 .reallocFn = realloc,
19 .shrinkFn = shrink,
20 },
21 .parent_allocator = parent_allocator,
22 .out_stream = out_stream,
23 };
3324 }
34 const result = self.parent_allocator.reallocFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
35 if (result) |buff| {
36 self.out_stream.print("success!\n", .{}) catch {};
37 } else |err| {
38 self.out_stream.print("failure!\n", .{}) catch {};
25
26 fn realloc(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) ![]u8 {
27 const self = @fieldParentPtr(Self, "allocator", allocator);
28 if (old_mem.len == 0) {
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;
3940 }
40 return result;
41 }
4241
43 fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
44 const self = @fieldParentPtr(Self, "allocator", allocator);
45 const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
46 if (new_size == 0) {
47 self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {};
48 } else {
49 self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {};
42 fn shrink(allocator: *Allocator, old_mem: []u8, old_align: u29, new_size: usize, new_align: u29) []u8 {
43 const self = @fieldParentPtr(Self, "allocator", allocator);
44 const result = self.parent_allocator.shrinkFn(self.parent_allocator, old_mem, old_align, new_size, new_align);
45 if (new_size == 0) {
46 self.out_stream.print("free of {} bytes success!\n", .{old_mem.len}) catch {};
47 } else {
48 self.out_stream.print("shrink from {} bytes to {} bytes success!\n", .{ old_mem.len, new_size }) catch {};
49 }
50 return result;
5051 }
51 return result;
52 }
53};
52 };
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
5562test "LoggingAllocator" {
5663 var buf: [255]u8 = undefined;
57 var slice_stream = std.io.SliceOutStream.init(buf[0..]);
58 const stream = &slice_stream.stream;
64 var fbs = std.io.fixedBufferStream(&buf);
5965
60 const allocator = &LoggingAllocator.init(std.testing.allocator, @ptrCast(*AnyErrorOutStream, stream)).allocator;
66 const allocator = &loggingAllocator(std.testing.allocator, fbs.outStream()).allocator;
6167
6268 const ptr = try allocator.alloc(u8, 10);
6369 allocator.free(ptr);
......@@ -66,5 +72,5 @@ test "LoggingAllocator" {
6672 \\allocation of 10 success!
6773 \\free of 10 bytes success!
6874 \\
69 , slice_stream.getWritten());
75 , fbs.getWritten());
7076}
lib/std/http/headers.zig+6-8
......@@ -350,15 +350,13 @@ pub const Headers = struct {
350350 self: Self,
351351 comptime fmt: []const u8,
352352 options: std.fmt.FormatOptions,
353 context: var,
354 comptime Errors: type,
355 output: fn (@TypeOf(context), []const u8) Errors!void,
356 ) Errors!void {
353 out_stream: var,
354 ) !void {
357355 for (self.toSlice()) |entry| {
358 try output(context, entry.name);
359 try output(context, ": ");
360 try output(context, entry.value);
361 try output(context, "\n");
356 try out_stream.writeAll(entry.name);
357 try out_stream.writeAll(": ");
358 try out_stream.writeAll(entry.value);
359 try out_stream.writeAll("\n");
362360 }
363361 }
364362};
lib/std/io.zig+39-1020
......@@ -4,17 +4,13 @@ const root = @import("root");
44const c = std.c;
55
66const math = std.math;
7const debug = std.debug;
8const assert = debug.assert;
7const assert = std.debug.assert;
98const os = std.os;
109const fs = std.fs;
1110const mem = std.mem;
1211const meta = std.meta;
1312const trait = meta.trait;
14const Buffer = std.Buffer;
15const fmt = std.fmt;
1613const File = std.fs.File;
17const testing = std.testing;
1814
1915pub const Mode = enum {
2016 /// I/O operates normally, waiting for the operating system syscalls to complete.
......@@ -92,1045 +88,68 @@ pub fn getStdIn() File {
9288 };
9389}
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;
9891pub const InStream = @import("io/in_stream.zig").InStream;
9992pub 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`.
102pub fn writeFile(path: []const u8, data: []const u8) !void {
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 }
95pub const BufferedOutStream = @import("io/buffered_out_stream.zig").BufferedOutStream;
96pub const bufferedOutStream = @import("io/buffered_out_stream.zig").bufferedOutStream;
32697
327 /// Reads `bits` bits from the stream and returns a specified unsigned int type
328 /// containing them in the least significant end. The number of bits successfully
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));
98pub const BufferedInStream = @import("io/buffered_in_stream.zig").BufferedInStream;
99pub const bufferedInStream = @import("io/buffered_in_stream.zig").bufferedInStream;
332100
333 //by extending the buffer to a minimum of u8 we can cover a number of edge cases
334 // related to shifting and casting.
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);
101pub const PeekStream = @import("io/peek_stream.zig").PeekStream;
102pub const peekStream = @import("io/peek_stream.zig").peekStream;
342103
343 out_bits.* = @as(usize, 0);
344 if (U == u0 or bits == 0) return 0;
345 var out_buffer = @as(Buf, 0);
104pub const FixedBufferStream = @import("io/fixed_buffer_stream.zig").FixedBufferStream;
105pub const fixedBufferStream = @import("io/fixed_buffer_stream.zig").fixedBufferStream;
346106
347 if (self.bit_count > 0) {
348 const n = if (self.bit_count >= bits) @intCast(u3, bits) else self.bit_count;
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
107pub const COutStream = @import("io/c_out_stream.zig").COutStream;
108pub const cOutStream = @import("io/c_out_stream.zig").cOutStream;
365109
366 //copy bytes until we have enough bits, then leave the rest in bit_buffer
367 while (out_bits.* < bits) {
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 };
110pub const CountingOutStream = @import("io/counting_out_stream.zig").CountingOutStream;
111pub const countingOutStream = @import("io/counting_out_stream.zig").countingOutStream;
377112
378 switch (endian) {
379 .Big => {
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 }
113pub const BitInStream = @import("io/bit_in_stream.zig").BitInStream;
114pub const bitInStream = @import("io/bit_in_stream.zig").bitInStream;
387115
388 const shift = @intCast(u3, u8_bit_count - n);
389 out_buffer <<= @intCast(BufShift, n);
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 }
116pub const BitOutStream = @import("io/bit_out_stream.zig").BitOutStream;
117pub const bitOutStream = @import("io/bit_out_stream.zig").bitOutStream;
401118
402 const shift = @intCast(u3, u8_bit_count - n);
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 }
119pub const Packing = @import("io/serialization.zig").Packing;
411120
412 return @intCast(U, out_buffer);
413 }
121pub const Serializer = @import("io/serialization.zig").Serializer;
122pub const serializer = @import("io/serialization.zig").serializer;
414123
415 pub fn alignToByte(self: *Self) void {
416 self.bit_buffer = 0;
417 self.bit_count = 0;
418 }
124pub const Deserializer = @import("io/serialization.zig").Deserializer;
125pub const deserializer = @import("io/serialization.zig").deserializer;
419126
420 pub fn read(self_stream: *Stream, buffer: []u8) Error!usize {
421 var self = @fieldParentPtr(Self, "stream", self_stream);
127pub const BufferedAtomicFile = @import("io/buffered_atomic_file.zig").BufferedAtomicFile;
422128
423 var out_bits: usize = undefined;
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 }
129pub const StreamSource = @import("io/stream_source.zig").StreamSource;
434130
435 return self.in_stream.read(buffer);
436 }
437 };
131/// Deprecated; use `std.fs.Dir.writeFile`.
132pub fn writeFile(path: []const u8, data: []const u8) !void {
133 return fs.cwd().writeFile(path, data);
438134}
439135
440/// This is a simple OutStream that writes to a fixed buffer. If the returned number
441/// of bytes written is less than requested, the buffer is full.
442/// Returns error.OutOfMemory when no bytes would be written.
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());
136/// Deprecated; use `std.fs.Dir.readFileAlloc`.
137pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 {
138 return fs.cwd().readFileAlloc(allocator, path, math.maxInt(usize));
496139}
497140
498var null_out_stream_state = NullOutStream.init();
499pub const null_out_stream = &null_out_stream_state.stream;
500
501141/// An OutStream that doesn't write to anything.
502pub const NullOutStream = struct {
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}
142pub const null_out_stream = @as(NullOutStream, .{ .context = {} });
562143
563pub fn BufferedOutStream(comptime Error: type) type {
564 return BufferedOutStreamCustom(mem.page_size, Error);
144const NullOutStream = OutStream(void, error{}, dummyWrite);
145fn dummyWrite(context: void, data: []const u8) error{}!usize {
146 return data.len;
565147}
566148
567pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamError: type) type {
568 return struct {
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 };
149test "null_out_stream" {
150 null_out_stream.writeAll("yay" ** 10) catch |err| switch (err) {};
981151}
982152
983/// Creates a serializer that serializes types to any stream.
984/// If `is_packed` is true, the data will be bit-packed into the stream.
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 }
153test "" {
154 _ = @import("io/test.zig");
1136155}
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 @@
11const std = @import("../std.zig");
2const os = std.os;
3const OutStream = std.io.OutStream;
4const builtin = @import("builtin");
2const builtin = std.builtin;
3const io = std.io;
4const testing = std.testing;
55
6/// TODO make a proposal to make `std.fs.File` use *FILE when linking libc and this just becomes
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);
6pub const COutStream = io.OutStream(*std.c.FILE, std.fs.File.WriteError, cOutStreamWrite);
127
13 stream: Stream,
14 c_file: *std.c.FILE,
8pub fn cOutStream(c_file: *std.c.FILE) COutStream {
9 return .{ .context = c_file };
10}
1511
16 pub fn init(c_file: *std.c.FILE) COutStream {
17 return COutStream{
18 .c_file = c_file,
19 .stream = Stream{ .writeFn = writeFn },
20 };
12fn cOutStreamWrite(c_file: *std.c.FILE, bytes: []const u8) std.fs.File.WriteError!usize {
13 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, c_file);
14 if (amt_written >= 0) return amt_written;
15 switch (std.c._errno().*) {
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)),
2129 }
30}
2231
23 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
24 const self = @fieldParentPtr(COutStream, "stream", out_stream);
25 const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, self.c_file);
26 if (amt_written >= 0) return amt_written;
27 switch (std.c._errno().*) {
28 0 => unreachable,
29 os.EINVAL => unreachable,
30 os.EFAULT => unreachable,
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 }
32test "" {
33 if (!builtin.link_libc) return error.SkipZigTest;
34
35 const filename = "tmp_io_test_file.txt";
36 const out_file = std.c.fopen(filename, "w") orelse return error.UnableToOpenTestFile;
37 defer {
38 _ = std.c.fclose(out_file);
39 fs.cwd().deleteFileC(filename) catch {};
4240 }
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 @@
11const std = @import("../std.zig");
2const builtin = @import("builtin");
3const root = @import("root");
2const builtin = std.builtin;
43const math = std.math;
54const assert = std.debug.assert;
65const mem = std.mem;
76const Buffer = std.Buffer;
87const testing = std.testing;
98
10pub const default_stack_size = 1 * 1024 * 1024;
11pub const stack_size: usize = if (@hasDecl(root, "stack_size_std_io_InStream"))
12 root.stack_size_std_io_InStream
13else
14 default_stack_size;
15
16pub fn InStream(comptime ReadError: type) type {
9pub fn InStream(
10 comptime Context: type,
11 comptime ReadError: type,
12 /// Returns the number of bytes read. It may be less than buffer.len.
13 /// If the number of bytes read is 0, it means end of stream.
14 /// End of stream is not an error condition.
15 comptime readFn: fn (context: Context, buffer: []u8) ReadError!usize,
16) type {
1717 return struct {
18 const Self = @This();
1918 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.
26 /// If the number of bytes read is 0, it means end of stream.
27 /// End of stream is not an error condition.
28 readFn: ReadFn,
20 context: Context,
21
22 const Self = @This();
2923
3024 /// Returns the number of bytes read. It may be less than buffer.len.
3125 /// If the number of bytes read is 0, it means end of stream.
3226 /// End of stream is not an error condition.
33 pub fn read(self: *Self, buffer: []u8) Error!usize {
34 if (std.io.is_async) {
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 }
27 pub fn read(self: Self, buffer: []u8) Error!usize {
28 return readFn(self.context, buffer);
4229 }
4330
44 /// Deprecated: use `readAll`.
45 pub const readFull = readAll;
46
47 /// Returns the number of bytes read. If the number read is smaller than buf.len, it
31 /// Returns the number of bytes read. If the number read is smaller than `buffer.len`, it
4832 /// means the stream reached the end. Reaching the end of a stream is not an error
4933 /// condition.
50 pub fn readAll(self: *Self, buffer: []u8) Error!usize {
34 pub fn readAll(self: Self, buffer: []u8) Error!usize {
5135 var index: usize = 0;
5236 while (index != buffer.len) {
5337 const amt = try self.read(buffer[index..]);
......@@ -59,13 +43,13 @@ pub fn InStream(comptime ReadError: type) type {
5943
6044 /// Returns the number of bytes read. If the number read would be smaller than buf.len,
6145 /// error.EndOfStream is returned instead.
62 pub fn readNoEof(self: *Self, buf: []u8) !void {
46 pub fn readNoEof(self: Self, buf: []u8) !void {
6347 const amt_read = try self.readAll(buf);
6448 if (amt_read < buf.len) return error.EndOfStream;
6549 }
6650
6751 /// 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 {
6953 buffer.list.shrink(0);
7054 try self.readAllArrayList(&buffer.list, max_size);
7155 errdefer buffer.shrink(0);
......@@ -75,7 +59,7 @@ pub fn InStream(comptime ReadError: type) type {
7559 /// Appends to the `std.ArrayList` contents by reading from the stream until end of stream is found.
7660 /// If the number of bytes appended would exceed `max_append_size`, `error.StreamTooLong` is returned
7761 /// 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 {
7963 try array_list.ensureCapacity(math.min(max_append_size, 4096));
8064 const original_len = array_list.len;
8165 var start_index: usize = original_len;
......@@ -104,7 +88,7 @@ pub fn InStream(comptime ReadError: type) type {
10488 /// memory would be greater than `max_size`, returns `error.StreamTooLong`.
10589 /// Caller owns returned memory.
10690 /// 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 {
10892 var array_list = std.ArrayList(u8).init(allocator);
10993 defer array_list.deinit();
11094 try self.readAllArrayList(&array_list, max_size);
......@@ -116,7 +100,7 @@ pub fn InStream(comptime ReadError: type) type {
116100 /// If the `std.ArrayList` length would exceed `max_size`, `error.StreamTooLong` is returned and the
117101 /// `std.ArrayList` is populated with `max_size` bytes from the stream.
118102 pub fn readUntilDelimiterArrayList(
119 self: *Self,
103 self: Self,
120104 array_list: *std.ArrayList(u8),
121105 delimiter: u8,
122106 max_size: usize,
......@@ -142,7 +126,7 @@ pub fn InStream(comptime ReadError: type) type {
142126 /// Caller owns returned memory.
143127 /// If this function returns an error, the contents from the stream read so far are lost.
144128 pub fn readUntilDelimiterAlloc(
145 self: *Self,
129 self: Self,
146130 allocator: *mem.Allocator,
147131 delimiter: u8,
148132 max_size: usize,
......@@ -159,7 +143,7 @@ pub fn InStream(comptime ReadError: type) type {
159143 /// function is called again after that, returns null.
160144 /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
161145 /// 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 {
163147 var index: usize = 0;
164148 while (true) {
165149 const byte = self.readByte() catch |err| switch (err) {
......@@ -184,7 +168,7 @@ pub fn InStream(comptime ReadError: type) type {
184168 /// Reads from the stream until specified byte is found, discarding all data,
185169 /// including the delimiter.
186170 /// 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 {
188172 while (true) {
189173 const byte = self.readByte() catch |err| switch (err) {
190174 error.EndOfStream => return,
......@@ -195,7 +179,7 @@ pub fn InStream(comptime ReadError: type) type {
195179 }
196180
197181 /// Reads 1 byte from the stream or returns `error.EndOfStream`.
198 pub fn readByte(self: *Self) !u8 {
182 pub fn readByte(self: Self) !u8 {
199183 var result: [1]u8 = undefined;
200184 const amt_read = try self.read(result[0..]);
201185 if (amt_read < 1) return error.EndOfStream;
......@@ -203,43 +187,43 @@ pub fn InStream(comptime ReadError: type) type {
203187 }
204188
205189 /// Same as `readByte` except the returned byte is signed.
206 pub fn readByteSigned(self: *Self) !i8 {
190 pub fn readByteSigned(self: Self) !i8 {
207191 return @bitCast(i8, try self.readByte());
208192 }
209193
210194 /// 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 {
212196 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
213197 try self.readNoEof(bytes[0..]);
214198 return mem.readIntNative(T, &bytes);
215199 }
216200
217201 /// 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 {
219203 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
220204 try self.readNoEof(bytes[0..]);
221205 return mem.readIntForeign(T, &bytes);
222206 }
223207
224 pub fn readIntLittle(self: *Self, comptime T: type) !T {
208 pub fn readIntLittle(self: Self, comptime T: type) !T {
225209 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
226210 try self.readNoEof(bytes[0..]);
227211 return mem.readIntLittle(T, &bytes);
228212 }
229213
230 pub fn readIntBig(self: *Self, comptime T: type) !T {
214 pub fn readIntBig(self: Self, comptime T: type) !T {
231215 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
232216 try self.readNoEof(bytes[0..]);
233217 return mem.readIntBig(T, &bytes);
234218 }
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 {
237221 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
238222 try self.readNoEof(bytes[0..]);
239223 return mem.readInt(T, &bytes, endian);
240224 }
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 {
243227 assert(size <= @sizeOf(ReturnType));
244228 var bytes_buf: [@sizeOf(ReturnType)]u8 = undefined;
245229 const bytes = bytes_buf[0..size];
......@@ -247,14 +231,14 @@ pub fn InStream(comptime ReadError: type) type {
247231 return mem.readVarInt(ReturnType, bytes, endian);
248232 }
249233
250 pub fn skipBytes(self: *Self, num_bytes: u64) !void {
234 pub fn skipBytes(self: Self, num_bytes: u64) !void {
251235 var i: u64 = 0;
252236 while (i < num_bytes) : (i += 1) {
253237 _ = try self.readByte();
254238 }
255239 }
256240
257 pub fn readStruct(self: *Self, comptime T: type) !T {
241 pub fn readStruct(self: Self, comptime T: type) !T {
258242 // Only extern and packed structs have defined in-memory layout.
259243 comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);
260244 var res: [1]T = undefined;
......@@ -265,7 +249,7 @@ pub fn InStream(comptime ReadError: type) type {
265249 /// Reads an integer with the same size as the given enum's tag type. If the integer matches
266250 /// an enum tag, casts the integer to the enum tag and returns it. Otherwise, returns an error.
267251 /// 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 {
269253 const E = error{
270254 /// An integer was read, but it did not match any of the tags in the supplied enum.
271255 InvalidValue,
......@@ -286,8 +270,7 @@ pub fn InStream(comptime ReadError: type) type {
286270
287271test "InStream" {
288272 var buf = "a\x02".*;
289 var slice_stream = std.io.SliceInStream.init(&buf);
290 const in_stream = &slice_stream.stream;
273 const in_stream = std.io.fixedBufferStream(&buf).inStream();
291274 testing.expect((try in_stream.readByte()) == 'a');
292275 testing.expect((try in_stream.readEnum(enum(u8) {
293276 a = 0,
lib/std/io/out_stream.zig+33-42
......@@ -1,94 +1,85 @@
11const std = @import("../std.zig");
2const builtin = @import("builtin");
3const root = @import("root");
2const builtin = std.builtin;
43const mem = std.mem;
54
6pub const default_stack_size = 1 * 1024 * 1024;
7pub const stack_size: usize = if (@hasDecl(root, "stack_size_std_io_OutStream"))
8 root.stack_size_std_io_OutStream
9else
10 default_stack_size;
11
12pub fn OutStream(comptime WriteError: type) type {
5pub fn OutStream(
6 comptime Context: type,
7 comptime WriteError: type,
8 comptime writeFn: fn (context: Context, bytes: []const u8) WriteError!usize,
9) type {
1310 return struct {
11 context: Context,
12
1413 const Self = @This();
1514 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,
22
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 }
16 pub fn write(self: Self, bytes: []const u8) Error!usize {
17 return writeFn(self.context, bytes);
3218 }
3319
34 pub fn write(self: *Self, bytes: []const u8) Error!void {
20 pub fn writeAll(self: Self, bytes: []const u8) Error!void {
3521 var index: usize = 0;
3622 while (index != bytes.len) {
37 index += try self.writeOnce(bytes[index..]);
23 index += try self.write(bytes[index..]);
3824 }
3925 }
4026
41 pub fn print(self: *Self, comptime format: []const u8, args: var) Error!void {
42 return std.fmt.format(self, Error, write, format, args);
27 pub fn print(self: Self, comptime format: []const u8, args: var) Error!void {
28 return std.fmt.format(self, format, args);
4329 }
4430
45 pub fn writeByte(self: *Self, byte: u8) Error!void {
31 pub fn writeByte(self: Self, byte: u8) Error!void {
4632 const array = [1]u8{byte};
47 return self.write(&array);
33 return self.writeAll(&array);
4834 }
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 {
5137 var bytes: [256]u8 = undefined;
5238 mem.set(u8, bytes[0..], byte);
5339
5440 var remaining: usize = n;
5541 while (remaining > 0) {
5642 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]);
5844 remaining -= to_write;
5945 }
6046 }
6147
6248 /// 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 {
6451 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
6552 mem.writeIntNative(T, &bytes, value);
66 return self.write(&bytes);
53 return self.writeAll(&bytes);
6754 }
6855
6956 /// 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 {
7159 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
7260 mem.writeIntForeign(T, &bytes, value);
73 return self.write(&bytes);
61 return self.writeAll(&bytes);
7462 }
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 {
7766 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
7867 mem.writeIntLittle(T, &bytes, value);
79 return self.write(&bytes);
68 return self.writeAll(&bytes);
8069 }
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 {
8373 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
8474 mem.writeIntBig(T, &bytes, value);
85 return self.write(&bytes);
75 return self.writeAll(&bytes);
8676 }
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 {
8980 var bytes: [(T.bit_count + 7) / 8]u8 = undefined;
9081 mem.writeInt(T, &bytes, value, endian);
91 return self.write(&bytes);
82 return self.writeAll(&bytes);
9283 }
9384 };
9485}
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 @@
11const std = @import("../std.zig");
22const 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 {
513 return struct {
14 context: Context,
15
616 const Self = @This();
717 pub const SeekError = SeekErrorType;
818 pub const GetSeekPosError = GetSeekPosErrorType;
919
10 seekToFn: fn (self: *Self, pos: u64) SeekError!void,
11 seekByFn: fn (self: *Self, pos: i64) SeekError!void,
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);
20 pub fn seekTo(self: Self, pos: u64) SeekError!void {
21 return seekToFn(self.context, pos);
1822 }
1923
20 pub fn seekBy(self: *Self, amt: i64) SeekError!void {
21 return self.seekByFn(self, amt);
24 pub fn seekBy(self: Self, amt: i64) SeekError!void {
25 return seekByFn(self.context, amt);
2226 }
2327
24 pub fn getEndPos(self: *Self) GetSeekPosError!u64 {
25 return self.getEndPosFn(self);
28 pub fn getEndPos(self: Self) GetSeekPosError!u64 {
29 return getEndPosFn(self.context);
2630 }
2731
28 pub fn getPos(self: *Self) GetSeekPosError!u64 {
29 return self.getPosFn(self);
32 pub fn getPos(self: Self) GetSeekPosError!u64 {
33 return getPosFn(self.context);
3034 }
3135 };
3236}
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 @@
1const builtin = @import("builtin");
2const std = @import("../std.zig");
1const std = @import("std");
2const builtin = std.builtin;
33const io = std.io;
44const meta = std.meta;
55const trait = std.trait;
......@@ -22,11 +22,10 @@ test "write a file, read it, then delete it" {
2222 var file = try cwd.createFile(tmp_file_name, .{});
2323 defer file.close();
2424
25 var file_out_stream = file.outStream();
26 var buf_stream = io.BufferedOutStream(File.WriteError).init(&file_out_stream.stream);
27 const st = &buf_stream.stream;
25 var buf_stream = io.bufferedOutStream(file.outStream());
26 const st = buf_stream.outStream();
2827 try st.print("begin", .{});
29 try st.write(data[0..]);
28 try st.writeAll(data[0..]);
3029 try st.print("end", .{});
3130 try buf_stream.flush();
3231 }
......@@ -48,9 +47,8 @@ test "write a file, read it, then delete it" {
4847 const expected_file_size: u64 = "begin".len + data.len + "end".len;
4948 expectEqual(expected_file_size, file_size);
5049
51 var file_in_stream = file.inStream();
52 var buf_stream = io.BufferedInStream(File.ReadError).init(&file_in_stream.stream);
53 const st = &buf_stream.stream;
50 var buf_stream = io.bufferedInStream(file.inStream());
51 const st = buf_stream.inStream();
5452 const contents = try st.readAllAlloc(std.testing.allocator, 2 * 1024);
5553 defer std.testing.allocator.free(contents);
5654
......@@ -61,224 +59,13 @@ test "write a file, read it, then delete it" {
6159 try cwd.deleteFile(tmp_file_name);
6260}
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
27262test "BitStreams with File Stream" {
27363 const tmp_file_name = "temp_test_file.txt";
27464 {
27565 var file = try fs.cwd().createFile(tmp_file_name, .{});
27666 defer file.close();
27767
278 var file_out = 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);
68 var bit_stream = io.bitOutStream(builtin.endian, file.outStream());
28269
28370 try bit_stream.writeBits(@as(u2, 1), 1);
28471 try bit_stream.writeBits(@as(u5, 2), 2);
......@@ -292,10 +79,7 @@ test "BitStreams with File Stream" {
29279 var file = try fs.cwd().openFile(tmp_file_name, .{});
29380 defer file.close();
29481
295 var file_in = 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);
82 var bit_stream = io.bitInStream(builtin.endian, file.inStream());
29983
30084 var out_bits: usize = undefined;
30185
......@@ -317,294 +101,6 @@ test "BitStreams with File Stream" {
317101 try fs.cwd().deleteFile(tmp_file_name);
318102}
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
608104test "File seek ops" {
609105 const tmp_file_name = "temp_test_file.txt";
610106 var file = try fs.cwd().createFile(tmp_file_name, .{});
......@@ -617,16 +113,39 @@ test "File seek ops" {
617113
618114 // Seek to the end
619115 try file.seekFromEnd(0);
620 std.testing.expect((try file.getPos()) == try file.getEndPos());
116 expect((try file.getPos()) == try file.getEndPos());
621117 // Negative delta
622118 try file.seekBy(-4096);
623 std.testing.expect((try file.getPos()) == 4096);
119 expect((try file.getPos()) == 4096);
624120 // Positive delta
625121 try file.seekBy(10);
626 std.testing.expect((try file.getPos()) == 4106);
122 expect((try file.getPos()) == 4106);
627123 // Absolute position
628124 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);
630149}
631150
632151test "updateTimes" {
......@@ -643,6 +162,6 @@ test "updateTimes" {
643162 stat_old.mtime - 5 * std.time.ns_per_s,
644163 );
645164 var stat_new = try file.stat();
646 std.testing.expect(stat_new.atime < stat_old.atime);
647 std.testing.expect(stat_new.mtime < stat_old.mtime);
165 expect(stat_new.atime < stat_old.atime);
166 expect(stat_new.mtime < stat_old.mtime);
648167}
lib/std/json.zig+77-66
......@@ -10,6 +10,7 @@ const mem = std.mem;
1010const maxInt = std.math.maxInt;
1111
1212pub const WriteStream = @import("json/write_stream.zig").WriteStream;
13pub const writeStream = @import("json/write_stream.zig").writeStream;
1314
1415const StringEscapes = union(enum) {
1516 None,
......@@ -2107,9 +2108,9 @@ test "import more json tests" {
21072108test "write json then parse it" {
21082109 var out_buffer: [1000]u8 = undefined;
21092110
2110 var slice_out_stream = std.io.SliceOutStream.init(&out_buffer);
2111 const out_stream = &slice_out_stream.stream;
2112 var jw = WriteStream(@TypeOf(out_stream).Child, 4).init(out_stream);
2111 var fixed_buffer_stream = std.io.fixedBufferStream(&out_buffer);
2112 const out_stream = fixed_buffer_stream.outStream();
2113 var jw = writeStream(out_stream, 4);
21132114
21142115 try jw.beginObject();
21152116
......@@ -2140,7 +2141,7 @@ test "write json then parse it" {
21402141
21412142 var parser = Parser.init(testing.allocator, false);
21422143 defer parser.deinit();
2143 var tree = try parser.parse(slice_out_stream.getWritten());
2144 var tree = try parser.parse(fixed_buffer_stream.getWritten());
21442145 defer tree.deinit();
21452146
21462147 testing.expect(tree.root.Object.get("f").?.value.Bool == false);
......@@ -2251,45 +2252,43 @@ pub const StringifyOptions = struct {
22512252pub fn stringify(
22522253 value: var,
22532254 options: StringifyOptions,
2254 context: var,
2255 comptime Errors: type,
2256 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
2257) Errors!void {
2255 out_stream: var,
2256) !void {
22582257 const T = @TypeOf(value);
22592258 switch (@typeInfo(T)) {
22602259 .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);
22622261 },
22632262 .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);
22652264 },
22662265 .Bool => {
2267 return output(context, if (value) "true" else "false");
2266 return out_stream.writeAll(if (value) "true" else "false");
22682267 },
22692268 .Optional => {
22702269 if (value) |payload| {
2271 return try stringify(payload, options, context, Errors, output);
2270 return try stringify(payload, options, out_stream);
22722271 } else {
2273 return output(context, "null");
2272 return out_stream.writeAll("null");
22742273 }
22752274 },
22762275 .Enum => {
22772276 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
2278 return value.jsonStringify(options, context, Errors, output);
2277 return value.jsonStringify(options, out_stream);
22792278 }
22802279
22812280 @compileError("Unable to stringify enum '" ++ @typeName(T) ++ "'");
22822281 },
22832282 .Union => {
22842283 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
2285 return value.jsonStringify(options, context, Errors, output);
2284 return value.jsonStringify(options, out_stream);
22862285 }
22872286
22882287 const info = @typeInfo(T).Union;
22892288 if (info.tag_type) |UnionTagType| {
22902289 inline for (info.fields) |u_field| {
22912290 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);
22932292 }
22942293 }
22952294 } else {
......@@ -2298,10 +2297,10 @@ pub fn stringify(
22982297 },
22992298 .Struct => |S| {
23002299 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
2301 return value.jsonStringify(options, context, Errors, output);
2300 return value.jsonStringify(options, out_stream);
23022301 }
23032302
2304 try output(context, "{");
2303 try out_stream.writeAll("{");
23052304 comptime var field_output = false;
23062305 inline for (S.fields) |Field, field_i| {
23072306 // don't include void fields
......@@ -2310,39 +2309,39 @@ pub fn stringify(
23102309 if (!field_output) {
23112310 field_output = true;
23122311 } else {
2313 try output(context, ",");
2312 try out_stream.writeAll(",");
23142313 }
23152314
2316 try stringify(Field.name, options, context, Errors, output);
2317 try output(context, ":");
2318 try stringify(@field(value, Field.name), options, context, Errors, output);
2315 try stringify(Field.name, options, out_stream);
2316 try out_stream.writeAll(":");
2317 try stringify(@field(value, Field.name), options, out_stream);
23192318 }
2320 try output(context, "}");
2319 try out_stream.writeAll("}");
23212320 return;
23222321 },
23232322 .Pointer => |ptr_info| switch (ptr_info.size) {
23242323 .One => {
23252324 // TODO: avoid loops?
2326 return try stringify(value.*, options, context, Errors, output);
2325 return try stringify(value.*, options, out_stream);
23272326 },
23282327 // TODO: .Many when there is a sentinel (waiting for https://github.com/ziglang/zig/pull/3972)
23292328 .Slice => {
23302329 if (ptr_info.child == u8 and std.unicode.utf8ValidateSlice(value)) {
2331 try output(context, "\"");
2330 try out_stream.writeAll("\"");
23322331 var i: usize = 0;
23332332 while (i < value.len) : (i += 1) {
23342333 switch (value[i]) {
23352334 // 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]),
23372336 // control characters with short escapes
2338 '\\' => try output(context, "\\\\"),
2339 '\"' => try output(context, "\\\""),
2340 '/' => try output(context, "\\/"),
2341 0x8 => try output(context, "\\b"),
2342 0xC => try output(context, "\\f"),
2343 '\n' => try output(context, "\\n"),
2344 '\r' => try output(context, "\\r"),
2345 '\t' => try output(context, "\\t"),
2337 '\\' => try out_stream.writeAll("\\\\"),
2338 '\"' => try out_stream.writeAll("\\\""),
2339 '/' => try out_stream.writeAll("\\/"),
2340 0x8 => try out_stream.writeAll("\\b"),
2341 0xC => try out_stream.writeAll("\\f"),
2342 '\n' => try out_stream.writeAll("\\n"),
2343 '\r' => try out_stream.writeAll("\\r"),
2344 '\t' => try out_stream.writeAll("\\t"),
23462345 else => {
23472346 const ulen = std.unicode.utf8ByteSequenceLength(value[i]) catch unreachable;
23482347 const codepoint = std.unicode.utf8Decode(value[i .. i + ulen]) catch unreachable;
......@@ -2350,40 +2349,40 @@ pub fn stringify(
23502349 // If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF),
23512350 // then it may be represented as a six-character sequence: a reverse solidus, followed
23522351 // by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point.
2353 try output(context, "\\u");
2354 try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, context, Errors, output);
2352 try out_stream.writeAll("\\u");
2353 try std.fmt.formatIntValue(codepoint, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
23552354 } else {
23562355 // To escape an extended character that is not in the Basic Multilingual Plane,
23572356 // the character is represented as a 12-character sequence, encoding the UTF-16 surrogate pair.
23582357 const high = @intCast(u16, (codepoint - 0x10000) >> 10) + 0xD800;
23592358 const low = @intCast(u16, codepoint & 0x3FF) + 0xDC00;
2360 try output(context, "\\u");
2361 try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, context, Errors, output);
2362 try output(context, "\\u");
2363 try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, context, Errors, output);
2359 try out_stream.writeAll("\\u");
2360 try std.fmt.formatIntValue(high, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
2361 try out_stream.writeAll("\\u");
2362 try std.fmt.formatIntValue(low, "x", std.fmt.FormatOptions{ .width = 4, .fill = '0' }, out_stream);
23642363 }
23652364 i += ulen - 1;
23662365 },
23672366 }
23682367 }
2369 try output(context, "\"");
2368 try out_stream.writeAll("\"");
23702369 return;
23712370 }
23722371
2373 try output(context, "[");
2372 try out_stream.writeAll("[");
23742373 for (value) |x, i| {
23752374 if (i != 0) {
2376 try output(context, ",");
2375 try out_stream.writeAll(",");
23772376 }
2378 try stringify(x, options, context, Errors, output);
2377 try stringify(x, options, out_stream);
23792378 }
2380 try output(context, "]");
2379 try out_stream.writeAll("]");
23812380 return;
23822381 },
23832382 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
23842383 },
23852384 .Array => |info| {
2386 return try stringify(value[0..], options, context, Errors, output);
2385 return try stringify(value[0..], options, out_stream);
23872386 },
23882387 else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
23892388 }
......@@ -2391,10 +2390,26 @@ pub fn stringify(
23912390}
23922391
23932392fn 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
23952401 expected_remaining: []const u8,
2396 fn testStringifyWrite(context: *@This(), bytes: []const u8) !void {
2397 if (context.expected_remaining.len < bytes.len) {
2402
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) {
23982413 std.debug.warn(
23992414 \\====== expected this output: =========
24002415 \\{}
......@@ -2402,12 +2417,12 @@ fn teststringify(expected: []const u8, value: var) !void {
24022417 \\{}
24032418 \\======================================
24042419 , .{
2405 context.expected_remaining,
2420 self.expected_remaining,
24062421 bytes,
24072422 });
24082423 return error.TooMuchData;
24092424 }
2410 if (!mem.eql(u8, context.expected_remaining[0..bytes.len], bytes)) {
2425 if (!mem.eql(u8, self.expected_remaining[0..bytes.len], bytes)) {
24112426 std.debug.warn(
24122427 \\====== expected this output: =========
24132428 \\{}
......@@ -2415,21 +2430,19 @@ fn teststringify(expected: []const u8, value: var) !void {
24152430 \\{}
24162431 \\======================================
24172432 , .{
2418 context.expected_remaining[0..bytes.len],
2433 self.expected_remaining[0..bytes.len],
24192434 bytes,
24202435 });
24212436 return error.DifferentData;
24222437 }
2423 context.expected_remaining = context.expected_remaining[bytes.len..];
2438 self.expected_remaining = self.expected_remaining[bytes.len..];
2439 return bytes.len;
24242440 }
24252441 };
2426 var buf: [100]u8 = undefined;
2427 var context = TestStringifyContext{ .expected_remaining = expected };
2428 try stringify(value, StringifyOptions{}, &context, error{
2429 TooMuchData,
2430 DifferentData,
2431 }, TestStringifyContext.testStringifyWrite);
2432 if (context.expected_remaining.len > 0) return error.NotEnoughData;
2442
2443 var vos = ValidationOutStream.init(expected);
2444 try stringify(value, StringifyOptions{}, vos.outStream());
2445 if (vos.expected_remaining.len > 0) return error.NotEnoughData;
24332446}
24342447
24352448test "stringify basic types" {
......@@ -2497,13 +2510,11 @@ test "stringify struct with custom stringifier" {
24972510 pub fn jsonStringify(
24982511 value: Self,
24992512 options: StringifyOptions,
2500 context: var,
2501 comptime Errors: type,
2502 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
2513 out_stream: var,
25032514 ) !void {
2504 try output(context, "[\"something special\",");
2505 try stringify(42, options, context, Errors, output);
2506 try output(context, "]");
2515 try out_stream.writeAll("[\"something special\",");
2516 try stringify(42, options, out_stream);
2517 try out_stream.writeAll("]");
25072518 }
25082519 }{ .foo = 42 });
25092520}
lib/std/json/write_stream.zig+26-19
......@@ -30,11 +30,11 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
3030 /// The string used as spacing.
3131 space: []const u8 = " ",
3232
33 stream: *OutStream,
33 stream: OutStream,
3434 state_index: usize,
3535 state: [max_depth]State,
3636
37 pub fn init(stream: *OutStream) Self {
37 pub fn init(stream: OutStream) Self {
3838 var self = Self{
3939 .stream = stream,
4040 .state_index = 1,
......@@ -90,8 +90,8 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
9090 self.pushState(.Value);
9191 try self.indent();
9292 try self.writeEscapedString(name);
93 try self.stream.write(":");
94 try self.stream.write(self.space);
93 try self.stream.writeAll(":");
94 try self.stream.writeAll(self.space);
9595 },
9696 }
9797 }
......@@ -134,16 +134,16 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
134134
135135 pub fn emitNull(self: *Self) !void {
136136 assert(self.state[self.state_index] == State.Value);
137 try self.stream.write("null");
137 try self.stream.writeAll("null");
138138 self.popState();
139139 }
140140
141141 pub fn emitBool(self: *Self, value: bool) !void {
142142 assert(self.state[self.state_index] == State.Value);
143143 if (value) {
144 try self.stream.write("true");
144 try self.stream.writeAll("true");
145145 } else {
146 try self.stream.write("false");
146 try self.stream.writeAll("false");
147147 }
148148 self.popState();
149149 }
......@@ -188,13 +188,13 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
188188 try self.stream.writeByte('"');
189189 for (string) |s| {
190190 switch (s) {
191 '"' => try self.stream.write("\\\""),
192 '\t' => try self.stream.write("\\t"),
193 '\r' => try self.stream.write("\\r"),
194 '\n' => try self.stream.write("\\n"),
195 8 => try self.stream.write("\\b"),
196 12 => try self.stream.write("\\f"),
197 '\\' => try self.stream.write("\\\\"),
191 '"' => try self.stream.writeAll("\\\""),
192 '\t' => try self.stream.writeAll("\\t"),
193 '\r' => try self.stream.writeAll("\\r"),
194 '\n' => try self.stream.writeAll("\\n"),
195 8 => try self.stream.writeAll("\\b"),
196 12 => try self.stream.writeAll("\\f"),
197 '\\' => try self.stream.writeAll("\\\\"),
198198 else => try self.stream.writeByte(s),
199199 }
200200 }
......@@ -231,10 +231,10 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
231231
232232 fn indent(self: *Self) !void {
233233 assert(self.state_index >= 1);
234 try self.stream.write(self.newline);
234 try self.stream.writeAll(self.newline);
235235 var i: usize = 0;
236236 while (i < self.state_index - 1) : (i += 1) {
237 try self.stream.write(self.one_indent);
237 try self.stream.writeAll(self.one_indent);
238238 }
239239 }
240240
......@@ -249,15 +249,22 @@ pub fn WriteStream(comptime OutStream: type, comptime max_depth: usize) type {
249249 };
250250}
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
252259test "json write stream" {
253260 var out_buf: [1024]u8 = undefined;
254 var slice_stream = std.io.SliceOutStream.init(&out_buf);
255 const out = &slice_stream.stream;
261 var slice_stream = std.io.fixedBufferStream(&out_buf);
262 const out = slice_stream.outStream();
256263
257264 var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
258265 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);
261268 try w.emitJson(try getJson(&arena_allocator.allocator));
262269
263270 const result = slice_stream.getWritten();
lib/std/math/big/int.zig+2-4
......@@ -519,16 +519,14 @@ pub const Int = struct {
519519 self: Int,
520520 comptime fmt: []const u8,
521521 options: std.fmt.FormatOptions,
522 context: var,
523 comptime FmtError: type,
524 output: fn (@TypeOf(context), []const u8) FmtError!void,
522 out_stream: var,
525523 ) FmtError!void {
526524 self.assertWritable();
527525 // TODO look at fmt and support other bases
528526 // TODO support read-only fixed integers
529527 const str = self.toString(self.allocator.?, 10) catch @panic("TODO make this non allocating");
530528 defer self.allocator.?.free(str);
531 return output(context, str);
529 return out_stream.print(str);
532530 }
533531
534532 /// 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 {
105105 return self.alignedAlloc(T, null, n);
106106 }
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
108122 pub fn alignedAlloc(
109123 self: *Allocator,
110124 comptime T: type,
......@@ -921,6 +935,9 @@ pub fn writeInt(comptime T: type, buffer: *[@divExact(T.bit_count, 8)]u8, value:
921935pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {
922936 assert(buffer.len >= @divExact(T.bit_count, 8));
923937
938 if (T.bit_count == 0)
939 return set(u8, buffer, 0);
940
924941 // TODO I want to call writeIntLittle here but comptime eval facilities aren't good enough
925942 const uint = std.meta.IntType(false, T.bit_count);
926943 var bits = @truncate(uint, value);
......@@ -938,6 +955,9 @@ pub fn writeIntSliceLittle(comptime T: type, buffer: []u8, value: T) void {
938955pub fn writeIntSliceBig(comptime T: type, buffer: []u8, value: T) void {
939956 assert(buffer.len >= @divExact(T.bit_count, 8));
940957
958 if (T.bit_count == 0)
959 return set(u8, buffer, 0);
960
941961 // TODO I want to call writeIntBig here but comptime eval facilities aren't good enough
942962 const uint = std.meta.IntType(false, T.bit_count);
943963 var bits = @truncate(uint, value);
......@@ -1807,7 +1827,7 @@ test "sliceAsBytes" {
18071827}
18081828
18091829test "sliceAsBytes with sentinel slice" {
1810 const empty_string:[:0]const u8 = "";
1830 const empty_string: [:0]const u8 = "";
18111831 const bytes = sliceAsBytes(empty_string);
18121832 testing.expect(bytes.len == 0);
18131833}
lib/std/net.zig+11-13
......@@ -269,15 +269,13 @@ pub const Address = extern union {
269269 self: Address,
270270 comptime fmt: []const u8,
271271 options: std.fmt.FormatOptions,
272 context: var,
273 comptime Errors: type,
274 comptime output: fn (@TypeOf(context), []const u8) Errors!void,
272 out_stream: var,
275273 ) !void {
276274 switch (self.any.family) {
277275 os.AF_INET => {
278276 const port = mem.bigToNative(u16, self.in.port);
279277 const bytes = @ptrCast(*const [4]u8, &self.in.addr);
280 try std.fmt.format(context, Errors, output, "{}.{}.{}.{}:{}", .{
278 try std.fmt.format(out_stream, "{}.{}.{}.{}:{}", .{
281279 bytes[0],
282280 bytes[1],
283281 bytes[2],
......@@ -288,7 +286,7 @@ pub const Address = extern union {
288286 os.AF_INET6 => {
289287 const port = mem.bigToNative(u16, self.in6.port);
290288 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:{}.{}.{}.{}]:{}", .{
292290 self.in6.addr[12],
293291 self.in6.addr[13],
294292 self.in6.addr[14],
......@@ -308,30 +306,30 @@ pub const Address = extern union {
308306 break :blk buf;
309307 },
310308 };
311 try output(context, "[");
309 try out_stream.writeAll("[");
312310 var i: usize = 0;
313311 var abbrv = false;
314312 while (i < native_endian_parts.len) : (i += 1) {
315313 if (native_endian_parts[i] == 0) {
316314 if (!abbrv) {
317 try output(context, if (i == 0) "::" else ":");
315 try out_stream.writeAll(if (i == 0) "::" else ":");
318316 abbrv = true;
319317 }
320318 continue;
321319 }
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]});
323321 if (i != native_endian_parts.len - 1) {
324 try output(context, ":");
322 try out_stream.writeAll(":");
325323 }
326324 }
327 try std.fmt.format(context, Errors, output, "]:{}", .{port});
325 try std.fmt.format(out_stream, "]:{}", .{port});
328326 },
329327 os.AF_UNIX => {
330328 if (!has_unix_sockets) {
331329 unreachable;
332330 }
333331
334 try std.fmt.format(context, Errors, output, "{}", .{&self.un.path});
332 try std.fmt.format(out_stream, "{}", .{&self.un.path});
335333 },
336334 else => unreachable,
337335 }
......@@ -816,7 +814,7 @@ fn linuxLookupNameFromHosts(
816814 };
817815 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();
820818 var line_buf: [512]u8 = undefined;
821819 while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) {
822820 error.StreamTooLong => blk: {
......@@ -1010,7 +1008,7 @@ fn getResolvConf(allocator: *mem.Allocator, rc: *ResolvConf) !void {
10101008 };
10111009 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();
10141012 var line_buf: [512]u8 = undefined;
10151013 while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) {
10161014 error.StreamTooLong => blk: {
lib/std/net/test.zig+1-1
......@@ -113,6 +113,6 @@ fn testClient(addr: net.Address) anyerror!void {
113113fn testServer(server: *net.StreamServer) anyerror!void {
114114 var client = try server.accept();
115115
116 const stream = &client.file.outStream().stream;
116 const stream = client.file.outStream();
117117 try stream.print("hello from server\n", .{});
118118}
lib/std/os.zig+59-4
......@@ -176,7 +176,7 @@ fn getRandomBytesDevURandom(buf: []u8) !void {
176176 .io_mode = .blocking,
177177 .async_block_allowed = std.fs.File.async_block_allowed_yes,
178178 };
179 const stream = &file.inStream().stream;
179 const stream = file.inStream();
180180 stream.readNoEof(buf) catch return error.Unexpected;
181181}
182182
......@@ -273,10 +273,10 @@ pub fn exit(status: u8) noreturn {
273273 // exit() is only avaliable if exitBootServices() has not been called yet.
274274 // This call to exit should not fail, so we don't care about its return value.
275275 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);
277277 }
278278 // 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);
280280 }
281281 system.exit(status);
282282}
......@@ -438,6 +438,61 @@ pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
438438 return index;
439439}
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
441496/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
442497///
443498/// Retries when interrupted by a signal.
......@@ -3077,7 +3132,7 @@ pub fn realpathW(pathname: [*:0]const u16, out_buffer: *[MAX_PATH_BYTES]u8) Real
30773132 windows.FILE_SHARE_READ,
30783133 null,
30793134 windows.OPEN_EXISTING,
3080 windows.FILE_ATTRIBUTE_NORMAL,
3135 windows.FILE_FLAG_BACKUP_SEMANTICS,
30813136 null,
30823137 );
30833138 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 {
5353};
5454
5555pub const off_t = i64;
56pub const ino_t = u64;
5657
5758/// Renamed to Stat to not conflict with the stat function.
5859/// atime, mtime, and ctime have functions to return `timespec`,
......@@ -64,7 +65,7 @@ pub const Stat = extern struct {
6465 dev: i32,
6566 mode: u16,
6667 nlink: u16,
67 ino: u64,
68 ino: ino_t,
6869 uid: u32,
6970 gid: u32,
7071 rdev: i32,
lib/std/os/bits/dragonfly.zig+3-1
......@@ -138,8 +138,10 @@ pub const MAP_SIZEALIGN = 262144;
138138
139139pub const PATH_MAX = 1024;
140140
141pub const ino_t = c_ulong;
142
141143pub const Stat = extern struct {
142 ino: c_ulong,
144 ino: ino_t,
143145 nlink: c_uint,
144146 dev: c_uint,
145147 mode: c_ushort,
lib/std/os/bits/freebsd.zig+2-1
......@@ -98,6 +98,7 @@ pub const msghdr_const = extern struct {
9898};
9999
100100pub const off_t = i64;
101pub const ino_t = u64;
101102
102103/// Renamed to Stat to not conflict with the stat function.
103104/// atime, mtime, and ctime have functions to return `timespec`,
......@@ -107,7 +108,7 @@ pub const off_t = i64;
107108/// methods to accomplish this.
108109pub const Stat = extern struct {
109110 dev: u64,
110 ino: u64,
111 ino: ino_t,
111112 nlink: usize,
112113
113114 mode: u16,
lib/std/os/bits/linux.zig+12-6
......@@ -18,6 +18,8 @@ pub usingnamespace switch (builtin.arch) {
1818 else => struct {},
1919};
2020
21pub usingnamespace @import("linux/netlink.zig");
22
2123const is_mips = builtin.arch.isMIPS();
2224
2325pub const pid_t = i32;
......@@ -30,6 +32,10 @@ pub const NAME_MAX = 255;
3032pub const PATH_MAX = 4096;
3133pub 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
3339pub const STDIN_FILENO = 0;
3440pub const STDOUT_FILENO = 1;
3541pub const STDERR_FILENO = 2;
......@@ -1290,12 +1296,12 @@ pub const io_uring_files_update = struct {
12901296};
12911297
12921298pub const utsname = extern struct {
1293 sysname: [65]u8,
1294 nodename: [65]u8,
1295 release: [65]u8,
1296 version: [65]u8,
1297 machine: [65]u8,
1298 domainname: [65]u8,
1299 sysname: [64:0]u8,
1300 nodename: [64:0]u8,
1301 release: [64:0]u8,
1302 version: [64:0]u8,
1303 machine: [64:0]u8,
1304 domainname: [64:0]u8,
12991305};
13001306pub 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 {
481481};
482482
483483pub const off_t = i64;
484pub const ino_t = u64;
484485
485486/// Renamed to Stat to not conflict with the stat function.
486487/// atime, mtime, and ctime have functions to return `timespec`,
......@@ -490,7 +491,7 @@ pub const off_t = i64;
490491/// methods to accomplish this.
491492pub const Stat = extern struct {
492493 dev: u64,
493 ino: u64,
494 ino: ino_t,
494495 nlink: usize,
495496
496497 mode: u32,
lib/std/os/bits/netbsd.zig+2-1
......@@ -69,6 +69,7 @@ pub const msghdr_const = extern struct {
6969};
7070
7171pub const off_t = i64;
72pub const ino_t = u64;
7273
7374/// Renamed to Stat to not conflict with the stat function.
7475/// atime, mtime, and ctime have functions to return `timespec`,
......@@ -79,7 +80,7 @@ pub const off_t = i64;
7980pub const Stat = extern struct {
8081 dev: u64,
8182 mode: u32,
82 ino: u64,
83 ino: ino_t,
8384 nlink: usize,
8485
8586 uid: u32,
lib/std/os/bits/wasi.zig+1
......@@ -178,6 +178,7 @@ pub const FILESTAT_SET_MTIM: fstflags_t = 0x0004;
178178pub const FILESTAT_SET_MTIM_NOW: fstflags_t = 0x0008;
179179
180180pub const inode_t = u64;
181pub const ino_t = inode_t;
181182
182183pub const linkcount_t = u32;
183184
lib/std/os/bits/windows.zig+1
......@@ -4,6 +4,7 @@ usingnamespace @import("../windows/bits.zig");
44const ws2_32 = @import("../windows/ws2_32.zig");
55
66pub const fd_t = HANDLE;
7pub const ino_t = LARGE_INTEGER;
78pub const pid_t = HANDLE;
89pub 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 {
350350 );
351351 }
352352 } 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 );
354360 }
355361}
356362
......@@ -384,8 +390,64 @@ pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
384390 return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
385391}
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
387420pub 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 }
389451}
390452
391453pub fn rename(old: [*:0]const u8, new: [*:0]const u8) usize {
lib/std/os/test.zig+34-9
......@@ -95,15 +95,41 @@ test "sendfile" {
9595 },
9696 };
9797
98 var written_buf: [header1.len + header2.len + 10 + trailer1.len + trailer2.len]u8 = undefined;
98 var written_buf: [100]u8 = undefined;
9999 try dest_file.writeFileAll(src_file, .{
100100 .in_offset = 1,
101101 .in_len = 10,
102102 .headers_and_trailers = &hdtr,
103103 .header_count = 2,
104104 });
105 try dest_file.preadAll(&written_buf, 0);
106 expect(mem.eql(u8, &written_buf, "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n"));
105 const amt = try dest_file.preadAll(&written_buf, 0);
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);
107133}
108134
109135test "std.Thread.getCurrentId" {
......@@ -354,8 +380,7 @@ test "mmap" {
354380 const file = try fs.cwd().createFile(test_out_file, .{});
355381 defer file.close();
356382
357 var out_stream = file.outStream();
358 const stream = &out_stream.stream;
383 const stream = file.outStream();
359384
360385 var i: u32 = 0;
361386 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
......@@ -378,8 +403,8 @@ test "mmap" {
378403 );
379404 defer os.munmap(data);
380405
381 var mem_stream = io.SliceInStream.init(data);
382 const stream = &mem_stream.stream;
406 var mem_stream = io.fixedBufferStream(data);
407 const stream = mem_stream.inStream();
383408
384409 var i: u32 = 0;
385410 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
......@@ -402,8 +427,8 @@ test "mmap" {
402427 );
403428 defer os.munmap(data);
404429
405 var mem_stream = io.SliceInStream.init(data);
406 const stream = &mem_stream.stream;
430 var mem_stream = io.fixedBufferStream(data);
431 const stream = mem_stream.inStream();
407432
408433 var i: u32 = alloc_size / 2 / @sizeOf(u32);
409434 while (i < alloc_size / @sizeOf(u32)) : (i += 1) {
lib/std/os/uefi.zig+7-8
......@@ -2,11 +2,9 @@
22pub const protocols = @import("uefi/protocols.zig");
33
44/// Status codes returned by EFI interfaces
5pub const status = @import("uefi/status.zig");
5pub const Status = @import("uefi/status.zig").Status;
66pub const tables = @import("uefi/tables.zig");
77
8const fmt = @import("std").fmt;
9
108/// The EFI image's handle that is passed to its entry point.
119pub var handle: Handle = undefined;
1210
......@@ -29,13 +27,11 @@ pub const Guid = extern struct {
2927 pub fn format(
3028 self: @This(),
3129 comptime f: []const u8,
32 options: fmt.FormatOptions,
33 context: var,
34 comptime Errors: type,
35 output: fn (@TypeOf(context), []const u8) Errors!void,
30 options: std.fmt.FormatOptions,
31 out_stream: var,
3632 ) Errors!void {
3733 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}", .{
3935 self.time_low,
4036 self.time_mid,
4137 self.time_high_and_version,
......@@ -105,3 +101,6 @@ pub const TimeCapabilities = extern struct {
105101 /// If true, a time set operation clears the device's time below the resolution level.
106102 sets_to_zero: bool,
107103};
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 @@
11pub 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;
37pub 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
518pub const InputKey = @import("protocols/simple_text_input_ex_protocol.zig").InputKey;
619pub 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
8295pub const HIIPopupSelection = @import("protocols/hii_popup_protocol.zig").HIIPopupSelection;
8396
8497pub 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 @@
11const uefi = @import("std").os.uefi;
22const Event = uefi.Event;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56/// Protocol for touchscreens
67pub const AbsolutePointerProtocol = extern struct {
7 _reset: extern fn (*const AbsolutePointerProtocol, bool) usize,
8 _get_state: extern fn (*const AbsolutePointerProtocol, *AbsolutePointerState) usize,
8 _reset: extern fn (*const AbsolutePointerProtocol, bool) Status,
9 _get_state: extern fn (*const AbsolutePointerProtocol, *AbsolutePointerState) Status,
910 wait_for_input: Event,
1011 mode: *AbsolutePointerMode,
1112
1213 /// 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 {
1415 return self._reset(self, verify);
1516 }
1617
1718 /// 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 {
1920 return self._get_state(self, state);
2021 }
2122
lib/std/os/uefi/protocols/device_path_protocol.zig+338-2
......@@ -1,8 +1,8 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33
4pub const DevicePathProtocol = extern struct {
5 type: u8,
4pub const DevicePathProtocol = packed struct {
5 type: DevicePathType,
66 subtype: u8,
77 length: u16,
88
......@@ -14,4 +14,340 @@ pub const DevicePathProtocol = extern struct {
1414 .clock_seq_low = 0x39,
1515 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
1616 };
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 };
17353};
lib/std/os/uefi/protocols/edid_override_protocol.zig+3-2
......@@ -1,14 +1,15 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33const Handle = uefi.Handle;
4const Status = uefi.Status;
45
56/// Override EDID information
67pub 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
910 /// Returns policy information and potentially a replacement EDID for the specified video output device.
1011 /// 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 {
1213 return self._get_edid(self, handle, attributes, edid_size, edid);
1314 }
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 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
3const Status = uefi.Status;
34
45/// Graphics output
56pub const GraphicsOutputProtocol = extern struct {
6 _query_mode: extern fn (*const GraphicsOutputProtocol, u32, *usize, **GraphicsOutputModeInformation) usize,
7 _set_mode: extern fn (*const GraphicsOutputProtocol, u32) usize,
8 _blt: extern fn (*const GraphicsOutputProtocol, ?[*]GraphicsOutputBltPixel, GraphicsOutputBltOperation, usize, usize, usize, usize, usize, usize, usize) usize,
7 _query_mode: extern fn (*const GraphicsOutputProtocol, u32, *usize, **GraphicsOutputModeInformation) Status,
8 _set_mode: extern fn (*const GraphicsOutputProtocol, u32) Status,
9 _blt: extern fn (*const GraphicsOutputProtocol, ?[*]GraphicsOutputBltPixel, GraphicsOutputBltOperation, usize, usize, usize, usize, usize, usize, usize) Status,
910 mode: *GraphicsOutputProtocolMode,
1011
1112 /// 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 {
1314 return self._query_mode(self, mode, size_of_info, info);
1415 }
1516
1617 /// 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 {
1819 return self._set_mode(self, mode);
1920 }
2021
2122 /// 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 {
2324 return self._blt(self, blt_buffer, blt_operation, source_x, source_y, destination_x, destination_y, width, height, delta);
2425 }
2526
lib/std/os/uefi/protocols/hii_database_protocol.zig+16-15
......@@ -1,38 +1,39 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
3const Status = uefi.Status;
34const hii = uefi.protocols.hii;
45
56/// Database manager for HII-related data structures.
67pub const HIIDatabaseProtocol = extern struct {
7 _new_package_list: usize, // TODO
8 _remove_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle) usize,
9 _update_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle, *const hii.HIIPackageList) usize,
10 _list_package_lists: extern fn (*const HIIDatabaseProtocol, u8, ?*const Guid, *usize, [*]hii.HIIHandle) usize,
11 _export_package_lists: extern fn (*const HIIDatabaseProtocol, ?hii.HIIHandle, *usize, *hii.HIIPackageList) usize,
12 _register_package_notify: usize, // TODO
13 _unregister_package_notify: usize, // TODO
14 _find_keyboard_layouts: usize, // TODO
15 _get_keyboard_layout: usize, // TODO
16 _set_keyboard_layout: usize, // TODO
17 _get_package_list_handle: usize, // TODO
8 _new_package_list: Status, // TODO
9 _remove_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle) Status,
10 _update_package_list: extern fn (*const HIIDatabaseProtocol, hii.HIIHandle, *const hii.HIIPackageList) Status,
11 _list_package_lists: extern fn (*const HIIDatabaseProtocol, u8, ?*const Guid, *usize, [*]hii.HIIHandle) Status,
12 _export_package_lists: extern fn (*const HIIDatabaseProtocol, ?hii.HIIHandle, *usize, *hii.HIIPackageList) Status,
13 _register_package_notify: Status, // TODO
14 _unregister_package_notify: Status, // TODO
15 _find_keyboard_layouts: Status, // TODO
16 _get_keyboard_layout: Status, // TODO
17 _set_keyboard_layout: Status, // TODO
18 _get_package_list_handle: Status, // TODO
1819
1920 /// 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 {
2122 return self._remove_package_list(self, handle);
2223 }
2324
2425 /// 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 {
2627 return self._update_package_list(self, handle, buffer);
2728 }
2829
2930 /// 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 {
3132 return self._list_package_lists(self, package_type, package_guid, buffer_length, handles);
3233 }
3334
3435 /// 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 {
3637 return self._export_package_lists(self, handle, buffer_size, buffer);
3738 }
3839
lib/std/os/uefi/protocols/hii_popup_protocol.zig+3-2
......@@ -1,14 +1,15 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
3const Status = uefi.Status;
34const hii = uefi.protocols.hii;
45
56/// Display a popup window
67pub const HIIPopupProtocol = extern struct {
78 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
1011 /// 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 {
1213 return self._create_popup(self, style, popup_type, handle, msg, user_selection);
1314 }
1415
lib/std/os/uefi/protocols/ip6_config_protocol.zig+9-8
......@@ -1,26 +1,27 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33const Event = uefi.Event;
4const Status = uefi.Status;
45
56pub const Ip6ConfigProtocol = extern struct {
6 _set_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, usize, *const c_void) usize,
7 _get_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, *usize, ?*const c_void) usize,
8 _register_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) usize,
9 _unregister_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) usize,
7 _set_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, usize, *const c_void) Status,
8 _get_data: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, *usize, ?*const c_void) Status,
9 _register_data_notify: extern fn (*const Ip6ConfigProtocol, Ip6ConfigDataType, Event) Status,
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 {
1213 return self._set_data(self, data_type, data_size, data);
1314 }
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 {
1617 return self._get_data(self, data_type, data_size, data);
1718 }
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 {
2021 return self._register_data_notify(self, data_type, event);
2122 }
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 {
2425 return self._unregister_data_notify(self, data_type, event);
2526 }
2627
lib/std/os/uefi/protocols/ip6_protocol.zig+20-19
......@@ -1,63 +1,64 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33const Event = uefi.Event;
4const Status = uefi.Status;
45const MacAddress = uefi.protocols.MacAddress;
56const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
67const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
78
89pub const Ip6Protocol = extern struct {
9 _get_mode_data: extern fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,
10 _configure: extern fn (*const Ip6Protocol, ?*const Ip6ConfigData) usize,
11 _groups: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address) usize,
12 _routes: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) usize,
13 _neighbors: extern fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) usize,
14 _transmit: extern fn (*const Ip6Protocol, *Ip6CompletionToken) usize,
15 _receive: extern fn (*const Ip6Protocol, *Ip6CompletionToken) usize,
16 _cancel: extern fn (*const Ip6Protocol, ?*Ip6CompletionToken) usize,
17 _poll: extern fn (*const Ip6Protocol) usize,
10 _get_mode_data: extern fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) Status,
11 _configure: extern fn (*const Ip6Protocol, ?*const Ip6ConfigData) Status,
12 _groups: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address) Status,
13 _routes: extern fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) Status,
14 _neighbors: extern fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) Status,
15 _transmit: extern fn (*const Ip6Protocol, *Ip6CompletionToken) Status,
16 _receive: extern fn (*const Ip6Protocol, *Ip6CompletionToken) Status,
17 _cancel: extern fn (*const Ip6Protocol, ?*Ip6CompletionToken) Status,
18 _poll: extern fn (*const Ip6Protocol) Status,
1819
1920 /// 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 {
2122 return self._get_mode_data(self, ip6_mode_data, mnp_config_data, snp_mode_data);
2223 }
2324
2425 /// 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 {
2627 return self._configure(self, ip6_config_data);
2728 }
2829
2930 /// 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 {
3132 return self._groups(self, join_flag, group_address);
3233 }
3334
3435 /// 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 {
3637 return self._routes(self, delete_route, destination, prefix_length, gateway_address);
3738 }
3839
3940 /// 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 {
4142 return self._neighbors(self, delete_flag, target_ip6_address, target_link_address, timeout, override);
4243 }
4344
4445 /// 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 {
4647 return self._transmit(self, token);
4748 }
4849
4950 /// 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 {
5152 return self._receive(self, token);
5253 }
5354
5455 /// 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 {
5657 return self._cancel(self, token);
5758 }
5859
5960 /// 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 {
6162 return self._poll(self);
6263 }
6364
......@@ -138,6 +139,6 @@ pub const Ip6IcmpType = extern struct {
138139
139140pub const Ip6CompletionToken = extern struct {
140141 event: Event,
141 status: usize,
142 status: Status,
142143 packet: *c_void, // union TODO
143144};
lib/std/os/uefi/protocols/ip6_service_binding_protocol.zig+5-4
......@@ -1,16 +1,17 @@
11const uefi = @import("std").os.uefi;
22const Handle = uefi.Handle;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56pub const Ip6ServiceBindingProtocol = extern struct {
6 _create_child: extern fn (*const Ip6ServiceBindingProtocol, *?Handle) usize,
7 _destroy_child: extern fn (*const Ip6ServiceBindingProtocol, Handle) usize,
7 _create_child: extern fn (*const Ip6ServiceBindingProtocol, *?Handle) Status,
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 {
1011 return self._create_child(self, handle);
1112 }
1213
13 pub fn destroyChild(self: *const Ip6ServiceBindingProtocol, handle: Handle) usize {
14 pub fn destroyChild(self: *const Ip6ServiceBindingProtocol, handle: Handle) Status {
1415 return self._destroy_child(self, handle);
1516 }
1617
lib/std/os/uefi/protocols/loaded_image_protocol.zig+13-3
......@@ -1,6 +1,7 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33const Handle = uefi.Handle;
4const Status = uefi.Status;
45const SystemTable = uefi.tables.SystemTable;
56const MemoryType = uefi.tables.MemoryType;
67const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
......@@ -13,15 +14,15 @@ pub const LoadedImageProtocol = extern struct {
1314 file_path: *DevicePathProtocol,
1415 reserved: *c_void,
1516 load_options_size: u32,
16 load_options: *c_void,
17 load_options: ?*c_void,
1718 image_base: [*]u8,
1819 image_size: u64,
1920 image_code_type: MemoryType,
2021 image_data_type: MemoryType,
21 _unload: extern fn (*const LoadedImageProtocol, Handle) usize,
22 _unload: extern fn (*const LoadedImageProtocol, Handle) Status,
2223
2324 /// 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 {
2526 return self._unload(self, handle);
2627 }
2728
......@@ -34,3 +35,12 @@ pub const LoadedImageProtocol = extern struct {
3435 .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b },
3536 };
3637};
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 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33const Event = uefi.Event;
4const Status = uefi.Status;
45const Time = uefi.Time;
56const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
67const MacAddress = uefi.protocols.MacAddress;
78
89pub const ManagedNetworkProtocol = extern struct {
9 _get_mode_data: extern fn (*const ManagedNetworkProtocol, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,
10 _configure: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkConfigData) usize,
11 _mcast_ip_to_mac: extern fn (*const ManagedNetworkProtocol, bool, *const c_void, *MacAddress) usize,
12 _groups: extern fn (*const ManagedNetworkProtocol, bool, ?*const MacAddress) usize,
13 _transmit: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) usize,
14 _receive: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) usize,
15 _cancel: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkCompletionToken) usize,
10 _get_mode_data: extern fn (*const ManagedNetworkProtocol, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) Status,
11 _configure: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkConfigData) Status,
12 _mcast_ip_to_mac: extern fn (*const ManagedNetworkProtocol, bool, *const c_void, *MacAddress) Status,
13 _groups: extern fn (*const ManagedNetworkProtocol, bool, ?*const MacAddress) Status,
14 _transmit: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) Status,
15 _receive: extern fn (*const ManagedNetworkProtocol, *const ManagedNetworkCompletionToken) Status,
16 _cancel: extern fn (*const ManagedNetworkProtocol, ?*const ManagedNetworkCompletionToken) Status,
1617 _poll: extern fn (*const ManagedNetworkProtocol) usize,
1718
1819 /// Returns the operational parameters for the current MNP child driver.
1920 /// 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 {
2122 return self._get_mode_data(self, mnp_config_data, snp_mode_data);
2223 }
2324
2425 /// 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 {
2627 return self._configure(self, mnp_config_data);
2728 }
2829
2930 /// Translates an IP multicast address to a hardware (MAC) multicast address.
3031 /// 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 {
3233 return self._mcast_ip_to_mac(self, ipv6flag, ipaddress);
3334 }
3435
3536 /// Enables and disables receive filters for multicast address.
3637 /// 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 {
3839 return self._groups(self, join_flag, mac_address);
3940 }
4041
4142 /// 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 {
4344 return self._transmit(self, token);
4445 }
4546
4647 /// 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 {
4849 return self._receive(self, token);
4950 }
5051
5152 /// 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 {
5354 return self._cancel(self, token);
5455 }
5556
5657 /// 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 {
5859 return self._poll(self);
5960 }
6061
......@@ -83,7 +84,7 @@ pub const ManagedNetworkConfigData = extern struct {
8384
8485pub const ManagedNetworkCompletionToken = extern struct {
8586 event: Event,
86 status: usize,
87 status: Status,
8788 packet: extern union {
8889 RxData: *ManagedNetworkReceiveData,
8990 TxData: *ManagedNetworkTransmitData,
lib/std/os/uefi/protocols/managed_network_service_binding_protocol.zig+5-4
......@@ -1,16 +1,17 @@
11const uefi = @import("std").os.uefi;
22const Handle = uefi.Handle;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56pub const ManagedNetworkServiceBindingProtocol = extern struct {
6 _create_child: extern fn (*const ManagedNetworkServiceBindingProtocol, *?Handle) usize,
7 _destroy_child: extern fn (*const ManagedNetworkServiceBindingProtocol, Handle) usize,
7 _create_child: extern fn (*const ManagedNetworkServiceBindingProtocol, *?Handle) Status,
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 {
1011 return self._create_child(self, handle);
1112 }
1213
13 pub fn destroyChild(self: *const ManagedNetworkServiceBindingProtocol, handle: Handle) usize {
14 pub fn destroyChild(self: *const ManagedNetworkServiceBindingProtocol, handle: Handle) Status {
1415 return self._destroy_child(self, handle);
1516 }
1617
lib/std/os/uefi/protocols/rng_protocol.zig+5-4
......@@ -1,18 +1,19 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
3const Status = uefi.Status;
34
45/// Random Number Generator protocol
56pub const RNGProtocol = extern struct {
6 _get_info: extern fn (*const RNGProtocol, *usize, [*]align(8) Guid) usize,
7 _get_rng: extern fn (*const RNGProtocol, ?*align(8) const Guid, usize, [*]u8) usize,
7 _get_info: extern fn (*const RNGProtocol, *usize, [*]align(8) Guid) Status,
8 _get_rng: extern fn (*const RNGProtocol, ?*align(8) const Guid, usize, [*]u8) Status,
89
910 /// 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 {
1112 return self._get_info(self, list_size, list);
1213 }
1314
1415 /// 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 {
1617 return self._get_rng(self, algo, value_length, value);
1718 }
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 @@
11const uefi = @import("std").os.uefi;
22const Event = uefi.Event;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56pub const SimpleNetworkProtocol = extern struct {
67 revision: u64,
7 _start: extern fn (*const SimpleNetworkProtocol) usize,
8 _stop: extern fn (*const SimpleNetworkProtocol) usize,
9 _initialize: extern fn (*const SimpleNetworkProtocol, usize, usize) usize,
10 _reset: extern fn (*const SimpleNetworkProtocol, bool) usize,
11 _shutdown: extern fn (*const SimpleNetworkProtocol) usize,
12 _receive_filters: extern fn (*const SimpleNetworkProtocol, SimpleNetworkReceiveFilter, SimpleNetworkReceiveFilter, bool, usize, ?[*]const MacAddress) usize,
13 _station_address: extern fn (*const SimpleNetworkProtocol, bool, ?*const MacAddress) usize,
14 _statistics: extern fn (*const SimpleNetworkProtocol, bool, ?*usize, ?*NetworkStatistics) usize,
15 _mcast_ip_to_mac: extern fn (*const SimpleNetworkProtocol, bool, *const c_void, *MacAddress) usize,
16 _nvdata: extern fn (*const SimpleNetworkProtocol, bool, usize, usize, [*]u8) usize,
17 _get_status: extern fn (*const SimpleNetworkProtocol, *SimpleNetworkInterruptStatus, ?*?[*]u8) usize,
18 _transmit: extern fn (*const SimpleNetworkProtocol, usize, usize, [*]const u8, ?*const MacAddress, ?*const MacAddress, ?*const u16) usize,
19 _receive: extern fn (*const SimpleNetworkProtocol, ?*usize, *usize, [*]u8, ?*MacAddress, ?*MacAddress, ?*u16) usize,
8 _start: extern fn (*const SimpleNetworkProtocol) Status,
9 _stop: extern fn (*const SimpleNetworkProtocol) Status,
10 _initialize: extern fn (*const SimpleNetworkProtocol, usize, usize) Status,
11 _reset: extern fn (*const SimpleNetworkProtocol, bool) Status,
12 _shutdown: extern fn (*const SimpleNetworkProtocol) Status,
13 _receive_filters: extern fn (*const SimpleNetworkProtocol, SimpleNetworkReceiveFilter, SimpleNetworkReceiveFilter, bool, usize, ?[*]const MacAddress) Status,
14 _station_address: extern fn (*const SimpleNetworkProtocol, bool, ?*const MacAddress) Status,
15 _statistics: extern fn (*const SimpleNetworkProtocol, bool, ?*usize, ?*NetworkStatistics) Status,
16 _mcast_ip_to_mac: extern fn (*const SimpleNetworkProtocol, bool, *const c_void, *MacAddress) Status,
17 _nvdata: extern fn (*const SimpleNetworkProtocol, bool, usize, usize, [*]u8) Status,
18 _get_status: extern fn (*const SimpleNetworkProtocol, *SimpleNetworkInterruptStatus, ?*?[*]u8) Status,
19 _transmit: extern fn (*const SimpleNetworkProtocol, usize, usize, [*]const u8, ?*const MacAddress, ?*const MacAddress, ?*const u16) Status,
20 _receive: extern fn (*const SimpleNetworkProtocol, ?*usize, *usize, [*]u8, ?*MacAddress, ?*MacAddress, ?*u16) Status,
2021 wait_for_packet: Event,
2122 mode: *SimpleNetworkMode,
2223
2324 /// 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 {
2526 return self._start(self);
2627 }
2728
2829 /// 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 {
3031 return self._stop(self);
3132 }
3233
3334 /// 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 {
3536 return self._initialize(self, extra_rx_buffer_size, extra_tx_buffer_size);
3637 }
3738
3839 /// 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 {
4041 return self._reset(self, extended_verification);
4142 }
4243
4344 /// 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 {
4546 return self._shutdown(self);
4647 }
4748
4849 /// 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 {
5051 return self._receive_filters(self, enable, disable, reset_mcast_filter, mcast_filter_cnt, mcast_filter);
5152 }
5253
5354 /// 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 {
5556 return self._station_address(self, reset, new);
5657 }
5758
5859 /// 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 {
6061 return self._statistics(self, reset_, statistics_size, statistics_table);
6162 }
6263
6364 /// 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 {
6566 return self._mcast_ip_to_mac(self, ipv6, ip, mac);
6667 }
6768
6869 /// 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 {
7071 return self._nvdata(self, read_write, offset, buffer_size, buffer);
7172 }
7273
7374 /// 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 {
7576 return self._get_status(self, interrupt_status, tx_buf);
7677 }
7778
7879 /// 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 {
8081 return self._transmit(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
8182 }
8283
8384 /// 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 {
8586 return self._receive(self, header_size, buffer_size, buffer, src_addr, dest_addr, protocol);
8687 }
8788
lib/std/os/uefi/protocols/simple_pointer_protocol.zig+5-4
......@@ -1,21 +1,22 @@
11const uefi = @import("std").os.uefi;
22const Event = uefi.Event;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56/// Protocol for mice
67pub const SimplePointerProtocol = struct {
7 _reset: extern fn (*const SimplePointerProtocol, bool) usize,
8 _get_state: extern fn (*const SimplePointerProtocol, *SimplePointerState) usize,
8 _reset: extern fn (*const SimplePointerProtocol, bool) Status,
9 _get_state: extern fn (*const SimplePointerProtocol, *SimplePointerState) Status,
910 wait_for_input: Event,
1011 mode: *SimplePointerMode,
1112
1213 /// 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 {
1415 return self._reset(self, verify);
1516 }
1617
1718 /// 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 {
1920 return self._get_state(self, state);
2021 }
2122
lib/std/os/uefi/protocols/simple_text_input_ex_protocol.zig+11-10
......@@ -1,38 +1,39 @@
11const uefi = @import("std").os.uefi;
22const Event = uefi.Event;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56/// Character input devices, e.g. Keyboard
67pub const SimpleTextInputExProtocol = extern struct {
7 _reset: extern fn (*const SimpleTextInputExProtocol, bool) usize,
8 _read_key_stroke_ex: extern fn (*const SimpleTextInputExProtocol, *KeyData) usize,
8 _reset: extern fn (*const SimpleTextInputExProtocol, bool) Status,
9 _read_key_stroke_ex: extern fn (*const SimpleTextInputExProtocol, *KeyData) Status,
910 wait_for_key_ex: Event,
10 _set_state: extern fn (*const SimpleTextInputExProtocol, *const u8) usize,
11 _register_key_notify: extern fn (*const SimpleTextInputExProtocol, *const KeyData, extern fn (*const KeyData) usize, **c_void) usize,
12 _unregister_key_notify: extern fn (*const SimpleTextInputExProtocol, *const c_void) usize,
11 _set_state: extern fn (*const SimpleTextInputExProtocol, *const u8) Status,
12 _register_key_notify: extern fn (*const SimpleTextInputExProtocol, *const KeyData, extern fn (*const KeyData) usize, **c_void) Status,
13 _unregister_key_notify: extern fn (*const SimpleTextInputExProtocol, *const c_void) Status,
1314
1415 /// 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 {
1617 return self._reset(self, verify);
1718 }
1819
1920 /// 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 {
2122 return self._read_key_stroke_ex(self, key_data);
2223 }
2324
2425 /// 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 {
2627 return self._set_state(self, state);
2728 }
2829
2930 /// 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 {
3132 return self._register_key_notify(self, key_data, notify, handle);
3233 }
3334
3435 /// 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 {
3637 return self._unregister_key_notify(self, handle);
3738 }
3839
lib/std/os/uefi/protocols/simple_text_input_protocol.zig+5-3
......@@ -1,20 +1,22 @@
11const uefi = @import("std").os.uefi;
22const Event = uefi.Event;
33const Guid = uefi.Guid;
4const InputKey = uefi.protocols.InputKey;
5const Status = uefi.Status;
46
57/// Character input devices, e.g. Keyboard
68pub const SimpleTextInputProtocol = extern struct {
79 _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,
911 wait_for_key: Event,
1012
1113 /// 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 {
1315 return self._reset(self, verify);
1416 }
1517
1618 /// 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 {
1820 return self._read_key_stroke(self, input_key);
1921 }
2022
lib/std/os/uefi/protocols/simple_text_output_protocol.zig+19-18
......@@ -1,61 +1,62 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
3const Status = uefi.Status;
34
45/// Character output devices
56pub const SimpleTextOutputProtocol = extern struct {
6 _reset: extern fn (*const SimpleTextOutputProtocol, bool) usize,
7 _output_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) usize,
8 _test_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) usize,
9 _query_mode: extern fn (*const SimpleTextOutputProtocol, usize, *usize, *usize) usize,
10 _set_mode: extern fn (*const SimpleTextOutputProtocol, usize) usize,
11 _set_attribute: extern fn (*const SimpleTextOutputProtocol, usize) usize,
12 _clear_screen: extern fn (*const SimpleTextOutputProtocol) usize,
13 _set_cursor_position: extern fn (*const SimpleTextOutputProtocol, usize, usize) usize,
14 _enable_cursor: extern fn (*const SimpleTextOutputProtocol, bool) usize,
7 _reset: extern fn (*const SimpleTextOutputProtocol, bool) Status,
8 _output_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) Status,
9 _test_string: extern fn (*const SimpleTextOutputProtocol, [*:0]const u16) Status,
10 _query_mode: extern fn (*const SimpleTextOutputProtocol, usize, *usize, *usize) Status,
11 _set_mode: extern fn (*const SimpleTextOutputProtocol, usize) Status,
12 _set_attribute: extern fn (*const SimpleTextOutputProtocol, usize) Status,
13 _clear_screen: extern fn (*const SimpleTextOutputProtocol) Status,
14 _set_cursor_position: extern fn (*const SimpleTextOutputProtocol, usize, usize) Status,
15 _enable_cursor: extern fn (*const SimpleTextOutputProtocol, bool) Status,
1516 mode: *SimpleTextOutputMode,
1617
1718 /// 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 {
1920 return self._reset(self, verify);
2021 }
2122
2223 /// 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 {
2425 return self._output_string(self, msg);
2526 }
2627
2728 /// 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 {
2930 return self._test_string(self, msg);
3031 }
3132
3233 /// 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 {
3435 return self._query_mode(self, mode_number, columns, rows);
3536 }
3637
3738 /// 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 {
3940 return self._set_mode(self, mode_number);
4041 }
4142
4243 /// 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 {
4445 return self._set_attribute(self, attribute);
4546 }
4647
4748 /// 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 {
4950 return self._clear_screen(self);
5051 }
5152
5253 /// 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 {
5455 return self._set_cursor_position(self, column, row);
5556 }
5657
5758 /// 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 {
5960 return self._enable_cursor(self, visible);
6061 }
6162
lib/std/os/uefi/protocols/udp6_protocol.zig+17-16
......@@ -1,6 +1,7 @@
11const uefi = @import("std").os.uefi;
22const Guid = uefi.Guid;
33const Event = uefi.Event;
4const Status = uefi.Status;
45const Time = uefi.Time;
56const Ip6ModeData = uefi.protocols.Ip6ModeData;
67const Ip6Address = uefi.protocols.Ip6Address;
......@@ -8,39 +9,39 @@ const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData;
89const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode;
910
1011pub const Udp6Protocol = extern struct {
11 _get_mode_data: extern fn (*const Udp6Protocol, ?*Udp6ConfigData, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) usize,
12 _configure: extern fn (*const Udp6Protocol, ?*const Udp6ConfigData) usize,
13 _groups: extern fn (*const Udp6Protocol, bool, ?*const Ip6Address) usize,
14 _transmit: extern fn (*const Udp6Protocol, *Udp6CompletionToken) usize,
15 _receive: extern fn (*const Udp6Protocol, *Udp6CompletionToken) usize,
16 _cancel: extern fn (*const Udp6Protocol, ?*Udp6CompletionToken) usize,
17 _poll: extern fn (*const Udp6Protocol) usize,
18
19 pub fn getModeData(self: *const Udp6Protocol, udp6_config_data: ?*Udp6ConfigData, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) usize {
12 _get_mode_data: extern fn (*const Udp6Protocol, ?*Udp6ConfigData, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) Status,
13 _configure: extern fn (*const Udp6Protocol, ?*const Udp6ConfigData) Status,
14 _groups: extern fn (*const Udp6Protocol, bool, ?*const Ip6Address) Status,
15 _transmit: extern fn (*const Udp6Protocol, *Udp6CompletionToken) Status,
16 _receive: extern fn (*const Udp6Protocol, *Udp6CompletionToken) Status,
17 _cancel: extern fn (*const Udp6Protocol, ?*Udp6CompletionToken) Status,
18 _poll: extern fn (*const Udp6Protocol) Status,
19
20 pub fn getModeData(self: *const Udp6Protocol, udp6_config_data: ?*Udp6ConfigData, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status {
2021 return self._get_mode_data(self, udp6_config_data, ip6_mode_data, mnp_config_data, snp_mode_data);
2122 }
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 {
2425 return self._configure(self, udp6_config_data);
2526 }
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 {
2829 return self._groups(self, join_flag, multicast_address);
2930 }
3031
31 pub fn transmit(self: *const Udp6Protocol, token: *Udp6CompletionToken) usize {
32 pub fn transmit(self: *const Udp6Protocol, token: *Udp6CompletionToken) Status {
3233 return self._transmit(self, token);
3334 }
3435
35 pub fn receive(self: *const Udp6Protocol, token: *Udp6CompletionToken) usize {
36 pub fn receive(self: *const Udp6Protocol, token: *Udp6CompletionToken) Status {
3637 return self._receive(self, token);
3738 }
3839
39 pub fn cancel(self: *const Udp6Protocol, token: ?*Udp6CompletionToken) usize {
40 pub fn cancel(self: *const Udp6Protocol, token: ?*Udp6CompletionToken) Status {
4041 return self._cancel(self, token);
4142 }
4243
43 pub fn poll(self: *const Udp6Protocol) usize {
44 pub fn poll(self: *const Udp6Protocol) Status {
4445 return self._poll(self);
4546 }
4647
......@@ -70,7 +71,7 @@ pub const Udp6ConfigData = extern struct {
7071
7172pub const Udp6CompletionToken = extern struct {
7273 event: Event,
73 status: usize,
74 Status: usize,
7475 packet: extern union {
7576 RxData: *Udp6ReceiveData,
7677 TxData: *Udp6TransmitData,
lib/std/os/uefi/protocols/udp6_service_binding_protocol.zig+5-4
......@@ -1,16 +1,17 @@
11const uefi = @import("std").os.uefi;
22const Handle = uefi.Handle;
33const Guid = uefi.Guid;
4const Status = uefi.Status;
45
56pub const Udp6ServiceBindingProtocol = extern struct {
6 _create_child: extern fn (*const Udp6ServiceBindingProtocol, *?Handle) usize,
7 _destroy_child: extern fn (*const Udp6ServiceBindingProtocol, Handle) usize,
7 _create_child: extern fn (*const Udp6ServiceBindingProtocol, *?Handle) Status,
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 {
1011 return self._create_child(self, handle);
1112 }
1213
13 pub fn destroyChild(self: *const Udp6ServiceBindingProtocol, handle: Handle) usize {
14 pub fn destroyChild(self: *const Udp6ServiceBindingProtocol, handle: Handle) Status {
1415 return self._destroy_child(self, handle);
1516 }
1617
lib/std/os/uefi/status.zig+100-82
......@@ -1,124 +1,142 @@
11const high_bit = 1 << @typeInfo(usize).Int.bits - 1;
22
3/// The operation completed successfully.
4pub const success: usize = 0;
3pub const Status = extern enum(usize) {
4 /// The operation completed successfully.
5 Success = 0,
56
6/// The image failed to load.
7pub const load_error: usize = high_bit | 1;
7 /// The image failed to load.
8 LoadError = high_bit | 1,
89
9/// A parameter was incorrect.
10pub const invalid_parameter: usize = high_bit | 2;
10 /// A parameter was incorrect.
11 InvalidParameter = high_bit | 2,
1112
12/// The operation is not supported.
13pub const unsupported: usize = high_bit | 3;
13 /// The operation is not supported.
14 Unsupported = high_bit | 3,
1415
15/// The buffer was not the proper size for the request.
16pub const bad_buffer_size: usize = high_bit | 4;
16 /// The buffer was not the proper size for the request.
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.
19pub const buffer_too_small: usize = high_bit | 5;
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.
20 BufferTooSmall = high_bit | 5,
2021
21/// There is no data pending upon return.
22pub const not_ready: usize = high_bit | 6;
22 /// There is no data pending upon return.
23 NotReady = high_bit | 6,
2324
24/// The physical device reported an error while attempting the operation.
25pub const device_error: usize = high_bit | 7;
25 /// The physical device reported an error while attempting the operation.
26 DeviceError = high_bit | 7,
2627
27/// The device cannot be written to.
28pub const write_protected: usize = high_bit | 8;
28 /// The device cannot be written to.
29 WriteProtected = high_bit | 8,
2930
30/// A resource has run out.
31pub const out_of_resources: usize = high_bit | 9;
31 /// A resource has run out.
32 OutOfResources = high_bit | 9,
3233
33/// An inconstancy was detected on the file system causing the operating to fail.
34pub const volume_corrupted: usize = high_bit | 10;
34 /// An inconstancy was detected on the file system causing the operating to fail.
35 VolumeCorrupted = high_bit | 10,
3536
36/// There is no more space on the file system.
37pub const volume_full: usize = high_bit | 11;
37 /// There is no more space on the file system.
38 VolumeFull = high_bit | 11,
3839
39/// The device does not contain any medium to perform the operation.
40pub const no_media: usize = high_bit | 12;
40 /// The device does not contain any medium to perform the operation.
41 NoMedia = high_bit | 12,
4142
42/// The medium in the device has changed since the last access.
43pub const media_changed: usize = high_bit | 13;
43 /// The medium in the device has changed since the last access.
44 MediaChanged = high_bit | 13,
4445
45/// The item was not found.
46pub const not_found: usize = high_bit | 14;
46 /// The item was not found.
47 NotFound = high_bit | 14,
4748
48/// Access was denied.
49pub const access_denied: usize = high_bit | 15;
49 /// Access was denied.
50 AccessDenied = high_bit | 15,
5051
51/// The server was not found or did not respond to the request.
52pub const no_response: usize = high_bit | 16;
52 /// The server was not found or did not respond to the request.
53 NoResponse = high_bit | 16,
5354
54/// A mapping to a device does not exist.
55pub const no_mapping: usize = high_bit | 17;
55 /// A mapping to a device does not exist.
56 NoMapping = high_bit | 17,
5657
57/// The timeout time expired.
58pub const timeout: usize = high_bit | 18;
58 /// The timeout time expired.
59 Timeout = high_bit | 18,
5960
60/// The protocol has not been started.
61pub const not_started: usize = high_bit | 19;
61 /// The protocol has not been started.
62 NotStarted = high_bit | 19,
6263
63/// The protocol has already been started.
64pub const already_started: usize = high_bit | 20;
64 /// The protocol has already been started.
65 AlreadyStarted = high_bit | 20,
6566
66/// The operation was aborted.
67pub const aborted: usize = high_bit | 21;
67 /// The operation was aborted.
68 Aborted = high_bit | 21,
6869
69/// An ICMP error occurred during the network operation.
70pub const icmp_error: usize = high_bit | 22;
70 /// An ICMP error occurred during the network operation.
71 IcmpError = high_bit | 22,
7172
72/// A TFTP error occurred during the network operation.
73pub const tftp_error: usize = high_bit | 23;
73 /// A TFTP error occurred during the network operation.
74 TftpError = high_bit | 23,
7475
75/// A protocol error occurred during the network operation.
76pub const protocol_error: usize = high_bit | 24;
76 /// A protocol error occurred during the network operation.
77 ProtocolError = high_bit | 24,
7778
78/// The function encountered an internal version that was incompatible with a version requested by the caller.
79pub const incompatible_version: usize = high_bit | 25;
79 /// The function encountered an internal version that was incompatible with a version requested by the caller.
80 IncompatibleVersion = high_bit | 25,
8081
81/// The function was not performed due to a security violation.
82pub const security_violation: usize = high_bit | 26;
82 /// The function was not performed due to a security violation.
83 SecurityViolation = high_bit | 26,
8384
84/// A CRC error was detected.
85pub const crc_error: usize = high_bit | 27;
85 /// A CRC error was detected.
86 CrcError = high_bit | 27,
8687
87/// Beginning or end of media was reached
88pub const end_of_media: usize = high_bit | 28;
88 /// Beginning or end of media was reached
89 EndOfMedia = high_bit | 28,
8990
90/// The end of the file was reached.
91pub const end_of_file: usize = high_bit | 31;
91 /// The end of the file was reached.
92 EndOfFile = high_bit | 31,
9293
93/// The language specified was invalid.
94pub const invalid_language: usize = high_bit | 32;
94 /// The language specified was invalid.
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.
97pub const compromised_data: usize = high_bit | 33;
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.
98 CompromisedData = high_bit | 33,
9899
99/// There is an address conflict address allocation
100pub const ip_address_conflict: usize = high_bit | 34;
100 /// There is an address conflict address allocation
101 IpAddressConflict = high_bit | 34,
101102
102/// A HTTP error occurred during the network operation.
103pub const http_error: usize = high_bit | 35;
103 /// A HTTP error occurred during the network operation.
104 HttpError = high_bit | 35,
104105
105/// The string contained one or more characters that the device could not render and were skipped.
106pub const warn_unknown_glyph: usize = 1;
106 NetworkUnreachable = high_bit | 100,
107107
108/// The handle was closed, but the file was not deleted.
109pub const warn_delete_failure: usize = 2;
108 HostUnreachable = high_bit | 101,
110109
111/// The handle was closed, but the data to the file was not flushed properly.
112pub const warn_write_failure: usize = 3;
110 ProtocolUnreachable = high_bit | 102,
113111
114/// The resulting buffer was too small, and the data was truncated to the buffer size.
115pub const warn_buffer_too_small: usize = 4;
112 PortUnreachable = high_bit | 103,
116113
117/// The data has not been updated within the timeframe set by localpolicy for this type of data.
118pub const warn_stale_data: usize = 5;
114 ConnectionFin = high_bit | 104,
119115
120/// The resulting buffer contains UEFI-compliant file system.
121pub const warn_file_system: usize = 6;
116 ConnectionReset = high_bit | 105,
122117
123/// The operation will be processed across a system reset.
124pub const warn_reset_required: usize = 7;
118 ConnectionRefused = high_bit | 106,
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 @@
1pub const AllocateType = @import("tables/boot_services.zig").AllocateType;
12pub const BootServices = @import("tables/boot_services.zig").BootServices;
23pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable;
34pub 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;
22const Event = uefi.Event;
33const Guid = uefi.Guid;
44const Handle = uefi.Handle;
5const Status = uefi.Status;
56const TableHeader = uefi.tables.TableHeader;
67const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
78
......@@ -19,101 +20,120 @@ const DevicePathProtocol = uefi.protocols.DevicePathProtocol;
1920pub const BootServices = extern struct {
2021 hdr: TableHeader,
2122
22 raiseTpl: usize, // TODO
23 restoreTpl: usize, // TODO
24 allocatePages: usize, // TODO
25 freePages: usize, // TODO
23 /// Raises a task's priority level and returns its previous level.
24 raiseTpl: extern fn (usize) usize,
25
26 /// 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
2735 /// 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
3038 /// Allocates pool memory.
31 allocatePool: extern fn (MemoryType, usize, *align(8) [*]u8) usize,
39 allocatePool: extern fn (MemoryType, usize, *[*]align(8) u8) Status,
3240
3341 /// Returns pool memory to the system.
34 freePool: extern fn ([*]align(8) u8) usize,
42 freePool: extern fn ([*]align(8) u8) Status,
3543
3644 /// 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
3947 /// 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
4250 /// 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
4553 /// Signals an event.
46 signalEvent: extern fn (Event) usize,
54 signalEvent: extern fn (Event) Status,
4755
4856 /// Closes an event.
49 closeEvent: extern fn (Event) usize,
57 closeEvent: extern fn (Event) Status,
5058
5159 /// 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, // TODO
55 reinstallProtocolInterface: usize, // TODO
56 uninstallProtocolInterface: usize, // TODO
62 installProtocolInterface: Status, // TODO
63 reinstallProtocolInterface: Status, // TODO
64 uninstallProtocolInterface: Status, // TODO
5765
5866 /// 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
6169 reserved: *c_void,
6270
63 registerProtocolNotify: usize, // TODO
64 locateHandle: usize, // TODO
65 locateDevicePath: usize, // TODO
66 installConfigurationTable: usize, // TODO
71 registerProtocolNotify: Status, // TODO
72
73 /// Returns an array of handles that support a specified protocol.
74 locateHandle: extern fn (LocateSearchType, ?*align(8) const Guid, ?*const c_void, *usize, [*]Handle) Status,
75
76 locateDevicePath: Status, // TODO
77 installConfigurationTable: Status, // TODO
6778
6879 /// 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
7182 /// 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
7485 /// 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
7788 /// Unloads an image.
78 unloadImage: extern fn (Handle) usize,
89 unloadImage: extern fn (Handle) Status,
7990
8091 /// Terminates all boot services.
81 exitBootServices: extern fn (Handle, usize) usize,
92 exitBootServices: extern fn (Handle, usize) Status,
8293
83 getNextMonotonicCount: usize, // TODO
94 /// Returns a monotonically increasing count for the platform.
95 getNextMonotonicCount: extern fn (*u64) Status,
8496
8597 /// Induces a fine-grained stall.
86 stall: extern fn (usize) usize,
98 stall: extern fn (usize) Status,
8799
88100 /// 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, // TODO
92 disconnectController: usize, // TODO
103 connectController: Status, // TODO
104 disconnectController: Status, // TODO
93105
94106 /// 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
97109 /// 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
100112 /// 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, // TODO
115 /// 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
105118 /// 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
108121 /// 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, // TODO
112 uninstallMultipleProtocolInterfaces: usize, // TODO
113 calculateCrc32: usize, // TODO
114 copyMem: usize, // TODO
115 setMem: usize, // TODO
116 createEventEx: usize, // TODO
127 /// Computes and returns a 32-bit CRC for a data buffer.
128 calculateCrc32: extern fn ([*]const u8, usize, *u32) Status,
129
130 /// Copies the contents of one buffer to another buffer
131 copyMem: extern fn ([*]u8, [*]const u8, usize) void,
132
133 /// Fills a buffer with a specified value
134 setMem: extern fn ([*]u8, usize, u8) void,
135
136 createEventEx: Status, // TODO
117137
118138 pub const signature: u64 = 0x56524553544f4f42;
119139
......@@ -187,13 +207,13 @@ pub const LocateSearchType = extern enum(u32) {
187207};
188208
189209pub const OpenProtocolAttributes = packed struct {
190 by_handle_protocol: bool,
191 get_protocol: bool,
192 test_protocol: bool,
193 by_child_controller: bool,
194 by_driver: bool,
195 exclusive: bool,
196 _pad: u26,
210 by_handle_protocol: bool = false,
211 get_protocol: bool = false,
212 test_protocol: bool = false,
213 by_child_controller: bool = false,
214 by_driver: bool = false,
215 exclusive: bool = false,
216 _pad: u26 = undefined,
197217};
198218
199219pub const ProtocolInformationEntry = extern struct {
......@@ -202,3 +222,9 @@ pub const ProtocolInformationEntry = extern struct {
202222 attributes: OpenProtocolAttributes,
203223 open_count: u32,
204224};
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;
33const TableHeader = uefi.tables.TableHeader;
44const Time = uefi.Time;
55const TimeCapabilities = uefi.TimeCapabilities;
6const Status = uefi.Status;
67
78/// Runtime services are provided by the firmware before and after exitBootServices has been called.
89///
......@@ -16,31 +17,31 @@ pub const RuntimeServices = extern struct {
1617 hdr: TableHeader,
1718
1819 /// 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, // TODO
22 getWakeupTime: usize, // TODO
23 setWakeupTime: usize, // TODO
24 setVirtualAddressMap: usize, // TODO
25 convertPointer: usize, // TODO
22 setTime: Status, // TODO
23 getWakeupTime: Status, // TODO
24 setWakeupTime: Status, // TODO
25 setVirtualAddressMap: Status, // TODO
26 convertPointer: Status, // TODO
2627
2728 /// 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
3031 /// 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
3334 /// 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, // TODO
37 getNextHighMonotonicCount: Status, // TODO
3738
3839 /// 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, // TODO
42 queryCapsuleCapabilities: usize, // TODO
43 queryVariableInfo: usize, // TODO
42 updateCapsule: Status, // TODO
43 queryCapsuleCapabilities: Status, // TODO
44 queryVariableInfo: Status, // TODO
4445
4546 pub const signature: u64 = 0x56524553544e5552;
4647};
lib/std/os/windows.zig+3
......@@ -407,6 +407,7 @@ pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64) ReadFileError!usiz
407407 switch (kernel32.GetLastError()) {
408408 .OPERATION_ABORTED => continue,
409409 .BROKEN_PIPE => return index,
410 .HANDLE_EOF => return index,
410411 else => |err| return unexpectedError(err),
411412 }
412413 }
......@@ -591,6 +592,8 @@ pub const CreateDirectoryError = error{
591592 FileNotFound,
592593 NoDevice,
593594 AccessDenied,
595 InvalidUtf8,
596 BadPathName,
594597 Unexpected,
595598};
596599
lib/std/os/windows/bits.zig+4
......@@ -225,6 +225,10 @@ pub const FILE_POSITION_INFORMATION = extern struct {
225225 CurrentByteOffset: LARGE_INTEGER,
226226};
227227
228pub const FILE_END_OF_FILE_INFORMATION = extern struct {
229 EndOfFile: LARGE_INTEGER,
230};
231
228232pub const FILE_MODE_INFORMATION = extern struct {
229233 Mode: ULONG,
230234};
lib/std/os/windows/kernel32.zig+1
......@@ -8,6 +8,7 @@ pub extern "kernel32" fn CancelIoEx(hFile: HANDLE, lpOverlapped: LPOVERLAPPED) c
88pub extern "kernel32" fn CloseHandle(hObject: HANDLE) callconv(.Stdcall) BOOL;
99
1010pub 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
1213pub extern "kernel32" fn CreateEventExW(
1314 lpEventAttributes: ?*SECURITY_ATTRIBUTES,
lib/std/os/windows/ntdll.zig+7
......@@ -16,6 +16,13 @@ pub extern "NtDll" fn NtQueryInformationFile(
1616 Length: ULONG,
1717 FileInformationClass: FILE_INFORMATION_CLASS,
1818) 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
2027pub extern "NtDll" fn NtQueryAttributesFile(
2128 ObjectAttributes: *OBJECT_ATTRIBUTES,
lib/std/pdb.zig+8-16
......@@ -495,8 +495,7 @@ const Msf = struct {
495495 streams: []MsfStream,
496496
497497 fn openFile(self: *Msf, allocator: *mem.Allocator, file: File) !void {
498 var file_stream = file.inStream();
499 const in = &file_stream.stream;
498 const in = file.inStream();
500499
501500 const superblock = try in.readStruct(SuperBlock);
502501
......@@ -529,7 +528,7 @@ const Msf = struct {
529528 );
530529
531530 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);
533532 const stream_sizes = try allocator.alloc(u32, stream_count);
534533 defer allocator.free(stream_sizes);
535534
......@@ -538,7 +537,7 @@ const Msf = struct {
538537 // and must be taken into account when resolving stream indices.
539538 const Nil = 0xFFFFFFFF;
540539 for (stream_sizes) |*s, i| {
541 const size = try self.directory.stream.readIntLittle(u32);
540 const size = try self.directory.inStream().readIntLittle(u32);
542541 s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize);
543542 }
544543
......@@ -553,7 +552,7 @@ const Msf = struct {
553552 var blocks = try allocator.alloc(u32, size);
554553 var j: u32 = 0;
555554 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);
557556 const n = (block_id % superblock.BlockSize);
558557 // 0 is for SuperBlock, 1 and 2 for FPMs.
559558 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 {
632631 blocks: []u32 = undefined,
633632 block_size: u32 = undefined,
634633
635 /// Implementation of InStream trait for Pdb.MsfStream
636 stream: Stream = undefined,
637
638634 pub const Error = @TypeOf(read).ReturnType.ErrorSet;
639 pub const Stream = io.InStream(Error);
640635
641636 fn init(block_size: u32, file: File, blocks: []u32) MsfStream {
642637 const stream = MsfStream{
......@@ -644,7 +639,6 @@ const MsfStream = struct {
644639 .pos = 0,
645640 .blocks = blocks,
646641 .block_size = block_size,
647 .stream = Stream{ .readFn = readFn },
648642 };
649643
650644 return stream;
......@@ -653,7 +647,7 @@ const MsfStream = struct {
653647 fn readNullTermString(self: *MsfStream, allocator: *mem.Allocator) ![]u8 {
654648 var list = ArrayList(u8).init(allocator);
655649 while (true) {
656 const byte = try self.stream.readByte();
650 const byte = try self.inStream().readByte();
657651 if (byte == 0) {
658652 return list.toSlice();
659653 }
......@@ -667,8 +661,7 @@ const MsfStream = struct {
667661 var offset = self.pos % self.block_size;
668662
669663 try self.in_file.seekTo(block * self.block_size + offset);
670 var file_stream = self.in_file.inStream();
671 const in = &file_stream.stream;
664 const in = self.in_file.inStream();
672665
673666 var size: usize = 0;
674667 var rem_buffer = buffer;
......@@ -715,8 +708,7 @@ const MsfStream = struct {
715708 return block * self.block_size + offset;
716709 }
717710
718 fn readFn(in_stream: *Stream, buffer: []u8) Error!usize {
719 const self = @fieldParentPtr(MsfStream, "stream", in_stream);
720 return self.read(buffer);
711 fn inStream(self: *MsfStream) std.io.InStream(*MsfStream, Error, read) {
712 return .{ .context = self };
721713 }
722714};
lib/std/progress.zig+2-2
......@@ -177,7 +177,7 @@ pub const Progress = struct {
177177 pub fn log(self: *Progress, comptime format: []const u8, args: var) void {
178178 const file = self.terminal orelse return;
179179 self.refresh();
180 file.outStream().stream.print(format, args) catch {
180 file.outStream().print(format, args) catch {
181181 self.terminal = null;
182182 return;
183183 };
......@@ -190,7 +190,7 @@ pub const Progress = struct {
190190 end.* += amt;
191191 self.columns_written += amt;
192192 } else |err| switch (err) {
193 error.BufferTooSmall => {
193 error.NoSpaceLeft => {
194194 self.columns_written += self.output_buffer.len - end.*;
195195 end.* = self.output_buffer.len;
196196 },
lib/std/special/build_runner.zig+4-4
......@@ -42,8 +42,8 @@ pub fn main() !void {
4242
4343 var targets = ArrayList([]const u8).init(allocator);
4444
45 const stderr_stream = &io.getStdErr().outStream().stream;
46 const stdout_stream = &io.getStdOut().outStream().stream;
45 const stderr_stream = io.getStdErr().outStream();
46 const stdout_stream = io.getStdOut().outStream();
4747
4848 while (nextArg(args, &arg_idx)) |arg| {
4949 if (mem.startsWith(u8, arg, "-D")) {
......@@ -159,7 +159,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
159159 try out_stream.print(" {s:22} {}\n", .{ name, top_level_step.description });
160160 }
161161
162 try out_stream.write(
162 try out_stream.writeAll(
163163 \\
164164 \\General Options:
165165 \\ --help Print this help and exit
......@@ -184,7 +184,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: var) !void {
184184 }
185185 }
186186
187 try out_stream.write(
187 try out_stream.writeAll(
188188 \\
189189 \\Advanced Options:
190190 \\ --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 {
5555}
5656
5757fn 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'";
5958 uefi.handle = handle;
6059 uefi.system_table = system_table;
6160
62 switch (@typeInfo(@TypeOf(root.main).ReturnType)) {
63 .NoReturn => {
61 switch (@TypeOf(root.main).ReturnType) {
62 noreturn => {
6463 root.main();
6564 },
66 .Void => {
65 void => {
6766 root.main();
6867 return 0;
6968 },
70 .Int => |info| {
71 if (info.bits != @typeInfo(usize).Int.bits) {
72 @compileError(bad_efi_main_ret);
73 }
69 usize => {
7470 return root.main();
7571 },
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'"),
7776 }
7877}
7978
lib/std/std.zig-1
......@@ -5,7 +5,6 @@ pub const BloomFilter = @import("bloom_filter.zig").BloomFilter;
55pub const BufMap = @import("buf_map.zig").BufMap;
66pub const BufSet = @import("buf_set.zig").BufSet;
77pub const Buffer = @import("buffer.zig").Buffer;
8pub const BufferOutStream = @import("io.zig").BufferOutStream;
98pub const ChildProcess = @import("child_process.zig").ChildProcess;
109pub const DynLib = @import("dynamic_library.zig").DynLib;
1110pub const HashMap = @import("hash_map.zig").HashMap;
lib/std/unicode.zig+68
......@@ -629,3 +629,71 @@ test "utf8ToUtf16LeWithNull" {
629629 testing.expect(utf16[2] == 0);
630630 }
631631}
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) {
378378 token: TokenIndex,
379379
380380 pub fn render(self: *const ThisError, tokens: *Tree.TokenList, stream: var) !void {
381 return stream.write(msg);
381 return stream.writeAll(msg);
382382 }
383383 };
384384 }
......@@ -434,6 +434,7 @@ pub const Node = struct {
434434 ContainerDecl,
435435 Asm,
436436 Comptime,
437 Noasync,
437438 Block,
438439
439440 // Misc
......@@ -502,68 +503,72 @@ pub const Node = struct {
502503 var n = base;
503504 while (true) {
504505 switch (n.id) {
505 Id.Root,
506 Id.ContainerField,
507 Id.ParamDecl,
508 Id.Block,
509 Id.Payload,
510 Id.PointerPayload,
511 Id.PointerIndexPayload,
512 Id.Switch,
513 Id.SwitchCase,
514 Id.SwitchElse,
515 Id.FieldInitializer,
516 Id.DocComment,
517 Id.TestDecl,
506 .Root,
507 .ContainerField,
508 .ParamDecl,
509 .Block,
510 .Payload,
511 .PointerPayload,
512 .PointerIndexPayload,
513 .Switch,
514 .SwitchCase,
515 .SwitchElse,
516 .FieldInitializer,
517 .DocComment,
518 .TestDecl,
518519 => return false,
519 Id.While => {
520 .While => {
520521 const while_node = @fieldParentPtr(While, "base", n);
521522 if (while_node.@"else") |@"else"| {
522523 n = &@"else".base;
523524 continue;
524525 }
525526
526 return while_node.body.id != Id.Block;
527 return while_node.body.id != .Block;
527528 },
528 Id.For => {
529 .For => {
529530 const for_node = @fieldParentPtr(For, "base", n);
530531 if (for_node.@"else") |@"else"| {
531532 n = &@"else".base;
532533 continue;
533534 }
534535
535 return for_node.body.id != Id.Block;
536 return for_node.body.id != .Block;
536537 },
537 Id.If => {
538 .If => {
538539 const if_node = @fieldParentPtr(If, "base", n);
539540 if (if_node.@"else") |@"else"| {
540541 n = &@"else".base;
541542 continue;
542543 }
543544
544 return if_node.body.id != Id.Block;
545 return if_node.body.id != .Block;
545546 },
546 Id.Else => {
547 .Else => {
547548 const else_node = @fieldParentPtr(Else, "base", n);
548549 n = else_node.body;
549550 continue;
550551 },
551 Id.Defer => {
552 .Defer => {
552553 const defer_node = @fieldParentPtr(Defer, "base", n);
553 return defer_node.expr.id != Id.Block;
554 return defer_node.expr.id != .Block;
554555 },
555 Id.Comptime => {
556 .Comptime => {
556557 const comptime_node = @fieldParentPtr(Comptime, "base", n);
557 return comptime_node.expr.id != Id.Block;
558 return comptime_node.expr.id != .Block;
558559 },
559 Id.Suspend => {
560 .Suspend => {
560561 const suspend_node = @fieldParentPtr(Suspend, "base", n);
561562 if (suspend_node.body) |body| {
562 return body.id != Id.Block;
563 return body.id != .Block;
563564 }
564565
565566 return true;
566567 },
568 .Noasync => {
569 const noasync_node = @fieldParentPtr(Noasync, "base", n);
570 return noasync_node.expr.id != .Block;
571 },
567572 else => return true,
568573 }
569574 }
......@@ -1081,6 +1086,29 @@ pub const Node = struct {
10811086 }
10821087 };
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
10841112 pub const Payload = struct {
10851113 base: Node = Node{ .id = .Payload },
10861114 lpipe: TokenIndex,
......@@ -1563,9 +1591,7 @@ pub const Node = struct {
15631591 pub const Op = union(enum) {
15641592 AddressOf,
15651593 ArrayType: ArrayInfo,
1566 Await: struct {
1567 noasync_token: ?TokenIndex = null,
1568 },
1594 Await,
15691595 BitNot,
15701596 BoolNot,
15711597 Cancel,
lib/std/zig/cross_target.zig+6-6
......@@ -504,22 +504,22 @@ pub const CrossTarget = struct {
504504 if (self.os_version_min != null or self.os_version_max != null) {
505505 switch (self.getOsVersionMin()) {
506506 .none => {},
507 .semver => |v| try result.print(".{}", .{v}),
508 .windows => |v| try result.print(".{}", .{@tagName(v)}),
507 .semver => |v| try result.outStream().print(".{}", .{v}),
508 .windows => |v| try result.outStream().print(".{}", .{@tagName(v)}),
509509 }
510510 }
511511 if (self.os_version_max) |max| {
512512 switch (max) {
513513 .none => {},
514 .semver => |v| try result.print("...{}", .{v}),
515 .windows => |v| try result.print("...{}", .{@tagName(v)}),
514 .semver => |v| try result.outStream().print("...{}", .{v}),
515 .windows => |v| try result.outStream().print("...{}", .{@tagName(v)}),
516516 }
517517 }
518518
519519 if (self.glibc_version) |v| {
520 try result.print("-{}.{}", .{ @tagName(self.getAbi()), v });
520 try result.outStream().print("-{}.{}", .{ @tagName(self.getAbi()), v });
521521 } else if (self.abi) |abi| {
522 try result.print("-{}", .{@tagName(abi)});
522 try result.outStream().print("-{}", .{@tagName(abi)});
523523 }
524524
525525 return result.toOwnedSlice();
lib/std/zig/parse.zig+49-25
......@@ -462,6 +462,7 @@ fn parseContainerField(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*No
462462/// Statement
463463/// <- KEYWORD_comptime? VarDecl
464464/// / KEYWORD_comptime BlockExprStatement
465/// / KEYWORD_noasync BlockExprStatement
465466/// / KEYWORD_suspend (SEMICOLON / BlockExprStatement)
466467/// / KEYWORD_defer BlockExprStatement
467468/// / KEYWORD_errdefer BlockExprStatement
......@@ -493,6 +494,19 @@ fn parseStatement(arena: *Allocator, it: *TokenIterator, tree: *Tree) Error!?*No
493494 return &node.base;
494495 }
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
496510 if (eatToken(it, .Keyword_suspend)) |suspend_token| {
497511 const semicolon = eatToken(it, .Semicolon);
498512
......@@ -856,6 +870,7 @@ fn parsePrefixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
856870/// / IfExpr
857871/// / KEYWORD_break BreakLabel? Expr?
858872/// / KEYWORD_comptime Expr
873/// / KEYWORD_noasync Expr
859874/// / KEYWORD_continue BreakLabel?
860875/// / KEYWORD_resume Expr
861876/// / KEYWORD_return Expr?
......@@ -870,7 +885,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
870885 const label = try parseBreakLabel(arena, it, tree);
871886 const expr_node = try parseExpr(arena, it, tree);
872887 const node = try arena.create(Node.ControlFlowExpression);
873 node.* = Node.ControlFlowExpression{
888 node.* = .{
874889 .ltoken = token,
875890 .kind = Node.ControlFlowExpression.Kind{ .Break = label },
876891 .rhs = expr_node,
......@@ -883,7 +898,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
883898 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },
884899 });
885900 const node = try arena.create(Node.Comptime);
886 node.* = Node.Comptime{
901 node.* = .{
887902 .doc_comments = null,
888903 .comptime_token = token,
889904 .expr = expr_node,
......@@ -891,10 +906,22 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
891906 return &node.base;
892907 }
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
894921 if (eatToken(it, .Keyword_continue)) |token| {
895922 const label = try parseBreakLabel(arena, it, tree);
896923 const node = try arena.create(Node.ControlFlowExpression);
897 node.* = Node.ControlFlowExpression{
924 node.* = .{
898925 .ltoken = token,
899926 .kind = Node.ControlFlowExpression.Kind{ .Continue = label },
900927 .rhs = null,
......@@ -907,7 +934,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
907934 .ExpectedExpr = AstError.ExpectedExpr{ .token = it.index },
908935 });
909936 const node = try arena.create(Node.PrefixOp);
910 node.* = Node.PrefixOp{
937 node.* = .{
911938 .op_token = token,
912939 .op = Node.PrefixOp.Op.Resume,
913940 .rhs = expr_node,
......@@ -918,7 +945,7 @@ fn parsePrimaryExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node
918945 if (eatToken(it, .Keyword_return)) |token| {
919946 const expr_node = try parseExpr(arena, it, tree);
920947 const node = try arena.create(Node.ControlFlowExpression);
921 node.* = Node.ControlFlowExpression{
948 node.* = .{
922949 .ltoken = token,
923950 .kind = Node.ControlFlowExpression.Kind.Return,
924951 .rhs = expr_node,
......@@ -1126,19 +1153,18 @@ fn parseErrorUnionExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*No
11261153
11271154/// SuffixExpr
11281155/// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
1129/// / KEYWORD_noasync PrimaryTypeExpr SuffixOp* FnCallArguments
11301156/// / PrimaryTypeExpr (SuffixOp / FnCallArguments)*
11311157fn 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);
11331159 if (maybe_async) |async_token| {
11341160 const token_fn = eatToken(it, .Keyword_fn);
1135 if (async_token.ptr.id == .Keyword_async and token_fn != null) {
1161 if (token_fn != null) {
11361162 // HACK: If we see the keyword `fn`, then we assume that
11371163 // we are parsing an async fn proto, and not a call.
11381164 // We therefore put back all tokens consumed by the async
11391165 // prefix...
11401166 putBackToken(it, token_fn.?);
1141 putBackToken(it, async_token.index);
1167 putBackToken(it, async_token);
11421168 return parsePrimaryTypeExpr(arena, it, tree);
11431169 }
11441170 // 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 {
11671193 .op = Node.SuffixOp.Op{
11681194 .Call = Node.SuffixOp.Op.Call{
11691195 .params = params.list,
1170 .async_token = async_token.index,
1196 .async_token = async_token,
11711197 },
11721198 },
11731199 .rtoken = params.rparen,
......@@ -1224,6 +1250,7 @@ fn parseSuffixExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
12241250/// / IfTypeExpr
12251251/// / INTEGER
12261252/// / KEYWORD_comptime TypeExpr
1253/// / KEYWORD_noasync TypeExpr
12271254/// / KEYWORD_error DOT IDENTIFIER
12281255/// / KEYWORD_false
12291256/// / KEYWORD_null
......@@ -1255,13 +1282,22 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
12551282 if (eatToken(it, .Keyword_comptime)) |token| {
12561283 const expr = (try parseTypeExpr(arena, it, tree)) orelse return null;
12571284 const node = try arena.create(Node.Comptime);
1258 node.* = Node.Comptime{
1285 node.* = .{
12591286 .doc_comments = null,
12601287 .comptime_token = token,
12611288 .expr = expr,
12621289 };
12631290 return &node.base;
12641291 }
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 }
12651301 if (eatToken(it, .Keyword_error)) |token| {
12661302 const period = try expectToken(it, tree, .Period);
12671303 const identifier = try expectNode(arena, it, tree, parseIdentifier, AstError{
......@@ -1269,7 +1305,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
12691305 });
12701306 const global_error_set = try createLiteral(arena, Node.ErrorType, token);
12711307 const node = try arena.create(Node.InfixOp);
1272 node.* = Node.InfixOp{
1308 node.* = .{
12731309 .op_token = period,
12741310 .lhs = global_error_set,
12751311 .op = Node.InfixOp.Op.Period,
......@@ -1281,7 +1317,7 @@ fn parsePrimaryTypeExpr(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*N
12811317 if (eatToken(it, .Keyword_null)) |token| return createLiteral(arena, Node.NullLiteral, token);
12821318 if (eatToken(it, .Keyword_anyframe)) |token| {
12831319 const node = try arena.create(Node.AnyFrameType);
1284 node.* = Node.AnyFrameType{
1320 node.* = .{
12851321 .anyframe_token = token,
12861322 .result = null,
12871323 };
......@@ -2180,18 +2216,6 @@ fn parsePrefixOp(arena: *Allocator, it: *TokenIterator, tree: *Tree) !?*Node {
21802216 .Ampersand => ops{ .AddressOf = {} },
21812217 .Keyword_try => ops{ .Try = {} },
21822218 .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 },
21952219 else => {
21962220 putBackToken(it, token.index);
21972221 return null;
lib/std/zig/parser_test.zig+16-6
......@@ -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
112test "zig fmt: noasync await" {
213 try testCanonical(
314 \\fn foo() void {
......@@ -2798,7 +2809,7 @@ const maxInt = std.math.maxInt;
27982809var fixed_buffer_mem: [100 * 1024]u8 = undefined;
27992810
28002811fn 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
28032814 const tree = try std.zig.parse(allocator, source);
28042815 defer tree.deinit();
......@@ -2813,17 +2824,17 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
28132824 {
28142825 var i: usize = 0;
28152826 while (i < loc.column) : (i += 1) {
2816 try stderr.write(" ");
2827 try stderr.writeAll(" ");
28172828 }
28182829 }
28192830 {
28202831 const caret_count = token.end - token.start;
28212832 var i: usize = 0;
28222833 while (i < caret_count) : (i += 1) {
2823 try stderr.write("~");
2834 try stderr.writeAll("~");
28242835 }
28252836 }
2826 try stderr.write("\n");
2837 try stderr.writeAll("\n");
28272838 }
28282839 if (tree.errors.len != 0) {
28292840 return error.ParseError;
......@@ -2832,8 +2843,7 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b
28322843 var buffer = try std.Buffer.initSize(allocator, 0);
28332844 errdefer buffer.deinit();
28342845
2835 var buffer_out_stream = io.BufferOutStream.init(&buffer);
2836 anything_changed.* = try std.zig.render(allocator, &buffer_out_stream.stream, tree);
2846 anything_changed.* = try std.zig.render(allocator, buffer.outStream(), tree);
28372847 return buffer.toOwnedSlice();
28382848}
28392849
lib/std/zig/render.zig+72-76
......@@ -12,64 +12,58 @@ pub const Error = error{
1212};
1313
1414/// Returns whether anything changed
15pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@TypeOf(stream).Child.Error || Error)!bool {
16 comptime assert(@typeInfo(@TypeOf(stream)) == .Pointer);
17
18 var anything_changed: bool = false;
19
15pub fn render(allocator: *mem.Allocator, stream: var, tree: *ast.Tree) (@TypeOf(stream).Error || Error)!bool {
2016 // make a passthrough stream that checks whether something changed
2117 const MyStream = struct {
2218 const MyStream = @This();
23 const StreamError = @TypeOf(stream).Child.Error;
24 const Stream = std.io.OutStream(StreamError);
19 const StreamError = @TypeOf(stream).Error;
2520
26 anything_changed_ptr: *bool,
2721 child_stream: @TypeOf(stream),
28 stream: Stream,
22 anything_changed: bool,
2923 source_index: usize,
3024 source: []const u8,
3125
32 fn write(iface_stream: *Stream, bytes: []const u8) StreamError!usize {
33 const self = @fieldParentPtr(MyStream, "stream", iface_stream);
34
35 if (!self.anything_changed_ptr.*) {
26 fn write(self: *MyStream, bytes: []const u8) StreamError!usize {
27 if (!self.anything_changed) {
3628 const end = self.source_index + bytes.len;
3729 if (end > self.source.len) {
38 self.anything_changed_ptr.* = true;
30 self.anything_changed = true;
3931 } else {
4032 const src_slice = self.source[self.source_index..end];
4133 self.source_index += bytes.len;
4234 if (!mem.eql(u8, bytes, src_slice)) {
43 self.anything_changed_ptr.* = true;
35 self.anything_changed = true;
4436 }
4537 }
4638 }
4739
48 return self.child_stream.writeOnce(bytes);
40 return self.child_stream.write(bytes);
4941 }
5042 };
5143 var my_stream = MyStream{
52 .stream = MyStream.Stream{ .writeFn = MyStream.write },
5344 .child_stream = stream,
54 .anything_changed_ptr = &anything_changed,
45 .anything_changed = false,
5546 .source_index = 0,
5647 .source = tree.source,
5748 };
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) {
62 anything_changed = true;
55 if (my_stream.source_index != my_stream.source.len) {
56 my_stream.anything_changed = true;
6357 }
6458
65 return anything_changed;
59 return my_stream.anything_changed;
6660}
6761
6862fn renderRoot(
6963 allocator: *mem.Allocator,
7064 stream: var,
7165 tree: *ast.Tree,
72) (@TypeOf(stream).Child.Error || Error)!void {
66) (@TypeOf(stream).Error || Error)!void {
7367 var tok_it = tree.tokens.iterator(0);
7468
7569 // render all the line comments at the beginning of the file
......@@ -189,7 +183,7 @@ fn renderRoot(
189183 }
190184}
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 {
193187 const first_token = node.firstToken();
194188 var prev_token = first_token;
195189 if (prev_token == 0) return;
......@@ -204,11 +198,11 @@ fn renderExtraNewline(tree: *ast.Tree, stream: var, start_col: *usize, node: *as
204198 }
205199}
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 {
208202 try renderContainerDecl(allocator, stream, tree, indent, start_col, decl, .Newline);
209203}
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 {
212206 switch (decl.id) {
213207 .FnProto => {
214208 const fn_proto = @fieldParentPtr(ast.Node.FnProto, "base", decl);
......@@ -343,7 +337,7 @@ fn renderExpression(
343337 start_col: *usize,
344338 base: *ast.Node,
345339 space: Space,
346) (@TypeOf(stream).Child.Error || Error)!void {
340) (@TypeOf(stream).Error || Error)!void {
347341 switch (base.id) {
348342 .Identifier => {
349343 const identifier = @fieldParentPtr(ast.Node.Identifier, "base", base);
......@@ -390,6 +384,12 @@ fn renderExpression(
390384 try renderToken(tree, stream, comptime_node.comptime_token, indent, start_col, Space.Space);
391385 return renderExpression(allocator, stream, tree, indent, start_col, comptime_node.expr, space);
392386 },
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
394394 .Suspend => {
395395 const suspend_node = @fieldParentPtr(ast.Node.Suspend, "base", base);
......@@ -443,9 +443,9 @@ fn renderExpression(
443443 switch (op_tok_id) {
444444 .Asterisk, .AsteriskAsterisk => try stream.writeByte('*'),
445445 .LBracket => if (tree.tokens.at(prefix_op_node.op_token + 2).id == .Identifier)
446 try stream.write("[*c")
446 try stream.writeAll("[*c")
447447 else
448 try stream.write("[*"),
448 try stream.writeAll("[*"),
449449 else => unreachable,
450450 }
451451 if (ptr_info.sentinel) |sentinel| {
......@@ -590,9 +590,6 @@ fn renderExpression(
590590 },
591591
592592 .Await => |await_info| {
593 if (await_info.noasync_token) |tok| {
594 try renderToken(tree, stream, tok, indent, start_col, Space.Space);
595 }
596593 try renderToken(tree, stream, prefix_op_node.op_token, indent, start_col, Space.Space);
597594 },
598595 }
......@@ -754,7 +751,7 @@ fn renderExpression(
754751 while (it.next()) |field_init| {
755752 var find_stream = FindByteOutStream.init('\n');
756753 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);
758755 if (find_stream.byte_found) break :blk false;
759756 }
760757 break :blk true;
......@@ -906,8 +903,7 @@ fn renderExpression(
906903 var column_widths = widths[widths.len - row_size ..];
907904
908905 // Null stream for counting the printed length of each expression
909 var null_stream = std.io.NullOutStream.init();
910 var counting_stream = std.io.CountingOutStream(std.io.NullOutStream.Error).init(&null_stream.stream);
906 var counting_stream = std.io.countingOutStream(std.io.null_out_stream);
911907
912908 var it = exprs.iterator(0);
913909 var i: usize = 0;
......@@ -915,7 +911,7 @@ fn renderExpression(
915911 while (it.next()) |expr| : (i += 1) {
916912 counting_stream.bytes_written = 0;
917913 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);
919915 const width = @intCast(usize, counting_stream.bytes_written);
920916 const col = i % row_size;
921917 column_widths[col] = std.math.max(column_widths[col], width);
......@@ -1333,7 +1329,7 @@ fn renderExpression(
13331329
13341330 // TODO: Remove condition after deprecating 'typeOf'. See https://github.com/ziglang/zig/issues/1348
13351331 if (mem.eql(u8, tree.tokenSlicePtr(tree.tokens.at(builtin_call.builtin_token)), "@typeOf")) {
1336 try stream.write("@TypeOf");
1332 try stream.writeAll("@TypeOf");
13371333 } else {
13381334 try renderToken(tree, stream, builtin_call.builtin_token, indent, start_col, Space.None); // @name
13391335 }
......@@ -1502,9 +1498,9 @@ fn renderExpression(
15021498 try renderExpression(allocator, stream, tree, indent, start_col, callconv_expr, Space.None);
15031499 try renderToken(tree, stream, callconv_rparen, indent, start_col, Space.Space); // )
15041500 } else if (cc_rewrite_str) |str| {
1505 try stream.write("callconv(");
1506 try stream.write(mem.toSliceConst(u8, str));
1507 try stream.write(") ");
1501 try stream.writeAll("callconv(");
1502 try stream.writeAll(mem.toSliceConst(u8, str));
1503 try stream.writeAll(") ");
15081504 }
15091505
15101506 switch (fn_proto.return_type) {
......@@ -1994,11 +1990,11 @@ fn renderExpression(
19941990 .AsmInput => {
19951991 const asm_input = @fieldParentPtr(ast.Node.AsmInput, "base", base);
19961992
1997 try stream.write("[");
1993 try stream.writeAll("[");
19981994 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.symbolic_name, Space.None);
1999 try stream.write("] ");
1995 try stream.writeAll("] ");
20001996 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.constraint, Space.None);
2001 try stream.write(" (");
1997 try stream.writeAll(" (");
20021998 try renderExpression(allocator, stream, tree, indent, start_col, asm_input.expr, Space.None);
20031999 return renderToken(tree, stream, asm_input.lastToken(), indent, start_col, space); // )
20042000 },
......@@ -2006,18 +2002,18 @@ fn renderExpression(
20062002 .AsmOutput => {
20072003 const asm_output = @fieldParentPtr(ast.Node.AsmOutput, "base", base);
20082004
2009 try stream.write("[");
2005 try stream.writeAll("[");
20102006 try renderExpression(allocator, stream, tree, indent, start_col, asm_output.symbolic_name, Space.None);
2011 try stream.write("] ");
2007 try stream.writeAll("] ");
20122008 try renderExpression(allocator, stream, tree, indent, start_col, asm_output.constraint, Space.None);
2013 try stream.write(" (");
2009 try stream.writeAll(" (");
20142010
20152011 switch (asm_output.kind) {
20162012 ast.Node.AsmOutput.Kind.Variable => |variable_name| {
20172013 try renderExpression(allocator, stream, tree, indent, start_col, &variable_name.base, Space.None);
20182014 },
20192015 ast.Node.AsmOutput.Kind.Return => |return_type| {
2020 try stream.write("-> ");
2016 try stream.writeAll("-> ");
20212017 try renderExpression(allocator, stream, tree, indent, start_col, return_type, Space.None);
20222018 },
20232019 }
......@@ -2049,7 +2045,7 @@ fn renderVarDecl(
20492045 indent: usize,
20502046 start_col: *usize,
20512047 var_decl: *ast.Node.VarDecl,
2052) (@TypeOf(stream).Child.Error || Error)!void {
2048) (@TypeOf(stream).Error || Error)!void {
20532049 if (var_decl.visib_token) |visib_token| {
20542050 try renderToken(tree, stream, visib_token, indent, start_col, Space.Space); // pub
20552051 }
......@@ -2122,7 +2118,7 @@ fn renderParamDecl(
21222118 start_col: *usize,
21232119 base: *ast.Node,
21242120 space: Space,
2125) (@TypeOf(stream).Child.Error || Error)!void {
2121) (@TypeOf(stream).Error || Error)!void {
21262122 const param_decl = @fieldParentPtr(ast.Node.ParamDecl, "base", base);
21272123
21282124 try renderDocComments(tree, stream, param_decl, indent, start_col);
......@@ -2151,7 +2147,7 @@ fn renderStatement(
21512147 indent: usize,
21522148 start_col: *usize,
21532149 base: *ast.Node,
2154) (@TypeOf(stream).Child.Error || Error)!void {
2150) (@TypeOf(stream).Error || Error)!void {
21552151 switch (base.id) {
21562152 .VarDecl => {
21572153 const var_decl = @fieldParentPtr(ast.Node.VarDecl, "base", base);
......@@ -2190,7 +2186,7 @@ fn renderTokenOffset(
21902186 start_col: *usize,
21912187 space: Space,
21922188 token_skip_bytes: usize,
2193) (@TypeOf(stream).Child.Error || Error)!void {
2189) (@TypeOf(stream).Error || Error)!void {
21942190 if (space == Space.BlockStart) {
21952191 if (start_col.* < indent + indent_delta)
21962192 return renderToken(tree, stream, token_index, indent, start_col, Space.Space);
......@@ -2201,7 +2197,7 @@ fn renderTokenOffset(
22012197 }
22022198
22032199 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
22062202 if (space == Space.NoComment)
22072203 return;
......@@ -2211,15 +2207,15 @@ fn renderTokenOffset(
22112207 if (space == Space.Comma) switch (next_token.id) {
22122208 .Comma => return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline),
22132209 .LineComment => {
2214 try stream.write(", ");
2210 try stream.writeAll(", ");
22152211 return renderToken(tree, stream, token_index + 1, indent, start_col, Space.Newline);
22162212 },
22172213 else => {
22182214 if (token_index + 2 < tree.tokens.len and tree.tokens.at(token_index + 2).id == .MultilineStringLiteralLine) {
2219 try stream.write(",");
2215 try stream.writeAll(",");
22202216 return;
22212217 } else {
2222 try stream.write(",\n");
2218 try stream.writeAll(",\n");
22232219 start_col.* = 0;
22242220 return;
22252221 }
......@@ -2243,7 +2239,7 @@ fn renderTokenOffset(
22432239 if (next_token.id == .MultilineStringLiteralLine) {
22442240 return;
22452241 } else {
2246 try stream.write("\n");
2242 try stream.writeAll("\n");
22472243 start_col.* = 0;
22482244 return;
22492245 }
......@@ -2306,7 +2302,7 @@ fn renderTokenOffset(
23062302 if (next_token.id == .MultilineStringLiteralLine) {
23072303 return;
23082304 } else {
2309 try stream.write("\n");
2305 try stream.writeAll("\n");
23102306 start_col.* = 0;
23112307 return;
23122308 }
......@@ -2324,7 +2320,7 @@ fn renderTokenOffset(
23242320 const newline_count = if (loc.line == 1) @as(u8, 1) else @as(u8, 2);
23252321 try stream.writeByteNTimes('\n', newline_count);
23262322 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
23292325 offset += 1;
23302326 token = next_token;
......@@ -2335,7 +2331,7 @@ fn renderTokenOffset(
23352331 if (next_token.id == .MultilineStringLiteralLine) {
23362332 return;
23372333 } else {
2338 try stream.write("\n");
2334 try stream.writeAll("\n");
23392335 start_col.* = 0;
23402336 return;
23412337 }
......@@ -2378,7 +2374,7 @@ fn renderToken(
23782374 indent: usize,
23792375 start_col: *usize,
23802376 space: Space,
2381) (@TypeOf(stream).Child.Error || Error)!void {
2377) (@TypeOf(stream).Error || Error)!void {
23822378 return renderTokenOffset(tree, stream, token_index, indent, start_col, space, 0);
23832379}
23842380
......@@ -2388,7 +2384,7 @@ fn renderDocComments(
23882384 node: var,
23892385 indent: usize,
23902386 start_col: *usize,
2391) (@TypeOf(stream).Child.Error || Error)!void {
2387) (@TypeOf(stream).Error || Error)!void {
23922388 const comment = node.doc_comments orelse return;
23932389 var it = comment.lines.iterator(0);
23942390 const first_token = node.firstToken();
......@@ -2398,7 +2394,7 @@ fn renderDocComments(
23982394 try stream.writeByteNTimes(' ', indent);
23992395 } else {
24002396 try renderToken(tree, stream, line_token_index.*, indent, start_col, Space.NoComment);
2401 try stream.write("\n");
2397 try stream.writeAll("\n");
24022398 try stream.writeByteNTimes(' ', indent);
24032399 }
24042400 }
......@@ -2424,27 +2420,23 @@ fn nodeCausesSliceOpSpace(base: *ast.Node) bool {
24242420 };
24252421}
24262422
2427// An OutStream that returns whether the given character has been written to it.
2428// The contents are not written to anything.
2423/// A `std.io.OutStream` that returns whether the given character has been written to it.
2424/// The contents are not written to anything.
24292425const FindByteOutStream = struct {
2430 const Self = FindByteOutStream;
2431 pub const Error = error{};
2432 pub const Stream = std.io.OutStream(Error);
2433
2434 stream: Stream,
24352426 byte_found: bool,
24362427 byte: u8,
24372428
2438 pub fn init(byte: u8) Self {
2439 return Self{
2440 .stream = Stream{ .writeFn = writeFn },
2429 pub const Error = error{};
2430 pub const OutStream = std.io.OutStream(*FindByteOutStream, Error, write);
2431
2432 pub fn init(byte: u8) FindByteOutStream {
2433 return FindByteOutStream{
24412434 .byte = byte,
24422435 .byte_found = false,
24432436 };
24442437 }
24452438
2446 fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
2447 const self = @fieldParentPtr(Self, "stream", out_stream);
2439 pub fn write(self: *FindByteOutStream, bytes: []const u8) Error!usize {
24482440 if (self.byte_found) return bytes.len;
24492441 self.byte_found = blk: {
24502442 for (bytes) |b|
......@@ -2453,11 +2445,15 @@ const FindByteOutStream = struct {
24532445 };
24542446 return bytes.len;
24552447 }
2448
2449 pub fn outStream(self: *FindByteOutStream) OutStream {
2450 return .{ .context = self };
2451 }
24562452};
24572453
2458fn copyFixingWhitespace(stream: var, slice: []const u8) @TypeOf(stream).Child.Error!void {
2454fn copyFixingWhitespace(stream: var, slice: []const u8) @TypeOf(stream).Error!void {
24592455 for (slice) |byte| switch (byte) {
2460 '\t' => try stream.write(" "),
2456 '\t' => try stream.writeAll(" "),
24612457 '\r' => {},
24622458 else => try stream.writeByte(byte),
24632459 };
lib/std/zig/system.zig+25-27
......@@ -201,8 +201,15 @@ pub const NativeTargetInfo = struct {
201201 switch (Target.current.os.tag) {
202202 .linux => {
203203 const uts = std.os.uname();
204 const release = mem.toSliceConst(u8, @ptrCast([*:0]const u8, &uts.release));
205 if (std.builtin.Version.parse(release)) |ver| {
204 const release = mem.toSliceConst(u8, &uts.release);
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| {
206213 os.version_range.linux.range.min = ver;
207214 os.version_range.linux.range.max = ver;
208215 } else |err| switch (err) {
......@@ -318,22 +325,19 @@ pub const NativeTargetInfo = struct {
318325 // native CPU architecture as being different than the current target), we use this:
319326 const cpu_arch = cross_target.getCpuArch();
320327
321 const cpu = switch (cross_target.cpu_model) {
328 var cpu = switch (cross_target.cpu_model) {
322329 .native => detectNativeCpuAndFeatures(cpu_arch, os, cross_target),
323 .baseline => baselineCpuAndFeatures(cpu_arch, cross_target),
330 .baseline => Target.Cpu.baseline(cpu_arch),
324331 .determined_by_cpu_arch => if (cross_target.cpu_arch == null)
325332 detectNativeCpuAndFeatures(cpu_arch, os, cross_target)
326333 else
327 baselineCpuAndFeatures(cpu_arch, cross_target),
328 .explicit => |model| blk: {
329 var adjusted_model = model.toCpu(cpu_arch);
330 cross_target.updateCpuFeatures(&adjusted_model.features);
331 break :blk adjusted_model;
332 },
334 Target.Cpu.baseline(cpu_arch),
335 .explicit => |model| model.toCpu(cpu_arch),
333336 } orelse backup_cpu_detection: {
334337 cpu_detection_unimplemented = true;
335 break :backup_cpu_detection baselineCpuAndFeatures(cpu_arch, cross_target);
338 break :backup_cpu_detection Target.Cpu.baseline(cpu_arch);
336339 };
340 cross_target.updateCpuFeatures(&cpu.features);
337341
338342 var target = try detectAbiAndDynamicLinker(allocator, cpu, os, cross_target);
339343 target.cpu_detection_unimplemented = cpu_detection_unimplemented;
......@@ -563,7 +567,7 @@ pub const NativeTargetInfo = struct {
563567 cross_target: CrossTarget,
564568 ) AbiAndDynamicLinkerFromFileError!NativeTargetInfo {
565569 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);
567571 const hdr32 = @ptrCast(*elf.Elf32_Ehdr, &hdr_buf);
568572 const hdr64 = @ptrCast(*elf.Elf64_Ehdr, &hdr_buf);
569573 if (!mem.eql(u8, hdr32.e_ident[0..4], "\x7fELF")) return error.InvalidElfMagic;
......@@ -603,7 +607,7 @@ pub const NativeTargetInfo = struct {
603607 // Reserve some bytes so that we can deref the 64-bit struct fields
604608 // even when the ELF file is 32-bits.
605609 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);
607611 var ph_buf_i: usize = 0;
608612 while (ph_buf_i < ph_read_byte_len and ph_i < phnum) : ({
609613 ph_i += 1;
......@@ -618,7 +622,7 @@ pub const NativeTargetInfo = struct {
618622 const p_offset = elfInt(is_64, need_bswap, ph32.p_offset, ph64.p_offset);
619623 const p_filesz = elfInt(is_64, need_bswap, ph32.p_filesz, ph64.p_filesz);
620624 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);
622626 // PT_INTERP includes a null byte in p_filesz.
623627 const len = p_filesz - 1;
624628 // dynamic_linker.max_byte is "max", not "len".
......@@ -649,7 +653,7 @@ pub const NativeTargetInfo = struct {
649653 // Reserve some bytes so that we can deref the 64-bit struct fields
650654 // even when the ELF file is 32-bits.
651655 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(
653657 file,
654658 dyn_buf[0 .. dyn_buf.len - dyn_reserve],
655659 dyn_off,
......@@ -694,14 +698,14 @@ pub const NativeTargetInfo = struct {
694698 var sh_buf: [16 * @sizeOf(elf.Elf64_Shdr)]u8 align(@alignOf(elf.Elf64_Shdr)) = undefined;
695699 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);
698702 const shstr32 = @ptrCast(*elf.Elf32_Shdr, @alignCast(@alignOf(elf.Elf32_Shdr), &sh_buf));
699703 const shstr64 = @ptrCast(*elf.Elf64_Shdr, @alignCast(@alignOf(elf.Elf64_Shdr), &sh_buf));
700704 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);
701705 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);
702706 var strtab_buf: [4096:0]u8 = undefined;
703707 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);
705709 const shstrtab = strtab_buf[0..shstrtab_read_len];
706710
707711 const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum);
......@@ -710,7 +714,7 @@ pub const NativeTargetInfo = struct {
710714 // Reserve some bytes so that we can deref the 64-bit struct fields
711715 // even when the ELF file is 32-bits.
712716 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(
714718 file,
715719 sh_buf[0 .. sh_buf.len - sh_reserve],
716720 shoff,
......@@ -744,7 +748,7 @@ pub const NativeTargetInfo = struct {
744748
745749 if (dynstr) |ds| {
746750 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);
748752 const strtab = strtab_buf[0..strtab_read_len];
749753 // TODO this pointer cast should not be necessary
750754 const rpath_list = mem.toSliceConst(u8, @ptrCast([*:0]u8, strtab[rpoff..].ptr));
......@@ -806,7 +810,7 @@ pub const NativeTargetInfo = struct {
806810 return result;
807811 }
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 {
810814 var i: u64 = 0;
811815 while (i < min_read_len) {
812816 const len = file.pread(buf[i .. buf.len - i], offset + i) catch |err| switch (err) {
......@@ -846,7 +850,7 @@ pub const NativeTargetInfo = struct {
846850 abi: Target.Abi,
847851 };
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) {
850854 if (is_64) {
851855 if (need_bswap) {
852856 return @byteSwap(@TypeOf(int_64), int_64);
......@@ -877,10 +881,4 @@ pub const NativeTargetInfo = struct {
877881 },
878882 }
879883 }
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 }
886884};
lib/std/zig/system/x86.zig+44-36
......@@ -2,6 +2,12 @@ const std = @import("std");
22const Target = std.Target;
33const 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
511fn setFeature(cpu: *Target.Cpu, feature: Target.x86.Feature, enabled: bool) void {
612 const idx = @as(Target.Cpu.Feature.Set.Index, @enumToInt(feature));
713
......@@ -12,6 +18,10 @@ inline fn bit(input: u32, offset: u5) bool {
1218 return (input >> offset) & 1 != 0;
1319}
1420
21inline fn hasMask(input: u32, mask: u32) bool {
22 return (input & mask) == mask;
23}
24
1525pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_target: CrossTarget) Target.Cpu {
1626 var cpu = Target.Cpu{
1727 .arch = arch,
......@@ -30,18 +40,15 @@ pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_ta
3040 leaf = cpuid(0x1, 0);
3141
3242 const brand_id = leaf.ebx & 0xff;
33 var family: u32 = 0;
34 var model: u32 = 0;
35
36 { // Detect model and family
37 family = (leaf.eax >> 8) & 0xf;
38 model = (leaf.eax >> 4) & 0xf;
39 if (family == 6 or family == 0xf) {
40 if (family == 0xf) {
41 family += (leaf.eax >> 20) & 0xff;
42 }
43 model += ((leaf.eax >> 16) & 0xf) << 4;
43
44 // Detect model and family
45 var family = (leaf.eax >> 8) & 0xf;
46 var model = (leaf.eax >> 4) & 0xf;
47 if (family == 6 or family == 0xf) {
48 if (family == 0xf) {
49 family += (leaf.eax >> 20) & 0xff;
4450 }
51 model += ((leaf.eax >> 16) & 0xf) << 4;
4552 }
4653
4754 // Now we detect the model.
......@@ -312,7 +319,6 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
312319
313320 leaf = cpuid(1, 0);
314321
315 setFeature(cpu, .cx8, bit(leaf.edx, 8));
316322 setFeature(cpu, .cx8, bit(leaf.edx, 8));
317323 setFeature(cpu, .cmov, bit(leaf.edx, 15));
318324 setFeature(cpu, .mmx, bit(leaf.edx, 23));
......@@ -330,11 +336,13 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
330336 setFeature(cpu, .aes, bit(leaf.ecx, 25));
331337 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) and
336 bit(leaf.ecx, 28) and
337 ((leaf.eax & 0x6) == 0x6);
345 const has_avx_save = hasMask(xcr0_eax, XCR0_XMM | XCR0_YMM);
338346
339347 // LLVM approaches avx512_save by hardcoding it to true on Darwin,
340348 // 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 {
358366 // set right now.
359367 const has_avx512_save = switch (os_tag.isDarwin()) {
360368 true => true,
361 false => has_avx and ((leaf.eax & 0xE0) == 0xE0),
369 false => hasMask(xcr0_eax, XCR0_MASKREG | XCR0_ZMM0_15 | XCR0_ZMM16_31),
362370 };
363371
364 setFeature(cpu, .avx, has_avx);
365 setFeature(cpu, .fma, has_avx and bit(leaf.ecx, 12));
372 setFeature(cpu, .avx, has_avx_save);
373 setFeature(cpu, .fma, has_avx_save and bit(leaf.ecx, 12));
366374 // Only enable XSAVE if OS has enabled support for saving YMM state.
367 setFeature(cpu, .xsave, has_avx and bit(leaf.ecx, 26));
368 setFeature(cpu, .f16c, has_avx and bit(leaf.ecx, 29));
375 setFeature(cpu, .xsave, has_avx_save and bit(leaf.ecx, 26));
376 setFeature(cpu, .f16c, has_avx_save and bit(leaf.ecx, 29));
369377
370378 leaf = cpuid(0x80000000, 0);
371379 const max_ext_level = leaf.eax;
......@@ -376,9 +384,9 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
376384 setFeature(cpu, .lzcnt, bit(leaf.ecx, 5));
377385 setFeature(cpu, .sse4a, bit(leaf.ecx, 6));
378386 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);
380388 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);
382390 setFeature(cpu, .tbm, bit(leaf.ecx, 21));
383391 setFeature(cpu, .mwaitx, bit(leaf.ecx, 29));
384392 setFeature(cpu, .@"64bit", bit(leaf.edx, 29));
......@@ -409,7 +417,7 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
409417 setFeature(cpu, .sgx, bit(leaf.ebx, 2));
410418 setFeature(cpu, .bmi, bit(leaf.ebx, 3));
411419 // 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);
413421 setFeature(cpu, .bmi2, bit(leaf.ebx, 8));
414422 setFeature(cpu, .invpcid, bit(leaf.ebx, 10));
415423 setFeature(cpu, .rtm, bit(leaf.ebx, 11));
......@@ -435,8 +443,8 @@ fn detectNativeFeatures(cpu: *Target.Cpu, os_tag: Target.Os.Tag) void {
435443 setFeature(cpu, .avx512vbmi2, bit(leaf.ecx, 6) and has_avx512_save);
436444 setFeature(cpu, .shstk, bit(leaf.ecx, 7));
437445 setFeature(cpu, .gfni, bit(leaf.ecx, 8));
438 setFeature(cpu, .vaes, bit(leaf.ecx, 9) and has_avx);
439 setFeature(cpu, .vpclmulqdq, bit(leaf.ecx, 10) and has_avx);
446 setFeature(cpu, .vaes, bit(leaf.ecx, 9) and has_avx_save);
447 setFeature(cpu, .vpclmulqdq, bit(leaf.ecx, 10) and has_avx_save);
440448 setFeature(cpu, .avx512vnni, bit(leaf.ecx, 11) and has_avx512_save);
441449 setFeature(cpu, .avx512bitalg, bit(leaf.ecx, 12) and has_avx512_save);
442450 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 {
487495 }
488496 }
489497
490 if (max_level >= 0xD and has_avx) {
498 if (max_level >= 0xD and has_avx_save) {
491499 leaf = cpuid(0xD, 0x1);
492500 // Only enable XSAVE if OS has enabled support for saving YMM state.
493501 setFeature(cpu, .xsaveopt, bit(leaf.eax, 0));
......@@ -518,32 +526,32 @@ fn cpuid(leaf_id: u32, subid: u32) CpuidLeaf {
518526 // Workaround for https://github.com/ziglang/zig/issues/215
519527 // Inline assembly in zig only supports one output,
520528 // so we pass a pointer to the struct.
521 var cpuid_leaf = CpuidLeaf{ .eax = 0, .ebx = 0, .ecx = 0, .edx = 0 };
522 const leaf_ptr = &cpuid_leaf;
529 var cpuid_leaf: CpuidLeaf = undefined;
523530
524531 // valid for both x86 and x86_64
525532 asm volatile (
526533 \\ cpuid
527 \\ movl %%eax, (%[leaf_ptr])
534 \\ movl %%eax, 0(%[leaf_ptr])
528535 \\ movl %%ebx, 4(%[leaf_ptr])
529536 \\ movl %%ecx, 8(%[leaf_ptr])
530537 \\ movl %%edx, 12(%[leaf_ptr])
531538 :
532539 : [leaf_id] "{eax}" (leaf_id),
533540 [subid] "{ecx}" (subid),
534 [leaf_ptr] "r" (leaf_ptr)
541 [leaf_ptr] "r" (&cpuid_leaf)
535542 : "eax", "ebx", "ecx", "edx"
536543 );
544
537545 return cpuid_leaf;
538546}
539547
540548// Read control register 0 (XCR0). Used to detect features such as AVX.
541549fn getXCR0() u32 {
542 return asm (
543 \\ .byte 0x0F, 0x01, 0xD0
550 return asm volatile (
551 \\ xor %%ecx, %%ecx
552 \\ xgetbv
544553 : [ret] "={eax}" (-> u32)
545 : [number] "{eax}" (@as(u32, 0)),
546 [number] "{edx}" (@as(u32, 0)),
547 [number] "{ecx}" (@as(u32, 0))
554 :
555 : "eax", "edx", "ecx"
548556 );
549557}
src-self-hosted/clang.zig+2
......@@ -787,6 +787,7 @@ pub extern fn ZigClangTagDecl_isThisDeclarationADefinition(self: *const ZigClang
787787pub extern fn ZigClangEnumType_getDecl(record_ty: ?*const struct_ZigClangEnumType) *const struct_ZigClangEnumDecl;
788788pub extern fn ZigClangRecordDecl_getCanonicalDecl(record_decl: ?*const struct_ZigClangRecordDecl) ?*const struct_ZigClangTagDecl;
789789pub 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;
790791pub extern fn ZigClangEnumDecl_getCanonicalDecl(self: ?*const struct_ZigClangEnumDecl) ?*const struct_ZigClangTagDecl;
791792pub extern fn ZigClangTypedefNameDecl_getCanonicalDecl(self: ?*const struct_ZigClangTypedefNameDecl) ?*const struct_ZigClangTypedefNameDecl;
792793pub 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
834835pub extern fn ZigClangType_isVoidType(self: ?*const struct_ZigClangType) bool;
835836pub extern fn ZigClangType_isConstantArrayType(self: ?*const struct_ZigClangType) bool;
836837pub extern fn ZigClangType_isRecordType(self: ?*const struct_ZigClangType) bool;
838pub extern fn ZigClangType_isIncompleteOrZeroLengthArrayType(self: ?*const struct_ZigClangType, *const ZigClangASTContext) bool;
837839pub extern fn ZigClangType_isArrayType(self: ?*const struct_ZigClangType) bool;
838840pub extern fn ZigClangType_isBooleanType(self: ?*const struct_ZigClangType) bool;
839841pub 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 {
306306
307307 fn errorPosition(self: *Tokenizer, position: usize, bytes: []const u8, comptime fmt: []const u8, args: var) Error {
308308 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);
310310 try buffer.append(" '");
311311 var out = makeOutput(std.Buffer.append, &buffer);
312312 try printCharValues(&out, bytes);
313313 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)});
315315 self.error_text = buffer.toSlice();
316316 return Error.InvalidInput;
317317 }
......@@ -319,10 +319,9 @@ pub const Tokenizer = struct {
319319 fn errorIllegalChar(self: *Tokenizer, position: usize, char: u8, comptime fmt: []const u8, args: var) Error {
320320 var buffer = try std.Buffer.initSize(&self.arena.allocator, 0);
321321 try buffer.append("illegal char ");
322 var out = makeOutput(std.Buffer.append, &buffer);
323 try printUnderstandableChar(&out, char);
324 std.fmt.format(&buffer, anyerror, std.Buffer.append, " at position {}", .{position}) catch {};
325 if (fmt.len != 0) std.fmt.format(&buffer, anyerror, std.Buffer.append, ": " ++ fmt, args) catch {};
322 try printUnderstandableChar(&buffer, char);
323 try buffer.outStream().print(" at position {}", .{position});
324 if (fmt.len != 0) try buffer.outStream().print(": " ++ fmt, args);
326325 self.error_text = buffer.toSlice();
327326 return Error.InvalidInput;
328327 }
......@@ -996,14 +995,13 @@ fn printCharValues(out: var, bytes: []const u8) !void {
996995 }
997996}
998997
999fn printUnderstandableChar(out: var, char: u8) !void {
998fn printUnderstandableChar(buffer: *std.Buffer, char: u8) !void {
1000999 if (!std.ascii.isPrint(char) or char == ' ') {
1001 const output = @typeInfo(@TypeOf(out)).Pointer.child.output;
1002 std.fmt.format(out.context, anyerror, output, "\\x{X:2}", .{char}) catch {};
1000 try buffer.outStream().print("\\x{X:2}", .{char});
10031001 } else {
1004 try out.write("'");
1005 try out.write(&[_]u8{printable_char_tab[char]});
1006 try out.write("'");
1002 try buffer.append("'");
1003 try buffer.appendByte(printable_char_tab[char]);
1004 try buffer.append("'");
10071005 }
10081006}
10091007
src-self-hosted/libc_installation.zig+5-30
......@@ -17,7 +17,6 @@ pub const LibCInstallation = struct {
1717 include_dir: ?[:0]const u8 = null,
1818 sys_include_dir: ?[:0]const u8 = null,
1919 crt_dir: ?[:0]const u8 = null,
20 static_crt_dir: ?[:0]const u8 = null,
2120 msvc_lib_dir: ?[:0]const u8 = null,
2221 kernel32_lib_dir: ?[:0]const u8 = null,
2322
......@@ -38,7 +37,7 @@ pub const LibCInstallation = struct {
3837 pub fn parse(
3938 allocator: *Allocator,
4039 libc_file: []const u8,
41 stderr: *std.io.OutStream(fs.File.WriteError),
40 stderr: var,
4241 ) !LibCInstallation {
4342 var self: LibCInstallation = .{};
4443
......@@ -98,13 +97,6 @@ pub const LibCInstallation = struct {
9897 try stderr.print("crt_dir may not be empty for {}\n", .{@tagName(Target.current.os.tag)});
9998 return error.ParseError;
10099 }
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 }
108100 if (self.msvc_lib_dir == null and is_windows and !is_gnu) {
109101 try stderr.print("msvc_lib_dir may not be empty for {}-{}\n", .{
110102 @tagName(Target.current.os.tag),
......@@ -123,12 +115,11 @@ pub const LibCInstallation = struct {
123115 return self;
124116 }
125117
126 pub fn render(self: LibCInstallation, out: *std.io.OutStream(fs.File.WriteError)) !void {
118 pub fn render(self: LibCInstallation, out: var) !void {
127119 @setEvalBranchQuota(4000);
128120 const include_dir = self.include_dir orelse "";
129121 const sys_include_dir = self.sys_include_dir orelse "";
130122 const crt_dir = self.crt_dir orelse "";
131 const static_crt_dir = self.static_crt_dir orelse "";
132123 const msvc_lib_dir = self.msvc_lib_dir orelse "";
133124 const kernel32_lib_dir = self.kernel32_lib_dir orelse "";
134125
......@@ -147,11 +138,6 @@ pub const LibCInstallation = struct {
147138 \\# Not needed when targeting MacOS.
148139 \\crt_dir={}
149140 \\
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 \\
155141 \\# The directory that contains `vcruntime.lib`.
156142 \\# Only needed when targeting MSVC on Windows.
157143 \\msvc_lib_dir={}
......@@ -164,7 +150,6 @@ pub const LibCInstallation = struct {
164150 include_dir,
165151 sys_include_dir,
166152 crt_dir,
167 static_crt_dir,
168153 msvc_lib_dir,
169154 kernel32_lib_dir,
170155 });
......@@ -186,7 +171,6 @@ pub const LibCInstallation = struct {
186171 var batch = Batch(FindError!void, 3, .auto_async).init();
187172 batch.add(&async self.findNativeIncludeDirPosix(args));
188173 batch.add(&async self.findNativeCrtDirPosix(args));
189 batch.add(&async self.findNativeStaticCrtDirPosix(args));
190174 try batch.wait();
191175 } else {
192176 var sdk: *ZigWindowsSDK = undefined;
......@@ -348,7 +332,7 @@ pub const LibCInstallation = struct {
348332
349333 for (searches) |search| {
350334 result_buf.shrink(0);
351 const stream = &std.io.BufferOutStream.init(&result_buf).stream;
335 const stream = result_buf.outStream();
352336 try stream.print("{}\\Include\\{}\\ucrt", .{ search.path, search.version });
353337
354338 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {
......@@ -395,7 +379,7 @@ pub const LibCInstallation = struct {
395379
396380 for (searches) |search| {
397381 result_buf.shrink(0);
398 const stream = &std.io.BufferOutStream.init(&result_buf).stream;
382 const stream = result_buf.outStream();
399383 try stream.print("{}\\Lib\\{}\\ucrt\\{}", .{ search.path, search.version, arch_sub_dir });
400384
401385 var dir = fs.cwd().openDirList(result_buf.toSliceConst()) catch |err| switch (err) {
......@@ -428,15 +412,6 @@ pub const LibCInstallation = struct {
428412 });
429413 }
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
440415 fn findNativeKernel32LibDir(
441416 self: *LibCInstallation,
442417 args: FindNativeOptions,
......@@ -459,7 +434,7 @@ pub const LibCInstallation = struct {
459434
460435 for (searches) |search| {
461436 result_buf.shrink(0);
462 const stream = &std.io.BufferOutStream.init(&result_buf).stream;
437 const stream = result_buf.outStream();
463438 try stream.print("{}\\Lib\\{}\\um\\{}", .{ search.path, search.version, arch_sub_dir });
464439
465440 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{
5252 "sparc-linux-gnu",
5353 "sparcv9-linux-gnu",
5454 "wasm32-freestanding-musl",
55 "x86_64-linux-gnu (native)",
55 "x86_64-linux-gnu",
5656 "x86_64-linux-gnux32",
5757 "x86_64-linux-musl",
5858 "x86_64-windows-gnu",
......@@ -61,7 +61,8 @@ const available_libcs = [_][]const u8{
6161pub fn cmdTargets(
6262 allocator: *Allocator,
6363 args: []const []const u8,
64 stdout: *io.OutStream(fs.File.WriteError),
64 /// Output stream
65 stdout: var,
6566 native_target: Target,
6667) !void {
6768 const available_glibcs = blk: {
......@@ -92,9 +93,9 @@ pub fn cmdTargets(
9293 };
9394 defer allocator.free(available_glibcs);
9495
95 const BOS = io.BufferedOutStream(fs.File.WriteError);
96 var bos = BOS.init(stdout);
97 var jws = std.json.WriteStream(BOS.Stream, 6).init(&bos.stream);
96 var bos = io.bufferedOutStream(stdout);
97 const bos_stream = bos.outStream();
98 var jws = std.json.WriteStream(@TypeOf(bos_stream), 6).init(bos_stream);
9899
99100 try jws.beginObject();
100101
......@@ -219,6 +220,6 @@ pub fn cmdTargets(
219220
220221 try jws.endObject();
221222
222 try bos.stream.writeByte('\n');
223 try bos_stream.writeByte('\n');
223224 return bos.flush();
224225}
src-self-hosted/stage2.zig+80-90
......@@ -18,8 +18,8 @@ const assert = std.debug.assert;
1818const LibCInstallation = @import("libc_installation.zig").LibCInstallation;
1919
2020var stderr_file: fs.File = undefined;
21var stderr: *io.OutStream(fs.File.WriteError) = undefined;
22var stdout: *io.OutStream(fs.File.WriteError) = undefined;
21var stderr: fs.File.OutStream = undefined;
22var stdout: fs.File.OutStream = undefined;
2323
2424comptime {
2525 _ = @import("dep_tokenizer.zig");
......@@ -146,7 +146,7 @@ export fn stage2_free_clang_errors(errors_ptr: [*]translate_c.ClangErrMsg, error
146146}
147147
148148export 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);
150150 _ = std.zig.render(std.heap.c_allocator, c_out_stream, tree) catch |e| switch (e) {
151151 error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode
152152 error.SystemResources => return .SystemResources,
......@@ -186,9 +186,9 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
186186 try args_list.append(mem.toSliceConst(u8, argv[arg_i]));
187187 }
188188
189 stdout = &std.io.getStdOut().outStream().stream;
189 stdout = std.io.getStdOut().outStream();
190190 stderr_file = std.io.getStdErr();
191 stderr = &stderr_file.outStream().stream;
191 stderr = stderr_file.outStream();
192192
193193 const args = args_list.toSliceConst()[2..];
194194
......@@ -203,11 +203,11 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
203203 const arg = args[i];
204204 if (mem.startsWith(u8, arg, "-")) {
205205 if (mem.eql(u8, arg, "--help")) {
206 try stdout.write(self_hosted_main.usage_fmt);
206 try stdout.writeAll(self_hosted_main.usage_fmt);
207207 process.exit(0);
208208 } else if (mem.eql(u8, arg, "--color")) {
209209 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");
211211 process.exit(1);
212212 }
213213 i += 1;
......@@ -238,14 +238,14 @@ fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
238238
239239 if (stdin_flag) {
240240 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");
242242 process.exit(1);
243243 }
244244
245245 const stdin_file = io.getStdIn();
246246 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);
249249 defer allocator.free(source_code);
250250
251251 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 {
272272 }
273273
274274 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");
276276 process.exit(1);
277277 }
278278
......@@ -409,11 +409,11 @@ fn printErrMsgToFile(
409409 const end_loc = tree.tokenLocationPtr(first_token.end, last_token);
410410
411411 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();
413413 try parse_error.render(&tree.tokens, out_stream);
414414 const text = text_buf.toOwnedSlice();
415415
416 const stream = &file.outStream().stream;
416 const stream = &file.outStream();
417417 try stream.print("{}:{}:{}: error: {}\n", .{ path, start_loc.line + 1, start_loc.column + 1, text });
418418
419419 if (!color_on) return;
......@@ -626,22 +626,30 @@ fn detectNativeCpuWithLLVM(
626626}
627627
628628// ABI warning
629export fn stage2_cmd_targets(zig_triple: [*:0]const u8) c_int {
630 cmdTargets(zig_triple) catch |err| {
629export fn stage2_cmd_targets(
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| {
631635 std.debug.warn("unable to list targets: {}\n", .{@errorName(err)});
632636 return -1;
633637 };
634638 return 0;
635639}
636640
637fn cmdTargets(zig_triple: [*:0]const u8) !void {
638 var cross_target = try CrossTarget.parse(.{ .arch_os_abi = mem.toSliceConst(u8, zig_triple) });
641fn cmdTargets(
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);
639647 var dynamic_linker: ?[*:0]u8 = null;
640648 const target = try crossTargetToTarget(cross_target, &dynamic_linker);
641649 return @import("print_targets.zig").cmdTargets(
642650 std.heap.c_allocator,
643651 &[0][]u8{},
644 &std.io.getStdOut().outStream().stream,
652 std.io.getStdOut().outStream(),
645653 target,
646654 );
647655}
......@@ -673,51 +681,58 @@ export fn stage2_target_parse(
673681 return .None;
674682}
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
676729fn stage2TargetParse(
677730 stage1_target: *Stage2Target,
678731 zig_triple_oz: ?[*:0]const u8,
679732 mcpu_oz: ?[*:0]const u8,
680733 dynamic_linker_oz: ?[*:0]const u8,
681734) !void {
682 const target: CrossTarget = if (zig_triple_oz) |zig_triple_z| blk: {
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
735 const target = try stage2CrossTarget(zig_triple_oz, mcpu_oz, dynamic_linker_oz);
721736 try stage1_target.fromTarget(target);
722737}
723738
......@@ -729,8 +744,6 @@ const Stage2LibCInstallation = extern struct {
729744 sys_include_dir_len: usize,
730745 crt_dir: [*:0]const u8,
731746 crt_dir_len: usize,
732 static_crt_dir: [*:0]const u8,
733 static_crt_dir_len: usize,
734747 msvc_lib_dir: [*:0]const u8,
735748 msvc_lib_dir_len: usize,
736749 kernel32_lib_dir: [*:0]const u8,
......@@ -758,13 +771,6 @@ const Stage2LibCInstallation = extern struct {
758771 self.crt_dir = "";
759772 self.crt_dir_len = 0;
760773 }
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 }
768774 if (libc.msvc_lib_dir) |s| {
769775 self.msvc_lib_dir = s.ptr;
770776 self.msvc_lib_dir_len = s.len;
......@@ -792,9 +798,6 @@ const Stage2LibCInstallation = extern struct {
792798 if (self.crt_dir_len != 0) {
793799 libc.crt_dir = self.crt_dir[0..self.crt_dir_len :0];
794800 }
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 }
798801 if (self.msvc_lib_dir_len != 0) {
799802 libc.msvc_lib_dir = self.msvc_lib_dir[0..self.msvc_lib_dir_len :0];
800803 }
......@@ -808,7 +811,7 @@ const Stage2LibCInstallation = extern struct {
808811// ABI warning
809812export fn stage2_libc_parse(stage1_libc: *Stage2LibCInstallation, libc_file_z: [*:0]const u8) Error {
810813 stderr_file = std.io.getStdErr();
811 stderr = &stderr_file.outStream().stream;
814 stderr = stderr_file.outStream();
812815 const libc_file = mem.toSliceConst(u8, libc_file_z);
813816 var libc = LibCInstallation.parse(std.heap.c_allocator, libc_file, stderr) catch |err| switch (err) {
814817 error.ParseError => return .SemanticAnalyzeFail,
......@@ -870,7 +873,7 @@ export fn stage2_libc_find_native(stage1_libc: *Stage2LibCInstallation) Error {
870873// ABI warning
871874export fn stage2_libc_render(stage1_libc: *Stage2LibCInstallation, output_file: *FILE) Error {
872875 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);
874877 libc.render(c_out_stream) catch |err| switch (err) {
875878 error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode
876879 error.SystemResources => return .SystemResources,
......@@ -902,26 +905,11 @@ const Stage2Target = extern struct {
902905 llvm_cpu_features: ?[*:0]const u8,
903906 cpu_builtin_str: ?[*:0]const u8,
904907 cache_hash: ?[*:0]const u8,
908 cache_hash_len: usize,
905909 os_builtin_str: ?[*:0]const u8,
906910
907911 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
925913 fn fromTarget(self: *Stage2Target, cross_target: CrossTarget) !void {
926914 const allocator = std.heap.c_allocator;
927915
......@@ -1031,7 +1019,7 @@ const Stage2Target = extern struct {
10311019 .macosx,
10321020 .netbsd,
10331021 .openbsd,
1034 => try os_builtin_str_buffer.print(
1022 => try os_builtin_str_buffer.outStream().print(
10351023 \\ .semver = .{{
10361024 \\ .min = .{{
10371025 \\ .major = {},
......@@ -1055,7 +1043,7 @@ const Stage2Target = extern struct {
10551043 target.os.version_range.semver.max.patch,
10561044 }),
10571045
1058 .linux => try os_builtin_str_buffer.print(
1046 .linux => try os_builtin_str_buffer.outStream().print(
10591047 \\ .linux = .{{
10601048 \\ .range = .{{
10611049 \\ .min = .{{
......@@ -1090,7 +1078,7 @@ const Stage2Target = extern struct {
10901078 target.os.version_range.linux.glibc.patch,
10911079 }),
10921080
1093 .windows => try os_builtin_str_buffer.print(
1081 .windows => try os_builtin_str_buffer.outStream().print(
10941082 \\ .windows = .{{
10951083 \\ .min = .{},
10961084 \\ .max = .{},
......@@ -1131,6 +1119,7 @@ const Stage2Target = extern struct {
11311119 }
11321120 };
11331121
1122 const cache_hash_slice = cache_hash.toOwnedSlice();
11341123 self.* = .{
11351124 .arch = @enumToInt(target.cpu.arch) + 1, // skip over ZigLLVM_UnknownArch
11361125 .vendor = 0,
......@@ -1140,7 +1129,8 @@ const Stage2Target = extern struct {
11401129 .llvm_cpu_features = llvm_features_buffer.toOwnedSlice().ptr,
11411130 .cpu_builtin_str = cpu_builtin_str_buffer.toOwnedSlice().ptr,
11421131 .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,
11441134 .is_native = cross_target.isNative(),
11451135 .glibc_or_darwin_version = glibc_or_darwin_version,
11461136 .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 {
560560
561561 // TODO https://github.com/ziglang/zig/issues/3756
562562 // 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;
564564 const var_decl_loc = ZigClangVarDecl_getLocation(var_decl);
565565
566566 const qual_type = ZigClangVarDecl_getTypeSourceInfo_getType(var_decl);
......@@ -632,7 +632,7 @@ fn visitVarDecl(c: *Context, var_decl: *const ZigClangVarDecl) Error!void {
632632 const align_expr = blk: {
633633 const alignment = ZigClangVarDecl_getAlignedAttribute(var_decl, rp.c.clang_context);
634634 if (alignment != 0) {
635 _ = try appendToken(rp.c, .Keyword_linksection, "align");
635 _ = try appendToken(rp.c, .Keyword_align, "align");
636636 _ = try appendToken(rp.c, .LParen, "(");
637637 // Clang reports the alignment in bits
638638 const expr = try transCreateNodeInt(rp.c, alignment / 8);
......@@ -677,7 +677,7 @@ fn transTypeDef(c: *Context, typedef_decl: *const ZigClangTypedefNameDecl, top_l
677677
678678 // TODO https://github.com/ziglang/zig/issues/3756
679679 // 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
682682 if (mem.eql(u8, checked_name, "uint8_t"))
683683 return transTypeDefAsBuiltin(c, typedef_decl, "u8")
......@@ -793,6 +793,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
793793 while (ZigClangRecordDecl_field_iterator_neq(it, end_it)) : (it = ZigClangRecordDecl_field_iterator_next(it)) {
794794 const field_decl = ZigClangRecordDecl_field_iterator_deref(it);
795795 const field_loc = ZigClangFieldDecl_getLocation(field_decl);
796 const field_qt = ZigClangFieldDecl_getType(field_decl);
796797
797798 if (ZigClangFieldDecl_isBitField(field_decl)) {
798799 const opaque = try transCreateNodeOpaqueType(c);
......@@ -801,6 +802,13 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
801802 break :blk opaque;
802803 }
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
804812 var is_anon = false;
805813 var raw_name = try c.str(ZigClangNamedDecl_getName_bytes_begin(@ptrCast(*const ZigClangNamedDecl, field_decl)));
806814 if (ZigClangFieldDecl_isAnonymousStructOrUnion(field_decl)) {
......@@ -809,7 +817,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
809817 }
810818 const field_name = try appendIdentifier(c, raw_name);
811819 _ = 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) {
813821 error.UnsupportedType => {
814822 const opaque = try transCreateNodeOpaqueType(c);
815823 semicolon = try appendToken(c, .Semicolon, ";");
......@@ -819,6 +827,20 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
819827 else => |e| return e,
820828 };
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
822844 const field_node = try c.a().create(ast.Node.ContainerField);
823845 field_node.* = .{
824846 .doc_comments = null,
......@@ -826,7 +848,7 @@ fn transRecordDecl(c: *Context, record_decl: *const ZigClangRecordDecl) Error!?*
826848 .name_token = field_name,
827849 .type_expr = field_type,
828850 .value_expr = null,
829 .align_expr = null,
851 .align_expr = align_expr,
830852 };
831853
832854 if (is_anon) {
......@@ -4599,7 +4621,7 @@ fn finishTransFnProto(
45994621 if (fn_decl) |decl| {
46004622 const alignment = ZigClangFunctionDecl_getAlignedAttribute(decl, rp.c.clang_context);
46014623 if (alignment != 0) {
4602 _ = try appendToken(rp.c, .Keyword_linksection, "align");
4624 _ = try appendToken(rp.c, .Keyword_align, "align");
46034625 _ = try appendToken(rp.c, .LParen, "(");
46044626 // Clang reports the alignment in bits
46054627 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
47314753
47324754fn appendTokenFmt(c: *Context, token_id: Token.Id, comptime format: []const u8, args: var) !ast.TokenIndex {
47334755 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 };
47394756 const start_index = c.source_buffer.len();
47404757 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);
47434760 const end_index = c.source_buffer.len();
47444761 const token_index = c.tree.tokens.len;
47454762 const new_token = try c.tree.tokens.addOne();
......@@ -4850,7 +4867,7 @@ fn transPreprocessorEntities(c: *Context, unit: *ZigClangASTUnit) Error!void {
48504867 const name = try c.str(raw_name);
48514868 // TODO https://github.com/ziglang/zig/issues/3756
48524869 // 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;
48544871 if (scope.containsNow(mangled_name)) {
48554872 continue;
48564873 }
......@@ -5354,7 +5371,7 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
53545371 const first_tok = it.list.at(0);
53555372 const token = try appendToken(c, .CharLiteral, try zigifyEscapeSequences(c, source[tok.start..tok.end], source[first_tok.start..first_tok.end], source_loc));
53565373 const node = try c.a().create(ast.Node.CharLiteral);
5357 node.* = ast.Node.CharLiteral{
5374 node.* = .{
53585375 .token = token,
53595376 };
53605377 return &node.base;
......@@ -5363,7 +5380,7 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
53635380 const first_tok = it.list.at(0);
53645381 const token = try appendToken(c, .StringLiteral, try zigifyEscapeSequences(c, source[tok.start..tok.end], source[first_tok.start..first_tok.end], source_loc));
53655382 const node = try c.a().create(ast.Node.StringLiteral);
5366 node.* = ast.Node.StringLiteral{
5383 node.* = .{
53675384 .token = token,
53685385 };
53695386 return &node.base;
......@@ -5428,15 +5445,14 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
54285445 return error.ParseError;
54295446 }
54305447
5431 // TODO: It might be nice if we only did the alignCasting for opaque types
5432 //( if (@typeInfo(@TypeOf(x)) == .Pointer)
5433 // @ptrCast(dest, @alignCast(@alignOf(dest.Child), x))
5434 //else if (@typeInfo(@TypeOf(x)) == .Integer)
5448 //if (@typeInfo(@TypeOf(x)) == .Pointer)
5449 // @ptrCast(dest, x)
5450 //else if (@typeInfo(@TypeOf(x)) == .Int and @typeInfo(dest) == .Pointer)
54355451 // @intToPtr(dest, x)
54365452 //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
54415457 const if_1 = try transCreateNodeIf(c);
54425458 const type_id_1 = try transCreateNodeBuiltinFnCall(c, "@typeInfo");
......@@ -5456,30 +5472,9 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
54565472 if_1.condition = &cmp_1.base;
54575473 _ = 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
54805475 const ptr_cast = try transCreateNodeBuiltinFnCall(c, "@ptrCast");
54815476 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);
54835478 ptr_cast.rparen_token = try appendToken(c, .RParen, ")");
54845479 if_1.body = &ptr_cast.base;
54855480
......@@ -5502,6 +5497,25 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
55025497 .rhs = try transCreateNodeEnumLiteral(c, "Int"),
55035498 };
55045499 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;
55055519 else_1.body = &if_2.base;
55065520 _ = try appendToken(c, .RParen, ")");
55075521
......@@ -5520,14 +5534,13 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
55205534 as.rparen_token = try appendToken(c, .RParen, ")");
55215535 else_2.body = &as.base;
55225536
5523 const group_rparen = try appendToken(c, .RParen, ")");
5524 const grouped_expr = try c.a().create(ast.Node.GroupedExpression);
5525 grouped_expr.* = .{
5526 .lparen = group_lparen,
5537 const group_node = try c.a().create(ast.Node.GroupedExpression);
5538 group_node.* = .{
5539 .lparen = lparen,
55275540 .expr = &if_1.base,
5528 .rparen = group_rparen,
5541 .rparen = try appendToken(c, .RParen, ")"),
55295542 };
5530 return &grouped_expr.base;
5543 return &group_node.base;
55315544 },
55325545 else => {
55335546 const first_tok = it.list.at(0);
......@@ -5543,12 +5556,63 @@ fn parseCPrimaryExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
55435556 }
55445557}
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
55465609fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8, source_loc: ZigClangSourceLocation, scope: *Scope) ParseError!*ast.Node {
55475610 var node = try parseCPrimaryExpr(c, it, source, source_loc, scope);
55485611 while (true) {
55495612 const tok = it.next().?;
55505613 var op_token: ast.TokenIndex = undefined;
55515614 var op_id: ast.Node.InfixOp.Op = undefined;
5615 var bool_op = false;
55525616 switch (tok.id) {
55535617 .Period => {
55545618 const name_tok = it.next().?;
......@@ -5637,10 +5701,12 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
56375701 .AmpersandAmpersand => {
56385702 op_token = try appendToken(c, .Keyword_and, "and");
56395703 op_id = .BoolAnd;
5704 bool_op = true;
56405705 },
56415706 .PipePipe => {
56425707 op_token = try appendToken(c, .Keyword_or, "or");
56435708 op_id = .BoolOr;
5709 bool_op = true;
56445710 },
56455711 .AngleBracketRight => {
56465712 op_token = try appendToken(c, .AngleBracketRight, ">");
......@@ -5711,12 +5777,10 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
57115777 op_id = .EqualEqual;
57125778 },
57135779 .Slash => {
5714 // unsigned/float division uses the operator
57155780 op_id = .Div;
57165781 op_token = try appendToken(c, .Slash, "/");
57175782 },
57185783 .Percent => {
5719 // unsigned/float division uses the operator
57205784 op_id = .Mod;
57215785 op_token = try appendToken(c, .Percent, "%");
57225786 },
......@@ -5725,12 +5789,15 @@ fn parseCSuffixOpExpr(c: *Context, it: *CTokenList.Iterator, source: []const u8,
57255789 return node;
57265790 },
57275791 }
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);
57285795 const op_node = try c.a().create(ast.Node.InfixOp);
57295796 op_node.* = .{
57305797 .op_token = op_token,
5731 .lhs = node,
5798 .lhs = lhs_node,
57325799 .op = op_id,
5733 .rhs = try parseCPrefixOpExpr(c, it, source, source_loc, scope),
5800 .rhs = try cast_fn(c, rhs_node),
57345801 };
57355802 node = &op_node.base;
57365803 }
src/all_types.hpp+13-1
......@@ -651,6 +651,7 @@ enum NodeType {
651651 NodeTypeSwitchProng,
652652 NodeTypeSwitchRange,
653653 NodeTypeCompTime,
654 NodeTypeNoAsync,
654655 NodeTypeBreak,
655656 NodeTypeContinue,
656657 NodeTypeAsmExpr,
......@@ -991,6 +992,10 @@ struct AstNodeCompTime {
991992 AstNode *expr;
992993};
993994
995struct AstNodeNoAsync {
996 AstNode *expr;
997};
998
994999struct AsmOutput {
9951000 Buf *asm_symbolic_name;
9961001 Buf *constraint;
......@@ -1148,7 +1153,6 @@ struct AstNodeErrorType {
11481153};
11491154
11501155struct AstNodeAwaitExpr {
1151 Token *noasync_token;
11521156 AstNode *expr;
11531157};
11541158
......@@ -1199,6 +1203,7 @@ struct AstNode {
11991203 AstNodeSwitchProng switch_prong;
12001204 AstNodeSwitchRange switch_range;
12011205 AstNodeCompTime comptime_expr;
1206 AstNodeNoAsync noasync_expr;
12021207 AstNodeAsmExpr asm_expr;
12031208 AstNodeFieldAccessExpr field_access_expr;
12041209 AstNodePtrDerefExpr ptr_deref_expr;
......@@ -1828,6 +1833,7 @@ enum PanicMsgId {
18281833 PanicMsgIdBadNoAsyncCall,
18291834 PanicMsgIdResumeNotSuspendedFn,
18301835 PanicMsgIdBadSentinel,
1836 PanicMsgIdShxTooBigRhs,
18311837
18321838 PanicMsgIdCount,
18331839};
......@@ -2324,6 +2330,7 @@ enum ScopeId {
23242330 ScopeIdRuntime,
23252331 ScopeIdTypeOf,
23262332 ScopeIdExpr,
2333 ScopeIdNoAsync,
23272334};
23282335
23292336struct Scope {
......@@ -2456,6 +2463,11 @@ struct ScopeCompTime {
24562463 Scope base;
24572464};
24582465
2466// This scope is created for a noasync expression.
2467// NodeTypeNoAsync
2468struct ScopeNoAsync {
2469 Scope base;
2470};
24592471
24602472// This scope is created for a function definition.
24612473// NodeTypeFnDef
src/analyze.cpp+65-24
......@@ -106,6 +106,7 @@ static ScopeExpr *find_expr_scope(Scope *scope) {
106106 case ScopeIdDecls:
107107 case ScopeIdFnDef:
108108 case ScopeIdCompTime:
109 case ScopeIdNoAsync:
109110 case ScopeIdVarDecl:
110111 case ScopeIdCImport:
111112 case ScopeIdSuspend:
......@@ -226,6 +227,12 @@ Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent) {
226227 return &scope->base;
227228}
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
229236Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent) {
230237 ScopeTypeOf *scope = heap::c_allocator.create<ScopeTypeOf>();
231238 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
19551962 return g->builtin_types.entry_invalid;
19561963 }
19571964
1958 switch (specified_return_type->id) {
1959 case ZigTypeIdInvalid:
1960 zig_unreachable();
1961
1962 case ZigTypeIdUndefined:
1963 case ZigTypeIdNull:
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;
1965 if(!is_valid_return_type(specified_return_type)){
1966 ErrorMsg* msg = add_node_error(g, fn_proto->return_type,
1967 buf_sprintf("%s return type '%s' not allowed", type_id_name(specified_return_type->id), buf_ptr(&specified_return_type->name)));
1968 Tld *tld = find_decl(g, &fn_entry->fndef_scope->base, &specified_return_type->name);
1969 if (tld != nullptr) {
1970 add_error_note(g, msg, tld->source_node, buf_sprintf("type declared here"));
19771971 }
1978
1979 default:
1980 break;
1972 return g->builtin_types.entry_invalid;
19811973 }
19821974
19831975 if (fn_proto->auto_err_set) {
......@@ -2049,6 +2041,19 @@ static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_sc
20492041 return get_fn_type(g, &fn_type_id);
20502042}
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
20522057bool type_is_invalid(ZigType *type_entry) {
20532058 switch (type_entry->id) {
20542059 case ZigTypeIdInvalid:
......@@ -2893,7 +2898,7 @@ static Error resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type) {
28932898 return ErrorSemanticAnalyzeFail;
28942899 }
28952900 if (field_is_opaque_type) {
2896 add_node_error(g, field_node->data.struct_field.type,
2901 add_node_error(g, field_node,
28972902 buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in structs"));
28982903 struct_type->data.structure.resolve_status = ResolveStatusInvalid;
28992904 return ErrorSemanticAnalyzeFail;
......@@ -3185,7 +3190,7 @@ static Error resolve_union_zero_bits(CodeGen *g, ZigType *union_type) {
31853190 return ErrorSemanticAnalyzeFail;
31863191 }
31873192 if (field_is_opaque_type) {
3188 add_node_error(g, field_node->data.struct_field.type,
3193 add_node_error(g, field_node,
31893194 buf_create_from_str(
31903195 "opaque types have unknown size and therefore cannot be directly embedded in unions"));
31913196 union_type->data.unionation.resolve_status = ResolveStatusInvalid;
......@@ -3755,6 +3760,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) {
37553760 case NodeTypeCompTime:
37563761 preview_comptime_decl(g, node, decls_scope);
37573762 break;
3763 case NodeTypeNoAsync:
37583764 case NodeTypeParamDecl:
37593765 case NodeTypeReturnExpr:
37603766 case NodeTypeDefer:
......@@ -5789,6 +5795,7 @@ ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) {
57895795 ZigValue *result = g->pass1_arena->create<ZigValue>();
57905796 result->type = type_entry;
57915797 result->special = ConstValSpecialStatic;
5798
57925799 if (result->type->id == ZigTypeIdStruct) {
57935800 // The fields array cannot be left unpopulated
57945801 const ZigType *struct_type = result->type;
......@@ -5800,6 +5807,22 @@ ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) {
58005807 assert(field_type != nullptr);
58015808 result->data.x_struct.fields[i] = get_the_one_possible_value(g, field_type);
58025809 }
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 }
58035826 } else if (result->type->id == ZigTypeIdPointer) {
58045827 result->data.x_ptr.special = ConstPtrSpecialRef;
58055828 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) {
61766199 case ScopeIdDecls:
61776200 case ScopeIdFnDef:
61786201 case ScopeIdCompTime:
6202 case ScopeIdNoAsync:
61796203 case ScopeIdCImport:
61806204 case ScopeIdSuspend:
61816205 case ScopeIdTypeOf:
......@@ -9528,6 +9552,23 @@ void copy_const_val(CodeGen *g, ZigValue *dest, ZigValue *src) {
95289552 }
95299553}
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
95319572bool type_is_numeric(ZigType *ty) {
95329573 switch (ty->id) {
95339574 case ZigTypeIdInvalid:
src/analyze.hpp+3
......@@ -125,6 +125,7 @@ ScopeLoop *create_loop_scope(CodeGen *g, AstNode *node, Scope *parent);
125125ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent);
126126ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn *fn_entry);
127127Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent);
128Scope *create_noasync_scope(CodeGen *g, AstNode *node, Scope *parent);
128129Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstSrc *is_comptime);
129130Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent);
130131ScopeExpr *create_expr_scope(CodeGen *g, AstNode *node, Scope *parent);
......@@ -197,6 +198,7 @@ size_t type_id_index(ZigType *entry);
197198ZigType *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id);
198199LinkLib *create_link_lib(Buf *name);
199200LinkLib *add_link_lib(CodeGen *codegen, Buf *lib);
201bool optional_value_is_null(ZigValue *val);
200202
201203uint32_t get_abi_alignment(CodeGen *g, ZigType *type_entry);
202204ZigType *get_align_amt_type(CodeGen *g);
......@@ -265,6 +267,7 @@ ZigValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *
265267void resolve_llvm_types_fn(CodeGen *g, ZigFn *fn);
266268bool fn_is_async(ZigFn *fn);
267269CallingConvention cc_from_fn_proto(AstNodeFnProto *fn_proto);
270bool is_valid_return_type(ZigType* type);
268271
269272Error type_val_resolve_abi_align(CodeGen *g, AstNode *source_node, ZigValue *type_val, uint32_t *abi_align);
270273Error 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) {
220220 return "SwitchRange";
221221 case NodeTypeCompTime:
222222 return "CompTime";
223 case NodeTypeNoAsync:
224 return "NoAsync";
223225 case NodeTypeBreak:
224226 return "Break";
225227 case NodeTypeContinue:
......@@ -1091,6 +1093,12 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
10911093 render_node_grouped(ar, node->data.comptime_expr.expr);
10921094 break;
10931095 }
1096 case NodeTypeNoAsync:
1097 {
1098 fprintf(ar->f, "noasync ");
1099 render_node_grouped(ar, node->data.noasync_expr.expr);
1100 break;
1101 }
10941102 case NodeTypeForExpr:
10951103 {
10961104 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) {
2424 ch->b64_digest = BUF_INIT;
2525}
2626
27void cache_str(CacheHash *ch, const char *ptr) {
27void cache_mem(CacheHash *ch, const char *ptr, size_t len) {
2828 assert(ch->manifest_file_path == nullptr);
2929 assert(ptr != nullptr);
3030 // + 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);
3236}
3337
3438void cache_int(CacheHash *ch, int x) {
src/cache_hash.hpp+1
......@@ -35,6 +35,7 @@ struct CacheHash {
3535void cache_init(CacheHash *ch, Buf *manifest_dir);
3636
3737// Next, use the hash population functions to add the initial parameters.
38void cache_mem(CacheHash *ch, const char *ptr, size_t len);
3839void cache_str(CacheHash *ch, const char *ptr);
3940void cache_int(CacheHash *ch, int x);
4041void cache_bool(CacheHash *ch, bool x);
src/codegen.cpp+137-4
......@@ -686,6 +686,7 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
686686 case ScopeIdLoop:
687687 case ScopeIdSuspend:
688688 case ScopeIdCompTime:
689 case ScopeIdNoAsync:
689690 case ScopeIdRuntime:
690691 case ScopeIdTypeOf:
691692 case ScopeIdExpr:
......@@ -967,11 +968,13 @@ static Buf *panic_msg_buf(PanicMsgId msg_id) {
967968 case PanicMsgIdResumedFnPendingAwait:
968969 return buf_create_from_str("resumed an async function which can only be awaited");
969970 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");
971972 case PanicMsgIdResumeNotSuspendedFn:
972973 return buf_create_from_str("resumed a non-suspended function");
973974 case PanicMsgIdBadSentinel:
974975 return buf_create_from_str("sentinel mismatch");
976 case PanicMsgIdShxTooBigRhs:
977 return buf_create_from_str("shift amount is greater than the type size");
975978 }
976979 zig_unreachable();
977980}
......@@ -2836,6 +2839,26 @@ static LLVMValueRef gen_rem(CodeGen *g, bool want_runtime_safety, bool want_fast
28362839
28372840}
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
28392862static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,
28402863 IrInstGenBinOp *bin_op_instruction)
28412864{
......@@ -2944,6 +2967,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,
29442967 {
29452968 assert(scalar_type->id == ZigTypeIdInt);
29462969 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
29472975 bool is_sloppy = (op_id == IrBinOpBitShiftLeftLossy);
29482976 if (is_sloppy) {
29492977 return LLVMBuildShl(g->builder, op1_value, op2_casted, "");
......@@ -2960,6 +2988,11 @@ static LLVMValueRef ir_render_bin_op(CodeGen *g, IrExecutableGen *executable,
29602988 {
29612989 assert(scalar_type->id == ZigTypeIdInt);
29622990 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
29632996 bool is_sloppy = (op_id == IrBinOpBitShiftRightLossy);
29642997 if (is_sloppy) {
29652998 if (scalar_type->data.integral.is_signed) {
......@@ -3930,6 +3963,7 @@ static void render_async_var_decls(CodeGen *g, Scope *scope) {
39303963 case ScopeIdLoop:
39313964 case ScopeIdSuspend:
39323965 case ScopeIdCompTime:
3966 case ScopeIdNoAsync:
39333967 case ScopeIdRuntime:
39343968 case ScopeIdTypeOf:
39353969 case ScopeIdExpr:
......@@ -5212,11 +5246,55 @@ static enum ZigLLVM_AtomicRMWBinOp to_ZigLLVMAtomicRMWBinOp(AtomicRmwOp op, bool
52125246 zig_unreachable();
52135247}
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
52155278static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, IrInstGenCmpxchg *instruction) {
52165279 LLVMValueRef ptr_val = ir_llvm_value(g, instruction->ptr);
52175280 LLVMValueRef cmp_val = ir_llvm_value(g, instruction->cmp_value);
52185281 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
52205298 LLVMAtomicOrdering success_order = to_LLVMAtomicOrdering(instruction->success_order);
52215299 LLVMAtomicOrdering failure_order = to_LLVMAtomicOrdering(instruction->failure_order);
52225300
......@@ -5229,6 +5307,9 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, I
52295307
52305308 if (!handle_is_ptr(g, optional_type)) {
52315309 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 }
52325313 LLVMValueRef success_bit = LLVMBuildExtractValue(g->builder, result_val, 1, "");
52335314 return LLVMBuildSelect(g->builder, success_bit, LLVMConstNull(get_llvm_type(g, child_type)), payload_val, "");
52345315 }
......@@ -5243,6 +5324,9 @@ static LLVMValueRef ir_render_cmpxchg(CodeGen *g, IrExecutableGen *executable, I
52435324 ir_assert(type_has_bits(g, child_type), &instruction->base);
52445325
52455326 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 }
52465330 LLVMValueRef val_ptr = LLVMBuildStructGEP(g->builder, result_loc, maybe_child_index, "");
52475331 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
58205904 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
58215905 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
58235923 if (get_codegen_ptr_type_bail(g, operand_type) == nullptr) {
58245924 return ZigLLVMBuildAtomicRMW(g->builder, op, ptr, operand, ordering, g->is_single_threaded);
58255925 }
......@@ -5838,6 +5938,17 @@ static LLVMValueRef ir_render_atomic_load(CodeGen *g, IrExecutableGen *executabl
58385938{
58395939 LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->ordering);
58405940 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 }
58415952 LLVMValueRef load_inst = gen_load(g, ptr, instruction->ptr->value->type, "");
58425953 LLVMSetOrdering(load_inst, ordering);
58435954 return load_inst;
......@@ -5849,6 +5960,18 @@ static LLVMValueRef ir_render_atomic_store(CodeGen *g, IrExecutableGen *executab
58495960 LLVMAtomicOrdering ordering = to_LLVMAtomicOrdering(instruction->ordering);
58505961 LLVMValueRef ptr = ir_llvm_value(g, instruction->ptr);
58515962 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 }
58525975 LLVMValueRef store_inst = gen_store(g, value, ptr, instruction->ptr->value->type);
58535976 LLVMSetOrdering(store_inst, ordering);
58545977 return nullptr;
......@@ -6895,8 +7018,18 @@ check: switch (const_val->special) {
68957018 case ZigTypeIdOptional:
68967019 {
68977020 ZigType *child_type = type_entry->data.maybe.child_type;
7021
68987022 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);
69007033 } else if (child_type->id == ZigTypeIdErrorSet) {
69017034 return gen_const_val_err_set(g, const_val, name);
69027035 } else if (!type_has_bits(g, child_type)) {
......@@ -8614,7 +8747,7 @@ static Error define_builtin_compile_vars(CodeGen *g) {
86148747 cache_int(&cache_hash, g->zig_target->os);
86158748 cache_int(&cache_hash, g->zig_target->abi);
86168749 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);
86188751 }
86198752 if (g->zig_target->glibc_or_darwin_version != nullptr) {
86208753 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) {
1025910392 cache_int(ch, g->zig_target->os);
1026010393 cache_int(ch, g->zig_target->abi);
1026110394 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);
1026310396 }
1026410397 if (g->zig_target->glibc_or_darwin_version != nullptr) {
1026510398 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[] = {
8080"musl/src/crypt/crypt.c",
8181"musl/src/crypt/crypt_blowfish.c",
8282"musl/src/crypt/crypt_des.c",
83"musl/src/crypt/crypt_des.h",
8483"musl/src/crypt/crypt_md5.c",
8584"musl/src/crypt/crypt_r.c",
8685"musl/src/crypt/crypt_sha256.c",
......@@ -90,7 +89,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
9089"musl/src/ctype/__ctype_get_mb_cur_max.c",
9190"musl/src/ctype/__ctype_tolower_loc.c",
9291"musl/src/ctype/__ctype_toupper_loc.c",
93"musl/src/ctype/alpha.h",
9492"musl/src/ctype/isalnum.c",
9593"musl/src/ctype/isalpha.c",
9694"musl/src/ctype/isascii.c",
......@@ -117,8 +115,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
117115"musl/src/ctype/iswupper.c",
118116"musl/src/ctype/iswxdigit.c",
119117"musl/src/ctype/isxdigit.c",
120"musl/src/ctype/nonspacing.h",
121"musl/src/ctype/punct.h",
122118"musl/src/ctype/toascii.c",
123119"musl/src/ctype/tolower.c",
124120"musl/src/ctype/toupper.c",
......@@ -126,8 +122,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
126122"musl/src/ctype/wcswidth.c",
127123"musl/src/ctype/wctrans.c",
128124"musl/src/ctype/wcwidth.c",
129"musl/src/ctype/wide.h",
130"musl/src/dirent/__dirent.h",
131125"musl/src/dirent/alphasort.c",
132126"musl/src/dirent/closedir.c",
133127"musl/src/dirent/dirfd.c",
......@@ -152,7 +146,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
152146"musl/src/env/setenv.c",
153147"musl/src/env/unsetenv.c",
154148"musl/src/errno/__errno_location.c",
155"musl/src/errno/__strerror.h",
156149"musl/src/errno/strerror.c",
157150"musl/src/exit/_Exit.c",
158151"musl/src/exit/abort.c",
......@@ -196,55 +189,18 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
196189"musl/src/fenv/sh/fenv.S",
197190"musl/src/fenv/x32/fenv.s",
198191"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",
220192"musl/src/internal/defsysinfo.c",
221"musl/src/internal/dynlink.h",
222"musl/src/internal/fdpic_crt.h",
223193"musl/src/internal/floatscan.c",
224"musl/src/internal/floatscan.h",
225"musl/src/internal/futex.h",
226194"musl/src/internal/i386/defsysinfo.s",
227195"musl/src/internal/intscan.c",
228"musl/src/internal/intscan.h",
229"musl/src/internal/ksigaction.h",
230196"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",
236197"musl/src/internal/procfdname.c",
237"musl/src/internal/pthread_impl.h",
238198"musl/src/internal/sh/__shcall.c",
239199"musl/src/internal/shgetc.c",
240"musl/src/internal/shgetc.h",
241"musl/src/internal/stdio_impl.h",
242"musl/src/internal/syscall.h",
243200"musl/src/internal/syscall_ret.c",
244201"musl/src/internal/vdso.c",
245202"musl/src/internal/version.c",
246203"musl/src/ipc/ftok.c",
247"musl/src/ipc/ipc.h",
248204"musl/src/ipc/msgctl.c",
249205"musl/src/ipc/msgget.c",
250206"musl/src/ipc/msgrcv.c",
......@@ -261,6 +217,7 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
261217"musl/src/ldso/aarch64/dlsym.s",
262218"musl/src/ldso/aarch64/tlsdesc.s",
263219"musl/src/ldso/arm/dlsym.s",
220"musl/src/ldso/arm/dlsym_time64.S",
264221"musl/src/ldso/arm/find_exidx.c",
265222"musl/src/ldso/arm/tlsdesc.S",
266223"musl/src/ldso/dl_iterate_phdr.c",
......@@ -271,18 +228,26 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
271228"musl/src/ldso/dlopen.c",
272229"musl/src/ldso/dlsym.c",
273230"musl/src/ldso/i386/dlsym.s",
231"musl/src/ldso/i386/dlsym_time64.S",
274232"musl/src/ldso/i386/tlsdesc.s",
275233"musl/src/ldso/m68k/dlsym.s",
234"musl/src/ldso/m68k/dlsym_time64.S",
276235"musl/src/ldso/microblaze/dlsym.s",
236"musl/src/ldso/microblaze/dlsym_time64.S",
277237"musl/src/ldso/mips/dlsym.s",
238"musl/src/ldso/mips/dlsym_time64.S",
278239"musl/src/ldso/mips64/dlsym.s",
279240"musl/src/ldso/mipsn32/dlsym.s",
241"musl/src/ldso/mipsn32/dlsym_time64.S",
280242"musl/src/ldso/or1k/dlsym.s",
243"musl/src/ldso/or1k/dlsym_time64.S",
281244"musl/src/ldso/powerpc/dlsym.s",
245"musl/src/ldso/powerpc/dlsym_time64.S",
282246"musl/src/ldso/powerpc64/dlsym.s",
283247"musl/src/ldso/riscv64/dlsym.s",
284248"musl/src/ldso/s390x/dlsym.s",
285249"musl/src/ldso/sh/dlsym.s",
250"musl/src/ldso/sh/dlsym_time64.S",
286251"musl/src/ldso/tlsdesc.c",
287252"musl/src/ldso/x32/dlsym.s",
288253"musl/src/ldso/x86_64/dlsym.s",
......@@ -369,30 +334,21 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
369334"musl/src/linux/xattr.c",
370335"musl/src/locale/__lctrans.c",
371336"musl/src/locale/__mo_lookup.c",
372"musl/src/locale/big5.h",
373337"musl/src/locale/bind_textdomain_codeset.c",
374338"musl/src/locale/c_locale.c",
375339"musl/src/locale/catclose.c",
376340"musl/src/locale/catgets.c",
377341"musl/src/locale/catopen.c",
378"musl/src/locale/codepages.h",
379342"musl/src/locale/dcngettext.c",
380343"musl/src/locale/duplocale.c",
381344"musl/src/locale/freelocale.c",
382"musl/src/locale/gb18030.h",
383"musl/src/locale/hkscs.h",
384345"musl/src/locale/iconv.c",
385346"musl/src/locale/iconv_close.c",
386"musl/src/locale/jis0208.h",
387"musl/src/locale/ksc.h",
388347"musl/src/locale/langinfo.c",
389"musl/src/locale/legacychars.h",
390348"musl/src/locale/locale_map.c",
391349"musl/src/locale/localeconv.c",
392350"musl/src/locale/newlocale.c",
393351"musl/src/locale/pleval.c",
394"musl/src/locale/pleval.h",
395"musl/src/locale/revjis.h",
396352"musl/src/locale/setlocale.c",
397353"musl/src/locale/strcoll.c",
398354"musl/src/locale/strfmon.c",
......@@ -401,7 +357,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
401357"musl/src/locale/uselocale.c",
402358"musl/src/locale/wcscoll.c",
403359"musl/src/locale/wcsxfrm.c",
404"musl/src/malloc/DESIGN",
405360"musl/src/malloc/aligned_alloc.c",
406361"musl/src/malloc/expand_heap.c",
407362"musl/src/malloc/lite_malloc.c",
......@@ -418,7 +373,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
418373"musl/src/math/__fpclassifyf.c",
419374"musl/src/math/__fpclassifyl.c",
420375"musl/src/math/__invtrigl.c",
421"musl/src/math/__invtrigl.h",
422376"musl/src/math/__math_divzero.c",
423377"musl/src/math/__math_divzerof.c",
424378"musl/src/math/__math_invalid.c",
......@@ -525,10 +479,8 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
525479"musl/src/math/exp2.c",
526480"musl/src/math/exp2f.c",
527481"musl/src/math/exp2f_data.c",
528"musl/src/math/exp2f_data.h",
529482"musl/src/math/exp2l.c",
530483"musl/src/math/exp_data.c",
531"musl/src/math/exp_data.h",
532484"musl/src/math/expf.c",
533485"musl/src/math/expl.c",
534486"musl/src/math/expm1.c",
......@@ -579,14 +531,9 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
579531"musl/src/math/i386/ceil.s",
580532"musl/src/math/i386/ceilf.s",
581533"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",
585534"musl/src/math/i386/exp2l.s",
586"musl/src/math/i386/expf.s",
535"musl/src/math/i386/exp_ld.s",
587536"musl/src/math/i386/expl.s",
588"musl/src/math/i386/expm1.s",
589"musl/src/math/i386/expm1f.s",
590537"musl/src/math/i386/expm1l.s",
591538"musl/src/math/i386/fabs.s",
592539"musl/src/math/i386/fabsf.s",
......@@ -673,19 +620,15 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
673620"musl/src/math/log1pl.c",
674621"musl/src/math/log2.c",
675622"musl/src/math/log2_data.c",
676"musl/src/math/log2_data.h",
677623"musl/src/math/log2f.c",
678624"musl/src/math/log2f_data.c",
679"musl/src/math/log2f_data.h",
680625"musl/src/math/log2l.c",
681626"musl/src/math/log_data.c",
682"musl/src/math/log_data.h",
683627"musl/src/math/logb.c",
684628"musl/src/math/logbf.c",
685629"musl/src/math/logbl.c",
686630"musl/src/math/logf.c",
687631"musl/src/math/logf_data.c",
688"musl/src/math/logf_data.h",
689632"musl/src/math/logl.c",
690633"musl/src/math/lrint.c",
691634"musl/src/math/lrintf.c",
......@@ -693,6 +636,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
693636"musl/src/math/lround.c",
694637"musl/src/math/lroundf.c",
695638"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",
696643"musl/src/math/modf.c",
697644"musl/src/math/modff.c",
698645"musl/src/math/modfl.c",
......@@ -710,7 +657,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
710657"musl/src/math/nexttowardl.c",
711658"musl/src/math/pow.c",
712659"musl/src/math/pow_data.c",
713"musl/src/math/pow_data.h",
714660"musl/src/math/powerpc/fabs.c",
715661"musl/src/math/powerpc/fabsf.c",
716662"musl/src/math/powerpc/fma.c",
......@@ -741,7 +687,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
741687"musl/src/math/powerpc64/truncf.c",
742688"musl/src/math/powf.c",
743689"musl/src/math/powf_data.c",
744"musl/src/math/powf_data.h",
745690"musl/src/math/powl.c",
746691"musl/src/math/remainder.c",
747692"musl/src/math/remainderf.c",
......@@ -958,7 +903,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
958903"musl/src/multibyte/c16rtomb.c",
959904"musl/src/multibyte/c32rtomb.c",
960905"musl/src/multibyte/internal.c",
961"musl/src/multibyte/internal.h",
962906"musl/src/multibyte/mblen.c",
963907"musl/src/multibyte/mbrlen.c",
964908"musl/src/multibyte/mbrtoc16.c",
......@@ -1021,12 +965,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
1021965"musl/src/network/inet_ntop.c",
1022966"musl/src/network/inet_pton.c",
1023967"musl/src/network/listen.c",
1024"musl/src/network/lookup.h",
1025968"musl/src/network/lookup_ipliteral.c",
1026969"musl/src/network/lookup_name.c",
1027970"musl/src/network/lookup_serv.c",
1028971"musl/src/network/netlink.c",
1029"musl/src/network/netlink.h",
1030972"musl/src/network/netname.c",
1031973"musl/src/network/ns_parse.c",
1032974"musl/src/network/ntohl.c",
......@@ -1070,12 +1012,10 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
10701012"musl/src/passwd/getspnam.c",
10711013"musl/src/passwd/getspnam_r.c",
10721014"musl/src/passwd/lckpwdf.c",
1073"musl/src/passwd/nscd.h",
10741015"musl/src/passwd/nscd_query.c",
10751016"musl/src/passwd/putgrent.c",
10761017"musl/src/passwd/putpwent.c",
10771018"musl/src/passwd/putspent.c",
1078"musl/src/passwd/pwf.h",
10791019"musl/src/prng/__rand48_step.c",
10801020"musl/src/prng/__seed48.c",
10811021"musl/src/prng/drand48.c",
......@@ -1083,7 +1023,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
10831023"musl/src/prng/lrand48.c",
10841024"musl/src/prng/mrand48.c",
10851025"musl/src/prng/rand.c",
1086"musl/src/prng/rand48.h",
10871026"musl/src/prng/rand_r.c",
10881027"musl/src/prng/random.c",
10891028"musl/src/prng/seed48.c",
......@@ -1095,7 +1034,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
10951034"musl/src/process/execv.c",
10961035"musl/src/process/execve.c",
10971036"musl/src/process/execvp.c",
1098"musl/src/process/fdop.h",
10991037"musl/src/process/fexecve.c",
11001038"musl/src/process/fork.c",
11011039"musl/src/process/i386/vfork.s",
......@@ -1134,7 +1072,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
11341072"musl/src/regex/regerror.c",
11351073"musl/src/regex/regexec.c",
11361074"musl/src/regex/tre-mem.c",
1137"musl/src/regex/tre.h",
11381075"musl/src/sched/affinity.c",
11391076"musl/src/sched/sched_cpucount.c",
11401077"musl/src/sched/sched_get_priority_max.c",
......@@ -1152,7 +1089,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
11521089"musl/src/search/tdestroy.c",
11531090"musl/src/search/tfind.c",
11541091"musl/src/search/tsearch.c",
1155"musl/src/search/tsearch.h",
11561092"musl/src/search/twalk.c",
11571093"musl/src/select/poll.c",
11581094"musl/src/select/pselect.c",
......@@ -1335,7 +1271,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
13351271"musl/src/stdio/fwrite.c",
13361272"musl/src/stdio/fwscanf.c",
13371273"musl/src/stdio/getc.c",
1338"musl/src/stdio/getc.h",
13391274"musl/src/stdio/getc_unlocked.c",
13401275"musl/src/stdio/getchar.c",
13411276"musl/src/stdio/getchar_unlocked.c",
......@@ -1354,7 +1289,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
13541289"musl/src/stdio/popen.c",
13551290"musl/src/stdio/printf.c",
13561291"musl/src/stdio/putc.c",
1357"musl/src/stdio/putc.h",
13581292"musl/src/stdio/putc_unlocked.c",
13591293"musl/src/stdio/putchar.c",
13601294"musl/src/stdio/putchar_unlocked.c",
......@@ -1746,7 +1680,6 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
17461680"musl/src/time/strftime.c",
17471681"musl/src/time/strptime.c",
17481682"musl/src/time/time.c",
1749"musl/src/time/time_impl.h",
17501683"musl/src/time/timegm.c",
17511684"musl/src/time/timer_create.c",
17521685"musl/src/time/timer_delete.c",
......@@ -1843,4 +1776,69 @@ static const char *ZIG_MUSL_SRC_FILES[] = {
18431776"musl/src/unistd/writev.c",
18441777"musl/src/unistd/x32/lseek.c",
18451778};
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};
18461844#endif
src/ir.cpp+299-99
......@@ -4978,6 +4978,7 @@ static void ir_count_defers(IrBuilderSrc *irb, Scope *inner_scope, Scope *outer_
49784978 case ScopeIdLoop:
49794979 case ScopeIdSuspend:
49804980 case ScopeIdCompTime:
4981 case ScopeIdNoAsync:
49814982 case ScopeIdRuntime:
49824983 case ScopeIdTypeOf:
49834984 case ScopeIdExpr:
......@@ -5033,6 +5034,7 @@ static bool ir_gen_defers_for_block(IrBuilderSrc *irb, Scope *inner_scope, Scope
50335034 case ScopeIdLoop:
50345035 case ScopeIdSuspend:
50355036 case ScopeIdCompTime:
5037 case ScopeIdNoAsync:
50365038 case ScopeIdRuntime:
50375039 case ScopeIdTypeOf:
50385040 case ScopeIdExpr:
......@@ -5910,10 +5912,18 @@ static IrInstSrc *ir_gen_array_access(IrBuilderSrc *irb, Scope *scope, AstNode *
59105912 if (array_ref_instruction == irb->codegen->invalid_inst_src)
59115913 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
59135921 AstNode *subscript_node = node->data.array_access_expr.subscript;
5914 IrInstSrc *subscript_instruction = ir_gen_node(irb, subscript_node, scope);
5915 if (subscript_instruction == irb->codegen->invalid_inst_src)
5916 return subscript_instruction;
5922 IrInstSrc *subscript_value = ir_gen_node_extra(irb, subscript_node, scope, LValNone, &result_loc_cast->base);
5923 if (subscript_value == irb->codegen->invalid_inst_src)
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
59185928 IrInstSrc *ptr_instruction = ir_build_elem_ptr(irb, scope, node, array_ref_instruction,
59195929 subscript_instruction, true, PtrLenSingle, nullptr);
......@@ -7266,6 +7276,18 @@ static IrInstSrc *ir_gen_builtin_fn_call(IrBuilderSrc *irb, Scope *scope, AstNod
72667276 zig_unreachable();
72677277}
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
72697291static IrInstSrc *ir_gen_fn_call(IrBuilderSrc *irb, Scope *scope, AstNode *node, LVal lval,
72707292 ResultLoc *result_loc)
72717293{
......@@ -7274,8 +7296,19 @@ static IrInstSrc *ir_gen_fn_call(IrBuilderSrc *irb, Scope *scope, AstNode *node,
72747296 if (node->data.fn_call_expr.modifier == CallModifierBuiltin)
72757297 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
72777310 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,
72797312 nullptr, node->data.fn_call_expr.params.items, node->data.fn_call_expr.params.length, lval, result_loc);
72807313}
72817314
......@@ -8981,7 +9014,7 @@ static IrInstSrc *ir_gen_switch_expr(IrBuilderSrc *irb, Scope *scope, AstNode *n
89819014 return irb->codegen->invalid_inst_src;
89829015 }
89839016 else_prong = prong_node;
8984 } else if (prong_item_count == 1 &&
9017 } else if (prong_item_count == 1 &&
89859018 prong_node->data.switch_prong.items.at(0)->type == NodeTypeSymbol &&
89869019 buf_eql_str(prong_node->data.switch_prong.items.at(0)->data.symbol_expr.symbol, "_")) {
89879020 if (underscore_prong) {
......@@ -9129,6 +9162,14 @@ static IrInstSrc *ir_gen_comptime(IrBuilderSrc *irb, Scope *parent_scope, AstNod
91299162 return ir_gen_node_extra(irb, node->data.comptime_expr.expr, child_scope, lval, nullptr);
91309163}
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
91329173static IrInstSrc *ir_gen_return_from_block(IrBuilderSrc *irb, Scope *break_scope, AstNode *node, ScopeBlock *block_scope) {
91339174 IrInstSrc *is_comptime;
91349175 if (ir_should_inline(irb->exec, break_scope)) {
......@@ -9709,6 +9750,10 @@ static IrInstSrc *ir_gen_fn_proto(IrBuilderSrc *irb, Scope *parent_scope, AstNod
97099750
97109751static IrInstSrc *ir_gen_resume(IrBuilderSrc *irb, Scope *scope, AstNode *node) {
97119752 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
97139758 IrInstSrc *target_inst = ir_gen_node_extra(irb, node->data.resume_expr.expr, scope, LValPtr, nullptr);
97149759 if (target_inst == irb->codegen->invalid_inst_src)
......@@ -9722,7 +9767,7 @@ static IrInstSrc *ir_gen_await_expr(IrBuilderSrc *irb, Scope *scope, AstNode *no
97229767{
97239768 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
97279772 AstNode *expr_node = node->data.await_expr.expr;
97289773 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
97689813 add_node_error(irb->codegen, node, buf_sprintf("suspend outside function definition"));
97699814 return irb->codegen->invalid_inst_src;
97709815 }
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
97719821 ScopeSuspend *existing_suspend_scope = get_scope_suspend(parent_scope);
97729822 if (existing_suspend_scope) {
97739823 if (!existing_suspend_scope->reported_err) {
......@@ -9897,6 +9947,8 @@ static IrInstSrc *ir_gen_node_raw(IrBuilderSrc *irb, AstNode *node, Scope *scope
98979947 return ir_gen_switch_expr(irb, scope, node, lval, result_loc);
98989948 case NodeTypeCompTime:
98999949 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);
99009952 case NodeTypeErrorType:
99019953 return ir_lval_wrap(irb, scope, ir_gen_error_type(irb, scope, node), lval, result_loc);
99029954 case NodeTypeBreak:
......@@ -15393,23 +15445,6 @@ static bool resolve_cmp_op_id(IrBinOp op_id, Cmp cmp) {
1539315445 }
1539415446}
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
1541315448static void set_optional_value_to_null(ZigValue *val) {
1541415449 assert(val->special == ConstValSpecialStatic);
1541515450 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
1552415559 switch (val->data.x_lazy->id) {
1552515560 case LazyValueIdInvalid:
1552615561 zig_unreachable();
15527 case LazyValueIdAlignOf:
15528 *result = CmpGT;
15562 case LazyValueIdAlignOf: {
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;
1552915574 return ErrorNone;
15575 }
1553015576 case LazyValueIdSizeOf: {
1553115577 LazyValueSizeOf *lazy_size_of = reinterpret_cast<LazyValueSizeOf *>(val->data.x_lazy);
1553215578 IrAnalyze *ira = lazy_size_of->ira;
......@@ -16556,49 +16602,69 @@ static IrInstGen *ir_analyze_bit_shift(IrAnalyze *ira, IrInstSrcBinOp *bin_op_in
1655616602 IrInstGen *casted_op2;
1655716603 IrBinOp op_id = bin_op_instruction->op_id;
1655816604 if (op1->value->type->id == ZigTypeIdComptimeInt) {
16605 // comptime_int has no finite bit width
1655916606 casted_op2 = op2;
1656016607
1656116608 if (op_id == IrBinOpBitShiftLeftLossy) {
1656216609 op_id = IrBinOpBitShiftLeftExact;
1656316610 }
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) {
1656616623 Buf *val_buf = buf_alloc();
16567 bigint_append_buf(val_buf, &casted_op2->value->data.x_bigint, 10);
16568 ir_add_error(ira, &casted_op2->base, buf_sprintf("shift by negative value %s", buf_ptr(val_buf)));
16624 bigint_append_buf(val_buf, &op2_val->data.x_bigint, 10);
16625 ir_add_error(ira, &casted_op2->base,
16626 buf_sprintf("shift by negative value %s", buf_ptr(val_buf)));
1656916627 return ira->codegen->invalid_inst_gen;
1657016628 }
1657116629 } else {
16630 const unsigned bit_count = op1->value->type->data.integral.bit_count;
1657216631 ZigType *shift_amt_type = get_smallest_unsigned_int_type(ira->codegen,
16573 op1->value->type->data.integral.bit_count - 1);
16574 if (bin_op_instruction->op_id == IrBinOpBitShiftLeftLossy &&
16575 op2->value->type->id == ZigTypeIdComptimeInt) {
16632 bit_count > 0 ? bit_count - 1 : 0);
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);
1657816641 if (op2_val == nullptr)
1657916642 return ira->codegen->invalid_inst_gen;
16580 if (!bigint_fits_in_bits(&op2_val->data.x_bigint,
16581 shift_amt_type->data.integral.bit_count,
16582 op2_val->data.x_bigint.is_negative)) {
16583 Buf *val_buf = buf_alloc();
16584 bigint_append_buf(val_buf, &op2_val->data.x_bigint, 10);
16643
16644 BigInt bit_count_value = {0};
16645 bigint_init_unsigned(&bit_count_value, bit_count);
16646
16647 if (bigint_cmp(&op2_val->data.x_bigint, &bit_count_value) != CmpLT) {
1658516648 ErrorMsg* msg = ir_add_error(ira,
1658616649 &bin_op_instruction->base.base,
1658716650 buf_sprintf("RHS of shift is too large for LHS type"));
16588 add_error_note(
16589 ira->codegen,
16590 msg,
16591 op2->base.source_node,
16592 buf_sprintf("value %s cannot fit into type %s",
16593 buf_ptr(val_buf),
16594 buf_ptr(&shift_amt_type->name)));
16651 add_error_note(ira->codegen, msg, op1->base.source_node,
16652 buf_sprintf("type %s has only %u bits",
16653 buf_ptr(&op1->value->type->name), bit_count));
16654
1659516655 return ira->codegen->invalid_inst_gen;
1659616656 }
1659716657 }
16658 }
1659816659
16599 casted_op2 = ir_implicit_cast(ira, op2, shift_amt_type);
16600 if (type_is_invalid(casted_op2->value->type))
16660 // Fast path for zero RHS
16661 if (instr_is_comptime(casted_op2)) {
16662 ZigValue *op2_val = ir_resolve_const(ira, casted_op2, UndefBad);
16663 if (op2_val == nullptr)
1660116664 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);
1660216668 }
1660316669
1660416670 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
1661116677 return ira->codegen->invalid_inst_gen;
1661216678
1661316679 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);
1662016680 }
1662116681
1662216682 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
1749817558
1749917559 ZigValue *init_val = nullptr;
1750017560 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
1750217569 if (is_comptime_var) {
1750317570 if (var->gen_is_const) {
1750417571 var->const_value = init_val;
......@@ -19306,6 +19373,19 @@ static IrInstGen *ir_analyze_fn_call(IrAnalyze *ira, IrInst* source_instr,
1930619373 ZigType *specified_return_type = ir_analyze_type_expr(ira, impl_fn->child_scope, return_type_node);
1930719374 if (type_is_invalid(specified_return_type))
1930819375 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
1930919389 if (fn_proto_node->data.fn_proto.auto_err_set) {
1931019390 ZigType *inferred_err_set_type = get_auto_err_set_type(ira->codegen, impl_fn);
1931119391 if ((err = type_resolve(ira->codegen, specified_return_type, ResolveStatusSizeKnown)))
......@@ -25095,12 +25175,50 @@ static IrInstGen *ir_analyze_instruction_cmpxchg(IrAnalyze *ira, IrInstSrcCmpxch
2509525175 return ira->codegen->invalid_inst_gen;
2509625176 }
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
2509825193 if (instr_is_comptime(casted_ptr) && casted_ptr->value->data.x_ptr.mut != ConstPtrMutRuntimeVar &&
2509925194 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;
2510125220 }
2510225221
25103 ZigType *result_type = get_optional_type(ira->codegen, operand_type);
2510425222 IrInstGen *result_loc;
2510525223 if (handle_is_ptr(ira->codegen, result_type)) {
2510625224 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
2603526153 if (array_type->data.pointer.ptr_len == PtrLenC) {
2603626154 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.
2603926157 // However, we want to be able to slice them without generating an allowzero slice (see issue #4401).
2604026158 // To achieve this, we generate a runtime safety check and make the slice type non-allowzero.
2604126159 if (array_type->data.pointer.allow_zero) {
......@@ -26330,7 +26448,7 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
2633026448
2633126449 if (type_is_invalid(ptr_val->value->type))
2633226450 return ira->codegen->invalid_inst_gen;
26333
26451
2633426452 ir_build_assert_non_null(ira, &instruction->base.base, ptr_val);
2633526453 }
2633626454
......@@ -28211,43 +28329,20 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op) {
2821128329 if (type_is_invalid(operand_type))
2821228330 return ira->codegen->builtin_types.entry_invalid;
2821328331
28214 if (operand_type->id == ZigTypeIdInt) {
28215 if (operand_type->data.integral.bit_count < 8) {
28216 ir_add_error(ira, &op->base,
28217 buf_sprintf("expected integer type 8 bits or larger, found %" PRIu32 "-bit integer type",
28218 operand_type->data.integral.bit_count));
28219 return ira->codegen->builtin_types.entry_invalid;
28332 if (operand_type->id == ZigTypeIdInt || operand_type->id == ZigTypeIdEnum) {
28333 ZigType *int_type;
28334 if (operand_type->id == ZigTypeIdEnum) {
28335 int_type = operand_type->data.enumeration.tag_int_type;
28336 } else {
28337 int_type = operand_type;
2822028338 }
28339 auto bit_count = int_type->data.integral.bit_count;
2822128340 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) {
2822328343 ir_add_error(ira, &op->base,
2822428344 buf_sprintf("expected %" PRIu32 "-bit integer type or smaller, found %" PRIu32 "-bit integer type",
28225 max_atomic_bits, operand_type->data.integral.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));
28345 max_atomic_bits, bit_count));
2825128346 return ira->codegen->builtin_types.entry_invalid;
2825228347 }
2825328348 } else if (operand_type->id == ZigTypeIdFloat) {
......@@ -28258,6 +28353,8 @@ static ZigType *ir_resolve_atomic_operand_type(IrAnalyze *ira, IrInstGen *op) {
2825828353 max_atomic_bits, (uint32_t) operand_type->data.floating.bit_count));
2825928354 return ira->codegen->builtin_types.entry_invalid;
2826028355 }
28356 } else if (operand_type->id == ZigTypeIdBool) {
28357 // will be treated as u8
2826128358 } else {
2826228359 Error err;
2826328360 ZigType *operand_ptr_type;
......@@ -28296,11 +28393,15 @@ static IrInstGen *ir_analyze_instruction_atomic_rmw(IrAnalyze *ira, IrInstSrcAto
2829628393
2829728394 if (operand_type->id == ZigTypeIdEnum && op != AtomicRmwOp_xchg) {
2829828395 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"));
2830028401 return ira->codegen->invalid_inst_gen;
2830128402 } else if (operand_type->id == ZigTypeIdFloat && op > AtomicRmwOp_sub) {
2830228403 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"));
2830428405 return ira->codegen->invalid_inst_gen;
2830528406 }
2830628407
......@@ -28321,14 +28422,103 @@ static IrInstGen *ir_analyze_instruction_atomic_rmw(IrAnalyze *ira, IrInstSrcAto
2832128422 return ira->codegen->invalid_inst_gen;
2832228423 }
2832328424
28324 if (instr_is_comptime(casted_operand) && instr_is_comptime(casted_ptr) && casted_ptr->value->data.x_ptr.mut == ConstPtrMutComptimeVar)
28325 {
28326 ir_add_error(ira, &instruction->base.base,
28327 buf_sprintf("compiler bug: TODO compile-time execution of @atomicRmw"));
28328 return ira->codegen->invalid_inst_gen;
28425 // special case zero bit types
28426 switch (type_has_one_possible_value(ira->codegen, operand_type)) {
28427 case OnePossibleValueInvalid:
28428 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;
2832928433 }
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,
2833228522 ordering, operand_type);
2833328523}
2833428524
......@@ -28400,6 +28590,16 @@ static IrInstGen *ir_analyze_instruction_atomic_store(IrAnalyze *ira, IrInstSrcA
2840028590 return ira->codegen->invalid_inst_gen;
2840128591 }
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
2840328603 if (instr_is_comptime(casted_value) && instr_is_comptime(casted_ptr)) {
2840428604 IrInstGen *result = ir_analyze_store_ptr(ira, &instruction->base.base, casted_ptr, value, false);
2840528605 result->value->type = ira->codegen->builtin_types.entry_void;
......@@ -30213,7 +30413,7 @@ static Error ir_resolve_lazy_raw(AstNode *source_node, ZigValue *val) {
3021330413 return ErrorSemanticAnalyzeFail;
3021430414 } else if (elem_type->id == ZigTypeIdOpaque) {
3021530415 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"));
3021730417 return ErrorSemanticAnalyzeFail;
3021830418 } else if (lazy_ptr_type->is_allowzero) {
3021930419 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) {
983983 return false;
984984}
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
9861014static const char *build_musl(CodeGen *parent, Stage2ProgressNode *progress_node) {
9871015 CodeGen *child_gen = create_child_codegen(parent, nullptr, OutTypeLib, nullptr, "c", progress_node);
9881016
9891017 // When there is a src/<arch>/foo.* then it should substitute for src/foo.*
9901018 // Even a .s file can substitute for a .c file.
9911019
992 enum MuslSrc {
993 MuslSrcAsm,
994 MuslSrcNormal,
995 MuslSrcO3,
996 };
997
9981020 const char *target_musl_arch_name = target_arch_musl_name(parent->zig_target->arch);
9991021
10001022 HashMap<Buf *, MuslSrc, buf_hash, buf_eql_buf> source_table = {};
1001 source_table.init(1800);
1023 source_table.init(2000);
10021024
10031025 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]);
1005
1006 MuslSrc src_kind;
1007 if (buf_ends_with_str(src_file, ".c")) {
1008 assert(buf_starts_with_str(src_file, "musl/src/"));
1009 bool want_O3 = buf_starts_with_str(src_file, "musl/src/malloc/") ||
1010 buf_starts_with_str(src_file, "musl/src/string/") ||
1011 buf_starts_with_str(src_file, "musl/src/internal/");
1012 src_kind = want_O3 ? MuslSrcO3 : MuslSrcNormal;
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);
1026 add_musl_src_file(source_table, ZIG_MUSL_SRC_FILES[i]);
1027 }
1028
1029 static const char *time32_compat_arch_list[] = {"arm", "i386", "mips", "powerpc"};
1030 for (size_t arch_i = 0; arch_i < array_length(time32_compat_arch_list); arch_i += 1) {
1031 if (strcmp(target_musl_arch_name, time32_compat_arch_list[arch_i]) == 0) {
1032 for (size_t i = 0; i < array_length(ZIG_MUSL_COMPAT_TIME32_FILES); i += 1) {
1033 add_musl_src_file(source_table, ZIG_MUSL_COMPAT_TIME32_FILES[i]);
1034 }
10201035 }
1021 source_table.put_unique(src_file, src_kind);
10221036 }
10231037
1038
10241039 ZigList<CFile *> c_source_files = {0};
10251040
10261041 Buf dirname = BUF_INIT;
src/main.cpp+1-1
......@@ -1392,7 +1392,7 @@ static int main0(int argc, char **argv) {
13921392 return main_exit(root_progress_node, EXIT_SUCCESS);
13931393 }
13941394 case CmdTargets:
1395 return stage2_cmd_targets(buf_ptr(&zig_triple_buf));
1395 return stage2_cmd_targets(target_string, mcpu, dynamic_linker);
13961396 case CmdNone:
13971397 return print_full_usage(arg0, stderr, EXIT_FAILURE);
13981398 }
src/parser.cpp+34-11
......@@ -876,6 +876,7 @@ static AstNode *ast_parse_container_field(ParseContext *pc) {
876876// Statement
877877// <- KEYWORD_comptime? VarDecl
878878// / KEYWORD_comptime BlockExprStatement
879// / KEYWORD_noasync BlockExprStatement
879880// / KEYWORD_suspend (SEMICOLON / BlockExprStatement)
880881// / KEYWORD_defer BlockExprStatement
881882// / KEYWORD_errdefer BlockExprStatement
......@@ -899,6 +900,14 @@ static AstNode *ast_parse_statement(ParseContext *pc) {
899900 return res;
900901 }
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
902911 Token *suspend = eat_token_if(pc, TokenIdKeywordSuspend);
903912 if (suspend != nullptr) {
904913 AstNode *statement = nullptr;
......@@ -1237,6 +1246,7 @@ static AstNode *ast_parse_prefix_expr(ParseContext *pc) {
12371246// / IfExpr
12381247// / KEYWORD_break BreakLabel? Expr?
12391248// / KEYWORD_comptime Expr
1249// / KEYWORD_noasync Expr
12401250// / KEYWORD_continue BreakLabel?
12411251// / KEYWORD_resume Expr
12421252// / KEYWORD_return Expr?
......@@ -1271,6 +1281,14 @@ static AstNode *ast_parse_primary_expr(ParseContext *pc) {
12711281 return res;
12721282 }
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
12741292 Token *continue_token = eat_token_if(pc, TokenIdKeywordContinue);
12751293 if (continue_token != nullptr) {
12761294 Token *label = ast_parse_break_label(pc);
......@@ -1459,13 +1477,11 @@ static AstNode *ast_parse_error_union_expr(ParseContext *pc) {
14591477
14601478// SuffixExpr
14611479// <- KEYWORD_async PrimaryTypeExpr SuffixOp* FnCallArguments
1462// / KEYWORD_noasync PrimaryTypeExpr SuffixOp* FnCallArguments
14631480// / PrimaryTypeExpr (SuffixOp / FnCallArguments)*
14641481static AstNode *ast_parse_suffix_expr(ParseContext *pc) {
1465 Token *async_token = eat_token(pc);
1466 bool is_async = async_token->id == TokenIdKeywordAsync;
1467 if (is_async || async_token->id == TokenIdKeywordNoAsync) {
1468 if (is_async && eat_token_if(pc, TokenIdKeywordFn) != nullptr) {
1482 Token *async_token = eat_token_if(pc, TokenIdKeywordAsync);
1483 if (async_token) {
1484 if (eat_token_if(pc, TokenIdKeywordFn) != nullptr) {
14691485 // HACK: If we see the keyword `fn`, then we assume that
14701486 // we are parsing an async fn proto, and not a call.
14711487 // We therefore put back all tokens consumed by the async
......@@ -1515,13 +1531,12 @@ static AstNode *ast_parse_suffix_expr(ParseContext *pc) {
15151531 assert(args->type == NodeTypeFnCallExpr);
15161532
15171533 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;
15191535 res->data.fn_call_expr.seen = false;
15201536 res->data.fn_call_expr.fn_ref_expr = child;
15211537 res->data.fn_call_expr.params = args->data.fn_call_expr.params;
15221538 return res;
15231539 }
1524 put_back_token(pc);
15251540
15261541 AstNode *res = ast_parse_primary_type_expr(pc);
15271542 if (res == nullptr)
......@@ -1582,6 +1597,7 @@ static AstNode *ast_parse_suffix_expr(ParseContext *pc) {
15821597// / IfTypeExpr
15831598// / INTEGER
15841599// / KEYWORD_comptime TypeExpr
1600// / KEYWORD_noasync TypeExpr
15851601// / KEYWORD_error DOT IDENTIFIER
15861602// / KEYWORD_false
15871603// / KEYWORD_null
......@@ -1683,6 +1699,14 @@ static AstNode *ast_parse_primary_type_expr(ParseContext *pc) {
16831699 return res;
16841700 }
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
16861710 Token *error = eat_token_if(pc, TokenIdKeywordError);
16871711 if (error != nullptr) {
16881712 Token *dot = expect_token(pc, TokenIdDot);
......@@ -2599,14 +2623,10 @@ static AstNode *ast_parse_prefix_op(ParseContext *pc) {
25992623 return res;
26002624 }
26012625
2602 Token *noasync_token = eat_token_if(pc, TokenIdKeywordNoAsync);
26032626 Token *await = eat_token_if(pc, TokenIdKeywordAwait);
26042627 if (await != nullptr) {
26052628 AstNode *res = ast_create_node(pc, NodeTypeAwaitExpr, await);
2606 res->data.await_expr.noasync_token = noasync_token;
26072629 return res;
2608 } else if (noasync_token != nullptr) {
2609 put_back_token(pc);
26102630 }
26112631
26122632 return nullptr;
......@@ -3125,6 +3145,9 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
31253145 case NodeTypeCompTime:
31263146 visit_field(&node->data.comptime_expr.expr, visit, context);
31273147 break;
3148 case NodeTypeNoAsync:
3149 visit_field(&node->data.comptime_expr.expr, visit, context);
3150 break;
31283151 case NodeTypeBreak:
31293152 // none
31303153 break;
src/stage2.cpp+4-3
......@@ -251,13 +251,16 @@ Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, cons
251251 target->cache_hash = "\n\n";
252252 }
253253
254 target->cache_hash_len = strlen(target->cache_hash);
255
254256 if (dynamic_linker != nullptr) {
255257 target->dynamic_linker = dynamic_linker;
256258 }
259
257260 return ErrorNone;
258261}
259262
260int stage2_cmd_targets(const char *zig_triple) {
263int stage2_cmd_targets(const char *zig_triple, const char *mcpu, const char *dynamic_linker) {
261264 const char *msg = "stage0 called stage2_cmd_targets";
262265 stage2_panic(msg, strlen(msg));
263266}
......@@ -269,8 +272,6 @@ enum Error stage2_libc_parse(struct Stage2LibCInstallation *libc, const char *li
269272 libc->sys_include_dir_len = strlen(libc->sys_include_dir);
270273 libc->crt_dir = "";
271274 libc->crt_dir_len = strlen(libc->crt_dir);
272 libc->static_crt_dir = "";
273 libc->static_crt_dir_len = strlen(libc->static_crt_dir);
274275 libc->msvc_lib_dir = "";
275276 libc->msvc_lib_dir_len = strlen(libc->msvc_lib_dir);
276277 libc->kernel32_lib_dir = "";
src/stage2.h+4-5
......@@ -201,9 +201,6 @@ ZIG_EXTERN_C void stage2_progress_complete_one(Stage2ProgressNode *node);
201201ZIG_EXTERN_C void stage2_progress_update_node(Stage2ProgressNode *node,
202202 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
207204// ABI warning
208205struct Stage2LibCInstallation {
209206 const char *include_dir;
......@@ -212,8 +209,6 @@ struct Stage2LibCInstallation {
212209 size_t sys_include_dir_len;
213210 const char *crt_dir;
214211 size_t crt_dir_len;
215 const char *static_crt_dir;
216 size_t static_crt_dir_len;
217212 const char *msvc_lib_dir;
218213 size_t msvc_lib_dir_len;
219214 const char *kernel32_lib_dir;
......@@ -293,6 +288,7 @@ struct ZigTarget {
293288 const char *llvm_cpu_features;
294289 const char *cpu_builtin_str;
295290 const char *cache_hash;
291 size_t cache_hash_len;
296292 const char *os_builtin_str;
297293 const char *dynamic_linker;
298294};
......@@ -301,6 +297,9 @@ struct ZigTarget {
301297ZIG_EXTERN_C enum Error stage2_target_parse(struct ZigTarget *target, const char *zig_triple, const char *mcpu,
302298 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
305304// ABI warning
306305struct Stage2NativePaths {
src/zig_clang.cpp+30
......@@ -1662,6 +1662,16 @@ unsigned ZigClangVarDecl_getAlignedAttribute(const struct ZigClangVarDecl *self,
16621662 return 0;
16631663}
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
16651675unsigned ZigClangFunctionDecl_getAlignedAttribute(const struct ZigClangFunctionDecl *self, const ZigClangASTContext* ctx) {
16661676 auto casted_self = reinterpret_cast<const clang::FunctionDecl *>(self);
16671677 auto casted_ctx = const_cast<clang::ASTContext *>(reinterpret_cast<const clang::ASTContext *>(ctx));
......@@ -1928,6 +1938,26 @@ bool ZigClangType_isRecordType(const ZigClangType *self) {
19281938 return casted->isRecordType();
19291939}
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
19311961bool ZigClangType_isConstantArrayType(const ZigClangType *self) {
19321962 auto casted = reinterpret_cast<const clang::Type *>(self);
19331963 return casted->isConstantArrayType();
src/zig_clang.h+2
......@@ -887,6 +887,7 @@ ZIG_EXTERN_C const struct ZigClangVarDecl *ZigClangVarDecl_getCanonicalDecl(cons
887887ZIG_EXTERN_C const char* ZigClangVarDecl_getSectionAttribute(const struct ZigClangVarDecl *self, size_t *len);
888888ZIG_EXTERN_C unsigned ZigClangVarDecl_getAlignedAttribute(const struct ZigClangVarDecl *self, const ZigClangASTContext* ctx);
889889ZIG_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
891892ZIG_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);
969970ZIG_EXTERN_C bool ZigClangType_isVoidType(const struct ZigClangType *self);
970971ZIG_EXTERN_C bool ZigClangType_isArrayType(const struct ZigClangType *self);
971972ZIG_EXTERN_C bool ZigClangType_isRecordType(const struct ZigClangType *self);
973ZIG_EXTERN_C bool ZigClangType_isIncompleteOrZeroLengthArrayType(const ZigClangQualType *self, const struct ZigClangASTContext *ctx);
972974ZIG_EXTERN_C bool ZigClangType_isConstantArrayType(const ZigClangType *self);
973975ZIG_EXTERN_C const char *ZigClangType_getTypeClassName(const struct ZigClangType *self);
974976ZIG_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 {
2222 \\
2323 \\pub fn main() void {
2424 \\ privateFunction();
25 \\ const stdout = &getStdOut().outStream().stream;
25 \\ const stdout = getStdOut().outStream();
2626 \\ stdout.print("OK 2\n", .{}) catch unreachable;
2727 \\}
2828 \\
......@@ -37,7 +37,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
3737 \\// purposefully conflicting function with main.zig
3838 \\// but it's private so it should be OK
3939 \\fn privateFunction() void {
40 \\ const stdout = &getStdOut().outStream().stream;
40 \\ const stdout = getStdOut().outStream();
4141 \\ stdout.print("OK 1\n", .{}) catch unreachable;
4242 \\}
4343 \\
......@@ -63,7 +63,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
6363 tc.addSourceFile("foo.zig",
6464 \\usingnamespace @import("std").io;
6565 \\pub fn foo_function() void {
66 \\ const stdout = &getStdOut().outStream().stream;
66 \\ const stdout = getStdOut().outStream();
6767 \\ stdout.print("OK\n", .{}) catch unreachable;
6868 \\}
6969 );
......@@ -74,7 +74,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
7474 \\
7575 \\pub fn bar_function() void {
7676 \\ if (foo_function()) {
77 \\ const stdout = &getStdOut().outStream().stream;
77 \\ const stdout = getStdOut().outStream();
7878 \\ stdout.print("OK\n", .{}) catch unreachable;
7979 \\ }
8080 \\}
......@@ -106,7 +106,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
106106 \\pub const a_text = "OK\n";
107107 \\
108108 \\pub fn ok() void {
109 \\ const stdout = &io.getStdOut().outStream().stream;
109 \\ const stdout = io.getStdOut().outStream();
110110 \\ stdout.print(b_text, .{}) catch unreachable;
111111 \\}
112112 );
......@@ -124,7 +124,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
124124 \\const io = @import("std").io;
125125 \\
126126 \\pub fn main() void {
127 \\ const stdout = &io.getStdOut().outStream().stream;
127 \\ const stdout = io.getStdOut().outStream();
128128 \\ stdout.print("Hello, world!\n{d:4} {x:3} {c}\n", .{@as(u32, 12), @as(u16, 0x12), @as(u8, 'a')}) catch unreachable;
129129 \\}
130130 , "Hello, world!\n 12 12 a\n");
......@@ -267,7 +267,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
267267 \\ var x_local : i32 = print_ok(x);
268268 \\}
269269 \\fn print_ok(val: @TypeOf(x)) @TypeOf(foo) {
270 \\ const stdout = &io.getStdOut().outStream().stream;
270 \\ const stdout = io.getStdOut().outStream();
271271 \\ stdout.print("OK\n", .{}) catch unreachable;
272272 \\ return 0;
273273 \\}
......@@ -349,7 +349,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
349349 \\pub fn main() void {
350350 \\ const bar = Bar {.field2 = 13,};
351351 \\ const foo = Foo {.field1 = bar,};
352 \\ const stdout = &io.getStdOut().outStream().stream;
352 \\ const stdout = io.getStdOut().outStream();
353353 \\ if (!foo.method()) {
354354 \\ stdout.print("BAD\n", .{}) catch unreachable;
355355 \\ }
......@@ -363,7 +363,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
363363 cases.add("defer with only fallthrough",
364364 \\const io = @import("std").io;
365365 \\pub fn main() void {
366 \\ const stdout = &io.getStdOut().outStream().stream;
366 \\ const stdout = io.getStdOut().outStream();
367367 \\ stdout.print("before\n", .{}) catch unreachable;
368368 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
369369 \\ defer stdout.print("defer2\n", .{}) catch unreachable;
......@@ -376,7 +376,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
376376 \\const io = @import("std").io;
377377 \\const os = @import("std").os;
378378 \\pub fn main() void {
379 \\ const stdout = &io.getStdOut().outStream().stream;
379 \\ const stdout = io.getStdOut().outStream();
380380 \\ stdout.print("before\n", .{}) catch unreachable;
381381 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
382382 \\ defer stdout.print("defer2\n", .{}) catch unreachable;
......@@ -393,7 +393,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
393393 \\ do_test() catch return;
394394 \\}
395395 \\fn do_test() !void {
396 \\ const stdout = &io.getStdOut().outStream().stream;
396 \\ const stdout = io.getStdOut().outStream();
397397 \\ stdout.print("before\n", .{}) catch unreachable;
398398 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
399399 \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;
......@@ -412,7 +412,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
412412 \\ do_test() catch return;
413413 \\}
414414 \\fn do_test() !void {
415 \\ const stdout = &io.getStdOut().outStream().stream;
415 \\ const stdout = io.getStdOut().outStream();
416416 \\ stdout.print("before\n", .{}) catch unreachable;
417417 \\ defer stdout.print("defer1\n", .{}) catch unreachable;
418418 \\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;
......@@ -429,7 +429,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
429429 \\const io = @import("std").io;
430430 \\
431431 \\pub fn main() void {
432 \\ const stdout = &io.getStdOut().outStream().stream;
432 \\ const stdout = io.getStdOut().outStream();
433433 \\ stdout.print(foo_txt, .{}) catch unreachable;
434434 \\}
435435 , "1234\nabcd\n");
......@@ -448,9 +448,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
448448 \\
449449 \\pub fn main() !void {
450450 \\ var args_it = std.process.args();
451 \\ var stdout_file = io.getStdOut();
452 \\ var stdout_adapter = stdout_file.outStream();
453 \\ const stdout = &stdout_adapter.stream;
451 \\ const stdout = io.getStdOut().outStream();
454452 \\ var index: usize = 0;
455453 \\ _ = args_it.skip();
456454 \\ while (args_it.next(allocator)) |arg_or_err| : (index += 1) {
......@@ -489,9 +487,7 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
489487 \\
490488 \\pub fn main() !void {
491489 \\ var args_it = std.process.args();
492 \\ var stdout_file = io.getStdOut();
493 \\ var stdout_adapter = stdout_file.outStream();
494 \\ const stdout = &stdout_adapter.stream;
490 \\ const stdout = io.getStdOut().outStream();
495491 \\ var index: usize = 0;
496492 \\ _ = args_it.skip();
497493 \\ 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");
22const std = @import("std");
33
44pub 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
561 cases.addTest("@TypeOf with no arguments",
662 \\export fn entry() void {
763 \\ _ = @TypeOf();
......@@ -310,7 +366,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
310366 \\ _ = @atomicRmw(f32, &x, .And, 2, .SeqCst);
311367 \\}
312368 , &[_][]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",
314370 });
315371
316372 cases.add("intToPtr with misaligned address",
......@@ -527,7 +583,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
527583 \\ _ = @atomicRmw(E, &x, .Add, .b, .SeqCst);
528584 \\}
529585 , &[_][]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",
531587 });
532588
533589 cases.add("disallow coercion from non-null-terminated pointer to null-terminated pointer",
......@@ -1592,7 +1648,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
15921648 \\ var y: [*c]c_void = x;
15931649 \\}
15941650 , &[_][]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",
15961652 });
15971653
15981654 cases.add("directly embedding opaque type in struct and union",
......@@ -1610,9 +1666,14 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
16101666 \\export fn b() void {
16111667 \\ var bar: Bar = undefined;
16121668 \\}
1669 \\export fn c() void {
1670 \\ var baz: *@OpaqueType() = undefined;
1671 \\ const qux = .{baz.*};
1672 \\}
16131673 , &[_][]const u8{
1614 "tmp.zig:3:8: 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",
1674 "tmp.zig:3:5: error: opaque types have unknown size and therefore cannot be directly embedded in structs",
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",
16161677 });
16171678
16181679 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 {
36053666 cases.add("array access of non array",
36063667 \\export fn f() void {
36073668 \\ var bad : bool = undefined;
3608 \\ bad[bad] = bad[bad];
3669 \\ bad[0] = bad[0];
36093670 \\}
36103671 \\export fn g() void {
36113672 \\ var bad : bool = undefined;
3612 \\ _ = bad[bad];
3673 \\ _ = bad[0];
36133674 \\}
36143675 , &[_][]const u8{
36153676 "tmp.zig:3:8: error: array access of non-array type 'bool'",
......@@ -4009,8 +4070,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
40094070 \\}
40104071 \\export fn entry() u16 { return f(); }
40114072 , &[_][]const u8{
4012 "tmp.zig:3:14: error: RHS of shift is too large for LHS type",
4013 "tmp.zig:3:17: note: value 8 cannot fit into type u3",
4073 "tmp.zig:3:17: error: integer value 8 cannot be coerced to type 'u3'",
40144074 });
40154075
40164076 cases.add("missing function call param",
......@@ -6538,9 +6598,41 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
65386598 \\export fn bar() !FooType {
65396599 \\ return error.InvalidValue;
65406600 \\}
6601 \\export fn bav() !@TypeOf(null) {
6602 \\ return error.InvalidValue;
6603 \\}
6604 \\export fn baz() !@TypeOf(undefined) {
6605 \\ return error.InvalidValue;
6606 \\}
65416607 , &[_][]const u8{
6542 "tmp.zig:2:18: error: opaque return type 'FooType' not allowed",
6543 "tmp.zig:1:1: note: declared here",
6608 "tmp.zig:2:18: error: Opaque return type 'FooType' not allowed",
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",
65446636 });
65456637
65466638 cases.add( // fixed bug #2032
test/run_translated_c.zig-18
......@@ -195,22 +195,4 @@ pub fn addCases(cases: *tests.RunTranslatedCContext) void {
195195 \\ return 0;
196196 \\}
197197 , "");
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");
216198}
test/runtime_safety.zig+30
......@@ -1,6 +1,36 @@
11const tests = @import("tests.zig");
22
33pub 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
434 cases.addRuntimeSafety("slice sentinel mismatch - optional pointers",
535 \\const std = @import("std");
636 \\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" {
1515 comptime expect(@alignOf(Foo) == 4);
1616 }
1717}
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 @@
11const std = @import("std");
2const expect = std.testing.expect;
2const testing = std.testing;
33const mem = std.mem;
4const expect = testing.expect;
5const expectEqual = testing.expectEqual;
46
57test "arrays" {
68 var array: [5]u32 = undefined;
......@@ -360,3 +362,17 @@ test "access the null element of a null terminated array" {
360362 S.doTheTest();
361363 comptime S.doTheTest();
362364}
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" {
15311531 S.doTheTest();
15321532 expect(S.finished);
15331533}
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");
22const expect = std.testing.expect;
33const expectEqual = std.testing.expectEqual;
44const builtin = @import("builtin");
5const AtomicRmwOp = builtin.AtomicRmwOp;
6const AtomicOrder = builtin.AtomicOrder;
75
86test "cmpxchg" {
7 testCmpxchg();
8 comptime testCmpxchg();
9}
10
11fn testCmpxchg() void {
912 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| {
1114 expect(x1 == 1234);
1215 } else {
1316 @panic("cmpxchg should have failed");
1417 }
1518
16 while (@cmpxchgWeak(i32, &x, 1234, 5678, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
19 while (@cmpxchgWeak(i32, &x, 1234, 5678, .SeqCst, .SeqCst)) |x1| {
1720 expect(x1 == 1234);
1821 }
1922 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);
2225 expect(x == 42);
2326}
2427
2528test "fence" {
2629 var x: i32 = 1234;
27 @fence(AtomicOrder.SeqCst);
30 @fence(.SeqCst);
2831 x = 5678;
2932}
3033
......@@ -36,18 +39,18 @@ test "atomicrmw and atomicload" {
3639}
3740
3841fn 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);
4043 expect(prev_value == 200);
4144 comptime {
4245 var x: i32 = 1234;
4346 const y: i32 = 12345;
44 expect(@atomicLoad(i32, &x, AtomicOrder.SeqCst) == 1234);
45 expect(@atomicLoad(i32, &y, AtomicOrder.SeqCst) == 12345);
47 expect(@atomicLoad(i32, &x, .SeqCst) == 1234);
48 expect(@atomicLoad(i32, &y, .SeqCst) == 12345);
4649 }
4750}
4851
4952fn testAtomicLoad(ptr: *u8) void {
50 const x = @atomicLoad(u8, ptr, AtomicOrder.SeqCst);
53 const x = @atomicLoad(u8, ptr, .SeqCst);
5154 expect(x == 42);
5255}
5356
......@@ -56,18 +59,18 @@ test "cmpxchg with ptr" {
5659 var data2: i32 = 5678;
5760 var data3: i32 = 9101;
5861 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| {
6063 expect(x1 == &data1);
6164 } else {
6265 @panic("cmpxchg should have failed");
6366 }
6467
65 while (@cmpxchgWeak(*i32, &x, &data1, &data3, AtomicOrder.SeqCst, AtomicOrder.SeqCst)) |x1| {
68 while (@cmpxchgWeak(*i32, &x, &data1, &data3, .SeqCst, .SeqCst)) |x1| {
6669 expect(x1 == &data1);
6770 }
6871 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);
7174 expect(x == &data2);
7275}
7376
......@@ -151,6 +154,7 @@ test "atomicrmw with floats" {
151154 return error.SkipZigTest;
152155 }
153156 testAtomicRmwFloat();
157 comptime testAtomicRmwFloat();
154158}
155159
156160fn testAtomicRmwFloat() void {
......@@ -163,3 +167,54 @@ fn testAtomicRmwFloat() void {
163167 _ = @atomicRmw(f32, &x, .Sub, 2, .SeqCst);
164168 expect(x == 4);
165169}
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 {
449449 expect(shifted == 0b00101101);
450450}
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
452471test "comptime_int addition" {
453472 comptime {
454473 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" {
175175 S.doTheTest();
176176 comptime S.doTheTest();
177177}
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;
44const fmt = std.fmt;
55
66pub fn main() !void {
7 const stdout = &io.getStdOut().outStream().stream;
7 const stdout = io.getStdOut().outStream();
88 const stdin = io.getStdIn();
99
1010 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 {
594594 }
595595 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();
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;
597 const stdout = child.stdout.?.inStream().readAllAlloc(b.allocator, max_stdout_size) catch unreachable;
601598 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;
603600 defer b.allocator.free(stderr);
604601
605602 const term = child.wait() catch |err| {
......@@ -826,11 +823,8 @@ pub const CompileErrorContext = struct {
826823 var stdout_buf = Buffer.initNull(b.allocator);
827824 var stderr_buf = Buffer.initNull(b.allocator);
828825
829 var stdout_file_in_stream = child.stdout.?.inStream();
830 var stderr_file_in_stream = child.stderr.?.inStream();
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;
826 child.stdout.?.inStream().readAllBuffer(&stdout_buf, max_stdout_size) catch unreachable;
827 child.stderr.?.inStream().readAllBuffer(&stderr_buf, max_stdout_size) catch unreachable;
834828
835829 const term = child.wait() catch |err| {
836830 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");
33const CrossTarget = std.zig.CrossTarget;
44
55pub 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
644 cases.add("nested loops without blocks",
745 \\void foo() {
846 \\ while (0) while (0) {}
......@@ -1420,7 +1458,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
14201458 cases.add("macro pointer cast",
14211459 \\#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)
14221460 , &[_][]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));
14241462 });
14251463
14261464 cases.add("basic macro function",
......@@ -1592,7 +1630,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
15921630 cases.add("shadowing primitive types",
15931631 \\unsigned anyerror = 2;
15941632 , &[_][]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));
15961634 });
15971635
15981636 cases.add("floats",
......@@ -2604,11 +2642,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
26042642 \\#define FOO(bar) baz((void *)(baz))
26052643 \\#define BAR (void*) a
26062644 , &[_][]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)))) {
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)));
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)))) {
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)));
26092647 \\}
26102648 ,
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));
26122650 });
26132651
26142652 cases.add("macro conditional operator",
......@@ -2770,19 +2808,4 @@ pub fn addCases(cases: *tests.TranslateCContext) void {
27702808 \\ return if (x > y) x else y;
27712809 \\}
27722810 });
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 });
27882811}