From b6a29ae30955277b8fa46685bf5c20e6d8e047c0 Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:07:35 +0000 Subject: [PATCH] Exe.darwin: line numbers for lldb, other C libraries; Host.darwin PLAN.md 5, step 6. A __DWARF segment holds the line table and the compile unit, which Link now makes for both Exe files; make lldb stops at a line on the Mac. link "name" loads @rpath/libname.dylib, its symbols bound by flat lookup, as extern doesn't say whose they are. test/mac/NarrowArgs checks a C procedure's narrow arguments past x7 and v7 against cc's own. Host.darwin is the compiler's host on the Mac: a compiler staged with it runs there, compiles and runs a program. x86-64's output is unchanged for 202 programs; the fixpoint holds. --- diff --git a/.claude/worktrees/agent-a2fc7142f6816bb63 b/.claude/worktrees/agent-a2fc7142f6816bb63 new file mode 160000 index 0000000..e99cab9 --- /dev/null +++ b/.claude/worktrees/agent-a2fc7142f6816bb63 @@ -0,0 +1 @@ +Subproject commit e99cab9b8685d604c3338e9f31339d8b2af63d18 diff --git a/CLAUDE.md b/CLAUDE.md index 88b7d65..804b050 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,6 +17,8 @@ make loc # lines of the compiler, by rloc; the last, code, is the budget make fixpoint # BOOT's release builds src, that builds src, that again: the last two agree make gdb # gdb stops at a line of a test and names it + make lldb # the same for lldb, on a Mac (a program made for darwin-arm64, in the container) + make mac-check # on an Apple Silicon Mac: test/mac and conform/run cross-compiled in the container, run natively, and lldb make stress # 40,000 native threads; make check runs a small version make alpine # test/libc in an Alpine container, over musl (docker) make fmt # lib/, examples/ and tools/ are formatted diff --git a/Makefile b/Makefile index e02daad..71a654c 100644 --- a/Makefile +++ b/Makefile @@ -50,6 +50,11 @@ gdb: raz test/gdb.sh +# the same for lldb, on a Mac: a program made for darwin-arm64 by the +# container's cross compiler (mac-build), stopped at a line +lldb: mac-build + test/lldb.sh + # the compiler's speed, on a generated program of about 350,000 lines, # the best of three runs; fails below 400,000 lines a second bench: raz | build @@ -207,7 +212,7 @@ site-check: build/site/Verify build/site/Verify -.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 +.PHONY: docker-image docker-check mac-build mac-check lldb docker-shell prev-bench fixpoint check gdb bench kernels stress alpine fmt loc man pdf dist site site-source site-check clean install uninstall # `make check` in a linux/amd64 container, for a machine that isn't one # (the repository is mounted at its own path, so git and the tests see @@ -222,8 +227,10 @@ # test/mac's programs (test/mac.sh), on an Apple Silicon Mac: compiled # for darwin-arm64 by the cross compiler in the container, then run here -mac-check: docker-image +mac-build: docker-image $(DOCKER) $(DOCKERIMAGE) sh -c "git config --global --add safe.directory '*' && timeout 1200 test/mac.sh build" + +mac-check: mac-build test/mac.sh run docker-shell: docker-image diff --git a/PLAN.md b/PLAN.md index cb5a5f0..abda534 100644 --- a/PLAN.md +++ b/PLAN.md @@ -283,8 +283,15 @@ twin, so that `Math.sqrt` is made in place (step 7). A rotation of a negative `I8` or `I16` leaves the bits above its width zero, where x86-64's `rol al, cl` leaves them as they were. -6. `Exe.darwin.raz`'s line numbers for lldb (its rebases came with - 5a); `Host.darwin.raz`. +6. Done. `Exe.darwin.raz`'s line numbers for lldb, in a `__DWARF` + segment (mapped, read only: dyld refuses a segment bigger in the file + than in memory), the compile unit and its abbreviation made by `Link` + for both formats, `make lldb`; other C libraries (`link "X11";` is + `@rpath/libX11.dylib`, four rpaths, binds by flat lookup); + `test/mac/NarrowArgs`, a C library `cc` builds, narrow arguments past + x7, a variadic call and a callback; `Host.darwin.raz`, and `HOST=darwin + src/cross.sh darwin-arm64`, which stages the first Mac compiler: it + runs on the Mac, compiles and runs programs, and builds `Procs`. 7. The library: `CAbi`, `Sys`, `Rt`, `Thread`, `Bytes`, `Math`, `Str`. 8. `test/` and `conform/` passing on the Mac; what differs by target (signals' words, errors' numbers) in files of the target's. diff --git a/doc/compiler.md b/doc/compiler.md index 2bb2538..d57f418 100644 --- a/doc/compiler.md +++ b/doc/compiler.md @@ -1,8 +1,8 @@ # Reading the raz compiler -The compiler is fifteen files of raz, about 16,500 lines of code (the +The compiler is fifteen files of raz, about 16,700 lines of code (the budget is 18,000); three of them, `A64.raz`, `Gen.arm64.raz` and -`Exe.darwin.raz`, are the Mac's back end, begun (`PLAN.md` 5), built +`Exe.darwin.raz`, with `Host.darwin.raz` for a compiler that runs on a Mac, are the Mac's back end, begun (`PLAN.md` 5), built only into a compiler for `darwin-arm64` (`src/cross.sh`). It is its own compiler: a release of it, the one `BOOT` names, builds `src/`, and `make fixpoint` checks that what it makes makes itself again, byte for byte. Each release was built by the @@ -28,10 +28,11 @@ | `src/Gen.arm64.raz` | 2,295 | 1,573 | The same for arm64: values, operations, reals, checks, calls, frames | | `src/Item.raz` | 2,553 | 2,051 | Items: types, constants, variables, operators, conversions, calls | | `src/Parse.raz` | 4,947 | 4,197 | Declarations, statements, expressions, built-ins, recovery, warnings | -| `src/Link.raz` | 481 | 365 | Tree shaking, layout, patching, the places | -| `src/Exe.linux.raz` | 455 | 358 | The executable, ELF: static and dynamic, symbol table, line numbers | -| `src/Exe.darwin.raz` | 458 | 332 | The executable for macOS, Mach-O: dyld's binds and rebases, the signature | +| `src/Link.raz` | 531 | 400 | Tree shaking, layout, patching, the places | +| `src/Exe.linux.raz` | 430 | 336 | The executable, ELF: static and dynamic, symbol table, line numbers | +| `src/Exe.darwin.raz` | 559 | 394 | The executable for macOS, Mach-O: dyld's binds and rebases, libraries, line numbers, the signature | | `src/Host.linux.raz` | 103 | 52 | The system running the compiler | +| `src/Host.darwin.raz` | 105 | 60 | The same, for a compiler that runs on a Mac | | `src/Raz.raz` | 499 | 390 | The command line, and `-q` for an editor | Every file opens with a comment that says what it is, what it depends @@ -2601,8 +2602,11 @@ Line numbers are DWARF 4: the line table `makeLines` made from the notes `Chunk.noteLine` made, and the single compile unit gdb needs to find -it, which `putDebug` writes. There are no types or variables in it; -gdb can stop at a line and show where it is, not print a variable. +it, which `Link.debugInfo` and `Link.debugAbbrev` make, shared with +`Exe.darwin.raz`, and `putDebug` places. There are no types or variables +in it; gdb can stop at a line and show where it is, not print a variable. +The table counts addresses in bytes (`minimum_instruction_length` 1), +which suits arm64 too, where every row is a multiple of 4. ## Exe.darwin.raz: the Mac's executable @@ -2610,8 +2614,7 @@ takes it and the kernel runs it, with the same calls as Linux's: the driver's `needLib`, `setStripped` and `write` mean what they mean there, and `setMusl` refuses musl. `-base` is refused, since macOS -loads a program where it chooses, and a library besides libSystem -isn't linked yet. The file: +loads a program where it chooses. The file: | Part | What | |---|---| @@ -2620,6 +2623,7 @@ | `__TEXT` | the header again, at 0, and the code, read and run | | `__DATA_CONST` | rodata, which dyld makes read-only once it has rebased it (`SG_READ_ONLY`) | | `__DATA` | the variables and C's symbols' quadwords, zeros, not in the file | +| `__DWARF` | the line numbers for lldb, three sections (below); not for `-s` | | `__LINKEDIT` | dyld's opcodes, the symbol table, and the code signature | and its load commands: `LC_DYLD_INFO_ONLY` for the rebases and binds; @@ -2627,21 +2631,58 @@ for lldb, and `LC_DYSYMTAB`, which says all are local; `LC_LOAD_DYLINKER` naming `/usr/lib/dyld`; `LC_UUID`, the first 16 bytes of the SHA-256 of what follows the header; `LC_BUILD_VERSION`, -macOS 11.0 and up; `LC_MAIN`, the entry point's offset; `LC_LOAD_DYLIB`, -`/usr/lib/libSystem.B.dylib`; and `LC_CODE_SIGNATURE`. The header has +macOS 11.0 and up; `LC_MAIN`, the entry point's offset; an +`LC_LOAD_DYLIB` for `/usr/lib/libSystem.B.dylib` and one for each +other library (below); four `LC_RPATH`s; and `LC_CODE_SIGNATURE`. The header has the room of every command, `HeaderRoom`, as the code's place is fixed before the commands' sizes are known. Rodata holds the addresses of other chunks (a constant's data fixups), and macOS loads a program anywhere, so dyld must move each: a rebase. -C's symbols are bound into their quadwords from libSystem by name, -with Mach-O's `_` before it. Both are dyld's opcodes, the plainest form +C's symbols are bound into their quadwords by name, with Mach-O's `_` +before it, by flat lookup (below). Both are dyld's opcodes, the plainest form it still takes: a rebase is `SET_SEGMENT_AND_OFFSET_ULEB` and `DO_REBASE_IMM_TIMES`, two bytes and the offset; a bind the symbol's name, its segment and offset, and `DO_BIND`. The other form, chained fixups, which Apple's linker writes now, threads them through the data itself with tables of where each chain starts on each page. +**Line numbers.** lldb reads DWARF from a `__DWARF` segment, as it does +Go's. `Link.makePlaces` has made the line table in the places, in +rodata, where `Rt` reads it; `Exe.darwin.raz` copies it into +`__debug_line`, and puts `Link.debugInfo`'s compile unit in +`__debug_info` and `Link.debugAbbrev`'s in `__debug_abbrev`, the same +bytes Linux's writes. The segment sits after `__DATA` and before +`__LINKEDIT`, which must stay last, for the signature, and is page +aligned like the others. dyld refuses a segment bigger in the file than +in memory (`filesize exceeds vmsize`), so it is mapped, read only, +with its sections flagged `S_ATTR_DEBUG`; nothing touches its pages +unless lldb reads them from the file. `make lldb` (`test/lldb.sh`) and +`make mac-check` run `lldb --batch -o 'b Procs.raz:13' -o run -o bt` +on conform's `Procs` and check that it stops at the line and names each +caller's. `dwarfdump --debug-line` reads the table too. + +**Libraries.** Every program loads libSystem, first. `link "name";` +loads another, by the path `libPath` makes of the name. A name with a +`/` is that path, as it is (`@executable_path/libx.dylib` works). A name +that ends in `.dylib` is `@rpath/` that name. Any other is a library +written as on Linux or bare: it is cut at its first dot and given +`lib` before it if it has none, so `X11`, `libX11` and `libX11.so.6` +are all `@rpath/libX11.dylib`, and so are `m` and `libm.so.6` for +`libm.dylib`, which dyld finds in its cache. Two names of one library +load it once. The program has four `LC_RPATH`s: `@executable_path`, so +that a program can ship its libraries beside it, `/usr/local/lib`, +`/opt/homebrew/lib`, where Homebrew keeps them, and `/usr/lib`. The +compiler looks for nothing when it compiles: a program can be made +where its libraries aren't, as the cross compiler does, and dyld says, +when the program starts, which one it didn't find. Each C symbol is +bound by `BIND_SPECIAL_DYLIB_FLAT_LOOKUP` (ordinal -2), and dyld looks +for it in all the libraries the program loaded, in order, as Linux's +loader does. A two-level namespace wants the library of each symbol, +which `extern` doesn't say (it is found "in the C libraries the program +links", section 9 of the report); flat lookup says exactly that. +`test/mac/NarrowArgs` links a library `cc -dynamiclib` makes. + arm64 macOS runs nothing unsigned, so the file ends with an ad-hoc code signature, which the kernel checks as it maps each page: a SuperBlob holding one CodeDirectory, big-endian, of version 20400H @@ -2702,13 +2743,41 @@ compiler for the Mac this way, in the linux/amd64 container, and `make mac-check` (`test/mac.sh`), on an Apple Silicon Mac, has it compile `test/mac`'s programs there and runs each here, natively, against its -`X.expect` and `X.status`; then conform/run's, which are counted, those +`X.expect` and `X.status` (a test with a C file, `X.c`, has it built into +`libX.dylib` here by `cc`, and as a program, with `-DMAIN`, whose output +must be `X.expect`, so C itself says what is right); then conform/run's, which are counted, those that fail listed in `build/mac/conform.fail`, and those not for the Mac, named in the script with why (`SystemImport`, as `SYSCALL` is Linux's), -skipped. The host changes nothing of the target: +skipped; and last `test/lldb.sh`, if lldb is there (`make lldb` is that +alone, after `make mac-build`, the container's half). The host changes nothing of the target: a program for another system still needs that system's `Sys` and `Rt`, and for a kernel the options `-bare`, `-s` and `-base`. +## Host.darwin.raz: a compiler that runs on a Mac + +`Host.darwin.raz` is `Host.linux.raz` for the compiler running on macOS +(step 9 of `PLAN.md` 5 builds the first); it has the same five +procedures and `CLib`. Four things differ. There is no `/proc`: +`libraryDir` asks `_NSGetExecutablePath` for the compiler's path and +`realpath` follows its links, then takes the `lib` beside it (argument +0 if either fails). There is one C library, so `cLibrary` says `glibc`, +meaning the system's, and there is no musl. There is no `memfd_create`: +`prepareRun` is a file in `$TMPDIR` (`/tmp` if it isn't set), named by +the compiler's process number, an error if that directory isn't +writable; `execute` runs it with `Sys.execve`, and the file stays, +for macOS to clear. And a file's code signature belongs to the file, so +a program written in place over one that has run is killed: +`writeExecutable` removes what is there first, then writes and sets +mode 755. It uses `Sys` and `Files`, the C ones, and declares two +externs of its own, `_NSGetExecutablePath` and `realpath`. + +`HOST=darwin src/cross.sh darwin-arm64` stages it: the Mac's `Host`, `Gen` and +`Exe` in a directory of their own, `build/cross/darwin-arm64-on-darwin`, +built by the cross compiler `src/cross.sh darwin-arm64` made, since +BOOT's makes programs for Linux. The result is a Mac executable: on a +Mac, `raz --version`, `raz -o hello Hello.raz` and `raz run` work, and +it builds conform's `Procs`, which lldb stops in. + ## Raz.raz: the command line `Raz.raz` parses the arguments, calls `Parse.compileMain`, and works out what @@ -3144,15 +3213,19 @@ | `Sys.chmod` | `Host.writeExecutable`: makes the program's file executable (mode 755) | | `Sys.close` | `Scan` and `Parse`: closes a source or `RAZ-VERSION` file after reading | | `Sys.closeDir`, `Sys.openDir`, `Sys.nextEntry`, `Sys.Dir` | `Parse`: the files of a directory, to find a module's other files for the one-module-of-each-name check | -| `Sys.env`, `Sys.envAt` | `Diag` (`NO_COLOR`) and `Raz.userLibraries` (`RAZ_PATH`, `HOME`; `envAt` tells unset from empty) | +| `Sys.env`, `Sys.envAt` | `Diag` (`NO_COLOR`), `Raz.userLibraries` (`RAZ_PATH`, `HOME`; `envAt` tells unset from empty) and `Host.darwin.raz` (`TMPDIR`, and the environment `execute` hands on) | | `Sys.errDenied`, `Sys.errNoEntry`, `Sys.errIntr` | `Scan`: "permission denied" and "there is no such file" in a message; a read of standard input a signal broke into, tried again | +| `Sys.execve` | `Host.darwin.raz`'s `execute`: runs the program `raz run` wrote, in the compiler's place | | `Sys.info`, `Sys.Info` | `Scan` and `Parse`: whether a path is a file (`file`) and its length (`size`) | | `Sys.isTerminal` | `Diag`: colour only when standard error is a terminal | +| `Sys.pid` | `Host.darwin.raz`'s `prepareRun`: the name of the file a program is written to | +| `Sys.remove` | `Host.darwin.raz`'s `writeExecutable`: a program's file is never written over in place | | `Sys.openRead`, `Sys.read` | `Scan`: reads a source file whole; `Parse`: the library's `RAZ-VERSION` | | `Sys.stdin` | `Scan`: `raz -q`'s source, read from standard input | | `Sys.readLink` | `Host.libraryDir`: `/proc/self/exe`, to find the library beside the compiler | | `Sys.stderr`, `Sys.stdout`, `Sys.write` | `Diag`: its messages, or `raz -q check`'s rows on standard output | -| `Sys.workDir` | `Diag`: shows a path relative to the working directory; `Exe`: the compilation directory of the line table | +| `Sys.workDir` | `Diag`: shows a path relative to the working directory; `Link`: the compilation directory of the line table | +| `Sys.writing` | `Host.darwin.raz`'s `prepareRun`: whether `$TMPDIR` is a directory the compiler may write to | `Rt`, the run time, besides `fail`, `exit` and the places (above): diff --git a/src/Exe.darwin.raz b/src/Exe.darwin.raz index 0865f38..c63c544 100644 --- a/src/Exe.darwin.raz +++ b/src/Exe.darwin.raz @@ -13,6 +13,7 @@ addresses in it (rebases) __DATA the variables, zeros, and C's symbols' quadwords, which dyld fills in (binds) + __DWARF the line numbers lldb reads (below), in the file only __LINKEDIT what dyld reads, unmapped by the program: the rebases and binds, the symbol table, and the code signature @@ -32,10 +33,27 @@ its pages of 4 KB, in a CodeDirectory, which the kernel checks as it maps them. + Line numbers are DWARF 4, the same as Linux's: Link makes the line + table (in the places, in rodata, where Rt reads it too) and the one + compile unit; here they are copied into __DWARF, a segment of three + sections, __debug_line, __debug_info and __debug_abbrev, which lldb + finds there as it does Go's. dyld refuses a segment bigger in the file + than in memory, so it is mapped, read only, and never touched: its + pages are read only if the program is stopped in lldb. It lies before __LINKEDIT, which must stay last, for the signature. + -s leaves it out, and the symbols. + + Libraries. Every program loads libSystem, first. A program that says + `link "name";` loads that library too, by the path libPath makes of + the name (below), and every C symbol is bound by flat lookup, as the + ordinal -2 (BIND_SPECIAL_DYLIB_FLAT_LOOKUP): dyld looks for it in all + the libraries the program loaded, in order, as Linux's loader does. + The compiler doesn't know which library defines a symbol, as `extern` + doesn't say, and the two-level namespace wants it to say; flat lookup + is how a Mac's program says "wherever it is". + Depends on: Link for the images and addresses, Chunk for the chunks, Scan for names and memory, Diag for errors, Host to write the file. - Leaves out: line numbers (DWARF, in __DWARF, PLAN.md 5), libraries - besides libSystem, an export trie (the program exports nothing). + Leaves out: an export trie (the program exports nothing). Exported variables can't be set from outside, so needLib, setMusl, setMainPath and setStripped do it. *) @@ -49,14 +67,20 @@ Page = 4000H; (* arm64 macOS's page, 16 KB, on which each segment starts *) HashPage = 1000H; (* the signature hashes pages of 4 KB *) Dyld = "/usr/lib/dyld"; - (* room for the header and the most load commands: see write *) - HeaderRoom = 32 + 72 + 3 * 152 + 72 + 48 + 24 + 80 + 32 + 24 + 24 + 24 + 56 + 16; + Rpaths: [4][]const U8 = ["@executable_path", "/usr/local/lib", "/opt/homebrew/lib", "/usr/lib"]; + (* room for the header and the load commands but the libraries': see + write. The most segments: __PAGEZERO, __TEXT, __DATA_CONST, __DATA, + __DWARF (three sections), __LINKEDIT; then dyld info, symbols and + the rest; the four rpaths of libPath. *) + HeaderRoom = 32 + 72 + 3 * 152 + (72 + 3 * 80) + 72 + 48 + 24 + 80 + 32 + 24 + 24 + 24 + 16 + + 32 + 32 + 32 + 24; var needed: [32]INT; (* the libraries to load, names interned *) numNeeded*: INT; stripped*: BOOL; (* -s: no symbols *) libc*: []const U8; (* the C library, libSystem *) + mainPath: []const U8; (* the main module's file, which lldb will name *) buf: ^U8; len, cap: INT; @@ -89,7 +113,34 @@ (* The main module's file, which line numbers will name *) proc setMainPath*(path: []const U8); begin - _ := path; + mainPath := path; +end; + +(* The path a `link` name loads from. A name with a / is a path, used as + it is (it may start with @executable_path/). Otherwise the name is a + library's, written as on Linux or without its decoration: "X11", + "libX11" and "libX11.so.6" all mean libX11.dylib, the name cut at its + first dot, "lib" put before it if it isn't there; a name that ends in + .dylib is kept whole. The file is then looked for, at run time, by + @rpath, which the program gives four places: its own directory, so + that a program can ship its libraries, /usr/local/lib and + /opt/homebrew/lib, where Homebrew keeps them, and /usr/lib. Nothing + is looked for when compiling, so a program can be compiled where its + libraries are not, as for another machine. *) +proc libPath(name: []const U8): []const U8; +var i, stem: INT; +begin + stem := 0; + for i := LEN(name) - 1 to 0 by -1 do + if name[i] = '/' then return name; end; + if name[i] = '.' then stem := i; end; + end; + if (LEN(name) > 6) and (name[LEN(name) - 6..LEN(name)] = ".dylib") then + return Diag.say("@rpath/{}", [Fmt.str(name)]); + end; + if stem = 0 then stem := LEN(name); end; + if (stem > 3) and (name[0..3] = "lib") then return Diag.say("@rpath/{}.dylib", [Fmt.str(name[0..stem])]); end; + return Diag.say("@rpath/lib{}.dylib", [Fmt.str(name[0..stem])]); end; proc setStripped*(yes: BOOL); @@ -230,7 +281,7 @@ const LcSegment = 19H; LcSymtab = 2H; LcDysymtab = 0BH; LcLoadDylinker = 0EH; LcLoadDylib = 0CH; LcUuid = 1BH; LcBuildVersion = 32H; LcMain = 80000028H; LcDyldInfoOnly = 80000022H; - LcCodeSignature = 1DH; + LcCodeSignature = 1DH; LcRpath = 8000001CH; (* A segment of 64 bits, followed by its nsects sections; prot is the access, 1 read, 2 write, 4 run *) @@ -275,20 +326,36 @@ rebaseOff, rebaseSize, bindOff, bindSize, symOff, nsyms, strOff, strSize, sigOff, sigSize, slots: INT; ident: []const U8; uuidAt, end0, sigRoom: INT; + dwarfOff, dwarfSize, dwarfAdr, libsRoom: INT; + dbgOff, dbgSize: [3]INT; + libs: [33][]const U8; (* the paths to load, libSystem first *) + nlibs: INT; + debug: BOOL; begin if Link.base # 400000H then Diag.fatal("-base: macOS loads a program where it chooses"); end; - for i := 1 to numNeeded - 1 do - Diag.fatal(Diag.say("not yet on darwin-arm64: a library besides libSystem, {}", [Fmt.str(Scan.nameOf(needed[i]))])); + libs[0] := libc; + nlibs := 1; + libsRoom := roundUp(24 + LEN(libc) + 1, 8); + for i := 0 to numNeeded - 1 do + libs[nlibs] := libPath(Scan.nameOf(needed[i])); + n := 0; (* several names may mean one library: "m" and "libm.so.6" *) + while libs[n] # libs[nlibs] do INC(n); end; + if n = nlibs then (* new *) + libsRoom := libsRoom + roundUp(24 + LEN(libs[nlibs]) + 1, 8); + INC(nlibs); + end; end; + debug := not stripped and (Link.placesChunk >= 0); cap := 1 shl 16; buf := Scan.grab(cap); len := 0; Link.setBase(Base); Link.setPaged(Page); - Link.linkAll(HeaderRoom, 0, 0); + Link.linkAll(HeaderRoom + libsRoom, 0, 0); textSize := roundUp(Link.textOff + Link.textSize, Page); (* __TEXT's, the header in it *) - leOff := Link.bssOff; (* the next page in the file: __DATA has no bytes there *) + dwarfOff := Link.bssOff; (* the next page in the file: __DATA has no bytes there *) leAdr := Link.bssAdr + roundUp(Link.bssSize, Page); + dwarfAdr := leAdr; (* the segments' numbers, as the opcodes name them, and the sections', as the symbols do: __PAGEZERO 0, __TEXT 1 (__text, 1) *) segRo := 2; @@ -301,6 +368,24 @@ putBytes(Link.textImg, Link.textSize); padTo(Link.roOff); putBytes(Link.roImg, Link.roSize); + padTo(dwarfOff); + + (* the line numbers: the line table, copied from the places, then the + compile unit and its abbreviation; each section's file offset and size *) + if debug then + dbgOff[0] := len; + dbgSize[0] := Link.linesSize; + putBytes(Link.roImg + (Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.linesOff), Link.linesSize); + ident := Link.debugInfo(mainPath); + dbgOff[1] := len; dbgSize[1] := LEN(ident); + putBytes(SYSTEM.PTR(ident), LEN(ident)); + ident := Link.debugAbbrev(); + dbgOff[2] := len; dbgSize[2] := LEN(ident); + putBytes(SYSTEM.PTR(ident), LEN(ident)); + end; + dwarfSize := len - dwarfOff; + leOff := roundUp(len, Page); (* __LINKEDIT, a page of its own *) + leAdr := leAdr + roundUp(dwarfSize, Page); (* in memory, after __DWARF *) padTo(leOff); (* rebases: each word in rodata that holds an address, a pointer @@ -315,10 +400,10 @@ padTo(roundUp(len, 8)); rebaseSize := len - rebaseOff; - (* binds: each C symbol's quadword, from library 1, libSystem, by - its name, which in Mach-O begins with _ *) + (* binds: each C symbol's quadword, by flat lookup (above), by its + name, which in Mach-O begins with _ *) bindOff := len; - putN(11H, 1); (* BIND_OPCODE_SET_DYLIB_ORDINAL_IMM, 1 *) + putN(3EH, 1); (* BIND_OPCODE_SET_DYLIB_SPECIAL_IMM, -2 *) putN(51H, 1); (* SET_TYPE_IMM, pointer *) for c := 0 to Chunk.numChunks - 1 do if isExt(c) then @@ -397,6 +482,13 @@ segment("__DATA", Link.bssAdr, roundUp(Link.bssSize, Page), 0, 0, 3, 1, 0); INC(ncmds); section("__bss", "__DATA", Link.bssAdr, Link.bssSize, 0, 3, 1); (* S_ZEROFILL *) end; + if debug then + (* read only, flags 0 *) + segment("__DWARF", dwarfAdr, roundUp(dwarfSize, Page), dwarfOff, dwarfSize, 1, 3, 0); INC(ncmds); + section("__debug_line", "__DWARF", dwarfAdr + dbgOff[0] - dwarfOff, dbgSize[0], dbgOff[0], 0, 02000000H); (* S_ATTR_DEBUG *) + section("__debug_info", "__DWARF", dwarfAdr + dbgOff[1] - dwarfOff, dbgSize[1], dbgOff[1], 0, 02000000H); + section("__debug_abbrev", "__DWARF", dwarfAdr + dbgOff[2] - dwarfOff, dbgSize[2], dbgOff[2], 0, 02000000H); + end; segment("__LINKEDIT", leAdr, roundUp(sigOff + sigRoom - leOff, Page), leOff, sigOff + sigRoom - leOff, 1, 0, 0); INC(ncmds); putN(LcDyldInfoOnly, 4); putN(48, 4); putN(rebaseOff, 4); putN(rebaseSize, 4); putN(bindOff, 4); putN(bindSize, 4); @@ -412,12 +504,20 @@ putN(1, 4); putN(0B0000H, 4); putN(0B0000H, 4); putN(0, 4); (* macOS, 11.0 and up, SDK 11.0, no tools *) INC(ncmds); putN(LcMain, 4); putN(24, 4); putN(Chunk.chunks[entry].adr - Base, 8); putN(0, 8); INC(ncmds); - (* libSystem, version 1.0.0 and compatible with 1.0.0, which any is *) - n := roundUp(24 + LEN(libc) + 1, 8); - putN(LcLoadDylib, 4); putN(n, 4); putN(24, 4); putN(2, 4); putN(10000H, 4); putN(10000H, 4); - putName(libc, n - 24); INC(ncmds); + (* each library, version 1.0.0 and compatible with 1.0.0, which any is + (dyld checks those of the library's own; the timestamp is 2) *) + for i := 0 to nlibs - 1 do + n := roundUp(24 + LEN(libs[i]) + 1, 8); + putN(LcLoadDylib, 4); putN(n, 4); putN(24, 4); putN(2, 4); putN(10000H, 4); putN(10000H, 4); + putName(libs[i], n - 24); INC(ncmds); + end; + (* where @rpath looks, in order (libPath) *) + for i := 0 to 3 do + n := roundUp(12 + LEN(Rpaths[i]) + 1, 8); + putN(LcRpath, 4); putN(n, 4); putN(12, 4); putName(Rpaths[i], n - 12); INC(ncmds); + end; putN(LcCodeSignature, 4); putN(16, 4); putN(sigOff, 4); putN(sigRoom, 4); INC(ncmds); - if len > HeaderRoom then Diag.fatal("internal error: the Mach-O header outgrew its room"); end; + if len > HeaderRoom + libsRoom then Diag.fatal("internal error: the Mach-O header outgrew its room"); end; i := len; len := 16; putN(ncmds, 4); putN(i - 32, 4); len := end0; @@ -454,5 +554,6 @@ end; begin + mainPath := ""; libc := "/usr/lib/libSystem.B.dylib"; end Exe. diff --git a/src/Exe.linux.raz b/src/Exe.linux.raz index f7130d1..48acb90 100644 --- a/src/Exe.linux.raz +++ b/src/Exe.linux.raz @@ -16,8 +16,8 @@ There is no PLT and no lazy binding, and the program exports nothing. Depends on: Link for the images and addresses, Chunk for the chunks, - Scan for names and memory, Diag for errors, Sys for the working - directory, and Host to write the file. + Scan for names and memory, Diag for errors, and Host to write the + file; Link also makes the DWARF's compile unit. Leaves out: position independent executables, symbol versions, the rest of DWARF. @@ -27,7 +27,7 @@ Exported variables can't be set from outside, so needLib, setMusl, setMainPath and setStripped do it. *) module Exe; -import Sys, Host, Fmt, Diag, Scan, Chunk, Link; +import Host, Fmt, Diag, Scan, Chunk, Link; import SYSTEM; const @@ -176,47 +176,22 @@ putN(0, 1); end; -(* LEB128, unsigned *) -proc putU(v: INT); -begin - while v >= 80H do - putN(v & 7FH | 80H, 1); - v := v shr 7; - end; - putN(v, 1); -end; - -(* The compile unit, which names the line table, and its abbreviation; - the table itself is in the places, in rodata (Link). Section - offsets go in off, sizes in size: line, info, abbrev. *) +(* The compile unit, which names the line table, and its abbreviation + (Link makes them); the table itself is in the places, in rodata. + Section offsets go in off, sizes in size: line, info, abbrev. *) proc putDebug(off, size: []INT); -var cwd: []const U8; err: INT; +var info, abbrev: []const U8; begin off[0] := Chunk.chunks[Link.placesChunk].adr - Link.roAdr + Link.roOff + Link.linesOff; size[0] := Link.linesSize; + info := Link.debugInfo(mainPath); off[1] := len; - putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *) - putU(1); - putStr(mainPath); - cwd, err := Sys.workDir(); - if err # 0 then cwd := ""; end; - putStr(cwd); - putStr("raz"); - putN(0, 4); (* the line table, at 0 *) - putN(Link.base + Link.textOff, 8); putN(Link.textSize, 8); (* the code, all of it *) - patch(off[1], len - off[1] - 4, 4); - size[1] := len - off[1]; - + putBytes(SYSTEM.PTR(info), LEN(info)); + size[1] := LEN(info); + abbrev := Link.debugAbbrev(); off[2] := len; - putU(1); putU(11H); putN(0, 1); (* 1: a compile unit, no children *) - putU(03H); putU(08H); (* name, a string *) - putU(1BH); putU(08H); (* comp_dir, a string *) - putU(25H); putU(08H); (* producer, a string *) - putU(10H); putU(17H); (* stmt_list, a section offset *) - putU(11H); putU(01H); (* low_pc, an address *) - putU(12H); putU(07H); (* high_pc, a length in 8 bytes *) - putN(0, 2); putN(0, 1); - size[2] := len - off[2]; + putBytes(SYSTEM.PTR(abbrev), LEN(abbrev)); + size[2] := LEN(abbrev); end; const diff --git a/src/Host.darwin.raz b/src/Host.darwin.raz new file mode 100644 index 0000000..648c217 --- /dev/null +++ b/src/Host.darwin.raz @@ -0,0 +1,105 @@ +(* Host: what the compiler asks of the system it runs on, beyond the + library. The host is the system running raz; the target, the one its + program will run on. This file is macOS's, for the compiler running + on a Mac (a cross compiler built for one is staged with it, as + src/cross.sh does); Host.linux.raz says what each procedure is for + and what a host must give, and this one gives the same five. + + macOS differs from Linux in four things the compiler asks: + - there is no /proc: the compiler's own path is _NSGetExecutablePath, + which may name it through a link, so realpath follows them; + - there is one C library, libSystem, so cLibrary says glibc, which + here means "the C library the system has", and there is no musl; + - there is no memfd_create: a program raz run starts is written to a + file, in $TMPDIR (/tmp if it is not set), named by the compiler's + process number, and the file stays after the program replaces the + compiler, which macOS clears out of $TMPDIR in time; + - a file's code signature belongs to the file: a program written + in place over one that has run is killed. prepareRun's name is new + each time, and writeExecutable removes a file that is there first. + + Depends on: Sys and Files for the system's services, Scan for memory + that lasts until exit, Diag and Fmt for paths. + Leaves out: compiling and the executable format, which are Parse and + Exe's. *) +module Host; +import Sys, Files, Fmt, Diag, Scan; +import SYSTEM; + +type + CLib* = (none, glibc, musl); (* the C library to link against *) + +const + Mode755 = 1EDH; (* rwxr-xr-x *) + PathMax = 4096; (* more than macOS's 1024, which realpath needs *) + NoRoom: ERROR = "no writable directory for the program"; + +extern proc _NSGetExecutablePath(buf: ^U8; size: ^U32): I32; +extern proc realpath(path, resolved: ^U8): ^U8; + +(* The directory of the library, ending in what the name of raz leaves, + "lib": the one beside raz as the system says it, links followed, or, + if it won't say, beside argument 0 as it was typed *) +proc libraryDir*: []const U8; +var raw, real: ^U8; size: U32; path: []const U8; n, i: INT; +begin + raw := Scan.grab(PathMax); + real := Scan.grab(PathMax); + size := U32(PathMax); + path := Files.arg(0); + if (_NSGetExecutablePath(raw, SYSTEM.ADR(size)) = 0) and (realpath(raw, real) # nil) then + n := 0; + while real[n] # 0 do INC(n); end; + path := real[0..n]; + end; + i := LEN(path); + while (i > 0) and (path[i - 1] # '/') do DEC(i); end; + if i = 0 then return "lib"; end; + return Diag.say("{}lib", [Fmt.str(path[0..i])]); +end; + +(* The C library a program is linked against: the Mac's one, libSystem *) +proc cLibrary*: CLib; +begin + return glibc; +end; + +(* The file at path made to hold data, an executable: any file there + removed first (see above), then written and given mode 755. False if + it failed. *) +proc writeExecutable*(path, data: []const U8): BOOL; +begin + _ := Sys.remove(path); + return Files.write(path, data) and (Sys.chmod(path, Mode755) >= 0); +end; + +(* The path raz run writes its program to: a file in $TMPDIR, if that + is a directory the compiler may write to *) +proc prepareRun*: ([]const U8, ERROR); +var dir: []const U8; +begin + dir := Sys.env("TMPDIR"); + if LEN(dir) = 0 then dir := "/tmp"; end; + if dir[LEN(dir) - 1] = '/' then dir := dir[0..LEN(dir) - 1]; end; + if Sys.access(dir, {Sys.writing}) # 0 then return "", NoRoom; end; + return Diag.say("{}/raz-run-{}", [Fmt.str(dir), Fmt.int(Sys.pid())]), nil; +end; + +(* The program at path runs in the compiler's place, with the compiler's + arguments from number first on as its own, first as its argument 0, + and the environment. It returns only if that failed: minus the errno. *) +proc execute*(path: []const U8; first: INT): INT; +var args, env: ^[]const U8; n, m, i: INT; more: BOOL; +begin + n := Files.argCount() - first; + args := ^[]const U8(Scan.grab((n + 1) * SIZE([]const U8))); + for i := 0 to n - 1 do args[i] := Files.arg(first + i); end; + m := 0; + _, more := Sys.envAt(0); + while more do INC(m); _, more := Sys.envAt(m); end; + env := ^[]const U8(Scan.grab((m + 1) * SIZE([]const U8))); + for i := 0 to m - 1 do env[i], _ := Sys.envAt(i); end; + return Sys.execve(path, args[0..n], env[0..m]); +end; + +end Host. diff --git a/src/Link.raz b/src/Link.raz index f0cea88..887bde8 100644 --- a/src/Link.raz +++ b/src/Link.raz @@ -19,11 +19,14 @@ loader to move with it. arm64's fixups, fields of an instruction, are patched here too. + Also here, shared by both executable formats, the DWARF the line table + needs (debugInfo, debugAbbrev): the one compile unit that points to it. + Depends on: Chunk for chunks and fixups, Scan for names and memory, - Diag for errors and paths. + Diag for errors and paths, Sys for the working directory. Leaves out: the file format; that is Exe. *) module Link; -import Fmt, Diag, Scan, Chunk; +import Sys, Fmt, Diag, Scan, Chunk; import SYSTEM; const @@ -339,6 +342,53 @@ patch8(buf, 24, np); patch8(buf, 32, nv); Chunk.setData(placesChunk, buf, names + lpLen, 8); +end; + +(* The compile unit that names the line table, and its abbreviation, DWARF + 4's .debug_info and .debug_abbrev: the main module's file and the + directory it was compiled in, the producer, the line table (at 0 of its + section), and the code, all of it. No types and no variables. Each is + made in lp, which the line table has left, and returned: copy it + before the next call. The address unit of the line table is a byte + (minimum_instruction_length 1, in makeLines), so its rows hold, and + its advances count, bytes, on arm64 too, where every row is a multiple + of 4: DWARF takes that, and no row needs dividing. *) +proc putStr(s: []const U8); +var i: INT; +begin + for i := 0 to LEN(s) - 1 do putB(INT(s[i])); end; + putB(0); +end; + +proc debugInfo*(name: []const U8): []const U8; +var cwd: []const U8; err: INT; +begin + lpLen := 0; + putN(0, 4); putN(4, 2); putN(0, 4); putN(8, 1); (* length, version, abbrev, address size *) + putU(1); (* abbreviation 1 *) + putStr(name); + cwd, err := Sys.workDir(); + if err # 0 then cwd := ""; end; + putStr(cwd); + putStr("raz"); + putN(0, 4); (* the line table, at 0 *) + putN(base + textOff, 8); putN(textSize, 8); (* the code, all of it *) + patch4(lp, 0, lpLen - 4); + return lp[0..lpLen]; +end; + +proc debugAbbrev*: []const U8; +begin + lpLen := 0; + putU(1); putU(11H); putB(0); (* 1: a compile unit, no children *) + putU(03H); putU(08H); (* name, a string *) + putU(1BH); putU(08H); (* comp_dir, a string *) + putU(25H); putU(08H); (* producer, a string *) + putU(10H); putU(17H); (* stmt_list, a section offset *) + putU(11H); putU(01H); (* low_pc, an address *) + putU(12H); putU(07H); (* high_pc, a length in 8 bytes *) + putN(0, 2); putB(0); + return lp[0..lpLen]; end; (* The address a as raz writes it, in hexadecimal: 0FFFFFFFF80000000H *) diff --git a/src/cross.sh b/src/cross.sh index 65328ff..5d5b3e4 100755 --- a/src/cross.sh +++ b/src/cross.sh @@ -4,7 +4,14 @@ # is whatever files the compiler was built from (doc/raz.md, 3). # # src/cross.sh TARGET [OUT] run from the repository root +# HOST=darwin src/cross.sh darwin-arm64 [OUT] # +# The second makes the compiler that runs on a Mac and compiles for it, +# the first Mac compiler (PLAN.md 5, step 9): the stage has the host's +# own Host.darwin.raz, and it is built by the cross compiler of the +# first form, which must be there, since BOOT's makes programs for this +# system, and a stage for another host can't be run here to be built. +# # Stage build/cross/TARGET/src/ holds src/'s generic files and, under # the plain names, the target's own: Gen.ARCH.raz as Gen.raz and # Exe.OS.raz as Exe.raz; and the host's, Host.OS.raz as Host.raz, the @@ -12,18 +19,18 @@ # With only plain names there, module lookup has one choice each. BOOT's # release builds the stage as the Makefile builds raz, from a directory # where src/Raz.raz is again at src/, so the paths a program holds are -# the same. The compiler is OUT, build/cross/TARGET/raz if not said; +# the same. The compiler is OUT, build/cross/TARGET/raz (or TARGET-on-HOST) if not said; # its library is lib/, beside it. set -e target=$1 -out=${2:-build/cross/$target/raz} case $target in *-*) ;; *) echo "usage: src/cross.sh OS-ARCH [OUT]" >&2; exit 2;; esac os=${target%%-*} arch=${target#*-} -host=$(uname -s | tr A-Z a-z) # the OS that runs the compiler +here=$(uname -s | tr A-Z a-z) +host=${HOST:-$here} # the OS that runs the compiler # Each unit with files by target, and the file this build takes of it missing= @@ -38,6 +45,8 @@ [ -x build/boot/raz ] || make build/boot/raz d=build/cross/$target +[ $host != $here ] && d=$d-on-$host +out=${2:-$d/raz} rm -rf $d mkdir -p $d/src $d/v for f in src/*.raz; do @@ -52,8 +61,9 @@ cp build/src/Version.raz $d/v/ ln -s ../../../lib $d/lib boot=$PWD/build/boot/raz +[ $host != $here ] && boot=$PWD/build/cross/$target/raz # the cross compiler, run here (cd $d && $boot -Werror -I src -I v -o raz src/Raz.raz) case $out in -build/cross/$target/raz) ;; +$d/raz) ;; *) cp $d/raz "$out";; esac diff --git a/test/compiler-host.sh b/test/compiler-host.sh index 44c05f9..c4dce86 100755 --- a/test/compiler-host.sh +++ b/test/compiler-host.sh @@ -31,7 +31,7 @@ mkdir "$top/src" "$top/work" cp src/*.raz "$top/src" # staged as src/cross.sh does: the plain name takes the place of Linux's -rm "$top/src/Host.linux.raz" +rm "$top"/src/Host.*.raz cp test/host/Host.raz "$top/src/Host.raz" "$raz" -Werror -I "$top/src" -I build/src -o "$top/compiler" "$top/src/Raz.raz" 2>"$top/build.err" || { cat "$top/build.err" diff --git a/test/lldb.sh b/test/lldb.sh new file mode 100755 index 0000000..c71c7f9 --- /dev/null +++ b/test/lldb.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Line numbers for lldb, as gdb.sh's for gdb, on a Mac: stops a test +# program at a line of its source, by file and line, and checks that +# lldb names it, and the line of each caller. The program is conform's +# Procs, which test/mac.sh build made for darwin-arm64 in build/mac. +prog=build/mac/conform/Procs +out=build/mac +if [ ! -x $prog ]; then echo "FAIL lldb: no $prog; make mac-build first"; exit 1; fi +lldb --batch -o 'b Procs.raz:13' -o run -o bt $prog > $out/lldb.out 2>&1 +for want in 'Procs.odd at Procs.raz:13' \ + 'Procs.even at Procs.raz:20' \ + 'Procs.main at Procs.raz:'; do + if ! grep -qF "$want" $out/lldb.out; then + echo "FAIL lldb: no \"$want\""; cat $out/lldb.out; exit 1 + fi +done +echo "lldb finds the lines" diff --git a/test/mac.sh b/test/mac.sh index f3af30d..9524553 100755 --- a/test/mac.sh +++ b/test/mac.sh @@ -15,6 +15,12 @@ # test/mac.sh build in the container: the cross compiler, then the programs # test/mac.sh run on the Mac: each program, run with a timeout # +# A test with a C file, test/mac/X.c, links the library that file makes: +# run builds it by cc into build/mac/libX.dylib, where the program finds +# it by @executable_path (Exe.darwin's libPath), and, built as a program +# with -DMAIN, it must print what X.expect holds, as C itself says it. +# Then lldb, if there is one, must find a line (test/lldb.sh). +# # build/mac is made anew each time: macOS keeps a file's code signature # while the file is open or cached, and kills a program whose file was # written again in place with another one. @@ -41,6 +47,14 @@ run) pass=0 fail=0 + for f in test/mac/*.c; do + name=$(basename $f .c) + cc -dynamiclib -o $out/lib$name.dylib $f + cc -DMAIN -o $out/$name.cmain $f + if ! $out/$name.cmain | cmp -s - test/mac/$name.expect; then + echo "FAIL $f: C's own output differs from $name.expect"; fail=$((fail + 1)) + fi + done for f in test/mac/*.raz; do name=$(basename $f .raz) want=0 @@ -93,6 +107,7 @@ fi done echo "conform/run: $cpass of $((cpass + cfail)) passed, $cskip not for this target; the others in $c.fail" + if command -v lldb > /dev/null; then test/lldb.sh || fail=$((fail + 1)); fi [ $fail = 0 ] ;; *) diff --git a/test/mac/NarrowArgs.c b/test/mac/NarrowArgs.c new file mode 100644 index 0000000..ee28feb --- /dev/null +++ b/test/mac/NarrowArgs.c @@ -0,0 +1,69 @@ +/* NarrowArgs's C side (test/mac.sh): built by cc into a library, which + the raz program links; with -DMAIN, built as a program that prints + what NarrowArgs.expect holds, so that C itself says what is right. */ +#include +#include +#include + +/* A running hash: each value changes every digit after it */ +static int64_t mix(int64_t h, int64_t v) { return (int64_t)((uint64_t)h * 1000003u + (uint64_t)v); } + +/* Eight integers in x0 to x7; then, on the stack, packed by size as + Apple's convention has it, i at 0, j at 1, k at 2, l at 4, m at 8, n + at 16, y at 24, z at 32 and last at 40; the reals p to w in v0 to v7 */ +int64_t narrow(int8_t a, uint8_t b, int16_t c, int32_t d, int64_t e, uint8_t f, int16_t g, int32_t h, + int8_t i, uint8_t j, int16_t k, int32_t l, int8_t m, int64_t n, + float p, double q, float r, double s, float t, double u, float v, double w, + float y, double z, int8_t last) { + int64_t x = 7; + x = mix(x, a); x = mix(x, b); x = mix(x, c); x = mix(x, d); + x = mix(x, e); x = mix(x, f); x = mix(x, g); x = mix(x, h); + x = mix(x, i); x = mix(x, j); x = mix(x, k); x = mix(x, l); + x = mix(x, m); x = mix(x, n); + x = mix(x, (int64_t)(p * 4)); x = mix(x, (int64_t)(q * 4)); + x = mix(x, (int64_t)(r * 4)); x = mix(x, (int64_t)(s * 4)); + x = mix(x, (int64_t)(t * 4)); x = mix(x, (int64_t)(u * 4)); + x = mix(x, (int64_t)(v * 4)); x = mix(x, (int64_t)(w * 4)); + x = mix(x, (int64_t)(y * 4)); x = mix(x, (int64_t)(z * 4)); + x = mix(x, last); + return x; +} + +/* A variadic procedure: its arguments past n all go on the stack, each 8 bytes */ +int64_t varsum(int n, ...) { + va_list ap; + int64_t x = 7; + int k; + va_start(ap, n); + for (k = 0; k < n; k++) { + if (k % 2 == 0) x = mix(x, va_arg(ap, int)); else x = mix(x, (int64_t)(va_arg(ap, double) * 4)); + } + va_end(ap); + return x; +} + +/* C calls back a procedure of ten integers, the last two on the stack */ +int64_t callback(int64_t (*cb)(int64_t, int64_t, int64_t, int64_t, int64_t, + int64_t, int64_t, int64_t, int64_t, int64_t)) { + return cb(1, -2, 3, -4, 5, -6, 7, -8, 9, -10); +} + +#ifdef MAIN +static int64_t mine(int64_t a, int64_t b, int64_t c, int64_t d, int64_t e, + int64_t f, int64_t g, int64_t h, int64_t i, int64_t j) { + int64_t x = 7; + x = mix(x, a); x = mix(x, b); x = mix(x, c); x = mix(x, d); x = mix(x, e); + x = mix(x, f); x = mix(x, g); x = mix(x, h); x = mix(x, i); x = mix(x, j); + return x; +} + +int main(void) { + printf("%lld\n", (long long)narrow(-1, 200, -300, -70000, -5000000000LL, 255, -32768, 2147483647, + -128, 129, -2, -100000, 127, 9000000000LL, + 1.5f, -2.25, 3.5f, 4.75, -5.5f, 6.25, 7.5f, -8.75, + 9.5f, 10.25, -100)); + printf("%lld\n", (long long)varsum(5, 1, 1.5, -3, -2.25, 5)); + printf("%lld\n", (long long)callback(mine)); + return 0; +} +#endif diff --git a/test/mac/NarrowArgs.expect b/test/mac/NarrowArgs.expect new file mode 100644 index 0000000..fa84e84 --- /dev/null +++ b/test/mac/NarrowArgs.expect @@ -0,0 +1,3 @@ +-4734827987094619837 +-7950848964622138137 +9213667167917808028 diff --git a/test/mac/NarrowArgs.raz b/test/mac/NarrowArgs.raz new file mode 100644 index 0000000..f7e47b8 --- /dev/null +++ b/test/mac/NarrowArgs.raz @@ -0,0 +1,48 @@ +(* Calling C with arguments of every width past the registers (PLAN.md 5, + step 6): Apple's convention packs a C procedure's own arguments on the + stack by their natural size, where a raz procedure's take 8 bytes + each. narrow has eight integers in x0 to x7, six more on the stack + (an I8, a U8, an I16, an I32, an I8, an I64), eight reals in v0 to v7 + and an F32, an F64 and an I8 past them. varsum is variadic, whose + arguments past its own go on the stack, 8 bytes each. callback has C + call a raz procedure of ten integers. Each answer is a hash C makes of + what it received; NarrowArgs.c, built as a program, prints the same. *) +module NarrowArgs; +import Out; +import SYSTEM; +link "NarrowArgs"; + +extern proc narrow(a: I8; b: U8; c: I16; d: I32; e: I64; f: U8; g: I16; h: I32; + i: I8; j: U8; k: I16; l: I32; m: I8; n: I64; + p: F32; q: F64; r: F32; s: F64; t: F32; u: F64; v: F32; w: F64; + y: F32; z: F64; last: I8): I64; +extern proc varsum(n: I32; ...): I64; +extern proc callback(cb: proc(a, b, c, d, e, f, g, h, i, j: I64): I64): I64; + +(* the same hash as C's mix *) +proc mix(h, v: I64): I64; +begin + return I64(U64(h) * 1000003 + U64(v)); +end; + +proc mine(a, b, c, d, e, f, g, h, i, j: I64): I64; +var x: I64; +begin + x := 7; + x := mix(x, a); x := mix(x, b); x := mix(x, c); x := mix(x, d); x := mix(x, e); + x := mix(x, f); x := mix(x, g); x := mix(x, h); x := mix(x, i); x := mix(x, j); + return x; +end; + +proc main*; +begin + Out.int(narrow(-1, 200, -300, -70000, -5000000000, 255, -32768, 2147483647, + -128, 129, -2, -100000, 127, 9000000000, + 1.5, -2.25, 3.5, 4.75, -5.5, 6.25, 7.5, -8.75, + 9.5, 10.25, -100)); Out.ln; + Out.int(varsum(5, 1, 1.5, -3, -2.25, 5)); Out.ln; + Out.int(callback(mine)); Out.ln; + Out.flush; +end; + +end NarrowArgs.