From 2b92b442767fed55ec333b001fb2f4043860750f Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:17:30 +0000 Subject: [PATCH] The first programs for darwin-arm64, run on the Mac: Gen.arm64, Exe.darwin PLAN.md 5, step 5a. Gen.arm64 begins: frames by Apple's convention, constants, calls, C through libSystem's quadwords, jumps, the entry point; what it can't make yet is noted on its procedure and is an error only where that procedure is live. Exe.darwin writes a Mach-O for dyld: binds and rebases by LC_DYLD_INFO_ONLY, an ad-hoc signature with SHA-256 page hashes. Link patches A64's fixups and lists the rebases. lib gains Rt.darwin-arm64 and CAbi.darwin-arm64, which tools/cabi.c, now ported to macOS, made here. make mac-check compiles test/mac in the container by src/cross.sh's compiler and runs it natively: 5 pass. x86-64's output is unchanged for 202 programs; the fixpoint holds. --- diff --git a/Makefile b/Makefile index 6d85f6c..e02daad 100644 --- a/Makefile +++ b/Makefile @@ -207,7 +207,7 @@ site-check: build/site/Verify build/site/Verify -.PHONY: docker-image docker-check docker-shell prev-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site site-source site-check clean install uninstall +.PHONY: docker-image docker-check mac-check docker-shell prev-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site site-source site-check clean install uninstall # `make check` in a linux/amd64 container, for a machine that isn't one # (the repository is mounted at its own path, so git and the tests see @@ -219,6 +219,12 @@ docker-check: docker-image $(DOCKER) $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && make check" + +# test/mac's programs (test/mac.sh), on an Apple Silicon Mac: compiled +# for darwin-arm64 by the cross compiler in the container, then run here +mac-check: docker-image + $(DOCKER) $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && timeout 1200 test/mac.sh build" + test/mac.sh run docker-shell: docker-image $(DOCKER) -it $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && exec bash" diff --git a/PLAN.md b/PLAN.md index 7d10b9f..cb5dbed 100644 --- a/PLAN.md +++ b/PLAN.md @@ -224,19 +224,37 @@ the assembler in Arm's syntax (`bl p`, `b p`, `adr xN, v` for names), checked against Apple's assembler (clang's, `llvm-mc`'s bytes) by `test/a64`; Chunk's arm64 fixup kinds, `fxBranch26`, `fxPage21` and - `fxPageOff12`, and `Scan.setBang` for a pre-index's `!`. Left for - later: `Link`'s patching of those kinds comes with step 6; no - compiler imports `A64` until step 5's `Gen.arm64.raz`, and - `Chunk.beginChunk` still pads code with x86's `int3`, which arm64's - Gen will want as `brk`. + `fxPageOff12`, and `Scan.setBang` for a pre-index's `!`. What it + left for later, `Link`'s patching of those kinds, `Gen.arm64.raz` + importing `A64`, and padding with `brk`, came with 5a. 5. `Gen.arm64.raz`, in pieces, each run on the Mac (owner, 2026-11-15): first a bare `Exe.darwin.raz` (a signed Mach-O over libSystem, no line numbers) and an `Rt` that only exits, built by the staged cross compiler in the container; then values and operations; jumps and checks; calls and frames; reals; atomics, deferred statements, the entry point. -6. `Exe.darwin.raz` and `Link`'s rebases, its line numbers for lldb; - `Host.darwin.raz`. + + 5a, done: programs made by the cross compiler (`src/cross.sh + darwin-arm64`) run on the Mac, `test/mac` by `make mac-check`. In + `Gen.arm64.raz`: frames, constants, variables, the integer + operations but division, comparisons and jumps, elements and slices + unchecked, calls with arguments in registers, C's calls, code + procedures and the entry point; every other routine notes "not yet + on arm64" on its procedure, an error if the program uses it. + `Exe.darwin.raz`: a signed Mach-O over libSystem, its rebases and + binds dyld's opcodes, no line numbers. `Link`: arm64's fixups, Mach-O's + paged layout, the rebases. `lib/Rt.darwin-arm64.raz`: exit through C's + exit, one procedure at exit, fail and stop by `write`. As the interface + check of `Rt` reads `Rt.raz`, and so compiles `Sys` over C, also + `lib/CAbi.darwin-arm64.raz`, from `tools/cabi.c` on the Mac, and a + code procedure skipped in a file read only for its interface. Left of + step 5: division and its check, the other checks and their stubs for + `Rt.fail`, the reals, arguments and results past the registers or in + memory (`x8`), Apple's variadic calls, `try`, deferred statements, + atomics and system calls, `COPY`, `FILL`, `NEW`'s zeroing, the bit + counts and rotations, copies past 256 bytes. +6. `Exe.darwin.raz`'s line numbers for lldb (its rebases came with + 5a); `Host.darwin.raz`. 7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`. 8. `test/` and `conform/` passing on the Mac; what differs by target (signals' words, errors' numbers) in files of the target's. diff --git a/doc/compiler.md b/doc/compiler.md index 47c94e9..9b9fe83 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,8 +1,9 @@ # Reading the raz compiler -The compiler is thirteen files of raz, about 14,600 lines of code (the -budget is 18,000); one of them, `A64.raz`, arm64's encoder, waits for -the back end that will use it (`PLAN.md` 5). It is its own compiler: a release of it, the one +The compiler is fifteen files of raz, about 16,100 lines of code (the +budget is 18,000); three of them, `A64.raz`, `Gen.arm64.raz` and +`Exe.darwin.raz`, are the Mac's back end, begun (`PLAN.md` 5), built +only into a compiler for `darwin-arm64` (`src/cross.sh`). It is its own compiler: a release of it, the one `BOOT` names, builds `src/`, and `make fixpoint` checks that what it makes makes itself again, byte for byte. Each release was built by the one before it, back to v0.19.0, which the Pascal compiler it was ported @@ -18,18 +19,20 @@ | File | Lines | Code | What | |---|---|---|---| | `src/Diag.raz` | 479 | 363 | Messages: positions, source excerpts, colour, counts | -| `src/Scan.raz` | 1,279 | 1,048 | Symbols, literals, comments, positions | +| `src/Scan.raz` | 1,288 | 1,050 | Symbols, literals, comments, positions | | `src/Sym.raz` | 866 | 689 | Types, objects, scopes, layout | -| `src/Chunk.raz` | 389 | 288 | The compiled program: chunks, fixups, line notes | -| `src/X64.raz` | 1,777 | 1,450 | The instruction encoder, jumps within a procedure, the assembler | -| `src/A64.raz` | 1,848 | 1,365 | The same for arm64, not yet imported: the encoder, jumps, the assembler | -| `src/Gen.x86_64.raz` | 2,860 | 1,998 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/Chunk.raz` | 410 | 302 | The compiled program: chunks, fixups, line notes | +| `src/X64.raz` | 1,771 | 1,450 | The instruction encoder, jumps within a procedure, the assembler | +| `src/A64.raz` | 1,843 | 1,365 | The same for arm64: the encoder, jumps, the assembler | +| `src/Gen.x86_64.raz` | 2,861 | 1,999 | The stack machine, for x86-64: values, operations, checks, calls, frames | +| `src/Gen.arm64.raz` | 1,468 | 1,107 | The same for arm64, begun: frames, values, operations, jumps, calls | | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls | -| `src/Parse.raz` | 4,938 | 4,191 | Declarations, statements, expressions, built-ins, recovery, warnings | -| `src/Link.raz` | 411 | 317 | Tree shaking, layout, patching, the places | +| `src/Parse.raz` | 4,948 | 4,198 | Declarations, statements, expressions, built-ins, recovery, warnings | +| `src/Link.raz` | 481 | 365 | Tree shaking, layout, patching, the places | | `src/Exe.linux.raz` | 455 | 358 | The executable, ELF: static and dynamic, symbol table, line numbers | +| `src/Exe.darwin.raz` | 458 | 332 | The executable for macOS, Mach-O: dyld's binds and rebases, the signature | | `src/Host.linux.raz` | 103 | 52 | The system running the compiler | -| `src/Raz.raz` | 493 | 385 | The command line, and `-q` for an editor | +| `src/Raz.raz` | 499 | 390 | The command line, and `-q` for an editor | Every file opens with a comment that says what it is, what it depends on and what it leaves out. Read those first; they are the map. @@ -1154,8 +1157,7 @@ `fxPage21`, an `adrp`'s distance in pages of 4 KB; `fxPageOff12`, an address's place in its page, in an `add` or, divided by the size the instruction reads, a load's or store's offset; as the Mach-O relocations -of the same names. `Link.raz` patches only x86-64's yet; arm64's come -with the Mac's executable. A constant's addresses +of the same names, which `Link.raz` patches. A constant's addresses are *data fixups*, `addDataFixup`'s: 64-bit fields in rodata that will hold a chunk's address itself, since the executable is loaded where the linker placed it. `noteLine` records which line and column of the source @@ -1165,7 +1167,11 @@ end of what was made, for a body compiled a second time. What other modules set in a chunk, such as `live` or `adr`, has a setter each (`setLive`, `setAdr`), since an exported variable can't be set from -outside. None of this depends on the machine. +outside. None of this depends on the machine, but two things a `Gen` +gives it: `pad`, the word that fills the gaps between procedures, a +trap if ever run (`setPad`: int3 on x86-64, brk on arm64); and, on a +chunk, what that `Gen` can't make yet (`setMissing`), an error if the +chunk is live (`Gen.arm64.raz` says more). ## X64.raz: machine code @@ -1278,9 +1284,9 @@ ## A64.raz: arm64's machine code -X64's twin, for arm64: what `Gen.arm64.raz` will call, and the -assembler of a code procedure on the Mac. No compiler imports it yet; -`test/a64` checks every routine against Apple's assembler. +X64's twin, for arm64: what `Gen.arm64.raz` calls, and the assembler +of a code procedure on the Mac. Only a compiler for `darwin-arm64` +imports it; `test/a64` checks every routine against Apple's assembler. Every instruction is one word of 32 bits, which `emit` writes. A routine builds the word from its fields with shifts and ors, and its @@ -1704,6 +1710,96 @@ `call` loads the register from it after each call, as System V has no callee-saved xmm register. +## Gen.arm64.raz: the stack machine on arm64 + +arm64's `Gen`, for macOS on Apple Silicon (`PLAN.md` 5), is begun. It +answers every call `Gen.x86_64.raz` answers, with the same parameters, +as the interface check holds the two files to (report, 3), and makes +frames, constants, the values of variables and their stores, the +integer operations but division, comparisons and jumps, elements and +slices unchecked, calls with integer arguments in registers, C's +calls, code procedures (`A64.assemble`) and the entry point. `Gen.Arch` +is `"arm64"`. + +*Not yet.* What it can't make yet isn't refused at once, since a +library module holds much that a program never calls: the C library's +`Sys` is compiled whole for the Mac, as the interface check of `Rt` +reads `Rt.raz`, which imports it. So a routine not yet made calls +`notYet`, which notes on the procedure's chunk what it is and where, +the first only (`Chunk.setMissing`); keeps the stack as the real +routine would, so that the compile reads on; and makes what code it +likes, never run. Once `Link.markLive` has marked what the program +reaches, `Raz` makes each live chunk so noted an error at its place: + + D.raz:8:19: error: not yet on arm64: div and mod + +A program that uses what isn't made fails to compile, and one that +doesn't compiles. `beginProc` comes before its chunk is begun, so its +notes wait for `enterBody` (`pending`). A routine not yet made reads +into `_` the parameters it doesn't use yet, so that none is warned of. + +*The stack* is x86-64's, kept as plainly as it can be: the value at +depth d is in `Regs[d mod 6]`, x9 to x14, which a call may change and +which carry no argument, so `call` moves the arguments into x0 to x7 in +any order, with none held back as x86's r8 and r9 are. A value is a +constant (`lConst`), an address in the frame or of a chunk not yet +made (`lAdr`), in its register (`lReg`) or spilled to a slot +(`lFrame`). There is no `lMem`, `lIdx`, `lHeld` or `lInto`: arm64 takes +memory only in a load or a store, so `pushVar` loads at once, an +operand is always a register, and a register variable is copied into +the value's register. Outside the stack, x15 and x17 are Gen's scratch, +as rax and rcx are x86's; x16 is A64's; x0 to x3 copy and cut slices, +between calls; x8 is kept for the address of a result in memory, as +Apple's convention has it, and x18, the system's, is never touched. + +A place in memory is a `Mem`: a register and an offset, or a chunk and +an offset, which A64 reaches by `adrp` and the place in the page +(`loadChunk`, `storeChunk`), since macOS loads a program anywhere. +`place` makes one of an `Adr`, as x86's makes an operand. + +*Frames* follow Apple's convention. The prologue pushes the frame +record, x29 and x30, points x29 at it, and lowers sp by the frame, whose +size `endProc` patches into two `sub`s, of its bits from 12 up and of +its low 12, so that a frame is less than 16 MB. `Loop.main` of +`test/mac`, with `i` in x19: + +``` +stp x29, x30, [sp, #-16]! +mov x29, sp +sub sp, sp, #0, lsl #12 ; the frame, patched in by endProc +sub sp, sp, #32 +stur xzr, [x29, #-8] ; sum, a local in memory, zeroed +stur x19, [x29, #-24] ; i's register, saved and zeroed +mov x19, #0 +... +mov sp, x29 ; endProc's +ldp x29, x30, [sp], #16 +ret +``` + +Every slot is at a negative offset from x29, and nothing is pushed in +a body, so sp stays a multiple of 16 and `pushed` is always 0. The +busiest variables take x19 to x23 (`VarRegs`), which a callee gives +back; no parameter is kept where it arrives (`keepArrived` does +nothing); the reals' variables will take d8 to d15 (`XVarRegs`, +numbered from `XmmVar`, 32, above every x register, which `Parse` tells +apart by it). + +*Calls* move each argument into x0 to x7; a single result comes back in +x0, two words in x0 and x1, and a narrow result of C's is extended, as +C leaves the upper bits as they fall. C's procedure is called through +the quadword the loader fills in, `adrp x16` of its page, `ldr x17, +[x16, ...]` and `blr x17`; a procedure value from its slot, `blr x17` +too. + +*The entry point* (`entryPoint`) is the C `main` that dyld calls: it +pushes a frame record, which links to dyld's, saves argc, an `int` it +extends to 64 bits, and argv, gives `Rt` C's `exit` in `cExit` and the +addresses it is given, runs every used module's body and `main`, and +calls `Rt.exit` with `main`'s result or 0. `brk #1` follows it, and +fills the gaps between procedures (`Chunk.setPad`). A program for the +Mac always uses C, so `dynamic` is always true; `-bare` is refused. + ## Item.raz: items An operand is an *item* (`Item`), as in Wirth's compilers. Its `mode` @@ -2093,7 +2189,13 @@ of its files there (a file's identity is its device and inode from `Sys.info`, which follows a symbolic link, as on every target); `checkSiblings` then reads the files for other targets beside it, declarations only, and `compareIface` holds them -to the same exports by their fingerprints. A generic module is +to the same exports by their fingerprints: a parameter's name is part +of a procedure's, and a named type's module part of the type's, so the +assemblers' readers, which both `Gen`s take, are `Scan`'s +(`Scan.ConstFn`, `Scan.NameFn`). A code procedure of such a file is +skipped to its `end`, not assembled, as it is in another machine's +assembly. The modules such a file imports are compiled whole, as any +import is: on the Mac, `Rt.raz`'s `Sys`. A generic module is compiled once per distinct list of arguments, where it is first used. The import only notes where its arguments are (`skipArgs`, `deferred`); `firstUse`, from `qualIdent`, has `makeInstance` go back there, where @@ -2324,11 +2426,26 @@ segments, with their different permissions, share a page. bss follows the loader's table, or begins a page of its own. +Mach-O is laid out otherwise. `Exe.darwin.raz` sets the base to +100000000H, past the 4 GB `__PAGEZERO` that arm64 macOS demands, and +`Link.setPaged` to its page of 16 KB: each segment then starts on a +page of its own, in the file as in memory, at the base plus its offset +in the file (`paged`), rodata on the page after the code and bss on the +page after rodata, with no bytes in the file. The 2 GB check, which is +for `X64.memAbs`'s 32-bit addresses, isn't made. The words of rodata +that a data fixup patches are listed by their addresses (`rebases`), +since macOS loads a program anywhere and dyld moves them with it. +arm64's fixups are patched by `patchArm`: a branch's distance in words, +an `adrp`'s in pages of 4 KB, and an address's place in its page, in an +`add` or, divided by the size it moves, in a load or a store, as +`Chunk.FixKind` says. The places keep the addresses the linker gave; +the Mac's `Rt` will take dyld's slide from what it looks up. + ## Exe.linux.raz: the executable `Exe`, the executable, is the one unit that knows the file format of -the target's system; this is Linux's, ELF. A macOS `Exe.darwin.raz` -will be Mach-O. `Exe.write` writes the ELF header, the program headers, the text and +the target's system; this is Linux's, ELF. macOS's, `Exe.darwin.raz`, +is Mach-O (below). `Exe.write` writes the ELF header, the program headers, the text and rodata images, and then what isn't loaded: section headers, a symbol table with every live procedure and variable by `Module.name`, and the compile unit that names the line table. The line table is in the @@ -2354,7 +2471,55 @@ notes `Chunk.noteLine` made, and the single compile unit gdb needs to find it, which `putDebug` writes. There are no types or variables in it; gdb can stop at a line and show where it is, not print a variable. + +## Exe.darwin.raz: the Mac's executable +`Exe` for macOS on arm64 writes Mach-O as dyld, the dynamic loader, +takes it and the kernel runs it, with the same calls as Linux's: the +driver's `needLib`, `setStripped` and `write` mean what they mean +there, and `setMusl` refuses musl. `-base` is refused, since macOS +loads a program where it chooses, and a library besides libSystem +isn't linked yet. The file: + +| Part | What | +|---|---| +| header | `MH_EXECUTE` for `CPU_TYPE_ARM64`, flags `MH_PIE` and the dynamic loader's | +| `__PAGEZERO` | 4 GB at address 0, no access: arm64 macOS runs no program without it | +| `__TEXT` | the header again, at 0, and the code, read and run | +| `__DATA_CONST` | rodata, which dyld makes read-only once it has rebased it (`SG_READ_ONLY`) | +| `__DATA` | the variables and C's symbols' quadwords, zeros, not in the file | +| `__LINKEDIT` | dyld's opcodes, the symbol table, and the code signature | + +and its load commands: `LC_DYLD_INFO_ONLY` for the rebases and binds; +`LC_SYMTAB` with each named live chunk, as on Linux, a local symbol +for lldb, and `LC_DYSYMTAB`, which says all are local; +`LC_LOAD_DYLINKER` naming `/usr/lib/dyld`; `LC_UUID`, the first 16 +bytes of the SHA-256 of what follows the header; `LC_BUILD_VERSION`, +macOS 11.0 and up; `LC_MAIN`, the entry point's offset; `LC_LOAD_DYLIB`, +`/usr/lib/libSystem.B.dylib`; and `LC_CODE_SIGNATURE`. The header has +the room of every command, `HeaderRoom`, as the code's place is fixed +before the commands' sizes are known. + +Rodata holds the addresses of other chunks (a constant's data fixups), +and macOS loads a program anywhere, so dyld must move each: a rebase. +C's symbols are bound into their quadwords from libSystem by name, +with Mach-O's `_` before it. Both are dyld's opcodes, the plainest form +it still takes: a rebase is `SET_SEGMENT_AND_OFFSET_ULEB` and +`DO_REBASE_IMM_TIMES`, two bytes and the offset; a bind the symbol's +name, its segment and offset, and `DO_BIND`. The other form, chained +fixups, which Apple's linker writes now, threads them through the data +itself with tables of where each chain starts on each page. + +arm64 macOS runs nothing unsigned, so the file ends with an ad-hoc +code signature, which the kernel checks as it maps each page: a +SuperBlob holding one CodeDirectory, big-endian, of version 20400H +(with the executable segment, `__TEXT`), flags ad hoc and the linker's, +the program's name, and a SHA-256 hash of each page of 4 KB of the +file before the signature. `putHash` is SHA-256 (FIPS 180-4), as +`site/Sha256.raz` has it, made for bytes rather than hex. `otool -l`, +`codesign -v -v` and `vtool -show` read the file as Apple's tools +make it. + ## Host.linux.raz: the system running the compiler The host is the system running raz; the target is the system its @@ -2401,7 +2566,11 @@ export, `CLib` too, and opens with what it is, as raz's does. `test/host/Host.raz` is such a file (its library from the environment, no run, no C), and `test/compiler-host.sh` builds the compiler with it -and checks the four differences. The host changes nothing of the target: +and checks the four differences. `src/cross.sh darwin-arm64` builds the +compiler for the Mac this way, in the linux/amd64 container, and `make +mac-check` (`test/mac.sh`), on an Apple Silicon Mac, has it compile +`test/mac`'s programs there and runs each here, natively, against its +`X.expect` and `X.status`. The host changes nothing of the target: a program for another system still needs that system's `Sys` and `Rt`, and for a kernel the options `-bare`, `-s` and `-base`. diff --git a/lib/CAbi.darwin-arm64.raz b/lib/CAbi.darwin-arm64.raz new file mode 100644 index 0000000..0afea21 --- /dev/null +++ b/lib/CAbi.darwin-arm64.raz @@ -0,0 +1,225 @@ +(* CAbi: what the C library fixes for Sys over C on darwin-arm64: the + numbers of its flags, requests, signals and limits, where the + fields of its structs lie, an At the offset and a Len the width, + its errnos beside Linux's, and errno and closeFrom. + + Written by tools/cabi.c, from the system's own headers; not to be + edited, but written again. *) +module CAbi; +import SYSTEM; + +const + (* open's flags, fcntl's requests, seek, flock, mmap, access *) + oRdonly* = 0; + oWronly* = 1; + oRdwr* = 2; + oCreat* = 512; + oExcl* = 2048; + oTrunc* = 1024; + oAppend* = 8; + oNonblock* = 4; + oCloexec* = 16777216; + oNoctty* = 131072; + fGetfd* = 1; + fSetfd* = 2; + fGetfl* = 3; + fSetfl* = 4; + fDupfdCloexec* = 67; + fdCloexec* = 1; + seekSet* = 0; + seekCur* = 1; + seekEnd* = 2; + lockEx* = 2; + lockSh* = 1; + lockNb* = 4; + protRead* = 1; + protWrite* = 2; + mapShared* = 1; + mapPrivate* = 2; + mapAnonymous* = 4096; + mfdCloexec* = 0; + atFdcwd* = -2; + fOk* = 0; + rOk* = 4; + wOk* = 2; + xOk* = 1; + (* struct stat, statvfs and dirent *) + statLen* = 144; + stDevAt* = 0; + stDevLen* = 4; + stInoAt* = 8; + stInoLen* = 8; + stNlinkAt* = 6; + stNlinkLen* = 2; + stModeAt* = 4; + stModeLen* = 2; + stSizeAt* = 96; + stSizeLen* = 8; + stUidAt* = 16; + stUidLen* = 4; + stGidAt* = 20; + stGidLen* = 4; + stMtimeAt* = 48; + stMtimeLen* = 8; + stMtimeNsAt* = 56; + stMtimeNsLen* = 8; + sIfmt* = 61440; + sIfdir* = 16384; + sIfreg* = 32768; + sIflnk* = 40960; + statvfsLen* = 64; + fFrsizeAt* = 8; + fFrsizeLen* = 8; + fBlocksAt* = 16; + fBlocksLen* = 4; + fBavailAt* = 24; + fBavailLen* = 4; + dNameAt* = 21; + dTypeAt* = 20; + dtUnknown* = 0; + dtDir* = 4; + dtReg* = 8; + dtLnk* = 10; + (* the terminal, poll and the clocks *) + tcsanow* = 0; + tcsadrain* = 1; + tiocgwinsz* = 1074295912; + tiocswinsz* = 2148037735; + tiocsctty* = 536900705; + pollin* = 1; + pollout* = 4; + clockRealtime* = 0; + clockMonotonic* = 6; + timerAbstime* = 0; + (* sockets, their addresses, and a message with fds *) + afUnix* = 1; + afInet* = 2; + afInet6* = 30; + sockStream* = 1; + sockDgram* = 2; + sockCloexec* = 0; + sockNonblock* = 0; + solSocket* = 65535; + soReuseaddr* = 4; + soError* = 4103; + soPeercred* = -1; + shutWr* = 1; + msgNosignal* = 524288; + msgDontwait* = 128; + msgCmsgCloexec* = 0; + scmRights* = 1; + sockaddrLen* = 128; + saFamilyAt* = 1; + saFamilyLen* = 1; + saLenAt* = 0; + sockaddrUnLen* = 106; + sunPathAt* = 2; + sunPathLen* = 104; + sockaddrInLen* = 16; + sinPortAt* = 2; + sinAddrAt* = 4; + sockaddrIn6Len* = 28; + sin6PortAt* = 2; + sin6AddrAt* = 8; + ucPidAt* = 0; + ucPidLen* = 0; + ucUidAt* = 4; + ucUidLen* = 4; + msghdrLen* = 48; + msgIovAt* = 16; + msgIovlenAt* = 24; + msgIovlenLen* = 8; + msgControlAt* = 32; + msgControllenAt* = 40; + msgControllenLen* = 4; + cmsgLenAt* = 0; + cmsgLenLen* = 4; + cmsgLevelAt* = 4; + cmsgTypeAt* = 8; + cmsgDataAt* = 12; + cmsgAlign* = 4; + (* signals, sigaction and sigprocmask *) + sigHup* = 1; + sigInt* = 2; + sigQuit* = 3; + sigFpe* = 8; + sigKill* = 9; + sigUsr1* = 30; + sigSegv* = 11; + sigUsr2* = 31; + sigPipe* = 13; + sigAlrm* = 14; + sigTerm* = 15; + sigChld* = 20; + sigCont* = 19; + sigStop* = 17; + sigTstp* = 18; + sigTtin* = 21; + sigTtou* = 22; + sigWinch* = 28; + sigMax* = 31; + sigactionLen* = 16; + saHandlerAt* = 0; + saMaskAt* = 8; + saFlagsAt* = 12; + saFlagsLen* = 4; + sigsetLen* = 4; + saRestart* = 2; + sigSetmask* = 3; + (* limits, time used, and wait *) + rlimitCpu* = 0; + rlimitFsize* = 1; + rlimitData* = 2; + rlimitStack* = 3; + rlimitCore* = 4; + rlimitNproc* = 7; + rlimitNofile* = 8; + rlimitAs* = 5; + rlimInfinity* = 9223372036854775807; + rusageSelf* = 0; + rusageChildren* = -1; + ruUtimeAt* = 0; + ruStimeAt* = 16; + tvSecAt* = 0; + tvSecLen* = 8; + tvUsecAt* = 8; + tvUsecLen* = 4; + wNohang* = 1; + wUntraced* = 2; + (* errnos: EINTR; and each POSIX names, the C library's number, then Linux's *) + eIntr* = 4; + errnos*: [152]I32 = [ + 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 35, 11, 12, 12, + 13, 13, 14, 14, 16, 16, 17, 17, 18, 18, 19, 19, + 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, + 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31, + 32, 32, 33, 33, 34, 34, 11, 35, 63, 36, 77, 37, + 78, 38, 66, 39, 62, 40, 91, 42, 90, 43, 97, 67, + 100, 71, 95, 72, 94, 74, 84, 75, 92, 84, 38, 88, + 39, 89, 40, 90, 41, 91, 42, 92, 43, 93, 45, 95, + 102, 95, 47, 97, 48, 98, 49, 99, 50, 100, 51, 101, + 52, 102, 53, 103, 54, 104, 55, 105, 56, 106, 57, 107, + 60, 110, 61, 111, 65, 113, 37, 114, 36, 115, 70, 116, + 69, 122, 89, 125, 105, 130, 104, 131]; + +extern proc __error: ^I32; +extern proc close(fd: I32): I32; +extern proc getdtablesize: I32; + +(* errno, this thread's *) +proc errno*: ^I32; +begin + return __error(); +end; + +(* Closes the fds from lo to hi, or every one from lo if hi < 0: one + by one, as macOS has no close_range. *) +proc closeFrom*(lo, hi: INT); +var fd: INT; +begin + if hi < 0 then hi := INT(getdtablesize()) - 1; end; + for fd := lo to hi do _ := close(I32(fd)); end; +end; + +end CAbi. diff --git a/lib/Rt.darwin-arm64.raz b/lib/Rt.darwin-arm64.raz new file mode 100644 index 0000000..bda5d05 --- /dev/null +++ b/lib/Rt.darwin-arm64.raz @@ -0,0 +1,93 @@ +(* The run time, for macOS on arm64: for now the least a program needs + to end, with lib/Rt.raz's interface, which every file of Rt keeps. + The compiler finds exit, fail and cExit by these names. exit runs + the procedure atExit registered, then ends the program by C's exit, + which the entry point gives cExit, as every program on a Mac reaches + the kernel through libSystem; fail and stop say what failed and end + it with status 2. It leaves out what lib/Rt.raz does on Linux, which + PLAN.md 5's step 7 brings here: more than one procedure at exit, the + places a failure is told by, the signals' handlers, the trace of + calls and the profiler; place, trace and startProfile do nothing. *) +module Rt; +import SYSTEM; + +const + Full*: ERROR = "too many procedures to run at exit"; (* atExit's *) + Failed = "raz: a check failed\n"; + +extern proc write(fd: I32; buf: ^U8; n: UINT): INT; + +var + atExitProc: proc; (* the procedure atExit registered, or nil *) + ending: INT; (* the status exit was given, once it has been *) + cExit: proc(status: I32); (* C's exit, set first thing *) + placer: proc(a: UINT); (* place, set first thing, or nil under raz -s *) + profiler: proc; (* startProfile, set first thing, or nil *) + +(* Registers p to run when the program ends by exit: one, for now *) +proc atExit*(p: proc): ERROR; +begin + if atExitProc # nil then return Full; end; + atExitProc := p; + return nil; +end; + +(* The status exit was given, while the procedure atExit registered + runs; 0 before *) +proc exitStatus*: INT; +begin + return ending; +end; + +(* Runs the procedure atExit registered, taken off first so that it + runs once, then ends the program with status *) +proc exit*(status: INT); +var p: proc; +begin + ending := status; + if atExitProc # nil then + p := atExitProc; + atExitProc := nil; + p(); + end; + cExit(I32(status)); +end; + +(* Says msg, and then a line feed, on standard error, then ends the + program by exit with status 2 *) +proc stop*(msg: []const U8); +begin + _ := write(2, SYSTEM.PTR(msg), UINT(LEN(msg))); + _ := write(2, SYSTEM.PTR("\n"), 1); + exit(2); +end; + +(* Where the code at address a comes from: not told yet *) +proc place*(a: UINT); +begin + _ := a; +end; + +(* The calls under way: not told yet *) +proc trace*; +begin +end; + +(* A check failed: the compiler's code calls this with what failed, + its values and where, none of which it tells yet *) +proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT); +begin + _ := what; _ := a; _ := b; _ := len; _ := name; _ := rdi; _ := rsi; + if placer # nil then placer(at); end; + _ := write(2, SYSTEM.PTR(Failed), LEN(Failed)); + exit(2); +end; + +(* The profiler: none yet *) +proc startProfile*; +begin +end; + +begin + _ := profiler; (* started here when RAZ_PROFILE is set, by step 7's Rt *) +end Rt. diff --git a/src/A64.raz b/src/A64.raz index 4234970..2281a62 100644 --- a/src/A64.raz +++ b/src/A64.raz @@ -25,8 +25,8 @@ Depends on: Scan, for errors and the assembler's symbols; Diag, for positions and text; Chunk, for the code buffer and fixups. - Leaves out: choosing instructions; that is Gen (Gen.arm64.raz, to - come). Only what Gen and the library's code procedures need is here; + Leaves out: choosing instructions; that is Gen (Gen.arm64.raz, which + calls it). Only what Gen and the library's code procedures need is here; `db` and `dd` give any other instruction. *) module A64; import Out, Fmt, Str, Diag, Scan, Chunk; @@ -75,14 +75,9 @@ Nop = 0D503201FH; type - (* The parser's reader of an integer constant in a code procedure: a - whole expression, or, when whole is false, a single factor *) - ConstFn* = proc(whole: BOOL): (I64, ERROR); - - (* The parser's reader of a name that stands for an address: a - procedure or a module variable. Its chunk, the name read; or -1, - nothing read, if the name is anything else *) - NameFn* = proc: (INT, ERROR); + (* The parser's readers of a constant and of a name (Scan says) *) + ConstFn* = Scan.ConstFn; + NameFn* = Scan.NameFn; (* The text of the instruction that starts at at, for the listing *) Said = record diff --git a/src/Chunk.raz b/src/Chunk.raz index ad78165..4e91125 100644 --- a/src/Chunk.raz +++ b/src/Chunk.raz @@ -35,6 +35,8 @@ realsAt*: Diag.Pos; saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *) saveAt*: INT; (* ... at this offset from the frame, one quadword each *) + missing*: []const U8; (* code: what the target's Gen can't make yet, first at missingAt; "" if none *) + missingAt*: Diag.Pos; end; (* A place in the source whose code starts at a place in text: for @@ -64,8 +66,7 @@ by the size a load or store reads from its own bits (31 and 30, or 16 for a q register), as ARM64_RELOC_PAGEOFF12 is - Link patches only fxRel32 yet: arm64's come with Exe.darwin.raz - (PLAN.md 5, step 6). *) + Link patches them all. *) FixKind* = (fxRel32, fxBranch26, fxPage21, fxPageOff12); Fixup* = record @@ -97,6 +98,11 @@ curChunk*: INT; (* the chunk of code being written *) varNotes*: ^VarNote; numVarNotes*: INT; + (* What fills the gaps between procedures in text, Gen's (setPad): a + word of four bytes, the byte at an offset that is i more than a + multiple of 4 its byte i, a trap if it were ever run: int3, CC, + on x86, brk on arm64 *) + pad*: INT; codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT; @@ -185,8 +191,8 @@ (* code is aligned to 32 bytes, the windows in which x86 fetches and caches it, so that a procedure's loops sit in them the same way whatever comes before: rat ran 5% slower at 16, by where its loops - fell. Padded with CC, x86's int3: a trap if it were ever run *) - while pc & 31 # 0 do put1(0CCH); end; + fell. Padded with Gen's trap (pad) *) + while pc & 31 # 0 do put1(pad shr (8 * (pc & 3))); end; curChunk := c; chunks[c].start := pc; chunks[c].align := 32; @@ -356,6 +362,21 @@ begin chunks[c].reals := true; chunks[c].realsAt := p; +end; + +(* Chunk c holds code its Gen can't make yet, what, the first at p: an + error if c is live (Raz), as a program can't use what isn't made *) +proc setMissing*(c: INT; what: []const U8; p: Diag.Pos); +begin + if LEN(chunks[c].missing) = 0 then + chunks[c].missing := what; + chunks[c].missingAt := p; + end; +end; + +proc setPad*(word: INT); +begin + pad := word; end; proc setSaves*(c, mask, at: INT); diff --git a/src/Exe.darwin.raz b/src/Exe.darwin.raz new file mode 100644 index 0000000..0865f38 --- /dev/null +++ b/src/Exe.darwin.raz @@ -0,0 +1,458 @@ +(* Exe: the executable file, for macOS on arm64: Mach-O. + + Exe.linux.raz, for Linux, is ELF; a target has one Exe, chosen by the + suffix of its file (doc/raz.md, 3), and no other unit knows the + format. This one writes a Mach-O executable as dyld, macOS's dynamic + loader, takes one, and the kernel runs one on arm64: + + the header and load commands + __PAGEZERO 4 GB at address 0, no access: arm64 macOS runs no + program without it, so a nil pointer faults + __TEXT the header again, and the code, read and run + __DATA_CONST rodata, made read-only once dyld has moved the + addresses in it (rebases) + __DATA the variables, zeros, and C's symbols' quadwords, which + dyld fills in (binds) + __LINKEDIT what dyld reads, unmapped by the program: the rebases + and binds, the symbol table, and the code signature + + Each segment starts on a page of 16 KB, in the file as in memory, at + its offset in the file from __TEXT's address (Link.setPaged). macOS + loads a program at an address of its own choosing (MH_PIE), so every + address held in data is listed for dyld to move with it: those in + rodata, which Link lists (Link.rebases); code makes its addresses by + adrp from its own. Every program is linked to libSystem, through + which a Mac's program reaches the kernel; C's symbols are bound from + it, as Linux's GLOB_DAT does it, into quadwords the code reads. The + rebases and binds are dyld's opcodes (LC_DYLD_INFO_ONLY), the + plainest form dyld still takes: a few bytes for each address, where + chained fixups would thread them through the data with tables to say + where each chain starts. arm64 macOS runs nothing unsigned, so the + file ends with an ad-hoc code signature: a SHA-256 hash of each of + its pages of 4 KB, in a CodeDirectory, which the kernel checks as it + maps them. + + Depends on: Link for the images and addresses, Chunk for the chunks, + Scan for names and memory, Diag for errors, Host to write the file. + Leaves out: line numbers (DWARF, in __DWARF, PLAN.md 5), libraries + besides libSystem, an export trie (the program exports nothing). + + Exported variables can't be set from outside, so needLib, setMusl, + setMainPath and setStripped do it. *) +module Exe; +import Host, Fmt, Diag, Scan, Chunk, Link; +import SYSTEM; + +const + Os* = "darwin"; (* the target's operating system, as a file's suffix says it *) + Base = 100000000H; (* __TEXT's address, past __PAGEZERO; dyld moves it *) + Page = 4000H; (* arm64 macOS's page, 16 KB, on which each segment starts *) + HashPage = 1000H; (* the signature hashes pages of 4 KB *) + Dyld = "/usr/lib/dyld"; + (* room for the header and the most load commands: see write *) + HeaderRoom = 32 + 72 + 3 * 152 + 72 + 48 + 24 + 80 + 32 + 24 + 24 + 24 + 56 + 16; + +var + needed: [32]INT; (* the libraries to load, names interned *) + numNeeded*: INT; + stripped*: BOOL; (* -s: no symbols *) + libc*: []const U8; (* the C library, libSystem *) + + buf: ^U8; + len, cap: INT; + +(* The library name, to be loaded, unless it is already: false if there + are too many *) +proc needLib*(name: INT): BOOL; +var i: INT; +begin + for i := 0 to numNeeded - 1 do + if needed[i] = name then return true; end; + end; + if numNeeded = 32 then return false; end; + needed[numNeeded] := name; + INC(numNeeded); + return true; +end; + +proc noLibs*; +begin + numNeeded := 0; +end; + +(* -libc chooses Linux's C library; a Mac has one, libSystem *) +proc setMusl*(yes: BOOL); +begin + if yes then Diag.fatal("-libc musl: a program for macOS is linked to libSystem"); end; +end; + +(* The main module's file, which line numbers will name *) +proc setMainPath*(path: []const U8); +begin + _ := path; +end; + +proc setStripped*(yes: BOOL); +begin + stripped := yes; +end; + +proc room(n: INT); +begin + if len + n > cap then + buf := Scan.regrab(buf, len, cap * 2 + n); + cap := cap * 2 + n; + end; +end; + +(* The n low bytes of v, least significant first, as Mach-O is *) +proc putN(v: INT; n: INT); +var i: INT; +begin + room(n); + for i := 0 to n - 1 do + buf[len] := U8(v & 0FFH); + v := v shr 8; + INC(len); + end; +end; + +(* The n low bytes of v, most significant first, as the signature is *) +proc putBE(v: INT; n: INT); +var i: INT; +begin + for i := n - 1 to 0 by -1 do putN(v shr (8 * i), 1); end; +end; + +proc putBytes(p: ^U8; n: INT); +begin + room(n); + if n > 0 then COPY(buf[len..len + n], p[0..n]); end; + len := len + n; +end; + +proc padTo(off: INT); +begin + while len < off do putN(0, 1); end; +end; + +(* s and a zero byte *) +proc putStr(s: []const U8); +begin + putBytes(SYSTEM.PTR(s), LEN(s)); + putN(0, 1); +end; + +(* s in a field of n bytes, the rest zeros, as a segment's name *) +proc putName(s: []const U8; n: INT); +var at: INT; +begin + at := len; + putBytes(SYSTEM.PTR(s), LEN(s)); + padTo(at + n); +end; + +(* LEB128, unsigned, as dyld's opcodes take their operands *) +proc putU(v: INT); +begin + while v >= 80H do + putN(v & 7FH | 80H, 1); + v := v shr 7; + end; + putN(v, 1); +end; + +(* n, up to a multiple of m *) +proc roundUp(n, m: INT): INT; +begin + return (n + m - 1) div m * m; +end; + +(* SHA-256 (FIPS 180-4), for the signature's hashes: the message in + blocks of 64 bytes, the last ones padded with a one bit, zeros and + the message's length in bits *) + +const + (* the first 32 bits of the cube roots of the first 64 primes *) + K: [64]U32 = [ + 0428A2F98H, 071374491H, 0B5C0FBCFH, 0E9B5DBA5H, 03956C25BH, 059F111F1H, 0923F82A4H, 0AB1C5ED5H, + 0D807AA98H, 012835B01H, 0243185BEH, 0550C7DC3H, 072BE5D74H, 080DEB1FEH, 09BDC06A7H, 0C19BF174H, + 0E49B69C1H, 0EFBE4786H, 00FC19DC6H, 0240CA1CCH, 02DE92C6FH, 04A7484AAH, 05CB0A9DCH, 076F988DAH, + 0983E5152H, 0A831C66DH, 0B00327C8H, 0BF597FC7H, 0C6E00BF3H, 0D5A79147H, 006CA6351H, 014292967H, + 027B70A85H, 02E1B2138H, 04D2C6DFCH, 053380D13H, 0650A7354H, 0766A0ABBH, 081C2C92EH, 092722C85H, + 0A2BFE8A1H, 0A81A664BH, 0C24B8B70H, 0C76C51A3H, 0D192E819H, 0D6990624H, 0F40E3585H, 0106AA070H, + 019A4C116H, 01E376C08H, 02748774CH, 034B0BCB5H, 0391C0CB3H, 04ED8AA4AH, 05B9CCA4FH, 0682E6FF3H, + 0748F82EEH, 078A5636FH, 084C87814H, 08CC70208H, 090BEFFFAH, 0A4506CEBH, 0BEF9A3F7H, 0C67178F2H]; + +type Hash = [8]U32; + +(* Mixes the 64 bytes p into the running hash h *) +proc block(var h: Hash; p: []const U8); +var w: [64]U32; v: Hash; t1, t2: U32; i: INT; +begin + for i := 0 to 15 do + w[i] := (U32(p[4 * i]) shl 24) | (U32(p[4 * i + 1]) shl 16) | (U32(p[4 * i + 2]) shl 8) | U32(p[4 * i + 3]); + end; + for i := 16 to 63 do + w[i] := w[i - 16] + (ROR(w[i - 15], 7) xor ROR(w[i - 15], 18) xor (w[i - 15] shr 3)) + + w[i - 7] + (ROR(w[i - 2], 17) xor ROR(w[i - 2], 19) xor (w[i - 2] shr 10)); + end; + v := h; (* a to h, as the standard names them, are v[0] to v[7] *) + for i := 0 to 63 do + t1 := v[7] + (ROR(v[4], 6) xor ROR(v[4], 11) xor ROR(v[4], 25)) + ((v[4] & v[5]) xor (~v[4] & v[6])) + K[i] + w[i]; + t2 := (ROR(v[0], 2) xor ROR(v[0], 13) xor ROR(v[0], 22)) + ((v[0] & v[1]) xor (v[0] & v[2]) xor (v[1] & v[2])); + v[7] := v[6]; v[6] := v[5]; v[5] := v[4]; v[4] := v[3] + t1; + v[3] := v[2]; v[2] := v[1]; v[1] := v[0]; v[0] := t1 + t2; + end; + for i := 0 to 7 do h[i] := h[i] + v[i]; end; +end; + +(* The SHA-256 of data, its 32 bytes put at the end of buf *) +proc putHash(data: []const U8); +var h: Hash; tail: [128]U8; whole, rest, n, i: INT; +begin + h := [06A09E667H, 0BB67AE85H, 03C6EF372H, 0A54FF53AH, 0510E527FH, 09B05688CH, 01F83D9ABH, 05BE0CD19H]; + whole := LEN(data) div 64 * 64; + for i := 0 to whole - 64 by 64 do block(h, data[i..i + 64]); end; + rest := LEN(data) - whole; + FILL(tail, 0); + COPY(tail[0..rest], data[whole..LEN(data)]); + tail[rest] := 80H; + n := 64; + if rest >= 56 then n := 128; end; + for i := 0 to 7 do tail[n - 1 - i] := U8(((LEN(data) * 8) shr (8 * i)) & 0FFH); end; + for i := 0 to n - 64 by 64 do block(h, tail[i..i + 64]); end; + for i := 0 to 7 do putBE(INT(h[i]), 4); end; +end; + +(* Load commands *) + +const + LcSegment = 19H; LcSymtab = 2H; LcDysymtab = 0BH; LcLoadDylinker = 0EH; LcLoadDylib = 0CH; + LcUuid = 1BH; LcBuildVersion = 32H; LcMain = 80000028H; LcDyldInfoOnly = 80000022H; + LcCodeSignature = 1DH; + +(* A segment of 64 bits, followed by its nsects sections; prot is the + access, 1 read, 2 write, 4 run *) +proc segment(name: []const U8; adr, vmSize, off, fileSize, prot, nsects, flags: INT); +begin + putN(LcSegment, 4); putN(72 + 80 * nsects, 4); + putName(name, 16); + putN(adr, 8); putN(vmSize, 8); (* where it is loaded, and its size there *) + putN(off, 8); putN(fileSize, 8); (* where it is in the file, and its size there *) + putN(prot, 4); putN(prot, 4); (* the most access it may have, and what it has *) + putN(nsects, 4); putN(flags, 4); +end; + +(* A section, what otool and lldb see of a segment: its name, its + segment's, address, size, file offset, alignment as a power of two, + no relocations, flags *) +proc section(name, seg: []const U8; adr, size, off, align, flags: INT); +begin + putName(name, 16); putName(seg, 16); + putN(adr, 8); putN(size, 8); + putN(off, 4); putN(align, 4); + putN(0, 4); putN(0, 4); (* relocations: none *) + putN(flags, 4); + putN(0, 12); (* reserved *) +end; + +(* Whether chunk c is a live C symbol, and a live chunk with a name the + symbol table gives *) +proc isExt(c: INT): BOOL; +begin + return Chunk.chunks[c].live and Chunk.chunks[c].ext; +end; + +proc isNamed(c: INT): BOOL; +begin + return not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext; +end; + +proc write*(path: []const U8; entry: INT); +var + c, i, n, textSize, leOff, leAdr, ncmds, segRo, segData, sectData: INT; + rebaseOff, rebaseSize, bindOff, bindSize, symOff, nsyms, strOff, strSize, sigOff, sigSize, slots: INT; + ident: []const U8; + uuidAt, end0, sigRoom: INT; +begin + if Link.base # 400000H then Diag.fatal("-base: macOS loads a program where it chooses"); end; + for i := 1 to numNeeded - 1 do + Diag.fatal(Diag.say("not yet on darwin-arm64: a library besides libSystem, {}", [Fmt.str(Scan.nameOf(needed[i]))])); + end; + cap := 1 shl 16; + buf := Scan.grab(cap); + len := 0; + Link.setBase(Base); + Link.setPaged(Page); + Link.linkAll(HeaderRoom, 0, 0); + textSize := roundUp(Link.textOff + Link.textSize, Page); (* __TEXT's, the header in it *) + leOff := Link.bssOff; (* the next page in the file: __DATA has no bytes there *) + leAdr := Link.bssAdr + roundUp(Link.bssSize, Page); + (* the segments' numbers, as the opcodes name them, and the + sections', as the symbols do: __PAGEZERO 0, __TEXT 1 (__text, 1) *) + segRo := 2; + segData := 2; + sectData := 2; + if Link.roSize > 0 then INC(segData); INC(sectData); end; + + (* the code and rodata, after the room for the header *) + padTo(Link.textOff); + putBytes(Link.textImg, Link.textSize); + padTo(Link.roOff); + putBytes(Link.roImg, Link.roSize); + padTo(leOff); + + (* rebases: each word in rodata that holds an address, a pointer + (type 1), at its segment and offset; then done *) + rebaseOff := len; + putN(11H, 1); (* REBASE_OPCODE_SET_TYPE_IMM, pointer *) + for i := 0 to Link.numRebases - 1 do + putN(20H | segRo, 1); putU(Link.rebases[i] - Link.roAdr); (* SET_SEGMENT_AND_OFFSET_ULEB *) + putN(51H, 1); (* DO_REBASE_IMM_TIMES, once *) + end; + putN(0, 1); (* DONE *) + padTo(roundUp(len, 8)); + rebaseSize := len - rebaseOff; + + (* binds: each C symbol's quadword, from library 1, libSystem, by + its name, which in Mach-O begins with _ *) + bindOff := len; + putN(11H, 1); (* BIND_OPCODE_SET_DYLIB_ORDINAL_IMM, 1 *) + putN(51H, 1); (* SET_TYPE_IMM, pointer *) + for c := 0 to Chunk.numChunks - 1 do + if isExt(c) then + putN(40H, 1); (* SET_SYMBOL_TRAILING_FLAGS_IMM, none *) + putN(INT('_'), 1); putStr(Scan.nameOf(Chunk.chunks[c].name)); + putN(70H | segData, 1); putU(Chunk.chunks[c].adr - Link.bssAdr); (* SET_SEGMENT_AND_OFFSET_ULEB *) + putN(90H, 1); (* DO_BIND *) + end; + end; + putN(0, 1); (* DONE *) + padTo(roundUp(len, 8)); + bindSize := len - bindOff; + + (* the symbol table: a local symbol (N_SECT, 0EH) for each named + live chunk, nlist_64: its name's offset, type, section, no + description, its address; the names follow, after a 0 *) + symOff := len; + nsyms := 0; + strSize := 1; + for c := 0 to Chunk.numChunks - 1 do + if isNamed(c) then + putN(strSize, 4); + putN(0EH, 1); + match Chunk.chunks[c].sec of + | secText: putN(1, 1); + | secRodata: putN(2, 1); + | secBss: putN(sectData, 1); + end; + putN(0, 2); + putN(Chunk.chunks[c].adr, 8); + strSize := strSize + LEN(Chunk.chunkName(c)) + 1; + INC(nsyms); + end; + end; + strOff := len; + putN(0, 1); + for c := 0 to Chunk.numChunks - 1 do + if isNamed(c) then putStr(Chunk.chunkName(c)); end; + end; + padTo(roundUp(len, 16)); + strSize := len - strOff; + + (* the signature's size: a SuperBlob of one blob, the CodeDirectory, + of 88 bytes, the program's name, and a hash of each page up to + the signature *) + sigOff := len; + i := LEN(path); + while (i > 0) and (path[i - 1] # '/') do DEC(i); end; + ident := path[i..LEN(path)]; + slots := roundUp(sigOff, HashPage) div HashPage; + sigSize := 12 + 8 + 88 + LEN(ident) + 1 + 32 * slots; + sigRoom := roundUp(sigSize, 16); + room(sigRoom); + + (* The header, in the room left for it, and the load commands. The + UUID, which names this build for lldb, is the first 16 bytes of + the hash of what follows the header. *) + end0 := len; + len := 0; + putN(0FEEDFACFH, 4); (* MH_MAGIC_64 *) + putN(0100000CH, 4); putN(0, 4); (* CPU_TYPE_ARM64, any of them *) + putN(2, 4); (* MH_EXECUTE *) + putN(0, 4); putN(0, 4); (* the commands' count and size, patched below *) + putN(200085H, 4); (* MH_PIE, TWOLEVEL, DYLDLINK, NOUNDEFS *) + putN(0, 4); + ncmds := 0; + segment("__PAGEZERO", 0, Base, 0, 0, 0, 0, 0); INC(ncmds); + segment("__TEXT", Base, textSize, 0, textSize, 5, 1, 0); INC(ncmds); + section("__text", "__TEXT", Base + Link.textOff, Link.textSize, Link.textOff, 5, 80000400H); (* instructions only *) + if Link.roSize > 0 then + (* SG_READ_ONLY, 10H: dyld takes write away once it has rebased *) + segment("__DATA_CONST", Link.roAdr, roundUp(Link.roSize, Page), Link.roOff, roundUp(Link.roSize, Page), 3, 1, 10H); INC(ncmds); + section("__const", "__DATA_CONST", Link.roAdr, Link.roSize, Link.roOff, 3, 0); + end; + if Link.bssSize > 0 then + segment("__DATA", Link.bssAdr, roundUp(Link.bssSize, Page), 0, 0, 3, 1, 0); INC(ncmds); + section("__bss", "__DATA", Link.bssAdr, Link.bssSize, 0, 3, 1); (* S_ZEROFILL *) + end; + segment("__LINKEDIT", leAdr, roundUp(sigOff + sigRoom - leOff, Page), leOff, sigOff + sigRoom - leOff, 1, 0, 0); INC(ncmds); + putN(LcDyldInfoOnly, 4); putN(48, 4); + putN(rebaseOff, 4); putN(rebaseSize, 4); putN(bindOff, 4); putN(bindSize, 4); + putN(0, 24); (* weak and lazy binds, exports: none *) + INC(ncmds); + putN(LcSymtab, 4); putN(24, 4); putN(symOff, 4); putN(nsyms, 4); putN(strOff, 4); putN(strSize, 4); INC(ncmds); + (* every symbol is local; none is defined for others or wanted *) + putN(LcDysymtab, 4); putN(80, 4); putN(0, 4); putN(nsyms, 4); putN(nsyms, 4); putN(0, 4); + putN(nsyms, 4); putN(0, 4); putN(0, 48); INC(ncmds); + putN(LcLoadDylinker, 4); putN(32, 4); putN(12, 4); putName(Dyld, 20); INC(ncmds); + putN(LcUuid, 4); putN(24, 4); uuidAt := len; putN(0, 16); INC(ncmds); + putN(LcBuildVersion, 4); putN(24, 4); + putN(1, 4); putN(0B0000H, 4); putN(0B0000H, 4); putN(0, 4); (* macOS, 11.0 and up, SDK 11.0, no tools *) + INC(ncmds); + putN(LcMain, 4); putN(24, 4); putN(Chunk.chunks[entry].adr - Base, 8); putN(0, 8); INC(ncmds); + (* libSystem, version 1.0.0 and compatible with 1.0.0, which any is *) + n := roundUp(24 + LEN(libc) + 1, 8); + putN(LcLoadDylib, 4); putN(n, 4); putN(24, 4); putN(2, 4); putN(10000H, 4); putN(10000H, 4); + putName(libc, n - 24); INC(ncmds); + putN(LcCodeSignature, 4); putN(16, 4); putN(sigOff, 4); putN(sigRoom, 4); INC(ncmds); + if len > HeaderRoom then Diag.fatal("internal error: the Mach-O header outgrew its room"); end; + i := len; + len := 16; putN(ncmds, 4); putN(i - 32, 4); + len := end0; + putHash(buf[Link.textOff..sigOff]); + COPY(buf[uuidAt..uuidAt + 16], buf[len - 32..len - 16]); + len := sigOff; + + (* the signature, big-endian: the SuperBlob (CSMAGIC_EMBEDDED_SIGNATURE), + its length and count, the index of its one blob, the + CodeDirectory, at 20 *) + putBE(0FADE0CC0H, 4); putBE(sigSize, 4); putBE(1, 4); + putBE(0, 4); putBE(20, 4); (* CSSLOT_CODEDIRECTORY *) + putBE(0FADE0C02H, 4); putBE(sigSize - 20, 4); (* CSMAGIC_CODEDIRECTORY *) + putBE(20400H, 4); (* the version with the executable segment *) + putBE(20002H, 4); (* ad hoc, and the linker's: no identity behind it *) + putBE(88 + LEN(ident) + 1, 4); putBE(88, 4); (* where the hashes and the name are *) + putBE(0, 4); putBE(slots, 4); (* no special slots; a slot a page *) + putBE(sigOff, 4); (* what is hashed: all before the signature *) + putN(32, 1); putN(2, 1); putN(0, 1); putN(12, 1); (* SHA-256's 32 bytes; no platform; pages of 2^12 *) + putN(0, 4 + 4 + 4 + 4 + 8); (* no scatter, no team, a 32-bit limit *) + putBE(0, 8); putBE(textSize, 8); (* the executable segment: __TEXT, from 0 *) + putBE(1, 8); (* CS_EXECSEG_MAIN_BINARY *) + putStr(ident); + for i := 0 to slots - 1 do + n := (i + 1) * HashPage; + if n > sigOff then n := sigOff; end; + putHash(buf[i * HashPage..n]); + end; + padTo(sigOff + sigRoom); + + if not Host.writeExecutable(path, buf[0..len]) then + Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)])); + end; +end; + +begin + libc := "/usr/lib/libSystem.B.dylib"; +end Exe. diff --git a/src/Exe.linux.raz b/src/Exe.linux.raz index 94c8693..f7130d1 100644 --- a/src/Exe.linux.raz +++ b/src/Exe.linux.raz @@ -1,6 +1,6 @@ (* Exe: the executable file, for Linux: ELF. - Exe.darwin.raz, for macOS, will be Mach-O; a target has one Exe, chosen + Exe.darwin.raz, for macOS, is Mach-O; a target has one Exe, chosen by the suffix of its file (doc/raz.md, 3), and no other unit knows the format. This one writes an ELF64 executable: the ELF header, the program headers, the linked text and rodata, and section headers diff --git a/src/Gen.arm64.raz b/src/Gen.arm64.raz new file mode 100644 index 0000000..cfa2158 --- /dev/null +++ b/src/Gen.arm64.raz @@ -0,0 +1,1468 @@ +(* Gen: the code generator, for arm64 (Gen.arm64.raz; x86-64's is + Gen.x86_64.raz, the suffix of the file choosing, doc/raz.md, 3). + + The same stack machine as x86-64's, with the same calls, which Item + and Parse make: they push constants, addresses and the values of + variables, operate on the values on top, store them and jump on + them. This one is begun: what it makes so far is frames, constants, + the values of variables and their stores, the integer operations but + division, comparisons and jumps, elements and slices unchecked, + calls of procedures with integer arguments in registers, C's through + the quadword the loader fills in, code procedures and the program's + entry point. What else is + asked is noted as "not yet on arm64" (notYet), and a program that + uses it fails to compile rather than run wrong; PLAN.md 5 says the + pieces still to come. + + The stack is kept in registers as on x86-64: the value at depth d, + depth 0 being the bottom, is in x9 to x14, register d mod 6, all of + them registers a call may change and that carry no argument, so + that a call moves its arguments into x0 to x7 in any order. A value + that needs a register a lower one holds spills that one to a frame + slot. A constant, or an address in the frame or of a chunk, is only + noted until something needs it in a register. A variable's value is + loaded when it is pushed: no instruction of arm64 but a load or a + store takes memory. + + Registers outside the stack: x15 and x17, Gen's scratch, as rax and + rcx are on x86-64; x16, the encoder's (A64); x0 to x3 for copying + and slices, between calls, where they hold nothing; x8, which Apple's convention + keeps for the address of a result in memory; x18, the system's, + never touched; x19 to x23, a procedure's busiest variables (VarRegs), + which a called procedure gives back as it found them; x29, the frame + pointer, and x30, the return address. + + Calls use Apple's arm64 convention: the first eight integer arguments + in x0 to x7, results in x0 and x1, sp a multiple of 16 always, a + frame record of x29 and x30 that x29 points at, so that the chain of + frames can be followed. A frame is made whole by the prologue, so + nothing is pushed in a body: sp stays where the prologue put it, and + pushed is always 0. + + Depends on: Scan and Diag for errors, Sym for types, Chunk for code + and data, A64 for instructions. + Leaves out, for now: reals, division, checks, COPY and FILL, + arguments and parameters on the machine's stack, results in memory, + try, deferred statements, atomics and system calls. *) +module Gen; +import Fmt, Diag, Scan, Sym, Chunk, A := A64; +import SYSTEM; + +const + Arch* = "arm64"; (* the target's machine, as a file's suffix says it *) + NoLabel* = -1; + WordSize* = 8; (* the size of an address, and of INT *) + (* What the machine catches by itself: a load or store within + NilPage bytes of address 0 (the Mac's page zero is 4 GB; this is + Linux's figure until Rt tells the Mac's faults) *) + NilPage* = 4096; + + FP = A.FP; LR = A.LR; SP = A.SP; ZR = A.ZR; + T = 15; U = 17; (* Gen's scratch *) + Dst = 0; Src = 1; Tmp = 2; (* copying's *) + +type + Kind* = (kWord, kLong, kF32, kF64); + + (* Where a variable is: its address is relative to the frame, to a + chunk, to an address on the stack, or to one held in a frame slot *) + Base* = (bFrame, bGlobal, bStack, bSlot, bReg, bPtr); + Adr* = record + base*: Base; + chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register; + bPtr: the register that holds the address *) + off*: I64; (* added to the address; for bReg, which word, 0 or 8 *) + hi*: INT; (* bReg, a slice: the register of its length, the + second word; chunk is that of its pointer *) + end; + + (* The code made so far, to go back to for a second try at a body *) + CodeMark* = record pc*, fixups*, lines*, said*, fails*, exit*: INT; end; + + (* For entryPoint: the address of chunk, put in the variable whose + chunk is into before the program starts; or, for C's symbols, the + address in chunk, the quadword the loader fills in *) + Link* = record chunk*, into*: INT; end; + + CallInfo* = record + sig*: ^Sym.Type; + param*: ^Sym.Obj; (* the parameter the next argument is for *) + obj*: ^Sym.Obj; (* the procedure called, if it has a name *) + n*: INT; (* the arguments *) + isF*: [64]BOOL; (* ... goes in a real's register *) + pair*: [64]BOOL; (* ... is a slice's first word, the next its second *) + target*: I64; (* the frame slot of a procedure value, if chunk < 0 *) + chunk*: INT; (* else the procedure's chunk *) + ext*: BOOL; (* C's: called through the chunk holding its address *) + ret*: I64; (* set by call: the temporary a slice result is in *) + end; + +const + (* the registers a procedure keeps its busiest variables in, which a + called procedure saves and gives back (Apple's x19 to x28); the + trap report finds them where the prologue saved them *) + VarRegs*: [5]INT = [19, 20, 21, 22, 23]; + (* the registers the trap report can show a variable in: VarRegs; no + parameter is kept where it arrives, so the last two are none *) + ShownRegs*: [7]INT = [19, 20, 21, 22, 23, -1, -1]; + (* the registers of real variables, d8 to d15, which a call keeps, + numbered from XmmVar up so that they aren't taken for x8 to x15 *) + XmmVar* = 32; + XVarRegs*: [8]INT = [XmmVar + 8, XmmVar + 9, XmmVar + 10, XmmVar + 11, + XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15]; + (* a procedure's registers of variables, as bits: bit i is VarRegs[i], + bit XBit + i XVarRegs[i] *) + XBit* = 5; + +var + rtFail*, argcChunk*, argvChunk*: INT; + lost*: BOOL; (* never set here: no parameter is kept where it arrived *) + depth*: INT; (* the values on the stack *) + pushed*: INT; (* quadwords pushed on the machine's stack: always 0 *) + codeChunk*: INT; (* the procedure or body being compiled, or -1 *) + +type + (* where a value on the stack is *) + Loc = (lConst, (* not loaded: val is the value *) + lAdr, (* not loaded: the address of chunk, or of the frame + if chunk is -1, plus val *) + lReg, (* in its register *) + lFrame); (* spilled: in the frame slot val *) + + Entry = record + loc: Loc; + val: I64; + chunk: INT; (* lAdr: the chunk, or -1 for the frame *) + k: Kind; + end; + + (* A place in memory: off from register base, or, if chunk >= 0, off + into that chunk, reached by adrp (A64.loadChunk) *) + Mem = record base, chunk: INT; off: I64; end; + +const + MaxStack = 1024; (* values waiting in one expression *) + NumRegs = 6; + Regs: [NumRegs]INT = [9, 10, 11, 12, 13, 14]; + (* the condition codes of the comparisons, from sEql: = # < <= > >= *) + CcSigned: [6]INT = [A.ccEQ, A.ccNE, A.ccLT, A.ccLE, A.ccGT, A.ccGE]; + CcUnsigned: [6]INT = [A.ccEQ, A.ccNE, A.ccLO, A.ccLS, A.ccHI, A.ccHS]; + (* sub sp, sp, #imm12 and the same shifted by 12: the prologue's two, + whose immediates endProc patches *) + SubSp = 0D10003FFH; SubSp12 = 0D14003FFH; + +var + stack: [MaxStack]Entry; + owner: [NumRegs]INT; (* the value in each register, or -1 *) + frameTop, frameMax, permTop: I64; + frameFix: INT; (* where the frame's two subs are *) + paramTop: I64; (* the parameters' slots end here *) + zeroTop: I64; (* the locals the prologue zeroes end here *) + retSlot: I64; + resType: ^Sym.Type; (* the procedure's result, or nil *) + exitL: INT; + (* parameters arriving in registers: where each is stored on entry *) + inReg: [8]INT; + inSlot: [8]I64; + inSize: [8]INT; + inObj: [8]^Sym.Obj; + numIn: INT; + regMask: INT; (* the registers of variables, as bits (XBit) *) + saveAt: I64; (* where they are saved, a quadword each *) + frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *) + pending: []const U8; (* what beginProc found not yet made, for enterBody's chunk *) + pendingAt: Diag.Pos; + +(* What this Gen can't make yet marks the procedure being compiled + (Chunk.setMissing), which is an error if the program uses it, and the + compile reads on: a module the program imports may hold what it never + calls, as Sys does. So each routine not yet made keeps the stack as + the real one would, and makes what code it likes, never run; it + reads into _ the parameters it doesn't use yet, so that none is + warned of. *) +proc notYetAt(what: []const U8; p: Diag.Pos); +begin + if codeChunk >= 0 then + Chunk.setMissing(codeChunk, Diag.say("not yet on arm64: {}", [Fmt.str(what)]), p); + elsif LEN(pending) = 0 then (* beginProc's, before enterBody names the chunk *) + pending := Diag.say("not yet on arm64: {}", [Fmt.str(what)]); + pendingAt := p; + end; +end; + +(* The same, at the place being read *) +proc notYet(what: []const U8); +begin + notYetAt(what, Scan.tokPos()); +end; + +(* -S: the text of each instruction is kept, and list prints it *) +proc setListing*(yes: BOOL); +begin + A.setListing(yes); +end; + +proc list*(home: INT); +begin + A.list(home); +end; + +(* A variable changed in place, x := x + e, is x86-64's; here it is + loaded and stored as any other *) +proc setInPlace*(r: INT); +begin + _ := r; +end; + +proc kindOf*(t: ^Sym.Type): Kind; +begin + if t^.form = Sym.fReal then + if t^.size = 4 then return kF32; end; + return kF64; + end; + if t^.size > WordSize then return kLong; end; + return kWord; +end; + +(* The stack *) + +proc isReal(i: INT): BOOL; +begin + return stack[i].k in {kF32, kF64}; +end; + +proc allocTemp*(size, align: I64): I64; forward; +proc allocPerm*(size, align: I64): I64; forward; +proc loaded(i: INT): INT; forward; + +(* The value i, in its register, goes to a frame slot *) +proc spill(i: INT); +var s: I64; +begin + _ := loaded(i); + s := allocTemp(8, 8); + A.store(Regs[i mod NumRegs], FP, INT(s), 8); + stack[i].loc := lFrame; + stack[i].val := s; + owner[i mod NumRegs] := -1; +end; + +(* Every value below depth d in a register, spilled, as a call may + change them *) +proc spillBelow(d: INT); +var r: INT; +begin + for r := 0 to NumRegs - 1 do + if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end; + end; +end; + +(* The register of value i, for it to hold: a lower value there is + spilled *) +proc claim(i: INT): INT; +var r: INT; +begin + r := i mod NumRegs; + if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end; + owner[r] := i; + return Regs[r]; +end; + +(* The value i into register r, from wherever it is; it stays where it + was, so r is a new copy *) +proc valueTo(i, r: INT); +begin + match stack[i].loc of + | lConst: A.movRI(r, stack[i].val); + | lAdr: + if stack[i].chunk >= 0 then A.addrChunk(r, stack[i].chunk, INT(stack[i].val)); + else A.aluI(A.opAdd, r, FP, stack[i].val); end; + | lReg: if Regs[i mod NumRegs] # r then A.movRR(r, Regs[i mod NumRegs]); end; + | lFrame: A.load(r, FP, INT(stack[i].val), 8, false); + end; +end; + +(* The value i, in its register *) +proc loaded(i: INT): INT; +var r: INT; +begin + if stack[i].loc # lReg then + r := claim(i); + valueTo(i, r); + stack[i].loc := lReg; + end; + return Regs[i mod NumRegs]; +end; + +proc top: INT; +begin + if depth = 0 then Diag.fatal("internal error: the stack is empty"); end; + return loaded(depth - 1); +end; + +(* A value on the stack's top; at its last place the compile ends, as on + x86-64 *) +proc newEntry(k: Kind; loc: Loc; v: I64); +begin + if depth > LEN(stack) - 1 then + _ := Scan.mark(Diag.say("more than {} values waiting in one expression", [Fmt.int(MaxStack)])); + Diag.finish(); + return; + end; + stack[depth].k := k; + stack[depth].loc := loc; + stack[depth].val := v; + stack[depth].chunk := -1; + INC(depth); +end; + +(* The register a new value on top is computed in *) +proc target: INT; +begin + return claim(depth); +end; + +(* The value just computed in target goes on top *) +proc computed(k: Kind); +begin + newEntry(k, lReg, 0); +end; + +(* drop emits no code, and the dropped value's register holds it until + the next push claims it, which place and operands rely on *) +proc drop*; +begin + DEC(depth); + if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end; +end; + +proc popTo(r: INT); +begin + valueTo(depth - 1, r); + drop(); +end; + +proc topConst: (BOOL, I64); +begin + return stack[depth - 1].loc = lConst, stack[depth - 1].val; +end; + +proc resetStack*(d, p: INT); +var r: INT; +begin + depth := d; + pushed := p; + for r := 0 to NumRegs - 1 do owner[r] := -1; end; +end; + +proc pushConst*(k: Kind; v: I64); +begin + if k in {kF32, kF64} then notYet("reals"); end; + newEntry(k, lConst, v); +end; + +(* The register of the word at a, a variable in registers: the + pointer's (off 0) or, for a slice, the length's (off 8) *) +proc regAt(a: Adr): INT; +begin + if a.off = 0 then return a.chunk; end; + return a.hi; +end; + +(* The memory a names. An address on the stack is popped, and is in its + register still; one in a slot is loaded into r. *) +proc place(a: Adr; r: INT): Mem; +var m: Mem; +begin + m.chunk := -1; + m.off := a.off; + match a.base of + | bFrame: m.base := FP; + | bGlobal: m.chunk := a.chunk; + | bStack: + if (stack[depth - 1].loc = lAdr) and (stack[depth - 1].chunk >= 0) then + m.chunk := stack[depth - 1].chunk; + m.off := m.off + stack[depth - 1].val; + elsif stack[depth - 1].loc = lAdr then + m.base := FP; + m.off := m.off + stack[depth - 1].val; + else + m.base := loaded(depth - 1); + end; + drop(); + | bPtr: m.base := a.chunk; + | bSlot: + A.load(r, FP, a.chunk, 8, false); + m.base := r; + | bReg: Diag.fatal("internal error: a register has no address"); + end; + return m; +end; + +(* Register r loaded from m, or stored there, size bytes *) +proc loadMem(r: INT; m: Mem; size: INT; signed: BOOL); +begin + if m.chunk >= 0 then A.loadChunk(r, m.chunk, INT(m.off), size, signed); + else A.load(r, m.base, INT(m.off), size, signed); end; +end; + +proc storeMem(r: INT; m: Mem; size: INT); +begin + if m.chunk >= 0 then A.storeChunk(r, m.chunk, INT(m.off), size); + else A.store(r, m.base, INT(m.off), size); end; +end; + +(* Register r := the address m *) +proc adrTo(r: INT; m: Mem); +begin + if m.chunk >= 0 then A.addrChunk(r, m.chunk, INT(m.off)); + elsif (m.off # 0) or (m.base # r) then A.aluI(A.opAdd, r, m.base, m.off); end; +end; + +(* The address a names, on top of the stack *) +proc pushAdr*(a: Adr); +var m: Mem; r: INT; +begin + if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *) + if a.base in {bFrame, bGlobal} then + newEntry(kWord, lAdr, a.off); + if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end; + return; + end; + (* With the address on the stack, place pops it first, so that target + may take its register; else target comes first, for place to load + a slot's pointer into *) + if a.base = bStack then + m := place(a, U); r := target(); + else + r := target(); m := place(a, r); + end; + adrTo(r, m); + computed(kWord); +end; + +proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind); +var m: Mem; r: INT; +begin + if k in {kF32, kF64} then notYet("reals"); end; + if a.base = bReg then + r := target(); + A.movRR(r, regAt(a)); + computed(k); + return; + end; + if a.base = bStack then + m := place(a, U); r := target(); + else + r := target(); m := place(a, r); + end; + loadMem(r, m, size, signed); + computed(k); +end; + +proc pushProc*(c: INT; ext: BOOL); +var r: INT; +begin + r := target(); + if ext then A.loadChunk(r, c, 0, 8, false); else A.addrChunk(r, c, 0); end; + computed(kWord); +end; + +(* Pops a value into the variable at a; an address on the stack is under + the value. A zero is stored from the zero register. *) +proc popVar*(a: Adr; size: INT); +var r: INT; v: I64; c: BOOL; +begin + if isReal(depth - 1) then notYet("reals"); end; + if a.base = bReg then + popTo(regAt(a)); + return; + end; + c, v := topConst(); + if c and (v = 0) then r := ZR; + elsif c then r := T; A.movRI(T, v); + else r := loaded(depth - 1); end; + drop(); + storeMem(r, place(a, U), size); +end; + +(* The two values on top change places, each loaded in its register *) +proc swap*; +var e: Entry; x, y: INT; +begin + x := loaded(depth - 2); + y := loaded(depth - 1); + A.movRR(T, x); + A.movRR(x, y); + A.movRR(y, T); + e := stack[depth - 2]; stack[depth - 2] := stack[depth - 1]; stack[depth - 1] := e; +end; + +(* Copying, by loads and stores of 8, 4, 2 and 1 bytes, from [x1] to + [x0], through x2 *) + +const MaxMoves = 256; + +proc copyBytes(size: I64); +var o, n: I64; +begin + if size > MaxMoves then notYet("a copy of more than 256 bytes"); return; end; + o := 0; + while o < size do + n := 8; + while n > size - o do n := n div 2; end; + A.load(Tmp, Src, INT(o), INT(n), false); + A.store(Tmp, Dst, INT(o), INT(n)); + INC(o, n); + end; +end; + +proc zeroBytes(size: I64); +var o, n: I64; +begin + if size > MaxMoves then notYet("zeroing more than 256 bytes"); return; end; + o := 0; + while o < size do + n := 8; + while n > size - o do n := n div 2; end; + A.store(ZR, Dst, INT(o), INT(n)); + INC(o, n); + end; +end; + +(* Pops a source's address, and a destination's under it, and copies + size bytes to off bytes past the destination *) +proc copyBlock*(size, off: I64); +begin + popTo(Src); + popTo(Dst); + if off # 0 then A.aluI(A.opAdd, Dst, Dst, off); end; + copyBytes(size); +end; + +(* Pops a source's address, and copies size bytes to a: for a slice in + registers, its two words into them *) +proc copyTo*(a: Adr; size: I64); +begin + popTo(Src); + if a.base = bReg then + A.load(a.chunk, Src, 0, 8, false); + A.load(a.hi, Src, 8, 8, false); + return; + end; + adrTo(Dst, place(a, Dst)); + copyBytes(size); +end; + +proc zeroVar*(a: Adr; size: I64); +begin + adrTo(Dst, place(a, Dst)); + zeroBytes(size); +end; + +(* Operations *) + +(* The right operand of the two values on top, popped, in register y: + its own, or U for a constant; the left one stays, in its register, + which is returned with y *) +proc operands: (INT, INT); +var v: I64; c: BOOL; y: INT; +begin + c, v := topConst(); + if c then A.movRI(U, v); y := U; else y := loaded(depth - 1); end; + drop(); + return top(), y; +end; + +(* The operation of two registers of +, -, &, | and xor *) +proc aluOf(sy: Scan.Sym): INT; +begin + match sy of + | sPlus: return A.opAdd; + | sMinus: return A.opSub; + | sAmp: return A.opAnd; + | sBar: return A.opOrr; + | else: return A.opEor; + end; +end; + +(* The two values on top, the left op the right, an integer of size + bytes, signed or not, computed in 64 bits and brought back to its + width, which is how a narrow integer wraps. A shift's count is taken + modulo the width, as x86-64's code takes it. *) +proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL); +var v: I64; r, y, bits, sh: INT; c, alu: BOOL; +begin + if k in {kF32, kF64} then notYet("reals"); end; + if (sy = Scan.sDiv) or (sy = Scan.sMod) then notYet("div and mod"); end; + bits := size * 8; + alu := (sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor); + (* a constant goes right, where it can be an immediate *) + if (alu and (sy # Scan.sMinus) or (sy = Scan.sTimes)) and (stack[depth - 2].loc = lConst) + and (stack[depth - 1].loc # lConst) then swap(); end; + if sy = Scan.sShl then sh := A.shLsl; elsif signed then sh := A.shAsr; else sh := A.shLsr; end; + c, v := topConst(); + if c and alu then + drop(); + r := top(); + A.aluI(aluOf(sy), r, r, v); + elsif c and ((sy = Scan.sShl) or (sy = Scan.sShr)) then + drop(); + r := top(); + A.shiftI(sh, r, r, INT(v & I64(bits - 1)), 8); + else + r, y := operands(); + if alu then + A.alu(aluOf(sy), r, r, y); + elsif sy = Scan.sTimes then + A.mul(r, r, y); + else (* sShl, sShr: the machine takes the count modulo 64 *) + if bits < 64 then A.aluI(A.opAnd, U, y, bits - 1); y := U; end; + A.shift(sh, r, r, y, 8); + end; + end; + if bits < 64 then A.extend(r, r, size, signed); end; + stack[depth - 1].k := k; +end; + +proc rotate*(left: BOOL; size: INT); +begin + _ := left; _ := size; + notYet("ROL and ROR"); + drop(); (* the count *) +end; + +proc countZeros*(leading: BOOL; size: INT); +begin + _ := leading; _ := size; + notYet("CLZ and CTZ"); +end; + +proc popCount*; +begin + notYet("POPCOUNT"); +end; + +proc abs*(k: Kind; size: INT); +begin + _ := k; _ := size; + notYet("ABS"); +end; + +(* The two values on top, compared: a BOOL, 1 or 0 *) +proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL); +var r, y, i: INT; +begin + if k in {kF32, kF64} then notYet("reals"); end; + i := INT(sy) - INT(Scan.sEql); + r, y := operands(); + A.cmp(r, y); + if signed then A.cset(CcSigned[i], r); else A.cset(CcUnsigned[i], r); end; + stack[depth - 1].k := kWord; +end; + +proc neg*(k: Kind; size: INT; signed: BOOL); +var r: INT; +begin + if k in {kF32, kF64} then notYet("reals"); end; + r := top(); + A.neg(r, r); + if size < 8 then A.extend(r, r, size, signed); end; +end; + +proc complement*(size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + A.mvn(r, r); + if size < 8 then A.extend(r, r, size, signed); end; +end; + +proc notBool*; +var r: INT; +begin + r := top(); + A.aluI(A.opEor, r, r, 1); +end; + +(* The integer on top, brought to size bytes *) +proc narrow*(size: INT; signed: BOOL); +var r: INT; +begin + r := top(); + if size < 8 then A.extend(r, r, size, signed); end; + stack[depth - 1].k := kWord; +end; + +proc intToReal*(k: Kind; big: BOOL); +begin + _ := big; + notYet("reals"); + stack[depth - 1].k := k; +end; + +proc realToInt*(k: Kind); +begin + _ := k; + notYet("reals"); + stack[depth - 1].k := kWord; +end; + +proc realToReal*(k: Kind); +begin + notYet("reals"); + stack[depth - 1].k := k; +end; + +proc compareSeq*(a, b: I64; shift: INT; eq: BOOL); +begin + _ := a; _ := b; _ := shift; _ := eq; + notYet("comparing slices"); + _ := target(); + computed(kWord); +end; + +(* An error points at its message's length, an 8-byte word, with the + text after it; nil is no error. Pops one, and makes the slice of its + message at tmp, empty for nil. *) +proc errorText*(tmp: I64); +var L: INT; +begin + popTo(T); + A.movRI(U, 0); + L := NoLabel; + A.cbz(false, T, L); + A.load(U, T, 0, 8, false); + A.aluI(A.opAdd, T, T, 8); + A.fixLink(L); + A.store(T, FP, INT(tmp), 8); + A.store(U, FP, INT(tmp) + 8, 8); +end; + +(* INC or DEC of the variable whose address is under the step on top; + its store cuts a narrow one to its width *) +proc incDec*(size: INT; signed, dec: BOOL); +var r, y, o: INT; +begin + if dec then o := A.opSub; else o := A.opAdd; end; + r, y := operands(); + drop(); + A.load(T, r, 0, size, signed); + A.alu(o, T, T, y); + A.store(T, r, 0, size); +end; + +(* INC or DEC of the variable in register r, by the value on top *) +proc incDecReg*(r, size: INT; signed, dec: BOOL); +var c: BOOL; v: I64; o: INT; +begin + if dec then o := A.opSub; else o := A.opAdd; end; + c, v := topConst(); + if c then A.aluI(o, r, r, v); else A.alu(o, r, r, loaded(depth - 1)); end; + drop(); + if size < 8 then A.extend(r, r, size, signed); end; +end; + +proc zeroNew*(size: I64); +begin + _ := size; + notYet("NEW"); +end; + +proc atomic*(which: INT); +begin + notYet("CAS, XCHG and XADD"); + if which = Sym.bCas then drop(); end; + drop(); + stack[depth - 1].k := kWord; +end; + +proc sysCall*(n: INT); +var i: INT; +begin + notYet("SYSCALL"); + for i := 1 to n do drop(); end; + _ := target(); + computed(kWord); +end; + +(* A barrier for every processor, dmb ish *) +proc fence*; +begin + A.dmb(); +end; + +(* Jumps. A label is the chain of the jumps to it, until it is placed + (A64). *) + +proc jump*(var L: INT); +begin + A.jmp(L); +end; + +(* Pops a BOOL, and jumps if it is when *) +proc jumpIf*(var L: INT; when: BOOL); +var r: INT; +begin + r := loaded(depth - 1); + drop(); + A.cbz(when, r, L); +end; + +(* Pops two integers, and jumps if the left op the right *) +proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT); +var r, y, i: INT; +begin + i := INT(sy) - INT(Scan.sEql); + r, y := operands(); + drop(); + A.cmp(r, y); + if signed then A.jcc(CcSigned[i], L); else A.jcc(CcUnsigned[i], L); end; +end; + +(* jumpCmp out of an expression: the values under the two compared are + spilled first, so that they are where the code after the landing + place expects them, whichever way it came (Gen.x86_64.raz says more) *) +proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT); +begin + spillBelow(depth - 2); + jumpCmp(sy, signed, L); +end; + +(* The two values on top, compared, as a BOOL: true unless notOp holds; + fj and tj, the chains of and, or and not, land on the 0 and the 1 *) +proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT); +var r, e: INT; +begin + jumpOut(notOp, signed, fj); + A.fixLink(tj); + r := target(); + A.movRI(r, 1); + e := NoLabel; + A.jmp(e); + A.fixLink(fj); + A.movRI(r, 0); + A.fixLink(e); + computed(kWord); +end; + +proc jumpBack*(top: INT); +begin + A.jmpBack(top); +end; + +proc fix*(L: INT); +begin + A.fixLink(L); +end; + +proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT; +begin + _ := slot; _ := lo; _ := n; _ := elseAt; _ := endL; + notYet("a jump table"); + return Chunk.pc; +end; + +(* The next entry of the table that jumpTable started at table *) +proc tableEntry*(table, target: INT); +begin + Chunk.put4(target - table); +end; + +(* A loop's start is aligned on x86-64, for its fetches; here it isn't *) +proc alignLoop*; +begin +end; + +proc joinJumps*(L1, L2: INT): INT; +begin + return A.joinLinks(L1, L2); +end; + +proc fixTo*(L, top: INT); +begin + A.fixLinkTo(L, top); +end; + +(* Checks, and what checks as it goes *) + +proc checkIndex*(n: I64; p: Diag.Pos); +begin + _ := n; + notYetAt("checks", p); +end; + +proc checkView*(n, below: I64; p: Diag.Pos); +begin + _ := n; _ := below; + notYetAt("checks", p); +end; + +proc checkEnum*(n: I64; name: INT; p: Diag.Pos); +begin + _ := n; _ := name; + notYetAt("checks", p); +end; + +proc checkNil*(reach: I64; p: Diag.Pos); +begin + _ := reach; + notYetAt("checks", p); +end; + +(* r times v, an element's size: by a shift where v is a power of two, + else through x3, free between calls as x0 to x2 are *) +proc mulI(r: INT; v: I64); +var n: INT; +begin + n := 0; + while (I64(1) shl n) < v do INC(n); end; + if (I64(1) shl n) = v then + if n > 0 then A.shiftI(A.shLsl, r, r, n, 8); end; + else + A.movRI(3, v); + A.mul(r, r, 3); + end; +end; + +(* Pops an index, and the address of the slice at a if it is on the + stack, and makes the address of the element it picks: the slice's + pointer plus the index times size *) +proc indexSlice*(a: Adr; size, room: I64; checked: BOOL; p: Diag.Pos); +var m: Mem; r: INT; +begin + if checked or (room > 0) then notYetAt("checks", p); end; + popTo(T); + mulI(T, size); + if a.base = bReg then + A.alu(A.opAdd, T, T, a.chunk); + else + m := place(a, U); + loadMem(U, m, 8, false); + A.alu(A.opAdd, T, T, U); + end; + r := target(); + A.movRR(r, T); + computed(kWord); +end; + +(* Pops an index, and a pointer under it, and makes the address of the + element it picks *) +proc indexPtr*(size: I64); +begin + mulI(top(), size); + op(Scan.sPlus, kWord, 8, false); +end; + +(* Pops an index, checked before, and makes the address of the element + it picks of the array at a *) +proc indexArray*(a: Adr; size: I64); +begin + mulI(top(), size); + pushAdr(a); + op(Scan.sPlus, kWord, 8, false); +end; + +(* Pops hi and lo, and the address of the array or slice at a if it is + on the stack, and makes the slice lo..hi of it, of elements of size + bytes, in the frame at tmp: its pointer, the start plus lo times size, + and its length, hi - lo *) +proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos); +var m: Mem; +begin + _ := n; + if checked then notYetAt("checks", p); end; + popTo(Tmp); (* hi *) + popTo(Src); (* lo *) + if a.base = bReg then + A.movRR(U, a.chunk); + else + m := place(a, U); + if isArray then adrTo(U, m); else loadMem(U, m, 8, false); end; + end; + A.alu(A.opSub, Tmp, Tmp, Src); + A.store(Tmp, FP, INT(tmp) + 8, 8); + mulI(Src, size); + A.alu(A.opAdd, U, U, Src); + A.store(U, FP, INT(tmp), 8); +end; + +proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos); +begin + _ := dOff; _ := sOff; _ := size; _ := checked; + notYetAt("COPY", p); +end; + +proc fillSlice*(dOff, size, n: I64; scalar: BOOL); +begin + _ := dOff; _ := size; _ := n; _ := scalar; + notYet("FILL"); + drop(); +end; + +(* Pops hi, lo and a pointer, and makes the slice p[lo..hi] at tmp *) +proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos); +begin + if checked then notYetAt("checks", p); end; + popTo(Tmp); (* hi *) + popTo(Src); (* lo *) + popTo(U); (* the pointer *) + A.alu(A.opSub, Tmp, Tmp, Src); + A.store(Tmp, FP, INT(tmp) + 8, 8); + mulI(Src, size); + A.alu(A.opAdd, U, U, Src); + A.store(U, FP, INT(tmp), 8); +end; + +(* Calls. The arguments are the c.n values on top, each moved into the + next of x0 to x7 just before the call; the values under them are + spilled first, as the call may change their registers. As the stack's + registers carry no argument, the moves may go in any order. A slice + goes as its two words, a record by value as the address of a copy + (Item makes it). A single result comes back in x0, two words in x0 + and x1: a slice is stored in the temporary c.ret, two results pushed + as two values. *) +proc call*(var c: CallInfo); +var res: ^Sym.Type; i, ni, first, r: INT; +begin + first := depth - c.n; + spillBelow(first); + res := c.sig^.base; + c.ret := 0; + if c.sig^.variadic then notYet("a call of a C procedure that takes ..."); end; + if (res # nil) and (Sym.holdsArray(res) or Sym.behindPointer(res)) then + notYet("a result in memory"); + c.ret := allocPerm(res^.size, res^.align); + elsif (res # nil) and (res^.form = Sym.fSlice) then + c.ret := allocTemp(res^.size, res^.align); + elsif (res # nil) and (res^.form = Sym.fReal) then + notYet("reals"); + end; + ni := 0; + for i := 0 to c.n - 1 do + if c.isF[i] then notYet("reals"); end; + if ni < 8 then valueTo(first + i, ni); else notYet("an argument past x7"); end; + INC(ni); + end; + for i := 1 to c.n do drop(); end; + if c.ext then + A.loadChunk(U, c.chunk, 0, 8, false); + A.callR(U); + elsif c.chunk >= 0 then + A.callChunk(c.chunk); + else + A.load(U, FP, INT(c.target), 8, false); + A.callR(U); + end; + if res # nil then + if res^.form = Sym.fSlice then + A.store(0, FP, INT(c.ret), 8); + A.store(1, FP, INT(c.ret) + 8, 8); + elsif Sym.inTwoRegs(res) then + A.movRR(target(), 0); computed(kWord); + A.movRR(target(), 1); computed(kWord); + elsif c.ret = 0 then + (* C leaves the bits above a narrow result as they fall *) + r := target(); + A.movRR(r, 0); + if res^.form = Sym.fBool then A.extend(r, r, 1, false); + elsif (res^.form = Sym.fInt) and (res^.size < 8) then A.extend(r, r, INT(res^.size), res^.signed); end; + computed(kindOf(res)); + end; + end; +end; + +(* Frames: a slot of size bytes, its offset from x29, negative. A + temporary is released at the end of its statement; allocPerm's lasts + the procedure. *) +proc allocTemp*(size, align: I64): I64; +begin + if align < 1 then align := 1; end; + frameTop := Sym.alignUp(frameTop + size, align); + if frameTop > frameMax then frameMax := frameTop; end; + return -frameTop; +end; + +proc allocPerm*(size, align: I64): I64; +var s: I64; +begin + s := allocTemp(size, align); + permTop := frameTop; + return s; +end; + +proc tempMark*: I64; +begin + return frameTop; +end; + +proc releaseTemps*(m: I64); +begin + if m < permTop then m := permTop; end; + frameTop := m; +end; + +proc keepTemps*; +begin + frameTop := frameMax; + permTop := frameMax; +end; + +(* The parameters' places: each in a frame slot of its own, stored there + from its register on entry. A var parameter, and a record or array + passed by value, holds an address (ind). *) +proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj); +var p: ^Sym.Obj; ni, k, w: INT; +begin + frameTop := 0; frameMax := 0; permTop := 0; + resetStack(0, 0); + exitL := NoLabel; + numIn := 0; + lost := false; + resType := sig^.base; + regMask := 0; + if (resType # nil) and Sym.behindPointer(resType) then + notYet("a result in memory"); + retSlot := allocPerm(8, 8); + end; + ni := 0; + p := params; + while p # nil do + p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice)); + k := 1; + if (p^.typ^.form = Sym.fSlice) and not p^.isVar then k := 2; end; + p^.val := allocPerm(8 * k, 8); + if (p^.typ^.form = Sym.fReal) and not p^.isVar or (ni + k > 8) then + notYet("a real parameter, or one past x7"); + k := 0; + end; + for w := 0 to k - 1 do (* a slice's two words, in two slots *) + inReg[numIn] := ni; inSlot[numIn] := p^.val + I64(8 * w); inObj[numIn] := p; + inSize[numIn] := 8; + if not p^.ind and (p^.typ^.form in {Sym.fInt, Sym.fBool, Sym.fEnum, Sym.fSet}) then inSize[numIn] := INT(p^.typ^.size); end; + INC(numIn); INC(ni); + end; + p := p^.next; + end; + paramTop := frameTop; +end; + +(* The frame as beginProc left it, with the parameters' slots only *) +proc resetLocals*; +begin + frameTop := paramTop; frameMax := paramTop; permTop := paramTop; +end; + +(* No parameter is kept where it arrived, as x86-64 keeps one in rdi or + rsi: each is stored on entry, or moved to its register variable *) +proc keepArrived*(o: ^Sym.Obj); +begin + _ := o; +end; + +proc keptIn*(o: ^Sym.Obj): BOOL; +begin + _ := o; + return false; +end; + +(* The locals in memory have their slots: the prologue zeroes those. The + registers of variables in mask are saved next, a quadword each, in + slots that need no zeroing; the frame as it then stands is where a + second try at the body starts. *) +proc useRegs*(mask: INT); +var i, k: INT; +begin + zeroTop := permTop; + regMask := mask; + k := 0; + for i := 0 to 4 do + if (mask & (1 shl i)) # 0 then INC(k); end; + end; + if k > 0 then saveAt := allocPerm(8 * k, 8); end; + frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop; +end; + +proc xHome*(r: INT; slot: I64); +begin + _ := r; _ := slot; +end; + +proc markCode*(var m: CodeMark); +begin + m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := A.saidCount(); + m.fails := 0; m.exit := exitL; +end; + +(* The code made since m taken back; the frame is left as it is *) +proc rewind*(m: CodeMark); +begin + Chunk.rewindTo(m.pc, m.fixups, m.lines); + A.unsay(m.said); + exitL := m.exit; +end; + +(* For a second try at the body: the code as it was at m, and the frame + as useRegs found it *) +proc redo*(m: CodeMark); +begin + Chunk.rewindTo(m.pc, m.fixups, m.lines); + A.unsay(m.said); + frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2]; + exitL := NoLabel; +end; + +(* The prologue, for the procedure's first line: the frame record, x29 + and x30, pushed, and x29 made to point at it; sp lowered by the + frame's size, known only at endProc, which patches it into the two + subs, of its bits from 12 up and of its low 12 (so a frame is less + than 16 MB); the locals in memory zeroed, from the parameters' slots + down to zeroTop, by a store each of the zero register up to 16, else + by a loop; the registers of variables saved and zeroed; and the + parameters stored from their registers to their slots, or moved to + their registers. *) +proc enterBody*(c, line: INT); +var i, loop, r: INT; n: I64; +begin + Chunk.beginChunk(c); + codeChunk := c; + if LEN(pending) > 0 then Chunk.setMissing(c, pending, pendingAt); pending := ""; end; + Chunk.noteLine(line, 1); (* a declaration starts a line *) + A.stp(FP, LR, SP, -16, A.mPre); + A.movRR(FP, SP); + frameFix := Chunk.pc; + A.say("sub sp, sp, frame, lsl #12"); Chunk.put4(SubSp12); + A.say("sub sp, sp, frame"); Chunk.put4(SubSp); + n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8; + if n <= 16 then + for i := 1 to INT(n) do A.store(ZR, FP, INT(-paramTop) - 8 * i, 8); end; + elsif n > 0 then + A.aluI(A.opSub, T, FP, paramTop + 8 * n); + A.movRI(U, n); + loop := Chunk.pc; + A.storeIdx(ZR, T, 8, 8, A.mPost); + A.aluI(A.opSubs, U, U, 1); + A.jccBack(A.ccNE, loop); + end; + if (regMask shr XBit) # 0 then notYet("reals in registers"); end; + Chunk.setSaves(c, regMask, INT(saveAt)); + n := 0; + for i := 0 to 4 do + if (regMask & (1 shl i)) # 0 then + A.store(VarRegs[i], FP, INT(saveAt + 8 * n), 8); + A.movRI(VarRegs[i], 0); + INC(n); + end; + end; + for i := 0 to numIn - 1 do + if inObj[i]^.reg # 0 then + r := inObj[i]^.reg; + if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end; + A.movRR(r, inReg[i]); + if inSize[i] < 8 then A.extend(r, r, inSize[i], inObj[i]^.typ^.signed); end; + else + A.store(inReg[i], FP, INT(inSlot[i]), inSize[i]); + end; + end; +end; + +proc resultSlot*: I64; +begin + return retSlot; +end; + +proc resultTo*(off: I64; size: INT); +begin + _ := off; _ := size; + notYet("a result in memory"); + drop(); +end; + +proc copyResult*(off, size: I64); +begin + _ := off; _ := size; + notYet("a result in memory"); + drop(); +end; + +(* return: the result, a value on top, goes in x0; two words, the two + values on top, in x0 and x1 *) +proc returnJump*; +begin + if (resType # nil) and Sym.behindPointer(resType) then + A.load(0, FP, INT(retSlot), 8, false); (* not yet made: marked by beginProc *) + elsif resType # nil then + if Sym.inTwoRegs(resType) then popTo(1); end; + popTo(0); + end; + A.jmp(exitL); +end; + +(* try, where the error isn't nil, first makes the machine's stack even + on x86-64; here nothing is pushed, so sp is as the prologue left it *) +proc tryAlign*; +begin +end; + +proc tryReturn*(slot: I64); +begin + _ := slot; + notYet("try"); +end; + +(* try, with no deferred statement to run: the error on top is tested in + its register r, which is returned, and, if it isn't nil, returned + from the procedure by tryReturnFrom *) +proc tryTest*(var ok: INT): INT; +var r: INT; +begin + r := loaded(depth - 1); + jumpIf(ok, false); + return r; +end; + +proc tryReturnFrom*(r: INT); +begin + _ := r; + notYet("try"); +end; + +(* The end of the procedure in chunk c: the code that returns, and the + frame's size, known only now, patched into its prologue. If it is + open, running off its end, it returns zeros. *) +proc endProc*(c: INT; open: BOOL): ERROR; +var n: I64; i: INT; +begin + codeChunk := -1; + if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end; + if open then + A.movRI(0, 0); + if Sym.inTwoRegs(resType) then A.movRI(1, 0); end; + else + A.dropJumpTo(exitL); + end; + A.fixLink(exitL); + n := 0; + for i := 0 to 4 do + if (regMask & (1 shl i)) # 0 then + A.load(VarRegs[i], FP, INT(saveAt + 8 * n), 8, false); + INC(n); + end; + end; + A.movRR(SP, FP); + A.ldp(FP, LR, SP, 16, A.mPost); + A.ret(); + n := Sym.alignUp(frameMax, 16); + if n >= 1000000H then return Scan.mark("frame too big: 16 MB or more"); end; + Chunk.put4At(frameFix, SubSp12 | INT((n shr 12) shl 10)); + Chunk.put4At(frameFix + 4, SubSp | INT((n & 0FFFH) shl 10)); + if A.listing then + A.restate(frameFix, Diag.say("sub sp, sp, #{}, lsl #12", [Fmt.int(INT(n shr 12))])); + A.restate(frameFix + 4, Diag.say("sub sp, sp, #{}", [Fmt.int(INT(n & 0FFFH))])); + end; + Chunk.endChunk(c); + return nil; +end; + +proc deferBegin*(var L: INT): (INT, INT); +begin + _ := L; + notYet("defer"); + return Chunk.pc, pushed; +end; + +proc deferEnd*(L, saved: INT); +begin + _ := L; _ := saved; + keepTemps(); +end; + +proc runDefer*(at: INT); +begin + _ := at; + notYet("defer"); +end; + +(* The name s, interned *) +proc internStr(s: []const U8): INT; +begin + return Scan.intern(SYSTEM.PTR(s), LEN(s)); +end; + +(* The entry point, main, and its chunk. macOS starts every program in + dyld, the dynamic loader, which binds its C symbols and calls the + procedure LC_MAIN names as C's main(argc, argv): this one. It saves + argc, an int (so its upper half is undefined until extended), and + argv; gives the library C's symbols it needs (cLinks: Rt's cExit) and + Rt the addresses it is given (links); runs every used module's body, + then main; and ends with Rt.exit, its status main's or 0. The frame + record it pushes links to dyld's, where a trace ends. Every program + reaches the kernel through libSystem, so dynamic is always so; bare, + for a machine with no system, isn't a Mac's. *) +proc entryPoint*(dynamic, bare: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cLinks: []Link; numCLinks, exitProc: INT; links: []Link; numLinks: INT): INT; +var entry, i: INT; m: ^Sym.Module; +begin + if bare or not dynamic then Diag.fatal("a program for macOS runs over libSystem: Rt must use C, and -bare is not for it"); end; + entry := Chunk.newChunk(Chunk.secText, -1, internStr("main")); + Chunk.beginChunk(entry); + A.stp(FP, LR, SP, -16, A.mPre); + A.movRR(FP, SP); + A.extend(0, 0, 4, true); + A.storeChunk(0, argcChunk, 0, 8); + A.storeChunk(1, argvChunk, 0, 8); + for i := 0 to numCLinks - 1 do + A.loadChunk(0, cLinks[i].chunk, 0, 8, false); + A.storeChunk(0, cLinks[i].into, 0, 8); + end; + for i := 0 to numLinks - 1 do + A.addrChunk(0, links[i].chunk, 0); + A.storeChunk(0, links[i].into, 0, 8); + end; + m := first; + while m # nil do + if m^.used and (m^.body >= 0) then A.callChunk(m^.body); end; + m := m^.next; + end; + if mainObj # nil then A.callChunk(mainObj^.chunk); end; + if (mainObj = nil) or (mainObj^.typ^.base = nil) then A.movRI(0, 0); end; + A.callChunk(exitProc); + A.brk(1); (* exit never returns: trap if it does *) + Chunk.endChunk(entry); + return entry; +end; + +(* A code procedure: its instructions, read by the assembler (A64), are + the whole of chunk c *) +proc codeProc*(c: INT; constExpr: A.ConstFn; nameFn: A.NameFn): ERROR; +begin + Chunk.beginChunk(c); + try A.assemble(constExpr, nameFn); + Chunk.endChunk(c); + return nil; +end; + +(* A code procedure that is one instruction on a real, as Math.sqrt on + x86-64, is made in place of its call there; none is, yet, here *) +proc oneRealOp*(c: INT): INT; +begin + _ := c; + return 0; +end; + +proc realInPlace*(op: INT); +begin + _ := op; + notYet("reals"); +end; + +begin + Chunk.setPad(0D4200020H); (* brk #1, a trap, between procedures *) + codeChunk := -1; + pending := ""; + resetStack(0, 0); + rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail")); + argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc")); + Chunk.setBss(argcChunk, 8, 8); + argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv")); + Chunk.setBss(argvChunk, 8, 8); +end Gen. diff --git a/src/Gen.x86_64.raz b/src/Gen.x86_64.raz index 8f1525e..5ef16e6 100644 --- a/src/Gen.x86_64.raz +++ b/src/Gen.x86_64.raz @@ -2849,6 +2849,7 @@ var i: INT; begin for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end; + Chunk.setPad(0CCCCCCCCH); (* int3, a trap, between procedures *) inPlace := -1; codeChunk := -1; resetStack(0, 0); diff --git a/src/Link.raz b/src/Link.raz index e343c87..f0cea88 100644 --- a/src/Link.raz +++ b/src/Link.raz @@ -12,6 +12,13 @@ loader's other tables come at the end of rodata; Exe writes them in the room left there. + Mach-O, Exe.darwin.raz's, is laid out otherwise (setPaged): each + segment starts on a page of its own, in the file as in memory, at + base plus its offset in the file; and, since macOS loads a program + anywhere, every address held in rodata is listed (rebases), for the + loader to move with it. arm64's fixups, fields of an instruction, + are patched here too. + Depends on: Chunk for chunks and fixups, Scan for names and memory, Diag for errors and paths. Leaves out: the file format; that is Exe. *) @@ -34,12 +41,21 @@ textImg*, roImg*: ^U8; placesChunk*: INT; (* the rodata chunk of the places, made by the caller *) linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *) + paged*: INT; (* 0, ELF's layout; or Mach-O's page, each segment on one *) + rebases*: ^INT; (* the addresses of rodata's words that hold an address *) + numRebases*: INT; proc setBase*(a: INT); begin base := a; end; +(* Mach-O's layout, its segments on pages of page bytes *) +proc setPaged*(page: INT); +begin + paged := page; +end; + proc setPlaces*(c: INT); begin placesChunk := c; @@ -334,6 +350,42 @@ return s; end; +(* The arm64 instruction at at in text, at address pc, made to reach + the address v, as its kind says (Chunk.FixKind): + fxBranch26 b, bl: (v - pc) / 4 in imm26, bits 0 to 25 + fxPage21 adrp: v's page less pc's, in pages of 4 KB, its low + two bits in immlo (29, 30), the rest in immhi (5 to 23) + fxPageOff12 add: v's place in its page in imm12 (10 to 21); a load + or store (bits 27 to 29 111, 24 and 25 01) that place + divided by the size it moves, 1 shl its bits 30 and 31, + or 16 for a q register (bit 26, the reals', with bit 23) + The fields hold zeros, as A64 left them. *) +proc patchArm(at: INT; kind: Chunk.FixKind; pc, v: INT); +var insn, d, sc: INT; +begin + insn := 0; + for d := 3 to 0 by -1 do insn := insn * 256 + INT(textImg[at + d]); end; + match kind of + | fxBranch26: + d := (v - pc) div 4; + if (d < -(1 shl 25)) or (d >= 1 shl 25) then Diag.fatal("the program's code is more than 128 MB"); end; + insn := insn | (d & 3FFFFFFH); + | fxPage21: + d := (v shr 12) - (pc shr 12); + insn := insn | ((d & 3) shl 29) | (((d shr 2) & 7FFFFH) shl 5); + | fxPageOff12: + d := v & 0FFFH; + if (insn & 3B000000H) = 39000000H then + sc := (insn shr 30) & 3; + if (insn & 04800000H) = 04800000H then sc := 4; end; + d := d shr sc; + end; + insn := insn | (d shl 10); + | else: + end; + patch4(textImg, at, insn); +end; + (* Places the live chunks, leaving roExtra bytes at the end of rodata and dynSize at the start of the writable segment. The segments follow each other in the file with no padding, and each is loaded a page @@ -352,12 +404,19 @@ if placesChunk >= 0 then makePlaces(base + textOff, e); end; roOff := (textOff + textSize + 31) div 32 * 32; roAdr := base + Page + roOff; + if paged > 0 then (* Mach-O: rodata on a page of its own, at its offset *) + roOff := (textOff + textSize + paged - 1) div paged * paged; + roAdr := base + roOff; + end; e := place(Chunk.secRodata, roAdr); extraAdr := (e + 7) div 8 * 8; if roExtra > 0 then e := extraAdr + roExtra; end; roSize := e - roAdr; bssOff := (roOff + roSize + 31) div 32 * 32; - if dynSize > 0 then + if paged > 0 then + bssOff := (roOff + roSize + paged - 1) div paged * paged; + bssAdr := base + bssOff; + elsif dynSize > 0 then bssAdr := base + 2 * Page + bssOff; else bssAdr := (roAdr + roSize + Page - 1) div Page * Page; @@ -368,17 +427,21 @@ by their sign, so the image must lie where such an address reaches: the low 2 GB, as at 400000H, or the top 2 GB, as a higher-half kernel at 0FFFFFFFF80000000H. The places keep each procedure's - start and stop in 32 bits too, which Rt.procAt reads so. *) + start and stop in 32 bits too, which Rt.procAt reads so. Mach-O's + image lies at 4 GB and up, which arm64's code reaches by adrp, and + whose places, below 4 GB of it, keep their order in 32 bits. *) (* By the size, e - base, which can't overflow, where e itself might *) - if not (((base >= 0) and (base <= Low - (e - base))) or ((base >= -Low) and (base <= -(e - base)))) then + if (paged = 0) and not (((base >= 0) and (base <= Low - (e - base))) or ((base >= -Low) and (base <= -(e - base)))) then Diag.fatal(Diag.say("-base {}: the program must lie in the low or the top 2 GB, where a 32-bit address reaches, and from there it doesn't", [Fmt.str(literal(base))])); end; textImg := Scan.grab(textSize + 1); - (* the gaps between code chunks are int3, a trap if ever run *) - for p := 0 to textSize do textImg[p] := 0CCH; end; + (* the gaps between code chunks are Gen's trap, as in Chunk *) + for p := 0 to textSize do textImg[p] := U8((Chunk.pad shr (8 * ((textOff + p) & 3))) & 0FFH); end; roImg := Scan.grab(roSize + 1); + rebases := ^INT(Scan.grab(Chunk.numDataFixups * SIZE(INT) + SIZE(INT))); + numRebases := 0; for p := 0 to roSize do roImg[p] := 0; end; for c := 0 to Chunk.numChunks - 1 do if Chunk.chunks[c].live then @@ -387,11 +450,15 @@ COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]); for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do at := Chunk.fixups[f].at - Chunk.chunks[c].start; - (* rel32: from the end of the field to the target; - or, X64.memAbs's, the target's address *) v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend; - if not Chunk.fixups[f].abs then v := v - (Chunk.chunks[c].adr + at + 4); end; - patch4(textImg, p + at, v); + if Chunk.fixups[f].kind # Chunk.fxRel32 then + patchArm(p + at, Chunk.fixups[f].kind, Chunk.chunks[c].adr + at, v); + else + (* rel32: from the end of the field to the target; + or, X64.memAbs's, the target's address *) + if not Chunk.fixups[f].abs then v := v - (Chunk.chunks[c].adr + at + 4); end; + patch4(textImg, p + at, v); + end; end; elsif Chunk.chunks[c].sec = Chunk.secRodata then p := Chunk.chunks[c].adr - roAdr; @@ -399,6 +466,8 @@ for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do patch8(roImg, p + Chunk.dataFixups[f].at, Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend); + rebases[numRebases] := Chunk.chunks[c].adr + Chunk.dataFixups[f].at; + INC(numRebases); end; end; end; @@ -408,4 +477,5 @@ begin placesChunk := -1; base := 400000H; + paged := 0; end Link. diff --git a/src/Parse.raz b/src/Parse.raz index a38ffe5..b68f1b3 100644 --- a/src/Parse.raz +++ b/src/Parse.raz @@ -3651,7 +3651,17 @@ _ := Item.needSystem(Scan.tokPos(), "a code procedure"); (* said, and the declaration read on *) Scan.next; p^.isCode := true; - try codeBody(p, sig, at); + if checkMode then + (* a file of another target's, read for its interface: its code + is in that machine's assembly, which this one's can't read; + ! is a symbol there, as A64's assembler has it *) + Scan.setBang(true); + while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do Scan.next; end; + Scan.setBang(false); + try expect(Scan.sEnd); + else + try codeBody(p, sig, at); + end; elsif checkMode then try skipBody(); else diff --git a/src/Raz.raz b/src/Raz.raz index c9af392..b7c1cfb 100644 --- a/src/Raz.raz +++ b/src/Raz.raz @@ -467,6 +467,12 @@ objIn(rt, "exit")^.chunk, links[0..numLinks], numLinks); Link.markLive(entry); + (* what the target's Gen can't make yet stops a program that uses it *) + for i := 0 to Chunk.numChunks - 1 do + if Chunk.chunks[i].live and (LEN(Chunk.chunks[i].missing) > 0) then + Diag.error(Chunk.chunks[i].missingAt, Chunk.chunks[i].missing); + end; + end; if not Parse.HasReals then for i := 0 to Chunk.numChunks - 1 do if Chunk.chunks[i].live and Chunk.chunks[i].reals then diff --git a/src/Scan.raz b/src/Scan.raz index c85de64..fc0e1b5 100644 --- a/src/Scan.raz +++ b/src/Scan.raz @@ -25,6 +25,15 @@ type NamePtr = ^U8; + (* The parser's readers for a code procedure's assembler, X64's or + A64's, here so that both Gens take the same types: of an integer + constant, a whole expression or, when whole is false, a single + factor; and of a name that stands for an address, a procedure or a + module variable, bare or qualified, its chunk, or -1, nothing read, + if the name is anything else, which is then read as a constant *) + ConstFn* = proc(whole: BOOL): (I64, ERROR); + NameFn* = proc: (INT, ERROR); + Sym* = (sNull, sIdent, sInt, sReal, sChar, sString, sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq, sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis, diff --git a/src/X64.raz b/src/X64.raz index 00c3722..9eea8fb 100644 --- a/src/X64.raz +++ b/src/X64.raz @@ -44,15 +44,9 @@ chunk*: INT; (* with RIP: the chunk addressed *) end; - (* The parser's reader of an integer constant in a code procedure: a - whole expression, or, when whole is false, a single factor *) - ConstFn* = proc(whole: BOOL): (I64, ERROR); - - (* The parser's reader of a name in a code procedure that stands for an - address: a procedure or a module variable, bare or qualified. Its - chunk, the name read; or -1, nothing read, if the name at the scan - is anything else, which is then read as a constant *) - NameFn* = proc: (INT, ERROR); + (* The parser's readers of a constant and of a name (Scan says) *) + ConstFn* = Scan.ConstFn; + NameFn* = Scan.NameFn; (* The text of the instruction that starts at at, for the listing *) Said = record diff --git a/test/mac.sh b/test/mac.sh new file mode 100755 index 0000000..ea6fd56 --- /dev/null +++ b/test/mac.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# The Mac's tests, make mac-check on an Apple Silicon Mac (PLAN.md 5): +# test/mac/X.raz compiled for darwin-arm64 by the cross compiler, which +# src/cross.sh builds in the linux/amd64 container, into build/mac/X; +# then each run here, natively, and what it prints and its status +# compared, as test/check.sh compares a test's: +# X.expect its standard output (optional; empty if missing) +# X.status its exit status (optional; 0 if missing) +# +# test/mac.sh build in the container: the cross compiler, then the programs +# test/mac.sh run on the Mac: each program, run with a timeout +# +# build/mac is made anew each time: macOS keeps a file's code signature +# while the file is open or cached, and kills a program whose file was +# written again in place with another one. +set -e +out=build/mac +case $1 in +build) + src/cross.sh darwin-arm64 + rm -rf $out + mkdir -p $out + for f in test/mac/*.raz; do + name=$(basename $f .raz) + build/cross/darwin-arm64/raz -o $out/$name $f 2>$out/$name.cerr || true + done + ;; +run) + pass=0 + fail=0 + for f in test/mac/*.raz; do + name=$(basename $f .raz) + want=0 + [ -f test/mac/$name.status ] && want=$(cat test/mac/$name.status) + if [ ! -x $out/$name ]; then + echo "FAIL $f: doesn't compile: $(cat $out/$name.cerr 2>/dev/null)"; fail=$((fail + 1)); continue + fi + # perl's alarm, as macOS has no timeout + status=0 + perl -e 'alarm 10; exec @ARGV' ./$out/$name > $out/$name.out 2>$out/$name.err || status=$? + if [ -f test/mac/$name.expect ]; then exp=test/mac/$name.expect; else exp=/dev/null; fi + if [ $status != $want ]; then + echo "FAIL $f: status $status, not $want"; fail=$((fail + 1)) + elif ! cmp -s $out/$name.out $exp; then + echo "FAIL $f: output differs"; fail=$((fail + 1)) + else + pass=$((pass + 1)) + fi + done + echo "$pass passed, $fail failed" + [ $fail = 0 ] + ;; +*) + echo "usage: test/mac.sh build|run" >&2 + exit 2 + ;; +esac diff --git a/test/mac/Exit.raz b/test/mac/Exit.raz new file mode 100644 index 0000000..d8de4d3 --- /dev/null +++ b/test/mac/Exit.raz @@ -0,0 +1,4 @@ +(* The least program: it does nothing, and ends with status 0 *) +module Exit; +begin +end Exit. diff --git a/test/mac/Fail.raz b/test/mac/Fail.raz new file mode 100644 index 0000000..51edd6b --- /dev/null +++ b/test/mac/Fail.raz @@ -0,0 +1,8 @@ +(* Rt.fail says a check failed, through libSystem's write, and ends the + program with status 2 *) +module Fail; +import Rt; + +begin + Rt.fail(0, 1, 2, 3, 0, nil, 0, 0); +end Fail. diff --git a/test/mac/Fail.status b/test/mac/Fail.status new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/test/mac/Fail.status @@ -0,0 +1 @@ +2 diff --git a/test/mac/Loop.raz b/test/mac/Loop.raz new file mode 100644 index 0000000..7d36bc5 --- /dev/null +++ b/test/mac/Loop.raz @@ -0,0 +1,27 @@ +(* Variables, a loop, calls with arguments and a narrow integer: the + status is the sum of 1 to 10, 55, plus 200 cut to a U8, 255 *) +module Loop; + +var total: INT; + +proc add(var t: INT; n: INT); +begin + t := t + n; +end; + +proc main*: INT; +var i, sum: INT; b: U8; +begin + i := 1; + while i <= 10 do + add(sum, i); + INC(i); + end; + total := sum; + b := 200; + b := b + 200; + if total = 55 then return total + INT(b) - 144; end; + return 1; +end; + +end Loop. diff --git a/test/mac/Loop.status b/test/mac/Loop.status new file mode 100644 index 0000000..c3f407c --- /dev/null +++ b/test/mac/Loop.status @@ -0,0 +1 @@ +55 diff --git a/test/mac/RtExit.raz b/test/mac/RtExit.raz new file mode 100644 index 0000000..1f39394 --- /dev/null +++ b/test/mac/RtExit.raz @@ -0,0 +1,8 @@ +(* Rt.exit, from a module's body, ends the program there *) +module RtExit; +import Rt; + +begin + Rt.exit(5); + Rt.exit(6); +end RtExit. diff --git a/test/mac/RtExit.status b/test/mac/RtExit.status new file mode 100644 index 0000000..7ed6ff8 --- /dev/null +++ b/test/mac/RtExit.status @@ -0,0 +1 @@ +5 diff --git a/test/mac/Status.raz b/test/mac/Status.raz new file mode 100644 index 0000000..a17c55f --- /dev/null +++ b/test/mac/Status.raz @@ -0,0 +1,9 @@ +(* main's result is the program's status *) +module Status; + +proc main*: INT; +begin + return 3; +end; + +end Status. diff --git a/test/mac/Status.status b/test/mac/Status.status new file mode 100644 index 0000000..00750ed --- /dev/null +++ b/test/mac/Status.status @@ -0,0 +1 @@ +3 diff --git a/tools/cabi.c b/tools/cabi.c index 17a80c9..ad44710 100644 --- a/tools/cabi.c +++ b/tools/cabi.c @@ -19,8 +19,17 @@ file pairs each with the C library's own; on Linux, each is checked against the headers before anything is written. - Leaves out: systems but Linux, for errno and closeFrom; a port adds - them where the #error is. */ + What a system hasn't, Linux's alone, is given a value that keeps Sys + over C compiling there, and that it must not count on: a flag 0, no + flag; an option -1, as saLenAt is -1 where a sockaddr has no sa_len. + On macOS (darwin-arm64), st_mtim is st_mtimespec, a peer's + credentials are struct xucred, which has no pid (0 bytes at 0), and + errno and closeFrom are its own. + + cc -o build/cabi tools/cabi.c && build/cabi darwin-arm64 > lib/CAbi.darwin-arm64.raz + + Leaves out: systems but Linux and macOS, for errno and closeFrom; a + port adds them where the #error is. */ #define _GNU_SOURCE #include #include @@ -43,6 +52,30 @@ #include #include +#ifndef MFD_CLOEXEC +#define MFD_CLOEXEC 0 +#endif +#ifndef TIMER_ABSTIME +#define TIMER_ABSTIME 0 +#endif +#ifndef SOCK_CLOEXEC +#define SOCK_CLOEXEC 0 +#endif +#ifndef SOCK_NONBLOCK +#define SOCK_NONBLOCK 0 +#endif +#ifndef MSG_CMSG_CLOEXEC +#define MSG_CMSG_CLOEXEC 0 +#endif +#ifndef SO_PEERCRED +#define SO_PEERCRED -1 +#endif +#ifdef __APPLE__ +#include +#define st_mtim st_mtimespec +#define CMSG_ALIGN(n) __DARWIN_ALIGN32(n) +#endif + /* Sys keeps a terminal's modes in 256 bytes, and struct rusage, whose size C libraries differ in, in 512 */ _Static_assert(sizeof(struct termios) <= 256, "struct termios is larger than Sys.Mode"); @@ -171,7 +204,12 @@ K("sockaddrIn6Len", sizeof(struct sockaddr_in6)); AT("sin6Port", struct sockaddr_in6, sin6_port); AT("sin6Addr", struct sockaddr_in6, sin6_addr); +#ifdef __linux__ READ("ucPid", struct ucred, pid); READ("ucUid", struct ucred, uid); +#else + K("ucPidAt", 0); K("ucPidLen", 0); + READ("ucUid", struct xucred, cr_uid); +#endif K("msghdrLen", sizeof(struct msghdr)); AT("msgIov", struct msghdr, msg_iov); WRITE("msgIovlen", struct msghdr, msg_iovlen, msg_control); @@ -231,6 +269,23 @@ "begin\n" " if hi < 0 then hi := 0FFFFFFFFH; end;\n" " _ := syscall(436, lo, hi, 0);\n" + "end;\n\n"); +#elif defined(__APPLE__) + printf("extern proc __error: ^I32;\n" + "extern proc close(fd: I32): I32;\n" + "extern proc getdtablesize: I32;\n\n" + "(* errno, this thread's *)\n" + "proc errno*: ^I32;\n" + "begin\n" + " return __error();\n" + "end;\n\n" + "(* Closes the fds from lo to hi, or every one from lo if hi < 0: one\n" + " by one, as macOS has no close_range. *)\n" + "proc closeFrom*(lo, hi: INT);\n" + "var fd: INT;\n" + "begin\n" + " if hi < 0 then hi := INT(getdtablesize()) - 1; end;\n" + " for fd := lo to hi do _ := close(I32(fd)); end;\n" "end;\n\n"); #else #error "a CAbi for this system needs its errno and closeFrom: add them here"