From 8952497244478aa5d2d225e6ee6adfaffd7d6ac9 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:55:54 +0000 Subject: [PATCH] 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. --- diff --git a/PLAN.md b/PLAN.md index abda534..8d0ef39 100644 --- a/PLAN.md +++ b/PLAN.md @@ -292,7 +292,7 @@ x7, a variadic call and a callback; `Host.darwin.raz`, and `HOST=darwin src/cross.sh darwin-arm64`, which stages the first Mac compiler: it runs on the Mac, compiles and runs programs, and builds `Procs`. -7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`. +7. Done. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`. 8. `test/` and `conform/` passing on the Mac; what differs by target (signals' words, errors' numbers) in files of the target's. 9. The first Mac compiler, by the staged cross compiler; it builds diff --git a/doc/compiler.md b/doc/compiler.md index d57f418..a0d0668 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1880,6 +1880,18 @@ catch, `Rt`'s handler tells: a nil pointer within page zero, 4 GB (`NilPage`), a call to nil, and a stack overflow at the guard page, each a SIGSEGV or SIGBUS, on a stack of its own (`lib/Rt.darwin-arm64.raz`). +That `Rt` is Linux's in all it tells: the place, from the places, and +the calls under way with their variables, up x29's chain of frame +records, a call being the `bl` 4 bytes before its return address, and +x19 to x23 (`VarRegs`) read back from where each frame saved them, or, +after a signal, from the context the kernel handed the handler. A stack +overflow can stop a procedure at its first instruction, the `stp` of +its frame record, so the handler makes that record itself, from the fp +and lr it found. Its code procedures (`framePtr`, `liveRegs`, `here`) +are written in `db`, since `BOOT`'s release reads `Rt`'s every file +for its interface when it builds `src/` and knows only x86-64's +instructions; no `sigReturn`, as libSystem's `_sigtramp` returns from a +handler. The rest is x86's, in arm64's instructions, each shown in its routine's comment: `copyBytes` and `zeroBytes` past 256 bytes by a loop @@ -2571,8 +2583,10 @@ arm64's fixups are patched by `patchArm`: a branch's distance in words, an `adrp`'s in pages of 4 KB, and an address's place in its page, in an `add` or, divided by the size it moves, in a load or a store, as -`Chunk.FixKind` says. The places keep the addresses the linker gave; -the Mac's `Rt` will take dyld's slide from what it looks up. +`Chunk.FixKind` says. The places keep the addresses the linker gave, +and are not rebased; the Mac's `Rt` takes dyld's slide, +`_dyld_get_image_vmaddr_slide(0)`, from each address before it looks it +up (`linked`). ## Exe.linux.raz: the executable @@ -2748,7 +2762,9 @@ must be `X.expect`, so C itself says what is right); then conform/run's, which are counted, those that fail listed in `build/mac/conform.fail`, and those not for the Mac, named in the script with why (`SystemImport`, as `SYSCALL` is Linux's), -skipped; and last `test/lldb.sh`, if lldb is there (`make lldb` is that +skipped; then each library module's own test, by the file the target +takes, and `test/libc`'s programs, which count as `test/mac`'s do, but +those named in `libNotHere`; and last `test/lldb.sh`, if lldb is there (`make lldb` is that alone, after `make mac-build`, the container's half). The host changes nothing of the target: a program for another system still needs that system's `Sys` and `Rt`, and for a kernel the options `-bare`, `-s` and `-base`. diff --git a/doc/raz-lib.md b/doc/raz-lib.md index 93b23aa..5eb0b7b 100644 --- a/doc/raz-lib.md +++ b/doc/raz-lib.md @@ -24,7 +24,7 @@ | `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 | | `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` | | `Out` | writing text and numbers to standard output, buffered; safe to call from several threads | -| `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C | +| `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 | | `Lock` | a lock for short sections, for C's threads and `Thread`'s alike | | `Thread` | threads, `spawn`, `join` and `signal`, and `Mutex`, in any program; in one that uses C, made by C's `pthread_create` | | `Task` | a thread given a value of its own, `Task(T)`: `spawn` copies it, with no cast | @@ -41,6 +41,7 @@ | `Vec` | a generic growable array, `Vec(T)`, indexed as a slice | | `Sort` | sorting a slice in place, `Sort(T; less)` | | `Math` | roots, powers, logarithms, rounding and trigonometry, and `pi`, for `F64` | +| `Arith` | the machine's own arithmetic that `Math` gives: `sqrt`, the 128-bit product `mul`, and `div128`; one file per machine | | `Files` | an argument as a string, and a whole file read or written | | `Opt` | a command line read through one table, by `getopt`'s rules with long options; its help and its mistakes | | `Width` | how many columns of a terminal a character, or a string, takes: 0, 1 or 2, as `wcwidth` says | @@ -176,7 +177,10 @@ with a message, as in the main thread. In a program that uses C, `Thread` makes its threads with C's `pthread_create`, so that C's library knows of them; in one that doesn't, with the system's own -calls. The program is the same either way. +calls. The program is the same either way. On macOS every program uses +C; a thread's stack is 1 MB, as on Linux without C, and a `Mutex` is +the system's `os_unfair_lock`, which the thread that took it must give +up: one that unlocks another's stops the program. `Sys.kill` signals a program, and the system gives the signal to any of its threads; `signal` gives it to `t` alone, until `t` is joined, @@ -514,8 +518,9 @@ `makeDirMode` is `makeDir` that gives the directory the bits `mode`, less those the umask takes away, as `openMode` gives a file: 1C0H (700) for one only its owner may enter. -Of the three above them, Linux gives a new directory only sticky; it -takes set-group-id from the directory it is made in. `setTime` sets +Of the three above them, Linux gives a new directory only sticky, and +macOS none, which `chmod` gives after; Linux takes set-group-id from +the directory it is made in. `setTime` sets the file's time, following a symbolic link, and the time it was last read with it, as a program that copies or restores a file keeps its time, so that a later run sees it unchanged: `sec` seconds and `nsec`, @@ -524,12 +529,18 @@ `Info.seconds` holds it in whole seconds, rounded down, whatever it is, so a program that copies times exactly takes `Info.seconds`, and the nanoseconds as `mtime - seconds * 1000000000`, which is right in -any year, since the wrapping cancels out (section 6.1). +any year, since the wrapping cancels out (section 6.1). That is as far +as the file system keeps the time: macOS's APFS keeps it in +nanoseconds too, and gives a time past 2262 as its last second there. **Programs.** `openPty` makes a pseudo-terminal, a terminal that a program, a terminal emulator, plays the screen and the keyboard of: what it writes to the fd is typed, and what the programs on the -terminal write it reads. +terminal write it reads. On macOS, whose pseudo-terminal takes no +modes and no size until its terminal has been opened, and reads an end +once that is closed again, `openPty` opens the terminal and holds it +until the first program `spawn` starts on it with `p.tty` takes it +over, or the fd is closed with `close` or `closeChecked`. `spawn` starts the program at `p.path`, with `p.args` as its arguments, the first being its name. A `p.path` without a `/` is @@ -745,7 +756,10 @@ `size` zeroed bytes, and `mapFile` maps it, or any file, so that what one program writes there another sees at once: so a program hands an X server or a Wayland compositor its pixels, by `sendFds` of a -`memFile` both map, rather than by copying them down a socket. +`memFile` both map, rather than by copying them down a socket. On +macOS, which has no `memfd_create`, a `memFile` is a POSIX shared memory +object whose name is gone at once: it can be mapped, but not read or +written with `read` and `write`. `mapFile` needs a file open to read and write; `mapRead` maps one that is open only to read, a dictionary that isn't the user's to write, for reading only: a write there stops the program. `protect` changes what @@ -763,7 +777,9 @@ most 107 bytes, as `struct sockaddr_un` holds; a longer one is -36 (ENAMETOOLONG). A path that starts with a zero byte is one of Linux's abstract names (D-Bus's `unix:abstract=`), which has no file: the -address is as long as the name, with no zero after it. +address is as long as the name, with no zero after it. A system that +has no abstract names, as macOS, refuses one with -22 (EINVAL); and +there `struct sockaddr_un` holds 103 bytes of a path. `poll` is `readyFor` without its limits. Each `Poll` names a descriptor `fd` and whether to wait to `read` from it, to `write` to @@ -934,7 +950,18 @@ proc mul*(a, b: U64): (U64, U64); (* a times b: the low 64 bits of the product, and the high *) proc divMod*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d: the quotient and the remainder; hi < d *) proc toReal*(s: []const U8): (F64, BOOL); (* s as a real, the F64 nearest it; false if it isn't one *) + +module Arith; +proc sqrt*(x: F64): F64; (* the square root, the machine's instruction *) +proc mul*(a, b: U64): (U64, U64); (* a times b: the low 64 bits of the product, and the high *) +proc div128*(hi, lo, d: U64): (U64, U64); (* hi, lo divided by d, which must be more than hi *) ``` + +`Math` keeps no machine code: its `sqrt`, `mul` and `divMod` are +`Arith`'s, a file for each machine. `div128` doesn't check that `hi < d`, +as `Math.divMod` does: on x86-64 the machine faults if it isn't, and on +arm64, which has no such division, it is long division in raz, whose +quotient is then wrong. A `Buf`, a `List`, a `Map` and a `Vec` take their memory from the allocator `init` gives them. `Buf.add`, `str` and `spare` stop the program, as a diff --git a/lib/Arith.arm64.raz b/lib/Arith.arm64.raz new file mode 100644 index 0000000..0bb62a0 --- /dev/null +++ b/lib/Arith.arm64.raz @@ -0,0 +1,66 @@ +(* Arith: the machine's arithmetic that raz has no operator for, which + Math gives as sqrt, mul and divMod: an F64's square root, the 128-bit + product of two U64s, and a 128-bit number divided by a U64. This file + is arm64's, Arith.x86_64.raz x86-64's. The root is fsqrt, and a call + of sqrt, an fsqrt and ret, is made in place (Gen.oneRealOp); the + product is mul for its low half and umulh for its high. arm64 has no + division of 128 bits by 64, only udiv of 64 by 64, so div128 is + long division in raz, a bit of the quotient at each of 64 steps. + Depends on Check, for its test. *) +module Arith; +import Check; +import SYSTEM; + +(* The square root of x, exact to the last bit; NaN for x below 0. *) +proc sqrt*(x: F64): F64; +code + fsqrt d0, d0; + ret; +end sqrt; + +(* a times b: the low 64 bits of the product, and the high, which come + back in x0 and x1. *) +proc mul*(a, b: U64): (U64, U64); +code + mul x2, x0, x1; + umulh x1, x0, x1; + mov x0, x2; + ret; +end mul; + +(* hi, lo divided by d, with hi < d, which the caller checks first: the + quotient and the remainder. As by hand, in base 2: the remainder so + far, hi, takes the next bit of lo at each step, and where it then + holds d, d is taken from it and that bit of the quotient is 1. The + remainder is below d before a step, so below 2d after the shift: it + holds d once at most, and its bit shifted out, top, says it is more + than 64 bits can hold, and so holds d too. *) +proc div128*(hi, lo, d: U64): (U64, U64); +var q: U64; i: INT; top: BOOL; +begin + q := 0; + for i := 1 to 64 do + top := hi shr 63 = 1; + hi := hi shl 1 | lo shr 63; + lo := lo shl 1; + q := q shl 1; + if top or (hi >= d) then + hi := hi - d; + q := q | 1; + end; + end; + return q, hi; +end; + +(* The module's test; Math's tests these more. *) +proc main*; +var lo, hi, q, r: U64; +begin + Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt"); + lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH); + Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul"); + q, r := div128(5, 9, 6); + Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128"); +end; + +end Arith. diff --git a/lib/Arith.x86_64.raz b/lib/Arith.x86_64.raz new file mode 100644 index 0000000..476a845 --- /dev/null +++ b/lib/Arith.x86_64.raz @@ -0,0 +1,50 @@ +(* Arith: the machine's arithmetic that raz has no operator for, which + Math gives as sqrt, mul and divMod: an F64's square root, the 128-bit + product of two U64s, and a 128-bit number divided by a U64. Each is + one instruction of the machine, so each is a code procedure, one + file per machine: this one for x86-64, Arith.arm64.raz for arm64. A + call of sqrt, a sqrtsd and ret, is made in place (Gen.oneRealOp). + Depends on Check, for its test. *) +module Arith; +import Check; +import SYSTEM; + +(* The square root of x, exact to the last bit; NaN for x below 0. *) +proc sqrt*(x: F64): F64; +code + sqrtsd xmm0, xmm0; + ret; +end sqrt; + +(* a times b: the low 64 bits of the product, and the high. *) +proc mul*(a, b: U64): (U64, U64); +code + mov rax, rdi; + mul rsi; + ret; +end mul; + +(* hi, lo divided by d: the quotient and the remainder, by the + machine's one instruction; it faults if hi >= d, which the caller + checks first. *) +proc div128*(hi, lo, d: U64): (U64, U64); +code + mov rcx, rdx; + mov rdx, rdi; + mov rax, rsi; + div rcx; + ret; +end div128; + +(* The module's test; Math's tests these more. *) +proc main*; +var lo, hi, q, r: U64; +begin + Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt"); + lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH); + Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul"); + q, r := div128(5, 9, 6); + Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128"); +end; + +end Arith. diff --git a/lib/C.darwin.raz b/lib/C.darwin.raz new file mode 100644 index 0000000..f7f18a5 --- /dev/null +++ b/lib/C.darwin.raz @@ -0,0 +1,181 @@ +(* The C library: what raz's own library calls in it, and what most + programs reach for; this file is macOS's, libSystem's, C.raz the + others'. A program that imports C uses C, as every program on a Mac + does. + + libSystem has every call of C.raz but those Linux's C library alone + has, which are procedures here that fail as C's calls do, -1 with + errno ENOSYS, as an unknown system call does: memfd_create, + clock_nanosleep, getrandom, accept4, close_range, sched_getaffinity + and pipe2 (Sys makes them of what libSystem has, in CAbi). errno is + __error here, and __errno_location gives it. stdout and stderr are + __stdoutp and __stderrp, put in variables of those names first. *) +module C; +import SYSTEM; + +extern proc write*(fd: I32; buf: ^U8; n: UINT): INT; +extern proc read*(fd: I32; buf: ^U8; n: UINT): INT; +extern proc open*(path: ^U8; flags: I32; ...): I32; +extern proc creat*(path: ^U8; mode: U32): I32; +extern proc close*(fd: I32): I32; +extern proc mmap*(addr: ^U8; n: UINT; prot, flags, fd: I32; off: I64): ^U8; +extern proc munmap*(addr: ^U8; n: UINT): I32; +extern proc mprotect*(addr: ^U8; n: UINT; prot: I32): I32; +extern proc isatty*(fd: I32): I32; +extern proc exit*(status: I32); +extern proc _exit*(status: I32); +extern proc __error: ^I32; +extern proc sched_yield*: I32; +extern proc pthread_create*(t: ^UINT; attr: ^U8; + start: proc(arg: ^U8): ^U8; arg: ^U8): I32; +extern proc pthread_join*(t: UINT; result: ^^U8): I32; +extern proc rename*(old, new: ^U8): I32; +extern proc unlink*(path: ^U8): I32; +extern proc mkdir*(path: ^U8; mode: U32): I32; +extern proc rmdir*(path: ^U8): I32; +extern proc chmod*(path: ^U8; mode: U32): I32; +extern proc chown*(path: ^U8; uid, gid: U32): I32; +extern proc mkfifo*(path: ^U8; mode: U32): I32; +extern proc utimensat*(dir: I32; path, times: ^U8; flags: I32): I32; +extern proc readlink*(path, buf: ^U8; n: UINT): INT; +extern proc lseek*(fd: I32; off: I64; whence: I32): I64; +extern proc opendir*(path: ^U8): ^U8; (* DIR * *) +extern proc readdir*(d: ^U8): ^U8; (* struct dirent * *) +extern proc closedir*(d: ^U8): I32; +extern proc tcgetattr*(fd: I32; t: ^U8): I32; +extern proc tcsetattr*(fd: I32; when: I32; t: ^U8): I32; +extern proc cfmakeraw*(t: ^U8); +extern proc ioctl*(fd: I32; request: UINT; ...): I32; +extern proc poll*(fds: ^U8; n: UINT; ms: I32): I32; +extern proc fcntl*(fd, cmd: I32; ...): I32; +extern proc socket*(domain, kind, protocol: I32): I32; +extern proc connect*(fd: I32; addr: ^U8; len: U32): I32; +extern proc send*(fd: I32; buf: ^U8; n: UINT; flags: I32): INT; +extern proc bind*(fd: I32; addr: ^U8; len: U32): I32; +extern proc listen*(fd, backlog: I32): I32; +extern proc accept*(fd: I32; addr: ^U8; len: ^U32): I32; +extern proc setsockopt*(fd, level, name: I32; value: ^U8; len: U32): I32; +extern proc getsockopt*(fd, level, name: I32; value: ^U8; len: ^U32): I32; +extern proc getpeername*(fd: I32; addr: ^U8; len: ^U32): I32; +extern proc shutdown*(fd, how: I32): I32; +extern proc socketpair*(domain, kind, protocol: I32; fds: ^I32): I32; +extern proc getsockname*(fd: I32; addr: ^U8; len: ^U32): I32; +extern proc recvfrom*(fd: I32; buf: ^U8; n: UINT; flags: I32; addr: ^U8; len: ^U32): INT; +extern proc sendto*(fd: I32; buf: ^U8; n: UINT; flags: I32; addr: ^U8; len: U32): INT; +extern proc sendmsg*(fd: I32; msg: ^U8; flags: I32): INT; +extern proc recvmsg*(fd: I32; msg: ^U8; flags: I32): INT; +extern proc ftruncate*(fd: I32; size: I64): I32; +extern proc inet_pton*(family: I32; src, dst: ^U8): I32; +extern proc clock_gettime*(clock: I32; t: ^U8): I32; +extern proc getenv*(name: ^U8): ^U8; +extern proc setenv*(name, value: ^U8; overwrite: I32): I32; +extern proc strerror*(err: I32): ^U8; +extern proc getcwd*(buf: ^U8; n: UINT): ^U8; +extern proc chdir*(path: ^U8): I32; +extern proc stat*(path, st: ^U8): I32; +extern proc fstat*(fd: I32; st: ^U8): I32; +extern proc fsync*(fd: I32): I32; +extern proc sync*; +extern proc flock*(fd, how: I32): I32; +extern proc lstat*(path, st: ^U8): I32; +extern proc statvfs*(path, st: ^U8): I32; +extern proc symlink*(target, path: ^U8): I32; +extern proc posix_openpt*(flags: I32): I32; +extern proc grantpt*(fd: I32): I32; +extern proc unlockpt*(fd: I32): I32; +extern proc ptsname*(fd: I32): ^U8; +extern proc fork*: I32; +extern proc setsid*: I32; +extern proc dup2*(fd, fd2: I32): I32; +extern proc dup*(fd: I32): I32; +extern proc execve*(path: ^U8; argv, envp: ^^U8): I32; +extern proc waitpid*(pid: I32; status: ^I32; options: I32): I32; +extern proc kill*(pid, signal: I32): I32; +extern proc getpid*: I32; +extern proc getuid*: U32; +extern proc geteuid*: U32; +extern proc gethostname*(name: ^U8; n: UINT): I32; +extern proc access*(path: ^U8; how: I32): I32; +extern proc umask*(mask: U32): U32; +extern proc getrusage*(who: I32; usage: ^U8): I32; +extern proc getrlimit*(which: I32; limit: ^U8): I32; +extern proc setrlimit*(which: I32; limit: ^U8): I32; +extern proc getpgrp*: I32; +extern proc setpgid*(pid, group: I32): I32; +extern proc tcsetpgrp*(fd, group: I32): I32; +extern proc tcgetpgrp*(fd: I32): I32; +extern proc sigaction*(sig: I32; act, old: ^U8): I32; +extern proc sigprocmask*(how: I32; mask, old: ^U8): I32; +extern proc printf*(format: ^U8; ...): I32; +extern proc fflush*(f: ^U8): I32; +extern var environ*: ^^U8; +extern var __stdoutp: ^U8; +extern var __stderrp: ^U8; + +var + stdout*: ^U8; (* FILE *: __stdoutp *) + stderr*: ^U8; (* __stderrp *) + +(* What a call Linux alone has does here, as each below: -1, errno + ENOSYS. Their parameters are named as in C.raz, as the interface + check wants, and dropped. *) +proc none: I32; +var e: ^I32; +begin + e := __error(); + e^ := 78; (* ENOSYS *) + return -1; +end; + +(* errno, this thread's *) +proc __errno_location*: ^I32; +begin + return __error(); +end; + +proc accept4*(fd: I32; addr: ^U8; len: ^U32; flags: I32): I32; +begin + _ := fd; _ := addr; _ := len; _ := flags; + return none(); +end; + +proc memfd_create*(name: ^U8; flags: U32): I32; +begin + _ := name; _ := flags; + return none(); +end; + +proc clock_nanosleep*(clock, flags: I32; t, left: ^U8): I32; +begin + _ := clock; _ := flags; _ := t; _ := left; + return none(); +end; + +proc getrandom*(buf: ^U8; n: UINT; flags: U32): INT; +begin + _ := buf; _ := n; _ := flags; + return INT(none()); +end; + +proc close_range*(first, last: U32; flags: I32): I32; +begin + _ := first; _ := last; _ := flags; + return none(); +end; + +proc sched_getaffinity*(pid: I32; size: UINT; mask: ^U8): I32; +begin + _ := pid; _ := size; _ := mask; + return none(); +end; + +proc pipe2*(fds: ^I32; flags: I32): I32; +begin + _ := fds; _ := flags; + return none(); +end; + +begin + stdout := __stdoutp; + stderr := __stderrp; +end C. diff --git a/lib/CAbi.darwin-arm64.raz b/lib/CAbi.darwin-arm64.raz index 0afea21..4b31f39 100644 --- a/lib/CAbi.darwin-arm64.raz +++ b/lib/CAbi.darwin-arm64.raz @@ -1,7 +1,7 @@ (* CAbi: what the C library fixes for Sys over C on darwin-arm64: the numbers of its flags, requests, signals and limits, where the fields of its structs lie, an At the offset and a Len the width, - its errnos beside Linux's, and errno and closeFrom. + its errnos beside Linux's, and the procedures that differ. Written by tools/cabi.c, from the system's own headers; not to be edited, but written again. *) @@ -86,6 +86,7 @@ tiocgwinsz* = 1074295912; tiocswinsz* = 2148037735; tiocsctty* = 536900705; + ptyHeld* = 1; pollin* = 1; pollout* = 4; clockRealtime* = 0; @@ -115,6 +116,7 @@ sockaddrUnLen* = 106; sunPathAt* = 2; sunPathLen* = 104; + unixAbstract* = 0; sockaddrInLen* = 16; sinPortAt* = 2; sinAddrAt* = 4; @@ -206,7 +208,21 @@ extern proc __error: ^I32; extern proc close(fd: I32): I32; extern proc getdtablesize: I32; +extern proc pipe(fds: ^I32): I32; +extern proc fcntl(fd, cmd: I32; ...): I32; +extern proc accept(fd: I32; addr: ^U8; len: ^U32): I32; +extern proc getentropy(buf: ^U8; n: UINT): I32; +extern proc getpid: I32; +extern proc shm_open(name: ^U8; flags: I32; ...): I32; +extern proc shm_unlink(name: ^U8): I32; +extern proc clock_gettime(clock: I32; t: ^U8): I32; +extern proc nanosleep(t, left: ^U8): I32; +extern proc sysconf(name: I32): INT; +extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32; +extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT; +var shmCount: INT; (* the shared memory objects memFile has made *) + (* errno, this thread's *) proc errno*: ^I32; begin @@ -220,6 +236,139 @@ begin if hi < 0 then hi := INT(getdtablesize()) - 1; end; for fd := lo to hi do _ := close(I32(fd)); end; +end; + +(* fd closed on exec, and nonblocking, as flags, oCloexec and + oNonblock, say: macOS has no flags for them where a pipe or a + socket is made, so another thread's exec in between keeps the fd + open, a gap Linux hasn't. *) +proc setFlags(fd, flags: I32); +begin + if flags & oCloexec # 0 then _ := fcntl(fd, fSetfd, fdCloexec); end; + if flags & oNonblock # 0 then _ := fcntl(fd, fSetfl, fcntl(fd, fGetfl) | oNonblock); end; +end; + +(* A pipe, its two fds put at fds, taking flags, oCloexec and + oNonblock: 0, or -1 with errno set, as C's calls are. *) +proc makePipe*(fds: ^I32; flags: I32): I32; +begin + if pipe(fds) # 0 then return -1; end; + setFlags(fds[0], flags); + setFlags(fds[1], flags); + return 0; +end; + +(* The next connection to the socket fd, closed on exec; or -1. *) +proc accepted*(fd: I32): I32; +var r: I32; +begin + r := accept(fd, nil, nil); + if r >= 0 then setFlags(r, oCloexec); end; + return r; +end; + +(* The kernel's random bytes, at most n, put at buf: how many, or -1. + getentropy gives 256 at most at a time. *) +proc random*(buf: ^U8; n: UINT): INT; +begin + if n > 256 then n := 256; end; + if getentropy(buf, n) # 0 then return -1; end; + return INT(n); +end; + +(* v in hexadecimal into name from i on: where its digits end *) +proc hex(var name: [32]U8; i, v: INT): INT; +var n, k, d: INT; +begin + n := v; + repeat INC(i); n := n shr 4; until n = 0; + k := i; + repeat + DEC(k); + d := v & 15; + if d < 10 then name[k] := U8(d) + '0'; else name[k] := U8(d - 10) + 'a'; end; + v := v shr 4; + until v = 0; + return i; +end; + +(* A file in memory, of no bytes, with no name, closed on exec: its + fd, or -1. macOS has no memfd_create: it is a POSIX shared memory + object, made with a name of its own, /raz.PID.N, which is removed + at once. Such an object can be given its size once, and mapped, but + not read or written. *) +proc memFile*: I32; +var name: [32]U8; fd: I32; i: INT; +begin + COPY(name[0..5], "/raz."); + i := hex(name, 5, INT(getpid())); + name[i] := '.'; + i := hex(name, i + 1, XADD(shmCount, 1)); + name[i] := 0; + fd := shm_open(SYSTEM.ADR(name[0]), oRdwr | oCreat | oExcl, 384); (* rw------- *) + if fd < 0 then return -1; end; + _ := shm_unlink(SYSTEM.ADR(name[0])); + setFlags(fd, oCloexec); + return fd; +end; + +(* Waits until t, a struct timespec of the monotonic clock: macOS has + no clock_nanosleep, so nanosleep sleeps what is left, again after + EINTR. *) +proc sleepUntil*(t: ^U8); +var now, left: [2]I64; at: ^I64; d: I64; +begin + at := ^I64(t); + repeat + _ := clock_gettime(clockMonotonic, ^U8(SYSTEM.ADR(now[0]))); + d := (at[0] - now[0]) * 1000000000 + at[1] - now[1]; + if d <= 0 then return; end; + left := [d div 1000000000, d mod 1000000000]; + _ := nanosleep(^U8(SYSTEM.ADR(left[0])), nil); + until false; +end; + +(* The number of processors this program may run on, or 0 if the + system doesn't say: those online, as macOS binds a program to none + of them. *) +proc processors*: INT; +begin + return sysconf(58); (* _SC_NPROCESSORS_ONLN *) +end; + +(* The process and the user at the other end of the Unix socket fd, + as the system recorded them when it connected, and 0; or -1. The + user is in a struct xucred, LOCAL_PEERCRED's, and the process is + asked for alone, LOCAL_PEERPID. *) +proc peer*(fd: I32; var pid, uid: INT): I32; +var cred: [16]U64; size: U32; p: ^U8; q: ^U32; id: I32; +begin + p := ^U8(SYSTEM.ADR(cred[0])); + size := U32(SIZE([16]U64)); + if getsockopt(fd, 0, 1, p, SYSTEM.ADR(size)) # 0 then return -1; end; + q := ^U32(p + ucUidAt); + uid := INT(q^); + size := 4; + if getsockopt(fd, 0, 2, ^U8(SYSTEM.ADR(id)), SYSTEM.ADR(size)) # 0 then return -1; end; + pid := INT(id); + return 0; +end; + +(* Sends n bytes at buf on the socket fd, without waiting, and without + SIGPIPE where the other end is gone: how many were sent, or -1. + macOS's send waits on a Unix socket though MSG_DONTWAIT is given, so + the socket is made nonblocking for it, as it was before after. *) +proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT; +var f: I32; r: INT; e: ^I32; err: I32; +begin + f := fcntl(fd, fGetfl); + if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f | oNonblock); end; + r := send(fd, buf, n, msgNosignal | msgDontwait); + e := __error(); + err := e^; + if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f); end; + e^ := err; + return r; end; end CAbi. diff --git a/lib/CAbi.linux-x86_64.raz b/lib/CAbi.linux-x86_64.raz index bf86f21..c2b94bd 100644 --- a/lib/CAbi.linux-x86_64.raz +++ b/lib/CAbi.linux-x86_64.raz @@ -1,7 +1,7 @@ (* CAbi: what the C library fixes for Sys over C on linux-x86_64: the numbers of its flags, requests, signals and limits, where the fields of its structs lie, an At the offset and a Len the width, - its errnos beside Linux's, and errno and closeFrom. + its errnos beside Linux's, and the procedures that differ. Written by tools/cabi.c, from the system's own headers; not to be edited, but written again. *) @@ -86,6 +86,7 @@ tiocgwinsz* = 21523; tiocswinsz* = 21524; tiocsctty* = 21518; + ptyHeld* = 0; pollin* = 1; pollout* = 4; clockRealtime* = 0; @@ -115,6 +116,7 @@ sockaddrUnLen* = 110; sunPathAt* = 2; sunPathLen* = 108; + unixAbstract* = 1; sockaddrInLen* = 16; sinPortAt* = 2; sinAddrAt* = 4; @@ -205,6 +207,14 @@ extern proc __errno_location: ^I32; extern proc syscall(n: INT; ...): INT; +extern proc pipe2(fds: ^I32; flags: I32): I32; +extern proc accept4(fd: I32; addr: ^U8; len: ^U32; flags: I32): I32; +extern proc getrandom(buf: ^U8; n: UINT; flags: U32): INT; +extern proc memfd_create(name: ^U8; flags: U32): I32; +extern proc clock_nanosleep(clock, flags: I32; t, left: ^U8): I32; +extern proc sched_getaffinity(pid: I32; size: UINT; mask: ^U8): I32; +extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32; +extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT; (* errno, this thread's *) proc errno*: ^I32; @@ -218,6 +228,77 @@ begin if hi < 0 then hi := 0FFFFFFFFH; end; _ := syscall(436, lo, hi, 0); +end; + +(* A pipe, its two fds put at fds, taking flags, oCloexec and + oNonblock, at once: 0, or -1 with errno set, as C's calls are. *) +proc makePipe*(fds: ^I32; flags: I32): I32; +begin + return pipe2(fds, flags); +end; + +(* The next connection to the socket fd, closed on exec; or -1. *) +proc accepted*(fd: I32): I32; +begin + return accept4(fd, nil, nil, sockCloexec); +end; + +(* The kernel's random bytes, at most n, put at buf: how many, or -1. *) +proc random*(buf: ^U8; n: UINT): INT; +begin + return getrandom(buf, n, 0); +end; + +(* A file in memory, of no bytes, with no name, closed on exec: its + fd, or -1. *) +proc memFile*: I32; +begin + return memfd_create(SYSTEM.PTR("raz\0"), mfdCloexec); (* the name /proc shows *) +end; + +(* Waits until t, a struct timespec of the monotonic clock, again + after EINTR. *) +proc sleepUntil*(t: ^U8); +begin + repeat until clock_nanosleep(clockMonotonic, timerAbstime, t, nil) # eIntr; +end; + +(* The number of processors this program may run on, or 0 if the + system doesn't say. *) +proc processors*: INT; +var mask: [1024]U8; i, b, count: INT; +begin + 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 *) + if sched_getaffinity(0, UINT(LEN(mask)), SYSTEM.ADR(mask[0])) # 0 then return 0; end; + count := 0; + for i := 0 to LEN(mask) - 1 do + for b := 0 to 7 do + if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end; + end; + end; + return count; +end; + +(* The process and the user at the other end of the Unix socket fd, + as the system recorded them when it connected, and 0; or -1. *) +proc peer*(fd: I32; var pid, uid: INT): I32; +var cred: [16]U64; size: U32; p: ^U8; q: ^U32; +begin + p := ^U8(SYSTEM.ADR(cred[0])); + size := U32(SIZE([16]U64)); + if getsockopt(fd, solSocket, soPeercred, p, SYSTEM.ADR(size)) # 0 then return -1; end; + q := ^U32(p + ucPidAt); + pid := INT(I32(q^)); + q := ^U32(p + ucUidAt); + uid := INT(q^); + return 0; +end; + +(* Sends n bytes at buf on the socket fd, without waiting, and without + SIGPIPE where the other end is gone: how many were sent, or -1. *) +proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT; +begin + return send(fd, buf, n, msgNosignal | msgDontwait); end; end CAbi. diff --git a/lib/Files.raz b/lib/Files.raz index a62457a..f07bd42 100644 --- a/lib/Files.raz +++ b/lib/Files.raz @@ -270,13 +270,22 @@ end; (* realPath and removeTree in a scratch tree, with links in it and one - out of it. *) + out of it. What realPath gives is under /tmp as realPath gives it, + which on a Mac is /private/tmp, /tmp being a link to it. *) proc testTree; const T = "/tmp/raz-files-test.d"; Out = "/tmp/raz-files-test.out"; -var p, q: Buf.Buf; here, now: []const U8; r: INT; +var p, q, rt, ro: Buf.Buf; here, now, realT, realOut: []const U8; r: INT; begin Buf.init(p, Heap.heap); Buf.init(q, Heap.heap); + Buf.init(rt, Heap.heap); + Buf.init(ro, Heap.heap); + if realPath("/tmp", rt) # 0 then Rt.stop("realPath: /tmp"); end; + Buf.str(ro, Buf.bytes(rt)); + Buf.str(rt, "/raz-files-test.d"); + Buf.str(ro, "/raz-files-test.out"); + realT := Buf.bytes(rt); + realOut := Buf.bytes(ro); _ := removeTree(T); _ := removeTree(Out); if (Sys.makeDir(T) # 0) or (Sys.makeDir(join(p, T, "/a")) # 0) @@ -293,12 +302,12 @@ or (Sys.symlink(Out, join(p, T, "/a/ex")) # 0) then Rt.stop("Files: links"); end; - wantReal(join(p, T, "/rel/f"), join(q, T, "/a/b/f"), 0, "realPath: a relative link"); - wantReal(join(p, T, "/abs/b/../b/./f"), join(q, T, "/a/b/f"), 0, "realPath: absolute link, .. and ."); - wantReal(join(p, T, "/a/up/f"), join(q, T, "/a/b/f"), 0, "realPath: a link read from its directory"); - wantReal(join(p, T, "/a/"), join(q, T, "/a"), 0, "realPath: a trailing slash"); - wantReal(join(p, T, "/a/b/../../abs/b"), join(q, T, "/a/b"), 0, "realPath: .. then a link"); - wantReal(join(p, T, "/a/ex/keep"), join(q, Out, "/keep"), 0, "realPath: a link out of the tree"); + wantReal(join(p, T, "/rel/f"), join(q, realT, "/a/b/f"), 0, "realPath: a relative link"); + wantReal(join(p, T, "/abs/b/../b/./f"), join(q, realT, "/a/b/f"), 0, "realPath: absolute link, .. and ."); + wantReal(join(p, T, "/a/up/f"), join(q, realT, "/a/b/f"), 0, "realPath: a link read from its directory"); + wantReal(join(p, T, "/a/"), join(q, realT, "/a"), 0, "realPath: a trailing slash"); + wantReal(join(p, T, "/a/b/../../abs/b"), join(q, realT, "/a/b"), 0, "realPath: .. then a link"); + wantReal(join(p, T, "/a/ex/keep"), join(q, realOut, "/keep"), 0, "realPath: a link out of the tree"); wantReal(join(p, T, "/a/nope"), "", Sys.errNoEntry, "realPath: a missing part"); wantReal(join(p, T, "/a/b/f/.."), "", -20, "realPath: .. of a file"); wantReal(join(p, T, "/loop"), "", -40, "realPath: a link loop"); @@ -320,6 +329,8 @@ if removeTree(Out) # 0 then Rt.stop("removeTree: the outside"); end; Buf.done(p); Buf.done(q); + Buf.done(rt); + Buf.done(ro); end; (* The module's test. *) diff --git a/lib/Math.raz b/lib/Math.raz index eb75ddf..3d3d60f 100644 --- a/lib/Math.raz +++ b/lib/Math.raz @@ -5,10 +5,12 @@ polynomials' coefficients are fdlibm's. Each is within an ulp, a unit in the result's last place. + The square root, mul and divMod's division are the machine's own, + from Arith, one file per machine; this file keeps no machine code. + Left out: sinh, cosh, fmod and hypot, until a program needs them. *) module Math; -import Check, Rt; -import SYSTEM; +import Arith, Check, Rt; const pi* = 3.141592653589793; (* the F64 nearest to pi *) @@ -33,12 +35,13 @@ return bits(x) shr 63 = 1; end; -(* The square root of x, exact to the last bit; NaN for x below 0. *) +(* The square root of x, exact to the last bit; NaN for x below 0: the + machine's own. A procedure that only returns is made in place, and + then Arith.sqrt's one instruction is too, with no call. *) proc sqrt*(x: F64): F64; -code - sqrtsd xmm0, xmm0; - ret; -end sqrt; +begin + return Arith.sqrt(x); +end; (* The largest whole number not above x. One of 2^52 or more is whole already, and so are an infinity and NaN. *) @@ -437,28 +440,16 @@ (* a times b: the low 64 bits of the product, and the high. *) proc mul*(a, b: U64): (U64, U64); -code - mov rax, rdi; - mul rsi; - ret; -end mul; - -(* hi, lo divided by d, by the machine's one instruction; it faults if hi >= d. *) -proc div128(hi, lo, d: U64): (U64, U64); -code - mov rcx, rdx; - mov rdx, rdi; - mov rax, rsi; - div rcx; - ret; -end div128; +begin + return Arith.mul(a, b); +end; (* hi, lo (a 128-bit number, hi its high word) divided by d: the quotient and the remainder. hi >= d, whose quotient doesn't fit a word, and d = 0 stop the program, as a division by zero does. *) proc divMod*(hi, lo, d: U64): (U64, U64); begin if hi >= d then Rt.stop("Math.divMod: hi >= d, the quotient doesn't fit a word"); end; - return div128(hi, lo, d); + return Arith.div128(hi, lo, d); end divMod; (* 64 bits of t from bit s on, the first bit of t[0] being 0. *) diff --git a/lib/Opt.raz b/lib/Opt.raz index c2c5ce7..8dc0286 100644 --- a/lib/Opt.raz +++ b/lib/Opt.raz @@ -587,7 +587,9 @@ begin outR, outW := Sys.pipe(); errR, errW := Sys.pipe(); - pid := Sys.spawn({path: "/proc/self/exe", args: c.args, env: [c.mode], fds: [0, outW, errW]}); + (* this program again, by the path it was run by, which has a slash in + it: raztest gives one, and Linux's /proc/self/exe is no Mac's *) + pid := Sys.spawn({path: Files.arg(0), args: c.args, env: [c.mode], fds: [0, outW, errW]}); Sys.close(outW); Sys.close(errW); if pid < 0 then Rt.stop("Opt: can't run the test's cases"); end; diff --git a/lib/Rt.darwin-arm64.raz b/lib/Rt.darwin-arm64.raz index b2ce13e..752f833 100644 --- a/lib/Rt.darwin-arm64.raz +++ b/lib/Rt.darwin-arm64.raz @@ -1,15 +1,31 @@ (* The run time, for macOS on arm64, with lib/Rt.raz's interface, which - every file of Rt keeps. The compiler finds exit, fail and cExit by - these names. exit runs the procedures atExit registered, then ends - the program by C's exit, which the entry point gives cExit, as every - program on a Mac reaches the kernel through libSystem; fail says - what failed, with its values, and stop its message, and they end it - with status 2; and a fault the machine catches, a nil pointer or - procedure or a stack overflow, is told by a handler, on a stack of - its own, as on Linux, and ends it so too. A failure is told by its - address, as on Linux in a program built with raz -s: the places, the - calls under way and the profiler are what PLAN.md 5's step 7 brings - here; place, trace and startProfile do nothing yet. *) + every file of Rt keeps, and its work: ending the program; fail, which + the compiler's code calls when a check fails; stop, for the library's + own failures; the handlers that say where the program was when a + signal stopped it; trace; and the profiler. The compiler finds fail, + exit, cExit, places, profiler, startProfile, teller, calls, placer + and place by these names. + + It is lib/Rt.raz's, but for what the Mac does otherwise: + - Every program reaches the kernel through libSystem, so Rt calls C, + by extern, and exit ends the program by C's exit, which the entry + point gives cExit. Rt imports nothing, so its body runs first. + - macOS loads a program at an address of its choosing, the same + image moved by a slide that dyld says, so an address the program + meets is the slide past the one the compiler laid out, which the + places hold (linked). + - The frames' chain is x29's: a frame record of x29 and x30, the + caller's frame and the return address, that x29 points at. A call + is the bl 4 bytes before the return address. A procedure's busiest + variables are in x19 to x23 (regs), as Gen.arm64.raz keeps them. + - The kernel hands a handler a siginfo and a ucontext laid out as + and have them (onSignal), and + the handler returns through libSystem's _sigtramp, which needs no + sigReturn of Rt's; nor is a division fault a signal on arm64, + where the code checks for it (Gen.divide) and calls fail. + A program built with raz -s has no places, so a failure is told by + its address, and no calls; one built with -noprofile no profiler. + -bare is not for a Mac. *) module Rt; import SYSTEM; @@ -17,13 +33,40 @@ Full*: ERROR = "too many procedures to run at exit"; (* atExit's *) MaxAtExit = 32; Digits = "0123456789abcdef"; - (* the signals a fault raises, and sigaction's flags SA_ONSTACK, - SA_RESETHAND and SA_SIGINFO, as macOS's has them *) - SigIll = 4; SigTrap = 5; SigFpe = 8; SigBus = 10; SigSegv = 11; + (* the signals a fault raises, and SIGPROF, as macOS's + has them *) + SigIll = 4; SigTrap = 5; SigFpe = 8; SigBus = 10; SigSegv = 11; SigProf = 27; + (* sigaction's flags: SA_ONSTACK, SA_RESETHAND and SA_SIGINFO; and + for the profiler, SA_ONSTACK, SA_RESTART, so that a call a sample + breaks into goes on, and SA_SIGINFO *) Flags = 1H + 4H + 40H; + ProfFlags = 1H + 2H + 40H; Low = 100000000H; (* page zero: no address below this is ever mapped *) + MaxSamples = 100000; + MaxProcs = 8192; + MaxPlaces = 65536; + (* the line table's special opcodes, as the compiler makes them *) + LineBase = -5; + LineRange = 14; + OpcodeBase = 13; + Depth = 24; (* the callers noted with each sample, at most *) + (* mmap's PROT_READ | PROT_WRITE and MAP_PRIVATE | MAP_ANON *) + Prot = 3; + Map = 1002H; type + (* A row of the line table: the code from address at on comes from + line and column col of file, numbered from 1 *) + Row = record at: UINT; file, line, col: INT; end; + (* A procedure, from address start to stop, called name, and its + count variables from first on; it saves the registers of its + variables, bits of regs, a quadword each from saveAt in its frame *) + Proc = record start, stop, name, first, count, saves: U32; saveAt: I32; end; + (* A variable of a procedure, at off from its frame, shown by kind: + 1 a signed integer, 2 an unsigned one, 3 a BOOL, 4 an address, + 5 a real; plus its size times 16, and 256 if the frame holds its + address, or 512 times 1 + i if it is in register i of regs *) + Local = record name: U32; off: I32; kind: U32; end; (* What sigaction and sigaltstack take, as macOS lays them out *) Action = record handler: proc(sig: I32; info, ctx: ^U8); mask, flags: I32; end; Stack = record sp: ^U8; size: INT; flags: I32; end; @@ -31,19 +74,51 @@ extern proc write(fd: I32; buf: ^U8; n: UINT): INT; extern proc sigaction(sig: I32; act, old: ^U8): I32; extern proc sigaltstack(ss, old: ^U8): I32; +extern proc _dyld_get_image_vmaddr_slide(image: U32): INT; +extern proc getenv(name: ^U8): ^U8; +extern proc mmap(addr: ^U8; n: UINT; prot, flags, fd: I32; off: I64): ^U8; +extern proc setitimer(which: I32; value, old: ^U8): I32; var atExits: [MaxAtExit]proc; numAtExit: INT; ending: INT; (* the status exit was given, once it has been *) cExit: proc(status: I32); (* C's exit, set first thing *) - placer: proc(a: UINT); (* place, set first thing, or nil under raz -s *) - profiler: proc; (* startProfile, set first thing, or nil *) + (* Set first thing too: where the line table is in them, where the + program's code starts and stops, as the compiler laid it out, the + numbers of procedures and variables; the procedures and variables, + and their names; and the line table, DWARF's line program. The + linker makes them. *) + places: ^INT; + slide: UINT; (* how far dyld moved the program from where the places have it *) line: [256]U8; (* the message being made *) + (* x19 to x23 in the frame being told of, where the compiler keeps a + procedure's busiest variables *) + regs: [5]UINT; + known: BOOL; (* regs are as the code a signal stopped had them *) + (* the frame record a procedure stopped at its first instruction + would have made, the caller's fp and lr, made by onSignal *) + unmade: [2]UINT; lineLen: INT; act: Action; alt: Stack; - altStack: [65536]U8; (* where the handler runs, even when the stack is full *) + altStack: [65536]U8; (* where the handlers run, even when the stack is full *) + (* the profile: where the program was at each sample, and how many + samples fell in each procedure and at each place *) + samples: [MaxSamples]UINT; + (* the callers at each sample, by their return addresses: a row of + Depth for each, a short one ended by 0; mapped when profiling *) + chains: ^UINT; + numSamples: INT; + profiler: proc; (* startProfile, put here by the entry point, or nil *) + (* calls, put here by the entry point, or nil under raz -s *) + teller: proc(ip, bp: UINT; vars: BOOL); + (* place, put here by the entry point, or nil, as teller *) + placer: proc(a: UINT); + procCount: [MaxProcs]INT; + procTotal: [MaxProcs]INT; (* the samples each procedure was on the chain of *) + placeCount: [MaxPlaces]INT; + timerv: [4]INT; (* setitimer's interval and value *) (* Registers p to run when the program ends by exit *) proc atExit*(p: proc): ERROR; @@ -54,6 +129,8 @@ return nil; end; +proc profile; forward; + (* The status exit was given, while the procedures atExit registered run; 0 before *) proc exitStatus*: INT; @@ -63,7 +140,7 @@ (* Runs the procedures registered with atExit, the last first, each taken off first so that it runs once, then ends the program with - status *) + status, through C's exit *) proc exit*(status: INT); var p: proc; begin @@ -85,8 +162,8 @@ exit(2); end; -(* Messages, made in line, as lib/Rt.raz makes them, one byte kept for - the line feed, and written by say in one piece *) +(* Messages, made in line, one byte kept for the line feed, and + written by say in one piece *) proc put(s: []const U8); var i: INT; begin @@ -142,37 +219,378 @@ lineLen := 0; end; -(* Puts where the code at address a is: its address, for now *) +(* The address the compiler laid out for the code at address a *) +proc linked(a: UINT): UINT; +begin + return a - slide; +end; + +(* Whether a is in the program's own code, not C's *) +proc inCode(a: UINT): BOOL; +begin + return (linked(a) >= UINT(places[1])) and (linked(a) < UINT(places[2])); +end; + +(* The names, after the procedures and variables *) +proc names: ^U8; +begin + return ^U8(places + 5) + 28 * places[3] + 12 * places[4]; +end; + +(* The line table *) +proc lines: ^U8; +begin + return ^U8(places) + places[0]; +end; + +(* The number p points at, in LEB128, unsigned, and where the next + thing starts *) +proc uleb(p: ^U8): (INT, ^U8); +var n, shift: INT; +begin + n := 0; + shift := 0; + while p^ >= 80H do + n := n | INT(p^ & 7FH) shl shift; + INC(shift, 7); + p := p + 1; + end; + return n | INT(p^) shl shift, p + 1; +end; + +(* The same, signed *) +proc sleb(p: ^U8): (INT, ^U8); +var n, shift, b: INT; +begin + n := 0; + shift := 0; + repeat + b := INT(p^); + p := p + 1; + n := n | (b & 7FH) shl shift; + INC(shift, 7); + until b < 80H; + if (shift < 64) and (b & 40H # 0) then n := n | (-1 shl shift); end; (* its sign *) + return n, p; +end; + +(* The path of the line table's file f, as a C string: the files' + names follow the table's header of 29 bytes, each ending in a zero + and followed by three numbers *) +proc path(f: INT): ^U8; +var p: ^U8; i, k: INT; +begin + p := lines() + 29; + for i := 2 to f do + while p^ # 0 do p := p + 1; end; + p := p + 1; + for k := 1 to 3 do _, p := uleb(p); end; + end; + return p; +end; + +(* The row of the line table that the code at address a, as linked, + comes from, the one with the highest address up to a, and its + number; or, if k >= 0, row number k. The number is -1 if there is + none. As lib/Rt.raz's row, whose comment says how. *) +proc row(a: UINT; k: INT): (Row, INT); +var p, stop: ^U8; q: ^U32; at: ^UINT; r, best: Row; n, found, op, v: INT; +begin + p := lines(); + q := ^U32(p); + stop := p + 4 + INT(q^); + q := ^U32(p + 6); + p := p + 10 + INT(q^); (* the program, past the header *) + r := {file: 1, line: 1}; + n := 0; + found := -1; + while p < stop do + op := INT(p^); + p := p + 1; + if op >= OpcodeBase then + op := op - OpcodeBase; + r.at := r.at + UINT(op div LineRange); + r.line := r.line + LineBase + op mod LineRange; + op := 1; + elsif op = 0 then (* extended: its length, then which *) + v, p := uleb(p); + if p^ = 1 then r := {file: 1, line: 1}; (* end_sequence *) + elsif p^ = 2 then at := ^UINT(p + 1); r.at := at^; (* set_address *) + end; + p := p + v; + elsif op = 2 then v, p := uleb(p); r.at := r.at + UINT(v); (* advance_pc *) + elsif op = 3 then v, p := sleb(p); r.line := r.line + v; (* advance_line *) + elsif op = 4 then r.file, p := uleb(p); (* set_file *) + elsif op = 5 then r.col, p := uleb(p); (* set_column *) + end; + if op = 1 then (* copy, or a special opcode: the row r *) + if n = k then return r, n; end; + if (k < 0) and (r.at <= a) and ((found < 0) or (r.at >= best.at)) then + best := r; + found := n; + end; + INC(n); + end; + end; + return best, found; +end; + +(* Puts where row r comes from, as file:line:col *) +proc putRow(r: Row); +begin + putStr(path(r.file)); + put(":"); + putInt(r.line); + put(":"); + putInt(r.col); +end; + +(* The compiler's, as fail is: puts where the code at address a comes + from, as file:line:col: and a space, if a is in the program's code *) +proc place*(a: UINT); +var r: Row; n: INT; +begin + if not inCode(a) then return; end; + r, n := row(linked(a), -1); + if n < 0 then return; end; + putRow(r); + put(": "); +end; + +(* Puts where the code at address a is: place, or, in a program built + with raz -s, which keeps no places, the address *) proc where(a: UINT); begin - if placer # nil then placer(a); end; - put("at "); - putHex(a); - put(": "); + if placer # nil then placer(a); + else + put("at "); + putHex(a); + put(": "); + end; end; -(* Where the code at address a comes from: not told yet *) -proc place*(a: UINT); +(* The frame pointer of the procedure that calls it, which a code + procedure leaves as it is. Rt's code procedures are written as their + words' bytes, in db, each instruction in a comment beside it: when + BOOT's release builds src/, it reads this file for Rt's interface, + and knows only x86-64's instructions, but db is in both assemblers. + Written so until BOOT names a release that skips a code procedure + in a file read for its interface. *) +proc framePtr: UINT; +code + db 0E0H, 03H, 1DH, 0AAH; (* mov x0, x29 *) + db 0C0H, 03H, 5FH, 0D6H; (* ret *) +end framePtr; + +(* The frame of the procedure that called the one calling this *) +proc callerFrame: UINT; +var q: ^UINT; begin - _ := a; + q := ^UINT(framePtr()); (* callerFrame's own: its caller's frame is in it *) + q := ^UINT(q^); + return q^; end; -(* The calls under way: not told yet *) +(* The procedure whose code holds address a, or nil. The places keep + the low 32 bits of a procedure's start and stop; the program lies + at 4 GB and up, as linked, within one stretch of 4 GB, so the low + 32 bits of an address in its code are in the same order as the + address. *) +proc procAt(a: UINT): ^Proc; +var p: ^Proc; i: INT; +begin + if (places = nil) or not inCode(a) then return nil; end; + p := ^Proc(places + 5); + a := linked(a) & 0FFFFFFFFH; + for i := 0 to places[3] - 1 do + if (UINT(p[i].start) <= a) and (a < UINT(p[i].stop)) then return p + i; end; + end; + return nil; +end; + +(* x with six figures after the point, or as m e n beyond them *) +proc putReal(x: F64); +var e, i: INT; f: U64; +begin + if x # x then put("nan"); return; end; + if x < 0.0 then put("-"); x := -x; end; + if (x > 1.0) and (x * 2.0 = x) then put("inf"); return; end; + e := 0; + while x >= 1.0E15 do x := x / 10.0; INC(e); end; + while (x # 0.0) and (x < 0.001) do x := x * 10.0; DEC(e); end; + f := U64(x * 1000000.0 + 0.5); + putInt(INT(f div 1000000)); + put("."); + for i := 1 to 6 do + f := f mod 1000000 * 10; + put(Digits[INT(f div 1000000)..INT(f div 1000000) + 1]); + end; + if e # 0 then put("e"); putInt(e); end; +end; + +(* The value of variable l of the frame at bp *) +proc putValue(bp: UINT; l: ^Local); +var a: ^U8; w: ^UINT; h: ^U16; s: ^U32; f: ^F32; d: ^F64; v: UINT; bits: INT; +begin + a := ^U8(bp) + INT(l^.off); + if l^.kind shr 9 # 0 then a := ^U8(SYSTEM.ADR(regs[INT(l^.kind shr 9) - 1])); end; + w := ^UINT(a); + if l^.kind & 256 # 0 then a := ^U8(w^); w := ^UINT(a); end; + h := ^U16(a); s := ^U32(a); f := ^F32(a); d := ^F64(a); + bits := INT(l^.kind shr 4 & 15) * 8; + match bits of + | 8: v := UINT(a^); + | 16: v := UINT(h^); + | 32: v := UINT(s^); + | else: v := w^; + end; + match l^.kind & 15 of + | 1: + if (bits < 64) and (v shr (bits - 1) # 0) then putInt(INT(v) - INT(1) shl bits); + else putInt(INT(v)); + end; + | 2: putInt(INT(v)); + | 3: if v # 0 then put("true"); else put("false"); end; + | 4: if v = 0 then put("nil"); else putHex(v); end; + | else: if bits = 32 then putReal(F64(f^)); else putReal(d^); end; + end; +end; + +(* Says that n more calls are as the one before, if there are any; + the lines it takes *) +proc more(n: INT): INT; +begin + if n = 0 then return 0; end; + put(" and "); + putInt(n); + put(" more the same"); + say; + return 1; +end; + +(* x19 to x23, into p[0] to p[4] *) +proc liveRegs(p: ^UINT); +code + db 13H, 50H, 00H, 0A9H; (* stp x19, x20, [x0] *) + db 15H, 58H, 01H, 0A9H; (* stp x21, x22, [x0, #16] *) + db 17H, 10H, 00H, 0F9H; (* str x23, [x0, #32] *) + db 0C0H, 03H, 5FH, 0D6H; (* ret *) +end liveRegs; + +(* An address in the code of the procedure that calls it: the return + address, in x30 *) +proc here: UINT; +code + db 0E0H, 03H, 1EH, 0AAH; (* mov x0, x30 *) + db 0C0H, 03H, 5FH, 0D6H; (* ret *) +end here; + +(* regs as the caller of p's frame at bp left them, where p saved them *) +proc restore(p: ^Proc; bp: UINT); +var i, j: INT; q: ^UINT; +begin + if p = nil then return; end; + j := 0; + for i := 0 to 4 do + if p^.saves shr i & 1 # 0 then + q := ^UINT(^U8(bp) + INT(p^.saveAt) + 8 * j); + regs[i] := q^; + INC(j); + end; + end; +end; + +(* Says the calls under way, a line each, from the one at address ip + whose frame is at bp: where each is, and its variables, unless vars + is false for the first. At most 20 lines; a frame that isn't the + program's ends them. Calls of one procedure from one place, as in a + recursion that overflowed the stack, are told once, and counted. *) +proc calls(ip, bp: UINT; vars: BOOL); +var p, last: ^Proc; l: ^Local; i, n, same: INT; q: ^UINT; lastIp, x, xip: UINT; saved: BOOL; +begin + (* the registers as they are, then as each frame from this one out + to bp's found them; or as a signal's context had them *) + if not known then + liveRegs(SYSTEM.ADR(regs[0])); + x := framePtr(); + xip := here(); + while (x # bp) and (x & 7 = 0) and (x # 0) do + restore(procAt(xip), x); + q := ^UINT(x); + if q[0] <= x then break; end; + xip := q[1] - 4; + x := q[0]; + end; + end; + saved := vars; (* not in a prologue: the frame has saved them *) + n := 0; + same := 0; + last := nil; + lastIp := 0; + while n < 20 do + p := procAt(ip); + if p = nil then break; end; + if (p = last) and (ip = lastIp) then + INC(same); + else + n := n + more(same); + same := 0; + last := p; + lastIp := ip; + put(" in "); + putStr(names() + INT(p^.name)); + put(" at "); + where(ip); + l := ^Local(^U8(places + 5) + 28 * places[3]) + INT(p^.first); + if not vars or (p^.count = 0) then DEC(lineLen, 2); end; (* where's ": " *) + for i := 0 to INT(p^.count) - 1 do + if vars then + if i > 0 then put(", "); end; + putStr(names() + INT(l[i].name)); + put(" = "); + putValue(bp, l + i); + end; + end; + say; + INC(n); + vars := true; + end; + if saved then restore(p, bp); end; + saved := true; + (* each frame is above the one it called, which ends a chain gone + wrong; but unmade, wherever it is, leads to the stack *) + q := ^UINT(bp); + if (bp & 7 # 0) or ((q[0] <= bp) and (bp # UINT(SYSTEM.ADR(unmade[0])))) then break; end; + ip := q[1] - 4; (* the call, the bl before its return address *) + bp := q[0]; + end; + _ := more(same); +end; + +(* Says on standard error the calls under way, from the one that calls + it, each with its variables, as after a failed check. *) proc trace*; +var q: ^UINT; begin + q := ^UINT(framePtr()); + calls(q[1] - 4, q[0], true); end; (* A check failed in the code at address at: says where, and what - failed, as lib/Rt.raz's fail, whose comment says what each kind is, - then ends the program by exit with status 2. The registers that - x86-64's trap report shows are none here. *) + failed, then the calls under way, as lib/Rt.raz's fail, whose + comment says what each kind is, then ends the program by exit with + status 2. The registers that x86-64's trap report shows, rdi and + rsi, are none here. *) proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT); begin _ := rdi; _ := rsi; where(at); - if what = 4 then put("stopped by a nil pointer"); - elsif what = 5 then put("stopped by a division fault"); - elsif what = 6 then put("stopped by a stack overflow"); + if (what >= 4) and (what <= 6) then + put("stopped by "); + if what = 4 then put("a nil pointer"); + elsif what = 5 then put("a division fault"); + else put("a stack overflow"); + end; elsif what = 0 then put("index "); putInt(a); elsif what = 7 then put("a view at index "); putInt(a); @@ -185,28 +603,36 @@ end; if what < 2 then put(" is out of range for a length of "); putInt(len); end; say; + if teller # nil then teller(at, callerFrame(), true); end; exit(2); end; -(* A fault stops the program: says where it was and why on standard - error, then ends it by exit with status 2, as a failed check does. - info and ctx are the kernel's siginfo and ucontext: the address that - faulted is at 24 in siginfo, and the registers at uc_mcontext, a - pointer at 48 in ucontext, past 16 bytes of the exception's state: - x0 to x28, then fp, lr, sp and pc. *) +(* A fault stops the program: says where it was and why, and the calls + under way, on standard error, then ends it by exit with status 2, as + a failed check does. info and ctx are the kernel's siginfo and + ucontext: the address that faulted is at 24 in siginfo, and the + registers at uc_mcontext, a pointer at 48 in ucontext, past the 16 + bytes of the exception's state: x0 to x28, then fp, lr, sp and pc. + A stack overflow can stop a procedure at its first instruction, the + stp that makes its frame record: it has no frame yet, so the calls + are told from one made of the fp and lr it found, unmade. *) proc onSignal(sig: I32; info, ctx: ^U8); -var adr, sp, pc: UINT; q: ^UINT; why: []const U8; +var adr, sp, pc, fp, lr: UINT; q: ^UINT; p: ^Proc; why: []const U8; begin q := ^UINT(info + 24); adr := q^; q := ^UINT(ctx + 48); q := ^UINT(q^ + 16); + regs := [q[19], q[20], q[21], q[22], q[23]]; + known := true; + fp := q[29]; + lr := q[30]; sp := q[31]; pc := q[32]; if sig = SigFpe then why := "a division fault"; elsif pc < Low then why := "a nil procedure"; - pc := q[30] - 4; (* the call, by its return address in lr *) + pc := lr - 4; (* the call, by its return address *) elsif adr < Low then why := "a nil pointer"; elsif adr - sp + 100000H < 200000H then why := "a stack overflow"; (* within a megabyte of sp *) elsif (sig = SigIll) or (sig = SigTrap) then why := "a trap"; @@ -216,16 +642,161 @@ put("stopped by "); put(why); say; + if teller # nil then + p := procAt(pc); + if (p # nil) and (linked(pc) & 0FFFFFFFFH = UINT(p^.start)) then + unmade := [fp, lr]; + fp := UINT(SYSTEM.ADR(unmade[0])); + end; + (* the variables of a frame the stack overflowed in may be past it *) + teller(pc, fp, why # "a stack overflow"); + end; exit(2); end; -(* The profiler: none yet *) +(* SIGPROF, every millisecond the program runs, in any of its threads: + notes where it was, and the calls under way, up the chain of frames. + The chain is followed only through the program's own code, whose + frames all keep it in x29: C's code may not. *) +proc onProf(_sig: I32; _info, ctx: ^U8); +var n, k: INT; q, f, row: ^UINT; ip, bp: UINT; +begin + n := XADD(numSamples, 1); + if n >= MaxSamples then return; end; + q := ^UINT(ctx + 48); + q := ^UINT(q^ + 16); + bp := q[29]; + ip := q[32]; + samples[n] := ip; + row := chains + n * Depth; + k := 0; + if (places # nil) and inCode(ip) then + while (k < Depth) and (bp # 0) and (bp & 7 = 0) do + f := ^UINT(bp); + if not inCode(f[1]) then break; end; + row[k] := f[1] - 4; (* the call, by its return address *) + INC(k); + if f[0] <= bp then break; end; + bp := f[0]; + end; + end; + if k < Depth then row[k] := 0; end; +end; + +(* The number of the procedure the code at address a is in, or -1 *) +proc procNum(a: UINT): INT; +var p: ^Proc; +begin + p := procAt(a); + if p = nil then return -1; end; + return p - ^Proc(places + 5); +end; + +(* The number of the line table's row the code at address a comes + from, or -1 *) +proc placeAt(a: UINT): INT; +var n: INT; +begin + if not inCode(a) then return -1; end; + _, n := row(linked(a), -1); + return n; +end; + +(* Puts the share of n that k is, as a percentage four wide *) +proc putShare(k, n: INT); +var i: INT; +begin + i := k * 100 div n; + if i < 10 then put(" "); elsif i < 100 then put(" "); else put(" "); end; + putInt(i); + put("%"); +end; + +(* Says the ten that took most of count's n samples, by name, with + their totals beside them if total isn't empty *) +proc top(count: []INT; total: []const INT; n: INT; byPlace: BOOL); +var i, k, best: INT; p: ^Proc; r: Row; +begin + p := ^Proc(places + 5); + for k := 1 to 10 do + best := 0; + for i := 1 to LEN(count) - 1 do + if count[i] > count[best] then best := i; end; + end; + if count[best] = 0 then return; end; + putShare(count[best], n); + if LEN(total) > 0 then put(" "); putShare(total[best], n); end; + put(" "); + if byPlace then + r, _ := row(0, best); + putRow(r); + else putStr(names() + INT(p[best].name)); + end; + say; + count[best] := 0; + end; +end; + +(* The compiler's, as fail is: if RAZ_PROFILE is set, samples the + program every millisecond of its time, and says at its end what took + it (profile) *) proc startProfile*; +var e: ^U8; pa: Action; begin + e := getenv(SYSTEM.PTR("RAZ_PROFILE\0")); + if (e = nil) or (e^ = 0) then return; end; + chains := ^UINT(mmap(nil, UINT(MaxSamples * Depth * SIZE(UINT)), Prot, Map, -1, 0)); + if INT(chains) = -1 then chains := nil; return; end; + pa := {handler: onProf, flags: ProfFlags}; + _ := sigaction(SigProf, ^U8(SYSTEM.ADR(pa)), nil); + timerv := [0, 1000, 0, 1000]; (* every millisecond, from one on *) + _ := setitimer(2, ^U8(SYSTEM.ADR(timerv)), nil); (* ITIMER_PROF *) + _ := atExit(profile); end; +(* At the end of a profiled run: which procedures, and which places in + the source, took the time, as shares of the samples *) +proc profile; +var t: [4]INT; i, n, k, j, m, s: INT; seen: [Depth + 1]INT; row: ^UINT; begin - _ := profiler; (* started here when RAZ_PROFILE is set, by step 7's Rt *) + t := [0, 0, 0, 0]; + _ := setitimer(2, ^U8(SYSTEM.ADR(t)), nil); (* no more *) + n := numSamples; + if n > MaxSamples then n := MaxSamples; end; + if (places = nil) or (n = 0) then return; end; + for i := 0 to n - 1 do + k := procNum(samples[i]); + if (k >= 0) and (k < MaxProcs) then INC(procCount[k]); end; + (* each procedure on the sample's chain counts once in its + total, however often it is there *) + row := chains + i * Depth; + m := 0; + for j := -1 to Depth - 1 do + if j < 0 then k := procNum(samples[i]); + elsif row[j] = 0 then break; + else k := procNum(row[j]); + end; + if (k >= 0) and (k < MaxProcs) then + s := 0; + while (s < m) and (seen[s] # k) do INC(s); end; + if s = m then seen[m] := k; INC(m); INC(procTotal[k]); end; + end; + end; + k := placeAt(samples[i]); + if (k >= 0) and (k < MaxPlaces) then INC(placeCount[k]); end; + end; + put("profile: "); + putInt(n); + put(" samples of a millisecond; each procedure's own, then with its calls'"); + say; + top(procCount[0..places[3]], procTotal[0..places[3]], n, false); + put("by place:"); + say; + top(placeCount, placeCount[0..0], n, true); +end; + +begin + slide := UINT(_dyld_get_image_vmaddr_slide(0)); (* image 0 is the program *) alt := {sp: SYSTEM.ADR(altStack[0]), size: LEN(altStack)}; _ := sigaltstack(^U8(SYSTEM.ADR(alt)), nil); act := {handler: onSignal, flags: Flags}; @@ -234,4 +805,5 @@ _ := sigaction(SigFpe, ^U8(SYSTEM.ADR(act)), nil); _ := sigaction(SigIll, ^U8(SYSTEM.ADR(act)), nil); _ := sigaction(SigTrap, ^U8(SYSTEM.ADR(act)), nil); + if profiler # nil then profiler(); end; end Rt. diff --git a/lib/Sys.raz b/lib/Sys.raz index 8545bc3..d24e5d5 100644 --- a/lib/Sys.raz +++ b/lib/Sys.raz @@ -8,12 +8,15 @@ two procedures whose names differ, it takes from CAbi, one file per target, which tools/cabi.c writes; so a struct the C library fills in or reads is bytes here, its fields read and written at CAbi's - offsets by field and setField. A failure is minus Linux's errno, on + offsets by field and setField. So do the calls that Linux's C + library has and another system's lacks (pipe2, accept4, getrandom, + memfd_create, clock_nanosleep, sched_getaffinity, SO_PEERCRED), which + CAbi makes there of what it has. A flag CAbi gives as 0, that system + lacking it, is done after: a socket closed on exec by keepOnExec. A failure is minus Linux's errno, on every target: linux maps the C library's, and errorText maps back. A terminal's modes, Mode, are its struct termios whole, which cabi - checks fits in 256 bytes. Still Linux's: memfd_create, getrandom, - pipe2 and accept4, which glibc and musl have, and what a wait - status holds, which every Unix encodes alike. *) + checks fits in 256 bytes. Still Linux's: what a wait status holds, + which every Unix encodes alike. *) module Sys; import C, CAbi; import SYSTEM; @@ -131,6 +134,8 @@ end; Winsize = record rows, cols, xpixel, ypixel: U16; end; + (* A pseudo-terminal's terminal, tty, opened and held for pty *) + Held = record pty, tty: INT; end; Pollfd = record fd: I32; events, revents: I16; end; (* a socket's address, struct sockaddr_storage, which holds any: @@ -166,6 +171,12 @@ sigRead, sigWrite: I32; (* the pipe the handler of caught signals writes their numbers to, once open *) noted: [CAbi.sigMax + 1]INT; (* 1 at sig when a signal handle took has come, until came asks *) broke: INT; (* 1 when one has come since a call that ready or readyFor makes again began *) + (* On macOS, where the controlling side of a pseudo-terminal takes + no modes and no size until its terminal is opened, and reads an + end once it has been and is closed again, openPty opens the + terminal and holds it, until spawn's child takes it over or the + pty is closed (CAbi.ptyHeld). A pty of 0 or less is none. *) + held: [16]Held; (* err, minus an errno of the C library's, as minus Linux's errno of the same name; err itself if it has none *) @@ -374,8 +385,11 @@ end; (* Closes the file descriptor fd. *) +proc release(pty: INT); forward; + proc close*(fd: INT); begin + if CAbi.ptyHeld = 1 then release(fd); end; _ := C.close(I32(fd)); end; @@ -387,6 +401,7 @@ closed again, after -4 (EINTR) too. *) proc closeChecked*(fd: INT): INT; begin + if CAbi.ptyHeld = 1 then release(fd); end; if C.close(I32(fd)) # 0 then return failed(); end; return 0; end; @@ -456,10 +471,9 @@ (* A file in memory, with no name, of size zeroed bytes: its fd, or minus an errno. It is closed in a program exec starts. *) proc memFile*(size: INT): INT; -var name: [4]U8; fd: I32; err: INT; +var fd: I32; err: INT; begin - _ := cstr("raz", name); (* the name /proc shows *) - fd := C.memfd_create(SYSTEM.ADR(name[0]), CAbi.mfdCloexec); + fd := CAbi.memFile(); if fd < 0 then return failed(); end; if C.ftruncate(fd, I64(size)) # 0 then err := failed(); (* before close can change errno *) @@ -854,8 +868,7 @@ begin at := clock() + I64(ms) * 1000000; t := {sec: at div 1000000000, nsec: at mod 1000000000}; - (* until t, again after EINTR, which it returns, the C library's *) - repeat until C.clock_nanosleep(CAbi.clockMonotonic, CAbi.timerAbstime, ^U8(SYSTEM.ADR(t)), nil) # CAbi.eIntr; + CAbi.sleepUntil(^U8(SYSTEM.ADR(t))); end; (* Ends the program: random bytes can't be faked. *) @@ -874,7 +887,7 @@ begin n := 0; while n < LEN(b) do (* a signal may cut it short *) - r := C.getrandom(SYSTEM.ADR(b[n]), UINT(LEN(b) - n), 0); + r := CAbi.random(SYSTEM.ADR(b[n]), UINT(LEN(b) - n)); if r > 0 then INC(n, r); elsif (r >= 0) or (failed() # errIntr) then noRandom(); (* r = 0 can't be, and is no progress *) end; @@ -890,6 +903,7 @@ begin fd := C.socket(I32(family), I32(kind) | CAbi.sockCloexec, 0); if fd < 0 then return failed(); end; + if CAbi.sockCloexec = 0 then _ := keepOnExec(INT(fd), false); end; if serving then one := 1; (* so that a server can start again at once *) _ := C.setsockopt(fd, CAbi.solSocket, CAbi.soReuseaddr, ^U8(SYSTEM.ADR(one)), 4); @@ -925,11 +939,13 @@ (* path as a Unix socket's address in a, and the address's length, or -36 (ENAMETOOLONG) if it is too long. A path that starts with a zero byte is one of Linux's abstract names, which has no file and no - trailing zero: its length ends with the name's. *) + trailing zero: its length ends with the name's; on a system that has + none, -22 (EINVAL). *) proc unixAddr(path: []const U8; a: ^Sockaddr): INT; var p: ^U8; begin if LEN(path) >= CAbi.sunPathLen then return -36; end; + if (LEN(path) > 0) and (path[0] = 0) and (CAbi.unixAbstract = 0) then return -22; end; p := ^U8(a); setFamily(p, CAbi.afUnix, CAbi.sockaddrUnLen); COPY(p[CAbi.sunPathAt..CAbi.sunPathAt + LEN(path)], path); @@ -1035,7 +1051,7 @@ proc accept*(fd: INT): INT; var r: I32; begin - r := C.accept4(I32(fd), nil, nil, CAbi.sockCloexec); + r := CAbi.accepted(I32(fd)); if r < 0 then return failed(); end; return INT(r); end; @@ -1052,20 +1068,15 @@ (* Who is at the other end of the connected socket fd, and 0; or minus an errno. *) proc peer*(fd: INT): (Remote, INT); -var r: Remote; a: Sockaddr; size, credSize: U32; cred: [CAbi.ucUidAt + CAbi.ucUidLen]U8; p: ^U8; +var r: Remote; a: Sockaddr; size: U32; p: ^U8; begin r := {unix: false, ipv6: false}; size := U32(SIZE(Sockaddr)); p := ^U8(SYSTEM.ADR(a)); if C.getpeername(I32(fd), p, SYSTEM.ADR(size)) # 0 then return r, failed(); end; if familyOf(p) = CAbi.afUnix then (* ask who made the connection *) - credSize := U32(LEN(cred)); - if C.getsockopt(I32(fd), CAbi.solSocket, CAbi.soPeercred, SYSTEM.ADR(cred[0]), SYSTEM.ADR(credSize)) # 0 then - return r, failed(); - end; + if CAbi.peer(I32(fd), r.pid, r.uid) # 0 then return r, failed(); end; r.unix := true; - r.pid := INT(field(SYSTEM.ADR(cred[0]), CAbi.ucPidAt, CAbi.ucPidLen)); - r.uid := INT(field(SYSTEM.ADR(cred[0]), CAbi.ucUidAt, CAbi.ucUidLen)); else r.port := portOf(p); if familyOf(p) = CAbi.afInet6 then @@ -1087,6 +1098,10 @@ if C.socketpair(CAbi.afUnix, CAbi.sockStream | CAbi.sockCloexec, 0, SYSTEM.ADR(fds[0])) # 0 then return -1, -1, failed(); end; + if CAbi.sockCloexec = 0 then + _ := keepOnExec(INT(fds[0]), false); + _ := keepOnExec(INT(fds[1]), false); + end; return INT(fds[0]), INT(fds[1]), 0; end; @@ -1108,7 +1123,7 @@ var r: INT; begin if LEN(s) = 0 then return 0; end; - r := C.send(I32(fd), SYSTEM.PTR(s), UINT(LEN(s)), CAbi.msgNosignal | CAbi.msgDontwait); + r := CAbi.sendNow(I32(fd), SYSTEM.PTR(s), UINT(LEN(s))); if r < 0 then return failed(); end; return r; end; @@ -1222,6 +1237,8 @@ if size = 0 then return -22; end; fd := C.socket(I32(familyOf(^U8(SYSTEM.ADR(a)))), CAbi.sockStream | CAbi.sockCloexec | CAbi.sockNonblock, 0); if fd < 0 then return failed(); end; + if CAbi.sockCloexec = 0 then _ := keepOnExec(INT(fd), false); end; + if CAbi.sockNonblock = 0 then _ := setBlocking(INT(fd), false); end; r := 0; if C.connect(fd, ^U8(SYSTEM.ADR(a)), U32(size)) # 0 then r := failed(); end; if r = -115 then (* EINPROGRESS *) @@ -1326,6 +1343,7 @@ for i := 0 to (size - CAbi.cmsgDataAt) div 4 - 1 do if k < LEN(fds) then fds[k] := INT(got[i]); + if CAbi.msgCmsgCloexec = 0 then _ := keepOnExec(fds[k], false); end; INC(k); else _ := C.close(got[i]); @@ -1409,11 +1427,13 @@ return 0; end; +proc ptyName(fd: INT; name: []U8): INT; forward; + (* A pseudo-terminal: the file descriptor of its controlling side, or minus an errno. Its other side, the terminal its programs run on, is unlocked, for spawn to open. *) proc openPty*: INT; -var fd: I32; err: INT; +var fd, t: I32; err, i, k: INT; name: [256]U8; begin fd := C.posix_openpt(CAbi.oRdwr | CAbi.oNoctty); if fd < 0 then return failed(); end; @@ -1422,9 +1442,45 @@ _ := C.close(fd); return err; end; + if CAbi.ptyHeld = 1 then (* macOS: its terminal held (held) *) + release(INT(fd)); (* one an fd closed since had *) + k := -1; + for i := 0 to LEN(held) - 1 do + if (held[i].pty <= 0) and (k < 0) then k := i; end; + end; + err := -24; (* EMFILE: none free *) + if k >= 0 then err := ptyName(INT(fd), name); end; + if err = 0 then + t := C.open(SYSTEM.ADR(name[0]), CAbi.oRdwr | CAbi.oNoctty | CAbi.oCloexec); + if t < 0 then err := failed(); else held[k] := {pty: INT(fd), tty: INT(t)}; end; + end; + if err # 0 then _ := C.close(fd); return err; end; + end; return INT(fd); end; +(* The terminal openPty holds for pty, or -1 *) +proc heldTty(pty: INT): INT; +var i: INT; +begin + for i := 0 to LEN(held) - 1 do + if held[i].pty = pty then return held[i].tty; end; + end; + return -1; +end; + +(* The terminal openPty holds for pty, if any, closed *) +proc release(pty: INT); +var i: INT; +begin + for i := 0 to LEN(held) - 1 do + if held[i].pty = pty then + _ := C.close(I32(held[i].tty)); + held[i].pty := -1; + end; + end; +end; + (* Tells the terminal of the pseudo-terminal fd that it has cols columns and rows rows: 0, or minus an errno. *) proc setTermSize*(fd, cols, rows: INT): INT; @@ -1515,7 +1571,7 @@ proc pipe*: (INT, INT); var fds: [2]I32; begin - if C.pipe2(SYSTEM.ADR(fds[0]), CAbi.oCloexec) # 0 then return failed(), -1; end; + if CAbi.makePipe(SYSTEM.ADR(fds[0]), CAbi.oCloexec) # 0 then return failed(), -1; end; return INT(fds[0]), INT(fds[1]); end; @@ -1552,16 +1608,9 @@ (* The number of processors this program may run on, at least 1. *) proc processors*: INT; -var mask: [1024]U8; i, b, count: INT; +var count: INT; begin - 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 *) - if C.sched_getaffinity(0, UINT(LEN(mask)), SYSTEM.ADR(mask[0])) # 0 then return 1; end; - count := 0; - for i := 0 to LEN(mask) - 1 do - for b := 0 to 7 do - if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end; - end; - end; + count := CAbi.processors(); if count < 1 then return 1; end; return count; end; @@ -1776,7 +1825,8 @@ begin if p.tty # 0 then _ := C.setsid(); - fd := C.open(SYSTEM.PTR(name), CAbi.oRdwr); + fd := I32(heldTty(p.tty)); (* the terminal openPty holds, on macOS *) + if fd < 0 then fd := C.open(SYSTEM.PTR(name), CAbi.oRdwr); end; if fd < 0 then return failed(); end; if C.ioctl(fd, CAbi.tiocsctty, 0) # 0 then return failed(); end; for i := 0 to 2 do _ := C.dup2(fd, I32(i)); end; @@ -1855,6 +1905,9 @@ C._exit(127); end; err := failed(); + if (pid > 0) and (p.tty # 0) and (CAbi.ptyHeld = 1) then + release(p.tty); (* the child holds the terminal now *) + end; if (pid > 0) and (p.tty = 0) then (* as the program does, for whichever of the two runs first *) g := p.group; @@ -1946,7 +1999,10 @@ proc waitFor(pid: INT; options: I32): (INT, Status, INT); var status, r: I32; begin - r := C.waitpid(I32(pid), SYSTEM.ADR(status), options); + (* again after EINTR, unless a signal handle took broke in: macOS + breaks into a wait for a SIGCHLD that nothing catches *) + _ := XCHG(broke, 0); + repeat r := C.waitpid(I32(pid), SYSTEM.ADR(status), options); until (r >= 0) or not again(); if r < 0 then return failed(), running, 0; end; if r = 0 then return 0, running, 0; end; if status & 7FH = 0 then return INT(r), exited, INT(status) shr 8 & 0FFH; end; @@ -2025,7 +2081,7 @@ if not takable(sigs[i]) then return -22; end; (* EINVAL *) end; if sigWrite = 0 then - if C.pipe2(SYSTEM.ADR(fds[0]), CAbi.oNonblock | CAbi.oCloexec) # 0 then return failed(); end; + if CAbi.makePipe(SYSTEM.ADR(fds[0]), CAbi.oNonblock | CAbi.oCloexec) # 0 then return failed(); end; sigRead := fds[0]; sigWrite := fds[1]; end; @@ -2165,8 +2221,9 @@ r, w := pipe(); if w < 0 then exit(2); end; + (* in /usr, which is no link, on macOS too, where /tmp is one *) child := spawn({path: "/bin/sh", args: ["sh", "-c", "echo $X $HOME; pwd"], env: ["X=x"], onlyEnv: true, - dir: "/tmp", fds: [0, w, 0]}); + dir: "/usr", fds: [0, w, 0]}); close(w); n := 0; repeat @@ -2174,7 +2231,7 @@ if m > 0 then INC(n, m); end; until m <= 0; close(r); - if buf[0..n] # "x\n/tmp\n" then exit(2); end; + if buf[0..n] # "x\n/usr\n" then exit(2); end; r, st, c := wait(child, true); if (r # child) or (st # exited) or (c # 0) then exit(2); end; @@ -2252,8 +2309,10 @@ if m > 0 then INC(n, m); end; until m <= 0; close(r); - r, st, c := waitExit(child); + (* the pty closed first: macOS's last close of a terminal, the + child's at its exit, waits until what was written to it is read *) close(pty); + r, st, c := waitExit(child); if (buf[0..n] # "out\n") or (r # child) or (st # exited) or (c # 0) then exit(2); end; sigs := catch([sigChld, sigHup]); @@ -2280,7 +2339,7 @@ proc testShell; var r, w, fd, n, k, child, c, err, pty, sigs, mask, parent: INT; t: I64; st: Status; buf: [64]U8; - m, raw: Mode; soft, hard, s2, h2, user, system: I64; e: []const U8; ok, path: BOOL; + m, raw, back: Mode; soft, hard, s2, h2, user, system: I64; e: []const U8; ok, path: BOOL; begin r, w := pipe(); if w < 0 then exit(2); end; @@ -2331,8 +2390,11 @@ if (err # 0) or not rawMode(pty) then exit(2); end; raw, err := getMode(pty); if (err # 0) or (raw.t = m.t) or (setMode(pty, m) # 0) then exit(2); end; - raw, err := getMode(pty); - if (err # 0) or (raw.t # m.t) then exit(2); end; + (* not raw again, and as it was, but for what the system notes + itself, as macOS's PENDIN after raw mode *) + back, err := getMode(pty); + if (err # 0) or (back.t = raw.t) then exit(2); end; + if (CAbi.ptyHeld = 0) and (back.t # m.t) then exit(2); end; m, err := getMode(-1); if err # -9 then exit(2); end; (* EBADF *) r, w := pipe(); @@ -2578,15 +2640,16 @@ munmap(p, 5); close(fd); _ := remove("/tmp/raz-sys-map"); - p := mmap(8192); + (* by 16 KB, a page of arm64 macOS's and four of x86-64's *) + p := mmap(32768); if p = nil then exit(2); end; p[0] := 1; - q := p + 4096; - if (protect(q, 4096, true, false) # 0) or (q[0] # 0) then exit(2); end; - if protect(q, 4096, true, true) # 0 then exit(2); end; + q := p + 16384; + if (protect(q, 16384, true, false) # 0) or (q[0] # 0) then exit(2); end; + if protect(q, 16384, true, true) # 0 then exit(2); end; q[0] := 2; - 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 *) - munmap(p, 8192); + 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 *) + munmap(p, 32768); end; (* poll over 100 socket pairs with a byte sent on three, so that all @@ -2624,6 +2687,10 @@ nm[0] := 0; (* an abstract name: a zero byte, then 17 *) COPY(nm[1..18], "raz-abstract-test"); l := listen(nm); + if CAbi.unixAbstract = 0 then (* not Linux: none *) + if (l # -22) or (connect(nm) # -22) then exit(2); end; + return; + end; c := connect(nm); if (l < 0) or (c < 0) or (readyOf([c, l], 1000) # l) then exit(2); end; s := accept(l); @@ -2752,7 +2819,9 @@ if (i.mtime # -1500000000) or (i.seconds # -2) then exit(2); end; if setTime("/tmp/raz-sys-dir/h", 10413792000, 0) # 0 then exit(2); end; (* 2300, past mtime's reach *) i, err := info("/tmp/raz-sys-dir/h"); - if i.seconds # 10413792000 then exit(2); end; + (* exact, or, where the file system keeps no time past 2262, as + APFS, which holds nanoseconds in 64 bits, its last second *) + if (i.seconds # 10413792000) and (i.seconds # 9223372036) then exit(2); end; if setTime("/tmp/raz-sys-dir/h", 0, 1000000000) # -22 then exit(2); end; if setTime("/no/such/file", 0, 0) # -2 then exit(2); end; (* the special bits: set-user-id by chmod, and sticky by makeDirMode *) @@ -2761,7 +2830,11 @@ if (i.mode # 1EDH) or (i.special # 800H) then exit(2); end; if makeDirMode("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end; i, err := info("/tmp/raz-sys-dir/m"); - if (err # 0) or not i.dir or (i.mode # 1C0H) or (i.special # 200H) then exit(2); end; + (* Linux gives it sticky, macOS doesn't, and chmod does *) + if (err # 0) or not i.dir or (i.mode # 1C0H) or (i.special & ~200H # 0) then exit(2); end; + if chmod("/tmp/raz-sys-dir/m", 3C0H) # 0 then exit(2); end; + i, err := info("/tmp/raz-sys-dir/m"); + if (err # 0) or (i.special # 200H) then exit(2); end; if removeDir("/tmp/raz-sys-dir/m") # 0 then exit(2); end; _ := remove("/tmp/raz-sys-dir/h"); fd := openMode("/tmp/raz-sys-dir/h", {writing, creating}, 1C0H); (* rwx------ *) @@ -2792,8 +2865,9 @@ (* the environment set: refused, added, set again, grown past its first array *) if (setEnv("", "x") # -22) or (setEnv("A=B", "x") # -22) or (setEnv("A", "\x00") # -22) then exit(2); end; if (setEnv("RAZ_SYS_TEST", "one") # 0) or (env("RAZ_SYS_TEST") # "one") then exit(2); end; - name := env("RAZ_SYS_TEST"); - if (setEnv("RAZ_SYS_TEST", "") # 0) or (env("RAZ_SYS_TEST") # "") or (name # "one") then exit(2); end; + (* what env gave before may be gone now: macOS's setenv writes the + new value over the old where it fits *) + if (setEnv("RAZ_SYS_TEST", "") # 0) or (env("RAZ_SYS_TEST") # "") then exit(2); end; buf := "RAZ_SYS_TEST_.."; for k := 0 to 99 do buf[13] := U8('0' + k div 10); diff --git a/lib/Thread.darwin.raz b/lib/Thread.darwin.raz new file mode 100644 index 0000000..00e5422 --- /dev/null +++ b/lib/Thread.darwin.raz @@ -0,0 +1,192 @@ +(* Threads, for macOS, with Thread.linux-x86_64.raz's interface: made + by C's pthread_create, as every program on a Mac uses C. The + compiler's entry point finds cCreate and cJoin by name and stores + C's pthread_create and pthread_join in them, as on Linux in a + program that uses C. Each thread runs on C's stack, of Stack bytes + asked for, below which C keeps a page that can't be touched, so + that running off the stack stops the program rather than spoiling + what lies below; beside it, in a mapping of Thread's own, a little + stack for Rt's signal handlers, so that they can say so, and the + Thread. + + A Mutex is os_unfair_lock, macOS's lock whose waiters sleep in the + kernel, the plainest it supports: __ulock_wait and __ulock_wake, + which it is made of, a futex's twins, are not for programs, and + pthread_mutex_t needs its initializer. As os_unfair_lock asks, the + thread that takes a Mutex gives it up; one that gives up another + thread's stops the program. + + Depends on Sys and Rt, and Check for its test. *) +module Thread; +import Sys, Rt, Check; +import SYSTEM; + +const + Failed*: ERROR = "can't start a thread"; + Stack = 1 shl 20; (* each thread's, as on Linux without C *) + Alt = 65536; (* the signal handlers' stack, more than macOS's least, MINSIGSTKSZ *) + Page = 16384; (* arm64 macOS's *) + +type + (* A thread, as spawn gives it, until join. *) + Thread* = record + tid: UINT; (* C's pthread_t *) + ended: INT; (* 1 once its procedure has returned *) + base: ^U8; (* the mapping it is in, the handlers' stack first *) + size: INT; + fn: proc(arg: ^U8); (* what it runs, and with what *) + arg: ^U8; + end; + (* What sigaltstack takes, as macOS lays it out *) + AltStack = record sp: ^U8; size: INT; flags: I32; end; + (* A lock whose waiters sleep, free when zeroed: an os_unfair_lock *) + Mutex* = record lock: U32; end; + +extern proc pthread_attr_init(attr: ^U8): I32; +extern proc pthread_attr_setstacksize(attr: ^U8; size: UINT): I32; +extern proc pthread_attr_destroy(attr: ^U8): I32; +extern proc pthread_kill(t: UINT; sig: I32): I32; +extern proc sigaltstack(ss, old: ^U8): I32; +extern proc os_unfair_lock_lock(lock: ^U32); +extern proc os_unfair_lock_unlock(lock: ^U32); + +var + (* C's pthread_create and pthread_join, given by the entry point *) + cCreate: proc(t: ^UINT; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32; + cJoin: proc(t: UINT; result: ^^U8): I32; + +(* Where a new thread starts, as pthread_create calls it: the signal + handlers' stack is a thread's own, so it is set here; then the + thread runs its procedure, and notes that it has ended, for signal. *) +proc run(arg: ^U8): ^U8; +var t: ^Thread; alt: AltStack; +begin + t := ^Thread(arg); + alt := {sp: t^.base, size: Alt}; + _ := sigaltstack(^U8(SYSTEM.ADR(alt)), nil); + t^.fn(t^.arg); + _ := XCHG(t^.ended, 1); + return nil; +end; + +(* Starts p(arg) in a new thread. *) +proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); +var base: ^U8; t: ^Thread; size: INT; tid: UINT; attr: [8]U64; r: I32; +begin + size := Alt + Page; + base := Sys.mmap(size); + if base = nil then return nil, Failed; end; + (* the handlers' stack, then the Thread in the last page *) + t := ^Thread(base + Alt); + t^.base := base; + t^.size := size; + t^.fn := p; + t^.arg := arg; + _ := pthread_attr_init(^U8(SYSTEM.ADR(attr))); + _ := pthread_attr_setstacksize(^U8(SYSTEM.ADR(attr)), Stack); + r := cCreate(SYSTEM.ADR(tid), ^U8(SYSTEM.ADR(attr)), run, ^U8(t)); + _ := pthread_attr_destroy(^U8(SYSTEM.ADR(attr))); + if r # 0 then + Sys.munmap(base, size); + return nil, Failed; + end; + t^.tid := tid; + return t, nil; +end; + +(* Waits for t to end, then frees what spawn took for it. *) +proc join*(t: ^Thread); +var base: ^U8; size: INT; +begin + _ := cJoin(t^.tid, nil); + base := t^.base; + size := t^.size; + Sys.munmap(base, size); +end; + +(* Sends the signal sig to t alone, not to any thread of the program + as Sys.kill does: 0, or minus an errno, -3 (ESRCH) if t has ended. + With Sys.handle(sig), a system call t waits in fails with -4, so + another thread can break into a read. By pthread_kill, whose errnos, + ESRCH and EINVAL, are Linux's numbers too. *) +proc signal*(t: ^Thread; sig: INT): INT; +begin + if XADD(t^.ended, 0) # 0 then return -3; end; + return -INT(pthread_kill(t^.tid, I32(sig))); +end; + +(* Takes m, sleeping while another thread holds it. *) +proc lock*(var m: Mutex); +begin + os_unfair_lock_lock(SYSTEM.ADR(m.lock)); +end; + +(* Gives up m, which the calling thread took, waking a thread that + waits for it. *) +proc unlock*(var m: Mutex); +begin + os_unfair_lock_unlock(SYSTEM.ADR(m.lock)); +end; + +(* The module's test, and make stress's. It starts n threads, in waves + of up to alive at a time, all waiting on one Mutex the test holds + until the wave is out; each, given it, adds one to a count. Every + thread is joined, so that a stack join didn't free would, over + enough of them, run the process out of mappings. With "fail", it + starts threads, all waiting, until spawn fails, which it must do + with Failed: make stress and make check run it with little memory. + Thread [n alive], Thread fail *) +var + testLock: Mutex; + testCount: INT; + wave: [1000]^Thread; + +proc testWork(_arg: ^U8); +begin + lock(testLock); + INC(testCount); + unlock(testLock); +end; + +proc testArg(i: INT): INT; +var s: ^U8; n, v: INT; +begin + s := SYSTEM.ARGV()[i]; + v := 0; + n := 0; + while s[n] # 0 do v := v * 10 + INT(s[n]) - '0'; INC(n); end; + return v; +end; + +(* The module's test: starts threads in waves, and counts that each ran. *) +proc main*; +var n, alive, started, k, i: INT; t: ^Thread; err: ERROR; fail: BOOL; +begin + n := 2000; alive := 50; + fail := (ARGC() = 2) and (SYSTEM.ARGV()[1][0] = 'f'); + if ARGC() = 3 then n := testArg(1); alive := testArg(2); end; + if fail then n := LEN(wave); alive := LEN(wave); end; + if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end; + started := 0; + while started < n do + lock(testLock); + k := 0; + while (k < alive) and (started + k < n) do + t, err := spawn(testWork, nil); + if err # nil then + if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end; + n := started + k; + break; + end; + wave[k] := t; + INC(k); + end; + unlock(testLock); + for i := 0 to k - 1 do join(wave[i]); end; + started := started + k; + end; + Check.int("Thread: every thread ran", testCount, started); + Check.ok(not (fail and (started = LEN(wave))), "Thread: spawn never failed"); +end; + +end Thread. diff --git a/test/check.sh b/test/check.sh index c55ae7b..1100c6e 100755 --- a/test/check.sh +++ b/test/check.sh @@ -370,6 +370,9 @@ if $raz -Werror -o $out/raztest tools/Test.raz 2>$out/raztest.cerr; then libtests= for f in lib/*.raz; do + case $f in # another target's file is tested there (test/mac.sh) + *.darwin-arm64.raz|*.darwin.raz|*.arm64.raz) continue;; + esac [ $f != lib/Sys.raz ] && grep -q '^proc main\*' $f && ! skip $f && libtests="$libtests $f" done RAZ=$raz $out/raztest -j $(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1) -o $out/lib \ diff --git a/test/err/Clash.err b/test/err/Clash.err index b4e2741..8b519f3 100644 --- a/test/err/Clash.err +++ b/test/err/Clash.err @@ -1,5 +1,5 @@ -lib/Sys.raz:18:8: error: module C is in test/err/mods/clash/C.raz and lib/C.raz - 18 | import C, CAbi; +lib/Sys.raz:21:8: error: module C is in test/err/mods/clash/C.raz and lib/C.raz + 21 | import C, CAbi; | ^ help: a program has one module of each name; a symbolic link to one of these files chooses it raz: 1 error diff --git a/test/libc/ExecOpenedC.raz b/test/libc/ExecOpenedC.raz index 6e2b496..1e9137f 100644 --- a/test/libc/ExecOpenedC.raz +++ b/test/libc/ExecOpenedC.raz @@ -1,6 +1,6 @@ (* Over the C library: a file open gives is closed in the program exec runs, unless keepOnExec says to keep it: of two opened files, sh sees - the second. *) + the second, in /dev/fd, which Linux and macOS have alike. *) module ExecOpenedC; import Sys; @@ -11,7 +11,7 @@ b := Sys.create("/dev/null"); if (a # 3) or (b # 4) or (Sys.keepOnExec(b, true) # 0) then return 1; end; return Sys.exec({path: "sh", - 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"]}); + args: ["sh", "-c", "for n in 3 4; do if [ -e /dev/fd/$n ]; then echo open $n; else echo closed $n; fi; done"]}); end; end ExecOpenedC. diff --git a/test/mac.sh b/test/mac.sh index 9524553..a17de0f 100755 --- a/test/mac.sh +++ b/test/mac.sh @@ -11,6 +11,14 @@ # which are counted and listed in build/mac/conform.fail, not failures # of the run. A few of conform/run are not for this target, each named # in notHere with the reason, and skipped. +# Then the library: each module's own main, its test, as the target +# takes its file (Name.darwin-arm64.raz, Name.darwin.raz, Name.arm64.raz +# or Name.raz), built with -Werror into build/mac/lib and run there, +# passing if it ends with status 0, as raztest has it; and test/libc's +# programs, over Sys, the C one, into build/mac/libc, compared as +# test/check.sh compares them (X.expect, X.status, and X.stderr with +# each address 0x?). These count as test/mac's do, but those named in +# libNotHere, with the reason, which are skipped. # # test/mac.sh build in the container: the cross compiler, then the programs # test/mac.sh run on the Mac: each program, run with a timeout @@ -28,6 +36,30 @@ out=build/mac # conform/run's programs that are not for darwin-arm64, and why notHere='SystemImport: SYSTEM.SYSCALL is Linux'"'"'s only (report 6.8)' +# the library's tests and test/libc's programs that are not for it, and why +libNotHere='test/libc/ExecveC: reads what signals sh ignores and catches in /proc/self/status, which is Linux'"'"'s' + +# The file of module $1 the target takes, as the compiler looks for it +libFile() { + for f in lib/$1.darwin-arm64.raz lib/$1.darwin.raz lib/$1.arm64.raz lib/$1.raz; do + [ -f $f ] && { echo $f; return; } + done +} + +# The library's modules that have a test, by the files the target takes +libTests() { + for m in $(ls lib/*.raz | sed 's|lib/||; s|\..*||' | sort -u); do + f=$(libFile $m) + [ -n "$f" ] && grep -q '^proc main\*' $f && echo $f + done +} + +# Runs $out/$1/$2 with a timeout, in its directory, from the arguments +# on: its status, its output in $2.out and $2.err +runIn() { + dir=$1; prog=$2; shift 2 + (cd $out/$dir && perl -e 'alarm 60; exec @ARGV' ./$prog "$@" > $prog.out 2>$prog.err) || return $? +} case $1 in build) src/cross.sh darwin-arm64 @@ -43,6 +75,16 @@ build/cross/darwin-arm64/raz -I conform/run/mods -o $out/conform/$name $f \ 2>$out/conform/$name.cerr || true done + mkdir -p $out/lib $out/libc + for f in $(libTests); do + name=$(basename $f .raz); name=${name%%.*} + build/cross/darwin-arm64/raz -Werror -o $out/lib/$name $f 2>$out/lib/$name.cerr || true + done + for f in test/libc/*.raz; do + name=$(basename $f .raz) + build/cross/darwin-arm64/raz -Werror -I test/libc/mods -o $out/libc/$name $f \ + 2>$out/libc/$name.cerr || true + done ;; run) pass=0 @@ -107,8 +149,51 @@ fi done echo "conform/run: $cpass of $((cpass + cfail)) passed, $cskip not for this target; the others in $c.fail" + # the library's tests, and test/libc's programs + lpass=0 + lfail=0 + lskip=0 + for f in $(libTests); do + name=$(basename $f .raz); name=${name%%.*} + if echo "$libNotHere" | grep -q "^lib/$name:"; then lskip=$((lskip + 1)); continue; fi + if [ ! -x $out/lib/$name ]; then + echo "FAIL $f: doesn't compile: $(head -3 $out/lib/$name.cerr)"; lfail=$((lfail + 1)); continue + fi + status=0 + runIn lib $name || status=$? + if [ $status != 0 ]; then + echo "FAIL $f: status $status"; tail -5 $out/lib/$name.err; lfail=$((lfail + 1)) + else + lpass=$((lpass + 1)) + fi + done + for f in test/libc/*.raz; do + name=$(basename $f .raz) + if echo "$libNotHere" | grep -q "^test/libc/$name:"; then lskip=$((lskip + 1)); continue; fi + if [ ! -x $out/libc/$name ]; then + echo "FAIL $f: doesn't compile: $(head -3 $out/libc/$name.cerr)"; lfail=$((lfail + 1)); continue + fi + want=0 + [ -f test/libc/$name.status ] && want=$(cat test/libc/$name.status) + # from the repository's root, as a message names the file so + status=0 + perl -e 'alarm 60; exec @ARGV' ./$out/libc/$name > $out/libc/$name.out 2>$out/libc/$name.err || status=$? + if [ -f test/libc/$name.expect ]; then exp=test/libc/$name.expect; else exp=/dev/null; fi + if [ $status != $want ]; then + echo "FAIL $f: status $status, not $want"; head -3 $out/libc/$name.err; lfail=$((lfail + 1)) + elif ! cmp -s $out/libc/$name.out $exp; then + echo "FAIL $f: output differs"; diff $out/libc/$name.out $exp | head -5; lfail=$((lfail + 1)) + elif [ -f test/libc/$name.stderr ] && ! sed 's/0x[0-9a-f]*/0x?/g' $out/libc/$name.err | + cmp -s - test/libc/$name.stderr; then + echo "FAIL $f: standard error differs"; diff $out/libc/$name.err test/libc/$name.stderr | head -5 + lfail=$((lfail + 1)) + else + lpass=$((lpass + 1)) + fi + done + echo "the library and test/libc: $lpass passed, $lfail failed, $lskip not for this target" if command -v lldb > /dev/null; then test/lldb.sh || fail=$((fail + 1)); fi - [ $fail = 0 ] + [ $fail = 0 ] && [ $lfail = 0 ] ;; *) echo "usage: test/mac.sh build|run" >&2 diff --git a/tools/cabi.c b/tools/cabi.c index ad44710..f19c5e7 100644 --- a/tools/cabi.c +++ b/tools/cabi.c @@ -1,8 +1,10 @@ /* cabi: writes lib/CAbi.OS-ARCH.raz, what the C library it is compiled against fixes for Sys over C (lib/Sys.raz): the numbers of flags, requests, signals, limits and errnos, where the fields Sys reads and - writes lie in the C library's structs, and the two procedures whose - names differ between systems. Nothing in that file is typed by hand: + writes lie in the C library's structs, and the procedures that differ + between systems: errno and closeFrom, and the calls Linux has and + another system makes otherwise (makePipe, accepted, random, memFile, + sleepUntil, processors, peer and sendNow). Nothing in that file is typed by hand: it is all this program's output, from the system's own headers. cc -o build/cabi tools/cabi.c && build/cabi linux-x86_64 > lib/CAbi.linux-x86_64.raz @@ -24,11 +26,16 @@ flag; an option -1, as saLenAt is -1 where a sockaddr has no sa_len. On macOS (darwin-arm64), st_mtim is st_mtimespec, a peer's credentials are struct xucred, which has no pid (0 bytes at 0), and - errno and closeFrom are its own. + the procedures are its own: no pipe2, accept4 or SOCK_CLOEXEC, so + fcntl after; getentropy for getrandom; a shared memory object for + memfd_create; nanosleep for clock_nanosleep; sysconf for + sched_getaffinity; LOCAL_PEERCRED and LOCAL_PEERPID for SO_PEERCRED; + and a socket made nonblocking for a send, whose MSG_DONTWAIT macOS + doesn't keep on a Unix socket. cc -o build/cabi tools/cabi.c && build/cabi darwin-arm64 > lib/CAbi.darwin-arm64.raz - Leaves out: systems but Linux and macOS, for errno and closeFrom; a + Leaves out: systems but Linux and macOS, for the procedures; a port adds them where the #error is. */ #define _GNU_SOURCE #include @@ -133,7 +140,7 @@ printf("(* CAbi: what the C library fixes for Sys over C on %s: the\n" " numbers of its flags, requests, signals and limits, where the\n" " fields of its structs lie, an At the offset and a Len the width,\n" - " its errnos beside Linux's, and errno and closeFrom.\n\n" + " its errnos beside Linux's, and the procedures that differ.\n\n" " Written by tools/cabi.c, from the system's own headers; not to be\n" " edited, but written again. *)\n", target); printf("module CAbi;\nimport SYSTEM;\n\nconst\n"); @@ -176,6 +183,11 @@ K("tcsanow", TCSANOW); K("tcsadrain", TCSADRAIN); K("tiocgwinsz", TIOCGWINSZ); K("tiocswinsz", TIOCSWINSZ); K("tiocsctty", TIOCSCTTY); +#ifdef __APPLE__ + K("ptyHeld", 1); /* a pseudo-terminal's controlling side works only while its terminal is open */ +#else + K("ptyHeld", 0); +#endif K("pollin", POLLIN); K("pollout", POLLOUT); K("clockRealtime", CLOCK_REALTIME); K("clockMonotonic", CLOCK_MONOTONIC); K("timerAbstime", TIMER_ABSTIME); @@ -198,6 +210,11 @@ #endif K("sockaddrUnLen", sizeof(struct sockaddr_un)); READ("sunPath", struct sockaddr_un, sun_path); +#ifdef __linux__ + K("unixAbstract", 1); /* a Unix socket's name may start with a zero: no file */ +#else + K("unixAbstract", 0); +#endif K("sockaddrInLen", sizeof(struct sockaddr_in)); AT("sinPort", struct sockaddr_in, sin_port); AT("sinAddr", struct sockaddr_in, sin_addr); @@ -257,28 +274,126 @@ #ifdef __linux__ printf("extern proc __errno_location: ^I32;\n" - "extern proc syscall(n: INT; ...): INT;\n\n" + "extern proc syscall(n: INT; ...): INT;\n" + "extern proc pipe2(fds: ^I32; flags: I32): I32;\n" + "extern proc accept4(fd: I32; addr: ^U8; len: ^U32; flags: I32): I32;\n" + "extern proc getrandom(buf: ^U8; n: UINT; flags: U32): INT;\n" + "extern proc memfd_create(name: ^U8; flags: U32): I32;\n" + "extern proc clock_nanosleep(clock, flags: I32; t, left: ^U8): I32;\n" + "extern proc sched_getaffinity(pid: I32; size: UINT; mask: ^U8): I32;\n" + "extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32;\n" + "extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;\n" + "\n" "(* errno, this thread's *)\n" "proc errno*: ^I32;\n" "begin\n" " return __errno_location();\n" - "end;\n\n" + "end;\n" + "\n" "(* Closes the fds from lo to hi, or every one from lo if hi < 0: by\n" " close_range's system call, since musl has no close_range. *)\n" "proc closeFrom*(lo, hi: INT);\n" "begin\n" " if hi < 0 then hi := 0FFFFFFFFH; end;\n" " _ := syscall(436, lo, hi, 0);\n" - "end;\n\n"); + "end;\n" + "\n" + "(* A pipe, its two fds put at fds, taking flags, oCloexec and\n" + " oNonblock, at once: 0, or -1 with errno set, as C's calls are. *)\n" + "proc makePipe*(fds: ^I32; flags: I32): I32;\n" + "begin\n" + " return pipe2(fds, flags);\n" + "end;\n" + "\n" + "(* The next connection to the socket fd, closed on exec; or -1. *)\n" + "proc accepted*(fd: I32): I32;\n" + "begin\n" + " return accept4(fd, nil, nil, sockCloexec);\n" + "end;\n" + "\n" + "(* The kernel's random bytes, at most n, put at buf: how many, or -1. *)\n" + "proc random*(buf: ^U8; n: UINT): INT;\n" + "begin\n" + " return getrandom(buf, n, 0);\n" + "end;\n" + "\n" + "(* A file in memory, of no bytes, with no name, closed on exec: its\n" + " fd, or -1. *)\n" + "proc memFile*: I32;\n" + "begin\n" + " return memfd_create(SYSTEM.PTR(\"raz\\0\"), mfdCloexec); (* the name /proc shows *)\n" + "end;\n" + "\n" + "(* Waits until t, a struct timespec of the monotonic clock, again\n" + " after EINTR. *)\n" + "proc sleepUntil*(t: ^U8);\n" + "begin\n" + " repeat until clock_nanosleep(clockMonotonic, timerAbstime, t, nil) # eIntr;\n" + "end;\n" + "\n" + "(* The number of processors this program may run on, or 0 if the\n" + " system doesn't say. *)\n" + "proc processors*: INT;\n" + "var mask: [1024]U8; i, b, count: INT;\n" + "begin\n" + " 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" + " if sched_getaffinity(0, UINT(LEN(mask)), SYSTEM.ADR(mask[0])) # 0 then return 0; end;\n" + " count := 0;\n" + " for i := 0 to LEN(mask) - 1 do\n" + " for b := 0 to 7 do\n" + " if (INT(mask[i]) shr b) & 1 = 1 then INC(count); end;\n" + " end;\n" + " end;\n" + " return count;\n" + "end;\n" + "\n" + "(* The process and the user at the other end of the Unix socket fd,\n" + " as the system recorded them when it connected, and 0; or -1. *)\n" + "proc peer*(fd: I32; var pid, uid: INT): I32;\n" + "var cred: [16]U64; size: U32; p: ^U8; q: ^U32;\n" + "begin\n" + " p := ^U8(SYSTEM.ADR(cred[0]));\n" + " size := U32(SIZE([16]U64));\n" + " if getsockopt(fd, solSocket, soPeercred, p, SYSTEM.ADR(size)) # 0 then return -1; end;\n" + " q := ^U32(p + ucPidAt);\n" + " pid := INT(I32(q^));\n" + " q := ^U32(p + ucUidAt);\n" + " uid := INT(q^);\n" + " return 0;\n" + "end;\n" + "\n" + "(* Sends n bytes at buf on the socket fd, without waiting, and without\n" + " SIGPIPE where the other end is gone: how many were sent, or -1. *)\n" + "proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT;\n" + "begin\n" + " return send(fd, buf, n, msgNosignal | msgDontwait);\n" + "end;\n" + "\n"); #elif defined(__APPLE__) printf("extern proc __error: ^I32;\n" "extern proc close(fd: I32): I32;\n" - "extern proc getdtablesize: I32;\n\n" + "extern proc getdtablesize: I32;\n" + "extern proc pipe(fds: ^I32): I32;\n" + "extern proc fcntl(fd, cmd: I32; ...): I32;\n" + "extern proc accept(fd: I32; addr: ^U8; len: ^U32): I32;\n" + "extern proc getentropy(buf: ^U8; n: UINT): I32;\n" + "extern proc getpid: I32;\n" + "extern proc shm_open(name: ^U8; flags: I32; ...): I32;\n" + "extern proc shm_unlink(name: ^U8): I32;\n" + "extern proc clock_gettime(clock: I32; t: ^U8): I32;\n" + "extern proc nanosleep(t, left: ^U8): I32;\n" + "extern proc sysconf(name: I32): INT;\n" + "extern proc getsockopt(fd, level, name: I32; value: ^U8; len: ^U32): I32;\n" + "extern proc send(fd: I32; buf: ^U8; n: UINT; flags: I32): INT;\n" + "\n" + "var shmCount: INT; (* the shared memory objects memFile has made *)\n" + "\n" "(* errno, this thread's *)\n" "proc errno*: ^I32;\n" "begin\n" " return __error();\n" - "end;\n\n" + "end;\n" + "\n" "(* Closes the fds from lo to hi, or every one from lo if hi < 0: one\n" " by one, as macOS has no close_range. *)\n" "proc closeFrom*(lo, hi: INT);\n" @@ -286,9 +401,144 @@ "begin\n" " if hi < 0 then hi := INT(getdtablesize()) - 1; end;\n" " for fd := lo to hi do _ := close(I32(fd)); end;\n" - "end;\n\n"); + "end;\n" + "\n" + "(* fd closed on exec, and nonblocking, as flags, oCloexec and\n" + " oNonblock, say: macOS has no flags for them where a pipe or a\n" + " socket is made, so another thread's exec in between keeps the fd\n" + " open, a gap Linux hasn't. *)\n" + "proc setFlags(fd, flags: I32);\n" + "begin\n" + " if flags & oCloexec # 0 then _ := fcntl(fd, fSetfd, fdCloexec); end;\n" + " if flags & oNonblock # 0 then _ := fcntl(fd, fSetfl, fcntl(fd, fGetfl) | oNonblock); end;\n" + "end;\n" + "\n" + "(* A pipe, its two fds put at fds, taking flags, oCloexec and\n" + " oNonblock: 0, or -1 with errno set, as C's calls are. *)\n" + "proc makePipe*(fds: ^I32; flags: I32): I32;\n" + "begin\n" + " if pipe(fds) # 0 then return -1; end;\n" + " setFlags(fds[0], flags);\n" + " setFlags(fds[1], flags);\n" + " return 0;\n" + "end;\n" + "\n" + "(* The next connection to the socket fd, closed on exec; or -1. *)\n" + "proc accepted*(fd: I32): I32;\n" + "var r: I32;\n" + "begin\n" + " r := accept(fd, nil, nil);\n" + " if r >= 0 then setFlags(r, oCloexec); end;\n" + " return r;\n" + "end;\n" + "\n" + "(* The kernel's random bytes, at most n, put at buf: how many, or -1.\n" + " getentropy gives 256 at most at a time. *)\n" + "proc random*(buf: ^U8; n: UINT): INT;\n" + "begin\n" + " if n > 256 then n := 256; end;\n" + " if getentropy(buf, n) # 0 then return -1; end;\n" + " return INT(n);\n" + "end;\n" + "\n" + "(* v in hexadecimal into name from i on: where its digits end *)\n" + "proc hex(var name: [32]U8; i, v: INT): INT;\n" + "var n, k, d: INT;\n" + "begin\n" + " n := v;\n" + " repeat INC(i); n := n shr 4; until n = 0;\n" + " k := i;\n" + " repeat\n" + " DEC(k);\n" + " d := v & 15;\n" + " if d < 10 then name[k] := U8(d) + '0'; else name[k] := U8(d - 10) + 'a'; end;\n" + " v := v shr 4;\n" + " until v = 0;\n" + " return i;\n" + "end;\n" + "\n" + "(* A file in memory, of no bytes, with no name, closed on exec: its\n" + " fd, or -1. macOS has no memfd_create: it is a POSIX shared memory\n" + " object, made with a name of its own, /raz.PID.N, which is removed\n" + " at once. Such an object can be given its size once, and mapped, but\n" + " not read or written. *)\n" + "proc memFile*: I32;\n" + "var name: [32]U8; fd: I32; i: INT;\n" + "begin\n" + " COPY(name[0..5], \"/raz.\");\n" + " i := hex(name, 5, INT(getpid()));\n" + " name[i] := '.';\n" + " i := hex(name, i + 1, XADD(shmCount, 1));\n" + " name[i] := 0;\n" + " fd := shm_open(SYSTEM.ADR(name[0]), oRdwr | oCreat | oExcl, 384); (* rw------- *)\n" + " if fd < 0 then return -1; end;\n" + " _ := shm_unlink(SYSTEM.ADR(name[0]));\n" + " setFlags(fd, oCloexec);\n" + " return fd;\n" + "end;\n" + "\n" + "(* Waits until t, a struct timespec of the monotonic clock: macOS has\n" + " no clock_nanosleep, so nanosleep sleeps what is left, again after\n" + " EINTR. *)\n" + "proc sleepUntil*(t: ^U8);\n" + "var now, left: [2]I64; at: ^I64; d: I64;\n" + "begin\n" + " at := ^I64(t);\n" + " repeat\n" + " _ := clock_gettime(clockMonotonic, ^U8(SYSTEM.ADR(now[0])));\n" + " d := (at[0] - now[0]) * 1000000000 + at[1] - now[1];\n" + " if d <= 0 then return; end;\n" + " left := [d div 1000000000, d mod 1000000000];\n" + " _ := nanosleep(^U8(SYSTEM.ADR(left[0])), nil);\n" + " until false;\n" + "end;\n" + "\n" + "(* The number of processors this program may run on, or 0 if the\n" + " system doesn't say: those online, as macOS binds a program to none\n" + " of them. *)\n" + "proc processors*: INT;\n" + "begin\n" + " return sysconf(%d); (* _SC_NPROCESSORS_ONLN *)\n" + "end;\n" + "\n" + "(* The process and the user at the other end of the Unix socket fd,\n" + " as the system recorded them when it connected, and 0; or -1. The\n" + " user is in a struct xucred, LOCAL_PEERCRED's, and the process is\n" + " asked for alone, LOCAL_PEERPID. *)\n" + "proc peer*(fd: I32; var pid, uid: INT): I32;\n" + "var cred: [16]U64; size: U32; p: ^U8; q: ^U32; id: I32;\n" + "begin\n" + " p := ^U8(SYSTEM.ADR(cred[0]));\n" + " size := U32(SIZE([16]U64));\n" + " if getsockopt(fd, %d, %d, p, SYSTEM.ADR(size)) # 0 then return -1; end;\n" + " q := ^U32(p + ucUidAt);\n" + " uid := INT(q^);\n" + " size := 4;\n" + " if getsockopt(fd, %d, %d, ^U8(SYSTEM.ADR(id)), SYSTEM.ADR(size)) # 0 then return -1; end;\n" + " pid := INT(id);\n" + " return 0;\n" + "end;\n" + "\n" + "(* Sends n bytes at buf on the socket fd, without waiting, and without\n" + " SIGPIPE where the other end is gone: how many were sent, or -1.\n" + " macOS's send waits on a Unix socket though MSG_DONTWAIT is given, so\n" + " the socket is made nonblocking for it, as it was before after. *)\n" + "proc sendNow*(fd: I32; buf: ^U8; n: UINT): INT;\n" + "var f: I32; r: INT; e: ^I32; err: I32;\n" + "begin\n" + " f := fcntl(fd, fGetfl);\n" + " if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f | oNonblock); end;\n" + " r := send(fd, buf, n, msgNosignal | msgDontwait);\n" + " e := __error();\n" + " err := e^;\n" + " if (f >= 0) and (f & oNonblock = 0) then _ := fcntl(fd, fSetfl, f); end;\n" + " e^ := err;\n" + " return r;\n" + "end;\n" + "\n", + _SC_NPROCESSORS_ONLN, SOL_LOCAL, LOCAL_PEERCRED, SOL_LOCAL, LOCAL_PEERPID); #else -#error "a CAbi for this system needs its errno and closeFrom: add them here" +#error "a CAbi for this system needs its procedures: add them here" #endif printf("end CAbi.\n"); return 0;