diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38bdbc5..08085cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,6 +87,97 @@ jobs: build/yard --version | grep -q "1.0.0" echo "✓ versions ok" + macos-cross: + # Cross-build the macOS executables on Linux: trackc itself, hello and + # every example for x86_64-macos and aarch64-macos (docs/native.md, + # "Mach-O layout"); the macos job runs them on real Macs. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Bootstrap trackc + run: scripts/bootstrap.sh + + - name: Cross-build for both macOS targets and check the images + run: | + tc=build/bootstrap/stage3/trackc + for t in x86_64-macos aarch64-macos; do + d=build/macos/$t + mkdir -p "$d/examples" + "$tc" build --target "$t" compiler/src/main.trk -o "$d/trackc" + for f in examples/*.trk; do + s=$(basename "$f" .trk) + case "$s" in *_err) continue ;; esac + "$tc" build --target "$t" "$f" -o "$d/examples/$s" + done + python3 tests/tools/macho_check.py "$d/trackc" "$d"/examples/* + done + + - uses: actions/upload-artifact@v4 + with: + name: macos-binaries + path: build/macos + if-no-files-found: error + + macos: + # [untested here] Runs the cross-built binaries on GitHub's Macs: the + # examples against their goldens, then trackc rebuilds hello on the Mac + # and must produce the same bytes as the Linux trackc did. + needs: macos-cross + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15-intel # Intel + target: x86_64-macos + - runner: macos-latest # Apple silicon + target: aarch64-macos + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/download-artifact@v4 + with: + name: macos-binaries + path: build/macos + + - name: Show the machine + run: uname -a && sw_vers + + - name: Examples print their goldens + run: | + d=build/macos/${{ matrix.target }} + chmod +x "$d/trackc" "$d"/examples/* + fails=0 + for f in examples/*.trk; do + s=$(basename "$f" .trk) + case "$s" in *_err) continue ;; esac + set +e + "$d/examples/$s" >"$d/examples/$s.out" 2>"$d/examples/$s.err" + rc=$? + set -e + hb=0 + if sed "s/@HOSTNAME_BYTES@/$hb/" "tests/cases/examples/$s.out" | cmp -s - "$d/examples/$s.out" \ + && [ "$rc" = "$(cat "tests/cases/examples/$s.code")" ]; then + echo "ok $s" + else + echo "FAIL $s (exit $rc)" + sed "s/@HOSTNAME_BYTES@/$hb/" "tests/cases/examples/$s.out" | diff - "$d/examples/$s.out" | head -20 || true + head -5 "$d/examples/$s.err" + fails=$((fails + 1)) + fi + done + [ "$fails" = 0 ] + + - name: trackc builds hello on the Mac, byte-identical to the cross build + run: | + d=build/macos/${{ matrix.target }} + mkdir -p build/onmac + "$d/trackc" build --target ${{ matrix.target }} examples/hello.trk -o build/onmac/hello + cmp build/onmac/hello "$d/examples/hello" + ./build/onmac/hello + "$d/trackc" check examples/stdlib_demo.trk + windows: # Track on Windows from the committed Windows seed # (bootstrap/seed/trackc.exe): no Linux machine, no toolchain. diff --git a/README.md b/README.md index 23dad2c..927d757 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,16 @@ - **Lexical Lenses.** Scoped mutable access without manual pointer arithmetic or ownership transfer. - **Native Backend.** `trackc build` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. - **Track only.** The repository holds no C or Rust. Track bootstraps from a committed native seed binary. -- **Cross-compiling.** `trackc build --target x86_64-windows` writes a Windows PE executable from any host. +- **Cross-compiling.** `trackc build --target x86_64-windows` writes a Windows PE executable from any host; `--target x86_64-macos` / `aarch64-macos` a signed Mach-O. | target | `trackc build --target` | status | |---|---|---| | x86_64-linux | default on Linux | static ELF | | x86_64-windows | `x86_64-windows` | PE32+ console .exe (kernel32); trackc.exe self-hosts | -| aarch64-linux, x86_64/aarch64-macos, aarch64-windows | | not yet | +| aarch64-linux | `aarch64-linux` | static ELF (A64 lifted from the x86-64 code) | +| x86_64-macos | `x86_64-macos` (default on a Mac) | Mach-O, libSystem, ad-hoc signed | +| aarch64-macos | `aarch64-macos` | Mach-O for Apple silicon, ad-hoc signed | +| aarch64-windows | | not yet | ## Hello World diff --git a/bootstrap/seed/trackc b/bootstrap/seed/trackc index 1bf8007..68fb5e7 100755 Binary files a/bootstrap/seed/trackc and b/bootstrap/seed/trackc differ diff --git a/bootstrap/seed/trackc.exe b/bootstrap/seed/trackc.exe index c74ff8b..28eb84e 100755 Binary files a/bootstrap/seed/trackc.exe and b/bootstrap/seed/trackc.exe differ diff --git a/compiler/rt/os/macos.trk b/compiler/rt/os/macos.trk new file mode 100644 index 0000000..be0d5ac --- /dev/null +++ b/compiler/rt/os/macos.trk @@ -0,0 +1,617 @@ +// rt/os/macos.trk — Track runtime OS layer for macOS, through libSystem. +// +// Implements the OS interface (docs/native.md, "The OS layer") with +// libSystem functions called through the import table (`extern`; dyld +// binds them, macho.trk): +// +// os_start process entry: LC_MAIN's main(argc, argv, envp, apple) +// hands argc and argv over; then rt_start +// os_syscall the kernel calls the portable modules (mem, io, libc) +// make through `syscall6`, by Linux number, mapped to +// libSystem: open flags, mmap flags, the stat layout, +// clock ids and socket options translated, failures as +// -errno (errno from __error()) +// os_args_count, os_arg, env_get, env_exists, sys_exec, process_spawn, +// clock_ms, file_*, dir_exists, track_file_*, net_socket_* +// +// No variadic call: arm64 macOS passes variadic arguments on the stack, +// so open(2) is called without a mode and a file is created with +// creat(2) (mac_open). +// +// libSystem returns -1 and sets errno; os_syscall returns -errno like the +// Linux kernel, with macOS errno values (ENOENT, EINTR, EBADF agree). + +extern "libSystem.B.dylib" fn c_read(fd: i64, buf: i64, n: i64) -> i64 as "read"; +extern "libSystem.B.dylib" fn c_write(fd: i64, buf: i64, n: i64) -> i64 as "write"; +extern "libSystem.B.dylib" fn c_open(path: i64, flags: i64) -> i32 as "open"; +extern "libSystem.B.dylib" fn c_creat(path: i64, mode: i64) -> i32 as "creat"; +extern "libSystem.B.dylib" fn c_close(fd: i64) -> i32 as "close"; +extern "libSystem.B.dylib" fn c_stat(path: i64, st: i64) -> i32 as "stat"; +extern "libSystem.B.dylib" fn c_lseek(fd: i64, off: i64, how: i64) -> i64 as "lseek"; +extern "libSystem.B.dylib" fn c_mmap(addr: i64, len: i64, prot: i64, flags: i64, fd: i64, off: i64) -> i64 as "mmap"; +extern "libSystem.B.dylib" fn c_munmap(addr: i64, len: i64) -> i32 as "munmap"; +extern "libSystem.B.dylib" fn c_pipe(fds: i64) -> i32 as "pipe"; +extern "libSystem.B.dylib" fn c_access(path: i64, mode: i64) -> i32 as "access"; +extern "libSystem.B.dylib" fn c_getpid() -> i32 as "getpid"; +extern "libSystem.B.dylib" fn c_kill(pid: i64, sig: i64) -> i32 as "kill"; +extern "libSystem.B.dylib" fn c_unlink(path: i64) -> i32 as "unlink"; +extern "libSystem.B.dylib" fn c_clock_gettime(id: i64, ts: i64) -> i32 as "clock_gettime"; +extern "libSystem.B.dylib" fn c_exit(code: i64) -> i64 as "exit"; +extern "libSystem.B.dylib" fn c_fchmod(fd: i64, mode: i64) -> i32 as "fchmod"; +extern "libSystem.B.dylib" fn c_errno_at() -> i64 as "__error"; +extern "libSystem.B.dylib" fn c_environ_at() -> i64 as "_NSGetEnviron"; +extern "libSystem.B.dylib" fn c_system(cmd: i64) -> i32 as "system"; +extern "libSystem.B.dylib" fn c_socket(domain: i64, kind: i64, proto: i64) -> i32 as "socket"; +extern "libSystem.B.dylib" fn c_setsockopt(fd: i64, level: i64, opt: i64, val: i64, len: i64) -> i32 as "setsockopt"; +extern "libSystem.B.dylib" fn c_bind(fd: i64, addr: i64, len: i64) -> i32 as "bind"; +extern "libSystem.B.dylib" fn c_listen(fd: i64, backlog: i64) -> i32 as "listen"; +extern "libSystem.B.dylib" fn c_accept(fd: i64, addr: i64, len: i64) -> i32 as "accept"; +extern "libSystem.B.dylib" fn c_connect(fd: i64, addr: i64, len: i64) -> i32 as "connect"; +extern "libSystem.B.dylib" fn c_send(fd: i64, buf: i64, n: i64, flags: i64) -> i64 as "send"; +extern "libSystem.B.dylib" fn c_recv(fd: i64, buf: i64, n: i64, flags: i64) -> i64 as "recv"; + +const MS_STAT = 6400; // macOS struct stat (144 bytes) in the state page + +// ---------------------------------------------------------------- process + +// The process entry (trackc's macOS entry calls it with LC_MAIN's argc +// and argv; envp follows argv as on Linux, and rt_getenv reads environ). +fn os_start(argc: i64, argv: i64) -> i64 { + return rt_start(argc, argv); +} + +fn os_args_count() -> i64 { return rs(RS_ARGC); } + +fn os_arg(idx: i64) -> i64 { + if idx >= 0 && idx < rs(RS_ARGC) { + return rt_dup(load64(rs(RS_ARGV) + 8 * idx)); + } + return rt_dup_n("", 0); +} + +// Value of environment variable `key` ("NAME=value"), or 0 when unset. +fn rt_getenv(key: i64) -> i64 { + let mut e = load64(c_environ_at()); + while load64(e) != 0 { + let entry = load64(e); + let mut i: i64 = 0; + while load8(key + i) != 0 && load8(key + i) == load8(entry + i) { + i = i + 1; + } + if load8(key + i) == 0 && load8(entry + i) == 61 { + return entry + i + 1; + } + e = e + 8; + } + return 0; +} + +fn env_get(key: i64) -> i64 { + if key == 0 { + return rt_dup_n("", 0); + } + let v = rt_getenv(key); + if v == 0 { + return rt_dup_n("", 0); + } + return rt_dup(v); +} + +fn env_exists(key: i64) -> i64 { + if key != 0 && rt_getenv(key) != 0 { + return 1; + } + return 0; +} + +// system(3): /bin/sh -c cmd; exit status, or 128 + signal. +fn sys_exec(cmd: i64) -> i64 { + if cmd == 0 { + return -1; + } + rt_flush(); + let status = c_system(cmd); + if status < 0 { + return -1; + } + if (status & 127) == 0 { + return (status >> 8) & 255; + } + return 128 + (status & 127); +} + +fn process_spawn(cmd: i64) -> i64 { return sys_exec(cmd); } + +fn clock_ms() -> i64 { + let ts = RT_BASE + RS_TIME; + c_clock_gettime(6, ts); // CLOCK_MONOTONIC + return load64(ts) * 1000 + load64(ts + 8) / 1000000; +} + +// ---------------------------------------------------------- kernel calls + +// A libSystem result: -errno when it failed (-1). +fn mac_ret(r: i64) -> i64 { + if r == -1 { + return 0 - (load64(c_errno_at()) & 4294967295); + } + return r; +} + +// Linux open(2) flags -> macOS. +fn mac_oflags(f: i64) -> i64 { + let mut m = f & 3; + if (f & 64) != 0 { m = m | 512; } // O_CREAT + if (f & 128) != 0 { m = m | 2048; } // O_EXCL + if (f & 512) != 0 { m = m | 1024; } // O_TRUNC + if (f & 1024) != 0 { m = m | 8; } // O_APPEND + if (f & 2048) != 0 { m = m | 4; } // O_NONBLOCK + if (f & 65536) != 0 { m = m | 1048576; } // O_DIRECTORY + if (f & 524288) != 0 { m = m | 16777216; } // O_CLOEXEC + return m; +} + +// open(2) with Linux flags and mode, without a variadic call: creating +// goes through creat(2) (O_WRONLY | O_CREAT | O_TRUNC), then the file is +// opened again with the asked flags minus O_CREAT and O_EXCL (unless +// creat's write-only descriptor already fits). +fn mac_open(path: i64, f: i64, mode: i64) -> i64 { + let flags = mac_oflags(f) & (0 - 2561); // without O_CREAT | O_EXCL + if (f & 64) == 0 { + return mac_ret(c_open(path, flags)); + } + if c_access(path, 0) == 0 { + if (f & 128) != 0 { + return -17; // EEXIST + } + return mac_ret(c_open(path, flags)); + } + let fd = mac_ret(c_creat(path, mode)); + if fd < 0 { + return fd; + } + if (f & 3) == 1 && (f & 1024) == 0 { + return fd; // creat's own descriptor fits + } + c_close(fd); + return mac_ret(c_open(path, flags)); +} + +// Linux mmap(2) flags -> macOS; MAP_FIXED_NOREPLACE becomes a hint that +// must be met (os_syscall checks). +fn mac_mflags(f: i64) -> i64 { + let mut m = f & 19; // MAP_SHARED | MAP_PRIVATE | MAP_FIXED + if (f & 32) != 0 { m = m | 4096; } // MAP_ANON + if (f & 16384) != 0 { m = m | 64; } // MAP_NORESERVE + return m; +} + +// stat(2) into the Linux struct stat layout the portable code reads: +// st_mode at 24, st_size at 48 (macOS 64-bit-inode stat: 4 and 96). +fn mac_stat(path: i64, st: i64) -> i64 { + let ms = RT_BASE + MS_STAT; + let r = mac_ret(c_stat(path, ms)); + if r < 0 { + return r; + } + rt_zero(st, 144); + store64(st + 24, load64(ms + 4) & 65535); + store64(st + 48, load64(ms + 96)); + return 0; +} + +// The `syscall6` calls of the portable runtime modules, by Linux number; +// -38 (ENOSYS) for the rest. +fn os_syscall(nr: i64, a: i64, b: i64, d: i64, e: i64, f: i64) -> i64 { + if nr == 0 { + return mac_ret(c_read(a, b, d)); + } + if nr == 1 { + return mac_ret(c_write(a, b, d)); + } + if nr == 2 { + return mac_open(a, b, d); + } + if nr == 3 { + return mac_ret(c_close(a)); + } + if nr == 4 { + return mac_stat(a, b); + } + if nr == 8 { + return mac_ret(c_lseek(a, b, d)); + } + if nr == 9 { + let p = mac_ret(c_mmap(a, b, d, mac_mflags(e), f, 0)); + if p >= 0 && (e & 1048576) != 0 && p != a { + c_munmap(p, b); + return -17; // EEXIST: the hint was not met + } + return p; + } + if nr == 11 { + return mac_ret(c_munmap(a, b)); + } + if nr == 25 { + // mremap(old, old_len, new_len, MAYMOVE): a new mapping, copied + let q = mac_ret(c_mmap(0, d, 3, 4098, -1, 0)); + if q < 0 { + return q; + } + let mut n = b; + if d < n { + n = d; + } + rt_copy(q, a, n); + c_munmap(a, b); + return q; + } + if nr == 28 { + return 0; // madvise: hints only + } + if nr == 91 { + return mac_ret(c_fchmod(a, b)); + } + if nr == 22 { + return mac_ret(c_pipe(a)); + } + if nr == 21 { + return mac_ret(c_access(a, b)); + } + if nr == 87 { + return mac_ret(c_unlink(a)); + } + if nr == 39 { + return c_getpid(); + } + if nr == 62 { + return mac_ret(c_kill(a, b)); + } + if nr == 228 { + let mut id = a; + if id == 1 { + id = 6; // CLOCK_MONOTONIC + } + return mac_ret(c_clock_gettime(id, b)); + } + if nr == 231 || nr == 60 { + c_exit(a); + return 0; + } + return -38; +} + +// ------------------------------------------------------------------ files +// +// A file handle is a runtime record [fd]; 0 when the open failed. + +const O_RDONLY = 0; +const O_WRONLY_CREAT_TRUNC = 577; // O_WRONLY | O_CREAT | O_TRUNC +const O_WRONLY_CREAT_APPEND = 1089; // O_WRONLY | O_CREAT | O_APPEND +const O_RDWR = 2; + +// open(2) flags for an fopen(3) mode string. +fn rt_open_flags(mode: i64) -> i64 { + let m = load8(mode); + let plus = rt_find(mode, "+") >= 0; + if m == 114 { + if plus { + return O_RDWR; + } + return O_RDONLY; + } + if m == 119 { + if plus { + return 578; // O_RDWR | O_CREAT | O_TRUNC + } + return O_WRONLY_CREAT_TRUNC; + } + if m == 97 { + if plus { + return 1090; // O_RDWR | O_CREAT | O_APPEND + } + return O_WRONLY_CREAT_APPEND; + } + return -1; +} + +fn file_open(path: i64, mode: i64) -> i64 { + if path == 0 || mode == 0 { + return 0; + } + let flags = rt_open_flags(mode); + if flags < 0 { + return 0; + } + let fd = sys3(SYS_OPEN, path, flags | 524288, 438); // O_CLOEXEC, 0666 + if fd < 0 { + return 0; + } + let h = rt_malloc(8); + store64(h, fd); + return h; +} + +fn file_close(h: i64) -> i64 { + if h != 0 { + sys1(SYS_CLOSE, load64(h)); + rt_free(h); + } + return 0; +} + +// Read everything from `fd` to end of file; "" on error. The size from +// lseek only sizes the first buffer: files whose size is not known up +// front (/proc, pipes) read whole too. +fn rt_read_fd(fd: i64) -> i64 { + let mut cap: i64 = 4096; + let end = sys3(SYS_LSEEK, fd, 0, 2); + if end >= 0 { + if sys3(SYS_LSEEK, fd, 0, 0) < 0 { + return rt_dup_n("", 0); + } + cap = end + 1; + } + let mut buf = rt_malloc(cap + 1); + let mut got: i64 = 0; + let mut going = true; + while going { + if got == cap { + cap = cap * 2; + buf = rt_realloc(buf, cap + 1); + } + let r = sys3(SYS_READ, fd, buf + got, cap - got); + if r == -4 { + // EINTR: retry + } else if r <= 0 { + going = false; + } else { + got = got + r; + } + } + store8(buf + got, 0); + return buf; +} + +fn file_read_all(h: i64) -> i64 { + if h == 0 { + return rt_dup_n("", 0); + } + return rt_read_fd(load64(h)); +} + +fn file_write(h: i64, content: i64) -> i64 { + if h == 0 || content == 0 { + return -1; + } + return rt_write_all(load64(h), content, rt_strlen(content)); +} + +fn file_exists(path: i64) -> i64 { + if path != 0 && sys2(SYS_ACCESS, path, 0) == 0 { + return 1; + } + return 0; +} + +fn file_remove(path: i64) -> i64 { + if path != 0 && sys1(SYS_UNLINK, path) == 0 { + return 0; + } + return -1; +} + +fn file_size(path: i64) -> i64 { + let st = RT_BASE + RS_STAT; + if path == 0 || sys2(SYS_STAT, path, st) != 0 { + return -1; + } + return load64(st + 48); +} + +fn dir_exists(path: i64) -> bool { + let st = RT_BASE + RS_STAT; + if path == 0 || sys2(SYS_STAT, path, st) != 0 { + return false; + } + return (load64(st + 24) & 61440) == 16384; +} + +fn file_copy(src: i64, dst: i64) -> i64 { + if src == 0 || dst == 0 { + return -1; + } + let fin = sys3(SYS_OPEN, src, O_RDONLY | 524288, 0); + if fin < 0 { + return -1; + } + let fout = sys3(SYS_OPEN, dst, O_WRONLY_CREAT_TRUNC | 524288, 438); + if fout < 0 { + sys1(SYS_CLOSE, fin); + return -1; + } + let buf = rt_malloc(65536); + let mut going = true; + while going { + let n = sys3(SYS_READ, fin, buf, 65536); + if n == -4 { + // EINTR: retry + } else if n <= 0 { + going = false; + } else { + rt_write_all(fout, buf, n); + } + } + rt_free(buf); + sys1(SYS_CLOSE, fin); + sys1(SYS_CLOSE, fout); + return 0; +} + +// Whole-file helpers: open, transfer, and close in one call. +fn track_file_read(path: i64) -> i64 { + if path == 0 { + return rt_dup_n("", 0); + } + let fd = sys3(SYS_OPEN, path, O_RDONLY | 524288, 0); + if fd < 0 { + return rt_dup_n("", 0); + } + let out = rt_read_fd(fd); + sys1(SYS_CLOSE, fd); + return out; +} + +fn track_file_write_all(path: i64, content: i64) -> i64 { + if path == 0 { + return -1; + } + let fd = sys3(SYS_OPEN, path, O_WRONLY_CREAT_TRUNC | 524288, 438); + if fd < 0 { + return -1; + } + let mut status: i64 = -1; + if content != 0 { + status = rt_write_all(fd, content, rt_strlen(content)); + } + if sys1(SYS_CLOSE, fd) != 0 { + status = -1; + } + return status; +} + +// ---------------------------------------------------------------- network + +// struct sockaddr_in for AF_INET (BSD: sin_len first), `port`, and the +// IPv4 address word `addr` (network byte order packed little-endian). +fn rt_sockaddr(port: i64, addr: i64) -> i64 { + let sa = RT_BASE + RS_SOCK; + let p = port & 65535; + store64(sa, 16 | (2 << 8) | ((p >> 8) << 16) | ((p & 255) << 24) | ((addr & 4294967295) << 32)); + store64(sa + 8, 0); + return sa; +} + +// inet_pton for dotted-quad IPv4; -1 when malformed. +fn rt_parse_ipv4(s: i64) -> i64 { + let mut addr: i64 = 0; + let mut part: i64 = 0; + let mut digits: i64 = 0; + let mut parts: i64 = 0; + let mut i: i64 = 0; + while true { + let ch = load8(s + i); + if rt_is_digit(ch) { + part = part * 10 + ch - 48; + digits = digits + 1; + if part > 255 || digits > 3 { + return -1; + } + } else if ch == 46 || ch == 0 { + if digits == 0 || parts == 4 { + return -1; + } + addr = addr | (part << (8 * parts)); + parts = parts + 1; + part = 0; + digits = 0; + if ch == 0 { + if parts != 4 { + return -1; + } + return addr; + } + } else { + return -1; + } + i = i + 1; + } + return -1; +} + +fn net_socket_tcp_listen(port: i64) -> i64 { + let fd = c_socket(2, 1, 0); + if fd < 0 { + return -1; + } + c_setsockopt(fd, 65535, 4, RT_BASE + RS_ONE, 4); // SOL_SOCKET, SO_REUSEADDR + let r = mac_ret(c_bind(fd, rt_sockaddr(port, 0), 16)); + if r < 0 { + let b = track_sb_new(); + if r == -48 { + track_sb_push(b, "Track Network Error: Port conflict! Port "); + track_sb_push_int(b, port); + track_sb_push(b, " is already in use by another process.\n"); + } else { + track_sb_push(b, "Track Network Error: Failed to bind TCP socket on port "); + track_sb_push_int(b, port); + track_sb_push(b, " (errno: "); + track_sb_push_int(b, 0 - r); + track_sb_push(b, ").\n"); + } + rt_err_bytes(load64(b), track_sb_len(b)); + c_close(fd); + return -1; + } + if c_listen(fd, 128) < 0 { + c_close(fd); + return -1; + } + return fd; +} + +fn net_socket_accept(server_fd: i64) -> i64 { + if server_fd < 0 { + return -1; + } + let r = c_accept(server_fd, 0, 0); + if r < 0 { + return -1; + } + return r; +} + +fn net_socket_connect(host: i64, port: i64) -> i64 { + if host == 0 { + return -1; + } + let fd = c_socket(2, 1, 0); + if fd < 0 { + return -1; + } + let addr = rt_parse_ipv4(host); + if addr < 0 || c_connect(fd, rt_sockaddr(port, addr), 16) < 0 { + c_close(fd); + return -1; + } + return fd; +} + +fn net_socket_send(fd: i64, data: i64, len: i64) -> i64 { + if fd < 0 || data == 0 { + return -1; + } + let r = c_send(fd, data, len, 0); + if r < 0 { + return -1; + } + return r; +} + +fn net_socket_recv(fd: i64, buf: i64, max_len: i64) -> i64 { + if fd < 0 || buf == 0 { + return -1; + } + let r = c_recv(fd, buf, max_len, 0); + if r < 0 { + return -1; + } + return r; +} + +fn net_socket_close(fd: i64) -> i64 { + if fd >= 0 { + c_close(fd); + } + return 0; +} diff --git a/compiler/src/ast.trk b/compiler/src/ast.trk index c0501fe..11172cd 100644 --- a/compiler/src/ast.trk +++ b/compiler/src/ast.trk @@ -32,7 +32,7 @@ const K_WHILE = 18; // a = condition, b = body const K_FOR = 19; // a = variable name, b = iterable, c = body const K_RETURN = 20; // a = value (-1) const K_ASSIGN = 21; // a = target, b = value -const K_FN = 22; // a = name, b = generics, c = [name, type]*, d = return type (-1), e = body +const K_FN = 22; // a = name, b = generics, c = [name, type]*, d = return type (-1), e = symbol text (`as "sym"`, -1: the name), e = body const K_USE = 23; // a = path text, b = import names (-1), c = alias name (-1) const K_CONST = 24; // a = name, b = value const K_TYPEDEF = 25; // a = name, b = target type @@ -45,7 +45,7 @@ const K_UNION = 31; // a = name, b = [name, payload type (-1)]* const K_MATCH = 32; // a = target, b = [pattern, guard (-1), body]* const K_STRUCT = 33; // a = name, b = [field name, type]* const K_FIELD = 34; // a = target, b = field name -const K_EXTERN = 35; // a = name, b = library text, c = [name, type]*, d = return type (-1) +const K_EXTERN = 35; // a = name, b = library text, c = [name, type]*, d = return type (-1), e = symbol text (`as "sym"`, -1: the name) // Patterns const P_IDENT = 40; // a = name diff --git a/compiler/src/ffi.trk b/compiler/src/ffi.trk index 87be023..3b88b39 100644 --- a/compiler/src/ffi.trk +++ b/compiler/src/ffi.trk @@ -10,6 +10,10 @@ // libSystem) or an aarch64 backend reuses the same two vectors and adds // its own call sequence next to ffi_win64_call. // +// x86_64-macos (macho.trk) uses ffi_sysv_call: the same tables, the +// System V AMD64 call sequence, the slot being a __got entry dyld binds. +// An aarch64 backend adds its own call sequence and reuses the tables. +// // Track's own calling convention (ngen.trk ng_arg_reg) is not the // platform's, so each call converts: arguments are evaluated and pushed // first (first argument deepest), then the call sequence moves them into @@ -88,3 +92,59 @@ fn ffi_win64_call(b: i64, fixups: i64, id: i64, nargs: i64, ret: i64) -> i64 { } return 0; } + +// System V AMD64 call of import `id` (x86_64-macos), its `nargs` +// arguments pushed (first argument deepest). rdi, rsi, rdx, rcx, r8, r9 +// take arguments 1-6, the rest go on the stack from [rsp], rsp is 16-byte +// aligned at the call and al = 0 (no vector registers: variadic callees +// such as open(2) read it). `ret` as for ffi_win64_call. Leaves the result +// in rax and pops the arguments. Clobbers rax, rcx, rdx, rsi, rdi, r8-r11 +// (volatile in System V; ngen marks the caller NG_CLOB and NG_VOLX). +fn ffi_sysv_call(b: i64, fixups: i64, id: i64, nargs: i64, ret: i64) -> i64 { + let mut extra: i64 = 0; + if nargs > 6 { + extra = nargs - 6; + } + let frame = (8 * extra + 8 + 15) & (0 - 16); + x_bytes3(b, 73, 137, 227); // mov r11, rsp (the pushed arguments) + x_bytes3(b, 72, 131, 228); + x_byte(b, 240); // and rsp, -16 + x_bytes3(b, 72, 129, 236); + x_u32(b, frame); // sub rsp, frame + x_bytes3(b, 76, 137, 156); + x_byte(b, 36); + x_u32(b, frame - 8); // mov [rsp + frame - 8], r11 + let mut i: i64 = 6; + while i < nargs { + ffi_rm_disp(b, 73, 139, 131, 8 * (nargs - 1 - i)); // mov rax, [r11 + d] + x_bytes3(b, 72, 137, 132); + x_byte(b, 36); + x_u32(b, 8 * (i - 6)); // mov [rsp + 8k], rax + i = i + 1; + } + if nargs > 0 { ffi_rm_disp(b, 73, 139, 187, 8 * (nargs - 1)); } // mov rdi, [r11 + d] + if nargs > 1 { ffi_rm_disp(b, 73, 139, 179, 8 * (nargs - 2)); } // mov rsi, [r11 + d] + if nargs > 2 { ffi_rm_disp(b, 73, 139, 147, 8 * (nargs - 3)); } // mov rdx, [r11 + d] + if nargs > 3 { ffi_rm_disp(b, 73, 139, 139, 8 * (nargs - 4)); } // mov rcx, [r11 + d] + if nargs > 4 { ffi_rm_disp(b, 77, 139, 131, 8 * (nargs - 5)); } // mov r8, [r11 + d] + if nargs > 5 { ffi_rm_disp(b, 77, 139, 139, 8 * (nargs - 6)); } // mov r9, [r11 + d] + x_bytes2(b, 49, 192); // xor eax, eax + x_bytes2(b, 255, 21); // call [rip + disp32] + vpush(fixups, vlen(b)); + vpush(fixups, id); + x_u32(b, 0); + x_bytes3(b, 72, 139, 164); + x_byte(b, 36); + x_u32(b, frame - 8); // mov rsp, [rsp + frame - 8] + if nargs > 0 { + x_bytes3(b, 72, 129, 196); + x_u32(b, 8 * nargs); // add rsp, 8 * nargs + } + if ret == 1 { + return x_bytes3(b, 72, 99, 192); // movsxd rax, eax + } + if ret == 2 { + return x_bytes2(b, 137, 192); // mov eax, eax + } + return 0; +} diff --git a/compiler/src/macho.trk b/compiler/src/macho.trk new file mode 100644 index 0000000..c2d73b7 --- /dev/null +++ b/compiler/src/macho.trk @@ -0,0 +1,631 @@ +// macho.trk — Mach-O 64 executable writer (x86_64-macos; aarch64-macos +// once an aarch64 backend exists: a cputype and a fixup patcher). +// +// Layout (every segment 16 KiB aligned in the file and in memory, the +// file offset of a byte equal to its address minus MO_BASE): +// +// __PAGEZERO 4 GiB, no access +// __TEXT file 0: mach header and load commands; __text at +// MO_TEXT_OFF (the entry, LC_MAIN), the code ngen made +// __DATA __data (the data ngen appends after the code: ngen pads the +// code to 16 KiB for this target, so its rip-relative +// references hold), then __got, one 8-byte slot per import +// __LINKEDIT dyld bind opcodes, export trie, symbol table, indirect +// symbol table, string table, then the code signature +// +// Load commands: the four segments, LC_DYLD_INFO_ONLY, LC_SYMTAB, +// LC_DYSYMTAB, LC_LOAD_DYLINKER (/usr/lib/dyld), LC_UUID, +// LC_BUILD_VERSION (macOS 11.0), LC_MAIN, one LC_LOAD_DYLIB per library, +// LC_CODE_SIGNATURE. Every import is bound by dyld into its __got slot +// (BIND_TYPE_POINTER, two-level namespace, library ordinal = position of +// its LC_LOAD_DYLIB); each call site is `call [rip + slot]` (ffi.trk). +// +// The code signature is ad hoc and linker-signed, as ld64 writes it: a +// SuperBlob holding one CodeDirectory (version 0x20400, flags adhoc | +// linker-signed, SHA-256 of every 4 KiB page of the file before the +// signature, the exec segment = __TEXT). Arm64 macOS runs nothing +// unsigned; x86_64 gets the same signature. + +import "base"; +import "x64"; + +const MO_BASE = 4294967296; // 0x100000000, the end of __PAGEZERO +const MO_PAGE = 16384; +const MO_TEXT_OFF = 16384; // __text: the page after the headers +const MO_CPU_X86_64 = 16777223; // CPU_TYPE_X86_64 (0x01000007) +const MO_CPU_ARM64 = 16777228; // CPU_TYPE_ARM64 (0x0100000c) +const MO_STACK = 33554432; // LC_MAIN stack size: 32 MiB (trackc recurses deeply) + +fn mo_up(n: i64, a: i64) -> i64 { return (n + a - 1) / a * a; } + +fn mo_u16(b: i64, v: i64) -> i64 { + x_byte(b, v); + return x_byte(b, v >> 8); +} + +fn mo_be32(b: i64, v: i64) -> i64 { + x_byte(b, v >> 24); + x_byte(b, v >> 16); + x_byte(b, v >> 8); + return x_byte(b, v); +} + +fn mo_be64(b: i64, v: i64) -> i64 { + mo_be32(b, v >> 32); + return mo_be32(b, v); +} + +fn mo_pad(b: i64, size: i64) -> i64 { + while vlen(b) < size { + vpush(b, 0); + } + return 0; +} + +fn mo_append(b: i64, src: i64) -> i64 { + let mut i: i64 = 0; + while i < vlen(src) { + vpush(b, vget(src, i)); + i = i + 1; + } + return 0; +} + +fn mo_cstr(b: i64, s: i64) -> i64 { + mo_append(b, text_bytes(s)); + return vpush(b, 0); +} + +// A 16-byte, NUL-padded name field. +fn mo_name16(b: i64, name: i64) -> i64 { + let at = vlen(b); + mo_append(b, text_bytes(name)); + return mo_pad(b, at + 16); +} + +fn mo_uleb(b: i64, v: i64) -> i64 { + let mut x = v; + while x >= 128 { + x_byte(b, (x & 127) | 128); + x = x >> 7; + } + return x_byte(b, x); +} + +fn mo_segment(b: i64, name: i64, addr: i64, vsize: i64, off: i64, fsize: i64, prot: i64, nsects: i64) -> i64 { + x_u32(b, 25); // LC_SEGMENT_64 + x_u32(b, 72 + 80 * nsects); + mo_name16(b, name); + x_u64(b, addr); + x_u64(b, vsize); + x_u64(b, off); + x_u64(b, fsize); + x_u32(b, prot); // maxprot + x_u32(b, prot); // initprot + x_u32(b, nsects); + return x_u32(b, 0); +} + +fn mo_section(b: i64, sect: i64, seg: i64, addr: i64, size: i64, off: i64, align: i64, flags: i64, r1: i64) -> i64 { + mo_name16(b, sect); + mo_name16(b, seg); + x_u64(b, addr); + x_u64(b, size); + x_u32(b, off); + x_u32(b, align); + x_u32(b, 0); + x_u32(b, 0); + x_u32(b, flags); + x_u32(b, r1); + x_u32(b, 0); + return x_u32(b, 0); +} + +// The symbol dyld looks up for `sym`. On x86_64 libSystem keeps the +// 32-bit-inode stat family under the plain names; the 64-bit-inode +// layout (the only one arm64 has) is `$INODE64`. +fn mo_symbol(sym: i64, cpu: i64) -> i64 { + if cpu == MO_CPU_X86_64 && (text_eq(sym, "stat") || text_eq(sym, "fstat") || text_eq(sym, "lstat")) { + return text_cat3("_", sym, "$INODE64"); + } + return text_cat("_", sym); +} + +// The install name of library `lib` as an extern names it. +fn mo_dylib_path(lib: i64) -> i64 { + if text_starts(lib, "/") { + return lib; + } + return text_cat("/usr/lib/", lib); +} + +// ---------------------------------------------------------------- SHA-256 + +const MO_M32 = 4294967295; + +fn sha_xor(a: i64, b: i64) -> i64 { return (a | b) - (a & b); } + +fn sha_rotr(x: i64, n: i64) -> i64 { return ((x >> n) | (x << (32 - n))) & MO_M32; } + +fn sha_k() -> i64 { + let k = vnew_cap(64); + vpush(k, 1116352408); vpush(k, 1899447441); vpush(k, 3049323471); vpush(k, 3921009573); + vpush(k, 961987163); vpush(k, 1508970993); vpush(k, 2453635748); vpush(k, 2870763221); + vpush(k, 3624381080); vpush(k, 310598401); vpush(k, 607225278); vpush(k, 1426881987); + vpush(k, 1925078388); vpush(k, 2162078206); vpush(k, 2614888103); vpush(k, 3248222580); + vpush(k, 3835390401); vpush(k, 4022224774); vpush(k, 264347078); vpush(k, 604807628); + vpush(k, 770255983); vpush(k, 1249150122); vpush(k, 1555081692); vpush(k, 1996064986); + vpush(k, 2554220882); vpush(k, 2821834349); vpush(k, 2952996808); vpush(k, 3210313671); + vpush(k, 3336571891); vpush(k, 3584528711); vpush(k, 113926993); vpush(k, 338241895); + vpush(k, 666307205); vpush(k, 773529912); vpush(k, 1294757372); vpush(k, 1396182291); + vpush(k, 1695183700); vpush(k, 1986661051); vpush(k, 2177026350); vpush(k, 2456956037); + vpush(k, 2730485921); vpush(k, 2820302411); vpush(k, 3259730800); vpush(k, 3345764771); + vpush(k, 3516065817); vpush(k, 3600352804); vpush(k, 4094571909); vpush(k, 275423344); + vpush(k, 430227734); vpush(k, 506948616); vpush(k, 659060556); vpush(k, 883997877); + vpush(k, 958139571); vpush(k, 1322822218); vpush(k, 1537002063); vpush(k, 1747873779); + vpush(k, 1955562222); vpush(k, 2024104815); vpush(k, 2227730452); vpush(k, 2361852424); + vpush(k, 2428436474); vpush(k, 2756734187); vpush(k, 3204031479); vpush(k, 3329325298); + return k; +} + +// One 64-byte block of `src` at `at` into the state `h`. +fn sha_block(h: i64, w: i64, k: i64, src: i64, at: i64) -> i64 { + let mut t: i64 = 0; + while t < 16 { + let p = at + 4 * t; + vset(w, t, (vget(src, p) << 24) | (vget(src, p + 1) << 16) | (vget(src, p + 2) << 8) | vget(src, p + 3)); + t = t + 1; + } + while t < 64 { + let x = vget(w, t - 15); + let y = vget(w, t - 2); + let s0 = sha_xor(sha_xor(sha_rotr(x, 7), sha_rotr(x, 18)), x >> 3); + let s1 = sha_xor(sha_xor(sha_rotr(y, 17), sha_rotr(y, 19)), y >> 10); + vset(w, t, (vget(w, t - 16) + s0 + vget(w, t - 7) + s1) & MO_M32); + t = t + 1; + } + let mut a = vget(h, 0); + let mut b = vget(h, 1); + let mut c = vget(h, 2); + let mut d = vget(h, 3); + let mut e = vget(h, 4); + let mut f = vget(h, 5); + let mut g = vget(h, 6); + let mut hh = vget(h, 7); + let mut r: i64 = 0; + while r < 64 { + let s1 = sha_xor(sha_xor(sha_rotr(e, 6), sha_rotr(e, 11)), sha_rotr(e, 25)); + let ch = sha_xor(e & f, (MO_M32 - e) & g); + let t1 = (hh + s1 + ch + vget(k, r) + vget(w, r)) & MO_M32; + let s0 = sha_xor(sha_xor(sha_rotr(a, 2), sha_rotr(a, 13)), sha_rotr(a, 22)); + let maj = sha_xor(sha_xor(a & b, a & c), b & c); + let t2 = (s0 + maj) & MO_M32; + hh = g; + g = f; + f = e; + e = (d + t1) & MO_M32; + d = c; + c = b; + b = a; + a = (t1 + t2) & MO_M32; + r = r + 1; + } + vset(h, 0, (vget(h, 0) + a) & MO_M32); + vset(h, 1, (vget(h, 1) + b) & MO_M32); + vset(h, 2, (vget(h, 2) + c) & MO_M32); + vset(h, 3, (vget(h, 3) + d) & MO_M32); + vset(h, 4, (vget(h, 4) + e) & MO_M32); + vset(h, 5, (vget(h, 5) + f) & MO_M32); + vset(h, 6, (vget(h, 6) + g) & MO_M32); + return vset(h, 7, (vget(h, 7) + hh) & MO_M32); +} + +// SHA-256 of bytes [from, to) of `src`, appended (32 bytes) to `out`. +fn sha256_into(out: i64, k: i64, src: i64, from: i64, to: i64) -> i64 { + let h = vnew_cap(8); + vpush(h, 1779033703); vpush(h, 3144134277); vpush(h, 1013904242); vpush(h, 2773480762); + vpush(h, 1359893119); vpush(h, 2600822924); vpush(h, 528734635); vpush(h, 1541459225); + let w = vfill(vnew_cap(64), 64, 0); + let mut at = from; + while at + 64 <= to { + sha_block(h, w, k, src, at); + at = at + 64; + } + let tail = vnew_cap(128); + while at < to { + vpush(tail, vget(src, at)); + at = at + 1; + } + vpush(tail, 128); + while vlen(tail) % 64 != 56 { + vpush(tail, 0); + } + mo_be64(tail, 8 * (to - from)); + let mut q: i64 = 0; + while q < vlen(tail) { + sha_block(h, w, k, tail, q); + q = q + 64; + } + let mut i: i64 = 0; + while i < 8 { + mo_be32(out, vget(h, i)); + i = i + 1; + } + return out; +} + +// ---------------------------------------------------------------- image + +// The libraries of `imports`, in order of first use. +fn mo_libs(imports: i64) -> i64 { + let libs = vnew(); + let mut i: i64 = 0; + while i < vlen(imports) { + let lib = vget(imports, i); + let mut seen = false; + let mut j: i64 = 0; + while j < vlen(libs) { + if text_eq(vget(libs, j), lib) { + seen = true; + } + j = j + 1; + } + if !seen { + vpush(libs, lib); + } + i = i + 2; + } + return libs; +} + +fn mo_ordinal(libs: i64, lib: i64) -> i64 { + let mut j: i64 = 0; + while j < vlen(libs) { + if text_eq(vget(libs, j), lib) { + return j + 1; + } + j = j + 1; + } + return 1; +} + +// x86_64: each fixup is the disp32 of a `call [rip + disp32]` in the code +// at MO_TEXT_OFF; it gets the distance to the import's __got slot. +fn mo_patch_x64(body: i64, fixups: i64, got_off: i64) -> i64 { + let mut f: i64 = 0; + while f < vlen(fixups) { + let at = vget(fixups, f); + x_patch32(body, at, got_off + 8 * vget(fixups, f + 1) - (MO_TEXT_OFF + at + 4)); + f = f + 2; + } + return 0; +} + +fn mo_get32(b: i64, at: i64) -> i64 { + return vget(b, at) | (vget(b, at + 1) << 8) | (vget(b, at + 2) << 16) | (vget(b, at + 3) << 24); +} + +fn mo_put32(b: i64, at: i64, v: i64) -> i64 { + vset(b, at, v & 255); + vset(b, at + 1, (v >> 8) & 255); + vset(b, at + 2, (v >> 16) & 255); + return vset(b, at + 3, (v >> 24) & 255); +} + +// arm64: each fixup is (word of an `adrp x16; ldr x16, [x16]` pair, +// import id) in the A64 code (ngen_a64.trk ax_import_call); the pair gets +// the page and offset of the import's __got slot. +fn mo_patch_a64(body: i64, fixups: i64, got_off: i64) -> i64 { + let mut f: i64 = 0; + while f < vlen(fixups) { + let at = 4 * vget(fixups, f); + let pc = MO_BASE + MO_TEXT_OFF + at; + let slot = MO_BASE + got_off + 8 * vget(fixups, f + 1); + let pages = (slot >> 12) - (pc >> 12); + let adrp = mo_get32(body, at); + mo_put32(body, at, (adrp & 2667577375) + (pages & 3) * 536870912 + ((pages >> 2) & 524287) * 32); + let ldr = mo_get32(body, at + 4); + mo_put32(body, at + 4, (ldr & 4290773983) + ((slot & 4095) / 8) * 1024); + f = f + 2; + } + return 0; +} + +// The whole signed Mach-O image of code+data `body` (the first `code` +// bytes code, a multiple of MO_PAGE) calling `imports` from the sites +// `fixups`, for CPU type `cpu`; `ident` names it in the signature. +fn macho_image(body: i64, code: i64, imports: i64, fixups: i64, ident: i64, cpu: i64) -> i64 { + let n = vlen(imports) / 2; + let libs = mo_libs(imports); + let mut dsize = mo_up(vlen(body) - code, 8); + if dsize < 8 { + dsize = 8; + } + let data_off = MO_TEXT_OFF + code; + let got_off = data_off + dsize; + let data_fsize = mo_up(dsize + 8 * n, MO_PAGE); + let le_off = data_off + data_fsize; + if cpu == MO_CPU_X86_64 { + mo_patch_x64(body, fixups, got_off); + } else { + mo_patch_a64(body, fixups, got_off); + } + // __LINKEDIT: bind opcodes + let le = vnew(); + let mut i: i64 = 0; + while i < n { + let ord = mo_ordinal(libs, vget(imports, 2 * i)); + if ord < 16 { + x_byte(le, 16 + ord); // BIND_OPCODE_SET_DYLIB_ORDINAL_IMM + } else { + x_byte(le, 32); // ..._ULEB + mo_uleb(le, ord); + } + x_byte(le, 64); // BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM + mo_cstr(le, mo_symbol(vget(imports, 2 * i + 1), cpu)); + x_byte(le, 81); // BIND_OPCODE_SET_TYPE_IMM pointer + x_byte(le, 114); // BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, segment 2 + mo_uleb(le, dsize + 8 * i); + x_byte(le, 144); // BIND_OPCODE_DO_BIND + i = i + 1; + } + x_byte(le, 0); // BIND_OPCODE_DONE + mo_pad(le, mo_up(vlen(le), 8)); + let bind_size = vlen(le); + // export trie: __mh_execute_header at offset 0 + let exp_at = vlen(le); + x_byte(le, 0); + x_byte(le, 1); + mo_cstr(le, "__mh_execute_header"); + x_byte(le, 23); + x_byte(le, 2); + x_byte(le, 0); + x_byte(le, 0); + x_byte(le, 0); + mo_pad(le, mo_up(vlen(le), 8)); + let exp_size = vlen(le) - exp_at; + // string table contents (offsets first: the symbols point into it) + let strs = vnew(); + x_byte(strs, 32); + x_byte(strs, 0); + let mh_name = vlen(strs); + mo_cstr(strs, "__mh_execute_header"); + let names = vnew(); + let mut s: i64 = 0; + while s < n { + vpush(names, vlen(strs)); + mo_cstr(strs, mo_symbol(vget(imports, 2 * s + 1), cpu)); + s = s + 1; + } + mo_pad(strs, mo_up(vlen(strs), 8)); + // symbol table: __mh_execute_header, then one undefined symbol per import + let sym_at = vlen(le); + x_u32(le, mh_name); + x_byte(le, 15); // N_SECT | N_EXT + x_byte(le, 1); + mo_u16(le, 16); // REFERENCED_DYNAMICALLY + x_u64(le, MO_BASE); + let mut y: i64 = 0; + while y < n { + x_u32(le, vget(names, y)); + x_byte(le, 1); // N_UNDF | N_EXT + x_byte(le, 0); + mo_u16(le, mo_ordinal(libs, vget(imports, 2 * y)) << 8); + x_u64(le, 0); + y = y + 1; + } + // indirect symbol table: __got slot i -> symbol 1 + i + let ind_at = vlen(le); + let mut z: i64 = 0; + while z < n { + x_u32(le, 1 + z); + z = z + 1; + } + mo_pad(le, mo_up(vlen(le), 8)); + let str_at = vlen(le); + mo_append(le, strs); + mo_pad(le, mo_up(vlen(le), 16)); + // code signature sizes + let sig_off = le_off + vlen(le); + let nslots = (sig_off + 4095) / 4096; + let id_bytes = text_len(ident) + 1; + let cd_len = 88 + id_bytes + 32 * nslots; + let sb_len = 20 + cd_len; + let sig_size = mo_up(sb_len, 16); + let le_fsize = vlen(le) + sig_size; + // UUID: the first 16 bytes of the SHA-256 of the code and data + let k = sha_k(); + let uuid = sha256_into(vnew(), k, body, 0, vlen(body)); + vset(uuid, 6, (vget(uuid, 6) & 15) | 48); // version 3 shape, as ld64 marks its UUIDs + vset(uuid, 8, (vget(uuid, 8) & 63) | 128); + // load commands + let lc = vnew(); + let mut ncmds: i64 = 0; + mo_segment(lc, "__PAGEZERO", 0, MO_BASE, 0, 0, 0, 0); + ncmds = ncmds + 1; + mo_segment(lc, "__TEXT", MO_BASE, data_off, 0, data_off, 5, 1); + mo_section(lc, "__text", "__TEXT", MO_BASE + MO_TEXT_OFF, code, MO_TEXT_OFF, 4, 2147484672, 0); + ncmds = ncmds + 1; + mo_segment(lc, "__DATA", MO_BASE + data_off, data_fsize, data_off, data_fsize, 3, 2); + mo_section(lc, "__data", "__DATA", MO_BASE + data_off, dsize, data_off, 3, 0, 0); + mo_section(lc, "__got", "__DATA", MO_BASE + got_off, 8 * n, got_off, 3, 6, 0); + ncmds = ncmds + 1; + mo_segment(lc, "__LINKEDIT", MO_BASE + le_off, mo_up(le_fsize, MO_PAGE), le_off, le_fsize, 1, 0); + ncmds = ncmds + 1; + x_u32(lc, 2147483682); // LC_DYLD_INFO_ONLY + x_u32(lc, 48); + x_u32(lc, 0); // no rebases: the code is position independent + x_u32(lc, 0); + x_u32(lc, le_off); + x_u32(lc, bind_size); + x_u32(lc, 0); + x_u32(lc, 0); + x_u32(lc, 0); + x_u32(lc, 0); + x_u32(lc, le_off + exp_at); + x_u32(lc, exp_size); + ncmds = ncmds + 1; + x_u32(lc, 2); // LC_SYMTAB + x_u32(lc, 24); + x_u32(lc, le_off + sym_at); + x_u32(lc, 1 + n); + x_u32(lc, le_off + str_at); + x_u32(lc, vlen(strs)); + ncmds = ncmds + 1; + x_u32(lc, 11); // LC_DYSYMTAB + x_u32(lc, 80); + x_u32(lc, 0); + x_u32(lc, 0); // locals + x_u32(lc, 0); + x_u32(lc, 1); // defined externals + x_u32(lc, 1); + x_u32(lc, n); // undefined + let mut q: i64 = 0; + while q < 6 { + x_u32(lc, 0); + q = q + 1; + } + x_u32(lc, le_off + ind_at); + x_u32(lc, n); + let mut q2: i64 = 0; + while q2 < 4 { + x_u32(lc, 0); + q2 = q2 + 1; + } + ncmds = ncmds + 1; + let dl_at = vlen(lc); + x_u32(lc, 14); // LC_LOAD_DYLINKER + x_u32(lc, 32); + x_u32(lc, 12); + mo_cstr(lc, "/usr/lib/dyld"); + mo_pad(lc, dl_at + 32); + ncmds = ncmds + 1; + x_u32(lc, 27); // LC_UUID + x_u32(lc, 24); + vtrunc(uuid, 16); + mo_append(lc, uuid); + ncmds = ncmds + 1; + x_u32(lc, 50); // LC_BUILD_VERSION + x_u32(lc, 24); + x_u32(lc, 1); // PLATFORM_MACOS + x_u32(lc, 720896); // minos 11.0 + x_u32(lc, 720896); // sdk 11.0 + x_u32(lc, 0); + ncmds = ncmds + 1; + x_u32(lc, 2147483688); // LC_MAIN + x_u32(lc, 24); + x_u64(lc, MO_TEXT_OFF); + x_u64(lc, MO_STACK); + ncmds = ncmds + 1; + let mut l: i64 = 0; + while l < vlen(libs) { + let path = mo_dylib_path(vget(libs, l)); + let at = vlen(lc); + let size = mo_up(24 + text_len(path) + 1, 8); + x_u32(lc, 12); // LC_LOAD_DYLIB + x_u32(lc, size); + x_u32(lc, 24); + x_u32(lc, 2); // timestamp + x_u32(lc, 65536); // current version 1.0.0 + x_u32(lc, 65536); // compatibility version 1.0.0 + mo_cstr(lc, path); + mo_pad(lc, at + size); + ncmds = ncmds + 1; + l = l + 1; + } + x_u32(lc, 29); // LC_CODE_SIGNATURE + x_u32(lc, 16); + x_u32(lc, sig_off); + x_u32(lc, sig_size); + ncmds = ncmds + 1; + // the file + let img = vnew_cap(sig_off + sig_size); + x_u32(img, 4277009103); // MH_MAGIC_64 + x_u32(img, cpu); + if cpu == MO_CPU_X86_64 { + x_u32(img, 3); // CPU_SUBTYPE_X86_64_ALL + } else { + x_u32(img, 0); // CPU_SUBTYPE_ARM64_ALL + } + x_u32(img, 2); // MH_EXECUTE + x_u32(img, ncmds); + x_u32(img, vlen(lc)); + x_u32(img, 2097285); // MH_NOUNDEFS | MH_DYLDLINK | MH_TWOLEVEL | MH_PIE + x_u32(img, 0); + mo_append(img, lc); + mo_pad(img, MO_TEXT_OFF); + let mut c: i64 = 0; + while c < vlen(body) { + vpush(img, vget(body, c)); + c = c + 1; + } + mo_pad(img, le_off); + mo_append(img, le); + // the signature: SuperBlob { CodeDirectory } + mo_be32(img, 4208856256); // CSMAGIC_EMBEDDED_SIGNATURE 0xfade0cc0 + mo_be32(img, sb_len); + mo_be32(img, 1); + mo_be32(img, 0); // CSSLOT_CODEDIRECTORY + mo_be32(img, 20); + mo_be32(img, 4208856066); // CSMAGIC_CODEDIRECTORY 0xfade0c02 + mo_be32(img, cd_len); + mo_be32(img, 132096); // version 0x20400 + mo_be32(img, 131074); // CS_ADHOC | CS_LINKER_SIGNED + mo_be32(img, 88 + id_bytes); // hashOffset + mo_be32(img, 88); // identOffset + mo_be32(img, 0); // nSpecialSlots + mo_be32(img, nslots); + mo_be32(img, sig_off); // codeLimit + x_byte(img, 32); // hashSize + x_byte(img, 2); // CS_HASHTYPE_SHA256 + x_byte(img, 0); // platform + x_byte(img, 12); // log2 page size + mo_be32(img, 0); // spare2 + mo_be32(img, 0); // scatterOffset + mo_be32(img, 0); // teamOffset + mo_be32(img, 0); // spare3 + mo_be64(img, 0); // codeLimit64 + mo_be64(img, 0); // execSegBase + mo_be64(img, data_off); // execSegLimit + mo_be64(img, 1); // CS_EXECSEG_MAIN_BINARY + mo_cstr(img, ident); + let mut p: i64 = 0; + while p < nslots { + let mut end = 4096 * (p + 1); + if end > sig_off { + end = sig_off; + } + sha256_into(img, k, img, 4096 * p, end); + p = p + 1; + } + mo_pad(img, sig_off + sig_size); + return img; +} + +// Write the Mach-O image to `path` (mode 0755). Returns 0 on success. +fn macho_write_file(path: i64, body: i64, code: i64, imports: i64, fixups: i64, ident: i64, cpu: i64) -> i64 { + let img = macho_image(body, code, imports, fixups, ident, cpu); + let n = vlen(img); + let buf: i64 = alloc(n + 8); + let mut i: i64 = 0; + while i < n { + memset(buf + i, vget(img, i), 1); + i = i + 1; + } + let fd: i64 = open64(path, 577, 493); + if fd < 0 { + return 1; + } + fchmod(fd, 493); + let mut done: i64 = 0; + while done < n { + let w: i64 = write(fd, buf + done, n - done); + if w <= 0 { + close(fd); + return 1; + } + done = done + w; + } + close(fd); + return 0; +} diff --git a/compiler/src/main.trk b/compiler/src/main.trk index 6577d7a..4141a3b 100644 --- a/compiler/src/main.trk +++ b/compiler/src/main.trk @@ -26,6 +26,7 @@ import "life"; import "ngen"; import "ngen_a64"; import "pe"; +import "macho"; import "runtime_trk"; import "lsp"; @@ -34,7 +35,7 @@ fn trackc_version() -> i64 { return "1.0.0"; } fn usage() -> i64 { err("trackc 1.0.0 — the self-hosted Track compiler\n\n"); err("USAGE:\n"); - err(" trackc build [-o ] Compile to a native executable (ELF, or PE for windows)\n"); + err(" trackc build [-o ] Compile to a native executable (ELF, PE for windows, Mach-O for macos)\n"); err(" -g, --symbols ...with a symbol table (nm, perf, gdb)\n"); err(" trackc run [args...] Compile and run\n"); err(" trackc check Parse and ownership-check only\n"); @@ -46,7 +47,7 @@ fn usage() -> i64 { err("\nOPTIONS:\n"); err(" --deny-warnings exit 1 when any warning is reported\n"); err(" --target - build/run/check for x86_64|aarch64 - linux|macos|windows\n"); - err(" (also TRACKC_TARGET; default: the host; built today: x86_64-linux, x86_64-windows)\n"); + err(" (also TRACKC_TARGET; default: the host; built today: x86_64-linux/macos/windows, aarch64-linux/macos)\n"); return 0; } @@ -126,7 +127,7 @@ const TG_LINUX = 0; const TG_WINDOWS = 1; const TG_MACOS = 2; -// The host's target: Windows when trackc itself runs there. +// The host's target: Windows or macOS when trackc itself runs there. fn host_target() -> i64 { if text_eq(env_get("OS"), "Windows_NT") { return "x86_64-windows"; @@ -135,6 +136,11 @@ fn host_target() -> i64 { if text_ends(me, ".exe") || text_ends(me, ".EXE") { return "x86_64-windows"; } + // macOS (an arm64 Mac runs x86_64 output under Rosetta 2; pass + // --target aarch64-macos for native code) + if path_exists("/System/Library/CoreServices/SystemVersion.plist") { + return "x86_64-macos"; + } return "x86_64-linux"; } @@ -218,14 +224,14 @@ fn check_target_buildable() -> i64 { check_target_known(); let arch = target_arch_name(); let os = target_os_name(); - if text_eq(arch, "x86_64") && (text_eq(os, "linux") || text_eq(os, "windows")) { + if text_eq(arch, "x86_64") && (text_eq(os, "linux") || text_eq(os, "windows") || text_eq(os, "macos")) { return 0; } - if text_eq(arch, "aarch64") && text_eq(os, "linux") { + if text_eq(arch, "aarch64") && (text_eq(os, "linux") || text_eq(os, "macos")) { return 0; } err(text_cat3("trackc: target '", target_text(), "' is not supported yet\n")); - err(" supported: x86_64-linux, x86_64-windows, aarch64-linux\n"); + err(" supported: x86_64-linux, x86_64-windows, x86_64-macos, aarch64-linux, aarch64-macos\n"); quit(2); return 0; } @@ -264,6 +270,15 @@ fn shell_quote(s: i64) -> i64 { return sb_text(b); } +// The last path component of `path`. +fn exe_name(path: i64) -> i64 { + let slash = last_slash(path); + if slash >= 0 { + return str_substr(path, slash + 1, text_len(path) - slash - 1); + } + return path; +} + fn file_stem(path: i64) -> i64 { let slash = last_slash(path); let mut name = path; @@ -351,6 +366,28 @@ fn build_native(path: i64, exe: i64) -> i64 { } return 0; } + if os == TG_MACOS { + let mut mcode = native_code_len(c); + let mut mfix = native_import_fixups(c); + let mut cpu = MO_CPU_X86_64; + if text_eq(target_arch_name(), "aarch64") { + // lift to A64; import calls become AAPCS64 calls (ngen_a64.trk) + let mlen = vfill(vnew(), 1, 0); + let afix = vnew(); + body = a64_translate_os(body, mcode, mlen, TG_MACOS, mfix, afix); + if body == 0 { + quit(1); + } + mcode = vget(mlen, 0); + mfix = afix; + cpu = MO_CPU_ARM64; + } + if macho_write_file(exe, body, mcode, native_imports(c), mfix, exe_name(exe), cpu) != 0 { + err(text_cat3("trackc: cannot write '", exe, "'\n")); + quit(1); + } + return 0; + } let mut code_len = native_code_len(c); let mut mach = ELF_X86_64; if text_eq(target_arch_name(), "aarch64") { diff --git a/compiler/src/ngen.trk b/compiler/src/ngen.trk index ed39519..8990ef3 100644 --- a/compiler/src/ngen.trk +++ b/compiler/src/ngen.trk @@ -5919,8 +5919,8 @@ fn ng_extern_of(c: i64, name: i64) -> i64 { fn ng_extern_call(c: i64, e: i64, args: i64, count: i64) -> i64 { let b = ncode(c); - if ng(c, NG_TARGET) != 1 { - err(text_cat3("trackc: native: imported function '", name_text(c, na(c, e)), "' needs --target x86_64-windows (this target has no import support yet)\n")); + if ng(c, NG_TARGET) != 1 && ng(c, NG_TARGET) != 2 { + err(text_cat3("trackc: native: imported function '", name_text(c, na(c, e)), "' needs --target x86_64-windows or x86_64-macos (this target has no import support yet)\n")); quit(1); } let mut i: i64 = 0; @@ -5929,7 +5929,11 @@ fn ng_extern_call(c: i64, e: i64, args: i64, count: i64) -> i64 { x_push_rax(b); i = i + 1; } - let id = ffi_import_id(ng(c, NG_IMPORTS), nb(c, e), name_text(c, na(c, e))); + let mut sym = name_text(c, na(c, e)); + if ne(c, e) != -1 { + sym = ne(c, e); + } + let id = ffi_import_id(ng(c, NG_IMPORTS), nb(c, e), sym); let ret = nd(c, e); let mut kind: i64 = 0; if ret >= 0 && is_prim(c, ret, PRIM_I32) { @@ -5939,6 +5943,9 @@ fn ng_extern_call(c: i64, e: i64, args: i64, count: i64) -> i64 { } ng_set(c, NG_CLOB, 1); ng_set(c, NG_VOLX, 1); + if ng(c, NG_TARGET) == 2 { + return ffi_sysv_call(b, ng(c, NG_IMPFIX), id, count, kind); + } return ffi_win64_call(b, ng(c, NG_IMPFIX), id, count, kind); } @@ -5959,6 +5966,19 @@ fn ng_entry_win(c: i64) -> i64 { return x_byte(b, 204); // int3: sys_exit does not return } +// macOS entry (LC_MAIN): dyld calls it as main(argc, argv, envp, apple) +// with rsp 8 mod 16. os_start(argc, argv) (the OS layer) calls rt_start, +// which ends in sys_exit, whose exit(3) does not return. +fn ng_entry_mac(c: i64) -> i64 { + let b = ncode(c); + x_bytes3(b, 72, 131, 236); + x_byte(b, 8); // sub rsp, 8 + x_byte(b, 87); // push rdi (argc) + x_byte(b, 86); // push rsi (argv) + ng_call_rt(c, "os_start", 2); + return x_byte(b, 204); // int3 +} + fn ng_is_declaration(c: i64, n: i64) -> bool { let k = nk(c, n); return k == K_FN || k == K_MACRODEF; @@ -6039,6 +6059,8 @@ fn generate_native_for(c: i64, target: i64) -> i64 { ng_set(c, NG_EXTERNS, ng_extern_table(c)); if target == 1 { ng_entry_win(c); + } else if target == 2 { + ng_entry_mac(c); } else { ng_entry(c); } @@ -6114,10 +6136,13 @@ fn generate_native_for(c: i64, target: i64) -> i64 { } return 0; } - // data after the code, 8-aligned (page-aligned for a PE .data section) + // data after the code, 8-aligned (page-aligned for a PE .data section + // or a Mach-O __DATA segment) let mut align: i64 = 8; if target == 1 { align = 4096; + } else if target == 2 { + align = 16384; // __DATA starts on a 16 KiB page (macho.trk) } while vlen(b) % align != 0 { x_byte(b, 204); diff --git a/compiler/src/ngen_a64.trk b/compiler/src/ngen_a64.trk index fa71a07..f3c2d80 100644 --- a/compiler/src/ngen_a64.trk +++ b/compiler/src/ngen_a64.trk @@ -28,6 +28,17 @@ // Interface: a64_translate(body, code_len, out) -> A64 body (code + the // unchanged data) or 0 after printing an error; vget(out, 0) is the A64 // code length. The entry point stays at offset 0. +// +// Import calls (ffi.trk ffi_sysv_call, `call [rip + slot]`) translate to +// an AAPCS64 call (ax_import_call): the System V argument registers move +// to x0..x5, the first two System V stack words to x6, x7, the real SP +// drops below the emulated stack, and adrp + ldr + blr reach the slot. +// a64_translate_os(body, code_len, out, os, x86 fixups, A64 fixups) takes +// the x86 fixups and returns the A64 ones, (adrp word, import id), for +// the image writer (macho.trk); macOS also moves the stub to a trap (the +// macOS layer makes no system calls: ngen lowers syscall6 to os_syscall), +// passes LC_MAIN's x0/x1 in as rdi/rsi, places the code at the Mach-O +// __text address and pads it to 16 KiB so __DATA starts on a page. import "base"; import "x64"; @@ -63,7 +74,10 @@ const AT_LIVE = 7; // flags of the current instruction are read later const AT_AR = 8; // mem_addr result: base register const AT_AO = 9; // mem_addr result: offset const AT_POS = 10; // x86 offset of the current instruction -const AT_SLOTS = 11; +const AT_OS = 11; // target OS (NG_TARGET): 0 linux, 2 macos +const AT_IMPIN = 12; // x86 import call fixups (code position, import id), ffi.trk +const AT_IMPOUT = 13; // A64 import call fixups (word of the adrp, import id) +const AT_SLOTS = 14; const AFK_SUB = 0; const AFK_ADD = 1; @@ -715,10 +729,59 @@ fn ax_pmovmskb(t: i64, rd: i64, vn: i64) -> i64 { } // Translate the decoded instruction d. +// x86 `call [rip + slot]` of an import (ffi_sysv_call) as an AAPCS64 +// call: rcx -> x3 first (x1 is rcx), rdi -> x0, rsi -> x1, rdx stays in +// x2, r8 -> x4, r9 -> x5, System V stack words 0 and 1 -> x6, x7 (calls +// of up to eight word arguments; Apple's variadic arguments, which go on +// the stack, are not supported). The real SP goes 16-aligned below the +// emulated stack, where x9 and x10 (rbx-class r14/r15, caller-saved in +// AAPCS64) are kept across the call. The result is in x0 = rax. +fn ax_import_call(t: i64, d: i64) -> bool { + let w = ax_tw(t); + let fx = ax_tg(t, AT_IMPIN); + let at = ax_tg(t, AT_POS) + 2; + let mut id: i64 = -1; + let mut i: i64 = 0; + while fx != 0 && i < vlen(fx) { + if vget(fx, i) == at { + id = vget(fx, i + 1); + } + i = i + 2; + } + if id < 0 { + return a64_fail(t, "indirect call that is not an import call"); + } + a_mov(w, 1, 3, 1); + a_mov(w, 1, 0, 21); + a_mov(w, 1, 1, 20); + a_mov(w, 1, 4, 22); + a_mov(w, 1, 5, 23); + a_ldr(w, 6, 28, 0); + a_ldr(w, 7, 28, 8); + a_subi(w, 1, AX16, 28, 16); + a_lsr_i(w, 1, AX16, AX16, 4); + a_lsl_i(w, 1, AX16, AX16, 4); + a_mov_sp(w, A_SP, AX16); + a_mem(w, 3, 0, 9, A_SP, 0); + a_mem(w, 3, 0, 10, A_SP, 8); + let adrp = a_adrp(w, AX16, 0); + a_ldr(w, AX16, AX16, 0); + a_blr(w, AX16); + a_ldr(w, 9, A_SP, 0); + a_ldr(w, 10, A_SP, 8); + let out = ax_tg(t, AT_IMPOUT); + vpush(out, adrp); + vpush(out, id); + return true; +} + fn a64_insn(t: i64, d: i64) -> bool { let w = ax_tw(t); let op = ax_dg(d, AD_OP); let reg = ax_dg(d, AD_REG); + if op == 255 && reg == 2 && ax_dg(d, AD_BASE) == -2 { + return ax_import_call(t, d); + } let sub = reg & 7; let md = ax_dg(d, AD_MOD); let size = ax_op_size(d); @@ -1114,7 +1177,19 @@ fn a64_sys_stub(w: i64) -> i64 { // Translate the x86-64 body (code_len code bytes, then data) to A64. fn a64_translate(body: i64, n: i64, out: i64) -> i64 { + return a64_translate_os(body, n, out, 0, 0, vnew()); +} + +// The macOS image's __text address (macho.trk MO_BASE + MO_TEXT_OFF). +const AX_MACHO_TEXT = 4294983680; + +// a64_translate for target OS `os`; `impin` holds the x86 import call +// fixups (0: none), `impout` receives the A64 ones. +fn a64_translate_os(body: i64, n: i64, out: i64, os: i64, impin: i64, impout: i64) -> i64 { let t = vfill(vnew_cap(AT_SLOTS), AT_SLOTS, 0); + vset(t, AT_OS, os); + vset(t, AT_IMPIN, impin); + vset(t, AT_IMPOUT, impout); let w = vnew_cap(n); vset(t, AT_W, w); vset(t, AT_FX, vnew()); @@ -1124,6 +1199,10 @@ fn a64_translate(body: i64, n: i64, out: i64) -> i64 { vset(t, AT_D, d); vset(t, AT_D2, vfill(vnew_cap(AD_SLOTS), AD_SLOTS, 0)); let map = vfill(vnew_cap(n + 1), n + 1, -1); + if os == 2 { + a_mov(w, 1, 21, 0); // LC_MAIN's argc, argv: the x86 entry reads rdi, rsi + a_mov(w, 1, 20, 1); + } a_mov_sp(w, 28, A_SP); // the emulated rsp starts at the entry stack let mut pos: i64 = 0; while pos < n { @@ -1145,12 +1224,19 @@ fn a64_translate(body: i64, n: i64, out: i64) -> i64 { } vset(map, n, vlen(w)); let stub = vlen(w); - a64_sys_stub(w); - while vlen(w) % 4 != 0 { + let mut origin = ELF_BASE + ELF_HEADERS; + let mut align: i64 = 4; + if os == 2 { + a_brk(w, 1); // no system calls on macOS + origin = AX_MACHO_TEXT; + align = 4096; // words: 16 KiB, the __DATA page + } else { + a64_sys_stub(w); + } + while vlen(w) % align != 0 { a_nop(w); } let code_bytes = vlen(w) * 4; - let origin = ELF_BASE + ELF_HEADERS; let fx = ax_tg(t, AT_FX); let mut i: i64 = 0; while i < vlen(fx) { diff --git a/compiler/src/parser.trk b/compiler/src/parser.trk index 2be5ec1..cbdaea5 100644 --- a/compiler/src/parser.trk +++ b/compiler/src/parser.trk @@ -721,7 +721,13 @@ fn parse_extern(c: i64) -> i64 { if p_accept(c, TK_ARROW) { ret = parse_type(c); } - return node_new(c, K_EXTERN, name, lib, params, ret, -1, pos); + // `as "symbol"`: the library's name for it, when Track's differs + let mut sym: i64 = -1; + if p_accept(c, TK_AS) { + sym = p_value(c); + p_expect(c, TK_STR); + } + return node_new(c, K_EXTERN, name, lib, params, ret, sym, pos); } fn parse_macro_def(c: i64) -> i64 { diff --git a/compiler/src/runtime_trk.trk b/compiler/src/runtime_trk.trk index 43b80bc..e5f6902 100644 --- a/compiler/src/runtime_trk.trk +++ b/compiler/src/runtime_trk.trk @@ -3,7 +3,7 @@ import "base"; -fn rt_module_count() -> i64 { return 7; } +fn rt_module_count() -> i64 { return 8; } fn rt_module_name(i: i64) -> i64 { if i == 0 { return "rt/mem.trk"; } @@ -12,7 +12,8 @@ fn rt_module_name(i: i64) -> i64 { if i == 3 { return "rt/vec.trk"; } if i == 4 { return "rt/os/linux.trk"; } if i == 5 { return "rt/os/windows.trk"; } - if i == 6 { return "rt/libc.trk"; } + if i == 6 { return "rt/os/macos.trk"; } + if i == 7 { return "rt/libc.trk"; } return ""; } @@ -3038,6 +3039,627 @@ fn rt_module_source_5(b: i64) -> i64 { } fn rt_module_source_6(b: i64) -> i64 { + sb_line(b, "// rt/os/macos.trk — Track runtime OS layer for macOS, through libSystem."); + sb_line(b, "//"); + sb_line(b, "// Implements the OS interface (docs/native.md, \"The OS layer\") with"); + sb_line(b, "// libSystem functions called through the import table (`extern`; dyld"); + sb_line(b, "// binds them, macho.trk):"); + sb_line(b, "//"); + sb_line(b, "// os_start process entry: LC_MAIN's main(argc, argv, envp, apple)"); + sb_line(b, "// hands argc and argv over; then rt_start"); + sb_line(b, "// os_syscall the kernel calls the portable modules (mem, io, libc)"); + sb_line(b, "// make through `syscall6`, by Linux number, mapped to"); + sb_line(b, "// libSystem: open flags, mmap flags, the stat layout,"); + sb_line(b, "// clock ids and socket options translated, failures as"); + sb_line(b, "// -errno (errno from __error())"); + sb_line(b, "// os_args_count, os_arg, env_get, env_exists, sys_exec, process_spawn,"); + sb_line(b, "// clock_ms, file_*, dir_exists, track_file_*, net_socket_*"); + sb_line(b, "//"); + sb_line(b, "// No variadic call: arm64 macOS passes variadic arguments on the stack,"); + sb_line(b, "// so open(2) is called without a mode and a file is created with"); + sb_line(b, "// creat(2) (mac_open)."); + sb_line(b, "//"); + sb_line(b, "// libSystem returns -1 and sets errno; os_syscall returns -errno like the"); + sb_line(b, "// Linux kernel, with macOS errno values (ENOENT, EINTR, EBADF agree)."); + sb_line(b, ""); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_read(fd: i64, buf: i64, n: i64) -> i64 as \"read\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_write(fd: i64, buf: i64, n: i64) -> i64 as \"write\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_open(path: i64, flags: i64) -> i32 as \"open\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_creat(path: i64, mode: i64) -> i32 as \"creat\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_close(fd: i64) -> i32 as \"close\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_stat(path: i64, st: i64) -> i32 as \"stat\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_lseek(fd: i64, off: i64, how: i64) -> i64 as \"lseek\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_mmap(addr: i64, len: i64, prot: i64, flags: i64, fd: i64, off: i64) -> i64 as \"mmap\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_munmap(addr: i64, len: i64) -> i32 as \"munmap\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_pipe(fds: i64) -> i32 as \"pipe\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_access(path: i64, mode: i64) -> i32 as \"access\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_getpid() -> i32 as \"getpid\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_kill(pid: i64, sig: i64) -> i32 as \"kill\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_unlink(path: i64) -> i32 as \"unlink\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_clock_gettime(id: i64, ts: i64) -> i32 as \"clock_gettime\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_exit(code: i64) -> i64 as \"exit\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_fchmod(fd: i64, mode: i64) -> i32 as \"fchmod\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_errno_at() -> i64 as \"__error\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_environ_at() -> i64 as \"_NSGetEnviron\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_system(cmd: i64) -> i32 as \"system\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_socket(domain: i64, kind: i64, proto: i64) -> i32 as \"socket\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_setsockopt(fd: i64, level: i64, opt: i64, val: i64, len: i64) -> i32 as \"setsockopt\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_bind(fd: i64, addr: i64, len: i64) -> i32 as \"bind\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_listen(fd: i64, backlog: i64) -> i32 as \"listen\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_accept(fd: i64, addr: i64, len: i64) -> i32 as \"accept\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_connect(fd: i64, addr: i64, len: i64) -> i32 as \"connect\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_send(fd: i64, buf: i64, n: i64, flags: i64) -> i64 as \"send\";"); + sb_line(b, "extern \"libSystem.B.dylib\" fn c_recv(fd: i64, buf: i64, n: i64, flags: i64) -> i64 as \"recv\";"); + sb_line(b, ""); + sb_line(b, "const MS_STAT = 6400; // macOS struct stat (144 bytes) in the state page"); + sb_line(b, ""); + sb_line(b, "// ---------------------------------------------------------------- process"); + sb_line(b, ""); + sb_line(b, "// The process entry (trackc's macOS entry calls it with LC_MAIN's argc"); + sb_line(b, "// and argv; envp follows argv as on Linux, and rt_getenv reads environ)."); + sb_line(b, "fn os_start(argc: i64, argv: i64) -> i64 {"); + sb_line(b, " return rt_start(argc, argv);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn os_args_count() -> i64 { return rs(RS_ARGC); }"); + sb_line(b, ""); + sb_line(b, "fn os_arg(idx: i64) -> i64 {"); + sb_line(b, " if idx >= 0 && idx < rs(RS_ARGC) {"); + sb_line(b, " return rt_dup(load64(rs(RS_ARGV) + 8 * idx));"); + sb_line(b, " }"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Value of environment variable `key` (\"NAME=value\"), or 0 when unset."); + sb_line(b, "fn rt_getenv(key: i64) -> i64 {"); + sb_line(b, " let mut e = load64(c_environ_at());"); + sb_line(b, " while load64(e) != 0 {"); + sb_line(b, " let entry = load64(e);"); + sb_line(b, " let mut i: i64 = 0;"); + sb_line(b, " while load8(key + i) != 0 && load8(key + i) == load8(entry + i) {"); + sb_line(b, " i = i + 1;"); + sb_line(b, " }"); + sb_line(b, " if load8(key + i) == 0 && load8(entry + i) == 61 {"); + sb_line(b, " return entry + i + 1;"); + sb_line(b, " }"); + sb_line(b, " e = e + 8;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn env_get(key: i64) -> i64 {"); + sb_line(b, " if key == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " let v = rt_getenv(key);"); + sb_line(b, " if v == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " return rt_dup(v);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn env_exists(key: i64) -> i64 {"); + sb_line(b, " if key != 0 && rt_getenv(key) != 0 {"); + sb_line(b, " return 1;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// system(3): /bin/sh -c cmd; exit status, or 128 + signal."); + sb_line(b, "fn sys_exec(cmd: i64) -> i64 {"); + sb_line(b, " if cmd == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " rt_flush();"); + sb_line(b, " let status = c_system(cmd);"); + sb_line(b, " if status < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " if (status & 127) == 0 {"); + sb_line(b, " return (status >> 8) & 255;"); + sb_line(b, " }"); + sb_line(b, " return 128 + (status & 127);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn process_spawn(cmd: i64) -> i64 { return sys_exec(cmd); }"); + sb_line(b, ""); + sb_line(b, "fn clock_ms() -> i64 {"); + sb_line(b, " let ts = RT_BASE + RS_TIME;"); + sb_line(b, " c_clock_gettime(6, ts); // CLOCK_MONOTONIC"); + sb_line(b, " return load64(ts) * 1000 + load64(ts + 8) / 1000000;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ---------------------------------------------------------- kernel calls"); + sb_line(b, ""); + sb_line(b, "// A libSystem result: -errno when it failed (-1)."); + sb_line(b, "fn mac_ret(r: i64) -> i64 {"); + sb_line(b, " if r == -1 {"); + sb_line(b, " return 0 - (load64(c_errno_at()) & 4294967295);"); + sb_line(b, " }"); + sb_line(b, " return r;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Linux open(2) flags -> macOS."); + sb_line(b, "fn mac_oflags(f: i64) -> i64 {"); + sb_line(b, " let mut m = f & 3;"); + sb_line(b, " if (f & 64) != 0 { m = m | 512; } // O_CREAT"); + sb_line(b, " if (f & 128) != 0 { m = m | 2048; } // O_EXCL"); + sb_line(b, " if (f & 512) != 0 { m = m | 1024; } // O_TRUNC"); + sb_line(b, " if (f & 1024) != 0 { m = m | 8; } // O_APPEND"); + sb_line(b, " if (f & 2048) != 0 { m = m | 4; } // O_NONBLOCK"); + sb_line(b, " if (f & 65536) != 0 { m = m | 1048576; } // O_DIRECTORY"); + sb_line(b, " if (f & 524288) != 0 { m = m | 16777216; } // O_CLOEXEC"); + sb_line(b, " return m;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// open(2) with Linux flags and mode, without a variadic call: creating"); + sb_line(b, "// goes through creat(2) (O_WRONLY | O_CREAT | O_TRUNC), then the file is"); + sb_line(b, "// opened again with the asked flags minus O_CREAT and O_EXCL (unless"); + sb_line(b, "// creat's write-only descriptor already fits)."); + sb_line(b, "fn mac_open(path: i64, f: i64, mode: i64) -> i64 {"); + sb_line(b, " let flags = mac_oflags(f) & (0 - 2561); // without O_CREAT | O_EXCL"); + sb_line(b, " if (f & 64) == 0 {"); + sb_line(b, " return mac_ret(c_open(path, flags));"); + sb_line(b, " }"); + sb_line(b, " if c_access(path, 0) == 0 {"); + sb_line(b, " if (f & 128) != 0 {"); + sb_line(b, " return -17; // EEXIST"); + sb_line(b, " }"); + sb_line(b, " return mac_ret(c_open(path, flags));"); + sb_line(b, " }"); + sb_line(b, " let fd = mac_ret(c_creat(path, mode));"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return fd;"); + sb_line(b, " }"); + sb_line(b, " if (f & 3) == 1 && (f & 1024) == 0 {"); + sb_line(b, " return fd; // creat's own descriptor fits"); + sb_line(b, " }"); + sb_line(b, " c_close(fd);"); + sb_line(b, " return mac_ret(c_open(path, flags));"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Linux mmap(2) flags -> macOS; MAP_FIXED_NOREPLACE becomes a hint that"); + sb_line(b, "// must be met (os_syscall checks)."); + sb_line(b, "fn mac_mflags(f: i64) -> i64 {"); + sb_line(b, " let mut m = f & 19; // MAP_SHARED | MAP_PRIVATE | MAP_FIXED"); + sb_line(b, " if (f & 32) != 0 { m = m | 4096; } // MAP_ANON"); + sb_line(b, " if (f & 16384) != 0 { m = m | 64; } // MAP_NORESERVE"); + sb_line(b, " return m;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// stat(2) into the Linux struct stat layout the portable code reads:"); + sb_line(b, "// st_mode at 24, st_size at 48 (macOS 64-bit-inode stat: 4 and 96)."); + sb_line(b, "fn mac_stat(path: i64, st: i64) -> i64 {"); + sb_line(b, " let ms = RT_BASE + MS_STAT;"); + sb_line(b, " let r = mac_ret(c_stat(path, ms));"); + sb_line(b, " if r < 0 {"); + sb_line(b, " return r;"); + sb_line(b, " }"); + sb_line(b, " rt_zero(st, 144);"); + sb_line(b, " store64(st + 24, load64(ms + 4) & 65535);"); + sb_line(b, " store64(st + 48, load64(ms + 96));"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// The `syscall6` calls of the portable runtime modules, by Linux number;"); + sb_line(b, "// -38 (ENOSYS) for the rest."); + sb_line(b, "fn os_syscall(nr: i64, a: i64, b: i64, d: i64, e: i64, f: i64) -> i64 {"); + sb_line(b, " if nr == 0 {"); + sb_line(b, " return mac_ret(c_read(a, b, d));"); + sb_line(b, " }"); + sb_line(b, " if nr == 1 {"); + sb_line(b, " return mac_ret(c_write(a, b, d));"); + sb_line(b, " }"); + sb_line(b, " if nr == 2 {"); + sb_line(b, " return mac_open(a, b, d);"); + sb_line(b, " }"); + sb_line(b, " if nr == 3 {"); + sb_line(b, " return mac_ret(c_close(a));"); + sb_line(b, " }"); + sb_line(b, " if nr == 4 {"); + sb_line(b, " return mac_stat(a, b);"); + sb_line(b, " }"); + sb_line(b, " if nr == 8 {"); + sb_line(b, " return mac_ret(c_lseek(a, b, d));"); + sb_line(b, " }"); + sb_line(b, " if nr == 9 {"); + sb_line(b, " let p = mac_ret(c_mmap(a, b, d, mac_mflags(e), f, 0));"); + sb_line(b, " if p >= 0 && (e & 1048576) != 0 && p != a {"); + sb_line(b, " c_munmap(p, b);"); + sb_line(b, " return -17; // EEXIST: the hint was not met"); + sb_line(b, " }"); + sb_line(b, " return p;"); + sb_line(b, " }"); + sb_line(b, " if nr == 11 {"); + sb_line(b, " return mac_ret(c_munmap(a, b));"); + sb_line(b, " }"); + sb_line(b, " if nr == 25 {"); + sb_line(b, " // mremap(old, old_len, new_len, MAYMOVE): a new mapping, copied"); + sb_line(b, " let q = mac_ret(c_mmap(0, d, 3, 4098, -1, 0));"); + sb_line(b, " if q < 0 {"); + sb_line(b, " return q;"); + sb_line(b, " }"); + sb_line(b, " let mut n = b;"); + sb_line(b, " if d < n {"); + sb_line(b, " n = d;"); + sb_line(b, " }"); + sb_line(b, " rt_copy(q, a, n);"); + sb_line(b, " c_munmap(a, b);"); + sb_line(b, " return q;"); + sb_line(b, " }"); + sb_line(b, " if nr == 28 {"); + sb_line(b, " return 0; // madvise: hints only"); + sb_line(b, " }"); + sb_line(b, " if nr == 91 {"); + sb_line(b, " return mac_ret(c_fchmod(a, b));"); + sb_line(b, " }"); + sb_line(b, " if nr == 22 {"); + sb_line(b, " return mac_ret(c_pipe(a));"); + sb_line(b, " }"); + sb_line(b, " if nr == 21 {"); + sb_line(b, " return mac_ret(c_access(a, b));"); + sb_line(b, " }"); + sb_line(b, " if nr == 87 {"); + sb_line(b, " return mac_ret(c_unlink(a));"); + sb_line(b, " }"); + sb_line(b, " if nr == 39 {"); + sb_line(b, " return c_getpid();"); + sb_line(b, " }"); + sb_line(b, " if nr == 62 {"); + sb_line(b, " return mac_ret(c_kill(a, b));"); + sb_line(b, " }"); + sb_line(b, " if nr == 228 {"); + sb_line(b, " let mut id = a;"); + sb_line(b, " if id == 1 {"); + sb_line(b, " id = 6; // CLOCK_MONOTONIC"); + sb_line(b, " }"); + sb_line(b, " return mac_ret(c_clock_gettime(id, b));"); + sb_line(b, " }"); + sb_line(b, " if nr == 231 || nr == 60 {"); + sb_line(b, " c_exit(a);"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " return -38;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ------------------------------------------------------------------ files"); + sb_line(b, "//"); + sb_line(b, "// A file handle is a runtime record [fd]; 0 when the open failed."); + sb_line(b, ""); + sb_line(b, "const O_RDONLY = 0;"); + sb_line(b, "const O_WRONLY_CREAT_TRUNC = 577; // O_WRONLY | O_CREAT | O_TRUNC"); + sb_line(b, "const O_WRONLY_CREAT_APPEND = 1089; // O_WRONLY | O_CREAT | O_APPEND"); + sb_line(b, "const O_RDWR = 2;"); + sb_line(b, ""); + sb_line(b, "// open(2) flags for an fopen(3) mode string."); + sb_line(b, "fn rt_open_flags(mode: i64) -> i64 {"); + sb_line(b, " let m = load8(mode);"); + sb_line(b, " let plus = rt_find(mode, \"+\") >= 0;"); + sb_line(b, " if m == 114 {"); + sb_line(b, " if plus {"); + sb_line(b, " return O_RDWR;"); + sb_line(b, " }"); + sb_line(b, " return O_RDONLY;"); + sb_line(b, " }"); + sb_line(b, " if m == 119 {"); + sb_line(b, " if plus {"); + sb_line(b, " return 578; // O_RDWR | O_CREAT | O_TRUNC"); + sb_line(b, " }"); + sb_line(b, " return O_WRONLY_CREAT_TRUNC;"); + sb_line(b, " }"); + sb_line(b, " if m == 97 {"); + sb_line(b, " if plus {"); + sb_line(b, " return 1090; // O_RDWR | O_CREAT | O_APPEND"); + sb_line(b, " }"); + sb_line(b, " return O_WRONLY_CREAT_APPEND;"); + sb_line(b, " }"); + sb_line(b, " return -1;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_open(path: i64, mode: i64) -> i64 {"); + sb_line(b, " if path == 0 || mode == 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let flags = rt_open_flags(mode);"); + sb_line(b, " if flags < 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let fd = sys3(SYS_OPEN, path, flags | 524288, 438); // O_CLOEXEC, 0666"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " let h = rt_malloc(8);"); + sb_line(b, " store64(h, fd);"); + sb_line(b, " return h;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_close(h: i64) -> i64 {"); + sb_line(b, " if h != 0 {"); + sb_line(b, " sys1(SYS_CLOSE, load64(h));"); + sb_line(b, " rt_free(h);"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Read everything from `fd` to end of file; \"\" on error. The size from"); + sb_line(b, "// lseek only sizes the first buffer: files whose size is not known up"); + sb_line(b, "// front (/proc, pipes) read whole too."); + sb_line(b, "fn rt_read_fd(fd: i64) -> i64 {"); + sb_line(b, " let mut cap: i64 = 4096;"); + sb_line(b, " let end = sys3(SYS_LSEEK, fd, 0, 2);"); + sb_line(b, " if end >= 0 {"); + sb_line(b, " if sys3(SYS_LSEEK, fd, 0, 0) < 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " cap = end + 1;"); + sb_line(b, " }"); + sb_line(b, " let mut buf = rt_malloc(cap + 1);"); + sb_line(b, " let mut got: i64 = 0;"); + sb_line(b, " let mut going = true;"); + sb_line(b, " while going {"); + sb_line(b, " if got == cap {"); + sb_line(b, " cap = cap * 2;"); + sb_line(b, " buf = rt_realloc(buf, cap + 1);"); + sb_line(b, " }"); + sb_line(b, " let r = sys3(SYS_READ, fd, buf + got, cap - got);"); + sb_line(b, " if r == -4 {"); + sb_line(b, " // EINTR: retry"); + sb_line(b, " } else if r <= 0 {"); + sb_line(b, " going = false;"); + sb_line(b, " } else {"); + sb_line(b, " got = got + r;"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " store8(buf + got, 0);"); + sb_line(b, " return buf;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_read_all(h: i64) -> i64 {"); + sb_line(b, " if h == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " return rt_read_fd(load64(h));"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_write(h: i64, content: i64) -> i64 {"); + sb_line(b, " if h == 0 || content == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return rt_write_all(load64(h), content, rt_strlen(content));"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_exists(path: i64) -> i64 {"); + sb_line(b, " if path != 0 && sys2(SYS_ACCESS, path, 0) == 0 {"); + sb_line(b, " return 1;"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_remove(path: i64) -> i64 {"); + sb_line(b, " if path != 0 && sys1(SYS_UNLINK, path) == 0 {"); + sb_line(b, " return 0;"); + sb_line(b, " }"); + sb_line(b, " return -1;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_size(path: i64) -> i64 {"); + sb_line(b, " let st = RT_BASE + RS_STAT;"); + sb_line(b, " if path == 0 || sys2(SYS_STAT, path, st) != 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return load64(st + 48);"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn dir_exists(path: i64) -> bool {"); + sb_line(b, " let st = RT_BASE + RS_STAT;"); + sb_line(b, " if path == 0 || sys2(SYS_STAT, path, st) != 0 {"); + sb_line(b, " return false;"); + sb_line(b, " }"); + sb_line(b, " return (load64(st + 24) & 61440) == 16384;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn file_copy(src: i64, dst: i64) -> i64 {"); + sb_line(b, " if src == 0 || dst == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let fin = sys3(SYS_OPEN, src, O_RDONLY | 524288, 0);"); + sb_line(b, " if fin < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let fout = sys3(SYS_OPEN, dst, O_WRONLY_CREAT_TRUNC | 524288, 438);"); + sb_line(b, " if fout < 0 {"); + sb_line(b, " sys1(SYS_CLOSE, fin);"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let buf = rt_malloc(65536);"); + sb_line(b, " let mut going = true;"); + sb_line(b, " while going {"); + sb_line(b, " let n = sys3(SYS_READ, fin, buf, 65536);"); + sb_line(b, " if n == -4 {"); + sb_line(b, " // EINTR: retry"); + sb_line(b, " } else if n <= 0 {"); + sb_line(b, " going = false;"); + sb_line(b, " } else {"); + sb_line(b, " rt_write_all(fout, buf, n);"); + sb_line(b, " }"); + sb_line(b, " }"); + sb_line(b, " rt_free(buf);"); + sb_line(b, " sys1(SYS_CLOSE, fin);"); + sb_line(b, " sys1(SYS_CLOSE, fout);"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// Whole-file helpers: open, transfer, and close in one call."); + sb_line(b, "fn track_file_read(path: i64) -> i64 {"); + sb_line(b, " if path == 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " let fd = sys3(SYS_OPEN, path, O_RDONLY | 524288, 0);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return rt_dup_n(\"\", 0);"); + sb_line(b, " }"); + sb_line(b, " let out = rt_read_fd(fd);"); + sb_line(b, " sys1(SYS_CLOSE, fd);"); + sb_line(b, " return out;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn track_file_write_all(path: i64, content: i64) -> i64 {"); + sb_line(b, " if path == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let fd = sys3(SYS_OPEN, path, O_WRONLY_CREAT_TRUNC | 524288, 438);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let mut status: i64 = -1;"); + sb_line(b, " if content != 0 {"); + sb_line(b, " status = rt_write_all(fd, content, rt_strlen(content));"); + sb_line(b, " }"); + sb_line(b, " if sys1(SYS_CLOSE, fd) != 0 {"); + sb_line(b, " status = -1;"); + sb_line(b, " }"); + sb_line(b, " return status;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// ---------------------------------------------------------------- network"); + sb_line(b, ""); + sb_line(b, "// struct sockaddr_in for AF_INET (BSD: sin_len first), `port`, and the"); + sb_line(b, "// IPv4 address word `addr` (network byte order packed little-endian)."); + sb_line(b, "fn rt_sockaddr(port: i64, addr: i64) -> i64 {"); + sb_line(b, " let sa = RT_BASE + RS_SOCK;"); + sb_line(b, " let p = port & 65535;"); + sb_line(b, " store64(sa, 16 | (2 << 8) | ((p >> 8) << 16) | ((p & 255) << 24) | ((addr & 4294967295) << 32));"); + sb_line(b, " store64(sa + 8, 0);"); + sb_line(b, " return sa;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "// inet_pton for dotted-quad IPv4; -1 when malformed."); + sb_line(b, "fn rt_parse_ipv4(s: i64) -> i64 {"); + sb_line(b, " let mut addr: i64 = 0;"); + sb_line(b, " let mut part: i64 = 0;"); + sb_line(b, " let mut digits: i64 = 0;"); + sb_line(b, " let mut parts: i64 = 0;"); + sb_line(b, " let mut i: i64 = 0;"); + sb_line(b, " while true {"); + sb_line(b, " let ch = load8(s + i);"); + sb_line(b, " if rt_is_digit(ch) {"); + sb_line(b, " part = part * 10 + ch - 48;"); + sb_line(b, " digits = digits + 1;"); + sb_line(b, " if part > 255 || digits > 3 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " } else if ch == 46 || ch == 0 {"); + sb_line(b, " if digits == 0 || parts == 4 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " addr = addr | (part << (8 * parts));"); + sb_line(b, " parts = parts + 1;"); + sb_line(b, " part = 0;"); + sb_line(b, " digits = 0;"); + sb_line(b, " if ch == 0 {"); + sb_line(b, " if parts != 4 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return addr;"); + sb_line(b, " }"); + sb_line(b, " } else {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " i = i + 1;"); + sb_line(b, " }"); + sb_line(b, " return -1;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn net_socket_tcp_listen(port: i64) -> i64 {"); + sb_line(b, " let fd = c_socket(2, 1, 0);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " c_setsockopt(fd, 65535, 4, RT_BASE + RS_ONE, 4); // SOL_SOCKET, SO_REUSEADDR"); + sb_line(b, " let r = mac_ret(c_bind(fd, rt_sockaddr(port, 0), 16));"); + sb_line(b, " if r < 0 {"); + sb_line(b, " let b = track_sb_new();"); + sb_line(b, " if r == -48 {"); + sb_line(b, " track_sb_push(b, \"Track Network Error: Port conflict! Port \");"); + sb_line(b, " track_sb_push_int(b, port);"); + sb_line(b, " track_sb_push(b, \" is already in use by another process.\\n\");"); + sb_line(b, " } else {"); + sb_line(b, " track_sb_push(b, \"Track Network Error: Failed to bind TCP socket on port \");"); + sb_line(b, " track_sb_push_int(b, port);"); + sb_line(b, " track_sb_push(b, \" (errno: \");"); + sb_line(b, " track_sb_push_int(b, 0 - r);"); + sb_line(b, " track_sb_push(b, \").\\n\");"); + sb_line(b, " }"); + sb_line(b, " rt_err_bytes(load64(b), track_sb_len(b));"); + sb_line(b, " c_close(fd);"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " if c_listen(fd, 128) < 0 {"); + sb_line(b, " c_close(fd);"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return fd;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn net_socket_accept(server_fd: i64) -> i64 {"); + sb_line(b, " if server_fd < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let r = c_accept(server_fd, 0, 0);"); + sb_line(b, " if r < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return r;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn net_socket_connect(host: i64, port: i64) -> i64 {"); + sb_line(b, " if host == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let fd = c_socket(2, 1, 0);"); + sb_line(b, " if fd < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let addr = rt_parse_ipv4(host);"); + sb_line(b, " if addr < 0 || c_connect(fd, rt_sockaddr(port, addr), 16) < 0 {"); + sb_line(b, " c_close(fd);"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return fd;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn net_socket_send(fd: i64, data: i64, len: i64) -> i64 {"); + sb_line(b, " if fd < 0 || data == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let r = c_send(fd, data, len, 0);"); + sb_line(b, " if r < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return r;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn net_socket_recv(fd: i64, buf: i64, max_len: i64) -> i64 {"); + sb_line(b, " if fd < 0 || buf == 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " let r = c_recv(fd, buf, max_len, 0);"); + sb_line(b, " if r < 0 {"); + sb_line(b, " return -1;"); + sb_line(b, " }"); + sb_line(b, " return r;"); + sb_line(b, "}"); + sb_line(b, ""); + sb_line(b, "fn net_socket_close(fd: i64) -> i64 {"); + sb_line(b, " if fd >= 0 {"); + sb_line(b, " c_close(fd);"); + sb_line(b, " }"); + sb_line(b, " return 0;"); + sb_line(b, "}"); + return 0; +} + +fn rt_module_source_7(b: i64) -> i64 { sb_line(b, "// libc.trk — the few libc entry points trackc's ELF writer (elf.trk)"); sb_line(b, "// calls by their libc names, so the Rust bootstrap compiler can link them"); sb_line(b, "// from libc. With the Track runtime (--rt=track, --native) these"); @@ -3079,5 +3701,6 @@ fn rt_module_source(i: i64) -> i64 { if i == 4 { rt_module_source_4(b); } if i == 5 { rt_module_source_5(b); } if i == 6 { rt_module_source_6(b); } + if i == 7 { rt_module_source_7(b); } return sb_text(b); } diff --git a/docs/native.md b/docs/native.md index 7c11559..5ab1bbe 100644 --- a/docs/native.md +++ b/docs/native.md @@ -27,7 +27,13 @@ generates code for: |---|---|---| | x86_64-linux | static ELF, Linux syscalls | default; output byte-identical to earlier trackc | | x86_64-windows | PE32+ console .exe, kernel32 imports | builds and runs (tested under wine); trackc.exe self-hosts | -| aarch64-linux, x86_64/aarch64-macos, aarch64-windows | | "not supported yet" | +| aarch64-linux | static ELF, A64 lifted from ngen's x86-64 (ngen_a64.trk) | builds and runs (tested under qemu) | +| x86_64-macos | Mach-O MH_EXECUTE, libSystem imports, ad-hoc signature | builds; structure and signature checked offline, runs in CI on an Intel Mac [CI only] | +| aarch64-macos | the same Mach-O for arm64, A64 lifted as for aarch64-linux | builds; checked offline, runs in CI on Apple silicon [CI only] | +| aarch64-windows | | "not supported yet" | + +On a Mac the default target is x86_64-macos (arm64 Macs run it under +Rosetta 2); pass `--target aarch64-macos` for native code. `run` only runs host-target programs. The target picks the OS layer: trackc loads `rt/os/.trk` with the portable rt modules and passes @@ -76,10 +82,70 @@ writer lays out the table and fills the fixups. For x86_64-windows each call is `call [rip + IAT slot]` with the Win64 ABI: arguments 1-4 in rcx, rdx, r8, r9, the rest on the stack above 32 bytes of shadow space, rsp 16-byte aligned (`ffi_win64_call`); pe.trk writes one import -descriptor per library. A macOS writer (dyld binding to libSystem, SysV -ABI) or aarch64-windows reuses the two tables and adds its own call -sequence next to `ffi_win64_call`. On a target without import support a -call to an `extern` function is an error. +descriptor per library. For x86_64-macos the call is the same +`call [rip + slot]`, the slot a `__got` entry, with the System V ABI: +arguments 1-6 in rdi, rsi, rdx, rcx, r8, r9, the rest at [rsp], rsp +16-byte aligned, al = 0 (`ffi_sysv_call`). For aarch64-macos the A64 +translator turns that sequence into an AAPCS64 call (`ax_import_call`: +x0-x5 from the System V registers, x6/x7 from the first two stack words, +adrp + ldr of the slot, blr); variadic arguments, which Apple's arm64 ABI +puts on the stack, are not supported, so the macOS layer calls no +variadic function with variadic arguments (open(2) without a mode, +creat(2) to create). aarch64-windows reuses the tables and the +translator hook with its own call sequence. On a target without import +support a call to an `extern` function is an error. + +`as "symbol"` after the signature names the library's symbol when the +Track name differs (a runtime name such as `write` is taken, or the +symbol is not an identifier): + +```track +extern "libSystem.B.dylib" fn c_write(fd: i64, buf: i64, n: i64) -> i64 as "write"; +``` + +### Mach-O layout (`macho.trk`) + +Segments are 16 KiB aligned in the file and in memory (a byte's file +offset is its address minus 0x100000000), so arm64's page size holds: + +| segment | contents | +|---|---| +| `__PAGEZERO` | 4 GiB, no access | +| `__TEXT` (r-x) | mach header and load commands; `__text` at file offset 0x4000, the entry (LC_MAIN) at its first byte | +| `__DATA` (rw-) | `__data` (ngen's data, the code padded to 16 KiB so rip-relative / adrp references hold), `__got` (one slot per import, S_NON_LAZY_SYMBOL_POINTERS) | +| `__LINKEDIT` (r--) | bind opcodes, export trie (`__mh_execute_header`), symbol table, indirect symbol table, string table, code signature | + +Load commands: the four segments, LC_DYLD_INFO_ONLY (bind opcodes, no +rebases: the code is position independent, the image is MH_PIE), +LC_SYMTAB, LC_DYSYMTAB, LC_LOAD_DYLINKER `/usr/lib/dyld`, LC_UUID (from +the SHA-256 of code and data, so builds are reproducible), +LC_BUILD_VERSION (macOS, minos 11.0), LC_MAIN (stack 32 MiB), one +LC_LOAD_DYLIB per library (`"libSystem.B.dylib"` is +`/usr/lib/libSystem.B.dylib`), LC_CODE_SIGNATURE. Each import is bound +with BIND_TYPE_POINTER into its `__got` slot, two-level namespace, the +library ordinal being its LC_LOAD_DYLIB. On x86_64 `stat`, `fstat` and +`lstat` bind `$INODE64`, the 64-bit-inode layout arm64 has under the +plain names. + +The entry is called as main(argc, argv, envp, apple); it passes argc and +argv to `os_start` (rt/os/macos.trk), which calls `rt_start`. The +cputype is x86_64 (0x01000007) or arm64 (0x0100000c); the x86_64 fixups +are rip displacements, the arm64 ones adrp + ldr pairs (`mo_patch_a64`). + +**Code signature.** Arm64 macOS refuses unsigned code, so every image +carries an ad-hoc, linker-signed signature as ld64 writes it: a +SuperBlob (0xfade0cc0) with one CodeDirectory (0xfade0c02, version +0x20400, flags `adhoc | linker-signed`, no special slots, identifier = +the output file name), SHA-256 (computed in Track) of every 4 KiB page of +the file up to the signature, `codeLimit` = the signature offset, exec +segment = `__TEXT` (main binary). `tests/tools/macho_check.py` re-parses +an image independently and recomputes every hash; `tests/sh/macos.sh` +runs it over hello, the examples and trackc for both macOS targets. + +Not checked off a Mac: running. CI's `macos` job runs the cross-built +binaries on an Intel runner (x86_64-macos) and an Apple-silicon one +(aarch64-macos), against the example goldens, and has trackc rebuild +hello there byte for byte. ### PE32+ layout (`pe.trk`) @@ -129,6 +195,7 @@ calls; `store64`/`store8` must not be reordered across `syscall6`. | `vec.trk` | `vec_*`, `track_i64_collection_*`, `track_sb_*`, `track_array_*`, `array_len`, `track_bad_field`, `math_*`, `add`/`sum`/`sub` | | `os/linux.trk` | the Linux OS layer: argv, `env_*`, `sys_exec`/`process_spawn` (fork + execve `/bin/sh -c` + wait4), `clock_ms`, `file_*`, `track_file_*`, `dir_exists`, `net_socket_*` | | `os/windows.trk` | the Windows OS layer (kernel32 through `extern`): the same interface, plus `os_start` and `os_syscall` | +| `os/macos.trk` | the macOS OS layer (libSystem through `extern`): the same interface, plus `os_start` and `os_syscall` (Linux numbers to libSystem calls; open/mmap flags, the stat layout, clock ids and socket options translated; -errno from `__error()`; `system(3)` for processes; environ from `_NSGetEnviron`) | | `libc.trk` | `open64`, `write`, `fchmod`, `close`, `memset`: the libc names `elf.trk` calls, written in Track | The runtime keeps the word-ABI behaviour of the retired C runtime diff --git a/scripts/embed_runtime.sh b/scripts/embed_runtime.sh index 0ec2971..eb4ff7b 100755 --- a/scripts/embed_runtime.sh +++ b/scripts/embed_runtime.sh @@ -12,7 +12,7 @@ set -eu root=$(cd "$(dirname "$0")/.." && pwd) out="$root/compiler/src/runtime_trk.trk" tmp="${out}.tmp.$$" -modules="mem io str vec os/linux os/windows libc" +modules="mem io str vec os/linux os/windows os/macos libc" { echo "// runtime_trk.trk — GENERATED by scripts/embed_runtime.sh from" diff --git a/tests/sh/ids.txt b/tests/sh/ids.txt index 822354d..cd896d9 100644 --- a/tests/sh/ids.txt +++ b/tests/sh/ids.txt @@ -107,3 +107,9 @@ arm64/arm64_hello_runs_under_qemu arm64/arm64_programs_print_their_goldens arm64/arm64_compiler_reaches_a_fixed_point_under_qemu arm64/arm64_target_does_not_change_x86_64_output +macos/macos_hello_is_a_signed_macho +macos/macos_examples_and_trackc_pass_the_checker +macos/macos_objdump_parses_headers_binds_and_code +macos/macos_checker_catches_a_changed_page +macos/macos_build_is_deterministic +macos/macos_extern_binds_the_as_symbol diff --git a/tests/sh/macos.sh b/tests/sh/macos.sh new file mode 100644 index 0000000..93984ee --- /dev/null +++ b/tests/sh/macos.sh @@ -0,0 +1,100 @@ +# macOS targets (`--target x86_64-macos` / `aarch64-macos`, compiler/src/ +# macho.trk, rt/os/macos.trk; docs/native.md "Mach-O layout"): structural +# checks only, nothing here runs Mac code (CI's macos jobs do). +# tests/tools/macho_check.py (independent of macho.trk) re-parses every +# image and recomputes its code signature hashes; llvm-objdump, when +# present, must parse headers, binds and code without a complaint. +# Commands run from the repository root. + +need_py() { + have python3 || skip "python3 not found" +} + +macho_check() { + cap python3 "$ROOT/tests/tools/macho_check.py" "$@" +} + +t_macos_hello_is_a_signed_macho() { + need_py + local a want + for a in x86_64 aarch64; do + in_repo "$TRACKC" build --target $a-macos examples/hello.trk -o "$T/hello_$a" + rc_ok "$a: build" + eq "$(od -An -tx1 -N 4 "$T/hello_$a" | tr -d ' ')" "cffaedfe" "$a: MH_MAGIC_64" + want=07000001 + [ $a = aarch64 ] && want=0c000001 + eq "$(od -An -tx1 -j 4 -N 4 "$T/hello_$a" | tr -d ' ')" "$want" "$a: cputype" + macho_check "$T/hello_$a" + rc_ok "$a: macho_check" + has "$OUT" "ok " "$a: checker verdict" + done +} + +t_macos_examples_and_trackc_pass_the_checker() { + need_py + local a e s n=0 + for a in x86_64 aarch64; do + for e in $(trk_files "$ROOT/examples") "$ROOT/compiler/src/main.trk"; do + s=$(stem "$e") + case "$s" in *_err) continue ;; esac + in_repo "$TRACKC" build --target $a-macos "$e" -o "$T/${a}_$s" + rc_ok "$a $s: build" + n=$((n + 1)) + done + done + macho_check "$T"/x86_64_* "$T"/aarch64_* + rc_ok "macho_check: $OUT" + [ "$n" -ge 30 ] || fail "only $n images" +} + +t_macos_objdump_parses_headers_binds_and_code() { + have llvm-objdump || skip "llvm-objdump not found" + local a + for a in x86_64 aarch64; do + in_repo "$TRACKC" build --target $a-macos examples/stdlib_demo.trk -o "$T/demo_$a" + rc_ok "$a: build" + cap llvm-objdump --macho --private-headers --bind --lazy-bind -d "$T/demo_$a" + rc_ok "$a: llvm-objdump" + eq "$ERR" "" "$a: llvm-objdump stderr" + has "$OUT" "LC_CODE_SIGNATURE" "$a: code signature command" + has "$OUT" "/usr/lib/libSystem.B.dylib" "$a: libSystem" + has "$OUT" "__got" "$a: GOT" + has "$OUT" "libSystem _write" "$a: write bound from libSystem" + has "$OUT" "symbol address: _write" "$a: a call through the _write slot" + done +} + +t_macos_checker_catches_a_changed_page() { + need_py + in_repo "$TRACKC" build --target x86_64-macos examples/hello.trk -o "$T/h" + rc_ok "build" + printf '\220' | dd of="$T/h" bs=1 seek=20000 conv=notrunc 2>/dev/null + macho_check "$T/h" + rc_is 1 "a changed page fails" + has "$OUT" "hash mismatch" "message" +} + +t_macos_build_is_deterministic() { + # the signature names the file, so both builds use the same name + in_repo "$TRACKC" build --target aarch64-macos examples/hello.trk -o "$T/1/hello" + rc_ok "first build" + in_repo "$TRACKC" build --target aarch64-macos examples/hello.trk -o "$T/2/hello" + rc_ok "second build" + same_file "$T/1/hello" "$T/2/hello" "two builds" +} + +t_macos_extern_binds_the_as_symbol() { + need_py + cat >"$T/ext.trk" <<'EOF2' +extern "libSystem.B.dylib" fn my_pid() -> i32 as "getpid"; +fn main() -> i64 { print(my_pid() > 0); return 0; } +EOF2 + trackc check "$T/ext.trk" + rc_ok "check" + trackc build --target x86_64-macos "$T/ext.trk" -o "$T/ext" + rc_ok "build" + grep -q '_getpid' "$T/ext" || fail "no _getpid symbol" + grep -q 'my_pid' "$T/ext" && fail "the Track name leaked into the image" + macho_check "$T/ext" + rc_ok "macho_check" +} diff --git a/tests/sh/xplat.sh b/tests/sh/xplat.sh index 56e9c41..d3e7575 100644 --- a/tests/sh/xplat.sh +++ b/tests/sh/xplat.sh @@ -26,10 +26,10 @@ t_xplat_unknown_target_is_a_clear_error() { } t_xplat_unsupported_target_says_so() { - in_repo "$TRACKC" build --target aarch64-macos examples/hello.trk -o "$T/x" + in_repo "$TRACKC" build --target aarch64-windows examples/hello.trk -o "$T/x" rc_is 2 "exit code" has "$ERR" "not supported yet" "message" - in_repo "$TRACKC" check --target aarch64-macos examples/hello.trk + in_repo "$TRACKC" check --target aarch64-windows examples/hello.trk rc_ok "check works for any known target" } diff --git a/tests/tools/macho_check.py b/tests/tools/macho_check.py new file mode 100644 index 0000000..a5f5db2 --- /dev/null +++ b/tests/tools/macho_check.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Independent structural checker for the Mach-O executables trackc writes +(docs/native.md, "Mach-O layout"). Written from Apple's , + and the code-signing blob formats, not from macho.trk. + + python3 tests/tools/macho_check.py FILE... + +Checks the header, the segments and sections (in the file, page-aligned, +not overlapping), LC_MAIN inside __text, the dyld bind opcodes (every +__got slot bound exactly once, to the symbol the indirect symbol table +names, from a loaded dylib), and the ad-hoc code signature: SuperBlob, +CodeDirectory fields, and every SHA-256 page hash recomputed. Prints +"ok FILE" per file; exits 1 with the first problem otherwise. +""" +import hashlib +import struct +import sys + +LC_SEGMENT_64, LC_SYMTAB, LC_DYSYMTAB, LC_LOAD_DYLIB = 0x19, 0x2, 0xB, 0xC +LC_LOAD_DYLINKER, LC_UUID, LC_CODE_SIGNATURE, LC_BUILD_VERSION = 0xE, 0x1B, 0x1D, 0x32 +LC_DYLD_INFO_ONLY, LC_MAIN = 0x80000022, 0x80000028 +CPUS = {0x01000007: "x86_64", 0x0100000C: "arm64"} + + +class Bad(Exception): + pass + + +def need(cond, msg): + if not cond: + raise Bad(msg) + + +def uleb(b, i): + v = s = 0 + while True: + x = b[i] + i += 1 + v |= (x & 0x7F) << s + s += 7 + if x < 0x80: + return v, i + + +def cstr(b, i): + j = b.index(b"\0", i) + return b[i:j].decode(), j + 1 + + +def check(path): + f = open(path, "rb").read() + magic, cpu, sub, ftype, ncmds, sizeofcmds, flags, _ = struct.unpack_from("<8I", f, 0) + need(magic == 0xFEEDFACF, "not MH_MAGIC_64") + need(cpu in CPUS, "cputype %#x" % cpu) + need(ftype == 2, "not MH_EXECUTE") + need(flags & 0x200085 == 0x200085, "flags %#x lack NOUNDEFS|DYLDLINK|TWOLEVEL|PIE" % flags) + page = 0x4000 + segs, sects, dylibs, cmds = [], [], [], {} + off = 32 + for _ in range(ncmds): + cmd, size = struct.unpack_from("<2I", f, off) + need(size % 8 == 0 and size >= 8, "load command size %d" % size) + cmds.setdefault(cmd, []).append(off) + if cmd == LC_SEGMENT_64: + name = f[off + 8:off + 24].rstrip(b"\0").decode() + va, vs, fo, fs, maxp, initp, ns, _ = struct.unpack_from("<4Q4I", f, off + 24) + need(size == 72 + 80 * ns, "segment %s size" % name) + segs.append((name, va, vs, fo, fs, initp)) + for k in range(ns): + s = off + 72 + 80 * k + sn = f[s:s + 16].rstrip(b"\0").decode() + sg = f[s + 16:s + 32].rstrip(b"\0").decode() + a, sz, so, al, _, _, fl, r1 = struct.unpack_from("<2Q6I", f, s + 32) + need(sg == name, "section %s in %s" % (sn, name)) + need(va <= a and a + sz <= va + vs, "section %s outside its segment" % sn) + need(so - fo == a - va, "section %s file/address mismatch" % sn) + need(a % (1 << al) == 0, "section %s misaligned" % sn) + sects.append((sn, sg, a, sz, so, fl, r1)) + elif cmd == LC_LOAD_DYLIB: + dylibs.append(cstr(f, off + struct.unpack_from("= 0xB0000, "build version platform %d minos %#x" % (plat, minos)) + # segments + names = [s[0] for s in segs] + need(names[0] == "__PAGEZERO" and segs[0][3:5] == (0, 0) and segs[0][5] == 0, "__PAGEZERO") + need(names[-1] == "__LINKEDIT", "__LINKEDIT last") + need("__TEXT" in names, "no __TEXT") + text = segs[names.index("__TEXT")] + need(text[3] == 0, "__TEXT must map the header") + end = 0 + for name, va, vs, fo, fs, prot in segs[1:]: + need(va % page == 0 and fo % page == 0 and vs % page == 0, "segment %s not page-aligned" % name) + need(fs <= vs and fo + fs <= len(f), "segment %s past the file" % name) + need(fo >= end, "segment %s overlaps" % name) + need(va - text[1] == fo, "segment %s address != file offset + base" % name) + need(not (prot & 2 and prot & 4), "segment %s writable and executable" % name) + end = fo + fs + le = segs[-1] + need(le[3] + le[4] == len(f), "__LINKEDIT does not end the file") + textsec = [s for s in sects if s[0] == "__text"] + need(len(textsec) == 1, "one __text") + entry, _ = struct.unpack_from("<2Q", f, cmds[LC_MAIN][0] + 8) + need(textsec[0][4] <= entry < textsec[0][4] + textsec[0][3], "LC_MAIN entry outside __text") + # symbols and binds + so_, ns_, stro, strs = struct.unpack_from("<4I", f, cmds[LC_SYMTAB][0] + 8) + syms = [] + for k in range(ns_): + strx, ty, sc, desc, val = struct.unpack_from("> 8 <= len(dylibs), "symbol %s library ordinal" % name) + want[g[2] + 8 * k] = (name, desc >> 8) + di = struct.unpack_from("<10I", f, cmds[LC_DYLD_INFO_ONLY][0] + 8) + need(di[1] == 0 or di[0] >= le[3], "rebase info outside __LINKEDIT") + b, i, stop = f, di[2], di[2] + di[3] + ordn = sym = seg = segoff = None + bound = {} + while i < stop: + op, imm = b[i] & 0xF0, b[i] & 0x0F + i += 1 + if op == 0x00: + break + elif op == 0x10: + ordn = imm + elif op == 0x20: + ordn, i = uleb(b, i) + elif op == 0x40: + sym, i = cstr(b, i) + elif op == 0x50: + need(imm == 1, "bind type %d" % imm) + elif op == 0x70: + seg = imm + segoff, i = uleb(b, i) + elif op == 0x90: + need(seg is not None and sym is not None and ordn, "incomplete bind") + addr = segs[seg][1] + segoff + need(addr not in bound, "slot %#x bound twice" % addr) + bound[addr] = (sym, ordn) + segoff += 8 + else: + raise Bad("unexpected bind opcode %#x" % b[i - 1]) + need(bound == want, "binds do not match the __got / indirect symbols") + # code signature + cs, cssize = struct.unpack_from("<2I", f, cmds[LC_CODE_SIGNATURE][0] + 8) + need(cs % 16 == 0 and cs >= le[3] and cs + cssize == len(f), "signature placement") + mg, ln, cnt = struct.unpack_from(">3I", f, cs) + need(mg == 0xFADE0CC0 and ln <= cssize, "SuperBlob") + cd = None + for k in range(cnt): + ty, o = struct.unpack_from(">2I", f, cs + 12 + 8 * k) + if ty == 0: + cd = cs + o + need(cd is not None, "no CodeDirectory slot") + (cmg, cln, ver, cflags, hoff, ioff, nspec, ncode, limit) = struct.unpack_from(">9I", f, cd) + hsize, htype, _plat, pshift = struct.unpack_from(">4B", f, cd + 36) + need(cmg == 0xFADE0C02, "CodeDirectory magic") + need(cflags & 0x20002 == 0x20002, "flags %#x lack adhoc|linker-signed" % cflags) + need(hsize == 32 and htype == 2 and pshift == 12, "not SHA-256 over 4 KiB pages") + need(limit == cs, "codeLimit %d != signature offset %d" % (limit, cs)) + need(ncode == (limit + 4095) // 4096, "nCodeSlots") + need(cd + cln <= cs + ln, "CodeDirectory past the SuperBlob") + if ver >= 0x20400: + base, lim, segflags = struct.unpack_from(">3Q", f, cd + 64) + need(base == text[3] and lim == text[4] and segflags & 1, "exec segment != __TEXT") + for p in range(ncode): + page_bytes = f[4096 * p:min(4096 * (p + 1), limit)] + h = f[cd + hoff + 32 * p:cd + hoff + 32 * (p + 1)] + need(hashlib.sha256(page_bytes).digest() == h, "page %d hash mismatch" % p) + return "%s %s, %d imports, %d pages hashed" % (CPUS[cpu], cstr(f, cd + ioff)[0], nslot, ncode) + + +def main(): + rc = 0 + for p in sys.argv[1:]: + try: + print("ok %s: %s" % (p, check(p))) + except (Bad, struct.error, ValueError, IndexError) as e: + print("FAIL %s: %s" % (p, e)) + rc = 1 + return rc + + +if __name__ == "__main__": + sys.exit(main())