diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 08085cc..5c74b9a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -202,3 +202,102 @@ jobs: ./scripts/install.ps1 & "$env:TRACK_INSTALL_DIR\trackc.exe" --version & "$env:TRACK_INSTALL_DIR\yard.exe" --version + + windows-arm-cross: + # Cross-build the aarch64-windows executables on Linux: trackc.exe, + # hello and every example (docs/native.md, "PE32+ layout"); the + # windows-arm job runs them on Windows on ARM. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Bootstrap trackc + run: scripts/bootstrap.sh + + - name: Cross-build for aarch64-windows and parse the images + run: | + tc=build/bootstrap/stage3/trackc + d=build/winarm + mkdir -p "$d/examples" + "$tc" build --target aarch64-windows compiler/src/main.trk -o "$d/trackc.exe" + for f in examples/*.trk; do + s=$(basename "$f" .trk) + case "$s" in *_err) continue ;; esac + "$tc" build --target aarch64-windows "$f" -o "$d/examples/$s.exe" + done + if command -v llvm-readobj >/dev/null; then + for x in "$d/trackc.exe" "$d"/examples/*.exe; do + llvm-readobj --file-headers --coff-imports "$x" | grep -q 'IMAGE_FILE_MACHINE_ARM64' + done + fi + + - uses: actions/upload-artifact@v4 + with: + name: winarm-binaries + path: build/winarm + if-no-files-found: error + + windows-arm: + # [untested here] Runs the cross-built binaries on GitHub's Windows on + # ARM runner: the examples against their goldens, then trackc.exe + # rebuilds hello on the device and must produce the same bytes as the + # Linux trackc did; last, the Arm64 trackc.exe runs the windows suite + # (its default target there is aarch64-windows). + needs: windows-arm-cross + runs-on: windows-11-arm + defaults: + run: + shell: pwsh + steps: + - uses: actions/checkout@v4 + + - uses: actions/download-artifact@v4 + with: + name: winarm-binaries + path: build/winarm + + - name: Show the machine + run: | + $env:PROCESSOR_ARCHITECTURE + [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture + + - name: Examples print their goldens + run: | + $d = Resolve-Path build/winarm + $fails = 0 + foreach ($f in Get-ChildItem examples -Filter '*.trk' | Sort-Object Name) { + $s = $f.BaseName + if ($s.EndsWith('_err')) { continue } + $exe = Join-Path $d "examples\$s.exe" + $out = Join-Path $d "examples\$s.out" + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $exe + $psi.WorkingDirectory = (Resolve-Path examples).Path + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $p = [System.Diagnostics.Process]::Start($psi) + $fs = [System.IO.File]::Create($out) + try { $p.StandardOutput.BaseStream.CopyTo($fs) } finally { $fs.Close() } + $p.WaitForExit() + $want = ([System.IO.File]::ReadAllText("tests/cases/examples/$s.out")).Replace('@HOSTNAME_BYTES@', '0') + $got = [System.IO.File]::ReadAllText($out) + $code = [int]([System.IO.File]::ReadAllText("tests/cases/examples/$s.code").Trim()) + if ($got -eq $want -and $p.ExitCode -eq $code) { Write-Host "ok $s" } + else { Write-Host "FAIL $s (exit $($p.ExitCode), want $code)"; $fails++ } + } + if ($fails -ne 0) { exit 1 } + + - name: trackc.exe builds hello on the device, byte-identical to the cross build + run: | + New-Item -ItemType Directory -Force -Path build/ondevice | Out-Null + & build/winarm/trackc.exe build --target aarch64-windows examples/hello.trk -o build/ondevice/hello.exe + if ($LASTEXITCODE -ne 0) { exit 1 } + $a = Get-FileHash build/ondevice/hello.exe + $b = Get-FileHash build/winarm/examples/hello.exe + if ($a.Hash -ne $b.Hash) { Write-Host "hello.exe differs from the cross build"; exit 1 } + & build/ondevice/hello.exe + & build/winarm/trackc.exe check examples/stdlib_demo.trk + if ($LASTEXITCODE -ne 0) { exit 1 } + + - name: The Arm64 trackc.exe passes the windows suite natively + run: ./tests/windows/run.ps1 build/winarm/trackc.exe diff --git a/README.md b/README.md index 927d757..e5ee2c9 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,16 @@ - **Lexical Lenses.** Scoped mutable access without manual pointer arithmetic or ownership transfer. - **Native Backend.** `trackc build` writes a static x86-64 Linux executable itself, with no C compiler, assembler or linker. - **Track only.** The repository holds no C or Rust. Track bootstraps from a committed native seed binary. -- **Cross-compiling.** `trackc build --target x86_64-windows` writes a Windows PE executable from any host; `--target x86_64-macos` / `aarch64-macos` a signed Mach-O. - -| target | `trackc build --target` | status | -|---|---|---| -| x86_64-linux | default on Linux | static ELF | -| x86_64-windows | `x86_64-windows` | PE32+ console .exe (kernel32); trackc.exe self-hosts | -| aarch64-linux | `aarch64-linux` | static ELF (A64 lifted from the x86-64 code) | -| x86_64-macos | `x86_64-macos` (default on a Mac) | Mach-O, libSystem, ad-hoc signed | -| aarch64-macos | `aarch64-macos` | Mach-O for Apple silicon, ad-hoc signed | -| aarch64-windows | | not yet | +- **Cross-compiling.** `trackc build --target -` writes any of six targets from any host: a Windows PE (x86_64 or Windows on ARM), a static Linux ELF, or a signed Mach-O. + +| target | `trackc build --target` | output | tested | +|---|---|---|---| +| x86_64-linux | default on Linux | static ELF | native (tests/run.sh) | +| x86_64-windows | default on x64 Windows | PE32+ console .exe (kernel32); trackc.exe self-hosts | wine locally; native in CI (`windows`) | +| aarch64-linux | `aarch64-linux` | static ELF (A64 lifted from the x86-64 code) | qemu-aarch64 locally | +| x86_64-macos | default on a Mac | Mach-O, libSystem, ad-hoc signed | structure offline; runs in CI only (`macos`, Intel) | +| aarch64-macos | `aarch64-macos` | Mach-O for Apple silicon, ad-hoc signed | structure offline; runs in CI only (`macos`, Apple silicon) | +| aarch64-windows | default on Windows on ARM | ARM64 PE32+ console .exe (kernel32) | llvm-readobj/objdump offline; runs in CI only (`windows-arm`) | ## Hello World diff --git a/bootstrap/seed/trackc b/bootstrap/seed/trackc index 68fb5e7..5be2933 100755 Binary files a/bootstrap/seed/trackc and b/bootstrap/seed/trackc differ diff --git a/bootstrap/seed/trackc.exe b/bootstrap/seed/trackc.exe index 28eb84e..6f1a4a3 100755 Binary files a/bootstrap/seed/trackc.exe and b/bootstrap/seed/trackc.exe differ diff --git a/compiler/src/main.trk b/compiler/src/main.trk index 4141a3b..bf56e59 100644 --- a/compiler/src/main.trk +++ b/compiler/src/main.trk @@ -47,7 +47,7 @@ fn usage() -> i64 { err("\nOPTIONS:\n"); err(" --deny-warnings exit 1 when any warning is reported\n"); err(" --target - build/run/check for x86_64|aarch64 - linux|macos|windows\n"); - err(" (also TRACKC_TARGET; default: the host; built today: x86_64-linux/macos/windows, aarch64-linux/macos)\n"); + err(" (also TRACKC_TARGET; default: the host; every pair builds)\n"); return 0; } @@ -130,6 +130,11 @@ const TG_MACOS = 2; // The host's target: Windows or macOS when trackc itself runs there. fn host_target() -> i64 { if text_eq(env_get("OS"), "Windows_NT") { + // an Arm64 trackc.exe sees ARM64; an x64 one, also under Windows + // on ARM's emulation, sees AMD64 + if text_eq(env_get("PROCESSOR_ARCHITECTURE"), "ARM64") { + return "aarch64-windows"; + } return "x86_64-windows"; } let me = arg_text(0); @@ -219,21 +224,10 @@ fn check_target_known() -> i64 { return 0; } -// Exit unless this trackc can generate code for the target. +// Exit unless this trackc can generate code for the target: every known +// arch-OS pair builds. fn check_target_buildable() -> i64 { - check_target_known(); - let arch = target_arch_name(); - let os = target_os_name(); - if text_eq(arch, "x86_64") && (text_eq(os, "linux") || text_eq(os, "windows") || text_eq(os, "macos")) { - return 0; - } - if text_eq(arch, "aarch64") && (text_eq(os, "linux") || text_eq(os, "macos")) { - return 0; - } - err(text_cat3("trackc: target '", target_text(), "' is not supported yet\n")); - err(" supported: x86_64-linux, x86_64-windows, x86_64-macos, aarch64-linux, aarch64-macos\n"); - quit(2); - return 0; + return check_target_known(); } fn front_end(path: i64) -> i64 { @@ -295,7 +289,7 @@ fn make_dir(dir: i64) -> i64 { if path_exists(dir) { return 0; } - if text_eq(host_target(), "x86_64-windows") { + if text_ends(host_target(), "-windows") { // cmd.exe: mkdir makes the parents too; it wants backslashes let sb = sb_new(); let bytes = text_bytes(dir); @@ -360,7 +354,21 @@ fn build_native(path: i64, exe: i64) -> i64 { quit(1); } if os == TG_WINDOWS { - if pe_write_file(exe, body, native_code_len(c), native_imports(c), native_import_fixups(c)) != 0 { + let mut wcode = native_code_len(c); + let mut wfix = native_import_fixups(c); + let arm = text_eq(target_arch_name(), "aarch64"); + if arm { + // lift to A64; Win64 import calls become Windows ARM64 calls + let wlen = vfill(vnew(), 1, 0); + let afix = vnew(); + body = a64_translate_os(body, wcode, wlen, TG_WINDOWS, wfix, afix); + if body == 0 { + quit(1); + } + wcode = vget(wlen, 0); + wfix = afix; + } + if pe_write_file_m(exe, body, wcode, native_imports(c), wfix, arm) != 0 { err(text_cat3("trackc: cannot write '", exe, "'\n")); quit(1); } diff --git a/compiler/src/ngen.trk b/compiler/src/ngen.trk index 8990ef3..2244f8d 100644 --- a/compiler/src/ngen.trk +++ b/compiler/src/ngen.trk @@ -5920,7 +5920,7 @@ fn ng_extern_of(c: i64, name: i64) -> i64 { fn ng_extern_call(c: i64, e: i64, args: i64, count: i64) -> i64 { let b = ncode(c); if ng(c, NG_TARGET) != 1 && ng(c, NG_TARGET) != 2 { - err(text_cat3("trackc: native: imported function '", name_text(c, na(c, e)), "' needs --target x86_64-windows or x86_64-macos (this target has no import support yet)\n")); + err(text_cat3("trackc: native: imported function '", name_text(c, na(c, e)), "' needs a windows or macos --target (x86_64 or aarch64; Linux output imports nothing)\n")); quit(1); } let mut i: i64 = 0; diff --git a/compiler/src/ngen_a64.trk b/compiler/src/ngen_a64.trk index f3c2d80..cb625ca 100644 --- a/compiler/src/ngen_a64.trk +++ b/compiler/src/ngen_a64.trk @@ -39,6 +39,9 @@ // macOS layer makes no system calls: ngen lowers syscall6 to os_syscall), // passes LC_MAIN's x0/x1 in as rdi/rsi, places the code at the Mach-O // __text address and pads it to 16 KiB so __DATA starts on a page. +// Windows (os 1, pe.trk) takes the Win64 sequence (ffi_win64_call) to a +// Windows ARM64 call (ax_import_call_win), also traps in the stub, and +// places the code at the PE .text address, padded to 4 KiB for .data. import "base"; import "x64"; @@ -74,7 +77,7 @@ const AT_LIVE = 7; // flags of the current instruction are read later const AT_AR = 8; // mem_addr result: base register const AT_AO = 9; // mem_addr result: offset const AT_POS = 10; // x86 offset of the current instruction -const AT_OS = 11; // target OS (NG_TARGET): 0 linux, 2 macos +const AT_OS = 11; // target OS (NG_TARGET): 0 linux, 1 windows, 2 macos const AT_IMPIN = 12; // x86 import call fixups (code position, import id), ffi.trk const AT_IMPOUT = 13; // A64 import call fixups (word of the adrp, import id) const AT_SLOTS = 14; @@ -751,6 +754,9 @@ fn ax_import_call(t: i64, d: i64) -> bool { if id < 0 { return a64_fail(t, "indirect call that is not an import call"); } + if ax_tg(t, AT_OS) == 1 { + return ax_import_call_win(t, id); + } a_mov(w, 1, 3, 1); a_mov(w, 1, 0, 21); a_mov(w, 1, 1, 20); @@ -775,6 +781,46 @@ fn ax_import_call(t: i64, d: i64) -> bool { return true; } +// The Windows variant (aarch64-windows): ngen emitted ffi_win64_call, so +// arguments 1-4 are in rcx, rdx, r8, r9 (x1, x2, x22, x23) and 5-10 at +// [rsp + 32 + 8k], above the 32-byte shadow space. The Windows ARM64 ABI +// is AAPCS64 with no shadow space: rcx -> x0, rdx -> x1, r8 -> x2, +// r9 -> x3, Win64 stack words 0-3 -> x4..x7, words 4 and 5 (arguments 9 +// and 10, CreateProcessW) -> [sp], [sp + 8]. SP goes 16-aligned below the +// emulated stack; x9 and x10 are kept at [sp + 16], [sp + 24]. x18 (the +// TEB) is never touched: the translator maps no x86 register to it and +// uses only x13..x17 as scratch. Calls of up to ten word arguments. +fn ax_import_call_win(t: i64, id: i64) -> bool { + let w = ax_tw(t); + a_mov(w, 1, 0, 1); + a_mov(w, 1, 1, 2); + a_mov(w, 1, 2, 22); + a_mov(w, 1, 3, 23); + a_ldr(w, 4, 28, 32); + a_ldr(w, 5, 28, 40); + a_ldr(w, 6, 28, 48); + a_ldr(w, 7, 28, 56); + a_ldr(w, 14, 28, 64); + a_ldr(w, AX17, 28, 72); + a_subi(w, 1, AX16, 28, 32); + a_lsr_i(w, 1, AX16, AX16, 4); + a_lsl_i(w, 1, AX16, AX16, 4); + a_mov_sp(w, A_SP, AX16); + a_mem(w, 3, 0, 14, A_SP, 0); + a_mem(w, 3, 0, AX17, A_SP, 8); + a_mem(w, 3, 0, 9, A_SP, 16); + a_mem(w, 3, 0, 10, A_SP, 24); + let adrp = a_adrp(w, AX16, 0); + a_ldr(w, AX16, AX16, 0); + a_blr(w, AX16); + a_ldr(w, 9, A_SP, 16); + a_ldr(w, 10, A_SP, 24); + let out = ax_tg(t, AT_IMPOUT); + vpush(out, adrp); + vpush(out, id); + return true; +} + fn a64_insn(t: i64, d: i64) -> bool { let w = ax_tw(t); let op = ax_dg(d, AD_OP); @@ -1182,6 +1228,10 @@ fn a64_translate(body: i64, n: i64, out: i64) -> i64 { // The macOS image's __text address (macho.trk MO_BASE + MO_TEXT_OFF). const AX_MACHO_TEXT = 4294983680; +// The Windows image's .text address (pe.trk PE_BASE + PE_TEXT_RVA). The +// loader may move the image (ARM64 images are always DYNAMIC_BASE), but by +// 64 KiB steps, so adrp page distances hold. +const AX_PE_TEXT = 5368713216; // a64_translate for target OS `os`; `impin` holds the x86 import call // fixups (0: none), `impout` receives the A64 ones. @@ -1230,6 +1280,10 @@ fn a64_translate_os(body: i64, n: i64, out: i64, os: i64, impin: i64, impout: i6 a_brk(w, 1); // no system calls on macOS origin = AX_MACHO_TEXT; align = 4096; // words: 16 KiB, the __DATA page + } else if os == 1 { + a_brk(w, 1); // nor on Windows (kernel32 through os_syscall) + origin = AX_PE_TEXT; + align = 1024; // words: 4 KiB, the .data page } else { a64_sys_stub(w); } diff --git a/compiler/src/pe.trk b/compiler/src/pe.trk index 093c086..2200adb 100644 --- a/compiler/src/pe.trk +++ b/compiler/src/pe.trk @@ -1,4 +1,4 @@ -// pe.trk — PE32+ console executable writer (x86_64-windows). +// pe.trk — PE32+ console executable writer (x86_64-windows, aarch64-windows). // // Layout (SectionAlignment 0x1000, FileAlignment 0x200, ImageBase // 0x140000000, no relocations: the image loads at its base): @@ -80,7 +80,7 @@ fn pe_cstr(b: i64, s: i64) -> i64 { // The .idata contents at `rva`; fills `slots` (import id -> IAT slot RVA) // and `dirs` with [import dir RVA, size, IAT RVA, size]. -fn pe_idata(imports: i64, rva: i64, slots: i64, dirs: i64) -> i64 { +fn pe_idata(imports: i64, rva: i64, slots: i64, dirs: i64, arm: bool) -> i64 { let n = vlen(imports) / 2; let libs = vnew(); let mut i: i64 = 0; @@ -115,7 +115,10 @@ fn pe_idata(imports: i64, rva: i64, slots: i64, dirs: i64) -> i64 { l = l + 1; } let desc_size = 20 * (nlib + 1); - let ilt = rva + desc_size; + let mut ilt = rva + desc_size; + if arm { + ilt = rva + pe_up(desc_size, 8); // ldr's scaled offset: 8-aligned slots + } let iat = ilt + 8 * vlen(order); let names_at = iat + 8 * vlen(order); // hint/name entries, then library names @@ -159,6 +162,7 @@ fn pe_idata(imports: i64, rva: i64, slots: i64, dirs: i64) -> i64 { vpush(b, 0); z = z + 1; } + pe_pad(b, ilt - rva); // lookup table, then the IAT (same contents until the loader binds it) let mut pass: i64 = 0; while pass < 2 { @@ -189,30 +193,84 @@ fn pe_idata(imports: i64, rva: i64, slots: i64, dirs: i64) -> i64 { return b; } +fn pe_get32(b: i64, at: i64) -> i64 { + return vget(b, at) + vget(b, at + 1) * 256 + vget(b, at + 2) * 65536 + vget(b, at + 3) * 16777216; +} + +// Patch the adrp + ldr pairs of aarch64 import calls (fixups: (word of +// the adrp, import id)) to load the import's IAT slot. +fn pe_patch_a64(body: i64, fixups: i64, slots: i64) -> i64 { + let mut f: i64 = 0; + while f < vlen(fixups) { + let at = 4 * vget(fixups, f); + let pc = PE_TEXT_RVA + at; + let slot = vget(slots, vget(fixups, f + 1)); + let pages = (slot >> 12) - (pc >> 12); + let adrp = pe_get32(body, at); + x_patch32(body, at, (adrp & 2667577375) + (pages & 3) * 536870912 + ((pages >> 2) & 524287) * 32); + let ldr = pe_get32(body, at + 4); + x_patch32(body, at + 4, (ldr & 4290774015) + ((slot & 4095) / 8) * 1024); + f = f + 2; + } + return 0; +} + // The whole PE image of code+data `body` (the first `code` bytes code, -// page-aligned) calling `imports` from the sites `fixups`. +// page-aligned) calling `imports` from the sites `fixups` (x86_64). fn pe_image(body: i64, code: i64, imports: i64, fixups: i64) -> i64 { + return pe_image_m(body, code, imports, fixups, false); +} + +// pe_image for x86_64 (`arm` false: AMD64, fixups are rip displacements) +// or aarch64 (`arm`: ARM64, fixups are adrp + ldr pairs). The ARM64 image +// is DYNAMIC_BASE (Windows on ARM requires it) with a .reloc section whose +// one block fixes nothing: the A64 code and data are position independent +// (adrp/add), and the loader moves images by 64 KiB, which keeps adrp's +// 4 KiB page distances. No load config and no .pdata: neither is needed to +// load or run (functions without unwind data count as leaf functions, and +// nothing here raises or unwinds an exception). +fn pe_image_m(body: i64, code: i64, imports: i64, fixups: i64, arm: bool) -> i64 { let mut dsize = vlen(body) - code; if dsize < 8 { dsize = 8; } + let mut hdrs = PE_HEADERS; + let mut nsec: i64 = 3; + if arm { + hdrs = 2 * PE_HEADERS; // a fourth section header + nsec = 4; + } let data_rva = PE_TEXT_RVA + pe_up(code, PE_SALIGN); let idata_rva = data_rva + pe_up(dsize, PE_SALIGN); let slots = vfill(vnew(), vlen(imports) / 2, 0); let dirs = vfill(vnew(), 4, 0); - let idata = pe_idata(imports, idata_rva, slots, dirs); - let image_size = idata_rva + pe_up(vlen(idata), PE_SALIGN); + let idata = pe_idata(imports, idata_rva, slots, dirs, arm); + let reloc_rva = idata_rva + pe_up(vlen(idata), PE_SALIGN); + let mut image_size = reloc_rva; + let reloc = vnew(); + if arm { + // one base relocation block, two IMAGE_REL_BASED_ABSOLUTE (padding) + x_u32(reloc, PE_TEXT_RVA); + x_u32(reloc, 12); + x_u32(reloc, 0); + image_size = reloc_rva + PE_SALIGN; + } // bind the call sites to their IAT slots - let mut f: i64 = 0; - while f < vlen(fixups) { - let at = vget(fixups, f); - x_patch32(body, at, vget(slots, vget(fixups, f + 1)) - (PE_TEXT_RVA + at + 4)); - f = f + 2; + if arm { + pe_patch_a64(body, fixups, slots); + } else { + let mut f: i64 = 0; + while f < vlen(fixups) { + let at = vget(fixups, f); + x_patch32(body, at, vget(slots, vget(fixups, f + 1)) - (PE_TEXT_RVA + at + 4)); + f = f + 2; + } } let text_raw = pe_up(code, PE_FALIGN); let data_raw = pe_up(dsize, PE_FALIGN); let idata_raw = pe_up(vlen(idata), PE_FALIGN); - let b = vnew_cap(PE_HEADERS + text_raw + data_raw + idata_raw); + let reloc_raw = pe_up(vlen(reloc), PE_FALIGN); + let b = vnew_cap(hdrs + text_raw + data_raw + idata_raw + reloc_raw); // DOS header: "MZ", e_lfanew = 0x80; a stub that prints and exits pe_u16(b, 23117); pe_pad(b, 60); @@ -232,13 +290,21 @@ fn pe_image(body: i64, code: i64, imports: i64, fixups: i64) -> i64 { pe_pad(b, 128); // PE signature and COFF header x_u32(b, 17744); // "PE\0\0" - pe_u16(b, 34404); // IMAGE_FILE_MACHINE_AMD64 - pe_u16(b, 3); // sections + if arm { + pe_u16(b, 43620); // IMAGE_FILE_MACHINE_ARM64 (0xaa64) + } else { + pe_u16(b, 34404); // IMAGE_FILE_MACHINE_AMD64 + } + pe_u16(b, nsec); // sections x_u32(b, 0); x_u32(b, 0); x_u32(b, 0); pe_u16(b, 240); // optional header size - pe_u16(b, 35); // RELOCS_STRIPPED | EXECUTABLE | LARGE_ADDRESS_AWARE + if arm { + pe_u16(b, 34); // EXECUTABLE | LARGE_ADDRESS_AWARE + } else { + pe_u16(b, 35); // RELOCS_STRIPPED | EXECUTABLE | LARGE_ADDRESS_AWARE + } // PE32+ optional header pe_u16(b, 523); // 0x20b x_byte(b, 1); @@ -259,10 +325,14 @@ fn pe_image(body: i64, code: i64, imports: i64, fixups: i64) -> i64 { pe_u16(b, 0); // subsystem version x_u32(b, 0); x_u32(b, image_size); - x_u32(b, PE_HEADERS); + x_u32(b, hdrs); x_u32(b, 0); // checksum pe_u16(b, 3); // IMAGE_SUBSYSTEM_WINDOWS_CUI - pe_u16(b, 33024); // NX_COMPAT | TERMINAL_SERVER_AWARE + if arm { + pe_u16(b, 33120); // + HIGH_ENTROPY_VA | DYNAMIC_BASE + } else { + pe_u16(b, 33024); // NX_COMPAT | TERMINAL_SERVER_AWARE + } x_u64(b, 268435456); // stack reserve 256 MiB (trackc recurses deeply) x_u64(b, 16777216); // stack commit 16 MiB (frames skip guard pages) x_u64(b, 1048576); @@ -274,6 +344,9 @@ fn pe_image(body: i64, code: i64, imports: i64, fixups: i64) -> i64 { if dd == 1 { x_u32(b, vget(dirs, 0)); x_u32(b, vget(dirs, 1)); + } else if dd == 5 && arm { + x_u32(b, reloc_rva); + x_u32(b, vlen(reloc)); } else if dd == 12 { x_u32(b, vget(dirs, 2)); x_u32(b, vget(dirs, 3)); @@ -282,34 +355,48 @@ fn pe_image(body: i64, code: i64, imports: i64, fixups: i64) -> i64 { } dd = dd + 1; } - pe_section(b, ".text", code, PE_TEXT_RVA, text_raw, PE_HEADERS, 1610612768); - pe_section(b, ".data", dsize, data_rva, data_raw, PE_HEADERS + text_raw, 3221225536); - pe_section(b, ".idata", vlen(idata), idata_rva, idata_raw, PE_HEADERS + text_raw + data_raw, 3221225536); - pe_pad(b, PE_HEADERS); + pe_section(b, ".text", code, PE_TEXT_RVA, text_raw, hdrs, 1610612768); + pe_section(b, ".data", dsize, data_rva, data_raw, hdrs + text_raw, 3221225536); + pe_section(b, ".idata", vlen(idata), idata_rva, idata_raw, hdrs + text_raw + data_raw, 3221225536); + if arm { + // INITIALIZED_DATA | DISCARDABLE | MEM_READ + pe_section(b, ".reloc", vlen(reloc), reloc_rva, reloc_raw, hdrs + text_raw + data_raw + idata_raw, 1107296320); + } + pe_pad(b, hdrs); let mut i: i64 = 0; while i < code { vpush(b, vget(body, i)); i = i + 1; } - pe_pad(b, PE_HEADERS + text_raw); + pe_pad(b, hdrs + text_raw); while i < vlen(body) { vpush(b, vget(body, i)); i = i + 1; } - pe_pad(b, PE_HEADERS + text_raw + data_raw); + pe_pad(b, hdrs + text_raw + data_raw); let mut k: i64 = 0; while k < vlen(idata) { vpush(b, vget(idata, k)); k = k + 1; } - pe_pad(b, PE_HEADERS + text_raw + data_raw + idata_raw); + pe_pad(b, hdrs + text_raw + data_raw + idata_raw); + let mut r: i64 = 0; + while r < vlen(reloc) { + vpush(b, vget(reloc, r)); + r = r + 1; + } + pe_pad(b, hdrs + text_raw + data_raw + idata_raw + reloc_raw); return b; } // Write the PE image to `path` (mode 0755 where that means anything). // Returns 0 on success. fn pe_write_file(path: i64, body: i64, code: i64, imports: i64, fixups: i64) -> i64 { - let img = pe_image(body, code, imports, fixups); + return pe_write_file_m(path, body, code, imports, fixups, false); +} + +fn pe_write_file_m(path: i64, body: i64, code: i64, imports: i64, fixups: i64, arm: bool) -> i64 { + let img = pe_image_m(body, code, imports, fixups, arm); let n = vlen(img); let buf: i64 = alloc(n + 8); let mut i: i64 = 0; diff --git a/docs/native.md b/docs/native.md index 5ab1bbe..6b19d40 100644 --- a/docs/native.md +++ b/docs/native.md @@ -2,8 +2,8 @@ `trackc` compiles `compiler/src/*.trk` straight to a native executable, with no C compiler and no C source in the chain: a static ELF for -x86_64-linux, a PE32+ console executable for x86_64-windows (see -"Targets"). Two halves: +x86_64-linux, a PE32+ console executable for x86_64-windows and +aarch64-windows, a Mach-O for macOS (see "Targets"). Two halves: - **the runtime written in Track** (`compiler/rt/*.trk`), which needs no libc; @@ -23,17 +23,20 @@ reachable (docs/bootstrap.md). The C backend and the C runtime pair is an error (exit 2). `check` accepts every known pair; `build` generates code for: -| target | output | status | +| target | output | tested | |---|---|---| -| x86_64-linux | static ELF, Linux syscalls | default; output byte-identical to earlier trackc | -| x86_64-windows | PE32+ console .exe, kernel32 imports | builds and runs (tested under wine); trackc.exe self-hosts | -| aarch64-linux | static ELF, A64 lifted from ngen's x86-64 (ngen_a64.trk) | builds and runs (tested under qemu) | -| x86_64-macos | Mach-O MH_EXECUTE, libSystem imports, ad-hoc signature | builds; structure and signature checked offline, runs in CI on an Intel Mac [CI only] | -| aarch64-macos | the same Mach-O for arm64, A64 lifted as for aarch64-linux | builds; checked offline, runs in CI on Apple silicon [CI only] | -| aarch64-windows | | "not supported yet" | +| x86_64-linux | static ELF, Linux syscalls | native: the default; output byte-identical to earlier trackc | +| x86_64-windows | PE32+ console .exe, kernel32 imports | wine locally (tests/sh/xplat.sh), native in CI (`windows`); trackc.exe self-hosts | +| aarch64-linux | static ELF, A64 lifted from ngen's x86-64 (ngen_a64.trk) | qemu-aarch64 locally (tests/sh/arm64.sh) | +| x86_64-macos | Mach-O MH_EXECUTE, libSystem imports, ad-hoc signature | structure and signature offline (tests/sh/macos.sh); runs in CI only, Intel Mac (`macos`) | +| aarch64-macos | the same Mach-O for arm64, A64 lifted as for aarch64-linux | the same offline checks; runs in CI only, Apple silicon (`macos`) | +| aarch64-windows | ARM64 PE32+ console .exe, A64 lifted, kernel32 imports | llvm-readobj / llvm-objdump offline (tests/sh/winarm.sh); runs in CI only, `windows-11-arm` (`windows-arm`). wine on x86-64 cannot load an ARM64 PE | On a Mac the default target is x86_64-macos (arm64 Macs run it under -Rosetta 2); pass `--target aarch64-macos` for native code. +Rosetta 2); pass `--target aarch64-macos` for native code. On Windows the +default follows the running trackc.exe: an Arm64 one sees +`PROCESSOR_ARCHITECTURE=ARM64` and defaults to aarch64-windows, an x64 one +(also under Windows on ARM's emulation) to x86_64-windows. `run` only runs host-target programs. The target picks the OS layer: trackc loads `rt/os/.trk` with the portable rt modules and passes @@ -91,8 +94,16 @@ x0-x5 from the System V registers, x6/x7 from the first two stack words, adrp + ldr of the slot, blr); variadic arguments, which Apple's arm64 ABI puts on the stack, are not supported, so the macOS layer calls no variadic function with variadic arguments (open(2) without a mode, -creat(2) to create). aarch64-windows reuses the tables and the -translator hook with its own call sequence. On a target without import +creat(2) to create). For aarch64-windows ngen emits the Win64 sequence +and the translator turns it into a Windows ARM64 call +(`ax_import_call_win`): that ABI is AAPCS64 with no shadow space, so rcx, +rdx, r8, r9 become x0-x3, the Win64 stack words above the shadow space +become x4-x7, and words 5 and 6 (arguments 9 and 10, CreateProcessW) go +to [sp], [sp + 8]; SP is 16-aligned below the emulated stack; calls take +up to ten word arguments. x18 holds the TEB on Windows ARM64 and must not +change: the translator maps no x86 register to it and its scratch +registers are x13-x17 (tests/sh/winarm.sh checks trackc.exe's code never +names x18). On a target without import support a call to an `extern` function is an error. `as "symbol"` after the signature names the library's symbol when the @@ -168,6 +179,32 @@ a file with open handles stays visible until they close (wine, FAT). `sys_exec` runs `cmd.exe /s /c "cmd"`. trackc treats `\` as a path separator too. +**ARM64 (aarch64-windows).** The same layout with machine +IMAGE_FILE_MACHINE_ARM64 (0xAA64), plain PE32+ (no CHPE, ARM64EC or +ARM64X), SectionAlignment 4 KiB (the Windows ARM64 page), the entry at +the first byte of `.text`, and a fourth section, `.reloc`. Windows on ARM +only loads ASLR images (link.exe and lld refuse `/DYNAMICBASE:NO` for +ARM64), so the image is DYNAMIC_BASE | HIGH_ENTROPY_VA, relocations not +stripped, and the base relocation directory holds one block of two +IMAGE_REL_BASED_ABSOLUTE (padding) entries: nothing needs fixing, since +the A64 code reaches data and the IAT with adrp + add/ldr and the loader +moves images by 64 KiB, which keeps adrp's 4 KiB page distances. Import +calls are adrp + ldr x16 of the IAT slot, then blr x16 (`pe_patch_a64`); +the import lookup table is 8-aligned for ldr's scaled offset. The +translator pads the code to 4 KiB so `.data` follows it at the address +the adrp pairs assume, and the system call stub is a `brk` (ngen sends +`syscall6` to `os_syscall`). + +Neither a load config directory nor exception data (`.pdata`/`.xdata`) +is emitted: neither is required to load or run. The load config only +carries opt-in features (CFG, SEH tables are x86-only, CHPE metadata); +without `.pdata` every function counts as a leaf for unwinding, which +matters only when an exception is dispatched through Track frames, and +the runtime raises none (`track_trap_div` calls ExitProcess). A fault +in Track code therefore ends the process without a usable stack trace. +[reported: from the PE/COFF spec and the ARM64 exception-handling +docs; not observed on hardware until the `windows-arm` CI job runs] + ## Machine builtins Registered in `checker.trk` (`register_builtins`) and lowered inline by diff --git a/tests/sh/ids.txt b/tests/sh/ids.txt index cd896d9..d8ce19e 100644 --- a/tests/sh/ids.txt +++ b/tests/sh/ids.txt @@ -1,3 +1,7 @@ +arm64/arm64_hello_runs_under_qemu +arm64/arm64_programs_print_their_goldens +arm64/arm64_compiler_reaches_a_fixed_point_under_qemu +arm64/arm64_target_does_not_change_x86_64_output cli/cli_help cli/cli_check_command cli/cli_invalid_command @@ -53,6 +57,12 @@ lifecycle/runtime_layout_consts_stay_reserved lifecycle/duplicate_functions_are_rejected lifecycle/string_plus_string_is_a_type_error lifecycle/for_in_exit_and_div_trap_keep_output +macos/macos_hello_is_a_signed_macho +macos/macos_examples_and_trackc_pass_the_checker +macos/macos_objdump_parses_headers_binds_and_code +macos/macos_checker_catches_a_changed_page +macos/macos_build_is_deterministic +macos/macos_extern_binds_the_as_symbol native/native_build_needs_no_c_toolchain native/native_programs_print_their_goldens native/native_compiler_reaches_a_fixed_point @@ -92,8 +102,13 @@ tools/nvim_headless_filetype_and_syntax tools/nvim_headless_lua_syntax_ok tools/nvim_devicon_svg_not_needed_headless tools/nvim_syntax_highlight_sample_headless +winarm/winarm_hello_is_an_arm64_pe +winarm/winarm_examples_and_trackc_parse +winarm/winarm_import_calls_load_iat_slots +winarm/winarm_never_touches_x18 +winarm/winarm_build_is_deterministic xplat/xplat_unknown_target_is_a_clear_error -xplat/xplat_unsupported_target_says_so +xplat/xplat_every_known_target_builds xplat/xplat_linux_target_is_the_default_output xplat/xplat_windows_build_is_a_pe32plus_image xplat/xplat_extern_needs_an_import_target @@ -103,13 +118,3 @@ xplat/xplat_windows_examples_print_their_goldens xplat/xplat_windows_trackc_builds_hello xplat/xplat_windows_rt_smoke_under_wine xplat/xplat_windows_divzero_is_status_integer_divide_by_zero -arm64/arm64_hello_runs_under_qemu -arm64/arm64_programs_print_their_goldens -arm64/arm64_compiler_reaches_a_fixed_point_under_qemu -arm64/arm64_target_does_not_change_x86_64_output -macos/macos_hello_is_a_signed_macho -macos/macos_examples_and_trackc_pass_the_checker -macos/macos_objdump_parses_headers_binds_and_code -macos/macos_checker_catches_a_changed_page -macos/macos_build_is_deterministic -macos/macos_extern_binds_the_as_symbol diff --git a/tests/sh/winarm.sh b/tests/sh/winarm.sh new file mode 100644 index 0000000..bcc3eb7 --- /dev/null +++ b/tests/sh/winarm.sh @@ -0,0 +1,109 @@ +# Windows on ARM (`--target aarch64-windows`, compiler/src/pe.trk with +# arm, ngen_a64.trk ax_import_call_win; docs/native.md "PE32+ layout"): +# structural checks only. Nothing here runs ARM64 Windows code: wine on an +# x86-64 host cannot load an ARM64 PE (CI's windows-arm job runs it). +# llvm-readobj and llvm-objdump must parse every image without a +# complaint. Commands run from the repository root. + +need_llvm() { + have llvm-readobj || skip "llvm-readobj not found" + have llvm-objdump || skip "llvm-objdump not found" +} + +t_winarm_hello_is_an_arm64_pe() { + need_llvm + in_repo "$TRACKC" build --target aarch64-windows examples/hello.trk -o "$T/hello.exe" + rc_ok "build" + eq "$(od -An -c -N 2 "$T/hello.exe" | tr -d ' ')" "MZ" "DOS magic" + eq "$(od -An -tx1 -j 132 -N 2 "$T/hello.exe" | tr -d ' ')" "64aa" "COFF machine ARM64" + cap llvm-readobj --file-headers --sections --coff-imports --coff-basereloc "$T/hello.exe" + rc_ok "llvm-readobj" + eq "$ERR" "" "llvm-readobj stderr" + has "$OUT" "Format: COFF-ARM64" "format" + has "$OUT" "IMAGE_FILE_MACHINE_ARM64 (0xAA64)" "machine" + has "$OUT" "Magic: 0x20B" "PE32+" + has "$OUT" "AddressOfEntryPoint: 0x1000" "entry at .text" + has "$OUT" "SectionAlignment: 4096" "section alignment" + has "$OUT" "IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE" "dynamic base" + has "$OUT" "IMAGE_SUBSYSTEM_WINDOWS_CUI" "console subsystem" + has "$OUT" "Name: .reloc" "relocation section" + has "$OUT" "Type: ABSOLUTE" "an empty relocation block" + has "$OUT" "Name: kernel32.dll" "kernel32 imports" + has "$OUT" "Symbol: WriteFile" "WriteFile imported" + has "$OUT" "Symbol: ExitProcess" "ExitProcess imported" + case "$OUT" in *RELOCS_STRIPPED*) fail "relocations marked stripped" ;; esac +} + +t_winarm_examples_and_trackc_parse() { + need_llvm + local e s n=0 + for e in $(trk_files "$ROOT/examples") "$ROOT/compiler/src/main.trk"; do + s=$(stem "$e") + case "$s" in *_err) continue ;; esac + in_repo "$TRACKC" build --target aarch64-windows "$e" -o "$T/$s.exe" + rc_ok "$s: build" + cap llvm-readobj --file-headers --sections --coff-imports "$T/$s.exe" + rc_ok "$s: llvm-readobj" + eq "$ERR" "" "$s: llvm-readobj stderr" + has "$OUT" "IMAGE_FILE_MACHINE_ARM64" "$s: machine" + cap llvm-objdump -d "$T/$s.exe" + rc_ok "$s: llvm-objdump" + eq "$ERR" "" "$s: llvm-objdump stderr" + n=$((n + 1)) + done + [ "$n" -ge 15 ] || fail "only $n images" +} + +# Every import call is adrp x16 + ldr x16 + blr x16, and the slot the +# pair loads is one of the IAT's slots. +t_winarm_import_calls_load_iat_slots() { + need_llvm + have python3 || skip "python3 not found" + in_repo "$TRACKC" build --target aarch64-windows examples/stdlib_demo.trk -o "$T/demo.exe" + rc_ok "build" + llvm-readobj --coff-imports "$T/demo.exe" >"$T/imp" || fail "llvm-readobj" + llvm-objdump -d "$T/demo.exe" >"$T/dis" || fail "llvm-objdump" + cap python3 -I - "$T/imp" "$T/dis" <<'PY' +import re, sys +imp = open(sys.argv[1]).read() +slots = {} +for block in imp.split("Import {")[1:]: + iat = int(re.search(r"ImportAddressTableRVA: (0x[0-9A-Fa-f]+)", block).group(1), 16) + for k, sym in enumerate(re.findall(r"Symbol: (\S+)", block)): + slots[0x140000000 + iat + 8 * k] = sym +lines = open(sys.argv[2]).read().splitlines() +calls = 0 +for i, l in enumerate(lines): + if not re.search(r"\tblr\tx16$", l): + continue + a = re.search(r"\tadrp\tx16, (0x[0-9a-f]+)$", lines[i - 2]) + b = re.search(r"\tldr\tx16, \[x16, #(0x[0-9a-f]+)\]$", lines[i - 1]) + if not a or not b: + sys.exit("blr x16 not after adrp + ldr: " + l) + slot = int(a.group(1), 16) + int(b.group(1), 16) + if slot not in slots: + sys.exit("call through 0x%x, not an IAT slot" % slot) + calls += 1 +print("ok %d import calls" % calls) +PY + rc_ok "$OUT" + has "$OUT" "ok " "verdict" +} + +t_winarm_never_touches_x18() { + need_llvm + in_repo "$TRACKC" build --target aarch64-windows compiler/src/main.trk -o "$T/trackc.exe" + rc_ok "build" + llvm-objdump -d "$T/trackc.exe" >"$T/dis" || fail "llvm-objdump" + grep -qE '\b[xw]18\b' "$T/dis" && fail "x18 (the TEB) is used: $(grep -m3 -E '\b[xw]18\b' "$T/dis")" + grep -q 'blr' "$T/dis" || fail "no import calls" + return 0 +} + +t_winarm_build_is_deterministic() { + in_repo "$TRACKC" build --target aarch64-windows examples/hello.trk -o "$T/1.exe" + rc_ok "first build" + in_repo "$TRACKC" build --target aarch64-windows examples/hello.trk -o "$T/2.exe" + rc_ok "second build" + same_file "$T/1.exe" "$T/2.exe" "two builds" +} diff --git a/tests/sh/xplat.sh b/tests/sh/xplat.sh index d3e7575..70d8ac3 100644 --- a/tests/sh/xplat.sh +++ b/tests/sh/xplat.sh @@ -25,12 +25,17 @@ t_xplat_unknown_target_is_a_clear_error() { rc_is 2 "TRACKC_TARGET is read" } -t_xplat_unsupported_target_says_so() { - in_repo "$TRACKC" build --target aarch64-windows examples/hello.trk -o "$T/x" - rc_is 2 "exit code" - has "$ERR" "not supported yet" "message" - in_repo "$TRACKC" check --target aarch64-windows examples/hello.trk - rc_ok "check works for any known target" +t_xplat_every_known_target_builds() { + local a o + for a in x86_64 aarch64; do + for o in linux macos windows; do + in_repo "$TRACKC" build --target $a-$o examples/hello.trk -o "$T/h_${a}_$o" + rc_ok "$a-$o: build" + [ -s "$T/h_${a}_$o" ] || fail "$a-$o: no image" + in_repo "$TRACKC" check --target $a-$o examples/hello.trk + rc_ok "$a-$o: check" + done + done } t_xplat_linux_target_is_the_default_output() { @@ -62,7 +67,7 @@ EOF rc_ok "check accepts extern" trackc build "$T/ext.trk" -o "$T/ext" rc_fail "linux build of an import" - has "$ERR" "needs --target x86_64-windows" "message" + has "$ERR" "needs a windows or macos --target" "message" } t_xplat_windows_hello_runs_under_wine() {