raz / commit 2b92b442

commit
2b92b442767fed55ec333b001fb2f4043860750f
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
489d8810
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.

patch · log

27 files changed, +2780 -65

Makefile (history) modified +7 -1

@@ -207,7 +207,7 @@
207207 site-check: build/site/Verify
208208 build/site/Verify
209209
210-.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
210+.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
211211
212212 # `make check` in a linux/amd64 container, for a machine that isn't one
213213 # (the repository is mounted at its own path, so git and the tests see
@@ -219,6 +219,12 @@
219219
220220 docker-check: docker-image
221221 $(DOCKER) $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && make check"
222+
223+# test/mac's programs (test/mac.sh), on an Apple Silicon Mac: compiled
224+# for darwin-arm64 by the cross compiler in the container, then run here
225+mac-check: docker-image
226+ $(DOCKER) $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && timeout 1200 test/mac.sh build"
227+ test/mac.sh run
222228
223229 docker-shell: docker-image
224230 $(DOCKER) -it $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && exec bash"

PLAN.md (history) modified +25 -7

@@ -224,19 +224,37 @@
224224 the assembler in Arm's syntax (`bl p`, `b p`, `adr xN, v` for names),
225225 checked against Apple's assembler (clang's, `llvm-mc`'s bytes) by
226226 `test/a64`; Chunk's arm64 fixup kinds, `fxBranch26`, `fxPage21` and
227- `fxPageOff12`, and `Scan.setBang` for a pre-index's `!`. Left for
228- later: `Link`'s patching of those kinds comes with step 6; no
229- compiler imports `A64` until step 5's `Gen.arm64.raz`, and
230- `Chunk.beginChunk` still pads code with x86's `int3`, which arm64's
231- Gen will want as `brk`.
227+ `fxPageOff12`, and `Scan.setBang` for a pre-index's `!`. What it
228+ left for later, `Link`'s patching of those kinds, `Gen.arm64.raz`
229+ importing `A64`, and padding with `brk`, came with 5a.
232230 5. `Gen.arm64.raz`, in pieces, each run on the Mac (owner, 2026-11-15):
233231 first a bare `Exe.darwin.raz` (a signed Mach-O over libSystem, no line
234232 numbers) and an `Rt` that only exits, built by the staged cross
235233 compiler in the container; then values and operations; jumps and
236234 checks; calls and frames; reals; atomics, deferred statements, the
237235 entry point.
238-6. `Exe.darwin.raz` and `Link`'s rebases, its line numbers for lldb;
239- `Host.darwin.raz`.
236+
237+ 5a, done: programs made by the cross compiler (`src/cross.sh
238+ darwin-arm64`) run on the Mac, `test/mac` by `make mac-check`. In
239+ `Gen.arm64.raz`: frames, constants, variables, the integer
240+ operations but division, comparisons and jumps, elements and slices
241+ unchecked, calls with arguments in registers, C's calls, code
242+ procedures and the entry point; every other routine notes "not yet
243+ on arm64" on its procedure, an error if the program uses it.
244+ `Exe.darwin.raz`: a signed Mach-O over libSystem, its rebases and
245+ binds dyld's opcodes, no line numbers. `Link`: arm64's fixups, Mach-O's
246+ paged layout, the rebases. `lib/Rt.darwin-arm64.raz`: exit through C's
247+ exit, one procedure at exit, fail and stop by `write`. As the interface
248+ check of `Rt` reads `Rt.raz`, and so compiles `Sys` over C, also
249+ `lib/CAbi.darwin-arm64.raz`, from `tools/cabi.c` on the Mac, and a
250+ code procedure skipped in a file read only for its interface. Left of
251+ step 5: division and its check, the other checks and their stubs for
252+ `Rt.fail`, the reals, arguments and results past the registers or in
253+ memory (`x8`), Apple's variadic calls, `try`, deferred statements,
254+ atomics and system calls, `COPY`, `FILL`, `NEW`'s zeroing, the bit
255+ counts and rotations, copies past 256 bytes.
256+6. `Exe.darwin.raz`'s line numbers for lldb (its rebases came with
257+ 5a); `Host.darwin.raz`.
240258 7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`.
241259 8. `test/` and `conform/` passing on the Mac; what differs by target
242260 (signals' words, errors' numbers) in files of the target's.

doc/compiler.md (history) modified +190 -21

@@ -1,8 +1,9 @@
11 # Reading the raz compiler
22
3-The compiler is thirteen files of raz, about 14,600 lines of code (the
4-budget is 18,000); one of them, `A64.raz`, arm64's encoder, waits for
5-the back end that will use it (`PLAN.md` 5). It is its own compiler: a release of it, the one
3+The compiler is fifteen files of raz, about 16,100 lines of code (the
4+budget is 18,000); three of them, `A64.raz`, `Gen.arm64.raz` and
5+`Exe.darwin.raz`, are the Mac's back end, begun (`PLAN.md` 5), built
6+only into a compiler for `darwin-arm64` (`src/cross.sh`). It is its own compiler: a release of it, the one
67 `BOOT` names, builds `src/`, and `make fixpoint` checks that what it
78 makes makes itself again, byte for byte. Each release was built by the
89 one before it, back to v0.19.0, which the Pascal compiler it was ported
@@ -18,18 +19,20 @@
1819 | File | Lines | Code | What |
1920 |---|---|---|---|
2021 | `src/Diag.raz` | 479 | 363 | Messages: positions, source excerpts, colour, counts |
21-| `src/Scan.raz` | 1,279 | 1,048 | Symbols, literals, comments, positions |
22+| `src/Scan.raz` | 1,288 | 1,050 | Symbols, literals, comments, positions |
2223 | `src/Sym.raz` | 866 | 689 | Types, objects, scopes, layout |
23-| `src/Chunk.raz` | 389 | 288 | The compiled program: chunks, fixups, line notes |
24-| `src/X64.raz` | 1,777 | 1,450 | The instruction encoder, jumps within a procedure, the assembler |
25-| `src/A64.raz` | 1,848 | 1,365 | The same for arm64, not yet imported: the encoder, jumps, the assembler |
26-| `src/Gen.x86_64.raz` | 2,860 | 1,998 | The stack machine, for x86-64: values, operations, checks, calls, frames |
24+| `src/Chunk.raz` | 410 | 302 | The compiled program: chunks, fixups, line notes |
25+| `src/X64.raz` | 1,771 | 1,450 | The instruction encoder, jumps within a procedure, the assembler |
26+| `src/A64.raz` | 1,843 | 1,365 | The same for arm64: the encoder, jumps, the assembler |
27+| `src/Gen.x86_64.raz` | 2,861 | 1,999 | The stack machine, for x86-64: values, operations, checks, calls, frames |
28+| `src/Gen.arm64.raz` | 1,468 | 1,107 | The same for arm64, begun: frames, values, operations, jumps, calls |
2729 | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls |
28-| `src/Parse.raz` | 4,938 | 4,191 | Declarations, statements, expressions, built-ins, recovery, warnings |
29-| `src/Link.raz` | 411 | 317 | Tree shaking, layout, patching, the places |
30+| `src/Parse.raz` | 4,948 | 4,198 | Declarations, statements, expressions, built-ins, recovery, warnings |
31+| `src/Link.raz` | 481 | 365 | Tree shaking, layout, patching, the places |
3032 | `src/Exe.linux.raz` | 455 | 358 | The executable, ELF: static and dynamic, symbol table, line numbers |
33+| `src/Exe.darwin.raz` | 458 | 332 | The executable for macOS, Mach-O: dyld's binds and rebases, the signature |
3134 | `src/Host.linux.raz` | 103 | 52 | The system running the compiler |
32-| `src/Raz.raz` | 493 | 385 | The command line, and `-q` for an editor |
35+| `src/Raz.raz` | 499 | 390 | The command line, and `-q` for an editor |
3336
3437 Every file opens with a comment that says what it is, what it depends
3538 on and what it leaves out. Read those first; they are the map.
@@ -1154,8 +1157,7 @@
11541157 `fxPage21`, an `adrp`'s distance in pages of 4 KB; `fxPageOff12`, an
11551158 address's place in its page, in an `add` or, divided by the size the
11561159 instruction reads, a load's or store's offset; as the Mach-O relocations
1157-of the same names. `Link.raz` patches only x86-64's yet; arm64's come
1158-with the Mac's executable. A constant's addresses
1160+of the same names, which `Link.raz` patches. A constant's addresses
11591161 are *data fixups*, `addDataFixup`'s: 64-bit fields in rodata that will
11601162 hold a chunk's address itself, since the executable is loaded where the
11611163 linker placed it. `noteLine` records which line and column of the source
@@ -1165,7 +1167,11 @@
11651167 end of what was made, for a body compiled a second time. What other
11661168 modules set in a chunk, such as `live` or `adr`, has a setter each
11671169 (`setLive`, `setAdr`), since an exported variable can't be set from
1168-outside. None of this depends on the machine.
1170+outside. None of this depends on the machine, but two things a `Gen`
1171+gives it: `pad`, the word that fills the gaps between procedures, a
1172+trap if ever run (`setPad`: int3 on x86-64, brk on arm64); and, on a
1173+chunk, what that `Gen` can't make yet (`setMissing`), an error if the
1174+chunk is live (`Gen.arm64.raz` says more).
11691175
11701176 ## X64.raz: machine code
11711177
@@ -1278,9 +1284,9 @@
12781284
12791285 ## A64.raz: arm64's machine code
12801286
1281-X64's twin, for arm64: what `Gen.arm64.raz` will call, and the
1282-assembler of a code procedure on the Mac. No compiler imports it yet;
1283-`test/a64` checks every routine against Apple's assembler.
1287+X64's twin, for arm64: what `Gen.arm64.raz` calls, and the assembler
1288+of a code procedure on the Mac. Only a compiler for `darwin-arm64`
1289+imports it; `test/a64` checks every routine against Apple's assembler.
12841290
12851291 Every instruction is one word of 32 bits, which `emit` writes. A
12861292 routine builds the word from its fields with shifts and ors, and its
@@ -1704,6 +1710,96 @@
17041710 `call` loads the register from it after each call, as System V has no
17051711 callee-saved xmm register.
17061712
1713+## Gen.arm64.raz: the stack machine on arm64
1714+
1715+arm64's `Gen`, for macOS on Apple Silicon (`PLAN.md` 5), is begun. It
1716+answers every call `Gen.x86_64.raz` answers, with the same parameters,
1717+as the interface check holds the two files to (report, 3), and makes
1718+frames, constants, the values of variables and their stores, the
1719+integer operations but division, comparisons and jumps, elements and
1720+slices unchecked, calls with integer arguments in registers, C's
1721+calls, code procedures (`A64.assemble`) and the entry point. `Gen.Arch`
1722+is `"arm64"`.
1723+
1724+*Not yet.* What it can't make yet isn't refused at once, since a
1725+library module holds much that a program never calls: the C library's
1726+`Sys` is compiled whole for the Mac, as the interface check of `Rt`
1727+reads `Rt.raz`, which imports it. So a routine not yet made calls
1728+`notYet`, which notes on the procedure's chunk what it is and where,
1729+the first only (`Chunk.setMissing`); keeps the stack as the real
1730+routine would, so that the compile reads on; and makes what code it
1731+likes, never run. Once `Link.markLive` has marked what the program
1732+reaches, `Raz` makes each live chunk so noted an error at its place:
1733+
1734+ D.raz:8:19: error: not yet on arm64: div and mod
1735+
1736+A program that uses what isn't made fails to compile, and one that
1737+doesn't compiles. `beginProc` comes before its chunk is begun, so its
1738+notes wait for `enterBody` (`pending`). A routine not yet made reads
1739+into `_` the parameters it doesn't use yet, so that none is warned of.
1740+
1741+*The stack* is x86-64's, kept as plainly as it can be: the value at
1742+depth d is in `Regs[d mod 6]`, x9 to x14, which a call may change and
1743+which carry no argument, so `call` moves the arguments into x0 to x7 in
1744+any order, with none held back as x86's r8 and r9 are. A value is a
1745+constant (`lConst`), an address in the frame or of a chunk not yet
1746+made (`lAdr`), in its register (`lReg`) or spilled to a slot
1747+(`lFrame`). There is no `lMem`, `lIdx`, `lHeld` or `lInto`: arm64 takes
1748+memory only in a load or a store, so `pushVar` loads at once, an
1749+operand is always a register, and a register variable is copied into
1750+the value's register. Outside the stack, x15 and x17 are Gen's scratch,
1751+as rax and rcx are x86's; x16 is A64's; x0 to x3 copy and cut slices,
1752+between calls; x8 is kept for the address of a result in memory, as
1753+Apple's convention has it, and x18, the system's, is never touched.
1754+
1755+A place in memory is a `Mem`: a register and an offset, or a chunk and
1756+an offset, which A64 reaches by `adrp` and the place in the page
1757+(`loadChunk`, `storeChunk`), since macOS loads a program anywhere.
1758+`place` makes one of an `Adr`, as x86's makes an operand.
1759+
1760+*Frames* follow Apple's convention. The prologue pushes the frame
1761+record, x29 and x30, points x29 at it, and lowers sp by the frame, whose
1762+size `endProc` patches into two `sub`s, of its bits from 12 up and of
1763+its low 12, so that a frame is less than 16 MB. `Loop.main` of
1764+`test/mac`, with `i` in x19:
1765+
1766+```
1767+stp x29, x30, [sp, #-16]!
1768+mov x29, sp
1769+sub sp, sp, #0, lsl #12 ; the frame, patched in by endProc
1770+sub sp, sp, #32
1771+stur xzr, [x29, #-8] ; sum, a local in memory, zeroed
1772+stur x19, [x29, #-24] ; i's register, saved and zeroed
1773+mov x19, #0
1774+...
1775+mov sp, x29 ; endProc's
1776+ldp x29, x30, [sp], #16
1777+ret
1778+```
1779+
1780+Every slot is at a negative offset from x29, and nothing is pushed in
1781+a body, so sp stays a multiple of 16 and `pushed` is always 0. The
1782+busiest variables take x19 to x23 (`VarRegs`), which a callee gives
1783+back; no parameter is kept where it arrives (`keepArrived` does
1784+nothing); the reals' variables will take d8 to d15 (`XVarRegs`,
1785+numbered from `XmmVar`, 32, above every x register, which `Parse` tells
1786+apart by it).
1787+
1788+*Calls* move each argument into x0 to x7; a single result comes back in
1789+x0, two words in x0 and x1, and a narrow result of C's is extended, as
1790+C leaves the upper bits as they fall. C's procedure is called through
1791+the quadword the loader fills in, `adrp x16` of its page, `ldr x17,
1792+[x16, ...]` and `blr x17`; a procedure value from its slot, `blr x17`
1793+too.
1794+
1795+*The entry point* (`entryPoint`) is the C `main` that dyld calls: it
1796+pushes a frame record, which links to dyld's, saves argc, an `int` it
1797+extends to 64 bits, and argv, gives `Rt` C's `exit` in `cExit` and the
1798+addresses it is given, runs every used module's body and `main`, and
1799+calls `Rt.exit` with `main`'s result or 0. `brk #1` follows it, and
1800+fills the gaps between procedures (`Chunk.setPad`). A program for the
1801+Mac always uses C, so `dynamic` is always true; `-bare` is refused.
1802+
17071803 ## Item.raz: items
17081804
17091805 An operand is an *item* (`Item`), as in Wirth's compilers. Its `mode`
@@ -2093,7 +2189,13 @@
20932189 of its files there (a file's identity is its device and inode from `Sys.info`,
20942190 which follows a symbolic link, as on every target); `checkSiblings` then reads the files for other
20952191 targets beside it, declarations only, and `compareIface` holds them
2096-to the same exports by their fingerprints. A generic module is
2192+to the same exports by their fingerprints: a parameter's name is part
2193+of a procedure's, and a named type's module part of the type's, so the
2194+assemblers' readers, which both `Gen`s take, are `Scan`'s
2195+(`Scan.ConstFn`, `Scan.NameFn`). A code procedure of such a file is
2196+skipped to its `end`, not assembled, as it is in another machine's
2197+assembly. The modules such a file imports are compiled whole, as any
2198+import is: on the Mac, `Rt.raz`'s `Sys`. A generic module is
20972199 compiled once per distinct list of arguments, where it is first used.
20982200 The import only notes where its arguments are (`skipArgs`, `deferred`);
20992201 `firstUse`, from `qualIdent`, has `makeInstance` go back there, where
@@ -2324,11 +2426,26 @@
23242426 segments, with their different permissions, share a page. bss follows
23252427 the loader's table, or begins a page of its own.
23262428
2429+Mach-O is laid out otherwise. `Exe.darwin.raz` sets the base to
2430+100000000H, past the 4 GB `__PAGEZERO` that arm64 macOS demands, and
2431+`Link.setPaged` to its page of 16 KB: each segment then starts on a
2432+page of its own, in the file as in memory, at the base plus its offset
2433+in the file (`paged`), rodata on the page after the code and bss on the
2434+page after rodata, with no bytes in the file. The 2 GB check, which is
2435+for `X64.memAbs`'s 32-bit addresses, isn't made. The words of rodata
2436+that a data fixup patches are listed by their addresses (`rebases`),
2437+since macOS loads a program anywhere and dyld moves them with it.
2438+arm64's fixups are patched by `patchArm`: a branch's distance in words,
2439+an `adrp`'s in pages of 4 KB, and an address's place in its page, in an
2440+`add` or, divided by the size it moves, in a load or a store, as
2441+`Chunk.FixKind` says. The places keep the addresses the linker gave;
2442+the Mac's `Rt` will take dyld's slide from what it looks up.
2443+
23272444 ## Exe.linux.raz: the executable
23282445
23292446 `Exe`, the executable, is the one unit that knows the file format of
2330-the target's system; this is Linux's, ELF. A macOS `Exe.darwin.raz`
2331-will be Mach-O. `Exe.write` writes the ELF header, the program headers, the text and
2447+the target's system; this is Linux's, ELF. macOS's, `Exe.darwin.raz`,
2448+is Mach-O (below). `Exe.write` writes the ELF header, the program headers, the text and
23322449 rodata images, and then what isn't loaded: section headers, a symbol
23332450 table with every live procedure and variable by `Module.name`, and
23342451 the compile unit that names the line table. The line table is in the
@@ -2354,7 +2471,55 @@
23542471 notes `Chunk.noteLine` made, and the single compile unit gdb needs to find
23552472 it, which `putDebug` writes. There are no types or variables in it;
23562473 gdb can stop at a line and show where it is, not print a variable.
2474+
2475+## Exe.darwin.raz: the Mac's executable
23572476
2477+`Exe` for macOS on arm64 writes Mach-O as dyld, the dynamic loader,
2478+takes it and the kernel runs it, with the same calls as Linux's: the
2479+driver's `needLib`, `setStripped` and `write` mean what they mean
2480+there, and `setMusl` refuses musl. `-base` is refused, since macOS
2481+loads a program where it chooses, and a library besides libSystem
2482+isn't linked yet. The file:
2483+
2484+| Part | What |
2485+|---|---|
2486+| header | `MH_EXECUTE` for `CPU_TYPE_ARM64`, flags `MH_PIE` and the dynamic loader's |
2487+| `__PAGEZERO` | 4 GB at address 0, no access: arm64 macOS runs no program without it |
2488+| `__TEXT` | the header again, at 0, and the code, read and run |
2489+| `__DATA_CONST` | rodata, which dyld makes read-only once it has rebased it (`SG_READ_ONLY`) |
2490+| `__DATA` | the variables and C's symbols' quadwords, zeros, not in the file |
2491+| `__LINKEDIT` | dyld's opcodes, the symbol table, and the code signature |
2492+
2493+and its load commands: `LC_DYLD_INFO_ONLY` for the rebases and binds;
2494+`LC_SYMTAB` with each named live chunk, as on Linux, a local symbol
2495+for lldb, and `LC_DYSYMTAB`, which says all are local;
2496+`LC_LOAD_DYLINKER` naming `/usr/lib/dyld`; `LC_UUID`, the first 16
2497+bytes of the SHA-256 of what follows the header; `LC_BUILD_VERSION`,
2498+macOS 11.0 and up; `LC_MAIN`, the entry point's offset; `LC_LOAD_DYLIB`,
2499+`/usr/lib/libSystem.B.dylib`; and `LC_CODE_SIGNATURE`. The header has
2500+the room of every command, `HeaderRoom`, as the code's place is fixed
2501+before the commands' sizes are known.
2502+
2503+Rodata holds the addresses of other chunks (a constant's data fixups),
2504+and macOS loads a program anywhere, so dyld must move each: a rebase.
2505+C's symbols are bound into their quadwords from libSystem by name,
2506+with Mach-O's `_` before it. Both are dyld's opcodes, the plainest form
2507+it still takes: a rebase is `SET_SEGMENT_AND_OFFSET_ULEB` and
2508+`DO_REBASE_IMM_TIMES`, two bytes and the offset; a bind the symbol's
2509+name, its segment and offset, and `DO_BIND`. The other form, chained
2510+fixups, which Apple's linker writes now, threads them through the data
2511+itself with tables of where each chain starts on each page.
2512+
2513+arm64 macOS runs nothing unsigned, so the file ends with an ad-hoc
2514+code signature, which the kernel checks as it maps each page: a
2515+SuperBlob holding one CodeDirectory, big-endian, of version 20400H
2516+(with the executable segment, `__TEXT`), flags ad hoc and the linker's,
2517+the program's name, and a SHA-256 hash of each page of 4 KB of the
2518+file before the signature. `putHash` is SHA-256 (FIPS 180-4), as
2519+`site/Sha256.raz` has it, made for bytes rather than hex. `otool -l`,
2520+`codesign -v -v` and `vtool -show` read the file as Apple's tools
2521+make it.
2522+
23582523 ## Host.linux.raz: the system running the compiler
23592524
23602525 The host is the system running raz; the target is the system its
@@ -2401,7 +2566,11 @@
24012566 export, `CLib` too, and opens with what it is, as raz's does.
24022567 `test/host/Host.raz` is such a file (its library from the environment,
24032568 no run, no C), and `test/compiler-host.sh` builds the compiler with it
2404-and checks the four differences. The host changes nothing of the target:
2569+and checks the four differences. `src/cross.sh darwin-arm64` builds the
2570+compiler for the Mac this way, in the linux/amd64 container, and `make
2571+mac-check` (`test/mac.sh`), on an Apple Silicon Mac, has it compile
2572+`test/mac`'s programs there and runs each here, natively, against its
2573+`X.expect` and `X.status`. The host changes nothing of the target:
24052574 a program for another system still needs that system's `Sys` and `Rt`,
24062575 and for a kernel the options `-bare`, `-s` and `-base`.
24072576

lib/CAbi.darwin-arm64.raz (history) added +225 -0

@@ -0,0 +1,225 @@
1+(* CAbi: what the C library fixes for Sys over C on darwin-arm64: the
2+ numbers of its flags, requests, signals and limits, where the
3+ fields of its structs lie, an At the offset and a Len the width,
4+ its errnos beside Linux's, and errno and closeFrom.
5+
6+ Written by tools/cabi.c, from the system's own headers; not to be
7+ edited, but written again. *)
8+module CAbi;
9+import SYSTEM;
10+
11+const
12+ (* open's flags, fcntl's requests, seek, flock, mmap, access *)
13+ oRdonly* = 0;
14+ oWronly* = 1;
15+ oRdwr* = 2;
16+ oCreat* = 512;
17+ oExcl* = 2048;
18+ oTrunc* = 1024;
19+ oAppend* = 8;
20+ oNonblock* = 4;
21+ oCloexec* = 16777216;
22+ oNoctty* = 131072;
23+ fGetfd* = 1;
24+ fSetfd* = 2;
25+ fGetfl* = 3;
26+ fSetfl* = 4;
27+ fDupfdCloexec* = 67;
28+ fdCloexec* = 1;
29+ seekSet* = 0;
30+ seekCur* = 1;
31+ seekEnd* = 2;
32+ lockEx* = 2;
33+ lockSh* = 1;
34+ lockNb* = 4;
35+ protRead* = 1;
36+ protWrite* = 2;
37+ mapShared* = 1;
38+ mapPrivate* = 2;
39+ mapAnonymous* = 4096;
40+ mfdCloexec* = 0;
41+ atFdcwd* = -2;
42+ fOk* = 0;
43+ rOk* = 4;
44+ wOk* = 2;
45+ xOk* = 1;
46+ (* struct stat, statvfs and dirent *)
47+ statLen* = 144;
48+ stDevAt* = 0;
49+ stDevLen* = 4;
50+ stInoAt* = 8;
51+ stInoLen* = 8;
52+ stNlinkAt* = 6;
53+ stNlinkLen* = 2;
54+ stModeAt* = 4;
55+ stModeLen* = 2;
56+ stSizeAt* = 96;
57+ stSizeLen* = 8;
58+ stUidAt* = 16;
59+ stUidLen* = 4;
60+ stGidAt* = 20;
61+ stGidLen* = 4;
62+ stMtimeAt* = 48;
63+ stMtimeLen* = 8;
64+ stMtimeNsAt* = 56;
65+ stMtimeNsLen* = 8;
66+ sIfmt* = 61440;
67+ sIfdir* = 16384;
68+ sIfreg* = 32768;
69+ sIflnk* = 40960;
70+ statvfsLen* = 64;
71+ fFrsizeAt* = 8;
72+ fFrsizeLen* = 8;
73+ fBlocksAt* = 16;
74+ fBlocksLen* = 4;
75+ fBavailAt* = 24;
76+ fBavailLen* = 4;
77+ dNameAt* = 21;
78+ dTypeAt* = 20;
79+ dtUnknown* = 0;
80+ dtDir* = 4;
81+ dtReg* = 8;
82+ dtLnk* = 10;
83+ (* the terminal, poll and the clocks *)
84+ tcsanow* = 0;
85+ tcsadrain* = 1;
86+ tiocgwinsz* = 1074295912;
87+ tiocswinsz* = 2148037735;
88+ tiocsctty* = 536900705;
89+ pollin* = 1;
90+ pollout* = 4;
91+ clockRealtime* = 0;
92+ clockMonotonic* = 6;
93+ timerAbstime* = 0;
94+ (* sockets, their addresses, and a message with fds *)
95+ afUnix* = 1;
96+ afInet* = 2;
97+ afInet6* = 30;
98+ sockStream* = 1;
99+ sockDgram* = 2;
100+ sockCloexec* = 0;
101+ sockNonblock* = 0;
102+ solSocket* = 65535;
103+ soReuseaddr* = 4;
104+ soError* = 4103;
105+ soPeercred* = -1;
106+ shutWr* = 1;
107+ msgNosignal* = 524288;
108+ msgDontwait* = 128;
109+ msgCmsgCloexec* = 0;
110+ scmRights* = 1;
111+ sockaddrLen* = 128;
112+ saFamilyAt* = 1;
113+ saFamilyLen* = 1;
114+ saLenAt* = 0;
115+ sockaddrUnLen* = 106;
116+ sunPathAt* = 2;
117+ sunPathLen* = 104;
118+ sockaddrInLen* = 16;
119+ sinPortAt* = 2;
120+ sinAddrAt* = 4;
121+ sockaddrIn6Len* = 28;
122+ sin6PortAt* = 2;
123+ sin6AddrAt* = 8;
124+ ucPidAt* = 0;
125+ ucPidLen* = 0;
126+ ucUidAt* = 4;
127+ ucUidLen* = 4;
128+ msghdrLen* = 48;
129+ msgIovAt* = 16;
130+ msgIovlenAt* = 24;
131+ msgIovlenLen* = 8;
132+ msgControlAt* = 32;
133+ msgControllenAt* = 40;
134+ msgControllenLen* = 4;
135+ cmsgLenAt* = 0;
136+ cmsgLenLen* = 4;
137+ cmsgLevelAt* = 4;
138+ cmsgTypeAt* = 8;
139+ cmsgDataAt* = 12;
140+ cmsgAlign* = 4;
141+ (* signals, sigaction and sigprocmask *)
142+ sigHup* = 1;
143+ sigInt* = 2;
144+ sigQuit* = 3;
145+ sigFpe* = 8;
146+ sigKill* = 9;
147+ sigUsr1* = 30;
148+ sigSegv* = 11;
149+ sigUsr2* = 31;
150+ sigPipe* = 13;
151+ sigAlrm* = 14;
152+ sigTerm* = 15;
153+ sigChld* = 20;
154+ sigCont* = 19;
155+ sigStop* = 17;
156+ sigTstp* = 18;
157+ sigTtin* = 21;
158+ sigTtou* = 22;
159+ sigWinch* = 28;
160+ sigMax* = 31;
161+ sigactionLen* = 16;
162+ saHandlerAt* = 0;
163+ saMaskAt* = 8;
164+ saFlagsAt* = 12;
165+ saFlagsLen* = 4;
166+ sigsetLen* = 4;
167+ saRestart* = 2;
168+ sigSetmask* = 3;
169+ (* limits, time used, and wait *)
170+ rlimitCpu* = 0;
171+ rlimitFsize* = 1;
172+ rlimitData* = 2;
173+ rlimitStack* = 3;
174+ rlimitCore* = 4;
175+ rlimitNproc* = 7;
176+ rlimitNofile* = 8;
177+ rlimitAs* = 5;
178+ rlimInfinity* = 9223372036854775807;
179+ rusageSelf* = 0;
180+ rusageChildren* = -1;
181+ ruUtimeAt* = 0;
182+ ruStimeAt* = 16;
183+ tvSecAt* = 0;
184+ tvSecLen* = 8;
185+ tvUsecAt* = 8;
186+ tvUsecLen* = 4;
187+ wNohang* = 1;
188+ wUntraced* = 2;
189+ (* errnos: EINTR; and each POSIX names, the C library's number, then Linux's *)
190+ eIntr* = 4;
191+ errnos*: [152]I32 = [
192+ 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
193+ 7, 7, 8, 8, 9, 9, 10, 10, 35, 11, 12, 12,
194+ 13, 13, 14, 14, 16, 16, 17, 17, 18, 18, 19, 19,
195+ 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25,
196+ 26, 26, 27, 27, 28, 28, 29, 29, 30, 30, 31, 31,
197+ 32, 32, 33, 33, 34, 34, 11, 35, 63, 36, 77, 37,
198+ 78, 38, 66, 39, 62, 40, 91, 42, 90, 43, 97, 67,
199+ 100, 71, 95, 72, 94, 74, 84, 75, 92, 84, 38, 88,
200+ 39, 89, 40, 90, 41, 91, 42, 92, 43, 93, 45, 95,
201+ 102, 95, 47, 97, 48, 98, 49, 99, 50, 100, 51, 101,
202+ 52, 102, 53, 103, 54, 104, 55, 105, 56, 106, 57, 107,
203+ 60, 110, 61, 111, 65, 113, 37, 114, 36, 115, 70, 116,
204+ 69, 122, 89, 125, 105, 130, 104, 131];
205+
206+extern proc __error: ^I32;
207+extern proc close(fd: I32): I32;
208+extern proc getdtablesize: I32;
209+
210+(* errno, this thread's *)
211+proc errno*: ^I32;
212+begin
213+ return __error();
214+end;
215+
216+(* Closes the fds from lo to hi, or every one from lo if hi < 0: one
217+ by one, as macOS has no close_range. *)
218+proc closeFrom*(lo, hi: INT);
219+var fd: INT;
220+begin
221+ if hi < 0 then hi := INT(getdtablesize()) - 1; end;
222+ for fd := lo to hi do _ := close(I32(fd)); end;
223+end;
224+
225+end CAbi.

lib/Rt.darwin-arm64.raz (history) added +93 -0

@@ -0,0 +1,93 @@
1+(* The run time, for macOS on arm64: for now the least a program needs
2+ to end, with lib/Rt.raz's interface, which every file of Rt keeps.
3+ The compiler finds exit, fail and cExit by these names. exit runs
4+ the procedure atExit registered, then ends the program by C's exit,
5+ which the entry point gives cExit, as every program on a Mac reaches
6+ the kernel through libSystem; fail and stop say what failed and end
7+ it with status 2. It leaves out what lib/Rt.raz does on Linux, which
8+ PLAN.md 5's step 7 brings here: more than one procedure at exit, the
9+ places a failure is told by, the signals' handlers, the trace of
10+ calls and the profiler; place, trace and startProfile do nothing. *)
11+module Rt;
12+import SYSTEM;
13+
14+const
15+ Full*: ERROR = "too many procedures to run at exit"; (* atExit's *)
16+ Failed = "raz: a check failed\n";
17+
18+extern proc write(fd: I32; buf: ^U8; n: UINT): INT;
19+
20+var
21+ atExitProc: proc; (* the procedure atExit registered, or nil *)
22+ ending: INT; (* the status exit was given, once it has been *)
23+ cExit: proc(status: I32); (* C's exit, set first thing *)
24+ placer: proc(a: UINT); (* place, set first thing, or nil under raz -s *)
25+ profiler: proc; (* startProfile, set first thing, or nil *)
26+
27+(* Registers p to run when the program ends by exit: one, for now *)
28+proc atExit*(p: proc): ERROR;
29+begin
30+ if atExitProc # nil then return Full; end;
31+ atExitProc := p;
32+ return nil;
33+end;
34+
35+(* The status exit was given, while the procedure atExit registered
36+ runs; 0 before *)
37+proc exitStatus*: INT;
38+begin
39+ return ending;
40+end;
41+
42+(* Runs the procedure atExit registered, taken off first so that it
43+ runs once, then ends the program with status *)
44+proc exit*(status: INT);
45+var p: proc;
46+begin
47+ ending := status;
48+ if atExitProc # nil then
49+ p := atExitProc;
50+ atExitProc := nil;
51+ p();
52+ end;
53+ cExit(I32(status));
54+end;
55+
56+(* Says msg, and then a line feed, on standard error, then ends the
57+ program by exit with status 2 *)
58+proc stop*(msg: []const U8);
59+begin
60+ _ := write(2, SYSTEM.PTR(msg), UINT(LEN(msg)));
61+ _ := write(2, SYSTEM.PTR("\n"), 1);
62+ exit(2);
63+end;
64+
65+(* Where the code at address a comes from: not told yet *)
66+proc place*(a: UINT);
67+begin
68+ _ := a;
69+end;
70+
71+(* The calls under way: not told yet *)
72+proc trace*;
73+begin
74+end;
75+
76+(* A check failed: the compiler's code calls this with what failed,
77+ its values and where, none of which it tells yet *)
78+proc fail*(what, a, b, len: INT; at: UINT; name: ^U8; rdi, rsi: UINT);
79+begin
80+ _ := what; _ := a; _ := b; _ := len; _ := name; _ := rdi; _ := rsi;
81+ if placer # nil then placer(at); end;
82+ _ := write(2, SYSTEM.PTR(Failed), LEN(Failed));
83+ exit(2);
84+end;
85+
86+(* The profiler: none yet *)
87+proc startProfile*;
88+begin
89+end;
90+
91+begin
92+ _ := profiler; (* started here when RAZ_PROFILE is set, by step 7's Rt *)
93+end Rt.

src/A64.raz (history) modified +5 -10

@@ -25,8 +25,8 @@
2525
2626 Depends on: Scan, for errors and the assembler's symbols; Diag, for
2727 positions and text; Chunk, for the code buffer and fixups.
28- Leaves out: choosing instructions; that is Gen (Gen.arm64.raz, to
29- come). Only what Gen and the library's code procedures need is here;
28+ Leaves out: choosing instructions; that is Gen (Gen.arm64.raz, which
29+ calls it). Only what Gen and the library's code procedures need is here;
3030 `db` and `dd` give any other instruction. *)
3131 module A64;
3232 import Out, Fmt, Str, Diag, Scan, Chunk;
@@ -75,14 +75,9 @@
7575 Nop = 0D503201FH;
7676
7777 type
78- (* The parser's reader of an integer constant in a code procedure: a
79- whole expression, or, when whole is false, a single factor *)
80- ConstFn* = proc(whole: BOOL): (I64, ERROR);
81-
82- (* The parser's reader of a name that stands for an address: a
83- procedure or a module variable. Its chunk, the name read; or -1,
84- nothing read, if the name is anything else *)
85- NameFn* = proc: (INT, ERROR);
78+ (* The parser's readers of a constant and of a name (Scan says) *)
79+ ConstFn* = Scan.ConstFn;
80+ NameFn* = Scan.NameFn;
8681
8782 (* The text of the instruction that starts at at, for the listing *)
8883 Said = record

src/Chunk.raz (history) modified +25 -4

@@ -35,6 +35,8 @@
3535 realsAt*: Diag.Pos;
3636 saveMask*: INT; (* code: the registers of variables it saves, as bits of Gen's VarRegs *)
3737 saveAt*: INT; (* ... at this offset from the frame, one quadword each *)
38+ missing*: []const U8; (* code: what the target's Gen can't make yet, first at missingAt; "" if none *)
39+ missingAt*: Diag.Pos;
3840 end;
3941
4042 (* A place in the source whose code starts at a place in text: for
@@ -64,8 +66,7 @@
6466 by the size a load or store reads from its own
6567 bits (31 and 30, or 16 for a q register), as
6668 ARM64_RELOC_PAGEOFF12 is
67- Link patches only fxRel32 yet: arm64's come with Exe.darwin.raz
68- (PLAN.md 5, step 6). *)
69+ Link patches them all. *)
6970 FixKind* = (fxRel32, fxBranch26, fxPage21, fxPageOff12);
7071
7172 Fixup* = record
@@ -97,6 +98,11 @@
9798 curChunk*: INT; (* the chunk of code being written *)
9899 varNotes*: ^VarNote;
99100 numVarNotes*: INT;
101+ (* What fills the gaps between procedures in text, Gen's (setPad): a
102+ word of four bytes, the byte at an offset that is i more than a
103+ multiple of 4 its byte i, a trap if it were ever run: int3, CC,
104+ on x86, brk on arm64 *)
105+ pad*: INT;
100106
101107 codeCap, roCap, chunkCap, fixCap, dataFixCap, lineCap, noteCap: INT;
102108
@@ -185,8 +191,8 @@
185191 (* code is aligned to 32 bytes, the windows in which x86 fetches and
186192 caches it, so that a procedure's loops sit in them the same way
187193 whatever comes before: rat ran 5% slower at 16, by where its loops
188- fell. Padded with CC, x86's int3: a trap if it were ever run *)
189- while pc & 31 # 0 do put1(0CCH); end;
194+ fell. Padded with Gen's trap (pad) *)
195+ while pc & 31 # 0 do put1(pad shr (8 * (pc & 3))); end;
190196 curChunk := c;
191197 chunks[c].start := pc;
192198 chunks[c].align := 32;
@@ -356,6 +362,21 @@
356362 begin
357363 chunks[c].reals := true;
358364 chunks[c].realsAt := p;
365+end;
366+
367+(* Chunk c holds code its Gen can't make yet, what, the first at p: an
368+ error if c is live (Raz), as a program can't use what isn't made *)
369+proc setMissing*(c: INT; what: []const U8; p: Diag.Pos);
370+begin
371+ if LEN(chunks[c].missing) = 0 then
372+ chunks[c].missing := what;
373+ chunks[c].missingAt := p;
374+ end;
375+end;
376+
377+proc setPad*(word: INT);
378+begin
379+ pad := word;
359380 end;
360381
361382 proc setSaves*(c, mask, at: INT);

src/Exe.darwin.raz (history) added +458 -0

@@ -0,0 +1,458 @@
1+(* Exe: the executable file, for macOS on arm64: Mach-O.
2+
3+ Exe.linux.raz, for Linux, is ELF; a target has one Exe, chosen by the
4+ suffix of its file (doc/raz.md, 3), and no other unit knows the
5+ format. This one writes a Mach-O executable as dyld, macOS's dynamic
6+ loader, takes one, and the kernel runs one on arm64:
7+
8+ the header and load commands
9+ __PAGEZERO 4 GB at address 0, no access: arm64 macOS runs no
10+ program without it, so a nil pointer faults
11+ __TEXT the header again, and the code, read and run
12+ __DATA_CONST rodata, made read-only once dyld has moved the
13+ addresses in it (rebases)
14+ __DATA the variables, zeros, and C's symbols' quadwords, which
15+ dyld fills in (binds)
16+ __LINKEDIT what dyld reads, unmapped by the program: the rebases
17+ and binds, the symbol table, and the code signature
18+
19+ Each segment starts on a page of 16 KB, in the file as in memory, at
20+ its offset in the file from __TEXT's address (Link.setPaged). macOS
21+ loads a program at an address of its own choosing (MH_PIE), so every
22+ address held in data is listed for dyld to move with it: those in
23+ rodata, which Link lists (Link.rebases); code makes its addresses by
24+ adrp from its own. Every program is linked to libSystem, through
25+ which a Mac's program reaches the kernel; C's symbols are bound from
26+ it, as Linux's GLOB_DAT does it, into quadwords the code reads. The
27+ rebases and binds are dyld's opcodes (LC_DYLD_INFO_ONLY), the
28+ plainest form dyld still takes: a few bytes for each address, where
29+ chained fixups would thread them through the data with tables to say
30+ where each chain starts. arm64 macOS runs nothing unsigned, so the
31+ file ends with an ad-hoc code signature: a SHA-256 hash of each of
32+ its pages of 4 KB, in a CodeDirectory, which the kernel checks as it
33+ maps them.
34+
35+ Depends on: Link for the images and addresses, Chunk for the chunks,
36+ Scan for names and memory, Diag for errors, Host to write the file.
37+ Leaves out: line numbers (DWARF, in __DWARF, PLAN.md 5), libraries
38+ besides libSystem, an export trie (the program exports nothing).
39+
40+ Exported variables can't be set from outside, so needLib, setMusl,
41+ setMainPath and setStripped do it. *)
42+module Exe;
43+import Host, Fmt, Diag, Scan, Chunk, Link;
44+import SYSTEM;
45+
46+const
47+ Os* = "darwin"; (* the target's operating system, as a file's suffix says it *)
48+ Base = 100000000H; (* __TEXT's address, past __PAGEZERO; dyld moves it *)
49+ Page = 4000H; (* arm64 macOS's page, 16 KB, on which each segment starts *)
50+ HashPage = 1000H; (* the signature hashes pages of 4 KB *)
51+ Dyld = "/usr/lib/dyld";
52+ (* room for the header and the most load commands: see write *)
53+ HeaderRoom = 32 + 72 + 3 * 152 + 72 + 48 + 24 + 80 + 32 + 24 + 24 + 24 + 56 + 16;
54+
55+var
56+ needed: [32]INT; (* the libraries to load, names interned *)
57+ numNeeded*: INT;
58+ stripped*: BOOL; (* -s: no symbols *)
59+ libc*: []const U8; (* the C library, libSystem *)
60+
61+ buf: ^U8;
62+ len, cap: INT;
63+
64+(* The library name, to be loaded, unless it is already: false if there
65+ are too many *)
66+proc needLib*(name: INT): BOOL;
67+var i: INT;
68+begin
69+ for i := 0 to numNeeded - 1 do
70+ if needed[i] = name then return true; end;
71+ end;
72+ if numNeeded = 32 then return false; end;
73+ needed[numNeeded] := name;
74+ INC(numNeeded);
75+ return true;
76+end;
77+
78+proc noLibs*;
79+begin
80+ numNeeded := 0;
81+end;
82+
83+(* -libc chooses Linux's C library; a Mac has one, libSystem *)
84+proc setMusl*(yes: BOOL);
85+begin
86+ if yes then Diag.fatal("-libc musl: a program for macOS is linked to libSystem"); end;
87+end;
88+
89+(* The main module's file, which line numbers will name *)
90+proc setMainPath*(path: []const U8);
91+begin
92+ _ := path;
93+end;
94+
95+proc setStripped*(yes: BOOL);
96+begin
97+ stripped := yes;
98+end;
99+
100+proc room(n: INT);
101+begin
102+ if len + n > cap then
103+ buf := Scan.regrab(buf, len, cap * 2 + n);
104+ cap := cap * 2 + n;
105+ end;
106+end;
107+
108+(* The n low bytes of v, least significant first, as Mach-O is *)
109+proc putN(v: INT; n: INT);
110+var i: INT;
111+begin
112+ room(n);
113+ for i := 0 to n - 1 do
114+ buf[len] := U8(v & 0FFH);
115+ v := v shr 8;
116+ INC(len);
117+ end;
118+end;
119+
120+(* The n low bytes of v, most significant first, as the signature is *)
121+proc putBE(v: INT; n: INT);
122+var i: INT;
123+begin
124+ for i := n - 1 to 0 by -1 do putN(v shr (8 * i), 1); end;
125+end;
126+
127+proc putBytes(p: ^U8; n: INT);
128+begin
129+ room(n);
130+ if n > 0 then COPY(buf[len..len + n], p[0..n]); end;
131+ len := len + n;
132+end;
133+
134+proc padTo(off: INT);
135+begin
136+ while len < off do putN(0, 1); end;
137+end;
138+
139+(* s and a zero byte *)
140+proc putStr(s: []const U8);
141+begin
142+ putBytes(SYSTEM.PTR(s), LEN(s));
143+ putN(0, 1);
144+end;
145+
146+(* s in a field of n bytes, the rest zeros, as a segment's name *)
147+proc putName(s: []const U8; n: INT);
148+var at: INT;
149+begin
150+ at := len;
151+ putBytes(SYSTEM.PTR(s), LEN(s));
152+ padTo(at + n);
153+end;
154+
155+(* LEB128, unsigned, as dyld's opcodes take their operands *)
156+proc putU(v: INT);
157+begin
158+ while v >= 80H do
159+ putN(v & 7FH | 80H, 1);
160+ v := v shr 7;
161+ end;
162+ putN(v, 1);
163+end;
164+
165+(* n, up to a multiple of m *)
166+proc roundUp(n, m: INT): INT;
167+begin
168+ return (n + m - 1) div m * m;
169+end;
170+
171+(* SHA-256 (FIPS 180-4), for the signature's hashes: the message in
172+ blocks of 64 bytes, the last ones padded with a one bit, zeros and
173+ the message's length in bits *)
174+
175+const
176+ (* the first 32 bits of the cube roots of the first 64 primes *)
177+ K: [64]U32 = [
178+ 0428A2F98H, 071374491H, 0B5C0FBCFH, 0E9B5DBA5H, 03956C25BH, 059F111F1H, 0923F82A4H, 0AB1C5ED5H,
179+ 0D807AA98H, 012835B01H, 0243185BEH, 0550C7DC3H, 072BE5D74H, 080DEB1FEH, 09BDC06A7H, 0C19BF174H,
180+ 0E49B69C1H, 0EFBE4786H, 00FC19DC6H, 0240CA1CCH, 02DE92C6FH, 04A7484AAH, 05CB0A9DCH, 076F988DAH,
181+ 0983E5152H, 0A831C66DH, 0B00327C8H, 0BF597FC7H, 0C6E00BF3H, 0D5A79147H, 006CA6351H, 014292967H,
182+ 027B70A85H, 02E1B2138H, 04D2C6DFCH, 053380D13H, 0650A7354H, 0766A0ABBH, 081C2C92EH, 092722C85H,
183+ 0A2BFE8A1H, 0A81A664BH, 0C24B8B70H, 0C76C51A3H, 0D192E819H, 0D6990624H, 0F40E3585H, 0106AA070H,
184+ 019A4C116H, 01E376C08H, 02748774CH, 034B0BCB5H, 0391C0CB3H, 04ED8AA4AH, 05B9CCA4FH, 0682E6FF3H,
185+ 0748F82EEH, 078A5636FH, 084C87814H, 08CC70208H, 090BEFFFAH, 0A4506CEBH, 0BEF9A3F7H, 0C67178F2H];
186+
187+type Hash = [8]U32;
188+
189+(* Mixes the 64 bytes p into the running hash h *)
190+proc block(var h: Hash; p: []const U8);
191+var w: [64]U32; v: Hash; t1, t2: U32; i: INT;
192+begin
193+ for i := 0 to 15 do
194+ 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]);
195+ end;
196+ for i := 16 to 63 do
197+ w[i] := w[i - 16] + (ROR(w[i - 15], 7) xor ROR(w[i - 15], 18) xor (w[i - 15] shr 3))
198+ + w[i - 7] + (ROR(w[i - 2], 17) xor ROR(w[i - 2], 19) xor (w[i - 2] shr 10));
199+ end;
200+ v := h; (* a to h, as the standard names them, are v[0] to v[7] *)
201+ for i := 0 to 63 do
202+ 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];
203+ 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]));
204+ v[7] := v[6]; v[6] := v[5]; v[5] := v[4]; v[4] := v[3] + t1;
205+ v[3] := v[2]; v[2] := v[1]; v[1] := v[0]; v[0] := t1 + t2;
206+ end;
207+ for i := 0 to 7 do h[i] := h[i] + v[i]; end;
208+end;
209+
210+(* The SHA-256 of data, its 32 bytes put at the end of buf *)
211+proc putHash(data: []const U8);
212+var h: Hash; tail: [128]U8; whole, rest, n, i: INT;
213+begin
214+ h := [06A09E667H, 0BB67AE85H, 03C6EF372H, 0A54FF53AH, 0510E527FH, 09B05688CH, 01F83D9ABH, 05BE0CD19H];
215+ whole := LEN(data) div 64 * 64;
216+ for i := 0 to whole - 64 by 64 do block(h, data[i..i + 64]); end;
217+ rest := LEN(data) - whole;
218+ FILL(tail, 0);
219+ COPY(tail[0..rest], data[whole..LEN(data)]);
220+ tail[rest] := 80H;
221+ n := 64;
222+ if rest >= 56 then n := 128; end;
223+ for i := 0 to 7 do tail[n - 1 - i] := U8(((LEN(data) * 8) shr (8 * i)) & 0FFH); end;
224+ for i := 0 to n - 64 by 64 do block(h, tail[i..i + 64]); end;
225+ for i := 0 to 7 do putBE(INT(h[i]), 4); end;
226+end;
227+
228+(* Load commands *)
229+
230+const
231+ LcSegment = 19H; LcSymtab = 2H; LcDysymtab = 0BH; LcLoadDylinker = 0EH; LcLoadDylib = 0CH;
232+ LcUuid = 1BH; LcBuildVersion = 32H; LcMain = 80000028H; LcDyldInfoOnly = 80000022H;
233+ LcCodeSignature = 1DH;
234+
235+(* A segment of 64 bits, followed by its nsects sections; prot is the
236+ access, 1 read, 2 write, 4 run *)
237+proc segment(name: []const U8; adr, vmSize, off, fileSize, prot, nsects, flags: INT);
238+begin
239+ putN(LcSegment, 4); putN(72 + 80 * nsects, 4);
240+ putName(name, 16);
241+ putN(adr, 8); putN(vmSize, 8); (* where it is loaded, and its size there *)
242+ putN(off, 8); putN(fileSize, 8); (* where it is in the file, and its size there *)
243+ putN(prot, 4); putN(prot, 4); (* the most access it may have, and what it has *)
244+ putN(nsects, 4); putN(flags, 4);
245+end;
246+
247+(* A section, what otool and lldb see of a segment: its name, its
248+ segment's, address, size, file offset, alignment as a power of two,
249+ no relocations, flags *)
250+proc section(name, seg: []const U8; adr, size, off, align, flags: INT);
251+begin
252+ putName(name, 16); putName(seg, 16);
253+ putN(adr, 8); putN(size, 8);
254+ putN(off, 4); putN(align, 4);
255+ putN(0, 4); putN(0, 4); (* relocations: none *)
256+ putN(flags, 4);
257+ putN(0, 12); (* reserved *)
258+end;
259+
260+(* Whether chunk c is a live C symbol, and a live chunk with a name the
261+ symbol table gives *)
262+proc isExt(c: INT): BOOL;
263+begin
264+ return Chunk.chunks[c].live and Chunk.chunks[c].ext;
265+end;
266+
267+proc isNamed(c: INT): BOOL;
268+begin
269+ return not stripped and Chunk.chunks[c].live and (Chunk.chunks[c].name >= 0) and not Chunk.chunks[c].ext;
270+end;
271+
272+proc write*(path: []const U8; entry: INT);
273+var
274+ c, i, n, textSize, leOff, leAdr, ncmds, segRo, segData, sectData: INT;
275+ rebaseOff, rebaseSize, bindOff, bindSize, symOff, nsyms, strOff, strSize, sigOff, sigSize, slots: INT;
276+ ident: []const U8;
277+ uuidAt, end0, sigRoom: INT;
278+begin
279+ if Link.base # 400000H then Diag.fatal("-base: macOS loads a program where it chooses"); end;
280+ for i := 1 to numNeeded - 1 do
281+ Diag.fatal(Diag.say("not yet on darwin-arm64: a library besides libSystem, {}", [Fmt.str(Scan.nameOf(needed[i]))]));
282+ end;
283+ cap := 1 shl 16;
284+ buf := Scan.grab(cap);
285+ len := 0;
286+ Link.setBase(Base);
287+ Link.setPaged(Page);
288+ Link.linkAll(HeaderRoom, 0, 0);
289+ textSize := roundUp(Link.textOff + Link.textSize, Page); (* __TEXT's, the header in it *)
290+ leOff := Link.bssOff; (* the next page in the file: __DATA has no bytes there *)
291+ leAdr := Link.bssAdr + roundUp(Link.bssSize, Page);
292+ (* the segments' numbers, as the opcodes name them, and the
293+ sections', as the symbols do: __PAGEZERO 0, __TEXT 1 (__text, 1) *)
294+ segRo := 2;
295+ segData := 2;
296+ sectData := 2;
297+ if Link.roSize > 0 then INC(segData); INC(sectData); end;
298+
299+ (* the code and rodata, after the room for the header *)
300+ padTo(Link.textOff);
301+ putBytes(Link.textImg, Link.textSize);
302+ padTo(Link.roOff);
303+ putBytes(Link.roImg, Link.roSize);
304+ padTo(leOff);
305+
306+ (* rebases: each word in rodata that holds an address, a pointer
307+ (type 1), at its segment and offset; then done *)
308+ rebaseOff := len;
309+ putN(11H, 1); (* REBASE_OPCODE_SET_TYPE_IMM, pointer *)
310+ for i := 0 to Link.numRebases - 1 do
311+ putN(20H | segRo, 1); putU(Link.rebases[i] - Link.roAdr); (* SET_SEGMENT_AND_OFFSET_ULEB *)
312+ putN(51H, 1); (* DO_REBASE_IMM_TIMES, once *)
313+ end;
314+ putN(0, 1); (* DONE *)
315+ padTo(roundUp(len, 8));
316+ rebaseSize := len - rebaseOff;
317+
318+ (* binds: each C symbol's quadword, from library 1, libSystem, by
319+ its name, which in Mach-O begins with _ *)
320+ bindOff := len;
321+ putN(11H, 1); (* BIND_OPCODE_SET_DYLIB_ORDINAL_IMM, 1 *)
322+ putN(51H, 1); (* SET_TYPE_IMM, pointer *)
323+ for c := 0 to Chunk.numChunks - 1 do
324+ if isExt(c) then
325+ putN(40H, 1); (* SET_SYMBOL_TRAILING_FLAGS_IMM, none *)
326+ putN(INT('_'), 1); putStr(Scan.nameOf(Chunk.chunks[c].name));
327+ putN(70H | segData, 1); putU(Chunk.chunks[c].adr - Link.bssAdr); (* SET_SEGMENT_AND_OFFSET_ULEB *)
328+ putN(90H, 1); (* DO_BIND *)
329+ end;
330+ end;
331+ putN(0, 1); (* DONE *)
332+ padTo(roundUp(len, 8));
333+ bindSize := len - bindOff;
334+
335+ (* the symbol table: a local symbol (N_SECT, 0EH) for each named
336+ live chunk, nlist_64: its name's offset, type, section, no
337+ description, its address; the names follow, after a 0 *)
338+ symOff := len;
339+ nsyms := 0;
340+ strSize := 1;
341+ for c := 0 to Chunk.numChunks - 1 do
342+ if isNamed(c) then
343+ putN(strSize, 4);
344+ putN(0EH, 1);
345+ match Chunk.chunks[c].sec of
346+ | secText: putN(1, 1);
347+ | secRodata: putN(2, 1);
348+ | secBss: putN(sectData, 1);
349+ end;
350+ putN(0, 2);
351+ putN(Chunk.chunks[c].adr, 8);
352+ strSize := strSize + LEN(Chunk.chunkName(c)) + 1;
353+ INC(nsyms);
354+ end;
355+ end;
356+ strOff := len;
357+ putN(0, 1);
358+ for c := 0 to Chunk.numChunks - 1 do
359+ if isNamed(c) then putStr(Chunk.chunkName(c)); end;
360+ end;
361+ padTo(roundUp(len, 16));
362+ strSize := len - strOff;
363+
364+ (* the signature's size: a SuperBlob of one blob, the CodeDirectory,
365+ of 88 bytes, the program's name, and a hash of each page up to
366+ the signature *)
367+ sigOff := len;
368+ i := LEN(path);
369+ while (i > 0) and (path[i - 1] # '/') do DEC(i); end;
370+ ident := path[i..LEN(path)];
371+ slots := roundUp(sigOff, HashPage) div HashPage;
372+ sigSize := 12 + 8 + 88 + LEN(ident) + 1 + 32 * slots;
373+ sigRoom := roundUp(sigSize, 16);
374+ room(sigRoom);
375+
376+ (* The header, in the room left for it, and the load commands. The
377+ UUID, which names this build for lldb, is the first 16 bytes of
378+ the hash of what follows the header. *)
379+ end0 := len;
380+ len := 0;
381+ putN(0FEEDFACFH, 4); (* MH_MAGIC_64 *)
382+ putN(0100000CH, 4); putN(0, 4); (* CPU_TYPE_ARM64, any of them *)
383+ putN(2, 4); (* MH_EXECUTE *)
384+ putN(0, 4); putN(0, 4); (* the commands' count and size, patched below *)
385+ putN(200085H, 4); (* MH_PIE, TWOLEVEL, DYLDLINK, NOUNDEFS *)
386+ putN(0, 4);
387+ ncmds := 0;
388+ segment("__PAGEZERO", 0, Base, 0, 0, 0, 0, 0); INC(ncmds);
389+ segment("__TEXT", Base, textSize, 0, textSize, 5, 1, 0); INC(ncmds);
390+ section("__text", "__TEXT", Base + Link.textOff, Link.textSize, Link.textOff, 5, 80000400H); (* instructions only *)
391+ if Link.roSize > 0 then
392+ (* SG_READ_ONLY, 10H: dyld takes write away once it has rebased *)
393+ segment("__DATA_CONST", Link.roAdr, roundUp(Link.roSize, Page), Link.roOff, roundUp(Link.roSize, Page), 3, 1, 10H); INC(ncmds);
394+ section("__const", "__DATA_CONST", Link.roAdr, Link.roSize, Link.roOff, 3, 0);
395+ end;
396+ if Link.bssSize > 0 then
397+ segment("__DATA", Link.bssAdr, roundUp(Link.bssSize, Page), 0, 0, 3, 1, 0); INC(ncmds);
398+ section("__bss", "__DATA", Link.bssAdr, Link.bssSize, 0, 3, 1); (* S_ZEROFILL *)
399+ end;
400+ segment("__LINKEDIT", leAdr, roundUp(sigOff + sigRoom - leOff, Page), leOff, sigOff + sigRoom - leOff, 1, 0, 0); INC(ncmds);
401+ putN(LcDyldInfoOnly, 4); putN(48, 4);
402+ putN(rebaseOff, 4); putN(rebaseSize, 4); putN(bindOff, 4); putN(bindSize, 4);
403+ putN(0, 24); (* weak and lazy binds, exports: none *)
404+ INC(ncmds);
405+ putN(LcSymtab, 4); putN(24, 4); putN(symOff, 4); putN(nsyms, 4); putN(strOff, 4); putN(strSize, 4); INC(ncmds);
406+ (* every symbol is local; none is defined for others or wanted *)
407+ putN(LcDysymtab, 4); putN(80, 4); putN(0, 4); putN(nsyms, 4); putN(nsyms, 4); putN(0, 4);
408+ putN(nsyms, 4); putN(0, 4); putN(0, 48); INC(ncmds);
409+ putN(LcLoadDylinker, 4); putN(32, 4); putN(12, 4); putName(Dyld, 20); INC(ncmds);
410+ putN(LcUuid, 4); putN(24, 4); uuidAt := len; putN(0, 16); INC(ncmds);
411+ putN(LcBuildVersion, 4); putN(24, 4);
412+ putN(1, 4); putN(0B0000H, 4); putN(0B0000H, 4); putN(0, 4); (* macOS, 11.0 and up, SDK 11.0, no tools *)
413+ INC(ncmds);
414+ putN(LcMain, 4); putN(24, 4); putN(Chunk.chunks[entry].adr - Base, 8); putN(0, 8); INC(ncmds);
415+ (* libSystem, version 1.0.0 and compatible with 1.0.0, which any is *)
416+ n := roundUp(24 + LEN(libc) + 1, 8);
417+ putN(LcLoadDylib, 4); putN(n, 4); putN(24, 4); putN(2, 4); putN(10000H, 4); putN(10000H, 4);
418+ putName(libc, n - 24); INC(ncmds);
419+ putN(LcCodeSignature, 4); putN(16, 4); putN(sigOff, 4); putN(sigRoom, 4); INC(ncmds);
420+ if len > HeaderRoom then Diag.fatal("internal error: the Mach-O header outgrew its room"); end;
421+ i := len;
422+ len := 16; putN(ncmds, 4); putN(i - 32, 4);
423+ len := end0;
424+ putHash(buf[Link.textOff..sigOff]);
425+ COPY(buf[uuidAt..uuidAt + 16], buf[len - 32..len - 16]);
426+ len := sigOff;
427+
428+ (* the signature, big-endian: the SuperBlob (CSMAGIC_EMBEDDED_SIGNATURE),
429+ its length and count, the index of its one blob, the
430+ CodeDirectory, at 20 *)
431+ putBE(0FADE0CC0H, 4); putBE(sigSize, 4); putBE(1, 4);
432+ putBE(0, 4); putBE(20, 4); (* CSSLOT_CODEDIRECTORY *)
433+ putBE(0FADE0C02H, 4); putBE(sigSize - 20, 4); (* CSMAGIC_CODEDIRECTORY *)
434+ putBE(20400H, 4); (* the version with the executable segment *)
435+ putBE(20002H, 4); (* ad hoc, and the linker's: no identity behind it *)
436+ putBE(88 + LEN(ident) + 1, 4); putBE(88, 4); (* where the hashes and the name are *)
437+ putBE(0, 4); putBE(slots, 4); (* no special slots; a slot a page *)
438+ putBE(sigOff, 4); (* what is hashed: all before the signature *)
439+ putN(32, 1); putN(2, 1); putN(0, 1); putN(12, 1); (* SHA-256's 32 bytes; no platform; pages of 2^12 *)
440+ putN(0, 4 + 4 + 4 + 4 + 8); (* no scatter, no team, a 32-bit limit *)
441+ putBE(0, 8); putBE(textSize, 8); (* the executable segment: __TEXT, from 0 *)
442+ putBE(1, 8); (* CS_EXECSEG_MAIN_BINARY *)
443+ putStr(ident);
444+ for i := 0 to slots - 1 do
445+ n := (i + 1) * HashPage;
446+ if n > sigOff then n := sigOff; end;
447+ putHash(buf[i * HashPage..n]);
448+ end;
449+ padTo(sigOff + sigRoom);
450+
451+ if not Host.writeExecutable(path, buf[0..len]) then
452+ Diag.fatal(Diag.say("can't write {}", [Fmt.str(path)]));
453+ end;
454+end;
455+
456+begin
457+ libc := "/usr/lib/libSystem.B.dylib";
458+end Exe.

src/Exe.linux.raz (history) modified +1 -1

@@ -1,6 +1,6 @@
11 (* Exe: the executable file, for Linux: ELF.
22
3- Exe.darwin.raz, for macOS, will be Mach-O; a target has one Exe, chosen
3+ Exe.darwin.raz, for macOS, is Mach-O; a target has one Exe, chosen
44 by the suffix of its file (doc/raz.md, 3), and no other unit knows the
55 format. This one writes an ELF64 executable: the ELF header, the
66 program headers, the linked text and rodata, and section headers

src/Gen.arm64.raz (history) added +1468 -0

@@ -0,0 +1,1468 @@
1+(* Gen: the code generator, for arm64 (Gen.arm64.raz; x86-64's is
2+ Gen.x86_64.raz, the suffix of the file choosing, doc/raz.md, 3).
3+
4+ The same stack machine as x86-64's, with the same calls, which Item
5+ and Parse make: they push constants, addresses and the values of
6+ variables, operate on the values on top, store them and jump on
7+ them. This one is begun: what it makes so far is frames, constants,
8+ the values of variables and their stores, the integer operations but
9+ division, comparisons and jumps, elements and slices unchecked,
10+ calls of procedures with integer arguments in registers, C's through
11+ the quadword the loader fills in, code procedures and the program's
12+ entry point. What else is
13+ asked is noted as "not yet on arm64" (notYet), and a program that
14+ uses it fails to compile rather than run wrong; PLAN.md 5 says the
15+ pieces still to come.
16+
17+ The stack is kept in registers as on x86-64: the value at depth d,
18+ depth 0 being the bottom, is in x9 to x14, register d mod 6, all of
19+ them registers a call may change and that carry no argument, so
20+ that a call moves its arguments into x0 to x7 in any order. A value
21+ that needs a register a lower one holds spills that one to a frame
22+ slot. A constant, or an address in the frame or of a chunk, is only
23+ noted until something needs it in a register. A variable's value is
24+ loaded when it is pushed: no instruction of arm64 but a load or a
25+ store takes memory.
26+
27+ Registers outside the stack: x15 and x17, Gen's scratch, as rax and
28+ rcx are on x86-64; x16, the encoder's (A64); x0 to x3 for copying
29+ and slices, between calls, where they hold nothing; x8, which Apple's convention
30+ keeps for the address of a result in memory; x18, the system's,
31+ never touched; x19 to x23, a procedure's busiest variables (VarRegs),
32+ which a called procedure gives back as it found them; x29, the frame
33+ pointer, and x30, the return address.
34+
35+ Calls use Apple's arm64 convention: the first eight integer arguments
36+ in x0 to x7, results in x0 and x1, sp a multiple of 16 always, a
37+ frame record of x29 and x30 that x29 points at, so that the chain of
38+ frames can be followed. A frame is made whole by the prologue, so
39+ nothing is pushed in a body: sp stays where the prologue put it, and
40+ pushed is always 0.
41+
42+ Depends on: Scan and Diag for errors, Sym for types, Chunk for code
43+ and data, A64 for instructions.
44+ Leaves out, for now: reals, division, checks, COPY and FILL,
45+ arguments and parameters on the machine's stack, results in memory,
46+ try, deferred statements, atomics and system calls. *)
47+module Gen;
48+import Fmt, Diag, Scan, Sym, Chunk, A := A64;
49+import SYSTEM;
50+
51+const
52+ Arch* = "arm64"; (* the target's machine, as a file's suffix says it *)
53+ NoLabel* = -1;
54+ WordSize* = 8; (* the size of an address, and of INT *)
55+ (* What the machine catches by itself: a load or store within
56+ NilPage bytes of address 0 (the Mac's page zero is 4 GB; this is
57+ Linux's figure until Rt tells the Mac's faults) *)
58+ NilPage* = 4096;
59+
60+ FP = A.FP; LR = A.LR; SP = A.SP; ZR = A.ZR;
61+ T = 15; U = 17; (* Gen's scratch *)
62+ Dst = 0; Src = 1; Tmp = 2; (* copying's *)
63+
64+type
65+ Kind* = (kWord, kLong, kF32, kF64);
66+
67+ (* Where a variable is: its address is relative to the frame, to a
68+ chunk, to an address on the stack, or to one held in a frame slot *)
69+ Base* = (bFrame, bGlobal, bStack, bSlot, bReg, bPtr);
70+ Adr* = record
71+ base*: Base;
72+ chunk*: INT; (* bGlobal: the chunk; bSlot: the frame slot; bReg: the register;
73+ bPtr: the register that holds the address *)
74+ off*: I64; (* added to the address; for bReg, which word, 0 or 8 *)
75+ hi*: INT; (* bReg, a slice: the register of its length, the
76+ second word; chunk is that of its pointer *)
77+ end;
78+
79+ (* The code made so far, to go back to for a second try at a body *)
80+ CodeMark* = record pc*, fixups*, lines*, said*, fails*, exit*: INT; end;
81+
82+ (* For entryPoint: the address of chunk, put in the variable whose
83+ chunk is into before the program starts; or, for C's symbols, the
84+ address in chunk, the quadword the loader fills in *)
85+ Link* = record chunk*, into*: INT; end;
86+
87+ CallInfo* = record
88+ sig*: ^Sym.Type;
89+ param*: ^Sym.Obj; (* the parameter the next argument is for *)
90+ obj*: ^Sym.Obj; (* the procedure called, if it has a name *)
91+ n*: INT; (* the arguments *)
92+ isF*: [64]BOOL; (* ... goes in a real's register *)
93+ pair*: [64]BOOL; (* ... is a slice's first word, the next its second *)
94+ target*: I64; (* the frame slot of a procedure value, if chunk < 0 *)
95+ chunk*: INT; (* else the procedure's chunk *)
96+ ext*: BOOL; (* C's: called through the chunk holding its address *)
97+ ret*: I64; (* set by call: the temporary a slice result is in *)
98+ end;
99+
100+const
101+ (* the registers a procedure keeps its busiest variables in, which a
102+ called procedure saves and gives back (Apple's x19 to x28); the
103+ trap report finds them where the prologue saved them *)
104+ VarRegs*: [5]INT = [19, 20, 21, 22, 23];
105+ (* the registers the trap report can show a variable in: VarRegs; no
106+ parameter is kept where it arrives, so the last two are none *)
107+ ShownRegs*: [7]INT = [19, 20, 21, 22, 23, -1, -1];
108+ (* the registers of real variables, d8 to d15, which a call keeps,
109+ numbered from XmmVar up so that they aren't taken for x8 to x15 *)
110+ XmmVar* = 32;
111+ XVarRegs*: [8]INT = [XmmVar + 8, XmmVar + 9, XmmVar + 10, XmmVar + 11,
112+ XmmVar + 12, XmmVar + 13, XmmVar + 14, XmmVar + 15];
113+ (* a procedure's registers of variables, as bits: bit i is VarRegs[i],
114+ bit XBit + i XVarRegs[i] *)
115+ XBit* = 5;
116+
117+var
118+ rtFail*, argcChunk*, argvChunk*: INT;
119+ lost*: BOOL; (* never set here: no parameter is kept where it arrived *)
120+ depth*: INT; (* the values on the stack *)
121+ pushed*: INT; (* quadwords pushed on the machine's stack: always 0 *)
122+ codeChunk*: INT; (* the procedure or body being compiled, or -1 *)
123+
124+type
125+ (* where a value on the stack is *)
126+ Loc = (lConst, (* not loaded: val is the value *)
127+ lAdr, (* not loaded: the address of chunk, or of the frame
128+ if chunk is -1, plus val *)
129+ lReg, (* in its register *)
130+ lFrame); (* spilled: in the frame slot val *)
131+
132+ Entry = record
133+ loc: Loc;
134+ val: I64;
135+ chunk: INT; (* lAdr: the chunk, or -1 for the frame *)
136+ k: Kind;
137+ end;
138+
139+ (* A place in memory: off from register base, or, if chunk >= 0, off
140+ into that chunk, reached by adrp (A64.loadChunk) *)
141+ Mem = record base, chunk: INT; off: I64; end;
142+
143+const
144+ MaxStack = 1024; (* values waiting in one expression *)
145+ NumRegs = 6;
146+ Regs: [NumRegs]INT = [9, 10, 11, 12, 13, 14];
147+ (* the condition codes of the comparisons, from sEql: = # < <= > >= *)
148+ CcSigned: [6]INT = [A.ccEQ, A.ccNE, A.ccLT, A.ccLE, A.ccGT, A.ccGE];
149+ CcUnsigned: [6]INT = [A.ccEQ, A.ccNE, A.ccLO, A.ccLS, A.ccHI, A.ccHS];
150+ (* sub sp, sp, #imm12 and the same shifted by 12: the prologue's two,
151+ whose immediates endProc patches *)
152+ SubSp = 0D10003FFH; SubSp12 = 0D14003FFH;
153+
154+var
155+ stack: [MaxStack]Entry;
156+ owner: [NumRegs]INT; (* the value in each register, or -1 *)
157+ frameTop, frameMax, permTop: I64;
158+ frameFix: INT; (* where the frame's two subs are *)
159+ paramTop: I64; (* the parameters' slots end here *)
160+ zeroTop: I64; (* the locals the prologue zeroes end here *)
161+ retSlot: I64;
162+ resType: ^Sym.Type; (* the procedure's result, or nil *)
163+ exitL: INT;
164+ (* parameters arriving in registers: where each is stored on entry *)
165+ inReg: [8]INT;
166+ inSlot: [8]I64;
167+ inSize: [8]INT;
168+ inObj: [8]^Sym.Obj;
169+ numIn: INT;
170+ regMask: INT; (* the registers of variables, as bits (XBit) *)
171+ saveAt: I64; (* where they are saved, a quadword each *)
172+ frameAt: [3]I64; (* frameTop, frameMax, permTop after the declarations *)
173+ pending: []const U8; (* what beginProc found not yet made, for enterBody's chunk *)
174+ pendingAt: Diag.Pos;
175+
176+(* What this Gen can't make yet marks the procedure being compiled
177+ (Chunk.setMissing), which is an error if the program uses it, and the
178+ compile reads on: a module the program imports may hold what it never
179+ calls, as Sys does. So each routine not yet made keeps the stack as
180+ the real one would, and makes what code it likes, never run; it
181+ reads into _ the parameters it doesn't use yet, so that none is
182+ warned of. *)
183+proc notYetAt(what: []const U8; p: Diag.Pos);
184+begin
185+ if codeChunk >= 0 then
186+ Chunk.setMissing(codeChunk, Diag.say("not yet on arm64: {}", [Fmt.str(what)]), p);
187+ elsif LEN(pending) = 0 then (* beginProc's, before enterBody names the chunk *)
188+ pending := Diag.say("not yet on arm64: {}", [Fmt.str(what)]);
189+ pendingAt := p;
190+ end;
191+end;
192+
193+(* The same, at the place being read *)
194+proc notYet(what: []const U8);
195+begin
196+ notYetAt(what, Scan.tokPos());
197+end;
198+
199+(* -S: the text of each instruction is kept, and list prints it *)
200+proc setListing*(yes: BOOL);
201+begin
202+ A.setListing(yes);
203+end;
204+
205+proc list*(home: INT);
206+begin
207+ A.list(home);
208+end;
209+
210+(* A variable changed in place, x := x + e, is x86-64's; here it is
211+ loaded and stored as any other *)
212+proc setInPlace*(r: INT);
213+begin
214+ _ := r;
215+end;
216+
217+proc kindOf*(t: ^Sym.Type): Kind;
218+begin
219+ if t^.form = Sym.fReal then
220+ if t^.size = 4 then return kF32; end;
221+ return kF64;
222+ end;
223+ if t^.size > WordSize then return kLong; end;
224+ return kWord;
225+end;
226+
227+(* The stack *)
228+
229+proc isReal(i: INT): BOOL;
230+begin
231+ return stack[i].k in {kF32, kF64};
232+end;
233+
234+proc allocTemp*(size, align: I64): I64; forward;
235+proc allocPerm*(size, align: I64): I64; forward;
236+proc loaded(i: INT): INT; forward;
237+
238+(* The value i, in its register, goes to a frame slot *)
239+proc spill(i: INT);
240+var s: I64;
241+begin
242+ _ := loaded(i);
243+ s := allocTemp(8, 8);
244+ A.store(Regs[i mod NumRegs], FP, INT(s), 8);
245+ stack[i].loc := lFrame;
246+ stack[i].val := s;
247+ owner[i mod NumRegs] := -1;
248+end;
249+
250+(* Every value below depth d in a register, spilled, as a call may
251+ change them *)
252+proc spillBelow(d: INT);
253+var r: INT;
254+begin
255+ for r := 0 to NumRegs - 1 do
256+ if (owner[r] >= 0) and (owner[r] < d) then spill(owner[r]); end;
257+ end;
258+end;
259+
260+(* The register of value i, for it to hold: a lower value there is
261+ spilled *)
262+proc claim(i: INT): INT;
263+var r: INT;
264+begin
265+ r := i mod NumRegs;
266+ if (owner[r] >= 0) and (owner[r] # i) then spill(owner[r]); end;
267+ owner[r] := i;
268+ return Regs[r];
269+end;
270+
271+(* The value i into register r, from wherever it is; it stays where it
272+ was, so r is a new copy *)
273+proc valueTo(i, r: INT);
274+begin
275+ match stack[i].loc of
276+ | lConst: A.movRI(r, stack[i].val);
277+ | lAdr:
278+ if stack[i].chunk >= 0 then A.addrChunk(r, stack[i].chunk, INT(stack[i].val));
279+ else A.aluI(A.opAdd, r, FP, stack[i].val); end;
280+ | lReg: if Regs[i mod NumRegs] # r then A.movRR(r, Regs[i mod NumRegs]); end;
281+ | lFrame: A.load(r, FP, INT(stack[i].val), 8, false);
282+ end;
283+end;
284+
285+(* The value i, in its register *)
286+proc loaded(i: INT): INT;
287+var r: INT;
288+begin
289+ if stack[i].loc # lReg then
290+ r := claim(i);
291+ valueTo(i, r);
292+ stack[i].loc := lReg;
293+ end;
294+ return Regs[i mod NumRegs];
295+end;
296+
297+proc top: INT;
298+begin
299+ if depth = 0 then Diag.fatal("internal error: the stack is empty"); end;
300+ return loaded(depth - 1);
301+end;
302+
303+(* A value on the stack's top; at its last place the compile ends, as on
304+ x86-64 *)
305+proc newEntry(k: Kind; loc: Loc; v: I64);
306+begin
307+ if depth > LEN(stack) - 1 then
308+ _ := Scan.mark(Diag.say("more than {} values waiting in one expression", [Fmt.int(MaxStack)]));
309+ Diag.finish();
310+ return;
311+ end;
312+ stack[depth].k := k;
313+ stack[depth].loc := loc;
314+ stack[depth].val := v;
315+ stack[depth].chunk := -1;
316+ INC(depth);
317+end;
318+
319+(* The register a new value on top is computed in *)
320+proc target: INT;
321+begin
322+ return claim(depth);
323+end;
324+
325+(* The value just computed in target goes on top *)
326+proc computed(k: Kind);
327+begin
328+ newEntry(k, lReg, 0);
329+end;
330+
331+(* drop emits no code, and the dropped value's register holds it until
332+ the next push claims it, which place and operands rely on *)
333+proc drop*;
334+begin
335+ DEC(depth);
336+ if owner[depth mod NumRegs] = depth then owner[depth mod NumRegs] := -1; end;
337+end;
338+
339+proc popTo(r: INT);
340+begin
341+ valueTo(depth - 1, r);
342+ drop();
343+end;
344+
345+proc topConst: (BOOL, I64);
346+begin
347+ return stack[depth - 1].loc = lConst, stack[depth - 1].val;
348+end;
349+
350+proc resetStack*(d, p: INT);
351+var r: INT;
352+begin
353+ depth := d;
354+ pushed := p;
355+ for r := 0 to NumRegs - 1 do owner[r] := -1; end;
356+end;
357+
358+proc pushConst*(k: Kind; v: I64);
359+begin
360+ if k in {kF32, kF64} then notYet("reals"); end;
361+ newEntry(k, lConst, v);
362+end;
363+
364+(* The register of the word at a, a variable in registers: the
365+ pointer's (off 0) or, for a slice, the length's (off 8) *)
366+proc regAt(a: Adr): INT;
367+begin
368+ if a.off = 0 then return a.chunk; end;
369+ return a.hi;
370+end;
371+
372+(* The memory a names. An address on the stack is popped, and is in its
373+ register still; one in a slot is loaded into r. *)
374+proc place(a: Adr; r: INT): Mem;
375+var m: Mem;
376+begin
377+ m.chunk := -1;
378+ m.off := a.off;
379+ match a.base of
380+ | bFrame: m.base := FP;
381+ | bGlobal: m.chunk := a.chunk;
382+ | bStack:
383+ if (stack[depth - 1].loc = lAdr) and (stack[depth - 1].chunk >= 0) then
384+ m.chunk := stack[depth - 1].chunk;
385+ m.off := m.off + stack[depth - 1].val;
386+ elsif stack[depth - 1].loc = lAdr then
387+ m.base := FP;
388+ m.off := m.off + stack[depth - 1].val;
389+ else
390+ m.base := loaded(depth - 1);
391+ end;
392+ drop();
393+ | bPtr: m.base := a.chunk;
394+ | bSlot:
395+ A.load(r, FP, a.chunk, 8, false);
396+ m.base := r;
397+ | bReg: Diag.fatal("internal error: a register has no address");
398+ end;
399+ return m;
400+end;
401+
402+(* Register r loaded from m, or stored there, size bytes *)
403+proc loadMem(r: INT; m: Mem; size: INT; signed: BOOL);
404+begin
405+ if m.chunk >= 0 then A.loadChunk(r, m.chunk, INT(m.off), size, signed);
406+ else A.load(r, m.base, INT(m.off), size, signed); end;
407+end;
408+
409+proc storeMem(r: INT; m: Mem; size: INT);
410+begin
411+ if m.chunk >= 0 then A.storeChunk(r, m.chunk, INT(m.off), size);
412+ else A.store(r, m.base, INT(m.off), size); end;
413+end;
414+
415+(* Register r := the address m *)
416+proc adrTo(r: INT; m: Mem);
417+begin
418+ if m.chunk >= 0 then A.addrChunk(r, m.chunk, INT(m.off));
419+ elsif (m.off # 0) or (m.base # r) then A.aluI(A.opAdd, r, m.base, m.off); end;
420+end;
421+
422+(* The address a names, on top of the stack *)
423+proc pushAdr*(a: Adr);
424+var m: Mem; r: INT;
425+begin
426+ if (a.base = bStack) and (a.off = 0) then return; end; (* it is on top already *)
427+ if a.base in {bFrame, bGlobal} then
428+ newEntry(kWord, lAdr, a.off);
429+ if a.base = bGlobal then stack[depth - 1].chunk := a.chunk; end;
430+ return;
431+ end;
432+ (* With the address on the stack, place pops it first, so that target
433+ may take its register; else target comes first, for place to load
434+ a slot's pointer into *)
435+ if a.base = bStack then
436+ m := place(a, U); r := target();
437+ else
438+ r := target(); m := place(a, r);
439+ end;
440+ adrTo(r, m);
441+ computed(kWord);
442+end;
443+
444+proc pushVar*(a: Adr; size: INT; signed: BOOL; k: Kind);
445+var m: Mem; r: INT;
446+begin
447+ if k in {kF32, kF64} then notYet("reals"); end;
448+ if a.base = bReg then
449+ r := target();
450+ A.movRR(r, regAt(a));
451+ computed(k);
452+ return;
453+ end;
454+ if a.base = bStack then
455+ m := place(a, U); r := target();
456+ else
457+ r := target(); m := place(a, r);
458+ end;
459+ loadMem(r, m, size, signed);
460+ computed(k);
461+end;
462+
463+proc pushProc*(c: INT; ext: BOOL);
464+var r: INT;
465+begin
466+ r := target();
467+ if ext then A.loadChunk(r, c, 0, 8, false); else A.addrChunk(r, c, 0); end;
468+ computed(kWord);
469+end;
470+
471+(* Pops a value into the variable at a; an address on the stack is under
472+ the value. A zero is stored from the zero register. *)
473+proc popVar*(a: Adr; size: INT);
474+var r: INT; v: I64; c: BOOL;
475+begin
476+ if isReal(depth - 1) then notYet("reals"); end;
477+ if a.base = bReg then
478+ popTo(regAt(a));
479+ return;
480+ end;
481+ c, v := topConst();
482+ if c and (v = 0) then r := ZR;
483+ elsif c then r := T; A.movRI(T, v);
484+ else r := loaded(depth - 1); end;
485+ drop();
486+ storeMem(r, place(a, U), size);
487+end;
488+
489+(* The two values on top change places, each loaded in its register *)
490+proc swap*;
491+var e: Entry; x, y: INT;
492+begin
493+ x := loaded(depth - 2);
494+ y := loaded(depth - 1);
495+ A.movRR(T, x);
496+ A.movRR(x, y);
497+ A.movRR(y, T);
498+ e := stack[depth - 2]; stack[depth - 2] := stack[depth - 1]; stack[depth - 1] := e;
499+end;
500+
501+(* Copying, by loads and stores of 8, 4, 2 and 1 bytes, from [x1] to
502+ [x0], through x2 *)
503+
504+const MaxMoves = 256;
505+
506+proc copyBytes(size: I64);
507+var o, n: I64;
508+begin
509+ if size > MaxMoves then notYet("a copy of more than 256 bytes"); return; end;
510+ o := 0;
511+ while o < size do
512+ n := 8;
513+ while n > size - o do n := n div 2; end;
514+ A.load(Tmp, Src, INT(o), INT(n), false);
515+ A.store(Tmp, Dst, INT(o), INT(n));
516+ INC(o, n);
517+ end;
518+end;
519+
520+proc zeroBytes(size: I64);
521+var o, n: I64;
522+begin
523+ if size > MaxMoves then notYet("zeroing more than 256 bytes"); return; end;
524+ o := 0;
525+ while o < size do
526+ n := 8;
527+ while n > size - o do n := n div 2; end;
528+ A.store(ZR, Dst, INT(o), INT(n));
529+ INC(o, n);
530+ end;
531+end;
532+
533+(* Pops a source's address, and a destination's under it, and copies
534+ size bytes to off bytes past the destination *)
535+proc copyBlock*(size, off: I64);
536+begin
537+ popTo(Src);
538+ popTo(Dst);
539+ if off # 0 then A.aluI(A.opAdd, Dst, Dst, off); end;
540+ copyBytes(size);
541+end;
542+
543+(* Pops a source's address, and copies size bytes to a: for a slice in
544+ registers, its two words into them *)
545+proc copyTo*(a: Adr; size: I64);
546+begin
547+ popTo(Src);
548+ if a.base = bReg then
549+ A.load(a.chunk, Src, 0, 8, false);
550+ A.load(a.hi, Src, 8, 8, false);
551+ return;
552+ end;
553+ adrTo(Dst, place(a, Dst));
554+ copyBytes(size);
555+end;
556+
557+proc zeroVar*(a: Adr; size: I64);
558+begin
559+ adrTo(Dst, place(a, Dst));
560+ zeroBytes(size);
561+end;
562+
563+(* Operations *)
564+
565+(* The right operand of the two values on top, popped, in register y:
566+ its own, or U for a constant; the left one stays, in its register,
567+ which is returned with y *)
568+proc operands: (INT, INT);
569+var v: I64; c: BOOL; y: INT;
570+begin
571+ c, v := topConst();
572+ if c then A.movRI(U, v); y := U; else y := loaded(depth - 1); end;
573+ drop();
574+ return top(), y;
575+end;
576+
577+(* The operation of two registers of +, -, &, | and xor *)
578+proc aluOf(sy: Scan.Sym): INT;
579+begin
580+ match sy of
581+ | sPlus: return A.opAdd;
582+ | sMinus: return A.opSub;
583+ | sAmp: return A.opAnd;
584+ | sBar: return A.opOrr;
585+ | else: return A.opEor;
586+ end;
587+end;
588+
589+(* The two values on top, the left op the right, an integer of size
590+ bytes, signed or not, computed in 64 bits and brought back to its
591+ width, which is how a narrow integer wraps. A shift's count is taken
592+ modulo the width, as x86-64's code takes it. *)
593+proc op*(sy: Scan.Sym; k: Kind; size: INT; signed: BOOL);
594+var v: I64; r, y, bits, sh: INT; c, alu: BOOL;
595+begin
596+ if k in {kF32, kF64} then notYet("reals"); end;
597+ if (sy = Scan.sDiv) or (sy = Scan.sMod) then notYet("div and mod"); end;
598+ bits := size * 8;
599+ alu := (sy = Scan.sPlus) or (sy = Scan.sMinus) or (sy = Scan.sAmp) or (sy = Scan.sBar) or (sy = Scan.sXor);
600+ (* a constant goes right, where it can be an immediate *)
601+ if (alu and (sy # Scan.sMinus) or (sy = Scan.sTimes)) and (stack[depth - 2].loc = lConst)
602+ and (stack[depth - 1].loc # lConst) then swap(); end;
603+ if sy = Scan.sShl then sh := A.shLsl; elsif signed then sh := A.shAsr; else sh := A.shLsr; end;
604+ c, v := topConst();
605+ if c and alu then
606+ drop();
607+ r := top();
608+ A.aluI(aluOf(sy), r, r, v);
609+ elsif c and ((sy = Scan.sShl) or (sy = Scan.sShr)) then
610+ drop();
611+ r := top();
612+ A.shiftI(sh, r, r, INT(v & I64(bits - 1)), 8);
613+ else
614+ r, y := operands();
615+ if alu then
616+ A.alu(aluOf(sy), r, r, y);
617+ elsif sy = Scan.sTimes then
618+ A.mul(r, r, y);
619+ else (* sShl, sShr: the machine takes the count modulo 64 *)
620+ if bits < 64 then A.aluI(A.opAnd, U, y, bits - 1); y := U; end;
621+ A.shift(sh, r, r, y, 8);
622+ end;
623+ end;
624+ if bits < 64 then A.extend(r, r, size, signed); end;
625+ stack[depth - 1].k := k;
626+end;
627+
628+proc rotate*(left: BOOL; size: INT);
629+begin
630+ _ := left; _ := size;
631+ notYet("ROL and ROR");
632+ drop(); (* the count *)
633+end;
634+
635+proc countZeros*(leading: BOOL; size: INT);
636+begin
637+ _ := leading; _ := size;
638+ notYet("CLZ and CTZ");
639+end;
640+
641+proc popCount*;
642+begin
643+ notYet("POPCOUNT");
644+end;
645+
646+proc abs*(k: Kind; size: INT);
647+begin
648+ _ := k; _ := size;
649+ notYet("ABS");
650+end;
651+
652+(* The two values on top, compared: a BOOL, 1 or 0 *)
653+proc compare*(sy: Scan.Sym; k: Kind; signed: BOOL);
654+var r, y, i: INT;
655+begin
656+ if k in {kF32, kF64} then notYet("reals"); end;
657+ i := INT(sy) - INT(Scan.sEql);
658+ r, y := operands();
659+ A.cmp(r, y);
660+ if signed then A.cset(CcSigned[i], r); else A.cset(CcUnsigned[i], r); end;
661+ stack[depth - 1].k := kWord;
662+end;
663+
664+proc neg*(k: Kind; size: INT; signed: BOOL);
665+var r: INT;
666+begin
667+ if k in {kF32, kF64} then notYet("reals"); end;
668+ r := top();
669+ A.neg(r, r);
670+ if size < 8 then A.extend(r, r, size, signed); end;
671+end;
672+
673+proc complement*(size: INT; signed: BOOL);
674+var r: INT;
675+begin
676+ r := top();
677+ A.mvn(r, r);
678+ if size < 8 then A.extend(r, r, size, signed); end;
679+end;
680+
681+proc notBool*;
682+var r: INT;
683+begin
684+ r := top();
685+ A.aluI(A.opEor, r, r, 1);
686+end;
687+
688+(* The integer on top, brought to size bytes *)
689+proc narrow*(size: INT; signed: BOOL);
690+var r: INT;
691+begin
692+ r := top();
693+ if size < 8 then A.extend(r, r, size, signed); end;
694+ stack[depth - 1].k := kWord;
695+end;
696+
697+proc intToReal*(k: Kind; big: BOOL);
698+begin
699+ _ := big;
700+ notYet("reals");
701+ stack[depth - 1].k := k;
702+end;
703+
704+proc realToInt*(k: Kind);
705+begin
706+ _ := k;
707+ notYet("reals");
708+ stack[depth - 1].k := kWord;
709+end;
710+
711+proc realToReal*(k: Kind);
712+begin
713+ notYet("reals");
714+ stack[depth - 1].k := k;
715+end;
716+
717+proc compareSeq*(a, b: I64; shift: INT; eq: BOOL);
718+begin
719+ _ := a; _ := b; _ := shift; _ := eq;
720+ notYet("comparing slices");
721+ _ := target();
722+ computed(kWord);
723+end;
724+
725+(* An error points at its message's length, an 8-byte word, with the
726+ text after it; nil is no error. Pops one, and makes the slice of its
727+ message at tmp, empty for nil. *)
728+proc errorText*(tmp: I64);
729+var L: INT;
730+begin
731+ popTo(T);
732+ A.movRI(U, 0);
733+ L := NoLabel;
734+ A.cbz(false, T, L);
735+ A.load(U, T, 0, 8, false);
736+ A.aluI(A.opAdd, T, T, 8);
737+ A.fixLink(L);
738+ A.store(T, FP, INT(tmp), 8);
739+ A.store(U, FP, INT(tmp) + 8, 8);
740+end;
741+
742+(* INC or DEC of the variable whose address is under the step on top;
743+ its store cuts a narrow one to its width *)
744+proc incDec*(size: INT; signed, dec: BOOL);
745+var r, y, o: INT;
746+begin
747+ if dec then o := A.opSub; else o := A.opAdd; end;
748+ r, y := operands();
749+ drop();
750+ A.load(T, r, 0, size, signed);
751+ A.alu(o, T, T, y);
752+ A.store(T, r, 0, size);
753+end;
754+
755+(* INC or DEC of the variable in register r, by the value on top *)
756+proc incDecReg*(r, size: INT; signed, dec: BOOL);
757+var c: BOOL; v: I64; o: INT;
758+begin
759+ if dec then o := A.opSub; else o := A.opAdd; end;
760+ c, v := topConst();
761+ if c then A.aluI(o, r, r, v); else A.alu(o, r, r, loaded(depth - 1)); end;
762+ drop();
763+ if size < 8 then A.extend(r, r, size, signed); end;
764+end;
765+
766+proc zeroNew*(size: I64);
767+begin
768+ _ := size;
769+ notYet("NEW");
770+end;
771+
772+proc atomic*(which: INT);
773+begin
774+ notYet("CAS, XCHG and XADD");
775+ if which = Sym.bCas then drop(); end;
776+ drop();
777+ stack[depth - 1].k := kWord;
778+end;
779+
780+proc sysCall*(n: INT);
781+var i: INT;
782+begin
783+ notYet("SYSCALL");
784+ for i := 1 to n do drop(); end;
785+ _ := target();
786+ computed(kWord);
787+end;
788+
789+(* A barrier for every processor, dmb ish *)
790+proc fence*;
791+begin
792+ A.dmb();
793+end;
794+
795+(* Jumps. A label is the chain of the jumps to it, until it is placed
796+ (A64). *)
797+
798+proc jump*(var L: INT);
799+begin
800+ A.jmp(L);
801+end;
802+
803+(* Pops a BOOL, and jumps if it is when *)
804+proc jumpIf*(var L: INT; when: BOOL);
805+var r: INT;
806+begin
807+ r := loaded(depth - 1);
808+ drop();
809+ A.cbz(when, r, L);
810+end;
811+
812+(* Pops two integers, and jumps if the left op the right *)
813+proc jumpCmp*(sy: Scan.Sym; signed: BOOL; var L: INT);
814+var r, y, i: INT;
815+begin
816+ i := INT(sy) - INT(Scan.sEql);
817+ r, y := operands();
818+ drop();
819+ A.cmp(r, y);
820+ if signed then A.jcc(CcSigned[i], L); else A.jcc(CcUnsigned[i], L); end;
821+end;
822+
823+(* jumpCmp out of an expression: the values under the two compared are
824+ spilled first, so that they are where the code after the landing
825+ place expects them, whichever way it came (Gen.x86_64.raz says more) *)
826+proc jumpOut*(sy: Scan.Sym; signed: BOOL; var L: INT);
827+begin
828+ spillBelow(depth - 2);
829+ jumpCmp(sy, signed, L);
830+end;
831+
832+(* The two values on top, compared, as a BOOL: true unless notOp holds;
833+ fj and tj, the chains of and, or and not, land on the 0 and the 1 *)
834+proc condValue*(notOp: Scan.Sym; signed: BOOL; fj, tj: INT);
835+var r, e: INT;
836+begin
837+ jumpOut(notOp, signed, fj);
838+ A.fixLink(tj);
839+ r := target();
840+ A.movRI(r, 1);
841+ e := NoLabel;
842+ A.jmp(e);
843+ A.fixLink(fj);
844+ A.movRI(r, 0);
845+ A.fixLink(e);
846+ computed(kWord);
847+end;
848+
849+proc jumpBack*(top: INT);
850+begin
851+ A.jmpBack(top);
852+end;
853+
854+proc fix*(L: INT);
855+begin
856+ A.fixLink(L);
857+end;
858+
859+proc jumpTable*(slot, lo: I64; n, elseAt: INT; var endL: INT): INT;
860+begin
861+ _ := slot; _ := lo; _ := n; _ := elseAt; _ := endL;
862+ notYet("a jump table");
863+ return Chunk.pc;
864+end;
865+
866+(* The next entry of the table that jumpTable started at table *)
867+proc tableEntry*(table, target: INT);
868+begin
869+ Chunk.put4(target - table);
870+end;
871+
872+(* A loop's start is aligned on x86-64, for its fetches; here it isn't *)
873+proc alignLoop*;
874+begin
875+end;
876+
877+proc joinJumps*(L1, L2: INT): INT;
878+begin
879+ return A.joinLinks(L1, L2);
880+end;
881+
882+proc fixTo*(L, top: INT);
883+begin
884+ A.fixLinkTo(L, top);
885+end;
886+
887+(* Checks, and what checks as it goes *)
888+
889+proc checkIndex*(n: I64; p: Diag.Pos);
890+begin
891+ _ := n;
892+ notYetAt("checks", p);
893+end;
894+
895+proc checkView*(n, below: I64; p: Diag.Pos);
896+begin
897+ _ := n; _ := below;
898+ notYetAt("checks", p);
899+end;
900+
901+proc checkEnum*(n: I64; name: INT; p: Diag.Pos);
902+begin
903+ _ := n; _ := name;
904+ notYetAt("checks", p);
905+end;
906+
907+proc checkNil*(reach: I64; p: Diag.Pos);
908+begin
909+ _ := reach;
910+ notYetAt("checks", p);
911+end;
912+
913+(* r times v, an element's size: by a shift where v is a power of two,
914+ else through x3, free between calls as x0 to x2 are *)
915+proc mulI(r: INT; v: I64);
916+var n: INT;
917+begin
918+ n := 0;
919+ while (I64(1) shl n) < v do INC(n); end;
920+ if (I64(1) shl n) = v then
921+ if n > 0 then A.shiftI(A.shLsl, r, r, n, 8); end;
922+ else
923+ A.movRI(3, v);
924+ A.mul(r, r, 3);
925+ end;
926+end;
927+
928+(* Pops an index, and the address of the slice at a if it is on the
929+ stack, and makes the address of the element it picks: the slice's
930+ pointer plus the index times size *)
931+proc indexSlice*(a: Adr; size, room: I64; checked: BOOL; p: Diag.Pos);
932+var m: Mem; r: INT;
933+begin
934+ if checked or (room > 0) then notYetAt("checks", p); end;
935+ popTo(T);
936+ mulI(T, size);
937+ if a.base = bReg then
938+ A.alu(A.opAdd, T, T, a.chunk);
939+ else
940+ m := place(a, U);
941+ loadMem(U, m, 8, false);
942+ A.alu(A.opAdd, T, T, U);
943+ end;
944+ r := target();
945+ A.movRR(r, T);
946+ computed(kWord);
947+end;
948+
949+(* Pops an index, and a pointer under it, and makes the address of the
950+ element it picks *)
951+proc indexPtr*(size: I64);
952+begin
953+ mulI(top(), size);
954+ op(Scan.sPlus, kWord, 8, false);
955+end;
956+
957+(* Pops an index, checked before, and makes the address of the element
958+ it picks of the array at a *)
959+proc indexArray*(a: Adr; size: I64);
960+begin
961+ mulI(top(), size);
962+ pushAdr(a);
963+ op(Scan.sPlus, kWord, 8, false);
964+end;
965+
966+(* Pops hi and lo, and the address of the array or slice at a if it is
967+ on the stack, and makes the slice lo..hi of it, of elements of size
968+ bytes, in the frame at tmp: its pointer, the start plus lo times size,
969+ and its length, hi - lo *)
970+proc slice*(a: Adr; isArray: BOOL; n, size, tmp: I64; checked: BOOL; p: Diag.Pos);
971+var m: Mem;
972+begin
973+ _ := n;
974+ if checked then notYetAt("checks", p); end;
975+ popTo(Tmp); (* hi *)
976+ popTo(Src); (* lo *)
977+ if a.base = bReg then
978+ A.movRR(U, a.chunk);
979+ else
980+ m := place(a, U);
981+ if isArray then adrTo(U, m); else loadMem(U, m, 8, false); end;
982+ end;
983+ A.alu(A.opSub, Tmp, Tmp, Src);
984+ A.store(Tmp, FP, INT(tmp) + 8, 8);
985+ mulI(Src, size);
986+ A.alu(A.opAdd, U, U, Src);
987+ A.store(U, FP, INT(tmp), 8);
988+end;
989+
990+proc copySlice*(dOff, sOff, size: I64; checked: BOOL; p: Diag.Pos);
991+begin
992+ _ := dOff; _ := sOff; _ := size; _ := checked;
993+ notYetAt("COPY", p);
994+end;
995+
996+proc fillSlice*(dOff, size, n: I64; scalar: BOOL);
997+begin
998+ _ := dOff; _ := size; _ := n; _ := scalar;
999+ notYet("FILL");
1000+ drop();
1001+end;
1002+
1003+(* Pops hi, lo and a pointer, and makes the slice p[lo..hi] at tmp *)
1004+proc slicePtr*(size, tmp: I64; checked: BOOL; p: Diag.Pos);
1005+begin
1006+ if checked then notYetAt("checks", p); end;
1007+ popTo(Tmp); (* hi *)
1008+ popTo(Src); (* lo *)
1009+ popTo(U); (* the pointer *)
1010+ A.alu(A.opSub, Tmp, Tmp, Src);
1011+ A.store(Tmp, FP, INT(tmp) + 8, 8);
1012+ mulI(Src, size);
1013+ A.alu(A.opAdd, U, U, Src);
1014+ A.store(U, FP, INT(tmp), 8);
1015+end;
1016+
1017+(* Calls. The arguments are the c.n values on top, each moved into the
1018+ next of x0 to x7 just before the call; the values under them are
1019+ spilled first, as the call may change their registers. As the stack's
1020+ registers carry no argument, the moves may go in any order. A slice
1021+ goes as its two words, a record by value as the address of a copy
1022+ (Item makes it). A single result comes back in x0, two words in x0
1023+ and x1: a slice is stored in the temporary c.ret, two results pushed
1024+ as two values. *)
1025+proc call*(var c: CallInfo);
1026+var res: ^Sym.Type; i, ni, first, r: INT;
1027+begin
1028+ first := depth - c.n;
1029+ spillBelow(first);
1030+ res := c.sig^.base;
1031+ c.ret := 0;
1032+ if c.sig^.variadic then notYet("a call of a C procedure that takes ..."); end;
1033+ if (res # nil) and (Sym.holdsArray(res) or Sym.behindPointer(res)) then
1034+ notYet("a result in memory");
1035+ c.ret := allocPerm(res^.size, res^.align);
1036+ elsif (res # nil) and (res^.form = Sym.fSlice) then
1037+ c.ret := allocTemp(res^.size, res^.align);
1038+ elsif (res # nil) and (res^.form = Sym.fReal) then
1039+ notYet("reals");
1040+ end;
1041+ ni := 0;
1042+ for i := 0 to c.n - 1 do
1043+ if c.isF[i] then notYet("reals"); end;
1044+ if ni < 8 then valueTo(first + i, ni); else notYet("an argument past x7"); end;
1045+ INC(ni);
1046+ end;
1047+ for i := 1 to c.n do drop(); end;
1048+ if c.ext then
1049+ A.loadChunk(U, c.chunk, 0, 8, false);
1050+ A.callR(U);
1051+ elsif c.chunk >= 0 then
1052+ A.callChunk(c.chunk);
1053+ else
1054+ A.load(U, FP, INT(c.target), 8, false);
1055+ A.callR(U);
1056+ end;
1057+ if res # nil then
1058+ if res^.form = Sym.fSlice then
1059+ A.store(0, FP, INT(c.ret), 8);
1060+ A.store(1, FP, INT(c.ret) + 8, 8);
1061+ elsif Sym.inTwoRegs(res) then
1062+ A.movRR(target(), 0); computed(kWord);
1063+ A.movRR(target(), 1); computed(kWord);
1064+ elsif c.ret = 0 then
1065+ (* C leaves the bits above a narrow result as they fall *)
1066+ r := target();
1067+ A.movRR(r, 0);
1068+ if res^.form = Sym.fBool then A.extend(r, r, 1, false);
1069+ elsif (res^.form = Sym.fInt) and (res^.size < 8) then A.extend(r, r, INT(res^.size), res^.signed); end;
1070+ computed(kindOf(res));
1071+ end;
1072+ end;
1073+end;
1074+
1075+(* Frames: a slot of size bytes, its offset from x29, negative. A
1076+ temporary is released at the end of its statement; allocPerm's lasts
1077+ the procedure. *)
1078+proc allocTemp*(size, align: I64): I64;
1079+begin
1080+ if align < 1 then align := 1; end;
1081+ frameTop := Sym.alignUp(frameTop + size, align);
1082+ if frameTop > frameMax then frameMax := frameTop; end;
1083+ return -frameTop;
1084+end;
1085+
1086+proc allocPerm*(size, align: I64): I64;
1087+var s: I64;
1088+begin
1089+ s := allocTemp(size, align);
1090+ permTop := frameTop;
1091+ return s;
1092+end;
1093+
1094+proc tempMark*: I64;
1095+begin
1096+ return frameTop;
1097+end;
1098+
1099+proc releaseTemps*(m: I64);
1100+begin
1101+ if m < permTop then m := permTop; end;
1102+ frameTop := m;
1103+end;
1104+
1105+proc keepTemps*;
1106+begin
1107+ frameTop := frameMax;
1108+ permTop := frameMax;
1109+end;
1110+
1111+(* The parameters' places: each in a frame slot of its own, stored there
1112+ from its register on entry. A var parameter, and a record or array
1113+ passed by value, holds an address (ind). *)
1114+proc beginProc*(sig: ^Sym.Type; params: ^Sym.Obj);
1115+var p: ^Sym.Obj; ni, k, w: INT;
1116+begin
1117+ frameTop := 0; frameMax := 0; permTop := 0;
1118+ resetStack(0, 0);
1119+ exitL := NoLabel;
1120+ numIn := 0;
1121+ lost := false;
1122+ resType := sig^.base;
1123+ regMask := 0;
1124+ if (resType # nil) and Sym.behindPointer(resType) then
1125+ notYet("a result in memory");
1126+ retSlot := allocPerm(8, 8);
1127+ end;
1128+ ni := 0;
1129+ p := params;
1130+ while p # nil do
1131+ p^.ind := p^.isVar or (Sym.isAggregate(p^.typ) and (p^.typ^.form # Sym.fSlice));
1132+ k := 1;
1133+ if (p^.typ^.form = Sym.fSlice) and not p^.isVar then k := 2; end;
1134+ p^.val := allocPerm(8 * k, 8);
1135+ if (p^.typ^.form = Sym.fReal) and not p^.isVar or (ni + k > 8) then
1136+ notYet("a real parameter, or one past x7");
1137+ k := 0;
1138+ end;
1139+ for w := 0 to k - 1 do (* a slice's two words, in two slots *)
1140+ inReg[numIn] := ni; inSlot[numIn] := p^.val + I64(8 * w); inObj[numIn] := p;
1141+ inSize[numIn] := 8;
1142+ 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;
1143+ INC(numIn); INC(ni);
1144+ end;
1145+ p := p^.next;
1146+ end;
1147+ paramTop := frameTop;
1148+end;
1149+
1150+(* The frame as beginProc left it, with the parameters' slots only *)
1151+proc resetLocals*;
1152+begin
1153+ frameTop := paramTop; frameMax := paramTop; permTop := paramTop;
1154+end;
1155+
1156+(* No parameter is kept where it arrived, as x86-64 keeps one in rdi or
1157+ rsi: each is stored on entry, or moved to its register variable *)
1158+proc keepArrived*(o: ^Sym.Obj);
1159+begin
1160+ _ := o;
1161+end;
1162+
1163+proc keptIn*(o: ^Sym.Obj): BOOL;
1164+begin
1165+ _ := o;
1166+ return false;
1167+end;
1168+
1169+(* The locals in memory have their slots: the prologue zeroes those. The
1170+ registers of variables in mask are saved next, a quadword each, in
1171+ slots that need no zeroing; the frame as it then stands is where a
1172+ second try at the body starts. *)
1173+proc useRegs*(mask: INT);
1174+var i, k: INT;
1175+begin
1176+ zeroTop := permTop;
1177+ regMask := mask;
1178+ k := 0;
1179+ for i := 0 to 4 do
1180+ if (mask & (1 shl i)) # 0 then INC(k); end;
1181+ end;
1182+ if k > 0 then saveAt := allocPerm(8 * k, 8); end;
1183+ frameAt[0] := frameTop; frameAt[1] := frameMax; frameAt[2] := permTop;
1184+end;
1185+
1186+proc xHome*(r: INT; slot: I64);
1187+begin
1188+ _ := r; _ := slot;
1189+end;
1190+
1191+proc markCode*(var m: CodeMark);
1192+begin
1193+ m.pc := Chunk.pc; m.fixups := Chunk.numFixups; m.lines := Chunk.numLines; m.said := A.saidCount();
1194+ m.fails := 0; m.exit := exitL;
1195+end;
1196+
1197+(* The code made since m taken back; the frame is left as it is *)
1198+proc rewind*(m: CodeMark);
1199+begin
1200+ Chunk.rewindTo(m.pc, m.fixups, m.lines);
1201+ A.unsay(m.said);
1202+ exitL := m.exit;
1203+end;
1204+
1205+(* For a second try at the body: the code as it was at m, and the frame
1206+ as useRegs found it *)
1207+proc redo*(m: CodeMark);
1208+begin
1209+ Chunk.rewindTo(m.pc, m.fixups, m.lines);
1210+ A.unsay(m.said);
1211+ frameTop := frameAt[0]; frameMax := frameAt[1]; permTop := frameAt[2];
1212+ exitL := NoLabel;
1213+end;
1214+
1215+(* The prologue, for the procedure's first line: the frame record, x29
1216+ and x30, pushed, and x29 made to point at it; sp lowered by the
1217+ frame's size, known only at endProc, which patches it into the two
1218+ subs, of its bits from 12 up and of its low 12 (so a frame is less
1219+ than 16 MB); the locals in memory zeroed, from the parameters' slots
1220+ down to zeroTop, by a store each of the zero register up to 16, else
1221+ by a loop; the registers of variables saved and zeroed; and the
1222+ parameters stored from their registers to their slots, or moved to
1223+ their registers. *)
1224+proc enterBody*(c, line: INT);
1225+var i, loop, r: INT; n: I64;
1226+begin
1227+ Chunk.beginChunk(c);
1228+ codeChunk := c;
1229+ if LEN(pending) > 0 then Chunk.setMissing(c, pending, pendingAt); pending := ""; end;
1230+ Chunk.noteLine(line, 1); (* a declaration starts a line *)
1231+ A.stp(FP, LR, SP, -16, A.mPre);
1232+ A.movRR(FP, SP);
1233+ frameFix := Chunk.pc;
1234+ A.say("sub sp, sp, frame, lsl #12"); Chunk.put4(SubSp12);
1235+ A.say("sub sp, sp, frame"); Chunk.put4(SubSp);
1236+ n := (Sym.alignUp(zeroTop, 8) - paramTop) div 8;
1237+ if n <= 16 then
1238+ for i := 1 to INT(n) do A.store(ZR, FP, INT(-paramTop) - 8 * i, 8); end;
1239+ elsif n > 0 then
1240+ A.aluI(A.opSub, T, FP, paramTop + 8 * n);
1241+ A.movRI(U, n);
1242+ loop := Chunk.pc;
1243+ A.storeIdx(ZR, T, 8, 8, A.mPost);
1244+ A.aluI(A.opSubs, U, U, 1);
1245+ A.jccBack(A.ccNE, loop);
1246+ end;
1247+ if (regMask shr XBit) # 0 then notYet("reals in registers"); end;
1248+ Chunk.setSaves(c, regMask, INT(saveAt));
1249+ n := 0;
1250+ for i := 0 to 4 do
1251+ if (regMask & (1 shl i)) # 0 then
1252+ A.store(VarRegs[i], FP, INT(saveAt + 8 * n), 8);
1253+ A.movRI(VarRegs[i], 0);
1254+ INC(n);
1255+ end;
1256+ end;
1257+ for i := 0 to numIn - 1 do
1258+ if inObj[i]^.reg # 0 then
1259+ r := inObj[i]^.reg;
1260+ if inSlot[i] # inObj[i]^.val then r := inObj[i]^.reg2; end;
1261+ A.movRR(r, inReg[i]);
1262+ if inSize[i] < 8 then A.extend(r, r, inSize[i], inObj[i]^.typ^.signed); end;
1263+ else
1264+ A.store(inReg[i], FP, INT(inSlot[i]), inSize[i]);
1265+ end;
1266+ end;
1267+end;
1268+
1269+proc resultSlot*: I64;
1270+begin
1271+ return retSlot;
1272+end;
1273+
1274+proc resultTo*(off: I64; size: INT);
1275+begin
1276+ _ := off; _ := size;
1277+ notYet("a result in memory");
1278+ drop();
1279+end;
1280+
1281+proc copyResult*(off, size: I64);
1282+begin
1283+ _ := off; _ := size;
1284+ notYet("a result in memory");
1285+ drop();
1286+end;
1287+
1288+(* return: the result, a value on top, goes in x0; two words, the two
1289+ values on top, in x0 and x1 *)
1290+proc returnJump*;
1291+begin
1292+ if (resType # nil) and Sym.behindPointer(resType) then
1293+ A.load(0, FP, INT(retSlot), 8, false); (* not yet made: marked by beginProc *)
1294+ elsif resType # nil then
1295+ if Sym.inTwoRegs(resType) then popTo(1); end;
1296+ popTo(0);
1297+ end;
1298+ A.jmp(exitL);
1299+end;
1300+
1301+(* try, where the error isn't nil, first makes the machine's stack even
1302+ on x86-64; here nothing is pushed, so sp is as the prologue left it *)
1303+proc tryAlign*;
1304+begin
1305+end;
1306+
1307+proc tryReturn*(slot: I64);
1308+begin
1309+ _ := slot;
1310+ notYet("try");
1311+end;
1312+
1313+(* try, with no deferred statement to run: the error on top is tested in
1314+ its register r, which is returned, and, if it isn't nil, returned
1315+ from the procedure by tryReturnFrom *)
1316+proc tryTest*(var ok: INT): INT;
1317+var r: INT;
1318+begin
1319+ r := loaded(depth - 1);
1320+ jumpIf(ok, false);
1321+ return r;
1322+end;
1323+
1324+proc tryReturnFrom*(r: INT);
1325+begin
1326+ _ := r;
1327+ notYet("try");
1328+end;
1329+
1330+(* The end of the procedure in chunk c: the code that returns, and the
1331+ frame's size, known only now, patched into its prologue. If it is
1332+ open, running off its end, it returns zeros. *)
1333+proc endProc*(c: INT; open: BOOL): ERROR;
1334+var n: I64; i: INT;
1335+begin
1336+ codeChunk := -1;
1337+ if (depth # 0) or (pushed # 0) then Diag.fatal("internal error: stack depth"); end;
1338+ if open then
1339+ A.movRI(0, 0);
1340+ if Sym.inTwoRegs(resType) then A.movRI(1, 0); end;
1341+ else
1342+ A.dropJumpTo(exitL);
1343+ end;
1344+ A.fixLink(exitL);
1345+ n := 0;
1346+ for i := 0 to 4 do
1347+ if (regMask & (1 shl i)) # 0 then
1348+ A.load(VarRegs[i], FP, INT(saveAt + 8 * n), 8, false);
1349+ INC(n);
1350+ end;
1351+ end;
1352+ A.movRR(SP, FP);
1353+ A.ldp(FP, LR, SP, 16, A.mPost);
1354+ A.ret();
1355+ n := Sym.alignUp(frameMax, 16);
1356+ if n >= 1000000H then return Scan.mark("frame too big: 16 MB or more"); end;
1357+ Chunk.put4At(frameFix, SubSp12 | INT((n shr 12) shl 10));
1358+ Chunk.put4At(frameFix + 4, SubSp | INT((n & 0FFFH) shl 10));
1359+ if A.listing then
1360+ A.restate(frameFix, Diag.say("sub sp, sp, #{}, lsl #12", [Fmt.int(INT(n shr 12))]));
1361+ A.restate(frameFix + 4, Diag.say("sub sp, sp, #{}", [Fmt.int(INT(n & 0FFFH))]));
1362+ end;
1363+ Chunk.endChunk(c);
1364+ return nil;
1365+end;
1366+
1367+proc deferBegin*(var L: INT): (INT, INT);
1368+begin
1369+ _ := L;
1370+ notYet("defer");
1371+ return Chunk.pc, pushed;
1372+end;
1373+
1374+proc deferEnd*(L, saved: INT);
1375+begin
1376+ _ := L; _ := saved;
1377+ keepTemps();
1378+end;
1379+
1380+proc runDefer*(at: INT);
1381+begin
1382+ _ := at;
1383+ notYet("defer");
1384+end;
1385+
1386+(* The name s, interned *)
1387+proc internStr(s: []const U8): INT;
1388+begin
1389+ return Scan.intern(SYSTEM.PTR(s), LEN(s));
1390+end;
1391+
1392+(* The entry point, main, and its chunk. macOS starts every program in
1393+ dyld, the dynamic loader, which binds its C symbols and calls the
1394+ procedure LC_MAIN names as C's main(argc, argv): this one. It saves
1395+ argc, an int (so its upper half is undefined until extended), and
1396+ argv; gives the library C's symbols it needs (cLinks: Rt's cExit) and
1397+ Rt the addresses it is given (links); runs every used module's body,
1398+ then main; and ends with Rt.exit, its status main's or 0. The frame
1399+ record it pushes links to dyld's, where a trace ends. Every program
1400+ reaches the kernel through libSystem, so dynamic is always so; bare,
1401+ for a machine with no system, isn't a Mac's. *)
1402+proc entryPoint*(dynamic, bare: BOOL; first: ^Sym.Module; mainObj: ^Sym.Obj; cLinks: []Link; numCLinks, exitProc: INT; links: []Link; numLinks: INT): INT;
1403+var entry, i: INT; m: ^Sym.Module;
1404+begin
1405+ 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;
1406+ entry := Chunk.newChunk(Chunk.secText, -1, internStr("main"));
1407+ Chunk.beginChunk(entry);
1408+ A.stp(FP, LR, SP, -16, A.mPre);
1409+ A.movRR(FP, SP);
1410+ A.extend(0, 0, 4, true);
1411+ A.storeChunk(0, argcChunk, 0, 8);
1412+ A.storeChunk(1, argvChunk, 0, 8);
1413+ for i := 0 to numCLinks - 1 do
1414+ A.loadChunk(0, cLinks[i].chunk, 0, 8, false);
1415+ A.storeChunk(0, cLinks[i].into, 0, 8);
1416+ end;
1417+ for i := 0 to numLinks - 1 do
1418+ A.addrChunk(0, links[i].chunk, 0);
1419+ A.storeChunk(0, links[i].into, 0, 8);
1420+ end;
1421+ m := first;
1422+ while m # nil do
1423+ if m^.used and (m^.body >= 0) then A.callChunk(m^.body); end;
1424+ m := m^.next;
1425+ end;
1426+ if mainObj # nil then A.callChunk(mainObj^.chunk); end;
1427+ if (mainObj = nil) or (mainObj^.typ^.base = nil) then A.movRI(0, 0); end;
1428+ A.callChunk(exitProc);
1429+ A.brk(1); (* exit never returns: trap if it does *)
1430+ Chunk.endChunk(entry);
1431+ return entry;
1432+end;
1433+
1434+(* A code procedure: its instructions, read by the assembler (A64), are
1435+ the whole of chunk c *)
1436+proc codeProc*(c: INT; constExpr: A.ConstFn; nameFn: A.NameFn): ERROR;
1437+begin
1438+ Chunk.beginChunk(c);
1439+ try A.assemble(constExpr, nameFn);
1440+ Chunk.endChunk(c);
1441+ return nil;
1442+end;
1443+
1444+(* A code procedure that is one instruction on a real, as Math.sqrt on
1445+ x86-64, is made in place of its call there; none is, yet, here *)
1446+proc oneRealOp*(c: INT): INT;
1447+begin
1448+ _ := c;
1449+ return 0;
1450+end;
1451+
1452+proc realInPlace*(op: INT);
1453+begin
1454+ _ := op;
1455+ notYet("reals");
1456+end;
1457+
1458+begin
1459+ Chunk.setPad(0D4200020H); (* brk #1, a trap, between procedures *)
1460+ codeChunk := -1;
1461+ pending := "";
1462+ resetStack(0, 0);
1463+ rtFail := Chunk.newChunk(Chunk.secText, internStr("Rt"), internStr("fail"));
1464+ argcChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argc"));
1465+ Chunk.setBss(argcChunk, 8, 8);
1466+ argvChunk := Chunk.newChunk(Chunk.secBss, -1, internStr("argv"));
1467+ Chunk.setBss(argvChunk, 8, 8);
1468+end Gen.

src/Gen.x86_64.raz (history) modified +1 -0

@@ -2849,6 +2849,7 @@
28492849 var i: INT;
28502850 begin
28512851 for i := 0 to LEN(failStubs) - 1 do failStubs[i] := -1; end;
2852+ Chunk.setPad(0CCCCCCCCH); (* int3, a trap, between procedures *)
28522853 inPlace := -1;
28532854 codeChunk := -1;
28542855 resetStack(0, 0);

src/Link.raz (history) modified +79 -9

@@ -12,6 +12,13 @@
1212 loader's other tables come at the end of rodata; Exe writes them
1313 in the room left there.
1414
15+ Mach-O, Exe.darwin.raz's, is laid out otherwise (setPaged): each
16+ segment starts on a page of its own, in the file as in memory, at
17+ base plus its offset in the file; and, since macOS loads a program
18+ anywhere, every address held in rodata is listed (rebases), for the
19+ loader to move with it. arm64's fixups, fields of an instruction,
20+ are patched here too.
21+
1522 Depends on: Chunk for chunks and fixups, Scan for names and memory,
1623 Diag for errors and paths.
1724 Leaves out: the file format; that is Exe. *)
@@ -34,12 +41,21 @@
3441 textImg*, roImg*: ^U8;
3542 placesChunk*: INT; (* the rodata chunk of the places, made by the caller *)
3643 linesOff*, linesSize*: INT; (* the line table, in the places: .debug_line *)
44+ paged*: INT; (* 0, ELF's layout; or Mach-O's page, each segment on one *)
45+ rebases*: ^INT; (* the addresses of rodata's words that hold an address *)
46+ numRebases*: INT;
3747
3848 proc setBase*(a: INT);
3949 begin
4050 base := a;
4151 end;
4252
53+(* Mach-O's layout, its segments on pages of page bytes *)
54+proc setPaged*(page: INT);
55+begin
56+ paged := page;
57+end;
58+
4359 proc setPlaces*(c: INT);
4460 begin
4561 placesChunk := c;
@@ -334,6 +350,42 @@
334350 return s;
335351 end;
336352
353+(* The arm64 instruction at at in text, at address pc, made to reach
354+ the address v, as its kind says (Chunk.FixKind):
355+ fxBranch26 b, bl: (v - pc) / 4 in imm26, bits 0 to 25
356+ fxPage21 adrp: v's page less pc's, in pages of 4 KB, its low
357+ two bits in immlo (29, 30), the rest in immhi (5 to 23)
358+ fxPageOff12 add: v's place in its page in imm12 (10 to 21); a load
359+ or store (bits 27 to 29 111, 24 and 25 01) that place
360+ divided by the size it moves, 1 shl its bits 30 and 31,
361+ or 16 for a q register (bit 26, the reals', with bit 23)
362+ The fields hold zeros, as A64 left them. *)
363+proc patchArm(at: INT; kind: Chunk.FixKind; pc, v: INT);
364+var insn, d, sc: INT;
365+begin
366+ insn := 0;
367+ for d := 3 to 0 by -1 do insn := insn * 256 + INT(textImg[at + d]); end;
368+ match kind of
369+ | fxBranch26:
370+ d := (v - pc) div 4;
371+ if (d < -(1 shl 25)) or (d >= 1 shl 25) then Diag.fatal("the program's code is more than 128 MB"); end;
372+ insn := insn | (d & 3FFFFFFH);
373+ | fxPage21:
374+ d := (v shr 12) - (pc shr 12);
375+ insn := insn | ((d & 3) shl 29) | (((d shr 2) & 7FFFFH) shl 5);
376+ | fxPageOff12:
377+ d := v & 0FFFH;
378+ if (insn & 3B000000H) = 39000000H then
379+ sc := (insn shr 30) & 3;
380+ if (insn & 04800000H) = 04800000H then sc := 4; end;
381+ d := d shr sc;
382+ end;
383+ insn := insn | (d shl 10);
384+ | else:
385+ end;
386+ patch4(textImg, at, insn);
387+end;
388+
337389 (* Places the live chunks, leaving roExtra bytes at the end of rodata
338390 and dynSize at the start of the writable segment. The segments follow
339391 each other in the file with no padding, and each is loaded a page
@@ -352,12 +404,19 @@
352404 if placesChunk >= 0 then makePlaces(base + textOff, e); end;
353405 roOff := (textOff + textSize + 31) div 32 * 32;
354406 roAdr := base + Page + roOff;
407+ if paged > 0 then (* Mach-O: rodata on a page of its own, at its offset *)
408+ roOff := (textOff + textSize + paged - 1) div paged * paged;
409+ roAdr := base + roOff;
410+ end;
355411 e := place(Chunk.secRodata, roAdr);
356412 extraAdr := (e + 7) div 8 * 8;
357413 if roExtra > 0 then e := extraAdr + roExtra; end;
358414 roSize := e - roAdr;
359415 bssOff := (roOff + roSize + 31) div 32 * 32;
360- if dynSize > 0 then
416+ if paged > 0 then
417+ bssOff := (roOff + roSize + paged - 1) div paged * paged;
418+ bssAdr := base + bssOff;
419+ elsif dynSize > 0 then
361420 bssAdr := base + 2 * Page + bssOff;
362421 else
363422 bssAdr := (roAdr + roSize + Page - 1) div Page * Page;
@@ -368,17 +427,21 @@
368427 by their sign, so the image must lie where such an address reaches:
369428 the low 2 GB, as at 400000H, or the top 2 GB, as a higher-half
370429 kernel at 0FFFFFFFF80000000H. The places keep each procedure's
371- start and stop in 32 bits too, which Rt.procAt reads so. *)
430+ start and stop in 32 bits too, which Rt.procAt reads so. Mach-O's
431+ image lies at 4 GB and up, which arm64's code reaches by adrp, and
432+ whose places, below 4 GB of it, keep their order in 32 bits. *)
372433 (* By the size, e - base, which can't overflow, where e itself might *)
373- if not (((base >= 0) and (base <= Low - (e - base))) or ((base >= -Low) and (base <= -(e - base)))) then
434+ if (paged = 0) and not (((base >= 0) and (base <= Low - (e - base))) or ((base >= -Low) and (base <= -(e - base)))) then
374435 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",
375436 [Fmt.str(literal(base))]));
376437 end;
377438
378439 textImg := Scan.grab(textSize + 1);
379- (* the gaps between code chunks are int3, a trap if ever run *)
380- for p := 0 to textSize do textImg[p] := 0CCH; end;
440+ (* the gaps between code chunks are Gen's trap, as in Chunk *)
441+ for p := 0 to textSize do textImg[p] := U8((Chunk.pad shr (8 * ((textOff + p) & 3))) & 0FFH); end;
381442 roImg := Scan.grab(roSize + 1);
443+ rebases := ^INT(Scan.grab(Chunk.numDataFixups * SIZE(INT) + SIZE(INT)));
444+ numRebases := 0;
382445 for p := 0 to roSize do roImg[p] := 0; end;
383446 for c := 0 to Chunk.numChunks - 1 do
384447 if Chunk.chunks[c].live then
@@ -387,11 +450,15 @@
387450 COPY(textImg[p..p + Chunk.chunks[c].size], Chunk.text[Chunk.chunks[c].start..Chunk.chunks[c].start + Chunk.chunks[c].size]);
388451 for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
389452 at := Chunk.fixups[f].at - Chunk.chunks[c].start;
390- (* rel32: from the end of the field to the target;
391- or, X64.memAbs's, the target's address *)
392453 v := Chunk.chunks[Chunk.fixups[f].chunk].adr + Chunk.fixups[f].addend;
393- if not Chunk.fixups[f].abs then v := v - (Chunk.chunks[c].adr + at + 4); end;
394- patch4(textImg, p + at, v);
454+ if Chunk.fixups[f].kind # Chunk.fxRel32 then
455+ patchArm(p + at, Chunk.fixups[f].kind, Chunk.chunks[c].adr + at, v);
456+ else
457+ (* rel32: from the end of the field to the target;
458+ or, X64.memAbs's, the target's address *)
459+ if not Chunk.fixups[f].abs then v := v - (Chunk.chunks[c].adr + at + 4); end;
460+ patch4(textImg, p + at, v);
461+ end;
395462 end;
396463 elsif Chunk.chunks[c].sec = Chunk.secRodata then
397464 p := Chunk.chunks[c].adr - roAdr;
@@ -399,6 +466,8 @@
399466 for f := Chunk.chunks[c].firstFix to Chunk.chunks[c].firstFix + Chunk.chunks[c].numFix - 1 do
400467 patch8(roImg, p + Chunk.dataFixups[f].at,
401468 Chunk.chunks[Chunk.dataFixups[f].chunk].adr + Chunk.dataFixups[f].addend);
469+ rebases[numRebases] := Chunk.chunks[c].adr + Chunk.dataFixups[f].at;
470+ INC(numRebases);
402471 end;
403472 end;
404473 end;
@@ -408,4 +477,5 @@
408477 begin
409478 placesChunk := -1;
410479 base := 400000H;
480+ paged := 0;
411481 end Link.

src/Parse.raz (history) modified +11 -1

@@ -3651,7 +3651,17 @@
36513651 _ := Item.needSystem(Scan.tokPos(), "a code procedure"); (* said, and the declaration read on *)
36523652 Scan.next;
36533653 p^.isCode := true;
3654- try codeBody(p, sig, at);
3654+ if checkMode then
3655+ (* a file of another target's, read for its interface: its code
3656+ is in that machine's assembly, which this one's can't read;
3657+ ! is a symbol there, as A64's assembler has it *)
3658+ Scan.setBang(true);
3659+ while (Scan.tok # Scan.sEnd) and (Scan.tok # Scan.sEof) do Scan.next; end;
3660+ Scan.setBang(false);
3661+ try expect(Scan.sEnd);
3662+ else
3663+ try codeBody(p, sig, at);
3664+ end;
36553665 elsif checkMode then
36563666 try skipBody();
36573667 else

src/Raz.raz (history) modified +6 -0

@@ -467,6 +467,12 @@
467467 objIn(rt, "exit")^.chunk, links[0..numLinks], numLinks);
468468
469469 Link.markLive(entry);
470+ (* what the target's Gen can't make yet stops a program that uses it *)
471+ for i := 0 to Chunk.numChunks - 1 do
472+ if Chunk.chunks[i].live and (LEN(Chunk.chunks[i].missing) > 0) then
473+ Diag.error(Chunk.chunks[i].missingAt, Chunk.chunks[i].missing);
474+ end;
475+ end;
470476 if not Parse.HasReals then
471477 for i := 0 to Chunk.numChunks - 1 do
472478 if Chunk.chunks[i].live and Chunk.chunks[i].reals then

src/Scan.raz (history) modified +9 -0

@@ -25,6 +25,15 @@
2525 type
2626 NamePtr = ^U8;
2727
28+ (* The parser's readers for a code procedure's assembler, X64's or
29+ A64's, here so that both Gens take the same types: of an integer
30+ constant, a whole expression or, when whole is false, a single
31+ factor; and of a name that stands for an address, a procedure or a
32+ module variable, bare or qualified, its chunk, or -1, nothing read,
33+ if the name is anything else, which is then read as a constant *)
34+ ConstFn* = proc(whole: BOOL): (I64, ERROR);
35+ NameFn* = proc: (INT, ERROR);
36+
2837 Sym* = (sNull, sIdent, sInt, sReal, sChar, sString,
2938 sPlus, sMinus, sTimes, sSlash, sEql, sNeq, sLss, sLeq, sGtr, sGeq,
3039 sBecomes, sColon, sSemicolon, sComma, sPeriod, sUpto, sEllipsis,

src/X64.raz (history) modified +3 -9

@@ -44,15 +44,9 @@
4444 chunk*: INT; (* with RIP: the chunk addressed *)
4545 end;
4646
47- (* The parser's reader of an integer constant in a code procedure: a
48- whole expression, or, when whole is false, a single factor *)
49- ConstFn* = proc(whole: BOOL): (I64, ERROR);
50-
51- (* The parser's reader of a name in a code procedure that stands for an
52- address: a procedure or a module variable, bare or qualified. Its
53- chunk, the name read; or -1, nothing read, if the name at the scan
54- is anything else, which is then read as a constant *)
55- NameFn* = proc: (INT, ERROR);
47+ (* The parser's readers of a constant and of a name (Scan says) *)
48+ ConstFn* = Scan.ConstFn;
49+ NameFn* = Scan.NameFn;
5650
5751 (* The text of the instruction that starts at at, for the listing *)
5852 Said = record

test/mac.sh (history) added (executable) +57 -0

@@ -0,0 +1,57 @@
1+#!/bin/sh
2+# The Mac's tests, make mac-check on an Apple Silicon Mac (PLAN.md 5):
3+# test/mac/X.raz compiled for darwin-arm64 by the cross compiler, which
4+# src/cross.sh builds in the linux/amd64 container, into build/mac/X;
5+# then each run here, natively, and what it prints and its status
6+# compared, as test/check.sh compares a test's:
7+# X.expect its standard output (optional; empty if missing)
8+# X.status its exit status (optional; 0 if missing)
9+#
10+# test/mac.sh build in the container: the cross compiler, then the programs
11+# test/mac.sh run on the Mac: each program, run with a timeout
12+#
13+# build/mac is made anew each time: macOS keeps a file's code signature
14+# while the file is open or cached, and kills a program whose file was
15+# written again in place with another one.
16+set -e
17+out=build/mac
18+case $1 in
19+build)
20+ src/cross.sh darwin-arm64
21+ rm -rf $out
22+ mkdir -p $out
23+ for f in test/mac/*.raz; do
24+ name=$(basename $f .raz)
25+ build/cross/darwin-arm64/raz -o $out/$name $f 2>$out/$name.cerr || true
26+ done
27+ ;;
28+run)
29+ pass=0
30+ fail=0
31+ for f in test/mac/*.raz; do
32+ name=$(basename $f .raz)
33+ want=0
34+ [ -f test/mac/$name.status ] && want=$(cat test/mac/$name.status)
35+ if [ ! -x $out/$name ]; then
36+ echo "FAIL $f: doesn't compile: $(cat $out/$name.cerr 2>/dev/null)"; fail=$((fail + 1)); continue
37+ fi
38+ # perl's alarm, as macOS has no timeout
39+ status=0
40+ perl -e 'alarm 10; exec @ARGV' ./$out/$name > $out/$name.out 2>$out/$name.err || status=$?
41+ if [ -f test/mac/$name.expect ]; then exp=test/mac/$name.expect; else exp=/dev/null; fi
42+ if [ $status != $want ]; then
43+ echo "FAIL $f: status $status, not $want"; fail=$((fail + 1))
44+ elif ! cmp -s $out/$name.out $exp; then
45+ echo "FAIL $f: output differs"; fail=$((fail + 1))
46+ else
47+ pass=$((pass + 1))
48+ fi
49+ done
50+ echo "$pass passed, $fail failed"
51+ [ $fail = 0 ]
52+ ;;
53+*)
54+ echo "usage: test/mac.sh build|run" >&2
55+ exit 2
56+ ;;
57+esac

test/mac/Exit.raz (history) added +4 -0

@@ -0,0 +1,4 @@
1+(* The least program: it does nothing, and ends with status 0 *)
2+module Exit;
3+begin
4+end Exit.

test/mac/Fail.raz (history) added +8 -0

@@ -0,0 +1,8 @@
1+(* Rt.fail says a check failed, through libSystem's write, and ends the
2+ program with status 2 *)
3+module Fail;
4+import Rt;
5+
6+begin
7+ Rt.fail(0, 1, 2, 3, 0, nil, 0, 0);
8+end Fail.

test/mac/Fail.status (history) added +1 -0

@@ -0,0 +1 @@
1+2

test/mac/Loop.raz (history) added +27 -0

@@ -0,0 +1,27 @@
1+(* Variables, a loop, calls with arguments and a narrow integer: the
2+ status is the sum of 1 to 10, 55, plus 200 cut to a U8, 255 *)
3+module Loop;
4+
5+var total: INT;
6+
7+proc add(var t: INT; n: INT);
8+begin
9+ t := t + n;
10+end;
11+
12+proc main*: INT;
13+var i, sum: INT; b: U8;
14+begin
15+ i := 1;
16+ while i <= 10 do
17+ add(sum, i);
18+ INC(i);
19+ end;
20+ total := sum;
21+ b := 200;
22+ b := b + 200;
23+ if total = 55 then return total + INT(b) - 144; end;
24+ return 1;
25+end;
26+
27+end Loop.

test/mac/Loop.status (history) added +1 -0

@@ -0,0 +1 @@
1+55

test/mac/RtExit.raz (history) added +8 -0

@@ -0,0 +1,8 @@
1+(* Rt.exit, from a module's body, ends the program there *)
2+module RtExit;
3+import Rt;
4+
5+begin
6+ Rt.exit(5);
7+ Rt.exit(6);
8+end RtExit.

test/mac/RtExit.status (history) added +1 -0

@@ -0,0 +1 @@
1+5

test/mac/Status.raz (history) added +9 -0

@@ -0,0 +1,9 @@
1+(* main's result is the program's status *)
2+module Status;
3+
4+proc main*: INT;
5+begin
6+ return 3;
7+end;
8+
9+end Status.

test/mac/Status.status (history) added +1 -0

@@ -0,0 +1 @@
1+3

tools/cabi.c (history) modified +57 -2

@@ -19,8 +19,17 @@
1919 file pairs each with the C library's own; on Linux,
2020 each is checked against the headers before anything is written.
2121
22- Leaves out: systems but Linux, for errno and closeFrom; a port adds
23- them where the #error is. */
22+ What a system hasn't, Linux's alone, is given a value that keeps Sys
23+ over C compiling there, and that it must not count on: a flag 0, no
24+ flag; an option -1, as saLenAt is -1 where a sockaddr has no sa_len.
25+ On macOS (darwin-arm64), st_mtim is st_mtimespec, a peer's
26+ credentials are struct xucred, which has no pid (0 bytes at 0), and
27+ errno and closeFrom are its own.
28+
29+ cc -o build/cabi tools/cabi.c && build/cabi darwin-arm64 > lib/CAbi.darwin-arm64.raz
30+
31+ Leaves out: systems but Linux and macOS, for errno and closeFrom; a
32+ port adds them where the #error is. */
2433 #define _GNU_SOURCE
2534 #include <dirent.h>
2635 #include <errno.h>
@@ -43,6 +52,30 @@
4352 #include <time.h>
4453 #include <unistd.h>
4554
55+#ifndef MFD_CLOEXEC
56+#define MFD_CLOEXEC 0
57+#endif
58+#ifndef TIMER_ABSTIME
59+#define TIMER_ABSTIME 0
60+#endif
61+#ifndef SOCK_CLOEXEC
62+#define SOCK_CLOEXEC 0
63+#endif
64+#ifndef SOCK_NONBLOCK
65+#define SOCK_NONBLOCK 0
66+#endif
67+#ifndef MSG_CMSG_CLOEXEC
68+#define MSG_CMSG_CLOEXEC 0
69+#endif
70+#ifndef SO_PEERCRED
71+#define SO_PEERCRED -1
72+#endif
73+#ifdef __APPLE__
74+#include <sys/ucred.h>
75+#define st_mtim st_mtimespec
76+#define CMSG_ALIGN(n) __DARWIN_ALIGN32(n)
77+#endif
78+
4679 /* Sys keeps a terminal's modes in 256 bytes, and struct rusage, whose
4780 size C libraries differ in, in 512 */
4881 _Static_assert(sizeof(struct termios) <= 256, "struct termios is larger than Sys.Mode");
@@ -171,7 +204,12 @@
171204 K("sockaddrIn6Len", sizeof(struct sockaddr_in6));
172205 AT("sin6Port", struct sockaddr_in6, sin6_port);
173206 AT("sin6Addr", struct sockaddr_in6, sin6_addr);
207+#ifdef __linux__
174208 READ("ucPid", struct ucred, pid); READ("ucUid", struct ucred, uid);
209+#else
210+ K("ucPidAt", 0); K("ucPidLen", 0);
211+ READ("ucUid", struct xucred, cr_uid);
212+#endif
175213 K("msghdrLen", sizeof(struct msghdr));
176214 AT("msgIov", struct msghdr, msg_iov);
177215 WRITE("msgIovlen", struct msghdr, msg_iovlen, msg_control);
@@ -231,6 +269,23 @@
231269 "begin\n"
232270 " if hi < 0 then hi := 0FFFFFFFFH; end;\n"
233271 " _ := syscall(436, lo, hi, 0);\n"
272+ "end;\n\n");
273+#elif defined(__APPLE__)
274+ printf("extern proc __error: ^I32;\n"
275+ "extern proc close(fd: I32): I32;\n"
276+ "extern proc getdtablesize: I32;\n\n"
277+ "(* errno, this thread's *)\n"
278+ "proc errno*: ^I32;\n"
279+ "begin\n"
280+ " return __error();\n"
281+ "end;\n\n"
282+ "(* Closes the fds from lo to hi, or every one from lo if hi < 0: one\n"
283+ " by one, as macOS has no close_range. *)\n"
284+ "proc closeFrom*(lo, hi: INT);\n"
285+ "var fd: INT;\n"
286+ "begin\n"
287+ " if hi < 0 then hi := INT(getdtablesize()) - 1; end;\n"
288+ " for fd := lo to hi do _ := close(I32(fd)); end;\n"
234289 "end;\n\n");
235290 #else
236291 #error "a CAbi for this system needs its errno and closeFrom: add them here"