raz / commit 89524972

commit
8952497244478aa5d2d225e6ee6adfaffd7d6ac9
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
c06c29f2
The library on the Mac: Rt, Thread, Sys over libSystem; Arith

PLAN.md 5, step 7. Rt.darwin-arm64 tells a failed check and a signal
at its place, with the calls under way, as Linux's does; Thread.darwin
makes pthreads, its Mutex os_unfair_lock. Arith, a new module by the
owner's word, holds Math's machine code, one file a machine, so
Math.sqrt is one fsqrt or sqrtsd. tools/cabi.c writes what macOS lacks
of Linux's calls into CAbi.darwin-arm64; both CAbi files regenerated.
doc/raz-lib.md says where the Mac differs. On the Mac, the library's
tests and test/libc pass but ExecveC (/proc is Linux's); conform/run
all pass; make check passes in the container; the fixpoint holds.

patch · log

19 files changed, +1908 -158

PLAN.md (history) modified +1 -1

@@ -292,7 +292,7 @@
292292 x7, a variadic call and a callback; `Host.darwin.raz`, and `HOST=darwin
293293 src/cross.sh darwin-arm64`, which stages the first Mac compiler: it
294294 runs on the Mac, compiles and runs programs, and builds `Procs`.
295-7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`.
295+7. Done. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`.
296296 8. `test/` and `conform/` passing on the Mac; what differs by target
297297 (signals' words, errors' numbers) in files of the target's.
298298 9. The first Mac compiler, by the staged cross compiler; it builds

doc/compiler.md (history) modified +19 -3

@@ -1880,6 +1880,18 @@
18801880 catch, `Rt`'s handler tells: a nil pointer within page zero, 4 GB
18811881 (`NilPage`), a call to nil, and a stack overflow at the guard page,
18821882 each a SIGSEGV or SIGBUS, on a stack of its own (`lib/Rt.darwin-arm64.raz`).
1883+That `Rt` is Linux's in all it tells: the place, from the places, and
1884+the calls under way with their variables, up x29's chain of frame
1885+records, a call being the `bl` 4 bytes before its return address, and
1886+x19 to x23 (`VarRegs`) read back from where each frame saved them, or,
1887+after a signal, from the context the kernel handed the handler. A stack
1888+overflow can stop a procedure at its first instruction, the `stp` of
1889+its frame record, so the handler makes that record itself, from the fp
1890+and lr it found. Its code procedures (`framePtr`, `liveRegs`, `here`)
1891+are written in `db`, since `BOOT`'s release reads `Rt`'s every file
1892+for its interface when it builds `src/` and knows only x86-64's
1893+instructions; no `sigReturn`, as libSystem's `_sigtramp` returns from a
1894+handler.
18831895
18841896 The rest is x86's, in arm64's instructions, each shown in its
18851897 routine's comment: `copyBytes` and `zeroBytes` past 256 bytes by a loop
@@ -2571,8 +2583,10 @@
25712583 arm64's fixups are patched by `patchArm`: a branch's distance in words,
25722584 an `adrp`'s in pages of 4 KB, and an address's place in its page, in an
25732585 `add` or, divided by the size it moves, in a load or a store, as
2574-`Chunk.FixKind` says. The places keep the addresses the linker gave;
2575-the Mac's `Rt` will take dyld's slide from what it looks up.
2586+`Chunk.FixKind` says. The places keep the addresses the linker gave,
2587+and are not rebased; the Mac's `Rt` takes dyld's slide,
2588+`_dyld_get_image_vmaddr_slide(0)`, from each address before it looks it
2589+up (`linked`).
25762590
25772591 ## Exe.linux.raz: the executable
25782592
@@ -2748,7 +2762,9 @@
27482762 must be `X.expect`, so C itself says what is right); then conform/run's, which are counted, those
27492763 that fail listed in `build/mac/conform.fail`, and those not for the Mac,
27502764 named in the script with why (`SystemImport`, as `SYSCALL` is Linux's),
2751-skipped; and last `test/lldb.sh`, if lldb is there (`make lldb` is that
2765+skipped; then each library module's own test, by the file the target
2766+takes, and `test/libc`'s programs, which count as `test/mac`'s do, but
2767+those named in `libNotHere`; and last `test/lldb.sh`, if lldb is there (`make lldb` is that
27522768 alone, after `make mac-build`, the container's half). The host changes nothing of the target:
27532769 a program for another system still needs that system's `Sys` and `Rt`,
27542770 and for a kernel the options `-bare`, `-s` and `-base`.

doc/raz-lib.md (history) modified +35 -8

@@ -24,7 +24,7 @@
2424 | `Rt` | ending the program, `exit`, `exitStatus` and `atExit`; `stop`, which ends it with a message; `trace`, the calls under way; what the compiler's checks call when they fail |
2525 | `Sys` | system calls: `open`, `openMode`, `openRead`, `create`, `read`, `write`, `seek`, `position`, `truncate`, `sync`, `syncAll`, `lock`, `lockShared`, `close`, `closeChecked`, `dup`, `dupTo`, `dupAbove`, `keepOnExec`, `mmap`, `munmap`, `mapRead`, `protect`, `isTerminal`, `yield`, `exit`; files and directories, `rename`, `remove`, `removeDir`, `makeDir`, `makeDirMode`, `chmod`, `setTime`, `access`, `umask`, `symlink`, `readLink`, `info`, `linkInfo`, `infoOf`, `openDir`, `nextEntry`, `entryKind`, `closeDir`; the terminal, `rawMode`, `restoreMode`, `getMode`, `setMode`, `termSize`, `ready`; the environment, `env`, `findEnv`, `envAt`, `setEnv`, `workDir`, `setWorkDir`; programs, `spawn`, `exec` and `execve`, pipes and signals; the user, the machine, time used and limits; time, `clock`, `now`, `sleep`; `random`; errors, by name, and what one means, `errorText`; sockets, among them datagrams served and files passed; and memory shared through a file. One file per target, and `Sys.raz` over the C library for the others, which takes what each C library fixes from `CAbi` |
2626 | `Out` | writing text and numbers to standard output, buffered; safe to call from several threads |
27-| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C |
27+| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C. On macOS, a call only Linux's C library has fails with ENOSYS |
2828 | `Lock` | a lock for short sections, for C's threads and `Thread`'s alike |
2929 | `Thread` | threads, `spawn`, `join` and `signal`, and `Mutex`, in any program; in one that uses C, made by C's `pthread_create` |
3030 | `Task` | a thread given a value of its own, `Task(T)`: `spawn` copies it, with no cast |
@@ -41,6 +41,7 @@
4141 | `Vec` | a generic growable array, `Vec(T)`, indexed as a slice |
4242 | `Sort` | sorting a slice in place, `Sort(T; less)` |
4343 | `Math` | roots, powers, logarithms, rounding and trigonometry, and `pi`, for `F64` |
44+| `Arith` | the machine's own arithmetic that `Math` gives: `sqrt`, the 128-bit product `mul`, and `div128`; one file per machine |
4445 | `Files` | an argument as a string, and a whole file read or written |
4546 | `Opt` | a command line read through one table, by `getopt`'s rules with long options; its help and its mistakes |
4647 | `Width` | how many columns of a terminal a character, or a string, takes: 0, 1 or 2, as `wcwidth` says |
@@ -176,7 +177,10 @@
176177 with a message, as in the main thread. In a program that uses C,
177178 `Thread` makes its threads with C's `pthread_create`, so that C's
178179 library knows of them; in one that doesn't, with the system's own
179-calls. The program is the same either way.
180+calls. The program is the same either way. On macOS every program uses
181+C; a thread's stack is 1 MB, as on Linux without C, and a `Mutex` is
182+the system's `os_unfair_lock`, which the thread that took it must give
183+up: one that unlocks another's stops the program.
180184
181185 `Sys.kill` signals a program, and the system gives the signal to any
182186 of its threads; `signal` gives it to `t` alone, until `t` is joined,
@@ -514,8 +518,9 @@
514518 `makeDirMode` is `makeDir` that gives the
515519 directory the bits `mode`, less those the umask takes away, as
516520 `openMode` gives a file: 1C0H (700) for one only its owner may enter.
517-Of the three above them, Linux gives a new directory only sticky; it
518-takes set-group-id from the directory it is made in. `setTime` sets
521+Of the three above them, Linux gives a new directory only sticky, and
522+macOS none, which `chmod` gives after; Linux takes set-group-id from
523+the directory it is made in. `setTime` sets
519524 the file's time, following a symbolic link, and the time it was last
520525 read with it, as a program that copies or restores a file keeps its
521526 time, so that a later run sees it unchanged: `sec` seconds and `nsec`,
@@ -524,12 +529,18 @@
524529 `Info.seconds` holds it in whole seconds, rounded down, whatever it
525530 is, so a program that copies times exactly takes `Info.seconds`, and
526531 the nanoseconds as `mtime - seconds * 1000000000`, which is right in
527-any year, since the wrapping cancels out (section 6.1).
532+any year, since the wrapping cancels out (section 6.1). That is as far
533+as the file system keeps the time: macOS's APFS keeps it in
534+nanoseconds too, and gives a time past 2262 as its last second there.
528535
529536 **Programs.** `openPty` makes a pseudo-terminal, a terminal that a
530537 program, a terminal emulator, plays the screen and the keyboard of:
531538 what it writes to the fd is typed, and what the programs on the
532-terminal write it reads.
539+terminal write it reads. On macOS, whose pseudo-terminal takes no
540+modes and no size until its terminal has been opened, and reads an end
541+once that is closed again, `openPty` opens the terminal and holds it
542+until the first program `spawn` starts on it with `p.tty` takes it
543+over, or the fd is closed with `close` or `closeChecked`.
533544
534545 `spawn` starts the program at `p.path`, with `p.args` as its
535546 arguments, the first being its name. A `p.path` without a `/` is
@@ -745,7 +756,10 @@
745756 `size` zeroed bytes, and `mapFile` maps it, or any file, so that
746757 what one program writes there another sees at once: so a program hands
747758 an X server or a Wayland compositor its pixels, by `sendFds` of a
748-`memFile` both map, rather than by copying them down a socket.
759+`memFile` both map, rather than by copying them down a socket. On
760+macOS, which has no `memfd_create`, a `memFile` is a POSIX shared memory
761+object whose name is gone at once: it can be mapped, but not read or
762+written with `read` and `write`.
749763 `mapFile` needs a file open to read and write; `mapRead` maps one that
750764 is open only to read, a dictionary that isn't the user's to write, for
751765 reading only: a write there stops the program. `protect` changes what
@@ -763,7 +777,9 @@
763777 most 107 bytes, as `struct sockaddr_un` holds; a longer one is -36
764778 (ENAMETOOLONG). A path that starts with a zero byte is one of Linux's
765779 abstract names (D-Bus's `unix:abstract=`), which has no file: the
766-address is as long as the name, with no zero after it.
780+address is as long as the name, with no zero after it. A system that
781+has no abstract names, as macOS, refuses one with -22 (EINVAL); and
782+there `struct sockaddr_un` holds 103 bytes of a path.
767783
768784 `poll` is `readyFor` without its limits. Each `Poll` names a
769785 descriptor `fd` and whether to wait to `read` from it, to `write` to
@@ -934,7 +950,18 @@
934950 proc mul*(a, b: U64): (U64, U64); (* a times b: the low 64 bits of the product, and the high *)
935951 proc divMod*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *)
936952 proc toReal*(s: []const U8): (F64, BOOL); (* s as a real, the F64 nearest it; false if it isn't one *)
953+
954+module Arith;
955+proc sqrt*(x: F64): F64; (* the square root, the machine's instruction *)
956+proc mul*(a, b: U64): (U64, U64); (* a times b: the low 64 bits of the product, and the high *)
957+proc div128*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d, which must be more than hi *)
937958 ```
959+
960+`Math` keeps no machine code: its `sqrt`, `mul` and `divMod` are
961+`Arith`'s, a file for each machine. `div128` doesn't check that `hi < d`,
962+as `Math.divMod` does: on x86-64 the machine faults if it isn't, and on
963+arm64, which has no such division, it is long division in raz, whose
964+quotient is then wrong.
938965
939966 A `Buf`, a `List`, a `Map` and a `Vec` take their memory from the
940967 allocator `init` gives them. `Buf.add`, `str` and `spare` stop the program, as a

lib/Arith.arm64.raz (history) added +66 -0

@@ -0,0 +1,66 @@
1+(* Arith: the machine's arithmetic that raz has no operator for, which
2+ Math gives as sqrt, mul and divMod: an F64's square root, the 128-bit
3+ product of two U64s, and a 128-bit number divided by a U64. This file
4+ is arm64's, Arith.x86_64.raz x86-64's. The root is fsqrt, and a call
5+ of sqrt, an fsqrt and ret, is made in place (Gen.oneRealOp); the
6+ product is mul for its low half and umulh for its high. arm64 has no
7+ division of 128 bits by 64, only udiv of 64 by 64, so div128 is
8+ long division in raz, a bit of the quotient at each of 64 steps.
9+ Depends on Check, for its test. *)
10+module Arith;
11+import Check;
12+import SYSTEM;
13+
14+(* The square root of x, exact to the last bit; NaN for x below 0. *)
15+proc sqrt*(x: F64): F64;
16+code
17+ fsqrt d0, d0;
18+ ret;
19+end sqrt;
20+
21+(* a times b: the low 64 bits of the product, and the high, which come
22+ back in x0 and x1. *)
23+proc mul*(a, b: U64): (U64, U64);
24+code
25+ mul x2, x0, x1;
26+ umulh x1, x0, x1;
27+ mov x0, x2;
28+ ret;
29+end mul;
30+
31+(* hi, lo divided by d, with hi < d, which the caller checks first: the
32+ quotient and the remainder. As by hand, in base 2: the remainder so
33+ far, hi, takes the next bit of lo at each step, and where it then
34+ holds d, d is taken from it and that bit of the quotient is 1. The
35+ remainder is below d before a step, so below 2d after the shift: it
36+ holds d once at most, and its bit shifted out, top, says it is more
37+ than 64 bits can hold, and so holds d too. *)
38+proc div128*(hi, lo, d: U64): (U64, U64);
39+var q: U64; i: INT; top: BOOL;
40+begin
41+ q := 0;
42+ for i := 1 to 64 do
43+ top := hi shr 63 = 1;
44+ hi := hi shl 1 | lo shr 63;
45+ lo := lo shl 1;
46+ q := q shl 1;
47+ if top or (hi >= d) then
48+ hi := hi - d;
49+ q := q | 1;
50+ end;
51+ end;
52+ return q, hi;
53+end;
54+
55+(* The module's test; Math's tests these more. *)
56+proc main*;
57+var lo, hi, q, r: U64;
58+begin
59+ Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt");
60+ lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH);
61+ Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul");
62+ q, r := div128(5, 9, 6);
63+ Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128");
64+end;
65+
66+end Arith.

lib/Arith.x86_64.raz (history) added +50 -0

@@ -0,0 +1,50 @@
1+(* Arith: the machine's arithmetic that raz has no operator for, which
2+ Math gives as sqrt, mul and divMod: an F64's square root, the 128-bit
3+ product of two U64s, and a 128-bit number divided by a U64. Each is
4+ one instruction of the machine, so each is a code procedure, one
5+ file per machine: this one for x86-64, Arith.arm64.raz for arm64. A
6+ call of sqrt, a sqrtsd and ret, is made in place (Gen.oneRealOp).
7+ Depends on Check, for its test. *)
8+module Arith;
9+import Check;
10+import SYSTEM;
11+
12+(* The square root of x, exact to the last bit; NaN for x below 0. *)
13+proc sqrt*(x: F64): F64;
14+code
15+ sqrtsd xmm0, xmm0;
16+ ret;
17+end sqrt;
18+
19+(* a times b: the low 64 bits of the product, and the high. *)
20+proc mul*(a, b: U64): (U64, U64);
21+code
22+ mov rax, rdi;
23+ mul rsi;
24+ ret;
25+end mul;
26+
27+(* hi, lo divided by d: the quotient and the remainder, by the
28+ machine's one instruction; it faults if hi >= d, which the caller
29+ checks first. *)
30+proc div128*(hi, lo, d: U64): (U64, U64);
31+code
32+ mov rcx, rdx;
33+ mov rdx, rdi;
34+ mov rax, rsi;
35+ div rcx;
36+ ret;
37+end div128;
38+
39+(* The module's test; Math's tests these more. *)
40+proc main*;
41+var lo, hi, q, r: U64;
42+begin
43+ Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt");
44+ lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH);
45+ Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul");
46+ q, r := div128(5, 9, 6);
47+ Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128");
48+end;
49+
50+end Arith.

lib/C.darwin.raz (history) added +181 -0

@@ -0,0 +1,181 @@
1+(* The C library: what raz's own library calls in it, and what most
2+ programs reach for; this file is macOS's, libSystem's, C.raz the
3+ others'. A program that imports C uses C, as every program on a Mac
4+ does.
5+
6+ libSystem has every call of C.raz but those Linux's C library alone
7+ has, which are procedures here that fail as C's calls do, -1 with
8+ errno ENOSYS, as an unknown system call does: memfd_create,
9+ clock_nanosleep, getrandom, accept4, close_range, sched_getaffinity
10+ and pipe2 (Sys makes them of what libSystem has, in CAbi). errno is
11+ __error here, and __errno_location gives it. stdout and stderr are
12+ __stdoutp and __stderrp, put in variables of those names first. *)
13+module C;
14+import SYSTEM;
15+
16+extern proc write*(fd: I32; buf: ^U8; n: UINT): INT;
17+extern proc read*(fd: I32; buf: ^U8; n: UINT): INT;
18+extern proc open*(path: ^U8; flags: I32; ...): I32;
19+extern proc creat*(path: ^U8; mode: U32): I32;
20+extern proc close*(fd: I32): I32;
21+extern proc mmap*(addr: ^U8; n: UINT; prot, flags, fd: I32; off: I64): ^U8;
22+extern proc munmap*(addr: ^U8; n: UINT): I32;
23+extern proc mprotect*(addr: ^U8; n: UINT; prot: I32): I32;
24+extern proc isatty*(fd: I32): I32;
25+extern proc exit*(status: I32);
26+extern proc _exit*(status: I32);
27+extern proc __error: ^I32;
28+extern proc sched_yield*: I32;
29+extern proc pthread_create*(t: ^UINT; attr: ^U8;
30+ start: proc(arg: ^U8): ^U8; arg: ^U8): I32;
31+extern proc pthread_join*(t: UINT; result: ^^U8): I32;
32+extern proc rename*(old, new: ^U8): I32;
33+extern proc unlink*(path: ^U8): I32;
34+extern proc mkdir*(path: ^U8; mode: U32): I32;
35+extern proc rmdir*(path: ^U8): I32;
36+extern proc chmod*(path: ^U8; mode: U32): I32;
37+extern proc chown*(path: ^U8; uid, gid: U32): I32;
38+extern proc mkfifo*(path: ^U8; mode: U32): I32;
39+extern proc utimensat*(dir: I32; path, times: ^U8; flags: I32): I32;
40+extern proc readlink*(path, buf: ^U8; n: UINT): INT;
41+extern proc lseek*(fd: I32; off: I64; whence: I32): I64;
42+extern proc opendir*(path: ^U8): ^U8; (* DIR * *)
43+extern proc readdir*(d: ^U8): ^U8; (* struct dirent * *)
44+extern proc closedir*(d: ^U8): I32;
45+extern proc tcgetattr*(fd: I32; t: ^U8): I32;
46+extern proc tcsetattr*(fd: I32; when: I32; t: ^U8): I32;
47+extern proc cfmakeraw*(t: ^U8);
48+extern proc ioctl*(fd: I32; request: UINT; ...): I32;
49+extern proc poll*(fds: ^U8; n: UINT; ms: I32): I32;
50+extern proc fcntl*(fd, cmd: I32; ...): I32;
51+extern proc socket*(domain, kind, protocol: I32): I32;
52+extern proc connect*(fd: I32; addr: ^U8; len: U32): I32;
53+extern proc send*(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;
54+extern proc bind*(fd: I32; addr: ^U8; len: U32): I32;
55+extern proc listen*(fd, backlog: I32): I32;
56+extern proc accept*(fd: I32; addr: ^U8; len: ^U32): I32;
57+extern proc setsockopt*(fd, level, name: I32; value: ^U8; len: U32): I32;
58+extern proc getsockopt*(fd, level, name: I32; value: ^U8; len: ^U32): I32;
59+extern proc getpeername*(fd: I32; addr: ^U8; len: ^U32): I32;
60+extern proc shutdown*(fd, how: I32): I32;
61+extern proc socketpair*(domain, kind, protocol: I32; fds: ^I32): I32;
62+extern proc getsockname*(fd: I32; addr: ^U8; len: ^U32): I32;
63+extern proc recvfrom*(fd: I32; buf: ^U8; n: UINT; flags: I32; addr: ^U8; len: ^U32): INT;
64+extern proc sendto*(fd: I32; buf: ^U8; n: UINT; flags: I32; addr: ^U8; len: U32): INT;
65+extern proc sendmsg*(fd: I32; msg: ^U8; flags: I32): INT;
66+extern proc recvmsg*(fd: I32; msg: ^U8; flags: I32): INT;
67+extern proc ftruncate*(fd: I32; size: I64): I32;
68+extern proc inet_pton*(family: I32; src, dst: ^U8): I32;
69+extern proc clock_gettime*(clock: I32; t: ^U8): I32;
70+extern proc getenv*(name: ^U8): ^U8;
71+extern proc setenv*(name, value: ^U8; overwrite: I32): I32;
72+extern proc strerror*(err: I32): ^U8;
73+extern proc getcwd*(buf: ^U8; n: UINT): ^U8;
74+extern proc chdir*(path: ^U8): I32;
75+extern proc stat*(path, st: ^U8): I32;
76+extern proc fstat*(fd: I32; st: ^U8): I32;
77+extern proc fsync*(fd: I32): I32;
78+extern proc sync*;
79+extern proc flock*(fd, how: I32): I32;
80+extern proc lstat*(path, st: ^U8): I32;
81+extern proc statvfs*(path, st: ^U8): I32;
82+extern proc symlink*(target, path: ^U8): I32;
83+extern proc posix_openpt*(flags: I32): I32;
84+extern proc grantpt*(fd: I32): I32;
85+extern proc unlockpt*(fd: I32): I32;
86+extern proc ptsname*(fd: I32): ^U8;
87+extern proc fork*: I32;
88+extern proc setsid*: I32;
89+extern proc dup2*(fd, fd2: I32): I32;
90+extern proc dup*(fd: I32): I32;
91+extern proc execve*(path: ^U8; argv, envp: ^^U8): I32;
92+extern proc waitpid*(pid: I32; status: ^I32; options: I32): I32;
93+extern proc kill*(pid, signal: I32): I32;
94+extern proc getpid*: I32;
95+extern proc getuid*: U32;
96+extern proc geteuid*: U32;
97+extern proc gethostname*(name: ^U8; n: UINT): I32;
98+extern proc access*(path: ^U8; how: I32): I32;
99+extern proc umask*(mask: U32): U32;
100+extern proc getrusage*(who: I32; usage: ^U8): I32;
101+extern proc getrlimit*(which: I32; limit: ^U8): I32;
102+extern proc setrlimit*(which: I32; limit: ^U8): I32;
103+extern proc getpgrp*: I32;
104+extern proc setpgid*(pid, group: I32): I32;
105+extern proc tcsetpgrp*(fd, group: I32): I32;
106+extern proc tcgetpgrp*(fd: I32): I32;
107+extern proc sigaction*(sig: I32; act, old: ^U8): I32;
108+extern proc sigprocmask*(how: I32; mask, old: ^U8): I32;
109+extern proc printf*(format: ^U8; ...): I32;
110+extern proc fflush*(f: ^U8): I32;
111+extern var environ*: ^^U8;
112+extern var __stdoutp: ^U8;
113+extern var __stderrp: ^U8;
114+
115+var
116+ stdout*: ^U8; (* FILE *: __stdoutp *)
117+ stderr*: ^U8; (* __stderrp *)
118+
119+(* What a call Linux alone has does here, as each below: -1, errno
120+ ENOSYS. Their parameters are named as in C.raz, as the interface
121+ check wants, and dropped. *)
122+proc none: I32;
123+var e: ^I32;
124+begin
125+ e := __error();
126+ e^ := 78; (* ENOSYS *)
127+ return -1;
128+end;
129+
130+(* errno, this thread's *)
131+proc __errno_location*: ^I32;
132+begin
133+ return __error();
134+end;
135+
136+proc accept4*(fd: I32; addr: ^U8; len: ^U32; flags: I32): I32;
137+begin
138+ _ := fd; _ := addr; _ := len; _ := flags;
139+ return none();
140+end;
141+
142+proc memfd_create*(name: ^U8; flags: U32): I32;
143+begin
144+ _ := name; _ := flags;
145+ return none();
146+end;
147+
148+proc clock_nanosleep*(clock, flags: I32; t, left: ^U8): I32;
149+begin
150+ _ := clock; _ := flags; _ := t; _ := left;
151+ return none();
152+end;
153+
154+proc getrandom*(buf: ^U8; n: UINT; flags: U32): INT;
155+begin
156+ _ := buf; _ := n; _ := flags;
157+ return INT(none());
158+end;
159+
160+proc close_range*(first, last: U32; flags: I32): I32;
161+begin
162+ _ := first; _ := last; _ := flags;
163+ return none();
164+end;
165+
166+proc sched_getaffinity*(pid: I32; size: UINT; mask: ^U8): I32;
167+begin
168+ _ := pid; _ := size; _ := mask;
169+ return none();
170+end;
171+
172+proc pipe2*(fds: ^I32; flags: I32): I32;
173+begin
174+ _ := fds; _ := flags;
175+ return none();
176+end;
177+
178+begin
179+ stdout := __stdoutp;
180+ stderr := __stderrp;
181+end C.

lib/CAbi.darwin-arm64.raz (history) modified +150 -1

@@ -1,7 +1,7 @@
11 (* CAbi: what the C library fixes for Sys over C on darwin-arm64: the
22 numbers of its flags, requests, signals and limits, where the
33 fields of its structs lie, an At the offset and a Len the width,
4- its errnos beside Linux's, and errno and closeFrom.
4+ its errnos beside Linux's, and the procedures that differ.
55
66 Written by tools/cabi.c, from the system's own headers; not to be
77 edited, but written again. *)
@@ -86,6 +86,7 @@
8686 tiocgwinsz* = 1074295912;
8787 tiocswinsz* = 2148037735;
8888 tiocsctty* = 536900705;
89+ ptyHeld* = 1;
8990 pollin* = 1;
9091 pollout* = 4;
9192 clockRealtime* = 0;
@@ -115,6 +116,7 @@
115116 sockaddrUnLen* = 106;
116117 sunPathAt* = 2;
117118 sunPathLen* = 104;
119+ unixAbstract* = 0;
118120 sockaddrInLen* = 16;
119121 sinPortAt* = 2;
120122 sinAddrAt* = 4;
@@ -206,7 +208,21 @@
206208 extern proc __error: ^I32;
207209 extern proc close(fd: I32): I32;
208210 extern proc getdtablesize: I32;
211+extern proc pipe(fds: ^I32): I32;
212+extern proc fcntl(fd, cmd: I32; ...): I32;
213+extern proc accept(fd: I32; addr: ^U8; len: ^U32): I32;
214+extern proc getentropy(buf: ^U8; n: UINT): I32;
215+extern proc getpid: I32;
216+extern proc shm_open(name: ^U8; flags: I32; ...): I32;
217+extern proc shm_unlink(name: ^U8): I32;
218+extern proc clock_gettime(clock: I32; t: ^U8): I32;
219+extern proc nanosleep(t, left: ^U8): I32;
220+extern proc sysconf(name: I32): INT;
221+extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32;
222+extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;
209223
224+var shmCount: INT; (* the shared memory objects memFile has made *)
225+
210226 (* errno, this thread's *)
211227 proc errno*: ^I32;
212228 begin
@@ -220,6 +236,139 @@
220236 begin
221237 if hi < 0 then hi := INT(getdtablesize()) - 1; end;
222238 for fd := lo to hi do _ := close(I32(fd)); end;
239+end;
240+
241+(* fd closed on exec, and nonblocking, as flags, oCloexec and
242+ oNonblock, say: macOS has no flags for them where a pipe or a
243+ socket is made, so another thread's exec in between keeps the fd
244+ open, a gap Linux hasn't. *)
245+proc setFlags(fd, flags: I32);
246+begin
247+ if flags & oCloexec # 0 then _ := fcntl(fd, fSetfd, fdCloexec); end;
248+ if flags & oNonblock # 0 then _ := fcntl(fd, fSetfl, fcntl(fd, fGetfl) | oNonblock); end;
249+end;
250+
251+(* A pipe, its two fds put at fds, taking flags, oCloexec and
252+ oNonblock: 0, or -1 with errno set, as C's calls are. *)
253+proc makePipe*(fds: ^I32; flags: I32): I32;
254+begin
255+ if pipe(fds) # 0 then return -1; end;
256+ setFlags(fds[0], flags);
257+ setFlags(fds[1], flags);
258+ return 0;
259+end;
260+
261+(* The next connection to the socket fd, closed on exec; or -1. *)
262+proc accepted*(fd: I32): I32;
263+var r: I32;
264+begin
265+ r := accept(fd, nil, nil);
266+ if r >= 0 then setFlags(r, oCloexec); end;
267+ return r;
268+end;
269+
270+(* The kernel's random bytes, at most n, put at buf: how many, or -1.
271+ getentropy gives 256 at most at a time. *)
272+proc random*(buf: ^U8; n: UINT): INT;
273+begin
274+ if n > 256 then n := 256; end;
275+ if getentropy(buf, n) # 0 then return -1; end;
276+ return INT(n);
277+end;
278+
279+(* v in hexadecimal into name from i on: where its digits end *)
280+proc hex(var name: [32]U8; i, v: INT): INT;
281+var n, k, d: INT;
282+begin
283+ n := v;
284+ repeat INC(i); n := n shr 4; until n = 0;
285+ k := i;
286+ repeat
287+ DEC(k);
288+ d := v & 15;
289+ if d < 10 then name[k] := U8(d) + '0'; else name[k] := U8(d - 10) + 'a'; end;
290+ v := v shr 4;
291+ until v = 0;
292+ return i;
293+end;
294+
295+(* A file in memory, of no bytes, with no name, closed on exec: its
296+ fd, or -1. macOS has no memfd_create: it is a POSIX shared memory
297+ object, made with a name of its own, /raz.PID.N, which is removed
298+ at once. Such an object can be given its size once, and mapped, but
299+ not read or written. *)
300+proc memFile*: I32;
301+var name: [32]U8; fd: I32; i: INT;
302+begin
303+ COPY(name[0..5], "/raz.");
304+ i := hex(name, 5, INT(getpid()));
305+ name[i] := '.';
306+ i := hex(name, i + 1, XADD(shmCount, 1));
307+ name[i] := 0;
308+ fd := shm_open(SYSTEM.ADR(name[0]), oRdwr | oCreat | oExcl, 384); (* rw------- *)
309+ if fd < 0 then return -1; end;
310+ _ := shm_unlink(SYSTEM.ADR(name[0]));
311+ setFlags(fd, oCloexec);
312+ return fd;
313+end;
314+
315+(* Waits until t, a struct timespec of the monotonic clock: macOS has
316+ no clock_nanosleep, so nanosleep sleeps what is left, again after
317+ EINTR. *)
318+proc sleepUntil*(t: ^U8);
319+var now, left: [2]I64; at: ^I64; d: I64;
320+begin
321+ at := ^I64(t);
322+ repeat
323+ _ := clock_gettime(clockMonotonic, ^U8(SYSTEM.ADR(now[0])));
324+ d := (at[0] - now[0]) * 1000000000 + at[1] - now[1];
325+ if d <= 0 then return; end;
326+ left := [d div 1000000000, d mod 1000000000];
327+ _ := nanosleep(^U8(SYSTEM.ADR(left[0])), nil);
328+ until false;
329+end;
330+
331+(* The number of processors this program may run on, or 0 if the
332+ system doesn't say: those online, as macOS binds a program to none
333+ of them. *)
334+proc processors*: INT;
335+begin
336+ return sysconf(58); (* _SC_NPROCESSORS_ONLN *)
337+end;
338+
339+(* The process and the user at the other end of the Unix socket fd,
340+ as the system recorded them when it connected, and 0; or -1. The
341+ user is in a struct xucred, LOCAL_PEERCRED's, and the process is
342+ asked for alone, LOCAL_PEERPID. *)
343+proc peer*(fd: I32; var pid, uid: INT): I32;
344+var cred: [16]U64; size: U32; p: ^U8; q: ^U32; id: I32;
345+begin
346+ p := ^U8(SYSTEM.ADR(cred[0]));
347+ size := U32(SIZE([16]U64));
348+ if getsockopt(fd, 0, 1, p, SYSTEM.ADR(size)) # 0 then return -1; end;
349+ q := ^U32(p + ucUidAt);
350+ uid := INT(q^);
351+ size := 4;
352+ if getsockopt(fd, 0, 2, ^U8(SYSTEM.ADR(id)), SYSTEM.ADR(size)) # 0 then return -1; end;
353+ pid := INT(id);
354+ return 0;
355+end;
356+
357+(* Sends n bytes at buf on the socket fd, without waiting, and without
358+ SIGPIPE where the other end is gone: how many were sent, or -1.
359+ macOS's send waits on a Unix socket though MSG_DONTWAIT is given, so
360+ the socket is made nonblocking for it, as it was before after. *)
361+proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT;
362+var f: I32; r: INT; e: ^I32; err: I32;
363+begin
364+ f := fcntl(fd, fGetfl);
365+ if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f | oNonblock); end;
366+ r := send(fd, buf, n, msgNosignal | msgDontwait);
367+ e := __error();
368+ err := e^;
369+ if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f); end;
370+ e^ := err;
371+ return r;
223372 end;
224373
225374 end CAbi.

lib/CAbi.linux-x86_64.raz (history) modified +82 -1

@@ -1,7 +1,7 @@
11 (* CAbi: what the C library fixes for Sys over C on linux-x86_64: the
22 numbers of its flags, requests, signals and limits, where the
33 fields of its structs lie, an At the offset and a Len the width,
4- its errnos beside Linux's, and errno and closeFrom.
4+ its errnos beside Linux's, and the procedures that differ.
55
66 Written by tools/cabi.c, from the system's own headers; not to be
77 edited, but written again. *)
@@ -86,6 +86,7 @@
8686 tiocgwinsz* = 21523;
8787 tiocswinsz* = 21524;
8888 tiocsctty* = 21518;
89+ ptyHeld* = 0;
8990 pollin* = 1;
9091 pollout* = 4;
9192 clockRealtime* = 0;
@@ -115,6 +116,7 @@
115116 sockaddrUnLen* = 110;
116117 sunPathAt* = 2;
117118 sunPathLen* = 108;
119+ unixAbstract* = 1;
118120 sockaddrInLen* = 16;
119121 sinPortAt* = 2;
120122 sinAddrAt* = 4;
@@ -205,6 +207,14 @@
205207
206208 extern proc __errno_location: ^I32;
207209 extern proc syscall(n: INT; ...): INT;
210+extern proc pipe2(fds: ^I32; flags: I32): I32;
211+extern proc accept4(fd: I32; addr: ^U8; len: ^U32; flags: I32): I32;
212+extern proc getrandom(buf: ^U8; n: UINT; flags: U32): INT;
213+extern proc memfd_create(name: ^U8; flags: U32): I32;
214+extern proc clock_nanosleep(clock, flags: I32; t, left: ^U8): I32;
215+extern proc sched_getaffinity(pid: I32; size: UINT; mask: ^U8): I32;
216+extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32;
217+extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;
208218
209219 (* errno, this thread's *)
210220 proc errno*: ^I32;
@@ -218,6 +228,77 @@
218228 begin
219229 if hi < 0 then hi := 0FFFFFFFFH; end;
220230 _ := syscall(436, lo, hi, 0);
231+end;
232+
233+(* A pipe, its two fds put at fds, taking flags, oCloexec and
234+ oNonblock, at once: 0, or -1 with errno set, as C's calls are. *)
235+proc makePipe*(fds: ^I32; flags: I32): I32;
236+begin
237+ return pipe2(fds, flags);
238+end;
239+
240+(* The next connection to the socket fd, closed on exec; or -1. *)
241+proc accepted*(fd: I32): I32;
242+begin
243+ return accept4(fd, nil, nil, sockCloexec);
244+end;
245+
246+(* The kernel's random bytes, at most n, put at buf: how many, or -1. *)
247+proc random*(buf: ^U8; n: UINT): INT;
248+begin
249+ return getrandom(buf, n, 0);
250+end;
251+
252+(* A file in memory, of no bytes, with no name, closed on exec: its
253+ fd, or -1. *)
254+proc memFile*: I32;
255+begin
256+ return memfd_create(SYSTEM.PTR("raz\0"), mfdCloexec); (* the name /proc shows *)
257+end;
258+
259+(* Waits until t, a struct timespec of the monotonic clock, again
260+ after EINTR. *)
261+proc sleepUntil*(t: ^U8);
262+begin
263+ repeat until clock_nanosleep(clockMonotonic, timerAbstime, t, nil) # eIntr;
264+end;
265+
266+(* The number of processors this program may run on, or 0 if the
267+ system doesn't say. *)
268+proc processors*: INT;
269+var mask: [1024]U8; i, b, count: INT;
270+begin
271+ for i := 0 to LEN(mask) - 1 do mask[i] := 0; end; (* the C library fills in as many bytes as the system has processors' bits *)
272+ if sched_getaffinity(0, UINT(LEN(mask)), SYSTEM.ADR(mask[0])) # 0 then return 0; end;
273+ count := 0;
274+ for i := 0 to LEN(mask) - 1 do
275+ for b := 0 to 7 do
276+ if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end;
277+ end;
278+ end;
279+ return count;
280+end;
281+
282+(* The process and the user at the other end of the Unix socket fd,
283+ as the system recorded them when it connected, and 0; or -1. *)
284+proc peer*(fd: I32; var pid, uid: INT): I32;
285+var cred: [16]U64; size: U32; p: ^U8; q: ^U32;
286+begin
287+ p := ^U8(SYSTEM.ADR(cred[0]));
288+ size := U32(SIZE([16]U64));
289+ if getsockopt(fd, solSocket, soPeercred, p, SYSTEM.ADR(size)) # 0 then return -1; end;
290+ q := ^U32(p + ucPidAt);
291+ pid := INT(I32(q^));
292+ q := ^U32(p + ucUidAt);
293+ uid := INT(q^);
294+ return 0;
295+end;
296+
297+(* Sends n bytes at buf on the socket fd, without waiting, and without
298+ SIGPIPE where the other end is gone: how many were sent, or -1. *)
299+proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT;
300+begin
301+ return send(fd, buf, n, msgNosignal | msgDontwait);
221302 end;
222303
223304 end CAbi.

lib/Files.raz (history) modified +19 -8

@@ -270,13 +270,22 @@
270270 end;
271271
272272 (* realPath and removeTree in a scratch tree, with links in it and one
273- out of it. *)
273+ out of it. What realPath gives is under /tmp as realPath gives it,
274+ which on a Mac is /private/tmp, /tmp being a link to it. *)
274275 proc testTree;
275276 const T = "/tmp/raz-files-test.d"; Out = "/tmp/raz-files-test.out";
276-var p, q: Buf.Buf; here, now: []const U8; r: INT;
277+var p, q, rt, ro: Buf.Buf; here, now, realT, realOut: []const U8; r: INT;
277278 begin
278279 Buf.init(p, Heap.heap);
279280 Buf.init(q, Heap.heap);
281+ Buf.init(rt, Heap.heap);
282+ Buf.init(ro, Heap.heap);
283+ if realPath("/tmp", rt) # 0 then Rt.stop("realPath: /tmp"); end;
284+ Buf.str(ro, Buf.bytes(rt));
285+ Buf.str(rt, "/raz-files-test.d");
286+ Buf.str(ro, "/raz-files-test.out");
287+ realT := Buf.bytes(rt);
288+ realOut := Buf.bytes(ro);
280289 _ := removeTree(T);
281290 _ := removeTree(Out);
282291 if (Sys.makeDir(T) # 0) or (Sys.makeDir(join(p, T, "/a")) # 0)
@@ -293,12 +302,12 @@
293302 or (Sys.symlink(Out, join(p, T, "/a/ex")) # 0) then
294303 Rt.stop("Files: links");
295304 end;
296- wantReal(join(p, T, "/rel/f"), join(q, T, "/a/b/f"), 0, "realPath: a relative link");
297- wantReal(join(p, T, "/abs/b/../b/./f"), join(q, T, "/a/b/f"), 0, "realPath: absolute link, .. and .");
298- wantReal(join(p, T, "/a/up/f"), join(q, T, "/a/b/f"), 0, "realPath: a link read from its directory");
299- wantReal(join(p, T, "/a/"), join(q, T, "/a"), 0, "realPath: a trailing slash");
300- wantReal(join(p, T, "/a/b/../../abs/b"), join(q, T, "/a/b"), 0, "realPath: .. then a link");
301- wantReal(join(p, T, "/a/ex/keep"), join(q, Out, "/keep"), 0, "realPath: a link out of the tree");
305+ wantReal(join(p, T, "/rel/f"), join(q, realT, "/a/b/f"), 0, "realPath: a relative link");
306+ wantReal(join(p, T, "/abs/b/../b/./f"), join(q, realT, "/a/b/f"), 0, "realPath: absolute link, .. and .");
307+ wantReal(join(p, T, "/a/up/f"), join(q, realT, "/a/b/f"), 0, "realPath: a link read from its directory");
308+ wantReal(join(p, T, "/a/"), join(q, realT, "/a"), 0, "realPath: a trailing slash");
309+ wantReal(join(p, T, "/a/b/../../abs/b"), join(q, realT, "/a/b"), 0, "realPath: .. then a link");
310+ wantReal(join(p, T, "/a/ex/keep"), join(q, realOut, "/keep"), 0, "realPath: a link out of the tree");
302311 wantReal(join(p, T, "/a/nope"), "", Sys.errNoEntry, "realPath: a missing part");
303312 wantReal(join(p, T, "/a/b/f/.."), "", -20, "realPath: .. of a file");
304313 wantReal(join(p, T, "/loop"), "", -40, "realPath: a link loop");
@@ -320,6 +329,8 @@
320329 if removeTree(Out) # 0 then Rt.stop("removeTree: the outside"); end;
321330 Buf.done(p);
322331 Buf.done(q);
332+ Buf.done(rt);
333+ Buf.done(ro);
323334 end;
324335
325336 (* The module's test. *)

lib/Math.raz (history) modified +14 -23

@@ -5,10 +5,12 @@
55 polynomials' coefficients are fdlibm's. Each is within an ulp, a
66 unit in the result's last place.
77
8+ The square root, mul and divMod's division are the machine's own,
9+ from Arith, one file per machine; this file keeps no machine code.
10+
811 Left out: sinh, cosh, fmod and hypot, until a program needs them. *)
912 module Math;
10-import Check, Rt;
11-import SYSTEM;
13+import Arith, Check, Rt;
1214
1315 const
1416 pi* = 3.141592653589793; (* the F64 nearest to pi *)
@@ -33,12 +35,13 @@
3335 return bits(x) shr 63 = 1;
3436 end;
3537
36-(* The square root of x, exact to the last bit; NaN for x below 0. *)
38+(* The square root of x, exact to the last bit; NaN for x below 0: the
39+ machine's own. A procedure that only returns is made in place, and
40+ then Arith.sqrt's one instruction is too, with no call. *)
3741 proc sqrt*(x: F64): F64;
38-code
39- sqrtsd xmm0, xmm0;
40- ret;
41-end sqrt;
42+begin
43+ return Arith.sqrt(x);
44+end;
4245
4346 (* The largest whole number not above x. One of 2^52 or more is whole
4447 already, and so are an infinity and NaN. *)
@@ -437,28 +440,16 @@
437440
438441 (* a times b: the low 64 bits of the product, and the high. *)
439442 proc mul*(a, b: U64): (U64, U64);
440-code
441- mov rax, rdi;
442- mul rsi;
443- ret;
444-end mul;
445-
446-(* hi, lo divided by d, by the machine's one instruction; it faults if hi >= d. *)
447-proc div128(hi, lo, d: U64): (U64, U64);
448-code
449- mov rcx, rdx;
450- mov rdx, rdi;
451- mov rax, rsi;
452- div rcx;
453- ret;
454-end div128;
443+begin
444+ return Arith.mul(a, b);
445+end;
455446
456447 (* hi, lo (a 128-bit number, hi its high word) divided by d: the quotient and the remainder.
457448 hi >= d, whose quotient doesn't fit a word, and d = 0 stop the program, as a division by zero does. *)
458449 proc divMod*(hi, lo, d: U64): (U64, U64);
459450 begin
460451 if hi >= d then Rt.stop("Math.divMod: hi >= d, the quotient doesn't fit a word"); end;
461- return div128(hi, lo, d);
452+ return Arith.div128(hi, lo, d);
462453 end divMod;
463454
464455 (* 64 bits of t from bit s on, the first bit of t[0] being 0. *)

lib/Opt.raz (history) modified +3 -1

@@ -587,7 +587,9 @@
587587 begin
588588 outR, outW := Sys.pipe();
589589 errR, errW := Sys.pipe();
590- pid := Sys.spawn({path: "/proc/self/exe", args: c.args, env: [c.mode], fds: [0, outW, errW]});
590+ (* this program again, by the path it was run by, which has a slash in
591+ it: raztest gives one, and Linux's /proc/self/exe is no Mac's *)
592+ pid := Sys.spawn({path: Files.arg(0), args: c.args, env: [c.mode], fds: [0, outW, errW]});
591593 Sys.close(outW);
592594 Sys.close(errW);
593595 if pid < 0 then Rt.stop("Opt: can't run the test's cases"); end;

lib/Rt.darwin-arm64.raz (history) modified +617 -45

@@ -1,15 +1,31 @@
11 (* The run time, for macOS on arm64, with lib/Rt.raz's interface, which
2- every file of Rt keeps. The compiler finds exit, fail and cExit by
3- these names. exit runs the procedures atExit registered, then ends
4- the program by C's exit, which the entry point gives cExit, as every
5- program on a Mac reaches the kernel through libSystem; fail says
6- what failed, with its values, and stop its message, and they end it
7- with status 2; and a fault the machine catches, a nil pointer or
8- procedure or a stack overflow, is told by a handler, on a stack of
9- its own, as on Linux, and ends it so too. A failure is told by its
10- address, as on Linux in a program built with raz -s: the places, the
11- calls under way and the profiler are what PLAN.md 5's step 7 brings
12- here; place, trace and startProfile do nothing yet. *)
2+ every file of Rt keeps, and its work: ending the program; fail, which
3+ the compiler's code calls when a check fails; stop, for the library's
4+ own failures; the handlers that say where the program was when a
5+ signal stopped it; trace; and the profiler. The compiler finds fail,
6+ exit, cExit, places, profiler, startProfile, teller, calls, placer
7+ and place by these names.
8+
9+ It is lib/Rt.raz's, but for what the Mac does otherwise:
10+ - Every program reaches the kernel through libSystem, so Rt calls C,
11+ by extern, and exit ends the program by C's exit, which the entry
12+ point gives cExit. Rt imports nothing, so its body runs first.
13+ - macOS loads a program at an address of its choosing, the same
14+ image moved by a slide that dyld says, so an address the program
15+ meets is the slide past the one the compiler laid out, which the
16+ places hold (linked).
17+ - The frames' chain is x29's: a frame record of x29 and x30, the
18+ caller's frame and the return address, that x29 points at. A call
19+ is the bl 4 bytes before the return address. A procedure's busiest
20+ variables are in x19 to x23 (regs), as Gen.arm64.raz keeps them.
21+ - The kernel hands a handler a siginfo and a ucontext laid out as
22+ <sys/signal.h> and <mach/arm/_structs.h> have them (onSignal), and
23+ the handler returns through libSystem's _sigtramp, which needs no
24+ sigReturn of Rt's; nor is a division fault a signal on arm64,
25+ where the code checks for it (Gen.divide) and calls fail.
26+ A program built with raz -s has no places, so a failure is told by
27+ its address, and no calls; one built with -noprofile no profiler.
28+ -bare is not for a Mac. *)
1329 module Rt;
1430 import SYSTEM;
1531
@@ -17,13 +33,40 @@
1733 Full*: ERROR = "too many procedures to run at exit"; (* atExit's *)
1834 MaxAtExit = 32;
1935 Digits = "0123456789abcdef";
20- (* the signals a fault raises, and sigaction's flags SA_ONSTACK,
21- SA_RESETHAND and SA_SIGINFO, as macOS's <signal.h> has them *)
22- SigIll = 4; SigTrap = 5; SigFpe = 8; SigBus = 10; SigSegv = 11;
36+ (* the signals a fault raises, and SIGPROF, as macOS's <signal.h>
37+ has them *)
38+ SigIll = 4; SigTrap = 5; SigFpe = 8; SigBus = 10; SigSegv = 11; SigProf = 27;
39+ (* sigaction's flags: SA_ONSTACK, SA_RESETHAND and SA_SIGINFO; and
40+ for the profiler, SA_ONSTACK, SA_RESTART, so that a call a sample
41+ breaks into goes on, and SA_SIGINFO *)
2342 Flags = 1H + 4H + 40H;
43+ ProfFlags = 1H + 2H + 40H;
2444 Low = 100000000H; (* page zero: no address below this is ever mapped *)
45+ MaxSamples = 100000;
46+ MaxProcs = 8192;
47+ MaxPlaces = 65536;
48+ (* the line table's special opcodes, as the compiler makes them *)
49+ LineBase = -5;
50+ LineRange = 14;
51+ OpcodeBase = 13;
52+ Depth = 24; (* the callers noted with each sample, at most *)
53+ (* mmap's PROT_READ | PROT_WRITE and MAP_PRIVATE | MAP_ANON *)
54+ Prot = 3;
55+ Map = 1002H;
2556
2657 type
58+ (* A row of the line table: the code from address at on comes from
59+ line and column col of file, numbered from 1 *)
60+ Row = record at: UINT; file, line, col: INT; end;
61+ (* A procedure, from address start to stop, called name, and its
62+ count variables from first on; it saves the registers of its
63+ variables, bits of regs, a quadword each from saveAt in its frame *)
64+ Proc = record start, stop, name, first, count, saves: U32; saveAt: I32; end;
65+ (* A variable of a procedure, at off from its frame, shown by kind:
66+ 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address,
67+ 5 a real; plus its size times 16, and 256 if the frame holds its
68+ address, or 512 times 1 + i if it is in register i of regs *)
69+ Local = record name: U32; off: I32; kind: U32; end;
2770 (* What sigaction and sigaltstack take, as macOS lays them out *)
2871 Action = record handler: proc(sig: I32; info, ctx: ^U8); mask, flags: I32; end;
2972 Stack = record sp: ^U8; size: INT; flags: I32; end;
@@ -31,19 +74,51 @@
3174 extern proc write(fd: I32; buf: ^U8; n: UINT): INT;
3275 extern proc sigaction(sig: I32; act, old: ^U8): I32;
3376 extern proc sigaltstack(ss, old: ^U8): I32;
77+extern proc _dyld_get_image_vmaddr_slide(image: U32): INT;
78+extern proc getenv(name: ^U8): ^U8;
79+extern proc mmap(addr: ^U8; n: UINT; prot, flags, fd: I32; off: I64): ^U8;
80+extern proc setitimer(which: I32; value, old: ^U8): I32;
3481
3582 var
3683 atExits: [MaxAtExit]proc;
3784 numAtExit: INT;
3885 ending: INT; (* the status exit was given, once it has been *)
3986 cExit: proc(status: I32); (* C's exit, set first thing *)
40- placer: proc(a: UINT); (* place, set first thing, or nil under raz -s *)
41- profiler: proc; (* startProfile, set first thing, or nil *)
87+ (* Set first thing too: where the line table is in them, where the
88+ program's code starts and stops, as the compiler laid it out, the
89+ numbers of procedures and variables; the procedures and variables,
90+ and their names; and the line table, DWARF's line program. The
91+ linker makes them. *)
92+ places: ^INT;
93+ slide: UINT; (* how far dyld moved the program from where the places have it *)
4294 line: [256]U8; (* the message being made *)
95+ (* x19 to x23 in the frame being told of, where the compiler keeps a
96+ procedure's busiest variables *)
97+ regs: [5]UINT;
98+ known: BOOL; (* regs are as the code a signal stopped had them *)
99+ (* the frame record a procedure stopped at its first instruction
100+ would have made, the caller's fp and lr, made by onSignal *)
101+ unmade: [2]UINT;
43102 lineLen: INT;
44103 act: Action;
45104 alt: Stack;
46- altStack: [65536]U8; (* where the handler runs, even when the stack is full *)
105+ altStack: [65536]U8; (* where the handlers run, even when the stack is full *)
106+ (* the profile: where the program was at each sample, and how many
107+ samples fell in each procedure and at each place *)
108+ samples: [MaxSamples]UINT;
109+ (* the callers at each sample, by their return addresses: a row of
110+ Depth for each, a short one ended by 0; mapped when profiling *)
111+ chains: ^UINT;
112+ numSamples: INT;
113+ profiler: proc; (* startProfile, put here by the entry point, or nil *)
114+ (* calls, put here by the entry point, or nil under raz -s *)
115+ teller: proc(ip, bp: UINT; vars: BOOL);
116+ (* place, put here by the entry point, or nil, as teller *)
117+ placer: proc(a: UINT);
118+ procCount: [MaxProcs]INT;
119+ procTotal: [MaxProcs]INT; (* the samples each procedure was on the chain of *)
120+ placeCount: [MaxPlaces]INT;
121+ timerv: [4]INT; (* setitimer's interval and value *)
47122
48123 (* Registers p to run when the program ends by exit *)
49124 proc atExit*(p: proc): ERROR;
@@ -54,6 +129,8 @@
54129 return nil;
55130 end;
56131
132+proc profile; forward;
133+
57134 (* The status exit was given, while the procedures atExit registered
58135 run; 0 before *)
59136 proc exitStatus*: INT;
@@ -63,7 +140,7 @@
63140
64141 (* Runs the procedures registered with atExit, the last first, each
65142 taken off first so that it runs once, then ends the program with
66- status *)
143+ status, through C's exit *)
67144 proc exit*(status: INT);
68145 var p: proc;
69146 begin
@@ -85,8 +162,8 @@
85162 exit(2);
86163 end;
87164
88-(* Messages, made in line, as lib/Rt.raz makes them, one byte kept for
89- the line feed, and written by say in one piece *)
165+(* Messages, made in line, one byte kept for the line feed, and
166+ written by say in one piece *)
90167 proc put(s: []const U8);
91168 var i: INT;
92169 begin
@@ -142,37 +219,378 @@
142219 lineLen := 0;
143220 end;
144221
145-(* Puts where the code at address a is: its address, for now *)
222+(* The address the compiler laid out for the code at address a *)
223+proc linked(a: UINT): UINT;
224+begin
225+ return a - slide;
226+end;
227+
228+(* Whether a is in the program's own code, not C's *)
229+proc inCode(a: UINT): BOOL;
230+begin
231+ return (linked(a) >= UINT(places[1])) and (linked(a) < UINT(places[2]));
232+end;
233+
234+(* The names, after the procedures and variables *)
235+proc names: ^U8;
236+begin
237+ return ^U8(places + 5) + 28 * places[3] + 12 * places[4];
238+end;
239+
240+(* The line table *)
241+proc lines: ^U8;
242+begin
243+ return ^U8(places) + places[0];
244+end;
245+
246+(* The number p points at, in LEB128, unsigned, and where the next
247+ thing starts *)
248+proc uleb(p: ^U8): (INT, ^U8);
249+var n, shift: INT;
250+begin
251+ n := 0;
252+ shift := 0;
253+ while p^ >= 80H do
254+ n := n | INT(p^ & 7FH) shl shift;
255+ INC(shift, 7);
256+ p := p + 1;
257+ end;
258+ return n | INT(p^) shl shift, p + 1;
259+end;
260+
261+(* The same, signed *)
262+proc sleb(p: ^U8): (INT, ^U8);
263+var n, shift, b: INT;
264+begin
265+ n := 0;
266+ shift := 0;
267+ repeat
268+ b := INT(p^);
269+ p := p + 1;
270+ n := n | (b & 7FH) shl shift;
271+ INC(shift, 7);
272+ until b < 80H;
273+ if (shift < 64) and (b & 40H # 0) then n := n | (-1 shl shift); end; (* its sign *)
274+ return n, p;
275+end;
276+
277+(* The path of the line table's file f, as a C string: the files'
278+ names follow the table's header of 29 bytes, each ending in a zero
279+ and followed by three numbers *)
280+proc path(f: INT): ^U8;
281+var p: ^U8; i, k: INT;
282+begin
283+ p := lines() + 29;
284+ for i := 2 to f do
285+ while p^ # 0 do p := p + 1; end;
286+ p := p + 1;
287+ for k := 1 to 3 do _, p := uleb(p); end;
288+ end;
289+ return p;
290+end;
291+
292+(* The row of the line table that the code at address a, as linked,
293+ comes from, the one with the highest address up to a, and its
294+ number; or, if k >= 0, row number k. The number is -1 if there is
295+ none. As lib/Rt.raz's row, whose comment says how. *)
296+proc row(a: UINT; k: INT): (Row, INT);
297+var p, stop: ^U8; q: ^U32; at: ^UINT; r, best: Row; n, found, op, v: INT;
298+begin
299+ p := lines();
300+ q := ^U32(p);
301+ stop := p + 4 + INT(q^);
302+ q := ^U32(p + 6);
303+ p := p + 10 + INT(q^); (* the program, past the header *)
304+ r := {file: 1, line: 1};
305+ n := 0;
306+ found := -1;
307+ while p < stop do
308+ op := INT(p^);
309+ p := p + 1;
310+ if op >= OpcodeBase then
311+ op := op - OpcodeBase;
312+ r.at := r.at + UINT(op div LineRange);
313+ r.line := r.line + LineBase + op mod LineRange;
314+ op := 1;
315+ elsif op = 0 then (* extended: its length, then which *)
316+ v, p := uleb(p);
317+ if p^ = 1 then r := {file: 1, line: 1}; (* end_sequence *)
318+ elsif p^ = 2 then at := ^UINT(p + 1); r.at := at^; (* set_address *)
319+ end;
320+ p := p + v;
321+ elsif op = 2 then v, p := uleb(p); r.at := r.at + UINT(v); (* advance_pc *)
322+ elsif op = 3 then v, p := sleb(p); r.line := r.line + v; (* advance_line *)
323+ elsif op = 4 then r.file, p := uleb(p); (* set_file *)
324+ elsif op = 5 then r.col, p := uleb(p); (* set_column *)
325+ end;
326+ if op = 1 then (* copy, or a special opcode: the row r *)
327+ if n = k then return r, n; end;
328+ if (k < 0) and (r.at <= a) and ((found < 0) or (r.at >= best.at)) then
329+ best := r;
330+ found := n;
331+ end;
332+ INC(n);
333+ end;
334+ end;
335+ return best, found;
336+end;
337+
338+(* Puts where row r comes from, as file:line:col *)
339+proc putRow(r: Row);
340+begin
341+ putStr(path(r.file));
342+ put(":");
343+ putInt(r.line);
344+ put(":");
345+ putInt(r.col);
346+end;
347+
348+(* The compiler's, as fail is: puts where the code at address a comes
349+ from, as file:line:col: and a space, if a is in the program's code *)
350+proc place*(a: UINT);
351+var r: Row; n: INT;
352+begin
353+ if not inCode(a) then return; end;
354+ r, n := row(linked(a), -1);
355+ if n < 0 then return; end;
356+ putRow(r);
357+ put(": ");
358+end;
359+
360+(* Puts where the code at address a is: place, or, in a program built
361+ with raz -s, which keeps no places, the address *)
146362 proc where(a: UINT);
147363 begin
148- if placer # nil then placer(a); end;
149- put("at ");
150- putHex(a);
151- put(": ");
364+ if placer # nil then placer(a);
365+ else
366+ put("at ");
367+ putHex(a);
368+ put(": ");
369+ end;
152370 end;
153371
154-(* Where the code at address a comes from: not told yet *)
155-proc place*(a: UINT);
372+(* The frame pointer of the procedure that calls it, which a code
373+ procedure leaves as it is. Rt's code procedures are written as their
374+ words' bytes, in db, each instruction in a comment beside it: when
375+ BOOT's release builds src/, it reads this file for Rt's interface,
376+ and knows only x86-64's instructions, but db is in both assemblers.
377+ Written so until BOOT names a release that skips a code procedure
378+ in a file read for its interface. *)
379+proc framePtr: UINT;
380+code
381+ db 0E0H, 03H, 1DH, 0AAH; (* mov x0, x29 *)
382+ db 0C0H, 03H, 5FH, 0D6H; (* ret *)
383+end framePtr;
384+
385+(* The frame of the procedure that called the one calling this *)
386+proc callerFrame: UINT;
387+var q: ^UINT;
156388 begin
157- _ := a;
389+ q := ^UINT(framePtr()); (* callerFrame's own: its caller's frame is in it *)
390+ q := ^UINT(q^);
391+ return q^;
158392 end;
159393
160-(* The calls under way: not told yet *)
394+(* The procedure whose code holds address a, or nil. The places keep
395+ the low 32 bits of a procedure's start and stop; the program lies
396+ at 4 GB and up, as linked, within one stretch of 4 GB, so the low
397+ 32 bits of an address in its code are in the same order as the
398+ address. *)
399+proc procAt(a: UINT): ^Proc;
400+var p: ^Proc; i: INT;
401+begin
402+ if (places = nil) or not inCode(a) then return nil; end;
403+ p := ^Proc(places + 5);
404+ a := linked(a) & 0FFFFFFFFH;
405+ for i := 0 to places[3] - 1 do
406+ if (UINT(p[i].start) <= a) and (a < UINT(p[i].stop)) then return p + i; end;
407+ end;
408+ return nil;
409+end;
410+
411+(* x with six figures after the point, or as m e n beyond them *)
412+proc putReal(x: F64);
413+var e, i: INT; f: U64;
414+begin
415+ if x # x then put("nan"); return; end;
416+ if x < 0.0 then put("-"); x := -x; end;
417+ if (x > 1.0) and (x * 2.0 = x) then put("inf"); return; end;
418+ e := 0;
419+ while x >= 1.0E15 do x := x / 10.0; INC(e); end;
420+ while (x # 0.0) and (x < 0.001) do x := x * 10.0; DEC(e); end;
421+ f := U64(x * 1000000.0 + 0.5);
422+ putInt(INT(f div 1000000));
423+ put(".");
424+ for i := 1 to 6 do
425+ f := f mod 1000000 * 10;
426+ put(Digits[INT(f div 1000000)..INT(f div 1000000) + 1]);
427+ end;
428+ if e # 0 then put("e"); putInt(e); end;
429+end;
430+
431+(* The value of variable l of the frame at bp *)
432+proc putValue(bp: UINT; l: ^Local);
433+var a: ^U8; w: ^UINT; h: ^U16; s: ^U32; f: ^F32; d: ^F64; v: UINT; bits: INT;
434+begin
435+ a := ^U8(bp) + INT(l^.off);
436+ if l^.kind shr 9 # 0 then a := ^U8(SYSTEM.ADR(regs[INT(l^.kind shr 9) - 1])); end;
437+ w := ^UINT(a);
438+ if l^.kind & 256 # 0 then a := ^U8(w^); w := ^UINT(a); end;
439+ h := ^U16(a); s := ^U32(a); f := ^F32(a); d := ^F64(a);
440+ bits := INT(l^.kind shr 4 & 15) * 8;
441+ match bits of
442+ | 8: v := UINT(a^);
443+ | 16: v := UINT(h^);
444+ | 32: v := UINT(s^);
445+ | else: v := w^;
446+ end;
447+ match l^.kind & 15 of
448+ | 1:
449+ if (bits < 64) and (v shr (bits - 1) # 0) then putInt(INT(v) - INT(1) shl bits);
450+ else putInt(INT(v));
451+ end;
452+ | 2: putInt(INT(v));
453+ | 3: if v # 0 then put("true"); else put("false"); end;
454+ | 4: if v = 0 then put("nil"); else putHex(v); end;
455+ | else: if bits = 32 then putReal(F64(f^)); else putReal(d^); end;
456+ end;
457+end;
458+
459+(* Says that n more calls are as the one before, if there are any;
460+ the lines it takes *)
461+proc more(n: INT): INT;
462+begin
463+ if n = 0 then return 0; end;
464+ put(" and ");
465+ putInt(n);
466+ put(" more the same");
467+ say;
468+ return 1;
469+end;
470+
471+(* x19 to x23, into p[0] to p[4] *)
472+proc liveRegs(p: ^UINT);
473+code
474+ db 13H, 50H, 00H, 0A9H; (* stp x19, x20, [x0] *)
475+ db 15H, 58H, 01H, 0A9H; (* stp x21, x22, [x0, #16] *)
476+ db 17H, 10H, 00H, 0F9H; (* str x23, [x0, #32] *)
477+ db 0C0H, 03H, 5FH, 0D6H; (* ret *)
478+end liveRegs;
479+
480+(* An address in the code of the procedure that calls it: the return
481+ address, in x30 *)
482+proc here: UINT;
483+code
484+ db 0E0H, 03H, 1EH, 0AAH; (* mov x0, x30 *)
485+ db 0C0H, 03H, 5FH, 0D6H; (* ret *)
486+end here;
487+
488+(* regs as the caller of p's frame at bp left them, where p saved them *)
489+proc restore(p: ^Proc; bp: UINT);
490+var i, j: INT; q: ^UINT;
491+begin
492+ if p = nil then return; end;
493+ j := 0;
494+ for i := 0 to 4 do
495+ if p^.saves shr i & 1 # 0 then
496+ q := ^UINT(^U8(bp) + INT(p^.saveAt) + 8 * j);
497+ regs[i] := q^;
498+ INC(j);
499+ end;
500+ end;
501+end;
502+
503+(* Says the calls under way, a line each, from the one at address ip
504+ whose frame is at bp: where each is, and its variables, unless vars
505+ is false for the first. At most 20 lines; a frame that isn't the
506+ program's ends them. Calls of one procedure from one place, as in a
507+ recursion that overflowed the stack, are told once, and counted. *)
508+proc calls(ip, bp: UINT; vars: BOOL);
509+var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp, x, xip: UINT; saved: BOOL;
510+begin
511+ (* the registers as they are, then as each frame from this one out
512+ to bp's found them; or as a signal's context had them *)
513+ if not known then
514+ liveRegs(SYSTEM.ADR(regs[0]));
515+ x := framePtr();
516+ xip := here();
517+ while (x # bp) and (x & 7 = 0) and (x # 0) do
518+ restore(procAt(xip), x);
519+ q := ^UINT(x);
520+ if q[0] <= x then break; end;
521+ xip := q[1] - 4;
522+ x := q[0];
523+ end;
524+ end;
525+ saved := vars; (* not in a prologue: the frame has saved them *)
526+ n := 0;
527+ same := 0;
528+ last := nil;
529+ lastIp := 0;
530+ while n < 20 do
531+ p := procAt(ip);
532+ if p = nil then break; end;
533+ if (p = last) and (ip = lastIp) then
534+ INC(same);
535+ else
536+ n := n + more(same);
537+ same := 0;
538+ last := p;
539+ lastIp := ip;
540+ put(" in ");
541+ putStr(names() + INT(p^.name));
542+ put(" at ");
543+ where(ip);
544+ l := ^Local(^U8(places + 5) + 28 * places[3]) + INT(p^.first);
545+ if not vars or (p^.count = 0) then DEC(lineLen, 2); end; (* where's ": " *)
546+ for i := 0 to INT(p^.count) - 1 do
547+ if vars then
548+ if i > 0 then put(", "); end;
549+ putStr(names() + INT(l[i].name));
550+ put(" = ");
551+ putValue(bp, l + i);
552+ end;
553+ end;
554+ say;
555+ INC(n);
556+ vars := true;
557+ end;
558+ if saved then restore(p, bp); end;
559+ saved := true;
560+ (* each frame is above the one it called, which ends a chain gone
561+ wrong; but unmade, wherever it is, leads to the stack *)
562+ q := ^UINT(bp);
563+ if (bp & 7 # 0) or ((q[0] <= bp) and (bp # UINT(SYSTEM.ADR(unmade[0])))) then break; end;
564+ ip := q[1] - 4; (* the call, the bl before its return address *)
565+ bp := q[0];
566+ end;
567+ _ := more(same);
568+end;
569+
570+(* Says on standard error the calls under way, from the one that calls
571+ it, each with its variables, as after a failed check. *)
161572 proc trace*;
573+var q: ^UINT;
162574 begin
575+ q := ^UINT(framePtr());
576+ calls(q[1] - 4, q[0], true);
163577 end;
164578
165579 (* A check failed in the code at address at: says where, and what
166- failed, as lib/Rt.raz's fail, whose comment says what each kind is,
167- then ends the program by exit with status 2. The registers that
168- x86-64's trap report shows are none here. *)
580+ failed, then the calls under way, as lib/Rt.raz's fail, whose
581+ comment says what each kind is, then ends the program by exit with
582+ status 2. The registers that x86-64's trap report shows, rdi and
583+ rsi, are none here. *)
169584 proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);
170585 begin
171586 _ := rdi; _ := rsi;
172587 where(at);
173- if what = 4 then put("stopped by a nil pointer");
174- elsif what = 5 then put("stopped by a division fault");
175- elsif what = 6 then put("stopped by a stack overflow");
588+ if (what >= 4) and (what <= 6) then
589+ put("stopped by ");
590+ if what = 4 then put("a nil pointer");
591+ elsif what = 5 then put("a division fault");
592+ else put("a stack overflow");
593+ end;
176594 elsif what = 0 then put("index "); putInt(a);
177595 elsif what = 7 then
178596 put("a view at index "); putInt(a);
@@ -185,28 +603,36 @@
185603 end;
186604 if what < 2 then put(" is out of range for a length of "); putInt(len); end;
187605 say;
606+ if teller # nil then teller(at, callerFrame(), true); end;
188607 exit(2);
189608 end;
190609
191-(* A fault stops the program: says where it was and why on standard
192- error, then ends it by exit with status 2, as a failed check does.
193- info and ctx are the kernel's siginfo and ucontext: the address that
194- faulted is at 24 in siginfo, and the registers at uc_mcontext, a
195- pointer at 48 in ucontext, past 16 bytes of the exception's state:
196- x0 to x28, then fp, lr, sp and pc. *)
610+(* A fault stops the program: says where it was and why, and the calls
611+ under way, on standard error, then ends it by exit with status 2, as
612+ a failed check does. info and ctx are the kernel's siginfo and
613+ ucontext: the address that faulted is at 24 in siginfo, and the
614+ registers at uc_mcontext, a pointer at 48 in ucontext, past the 16
615+ bytes of the exception's state: x0 to x28, then fp, lr, sp and pc.
616+ A stack overflow can stop a procedure at its first instruction, the
617+ stp that makes its frame record: it has no frame yet, so the calls
618+ are told from one made of the fp and lr it found, unmade. *)
197619 proc onSignal(sig: I32; info, ctx: ^U8);
198-var adr, sp, pc: UINT; q: ^UINT; why: []const U8;
620+var adr, sp, pc, fp, lr: UINT; q: ^UINT; p: ^Proc; why: []const U8;
199621 begin
200622 q := ^UINT(info + 24);
201623 adr := q^;
202624 q := ^UINT(ctx + 48);
203625 q := ^UINT(q^ + 16);
626+ regs := [q[19], q[20], q[21], q[22], q[23]];
627+ known := true;
628+ fp := q[29];
629+ lr := q[30];
204630 sp := q[31];
205631 pc := q[32];
206632 if sig = SigFpe then why := "a division fault";
207633 elsif pc < Low then
208634 why := "a nil procedure";
209- pc := q[30] - 4; (* the call, by its return address in lr *)
635+ pc := lr - 4; (* the call, by its return address *)
210636 elsif adr < Low then why := "a nil pointer";
211637 elsif adr - sp + 100000H < 200000H then why := "a stack overflow"; (* within a megabyte of sp *)
212638 elsif (sig = SigIll) or (sig = SigTrap) then why := "a trap";
@@ -216,16 +642,161 @@
216642 put("stopped by ");
217643 put(why);
218644 say;
645+ if teller # nil then
646+ p := procAt(pc);
647+ if (p # nil) and (linked(pc) & 0FFFFFFFFH = UINT(p^.start)) then
648+ unmade := [fp, lr];
649+ fp := UINT(SYSTEM.ADR(unmade[0]));
650+ end;
651+ (* the variables of a frame the stack overflowed in may be past it *)
652+ teller(pc, fp, why # "a stack overflow");
653+ end;
219654 exit(2);
220655 end;
221656
222-(* The profiler: none yet *)
657+(* SIGPROF, every millisecond the program runs, in any of its threads:
658+ notes where it was, and the calls under way, up the chain of frames.
659+ The chain is followed only through the program's own code, whose
660+ frames all keep it in x29: C's code may not. *)
661+proc onProf(_sig: I32; _info, ctx: ^U8);
662+var n, k: INT; q, f, row: ^UINT; ip, bp: UINT;
663+begin
664+ n := XADD(numSamples, 1);
665+ if n >= MaxSamples then return; end;
666+ q := ^UINT(ctx + 48);
667+ q := ^UINT(q^ + 16);
668+ bp := q[29];
669+ ip := q[32];
670+ samples[n] := ip;
671+ row := chains + n * Depth;
672+ k := 0;
673+ if (places # nil) and inCode(ip) then
674+ while (k < Depth) and (bp # 0) and (bp & 7 = 0) do
675+ f := ^UINT(bp);
676+ if not inCode(f[1]) then break; end;
677+ row[k] := f[1] - 4; (* the call, by its return address *)
678+ INC(k);
679+ if f[0] <= bp then break; end;
680+ bp := f[0];
681+ end;
682+ end;
683+ if k < Depth then row[k] := 0; end;
684+end;
685+
686+(* The number of the procedure the code at address a is in, or -1 *)
687+proc procNum(a: UINT): INT;
688+var p: ^Proc;
689+begin
690+ p := procAt(a);
691+ if p = nil then return -1; end;
692+ return p - ^Proc(places + 5);
693+end;
694+
695+(* The number of the line table's row the code at address a comes
696+ from, or -1 *)
697+proc placeAt(a: UINT): INT;
698+var n: INT;
699+begin
700+ if not inCode(a) then return -1; end;
701+ _, n := row(linked(a), -1);
702+ return n;
703+end;
704+
705+(* Puts the share of n that k is, as a percentage four wide *)
706+proc putShare(k, n: INT);
707+var i: INT;
708+begin
709+ i := k * 100 div n;
710+ if i < 10 then put(" "); elsif i < 100 then put(" "); else put(" "); end;
711+ putInt(i);
712+ put("%");
713+end;
714+
715+(* Says the ten that took most of count's n samples, by name, with
716+ their totals beside them if total isn't empty *)
717+proc top(count: []INT; total: []const INT; n: INT; byPlace: BOOL);
718+var i, k, best: INT; p: ^Proc; r: Row;
719+begin
720+ p := ^Proc(places + 5);
721+ for k := 1 to 10 do
722+ best := 0;
723+ for i := 1 to LEN(count) - 1 do
724+ if count[i] > count[best] then best := i; end;
725+ end;
726+ if count[best] = 0 then return; end;
727+ putShare(count[best], n);
728+ if LEN(total) > 0 then put(" "); putShare(total[best], n); end;
729+ put(" ");
730+ if byPlace then
731+ r, _ := row(0, best);
732+ putRow(r);
733+ else putStr(names() + INT(p[best].name));
734+ end;
735+ say;
736+ count[best] := 0;
737+ end;
738+end;
739+
740+(* The compiler's, as fail is: if RAZ_PROFILE is set, samples the
741+ program every millisecond of its time, and says at its end what took
742+ it (profile) *)
223743 proc startProfile*;
744+var e: ^U8; pa: Action;
224745 begin
746+ e := getenv(SYSTEM.PTR("RAZ_PROFILE\0"));
747+ if (e = nil) or (e^ = 0) then return; end;
748+ chains := ^UINT(mmap(nil, UINT(MaxSamples * Depth * SIZE(UINT)), Prot, Map, -1, 0));
749+ if INT(chains) = -1 then chains := nil; return; end;
750+ pa := {handler: onProf, flags: ProfFlags};
751+ _ := sigaction(SigProf, ^U8(SYSTEM.ADR(pa)), nil);
752+ timerv := [0, 1000, 0, 1000]; (* every millisecond, from one on *)
753+ _ := setitimer(2, ^U8(SYSTEM.ADR(timerv)), nil); (* ITIMER_PROF *)
754+ _ := atExit(profile);
225755 end;
226756
757+(* At the end of a profiled run: which procedures, and which places in
758+ the source, took the time, as shares of the samples *)
759+proc profile;
760+var t: [4]INT; i, n, k, j, m, s: INT; seen: [Depth + 1]INT; row: ^UINT;
227761 begin
228- _ := profiler; (* started here when RAZ_PROFILE is set, by step 7's Rt *)
762+ t := [0, 0, 0, 0];
763+ _ := setitimer(2, ^U8(SYSTEM.ADR(t)), nil); (* no more *)
764+ n := numSamples;
765+ if n > MaxSamples then n := MaxSamples; end;
766+ if (places = nil) or (n = 0) then return; end;
767+ for i := 0 to n - 1 do
768+ k := procNum(samples[i]);
769+ if (k >= 0) and (k < MaxProcs) then INC(procCount[k]); end;
770+ (* each procedure on the sample's chain counts once in its
771+ total, however often it is there *)
772+ row := chains + i * Depth;
773+ m := 0;
774+ for j := -1 to Depth - 1 do
775+ if j < 0 then k := procNum(samples[i]);
776+ elsif row[j] = 0 then break;
777+ else k := procNum(row[j]);
778+ end;
779+ if (k >= 0) and (k < MaxProcs) then
780+ s := 0;
781+ while (s < m) and (seen[s] # k) do INC(s); end;
782+ if s = m then seen[m] := k; INC(m); INC(procTotal[k]); end;
783+ end;
784+ end;
785+ k := placeAt(samples[i]);
786+ if (k >= 0) and (k < MaxPlaces) then INC(placeCount[k]); end;
787+ end;
788+ put("profile: ");
789+ putInt(n);
790+ put(" samples of a millisecond; each procedure's own, then with its calls'");
791+ say;
792+ top(procCount[0..places[3]], procTotal[0..places[3]], n, false);
793+ put("by place:");
794+ say;
795+ top(placeCount, placeCount[0..0], n, true);
796+end;
797+
798+begin
799+ slide := UINT(_dyld_get_image_vmaddr_slide(0)); (* image 0 is the program *)
229800 alt := {sp: SYSTEM.ADR(altStack[0]), size: LEN(altStack)};
230801 _ := sigaltstack(^U8(SYSTEM.ADR(alt)), nil);
231802 act := {handler: onSignal, flags: Flags};
@@ -234,4 +805,5 @@
234805 _ := sigaction(SigFpe, ^U8(SYSTEM.ADR(act)), nil);
235806 _ := sigaction(SigIll, ^U8(SYSTEM.ADR(act)), nil);
236807 _ := sigaction(SigTrap, ^U8(SYSTEM.ADR(act)), nil);
808+ if profiler # nil then profiler(); end;
237809 end Rt.

lib/Sys.raz (history) modified +124 -50

@@ -8,12 +8,15 @@
88 two procedures whose names differ, it takes from CAbi, one file per
99 target, which tools/cabi.c writes; so a struct the C library fills
1010 in or reads is bytes here, its fields read and written at CAbi's
11- offsets by field and setField. A failure is minus Linux's errno, on
11+ offsets by field and setField. So do the calls that Linux's C
12+ library has and another system's lacks (pipe2, accept4, getrandom,
13+ memfd_create, clock_nanosleep, sched_getaffinity, SO_PEERCRED), which
14+ CAbi makes there of what it has. A flag CAbi gives as 0, that system
15+ lacking it, is done after: a socket closed on exec by keepOnExec. A failure is minus Linux's errno, on
1216 every target: linux maps the C library's, and errorText maps back.
1317 A terminal's modes, Mode, are its struct termios whole, which cabi
14- checks fits in 256 bytes. Still Linux's: memfd_create, getrandom,
15- pipe2 and accept4, which glibc and musl have, and what a wait
16- status holds, which every Unix encodes alike. *)
18+ checks fits in 256 bytes. Still Linux's: what a wait status holds,
19+ which every Unix encodes alike. *)
1720 module Sys;
1821 import C, CAbi;
1922 import SYSTEM;
@@ -131,6 +134,8 @@
131134 end;
132135
133136 Winsize = record rows, cols, xpixel, ypixel: U16; end;
137+ (* A pseudo-terminal's terminal, tty, opened and held for pty *)
138+ Held = record pty, tty: INT; end;
134139 Pollfd = record fd: I32; events, revents: I16; end;
135140
136141 (* a socket's address, struct sockaddr_storage, which holds any:
@@ -166,6 +171,12 @@
166171 sigRead, sigWrite: I32; (* the pipe the handler of caught signals writes their numbers to, once open *)
167172 noted: [CAbi.sigMax + 1]INT; (* 1 at sig when a signal handle took has come, until came asks *)
168173 broke: INT; (* 1 when one has come since a call that ready or readyFor makes again began *)
174+ (* On macOS, where the controlling side of a pseudo-terminal takes
175+ no modes and no size until its terminal is opened, and reads an
176+ end once it has been and is closed again, openPty opens the
177+ terminal and holds it, until spawn's child takes it over or the
178+ pty is closed (CAbi.ptyHeld). A pty of 0 or less is none. *)
179+ held: [16]Held;
169180
170181 (* err, minus an errno of the C library's, as minus Linux's errno of
171182 the same name; err itself if it has none *)
@@ -374,8 +385,11 @@
374385 end;
375386
376387 (* Closes the file descriptor fd. *)
388+proc release(pty: INT); forward;
389+
377390 proc close*(fd: INT);
378391 begin
392+ if CAbi.ptyHeld = 1 then release(fd); end;
379393 _ := C.close(I32(fd));
380394 end;
381395
@@ -387,6 +401,7 @@
387401 closed again, after -4 (EINTR) too. *)
388402 proc closeChecked*(fd: INT): INT;
389403 begin
404+ if CAbi.ptyHeld = 1 then release(fd); end;
390405 if C.close(I32(fd)) # 0 then return failed(); end;
391406 return 0;
392407 end;
@@ -456,10 +471,9 @@
456471 (* A file in memory, with no name, of size zeroed bytes: its fd, or
457472 minus an errno. It is closed in a program exec starts. *)
458473 proc memFile*(size: INT): INT;
459-var name: [4]U8; fd: I32; err: INT;
474+var fd: I32; err: INT;
460475 begin
461- _ := cstr("raz", name); (* the name /proc shows *)
462- fd := C.memfd_create(SYSTEM.ADR(name[0]), CAbi.mfdCloexec);
476+ fd := CAbi.memFile();
463477 if fd < 0 then return failed(); end;
464478 if C.ftruncate(fd, I64(size)) # 0 then
465479 err := failed(); (* before close can change errno *)
@@ -854,8 +868,7 @@
854868 begin
855869 at := clock() + I64(ms) * 1000000;
856870 t := {sec: at div 1000000000, nsec: at mod 1000000000};
857- (* until t, again after EINTR, which it returns, the C library's *)
858- repeat until C.clock_nanosleep(CAbi.clockMonotonic, CAbi.timerAbstime, ^U8(SYSTEM.ADR(t)), nil) # CAbi.eIntr;
871+ CAbi.sleepUntil(^U8(SYSTEM.ADR(t)));
859872 end;
860873
861874 (* Ends the program: random bytes can't be faked. *)
@@ -874,7 +887,7 @@
874887 begin
875888 n := 0;
876889 while n < LEN(b) do (* a signal may cut it short *)
877- r := C.getrandom(SYSTEM.ADR(b[n]), UINT(LEN(b) - n), 0);
890+ r := CAbi.random(SYSTEM.ADR(b[n]), UINT(LEN(b) - n));
878891 if r > 0 then INC(n, r);
879892 elsif (r >= 0) or (failed() # errIntr) then noRandom(); (* r = 0 can't be, and is no progress *)
880893 end;
@@ -890,6 +903,7 @@
890903 begin
891904 fd := C.socket(I32(family), I32(kind) | CAbi.sockCloexec, 0);
892905 if fd < 0 then return failed(); end;
906+ if CAbi.sockCloexec = 0 then _ := keepOnExec(INT(fd), false); end;
893907 if serving then
894908 one := 1; (* so that a server can start again at once *)
895909 _ := C.setsockopt(fd, CAbi.solSocket, CAbi.soReuseaddr, ^U8(SYSTEM.ADR(one)), 4);
@@ -925,11 +939,13 @@
925939 (* path as a Unix socket's address in a, and the address's length, or
926940 -36 (ENAMETOOLONG) if it is too long. A path that starts with a zero
927941 byte is one of Linux's abstract names, which has no file and no
928- trailing zero: its length ends with the name's. *)
942+ trailing zero: its length ends with the name's; on a system that has
943+ none, -22 (EINVAL). *)
929944 proc unixAddr(path: []const U8; a: ^Sockaddr): INT;
930945 var p: ^U8;
931946 begin
932947 if LEN(path) >= CAbi.sunPathLen then return -36; end;
948+ if (LEN(path) > 0) and (path[0] = 0) and (CAbi.unixAbstract = 0) then return -22; end;
933949 p := ^U8(a);
934950 setFamily(p, CAbi.afUnix, CAbi.sockaddrUnLen);
935951 COPY(p[CAbi.sunPathAt..CAbi.sunPathAt + LEN(path)], path);
@@ -1035,7 +1051,7 @@
10351051 proc accept*(fd: INT): INT;
10361052 var r: I32;
10371053 begin
1038- r := C.accept4(I32(fd), nil, nil, CAbi.sockCloexec);
1054+ r := CAbi.accepted(I32(fd));
10391055 if r < 0 then return failed(); end;
10401056 return INT(r);
10411057 end;
@@ -1052,20 +1068,15 @@
10521068 (* Who is at the other end of the connected socket fd, and 0; or minus
10531069 an errno. *)
10541070 proc peer*(fd: INT): (Remote, INT);
1055-var r: Remote; a: Sockaddr; size, credSize: U32; cred: [CAbi.ucUidAt + CAbi.ucUidLen]U8; p: ^U8;
1071+var r: Remote; a: Sockaddr; size: U32; p: ^U8;
10561072 begin
10571073 r := {unix: false, ipv6: false};
10581074 size := U32(SIZE(Sockaddr));
10591075 p := ^U8(SYSTEM.ADR(a));
10601076 if C.getpeername(I32(fd), p, SYSTEM.ADR(size)) # 0 then return r, failed(); end;
10611077 if familyOf(p) = CAbi.afUnix then (* ask who made the connection *)
1062- credSize := U32(LEN(cred));
1063- if C.getsockopt(I32(fd), CAbi.solSocket, CAbi.soPeercred, SYSTEM.ADR(cred[0]), SYSTEM.ADR(credSize)) # 0 then
1064- return r, failed();
1065- end;
1078+ if CAbi.peer(I32(fd), r.pid, r.uid) # 0 then return r, failed(); end;
10661079 r.unix := true;
1067- r.pid := INT(field(SYSTEM.ADR(cred[0]), CAbi.ucPidAt, CAbi.ucPidLen));
1068- r.uid := INT(field(SYSTEM.ADR(cred[0]), CAbi.ucUidAt, CAbi.ucUidLen));
10691080 else
10701081 r.port := portOf(p);
10711082 if familyOf(p) = CAbi.afInet6 then
@@ -1087,6 +1098,10 @@
10871098 if C.socketpair(CAbi.afUnix, CAbi.sockStream | CAbi.sockCloexec, 0, SYSTEM.ADR(fds[0])) # 0 then
10881099 return -1, -1, failed();
10891100 end;
1101+ if CAbi.sockCloexec = 0 then
1102+ _ := keepOnExec(INT(fds[0]), false);
1103+ _ := keepOnExec(INT(fds[1]), false);
1104+ end;
10901105 return INT(fds[0]), INT(fds[1]), 0;
10911106 end;
10921107
@@ -1108,7 +1123,7 @@
11081123 var r: INT;
11091124 begin
11101125 if LEN(s) = 0 then return 0; end;
1111- r := C.send(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)), CAbi.msgNosignal | CAbi.msgDontwait);
1126+ r := CAbi.sendNow(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)));
11121127 if r < 0 then return failed(); end;
11131128 return r;
11141129 end;
@@ -1222,6 +1237,8 @@
12221237 if size = 0 then return -22; end;
12231238 fd := C.socket(I32(familyOf(^U8(SYSTEM.ADR(a)))), CAbi.sockStream | CAbi.sockCloexec | CAbi.sockNonblock, 0);
12241239 if fd < 0 then return failed(); end;
1240+ if CAbi.sockCloexec = 0 then _ := keepOnExec(INT(fd), false); end;
1241+ if CAbi.sockNonblock = 0 then _ := setBlocking(INT(fd), false); end;
12251242 r := 0;
12261243 if C.connect(fd, ^U8(SYSTEM.ADR(a)), U32(size)) # 0 then r := failed(); end;
12271244 if r = -115 then (* EINPROGRESS *)
@@ -1326,6 +1343,7 @@
13261343 for i := 0 to (size - CAbi.cmsgDataAt) div 4 - 1 do
13271344 if k < LEN(fds) then
13281345 fds[k] := INT(got[i]);
1346+ if CAbi.msgCmsgCloexec = 0 then _ := keepOnExec(fds[k], false); end;
13291347 INC(k);
13301348 else
13311349 _ := C.close(got[i]);
@@ -1409,11 +1427,13 @@
14091427 return 0;
14101428 end;
14111429
1430+proc ptyName(fd: INT; name: []U8): INT; forward;
1431+
14121432 (* A pseudo-terminal: the file descriptor of its controlling side, or
14131433 minus an errno. Its other side, the terminal its programs run on, is
14141434 unlocked, for spawn to open. *)
14151435 proc openPty*: INT;
1416-var fd: I32; err: INT;
1436+var fd, t: I32; err, i, k: INT; name: [256]U8;
14171437 begin
14181438 fd := C.posix_openpt(CAbi.oRdwr | CAbi.oNoctty);
14191439 if fd < 0 then return failed(); end;
@@ -1422,9 +1442,45 @@
14221442 _ := C.close(fd);
14231443 return err;
14241444 end;
1445+ if CAbi.ptyHeld = 1 then (* macOS: its terminal held (held) *)
1446+ release(INT(fd)); (* one an fd closed since had *)
1447+ k := -1;
1448+ for i := 0 to LEN(held) - 1 do
1449+ if (held[i].pty <= 0) and (k < 0) then k := i; end;
1450+ end;
1451+ err := -24; (* EMFILE: none free *)
1452+ if k >= 0 then err := ptyName(INT(fd), name); end;
1453+ if err = 0 then
1454+ t := C.open(SYSTEM.ADR(name[0]), CAbi.oRdwr | CAbi.oNoctty | CAbi.oCloexec);
1455+ if t < 0 then err := failed(); else held[k] := {pty: INT(fd), tty: INT(t)}; end;
1456+ end;
1457+ if err # 0 then _ := C.close(fd); return err; end;
1458+ end;
14251459 return INT(fd);
14261460 end;
14271461
1462+(* The terminal openPty holds for pty, or -1 *)
1463+proc heldTty(pty: INT): INT;
1464+var i: INT;
1465+begin
1466+ for i := 0 to LEN(held) - 1 do
1467+ if held[i].pty = pty then return held[i].tty; end;
1468+ end;
1469+ return -1;
1470+end;
1471+
1472+(* The terminal openPty holds for pty, if any, closed *)
1473+proc release(pty: INT);
1474+var i: INT;
1475+begin
1476+ for i := 0 to LEN(held) - 1 do
1477+ if held[i].pty = pty then
1478+ _ := C.close(I32(held[i].tty));
1479+ held[i].pty := -1;
1480+ end;
1481+ end;
1482+end;
1483+
14281484 (* Tells the terminal of the pseudo-terminal fd that it has cols
14291485 columns and rows rows: 0, or minus an errno. *)
14301486 proc setTermSize*(fd, cols, rows: INT): INT;
@@ -1515,7 +1571,7 @@
15151571 proc pipe*: (INT, INT);
15161572 var fds: [2]I32;
15171573 begin
1518- if C.pipe2(SYSTEM.ADR(fds[0]), CAbi.oCloexec) # 0 then return failed(), -1; end;
1574+ if CAbi.makePipe(SYSTEM.ADR(fds[0]), CAbi.oCloexec) # 0 then return failed(), -1; end;
15191575 return INT(fds[0]), INT(fds[1]);
15201576 end;
15211577
@@ -1552,16 +1608,9 @@
15521608
15531609 (* The number of processors this program may run on, at least 1. *)
15541610 proc processors*: INT;
1555-var mask: [1024]U8; i, b, count: INT;
1611+var count: INT;
15561612 begin
1557- for i := 0 to LEN(mask) - 1 do mask[i] := 0; end; (* the C library fills in as many bytes as the system has processors' bits *)
1558- if C.sched_getaffinity(0, UINT(LEN(mask)), SYSTEM.ADR(mask[0])) # 0 then return 1; end;
1559- count := 0;
1560- for i := 0 to LEN(mask) - 1 do
1561- for b := 0 to 7 do
1562- if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end;
1563- end;
1564- end;
1613+ count := CAbi.processors();
15651614 if count < 1 then return 1; end;
15661615 return count;
15671616 end;
@@ -1776,7 +1825,8 @@
17761825 begin
17771826 if p.tty # 0 then
17781827 _ := C.setsid();
1779- fd := C.open(SYSTEM.PTR(name), CAbi.oRdwr);
1828+ fd := I32(heldTty(p.tty)); (* the terminal openPty holds, on macOS *)
1829+ if fd < 0 then fd := C.open(SYSTEM.PTR(name), CAbi.oRdwr); end;
17801830 if fd < 0 then return failed(); end;
17811831 if C.ioctl(fd, CAbi.tiocsctty, 0) # 0 then return failed(); end;
17821832 for i := 0 to 2 do _ := C.dup2(fd, I32(i)); end;
@@ -1855,6 +1905,9 @@
18551905 C._exit(127);
18561906 end;
18571907 err := failed();
1908+ if (pid > 0) and (p.tty # 0) and (CAbi.ptyHeld = 1) then
1909+ release(p.tty); (* the child holds the terminal now *)
1910+ end;
18581911 if (pid > 0) and (p.tty = 0) then
18591912 (* as the program does, for whichever of the two runs first *)
18601913 g := p.group;
@@ -1946,7 +1999,10 @@
19461999 proc waitFor(pid: INT; options: I32): (INT, Status, INT);
19472000 var status, r: I32;
19482001 begin
1949- r := C.waitpid(I32(pid), SYSTEM.ADR(status), options);
2002+ (* again after EINTR, unless a signal handle took broke in: macOS
2003+ breaks into a wait for a SIGCHLD that nothing catches *)
2004+ _ := XCHG(broke, 0);
2005+ repeat r := C.waitpid(I32(pid), SYSTEM.ADR(status), options); until (r >= 0) or not again();
19502006 if r < 0 then return failed(), running, 0; end;
19512007 if r = 0 then return 0, running, 0; end;
19522008 if status & 7FH = 0 then return INT(r), exited, INT(status) shr 8 & 0FFH; end;
@@ -2025,7 +2081,7 @@
20252081 if not takable(sigs[i]) then return -22; end; (* EINVAL *)
20262082 end;
20272083 if sigWrite = 0 then
2028- if C.pipe2(SYSTEM.ADR(fds[0]), CAbi.oNonblock | CAbi.oCloexec) # 0 then return failed(); end;
2084+ if CAbi.makePipe(SYSTEM.ADR(fds[0]), CAbi.oNonblock | CAbi.oCloexec) # 0 then return failed(); end;
20292085 sigRead := fds[0];
20302086 sigWrite := fds[1];
20312087 end;
@@ -2165,8 +2221,9 @@
21652221
21662222 r, w := pipe();
21672223 if w < 0 then exit(2); end;
2224+ (* in /usr, which is no link, on macOS too, where /tmp is one *)
21682225 child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo $X $HOME; pwd"], env: ["X=x"], onlyEnv: true,
2169- dir: "/tmp", fds: [0, w, 0]});
2226+ dir: "/usr", fds: [0, w, 0]});
21702227 close(w);
21712228 n := 0;
21722229 repeat
@@ -2174,7 +2231,7 @@
21742231 if m > 0 then INC(n, m); end;
21752232 until m <= 0;
21762233 close(r);
2177- if buf[0..n] # "x\n/tmp\n" then exit(2); end;
2234+ if buf[0..n] # "x\n/usr\n" then exit(2); end;
21782235 r, st, c := wait(child, true);
21792236 if (r # child) or (st # exited) or (c # 0) then exit(2); end;
21802237
@@ -2252,8 +2309,10 @@
22522309 if m > 0 then INC(n, m); end;
22532310 until m <= 0;
22542311 close(r);
2255- r, st, c := waitExit(child);
2312+ (* the pty closed first: macOS's last close of a terminal, the
2313+ child's at its exit, waits until what was written to it is read *)
22562314 close(pty);
2315+ r, st, c := waitExit(child);
22572316 if (buf[0..n] # "out\n") or (r # child) or (st # exited) or (c # 0) then exit(2); end;
22582317
22592318 sigs := catch([sigChld, sigHup]);
@@ -2280,7 +2339,7 @@
22802339 proc testShell;
22812340 var
22822341 r, w, fd, n, k, child, c, err, pty, sigs, mask, parent: INT; t: I64; st: Status; buf: [64]U8;
2283- m, raw: Mode; soft, hard, s2, h2, user, system: I64; e: []const U8; ok, path: BOOL;
2342+ m, raw, back: Mode; soft, hard, s2, h2, user, system: I64; e: []const U8; ok, path: BOOL;
22842343 begin
22852344 r, w := pipe();
22862345 if w < 0 then exit(2); end;
@@ -2331,8 +2390,11 @@
23312390 if (err # 0) or not rawMode(pty) then exit(2); end;
23322391 raw, err := getMode(pty);
23332392 if (err # 0) or (raw.t = m.t) or (setMode(pty, m) # 0) then exit(2); end;
2334- raw, err := getMode(pty);
2335- if (err # 0) or (raw.t # m.t) then exit(2); end;
2393+ (* not raw again, and as it was, but for what the system notes
2394+ itself, as macOS's PENDIN after raw mode *)
2395+ back, err := getMode(pty);
2396+ if (err # 0) or (back.t = raw.t) then exit(2); end;
2397+ if (CAbi.ptyHeld = 0) and (back.t # m.t) then exit(2); end;
23362398 m, err := getMode(-1);
23372399 if err # -9 then exit(2); end; (* EBADF *)
23382400 r, w := pipe();
@@ -2578,15 +2640,16 @@
25782640 munmap(p, 5);
25792641 close(fd);
25802642 _ := remove("/tmp/raz-sys-map");
2581- p := mmap(8192);
2643+ (* by 16 KB, a page of arm64 macOS's and four of x86-64's *)
2644+ p := mmap(32768);
25822645 if p = nil then exit(2); end;
25832646 p[0] := 1;
2584- q := p + 4096;
2585- if (protect(q, 4096, true, false) # 0) or (q[0] # 0) then exit(2); end;
2586- if protect(q, 4096, true, true) # 0 then exit(2); end;
2647+ q := p + 16384;
2648+ if (protect(q, 16384, true, false) # 0) or (q[0] # 0) then exit(2); end;
2649+ if protect(q, 16384, true, true) # 0 then exit(2); end;
25872650 q[0] := 2;
2588- if (protect(p, 4096, false, false) # 0) or (protect(p, 4096, true, true) # 0) or (p[0] # 1) then exit(2); end; (* its bytes stay *)
2589- munmap(p, 8192);
2651+ if (protect(p, 16384, false, false) # 0) or (protect(p, 16384, true, true) # 0) or (p[0] # 1) then exit(2); end; (* its bytes stay *)
2652+ munmap(p, 32768);
25902653 end;
25912654
25922655 (* poll over 100 socket pairs with a byte sent on three, so that all
@@ -2624,6 +2687,10 @@
26242687 nm[0] := 0; (* an abstract name: a zero byte, then 17 *)
26252688 COPY(nm[1..18], "raz-abstract-test");
26262689 l := listen(nm);
2690+ if CAbi.unixAbstract = 0 then (* not Linux: none *)
2691+ if (l # -22) or (connect(nm) # -22) then exit(2); end;
2692+ return;
2693+ end;
26272694 c := connect(nm);
26282695 if (l < 0) or (c < 0) or (readyOf([c, l], 1000) # l) then exit(2); end;
26292696 s := accept(l);
@@ -2752,7 +2819,9 @@
27522819 if (i.mtime # -1500000000) or (i.seconds # -2) then exit(2); end;
27532820 if setTime("/tmp/raz-sys-dir/h", 10413792000, 0) # 0 then exit(2); end; (* 2300, past mtime's reach *)
27542821 i, err := info("/tmp/raz-sys-dir/h");
2755- if i.seconds # 10413792000 then exit(2); end;
2822+ (* exact, or, where the file system keeps no time past 2262, as
2823+ APFS, which holds nanoseconds in 64 bits, its last second *)
2824+ if (i.seconds # 10413792000) and (i.seconds # 9223372036) then exit(2); end;
27562825 if setTime("/tmp/raz-sys-dir/h", 0, 1000000000) # -22 then exit(2); end;
27572826 if setTime("/no/such/file", 0, 0) # -2 then exit(2); end;
27582827 (* the special bits: set-user-id by chmod, and sticky by makeDirMode *)
@@ -2761,7 +2830,11 @@
27612830 if (i.mode # 1EDH) or (i.special # 800H) then exit(2); end;
27622831 if makeDirMode("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end;
27632832 i, err := info("/tmp/raz-sys-dir/m");
2764- if (err # 0) or not i.dir or (i.mode # 1C0H) or (i.special # 200H) then exit(2); end;
2833+ (* Linux gives it sticky, macOS doesn't, and chmod does *)
2834+ if (err # 0) or not i.dir or (i.mode # 1C0H) or (i.special & ~200H # 0) then exit(2); end;
2835+ if chmod("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end;
2836+ i, err := info("/tmp/raz-sys-dir/m");
2837+ if (err # 0) or (i.special # 200H) then exit(2); end;
27652838 if removeDir("/tmp/raz-sys-dir/m") # 0 then exit(2); end;
27662839 _ := remove("/tmp/raz-sys-dir/h");
27672840 fd := openMode("/tmp/raz-sys-dir/h", {writing, creating}, 1C0H); (* rwx------ *)
@@ -2792,8 +2865,9 @@
27922865 (* the environment set: refused, added, set again, grown past its first array *)
27932866 if (setEnv("", "x") # -22) or (setEnv("A=B", "x") # -22) or (setEnv("A", "\x00") # -22) then exit(2); end;
27942867 if (setEnv("RAZ_SYS_TEST", "one") # 0) or (env("RAZ_SYS_TEST") # "one") then exit(2); end;
2795- name := env("RAZ_SYS_TEST");
2796- if (setEnv("RAZ_SYS_TEST", "") # 0) or (env("RAZ_SYS_TEST") # "") or (name # "one") then exit(2); end;
2868+ (* what env gave before may be gone now: macOS's setenv writes the
2869+ new value over the old where it fits *)
2870+ if (setEnv("RAZ_SYS_TEST", "") # 0) or (env("RAZ_SYS_TEST") # "") then exit(2); end;
27972871 buf := "RAZ_SYS_TEST_..";
27982872 for k := 0 to 99 do
27992873 buf[13] := U8('0' + k div 10);

lib/Thread.darwin.raz (history) added +192 -0

@@ -0,0 +1,192 @@
1+(* Threads, for macOS, with Thread.linux-x86_64.raz's interface: made
2+ by C's pthread_create, as every program on a Mac uses C. The
3+ compiler's entry point finds cCreate and cJoin by name and stores
4+ C's pthread_create and pthread_join in them, as on Linux in a
5+ program that uses C. Each thread runs on C's stack, of Stack bytes
6+ asked for, below which C keeps a page that can't be touched, so
7+ that running off the stack stops the program rather than spoiling
8+ what lies below; beside it, in a mapping of Thread's own, a little
9+ stack for Rt's signal handlers, so that they can say so, and the
10+ Thread.
11+
12+ A Mutex is os_unfair_lock, macOS's lock whose waiters sleep in the
13+ kernel, the plainest it supports: __ulock_wait and __ulock_wake,
14+ which it is made of, a futex's twins, are not for programs, and
15+ pthread_mutex_t needs its initializer. As os_unfair_lock asks, the
16+ thread that takes a Mutex gives it up; one that gives up another
17+ thread's stops the program.
18+
19+ Depends on Sys and Rt, and Check for its test. *)
20+module Thread;
21+import Sys, Rt, Check;
22+import SYSTEM;
23+
24+const
25+ Failed*: ERROR = "can't start a thread";
26+ Stack = 1 shl 20; (* each thread's, as on Linux without C *)
27+ Alt = 65536; (* the signal handlers' stack, more than macOS's least, MINSIGSTKSZ *)
28+ Page = 16384; (* arm64 macOS's *)
29+
30+type
31+ (* A thread, as spawn gives it, until join. *)
32+ Thread* = record
33+ tid: UINT; (* C's pthread_t *)
34+ ended: INT; (* 1 once its procedure has returned *)
35+ base: ^U8; (* the mapping it is in, the handlers' stack first *)
36+ size: INT;
37+ fn: proc(arg: ^U8); (* what it runs, and with what *)
38+ arg: ^U8;
39+ end;
40+ (* What sigaltstack takes, as macOS lays it out *)
41+ AltStack = record sp: ^U8; size: INT; flags: I32; end;
42+ (* A lock whose waiters sleep, free when zeroed: an os_unfair_lock *)
43+ Mutex* = record lock: U32; end;
44+
45+extern proc pthread_attr_init(attr: ^U8): I32;
46+extern proc pthread_attr_setstacksize(attr: ^U8; size: UINT): I32;
47+extern proc pthread_attr_destroy(attr: ^U8): I32;
48+extern proc pthread_kill(t: UINT; sig: I32): I32;
49+extern proc sigaltstack(ss, old: ^U8): I32;
50+extern proc os_unfair_lock_lock(lock: ^U32);
51+extern proc os_unfair_lock_unlock(lock: ^U32);
52+
53+var
54+ (* C's pthread_create and pthread_join, given by the entry point *)
55+ cCreate: proc(t: ^UINT; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32;
56+ cJoin: proc(t: UINT; result: ^^U8): I32;
57+
58+(* Where a new thread starts, as pthread_create calls it: the signal
59+ handlers' stack is a thread's own, so it is set here; then the
60+ thread runs its procedure, and notes that it has ended, for signal. *)
61+proc run(arg: ^U8): ^U8;
62+var t: ^Thread; alt: AltStack;
63+begin
64+ t := ^Thread(arg);
65+ alt := {sp: t^.base, size: Alt};
66+ _ := sigaltstack(^U8(SYSTEM.ADR(alt)), nil);
67+ t^.fn(t^.arg);
68+ _ := XCHG(t^.ended, 1);
69+ return nil;
70+end;
71+
72+(* Starts p(arg) in a new thread. *)
73+proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
74+var base: ^U8; t: ^Thread; size: INT; tid: UINT; attr: [8]U64; r: I32;
75+begin
76+ size := Alt + Page;
77+ base := Sys.mmap(size);
78+ if base = nil then return nil, Failed; end;
79+ (* the handlers' stack, then the Thread in the last page *)
80+ t := ^Thread(base + Alt);
81+ t^.base := base;
82+ t^.size := size;
83+ t^.fn := p;
84+ t^.arg := arg;
85+ _ := pthread_attr_init(^U8(SYSTEM.ADR(attr)));
86+ _ := pthread_attr_setstacksize(^U8(SYSTEM.ADR(attr)), Stack);
87+ r := cCreate(SYSTEM.ADR(tid), ^U8(SYSTEM.ADR(attr)), run, ^U8(t));
88+ _ := pthread_attr_destroy(^U8(SYSTEM.ADR(attr)));
89+ if r # 0 then
90+ Sys.munmap(base, size);
91+ return nil, Failed;
92+ end;
93+ t^.tid := tid;
94+ return t, nil;
95+end;
96+
97+(* Waits for t to end, then frees what spawn took for it. *)
98+proc join*(t: ^Thread);
99+var base: ^U8; size: INT;
100+begin
101+ _ := cJoin(t^.tid, nil);
102+ base := t^.base;
103+ size := t^.size;
104+ Sys.munmap(base, size);
105+end;
106+
107+(* Sends the signal sig to t alone, not to any thread of the program
108+ as Sys.kill does: 0, or minus an errno, -3 (ESRCH) if t has ended.
109+ With Sys.handle(sig), a system call t waits in fails with -4, so
110+ another thread can break into a read. By pthread_kill, whose errnos,
111+ ESRCH and EINVAL, are Linux's numbers too. *)
112+proc signal*(t: ^Thread; sig: INT): INT;
113+begin
114+ if XADD(t^.ended, 0) # 0 then return -3; end;
115+ return -INT(pthread_kill(t^.tid, I32(sig)));
116+end;
117+
118+(* Takes m, sleeping while another thread holds it. *)
119+proc lock*(var m: Mutex);
120+begin
121+ os_unfair_lock_lock(SYSTEM.ADR(m.lock));
122+end;
123+
124+(* Gives up m, which the calling thread took, waking a thread that
125+ waits for it. *)
126+proc unlock*(var m: Mutex);
127+begin
128+ os_unfair_lock_unlock(SYSTEM.ADR(m.lock));
129+end;
130+
131+(* The module's test, and make stress's. It starts n threads, in waves
132+ of up to alive at a time, all waiting on one Mutex the test holds
133+ until the wave is out; each, given it, adds one to a count. Every
134+ thread is joined, so that a stack join didn't free would, over
135+ enough of them, run the process out of mappings. With "fail", it
136+ starts threads, all waiting, until spawn fails, which it must do
137+ with Failed: make stress and make check run it with little memory.
138+ Thread [n alive], Thread fail *)
139+var
140+ testLock: Mutex;
141+ testCount: INT;
142+ wave: [1000]^Thread;
143+
144+proc testWork(_arg: ^U8);
145+begin
146+ lock(testLock);
147+ INC(testCount);
148+ unlock(testLock);
149+end;
150+
151+proc testArg(i: INT): INT;
152+var s: ^U8; n, v: INT;
153+begin
154+ s := SYSTEM.ARGV()[i];
155+ v := 0;
156+ n := 0;
157+ while s[n] # 0 do v := v * 10 + INT(s[n]) - '0'; INC(n); end;
158+ return v;
159+end;
160+
161+(* The module's test: starts threads in waves, and counts that each ran. *)
162+proc main*;
163+var n, alive, started, k, i: INT; t: ^Thread; err: ERROR; fail: BOOL;
164+begin
165+ n := 2000; alive := 50;
166+ fail := (ARGC() = 2) and (SYSTEM.ARGV()[1][0] = 'f');
167+ if ARGC() = 3 then n := testArg(1); alive := testArg(2); end;
168+ if fail then n := LEN(wave); alive := LEN(wave); end;
169+ if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end;
170+ started := 0;
171+ while started < n do
172+ lock(testLock);
173+ k := 0;
174+ while (k < alive) and (started + k < n) do
175+ t, err := spawn(testWork, nil);
176+ if err # nil then
177+ if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end;
178+ n := started + k;
179+ break;
180+ end;
181+ wave[k] := t;
182+ INC(k);
183+ end;
184+ unlock(testLock);
185+ for i := 0 to k - 1 do join(wave[i]); end;
186+ started := started + k;
187+ end;
188+ Check.int("Thread: every thread ran", testCount, started);
189+ Check.ok(not (fail and (started = LEN(wave))), "Thread: spawn never failed");
190+end;
191+
192+end Thread.

test/check.sh (history) modified +3 -0

@@ -370,6 +370,9 @@
370370 if $raz -Werror -o $out/raztest tools/Test.raz 2>$out/raztest.cerr; then
371371 libtests=
372372 for f in lib/*.raz; do
373+ case $f in # another target's file is tested there (test/mac.sh)
374+ *.darwin-arm64.raz|*.darwin.raz|*.arm64.raz) continue;;
375+ esac
373376 [ $f != lib/Sys.raz ] && grep -q '^proc main\*' $f && ! skip $f && libtests="$libtests $f"
374377 done
375378 RAZ=$raz $out/raztest -j $(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1) -o $out/lib \

test/err/Clash.err (history) modified +2 -2

@@ -1,5 +1,5 @@
1-lib/Sys.raz:18:8: error: module C is in test/err/mods/clash/C.raz and lib/C.raz
2- 18 | import C, CAbi;
1+lib/Sys.raz:21:8: error: module C is in test/err/mods/clash/C.raz and lib/C.raz
2+ 21 | import C, CAbi;
33 | ^
44 help: a program has one module of each name; a symbolic link to one of these files chooses it
55 raz: 1 error

test/libc/ExecOpenedC.raz (history) modified +2 -2

@@ -1,6 +1,6 @@
11 (* Over the C library: a file open gives is closed in the program exec
22 runs, unless keepOnExec says to keep it: of two opened files, sh sees
3- the second. *)
3+ the second, in /dev/fd, which Linux and macOS have alike. *)
44 module ExecOpenedC;
55 import Sys;
66
@@ -11,7 +11,7 @@
1111 b := Sys.create("/dev/null");
1212 if (a # 3) or (b # 4) or (Sys.keepOnExec(b, true) # 0) then return 1; end;
1313 return Sys.exec({path: "sh",
14- args: ["sh", "-c", "for n in 3 4; do if [ -e /proc/self/fd/$n ]; then echo open $n; else echo closed $n; fi; done"]});
14+ args: ["sh", "-c", "for n in 3 4; do if [ -e /dev/fd/$n ]; then echo open $n; else echo closed $n; fi; done"]});
1515 end;
1616
1717 end ExecOpenedC.

test/mac.sh (history) modified +86 -1

@@ -11,6 +11,14 @@
1111 # which are counted and listed in build/mac/conform.fail, not failures
1212 # of the run. A few of conform/run are not for this target, each named
1313 # in notHere with the reason, and skipped.
14+# Then the library: each module's own main, its test, as the target
15+# takes its file (Name.darwin-arm64.raz, Name.darwin.raz, Name.arm64.raz
16+# or Name.raz), built with -Werror into build/mac/lib and run there,
17+# passing if it ends with status 0, as raztest has it; and test/libc's
18+# programs, over Sys, the C one, into build/mac/libc, compared as
19+# test/check.sh compares them (X.expect, X.status, and X.stderr with
20+# each address 0x?). These count as test/mac's do, but those named in
21+# libNotHere, with the reason, which are skipped.
1422 #
1523 # test/mac.sh build in the container: the cross compiler, then the programs
1624 # test/mac.sh run on the Mac: each program, run with a timeout
@@ -28,6 +36,30 @@
2836 out=build/mac
2937 # conform/run's programs that are not for darwin-arm64, and why
3038 notHere='SystemImport: SYSTEM.SYSCALL is Linux'"'"'s only (report 6.8)'
39+# the library's tests and test/libc's programs that are not for it, and why
40+libNotHere='test/libc/ExecveC: reads what signals sh ignores and catches in /proc/self/status, which is Linux'"'"'s'
41+
42+# The file of module $1 the target takes, as the compiler looks for it
43+libFile() {
44+ for f in lib/$1.darwin-arm64.raz lib/$1.darwin.raz lib/$1.arm64.raz lib/$1.raz; do
45+ [ -f $f ] && { echo $f; return; }
46+ done
47+}
48+
49+# The library's modules that have a test, by the files the target takes
50+libTests() {
51+ for m in $(ls lib/*.raz | sed 's|lib/||; s|\..*||' | sort -u); do
52+ f=$(libFile $m)
53+ [ -n "$f" ] && grep -q '^proc main\*' $f && echo $f
54+ done
55+}
56+
57+# Runs $out/$1/$2 with a timeout, in its directory, from the arguments
58+# on: its status, its output in $2.out and $2.err
59+runIn() {
60+ dir=$1; prog=$2; shift 2
61+ (cd $out/$dir && perl -e 'alarm 60; exec @ARGV' ./$prog "$@" > $prog.out 2>$prog.err) || return $?
62+}
3163 case $1 in
3264 build)
3365 src/cross.sh darwin-arm64
@@ -43,6 +75,16 @@
4375 build/cross/darwin-arm64/raz -I conform/run/mods -o $out/conform/$name $f \
4476 2>$out/conform/$name.cerr || true
4577 done
78+ mkdir -p $out/lib $out/libc
79+ for f in $(libTests); do
80+ name=$(basename $f .raz); name=${name%%.*}
81+ build/cross/darwin-arm64/raz -Werror -o $out/lib/$name $f 2>$out/lib/$name.cerr || true
82+ done
83+ for f in test/libc/*.raz; do
84+ name=$(basename $f .raz)
85+ build/cross/darwin-arm64/raz -Werror -I test/libc/mods -o $out/libc/$name $f \
86+ 2>$out/libc/$name.cerr || true
87+ done
4688 ;;
4789 run)
4890 pass=0
@@ -107,8 +149,51 @@
107149 fi
108150 done
109151 echo "conform/run: $cpass of $((cpass + cfail)) passed, $cskip not for this target; the others in $c.fail"
152+ # the library's tests, and test/libc's programs
153+ lpass=0
154+ lfail=0
155+ lskip=0
156+ for f in $(libTests); do
157+ name=$(basename $f .raz); name=${name%%.*}
158+ if echo "$libNotHere" | grep -q "^lib/$name:"; then lskip=$((lskip + 1)); continue; fi
159+ if [ ! -x $out/lib/$name ]; then
160+ echo "FAIL $f: doesn't compile: $(head -3 $out/lib/$name.cerr)"; lfail=$((lfail + 1)); continue
161+ fi
162+ status=0
163+ runIn lib $name || status=$?
164+ if [ $status != 0 ]; then
165+ echo "FAIL $f: status $status"; tail -5 $out/lib/$name.err; lfail=$((lfail + 1))
166+ else
167+ lpass=$((lpass + 1))
168+ fi
169+ done
170+ for f in test/libc/*.raz; do
171+ name=$(basename $f .raz)
172+ if echo "$libNotHere" | grep -q "^test/libc/$name:"; then lskip=$((lskip + 1)); continue; fi
173+ if [ ! -x $out/libc/$name ]; then
174+ echo "FAIL $f: doesn't compile: $(head -3 $out/libc/$name.cerr)"; lfail=$((lfail + 1)); continue
175+ fi
176+ want=0
177+ [ -f test/libc/$name.status ] && want=$(cat test/libc/$name.status)
178+ # from the repository's root, as a message names the file so
179+ status=0
180+ perl -e 'alarm 60; exec @ARGV' ./$out/libc/$name > $out/libc/$name.out 2>$out/libc/$name.err || status=$?
181+ if [ -f test/libc/$name.expect ]; then exp=test/libc/$name.expect; else exp=/dev/null; fi
182+ if [ $status != $want ]; then
183+ echo "FAIL $f: status $status, not $want"; head -3 $out/libc/$name.err; lfail=$((lfail + 1))
184+ elif ! cmp -s $out/libc/$name.out $exp; then
185+ echo "FAIL $f: output differs"; diff $out/libc/$name.out $exp | head -5; lfail=$((lfail + 1))
186+ elif [ -f test/libc/$name.stderr ] && ! sed 's/0x[0-9a-f]*/0x?/g' $out/libc/$name.err |
187+ cmp -s - test/libc/$name.stderr; then
188+ echo "FAIL $f: standard error differs"; diff $out/libc/$name.err test/libc/$name.stderr | head -5
189+ lfail=$((lfail + 1))
190+ else
191+ lpass=$((lpass + 1))
192+ fi
193+ done
194+ echo "the library and test/libc: $lpass passed, $lfail failed, $lskip not for this target"
110195 if command -v lldb > /dev/null; then test/lldb.sh || fail=$((fail + 1)); fi
111- [ $fail = 0 ]
196+ [ $fail = 0 ] && [ $lfail = 0 ]
112197 ;;
113198 *)
114199 echo "usage: test/mac.sh build|run" >&2

tools/cabi.c (history) modified +262 -12

@@ -1,8 +1,10 @@
11 /* cabi: writes lib/CAbi.OS-ARCH.raz, what the C library it is compiled
22 against fixes for Sys over C (lib/Sys.raz): the numbers of flags,
33 requests, signals, limits and errnos, where the fields Sys reads and
4- writes lie in the C library's structs, and the two procedures whose
5- names differ between systems. Nothing in that file is typed by hand:
4+ writes lie in the C library's structs, and the procedures that differ
5+ between systems: errno and closeFrom, and the calls Linux has and
6+ another system makes otherwise (makePipe, accepted, random, memFile,
7+ sleepUntil, processors, peer and sendNow). Nothing in that file is typed by hand:
68 it is all this program's output, from the system's own headers.
79
810 cc -o build/cabi tools/cabi.c && build/cabi linux-x86_64 > lib/CAbi.linux-x86_64.raz
@@ -24,11 +26,16 @@
2426 flag; an option -1, as saLenAt is -1 where a sockaddr has no sa_len.
2527 On macOS (darwin-arm64), st_mtim is st_mtimespec, a peer's
2628 credentials are struct xucred, which has no pid (0 bytes at 0), and
27- errno and closeFrom are its own.
29+ the procedures are its own: no pipe2, accept4 or SOCK_CLOEXEC, so
30+ fcntl after; getentropy for getrandom; a shared memory object for
31+ memfd_create; nanosleep for clock_nanosleep; sysconf for
32+ sched_getaffinity; LOCAL_PEERCRED and LOCAL_PEERPID for SO_PEERCRED;
33+ and a socket made nonblocking for a send, whose MSG_DONTWAIT macOS
34+ doesn't keep on a Unix socket.
2835
2936 cc -o build/cabi tools/cabi.c && build/cabi darwin-arm64 > lib/CAbi.darwin-arm64.raz
3037
31- Leaves out: systems but Linux and macOS, for errno and closeFrom; a
38+ Leaves out: systems but Linux and macOS, for the procedures; a
3239 port adds them where the #error is. */
3340 #define _GNU_SOURCE
3441 #include <dirent.h>
@@ -133,7 +140,7 @@
133140 printf("(* CAbi: what the C library fixes for Sys over C on %s: the\n"
134141 " numbers of its flags, requests, signals and limits, where the\n"
135142 " fields of its structs lie, an At the offset and a Len the width,\n"
136- " its errnos beside Linux's, and errno and closeFrom.\n\n"
143+ " its errnos beside Linux's, and the procedures that differ.\n\n"
137144 " Written by tools/cabi.c, from the system's own headers; not to be\n"
138145 " edited, but written again. *)\n", target);
139146 printf("module CAbi;\nimport SYSTEM;\n\nconst\n");
@@ -176,6 +183,11 @@
176183 K("tcsanow", TCSANOW); K("tcsadrain", TCSADRAIN);
177184 K("tiocgwinsz", TIOCGWINSZ); K("tiocswinsz", TIOCSWINSZ);
178185 K("tiocsctty", TIOCSCTTY);
186+#ifdef __APPLE__
187+ K("ptyHeld", 1); /* a pseudo-terminal's controlling side works only while its terminal is open */
188+#else
189+ K("ptyHeld", 0);
190+#endif
179191 K("pollin", POLLIN); K("pollout", POLLOUT);
180192 K("clockRealtime", CLOCK_REALTIME); K("clockMonotonic", CLOCK_MONOTONIC);
181193 K("timerAbstime", TIMER_ABSTIME);
@@ -198,6 +210,11 @@
198210 #endif
199211 K("sockaddrUnLen", sizeof(struct sockaddr_un));
200212 READ("sunPath", struct sockaddr_un, sun_path);
213+#ifdef __linux__
214+ K("unixAbstract", 1); /* a Unix socket's name may start with a zero: no file */
215+#else
216+ K("unixAbstract", 0);
217+#endif
201218 K("sockaddrInLen", sizeof(struct sockaddr_in));
202219 AT("sinPort", struct sockaddr_in, sin_port);
203220 AT("sinAddr", struct sockaddr_in, sin_addr);
@@ -257,28 +274,126 @@
257274
258275 #ifdef __linux__
259276 printf("extern proc __errno_location: ^I32;\n"
260- "extern proc syscall(n: INT; ...): INT;\n\n"
277+ "extern proc syscall(n: INT; ...): INT;\n"
278+ "extern proc pipe2(fds: ^I32; flags: I32): I32;\n"
279+ "extern proc accept4(fd: I32; addr: ^U8; len: ^U32; flags: I32): I32;\n"
280+ "extern proc getrandom(buf: ^U8; n: UINT; flags: U32): INT;\n"
281+ "extern proc memfd_create(name: ^U8; flags: U32): I32;\n"
282+ "extern proc clock_nanosleep(clock, flags: I32; t, left: ^U8): I32;\n"
283+ "extern proc sched_getaffinity(pid: I32; size: UINT; mask: ^U8): I32;\n"
284+ "extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32;\n"
285+ "extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;\n"
286+ "\n"
261287 "(* errno, this thread's *)\n"
262288 "proc errno*: ^I32;\n"
263289 "begin\n"
264290 " return __errno_location();\n"
265- "end;\n\n"
291+ "end;\n"
292+ "\n"
266293 "(* Closes the fds from lo to hi, or every one from lo if hi < 0: by\n"
267294 " close_range's system call, since musl has no close_range. *)\n"
268295 "proc closeFrom*(lo, hi: INT);\n"
269296 "begin\n"
270297 " if hi < 0 then hi := 0FFFFFFFFH; end;\n"
271298 " _ := syscall(436, lo, hi, 0);\n"
272- "end;\n\n");
299+ "end;\n"
300+ "\n"
301+ "(* A pipe, its two fds put at fds, taking flags, oCloexec and\n"
302+ " oNonblock, at once: 0, or -1 with errno set, as C's calls are. *)\n"
303+ "proc makePipe*(fds: ^I32; flags: I32): I32;\n"
304+ "begin\n"
305+ " return pipe2(fds, flags);\n"
306+ "end;\n"
307+ "\n"
308+ "(* The next connection to the socket fd, closed on exec; or -1. *)\n"
309+ "proc accepted*(fd: I32): I32;\n"
310+ "begin\n"
311+ " return accept4(fd, nil, nil, sockCloexec);\n"
312+ "end;\n"
313+ "\n"
314+ "(* The kernel's random bytes, at most n, put at buf: how many, or -1. *)\n"
315+ "proc random*(buf: ^U8; n: UINT): INT;\n"
316+ "begin\n"
317+ " return getrandom(buf, n, 0);\n"
318+ "end;\n"
319+ "\n"
320+ "(* A file in memory, of no bytes, with no name, closed on exec: its\n"
321+ " fd, or -1. *)\n"
322+ "proc memFile*: I32;\n"
323+ "begin\n"
324+ " return memfd_create(SYSTEM.PTR(\"raz\\0\"), mfdCloexec); (* the name /proc shows *)\n"
325+ "end;\n"
326+ "\n"
327+ "(* Waits until t, a struct timespec of the monotonic clock, again\n"
328+ " after EINTR. *)\n"
329+ "proc sleepUntil*(t: ^U8);\n"
330+ "begin\n"
331+ " repeat until clock_nanosleep(clockMonotonic, timerAbstime, t, nil) # eIntr;\n"
332+ "end;\n"
333+ "\n"
334+ "(* The number of processors this program may run on, or 0 if the\n"
335+ " system doesn't say. *)\n"
336+ "proc processors*: INT;\n"
337+ "var mask: [1024]U8; i, b, count: INT;\n"
338+ "begin\n"
339+ " for i := 0 to LEN(mask) - 1 do mask[i] := 0; end; (* the C library fills in as many bytes as the system has processors' bits *)\n"
340+ " if sched_getaffinity(0, UINT(LEN(mask)), SYSTEM.ADR(mask[0])) # 0 then return 0; end;\n"
341+ " count := 0;\n"
342+ " for i := 0 to LEN(mask) - 1 do\n"
343+ " for b := 0 to 7 do\n"
344+ " if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end;\n"
345+ " end;\n"
346+ " end;\n"
347+ " return count;\n"
348+ "end;\n"
349+ "\n"
350+ "(* The process and the user at the other end of the Unix socket fd,\n"
351+ " as the system recorded them when it connected, and 0; or -1. *)\n"
352+ "proc peer*(fd: I32; var pid, uid: INT): I32;\n"
353+ "var cred: [16]U64; size: U32; p: ^U8; q: ^U32;\n"
354+ "begin\n"
355+ " p := ^U8(SYSTEM.ADR(cred[0]));\n"
356+ " size := U32(SIZE([16]U64));\n"
357+ " if getsockopt(fd, solSocket, soPeercred, p, SYSTEM.ADR(size)) # 0 then return -1; end;\n"
358+ " q := ^U32(p + ucPidAt);\n"
359+ " pid := INT(I32(q^));\n"
360+ " q := ^U32(p + ucUidAt);\n"
361+ " uid := INT(q^);\n"
362+ " return 0;\n"
363+ "end;\n"
364+ "\n"
365+ "(* Sends n bytes at buf on the socket fd, without waiting, and without\n"
366+ " SIGPIPE where the other end is gone: how many were sent, or -1. *)\n"
367+ "proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT;\n"
368+ "begin\n"
369+ " return send(fd, buf, n, msgNosignal | msgDontwait);\n"
370+ "end;\n"
371+ "\n");
273372 #elif defined(__APPLE__)
274373 printf("extern proc __error: ^I32;\n"
275374 "extern proc close(fd: I32): I32;\n"
276- "extern proc getdtablesize: I32;\n\n"
375+ "extern proc getdtablesize: I32;\n"
376+ "extern proc pipe(fds: ^I32): I32;\n"
377+ "extern proc fcntl(fd, cmd: I32; ...): I32;\n"
378+ "extern proc accept(fd: I32; addr: ^U8; len: ^U32): I32;\n"
379+ "extern proc getentropy(buf: ^U8; n: UINT): I32;\n"
380+ "extern proc getpid: I32;\n"
381+ "extern proc shm_open(name: ^U8; flags: I32; ...): I32;\n"
382+ "extern proc shm_unlink(name: ^U8): I32;\n"
383+ "extern proc clock_gettime(clock: I32; t: ^U8): I32;\n"
384+ "extern proc nanosleep(t, left: ^U8): I32;\n"
385+ "extern proc sysconf(name: I32): INT;\n"
386+ "extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32;\n"
387+ "extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;\n"
388+ "\n"
389+ "var shmCount: INT; (* the shared memory objects memFile has made *)\n"
390+ "\n"
277391 "(* errno, this thread's *)\n"
278392 "proc errno*: ^I32;\n"
279393 "begin\n"
280394 " return __error();\n"
281- "end;\n\n"
395+ "end;\n"
396+ "\n"
282397 "(* Closes the fds from lo to hi, or every one from lo if hi < 0: one\n"
283398 " by one, as macOS has no close_range. *)\n"
284399 "proc closeFrom*(lo, hi: INT);\n"
@@ -286,9 +401,144 @@
286401 "begin\n"
287402 " if hi < 0 then hi := INT(getdtablesize()) - 1; end;\n"
288403 " for fd := lo to hi do _ := close(I32(fd)); end;\n"
289- "end;\n\n");
404+ "end;\n"
405+ "\n"
406+ "(* fd closed on exec, and nonblocking, as flags, oCloexec and\n"
407+ " oNonblock, say: macOS has no flags for them where a pipe or a\n"
408+ " socket is made, so another thread's exec in between keeps the fd\n"
409+ " open, a gap Linux hasn't. *)\n"
410+ "proc setFlags(fd, flags: I32);\n"
411+ "begin\n"
412+ " if flags & oCloexec # 0 then _ := fcntl(fd, fSetfd, fdCloexec); end;\n"
413+ " if flags & oNonblock # 0 then _ := fcntl(fd, fSetfl, fcntl(fd, fGetfl) | oNonblock); end;\n"
414+ "end;\n"
415+ "\n"
416+ "(* A pipe, its two fds put at fds, taking flags, oCloexec and\n"
417+ " oNonblock: 0, or -1 with errno set, as C's calls are. *)\n"
418+ "proc makePipe*(fds: ^I32; flags: I32): I32;\n"
419+ "begin\n"
420+ " if pipe(fds) # 0 then return -1; end;\n"
421+ " setFlags(fds[0], flags);\n"
422+ " setFlags(fds[1], flags);\n"
423+ " return 0;\n"
424+ "end;\n"
425+ "\n"
426+ "(* The next connection to the socket fd, closed on exec; or -1. *)\n"
427+ "proc accepted*(fd: I32): I32;\n"
428+ "var r: I32;\n"
429+ "begin\n"
430+ " r := accept(fd, nil, nil);\n"
431+ " if r >= 0 then setFlags(r, oCloexec); end;\n"
432+ " return r;\n"
433+ "end;\n"
434+ "\n"
435+ "(* The kernel's random bytes, at most n, put at buf: how many, or -1.\n"
436+ " getentropy gives 256 at most at a time. *)\n"
437+ "proc random*(buf: ^U8; n: UINT): INT;\n"
438+ "begin\n"
439+ " if n > 256 then n := 256; end;\n"
440+ " if getentropy(buf, n) # 0 then return -1; end;\n"
441+ " return INT(n);\n"
442+ "end;\n"
443+ "\n"
444+ "(* v in hexadecimal into name from i on: where its digits end *)\n"
445+ "proc hex(var name: [32]U8; i, v: INT): INT;\n"
446+ "var n, k, d: INT;\n"
447+ "begin\n"
448+ " n := v;\n"
449+ " repeat INC(i); n := n shr 4; until n = 0;\n"
450+ " k := i;\n"
451+ " repeat\n"
452+ " DEC(k);\n"
453+ " d := v & 15;\n"
454+ " if d < 10 then name[k] := U8(d) + '0'; else name[k] := U8(d - 10) + 'a'; end;\n"
455+ " v := v shr 4;\n"
456+ " until v = 0;\n"
457+ " return i;\n"
458+ "end;\n"
459+ "\n"
460+ "(* A file in memory, of no bytes, with no name, closed on exec: its\n"
461+ " fd, or -1. macOS has no memfd_create: it is a POSIX shared memory\n"
462+ " object, made with a name of its own, /raz.PID.N, which is removed\n"
463+ " at once. Such an object can be given its size once, and mapped, but\n"
464+ " not read or written. *)\n"
465+ "proc memFile*: I32;\n"
466+ "var name: [32]U8; fd: I32; i: INT;\n"
467+ "begin\n"
468+ " COPY(name[0..5], \"/raz.\");\n"
469+ " i := hex(name, 5, INT(getpid()));\n"
470+ " name[i] := '.';\n"
471+ " i := hex(name, i + 1, XADD(shmCount, 1));\n"
472+ " name[i] := 0;\n"
473+ " fd := shm_open(SYSTEM.ADR(name[0]), oRdwr | oCreat | oExcl, 384); (* rw------- *)\n"
474+ " if fd < 0 then return -1; end;\n"
475+ " _ := shm_unlink(SYSTEM.ADR(name[0]));\n"
476+ " setFlags(fd, oCloexec);\n"
477+ " return fd;\n"
478+ "end;\n"
479+ "\n"
480+ "(* Waits until t, a struct timespec of the monotonic clock: macOS has\n"
481+ " no clock_nanosleep, so nanosleep sleeps what is left, again after\n"
482+ " EINTR. *)\n"
483+ "proc sleepUntil*(t: ^U8);\n"
484+ "var now, left: [2]I64; at: ^I64; d: I64;\n"
485+ "begin\n"
486+ " at := ^I64(t);\n"
487+ " repeat\n"
488+ " _ := clock_gettime(clockMonotonic, ^U8(SYSTEM.ADR(now[0])));\n"
489+ " d := (at[0] - now[0]) * 1000000000 + at[1] - now[1];\n"
490+ " if d <= 0 then return; end;\n"
491+ " left := [d div 1000000000, d mod 1000000000];\n"
492+ " _ := nanosleep(^U8(SYSTEM.ADR(left[0])), nil);\n"
493+ " until false;\n"
494+ "end;\n"
495+ "\n"
496+ "(* The number of processors this program may run on, or 0 if the\n"
497+ " system doesn't say: those online, as macOS binds a program to none\n"
498+ " of them. *)\n"
499+ "proc processors*: INT;\n"
500+ "begin\n"
501+ " return sysconf(%d); (* _SC_NPROCESSORS_ONLN *)\n"
502+ "end;\n"
503+ "\n"
504+ "(* The process and the user at the other end of the Unix socket fd,\n"
505+ " as the system recorded them when it connected, and 0; or -1. The\n"
506+ " user is in a struct xucred, LOCAL_PEERCRED's, and the process is\n"
507+ " asked for alone, LOCAL_PEERPID. *)\n"
508+ "proc peer*(fd: I32; var pid, uid: INT): I32;\n"
509+ "var cred: [16]U64; size: U32; p: ^U8; q: ^U32; id: I32;\n"
510+ "begin\n"
511+ " p := ^U8(SYSTEM.ADR(cred[0]));\n"
512+ " size := U32(SIZE([16]U64));\n"
513+ " if getsockopt(fd, %d, %d, p, SYSTEM.ADR(size)) # 0 then return -1; end;\n"
514+ " q := ^U32(p + ucUidAt);\n"
515+ " uid := INT(q^);\n"
516+ " size := 4;\n"
517+ " if getsockopt(fd, %d, %d, ^U8(SYSTEM.ADR(id)), SYSTEM.ADR(size)) # 0 then return -1; end;\n"
518+ " pid := INT(id);\n"
519+ " return 0;\n"
520+ "end;\n"
521+ "\n"
522+ "(* Sends n bytes at buf on the socket fd, without waiting, and without\n"
523+ " SIGPIPE where the other end is gone: how many were sent, or -1.\n"
524+ " macOS's send waits on a Unix socket though MSG_DONTWAIT is given, so\n"
525+ " the socket is made nonblocking for it, as it was before after. *)\n"
526+ "proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT;\n"
527+ "var f: I32; r: INT; e: ^I32; err: I32;\n"
528+ "begin\n"
529+ " f := fcntl(fd, fGetfl);\n"
530+ " if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f | oNonblock); end;\n"
531+ " r := send(fd, buf, n, msgNosignal | msgDontwait);\n"
532+ " e := __error();\n"
533+ " err := e^;\n"
534+ " if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f); end;\n"
535+ " e^ := err;\n"
536+ " return r;\n"
537+ "end;\n"
538+ "\n",
539+ _SC_NPROCESSORS_ONLN, SOL_LOCAL, LOCAL_PEERCRED, SOL_LOCAL, LOCAL_PEERPID);
290540 #else
291-#error "a CAbi for this system needs its errno and closeFrom: add them here"
541+#error "a CAbi for this system needs its procedures: add them here"
292542 #endif
293543 printf("end CAbi.\n");
294544 return 0;