Triforce v0.2.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ruckus7382sfgsgdf
2026-11-10 19:32:48 -06:00
commit 34b3683441
1730 changed files with 554853 additions and 0 deletions

24
third_party/a64-kit/NOTICE.TOTKPort.md vendored Normal file
View File

@@ -0,0 +1,24 @@
# Third-party code
Rexcomp and the AArch64 kit are by NotRexed. This repository includes:
| What | Where | License |
|---|---|---|
| suyu's AArch64 -> C translator (`arm64_to_c.h`, unmodified), from the mk8-recomp fork of suyu (`dougchansan/suyu-v0.0.4`, branch `mk8-recomp`, commit `89c5e72412b28c788557991a86f471ea3332f62a`) | `a64-kit/lift/suyu/` | GPL-2.0-or-later (texts next to it) |
| suyu / yuzu shader recompiler, common and video_core parts, with Rexcomp's WGSL backend and changes | `a64-kit/gpu/third_party/suyu/` | GPL-2.0-or-later and GPL-3.0-or-later per file (SPDX headers; texts next to it) |
| Small stand-ins for boost, fmt and ankerl::unordered_dense headers | `a64-kit/gpu/compat/` | see each file |
| wgpu-native v29.0.1.1, Windows x64 release | `third_party/wgpu-native/` | MIT or Apache-2.0 (`LICENSE.md` there) |
| NVN API types reconstructed from Darksiders II debug information by h1k421 (as adapted for TOTK by jhaizhou) | `a64-kit/gpu/render/nvn_api.h` | MIT (text in the file) |
| The native NVN layer's design, object layouts, command records and TOTK findings, after the NVN layer of d2r-mobile / MacNativeGames by jhaizhou (github.com/jhaizhou-ops/d2r-mobile, github.com/ly05010419/MacNativeGames) | `a64-kit/hos/nvn_native.c`, `a64-kit/gpu/render/rx_nvn.*` | MIT |
| NVN texture storage layout, from deko3d `source/dk_image.cpp` by fincs (via the layer above) | `a64-kit/hos/nvn_layout.c` | zlib |
| AMD FidelityFX Super Resolution 1 (EASU, RCAS), ported to WGSL | `a64-kit/gpu/render/rx_present_fx.cpp` | MIT (text in the file) |
| RenderDoc's in-application API header (`renderdoc_app.h`, RenderDoc 1.46, unmodified) | `a64-kit/gpu/render/renderdoc_app.h` | MIT (text in the file) |
| Zstandard 1.5.6 decoder (the single-file `zstddeclib.c` its release makes) | `third_party/zstd/` | BSD (`LICENSE` there) |
| The virtual cores' design (one guest thread per core, priority hand-offs, checkpoints), after MacNativeGames' `games/totk/runtime/threads.c` and TotK Recomp's `runtime/kernel.c` (the code is ours) | `a64-kit/hos/hos_thread.c` | MIT |
| The game's zstd decoder on the host's, after `runtime/ov_zstd.c` of TotK Recomp by valentderah (github.com/valentderah/totk-pc-recomp, Copyright (c) 2026 Valiantsin Dzerakh); occlusion counts from occlusion queries, after its `runtime/vk_exec_xfer.c` | `a64-kit/hos/totk_zstd.c`, `a64-kit/gpu/render/rx_core.cpp` | MIT |
| Where TOTK v1.0.0 sets its camera aspect and HUD scale, after TOTK-Ultrawide by Fruithapje21 (github.com/Fruithapje21/TOTK-Ultrawide) | `a64-kit/hos/totk_ultrawide*.c` | GPL-3.0 (locations only; the code is ours) |
Because of the GPL parts, `a64emit.dll`, the generated runtime, the lifted C and every game build made with this kit
are GPL. Game data and code are Nintendo's and are not included.
- `third_party/opus`: libopus 1.5.2 (https://opus-codec.org), BSD 3-clause; see third_party/opus/COPYING.

14
third_party/a64-kit/PROVENANCE.md vendored Normal file
View File

@@ -0,0 +1,14 @@
# a64-kit (vendored subset)
Copied unmodified from NotRexed's a64-kit (Rexcomp's AArch64 kit, `Porting Tools\Rexcomp\a64-kit`, a link to
`Ports\TOTK\TOTKPort\a64-kit`) at TOTKPort commit `60de030` (2026-10-30). Only the parts the lifter pipeline needs:
`lift/` (lifter, suyu's translator and its ctypes binding), `rt/` (guest model), `tools/nso.py`, `tools/toolchain.py`,
`tools/survey.py`, `hos/nx_image.py`, `tests/insn_test.py`.
It is vendored, not referenced in place, so that building `a64emit.dll` and `lld-link.exe` (both written next to
their sources) never writes into the TOTKPort checkout, and so that this project is pinned to one version.
mkw-recomp's changes live outside this folder (`nx2/`): they wrap these modules instead of editing them, so the
copy can be refreshed from upstream by copying the files again.
Licensing: `lift/suyu/arm64_to_c.h` is suyu's (GPL-2.0-or-later, texts in `lift/suyu/`), so `a64emit.dll`, the
generated runtime and all lifted C are GPL. See `NOTICE.TOTKPort.md`.

83
third_party/a64-kit/README.a64-kit.md vendored Normal file
View File

@@ -0,0 +1,83 @@
# a64-kit: AArch64 (Nintendo Switch)
The fourth kit, for 64-bit ARM console code. First port: [Tears of the Kingdom](../ports/zelda-totk/PORT.md).
**Status (2026-10-11): milestone 2.** The whole of TOTK's `main` + `sdk` lifts to C in about a minute, every
instruction form the game uses matches Unicorn bit for bit, and the native build compiles and links. The Horizon OS
layer (`hos/`) is only the image builder and a loader so far: nothing boots yet.
**Licensing:** the instruction translator is suyu's (GPL-2.0-or-later, `lift/suyu/`), so this kit and everything
built with it are GPL. The other kits are untouched by it. See [third_party/NOTICE.md](../third_party/NOTICE.md).
## Pipeline
```
NSP ─► tools/nx.py ─► exefs/ ─► hos/nx_image.py ─► image.bin + image.json we are rtld: modules at fixed
(tools/nso.py) addresses, relocations applied,
imports bound to hooks
│
▼
lift/a64_lift.py (functions, control flow, jump tables, PLT, calls)
+ lift/a64emit.dll (suyu's per-instruction translator, via ctypes)
│
▼
gen/code_NNN.c, a64_table.c, a64_suyu.h/.c (generated runtime), a64_stubs.c (import stubs)
│
▼
build.py native: clang -O1 + rt/ + hos/ -> <name>.exe
```
```bash
python a64-kit/build.py lift totk --exefs TOTK/exefs --skip subsdk0 --build TOTK/build
python a64-kit/build.py native totk --build TOTK/build
python a64-kit/tests/insn_test.py TOTK/image --per 8 --states 12 --fpsr
```
## Layout
| Path | What |
|---|---|
| `tools/nx.py` | NSP (PFS0) → NCA → ExeFS / RomFS. AES-XTS header, AES-CTR sections, keys from `~/.switch/prod.keys` (never printed) |
| `tools/nso.py` | NSO loader: LZ4 segments, MOD0, dynamic section, symbols, relocations, init_array, `.eh_frame_hdr` function starts |
| `tools/survey.py` | Instruction census of a module's `.text` |
| `tools/toolchain.py` | emsdk clang/lld lookup, native target flags |
| `hos/nx_image.py` | The image builder (rtld's job at build time) |
| `hos/hos_main.c` | Native process start (loads the image; booting is next) |
| `lift/a64_lift.py` | The lifter |
| `lift/a64emit.cpp`, `build_emit.py`, `a64emit.py` | suyu's translator as a DLL and its ctypes binding |
| `lift/a64_rtgen.py` | Writes suyu's FP helpers and runtime pieces, adapted to `rt/a64.h`, next to the lifted code |
| `lift/suyu/` | `arm64_to_c.h`, vendored unmodified, with its licenses |
| `rt/a64.h` | The guest model the lifted code sees |
| `rt/a64_rt.c` | Dispatch, indirect calls and jumps, traps, exclusive monitor, CNTPCT |
| `tests/insn_test.py` | Every instruction form a game uses, Unicorn vs lifted C |
## The guest model
| | a64-kit |
|---|---|
| Guest address space | 64-bit registers; every mapping below 4 GB (our loader and memory HLE pick all addresses), so an access is `A64_MEM + (uint32_t)addr`, natively and in wasm32 |
| Context | suyu's `GuestContext` shape: `x[32]` (x[31] = SP), NZCV bytes, `vreg[32][2]`, `fpcr`/`fpsr`, TPIDR(RO)_EL0, plus our exclusive monitor and thread pointer |
| Functions | `void f_XXXXXXXX(Ctx *restrict c)`: an entry plus everything reachable without crossing another entry (ppc-kit's model). Branches and fallthrough into another entry are `TAILCALL`s |
| Calls | `bl` writes LR and calls; `blr` → `a64_icall` (binary search over the function table); `ret` returns |
| `br` | Recovered jump tables → `switch` on the target; PLT stubs resolved through the relocated GOT; anything else (virtual tail calls) → `a64_ijump` |
| Exclusives | `ldxr` remembers (address, size, value); `stxr` compare-and-swaps against it, so real host threads are safe |
| Entries | `.eh_frame_hdr` starts, exports, init_array, RELATIVE/ABS64 targets in code, `bl` targets, ADR / ADRP+ADD targets |
## Numbers on TOTK (2026-10-11)
| | |
|---|---|
| Lift | 281,751 functions, 12.6M instructions emitted (shared tails included), 44 files, 1.1 GB of C, ~60 s |
| Translator coverage | 868,649 distinct words; 114 untranslatable, all data in code or the SDK's LSE path the A57 never takes (they trap) |
| Jump tables | 2,858 recognised; 27,126 `br` stay indirect: ~26,750 of them are virtual tail calls (`ldr xN, [vtable]; br xN`), ~380 other shapes are unchecked |
| FP guards | 654k suyu FPX1 guards, each one call of a generated helper (`a64_fpx.h`) instead of inline code |
| Instruction test | 574 forms, 38,494 random states, registers + NZCV + V regs + FPSR + memory: 0 differences from Unicorn |
| Compile | 100-200 s per ~25 MB file at -O1 on one core (LoopRotate capped, see build.py) |
What made the compile tractable (each measured on TOTK's physics chunk, 20 functions of up to 18k instructions):
1. **No entries at ADR / ADRP+ADD targets.** 3,735 entries came only from those, nearly all jump-table base labels;
each cut a function in two, and both halves re-walked the code between: 14.4M → 12.6M instructions.
2. **FPX guards outlined** into one helper call per lane op (`A64_FPX_FN`, noinline by default; define it as
`static inline` to trade compile time for speed).
3. **`-mllvm -rotation-max-header-size=0`**: LoopRotate was 120 s of a 306 s compile; with it, 197 s.
4. Splitting giant functions (`--max-func`) does not help: they are loops end to end, so it finds almost no cut.

205
third_party/a64-kit/hos/nx_image.py vendored Normal file
View File

@@ -0,0 +1,205 @@
"""Switch (Horizon) image builder: we are rtld.
Lays an ExeFS's modules out at fixed guest addresses, applies their relocations and binds every symbol import,
once, at build time. The result is the guest image the lifter reads and the runtime maps.
- Modules load in rtld's order (main, subsdk*, sdk) from MAIN_BASE, each 1 MB aligned. Skipped modules
(`skip`, e.g. subsdk0, TOTK's movie player) are not loaded; their exports become hooks.
- Symbols resolve in that same global order. A symbol named in `hle` that a loaded module defines is hooked at
its definition (the lifter emits a call of the hook there instead of the body). An undefined weak symbol
resolves to 0, as rtld does, unless it is in `hle`; any other unresolved symbol binds to a trampoline, so a
call to it stops with its name instead of jumping to 0.
- Trampolines are 16-byte slots from TRAMP_BASE. They are guest addresses with no code: the lifter turns calls
to them into calls of the hook `imp_<mangled name>` (the Rexcomp import model).
- Entry candidates: .eh_frame_hdr function starts, exported functions, init_array, every RELATIVE/ABS64 result
that lands in code, every BL target, each module's start.
Usage: python nx_image.py <exefs_dir> <out_dir> [--skip subsdk0] [--hle names.txt]
Writes image.bin (MAIN_BASE .. end), image.json (modules, hooks, entries, init order) to out_dir.
"""
import json
import os
import struct
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "tools"))
import nso
MAIN_BASE = 0x08000000
TRAMP_BASE = 0x07000000
ALIGN = 0x100000
def c_ident(sym):
return "imp_" + "".join(ch if ch.isalnum() or ch == "_" else "_" for ch in sym)
class NxImage:
def __init__(self, exefs, skip=(), hle=()):
self.modules = [m for m in nso.load_exefs(exefs) if m.name != "rtld" and m.name not in skip]
self.skipped = [n for n in skip]
base = MAIN_BASE
for m in self.modules:
m.base = base
base = (base + len(m.image) + ALIGN - 1) & ~(ALIGN - 1)
self.end = base
self.mem = bytearray(self.end - MAIN_BASE)
for m in self.modules:
self.mem[m.base - MAIN_BASE:m.base - MAIN_BASE + len(m.image)] = m.image
self.hle = set(hle)
self.exports = {}
for m in self.modules:
for s in m.symbols:
if s["defined"] and s["name"] and s["name"] not in self.exports:
self.exports[s["name"]] = (m, s)
self.hooks = {} # guest address -> C name
self.hook_syms = {} # C name -> symbol
self.tramp = {} # symbol -> trampoline address
self.unresolved = {} # symbol -> number of references
# An HLE'd symbol a loaded module defines is hooked at its definition: the game's import resolves to it
# as usual, and lifted SDK code calling it internally reaches the same host function.
for sym in sorted(self.hle):
hit = self.exports.get(sym)
if hit:
m, s = hit
name = c_ident(sym)
self.hooks[m.base + s["value"]] = name
self.hook_syms[name] = sym
self._relocate()
self.code = [(m.base + lo, m.base + hi, m.name) for m in self.modules for lo, hi in [m.code_range()]]
self._entries()
self.names = self.symbol_names()
# ---- binding ---------------------------------------------------------------------------------------
def trampoline(self, sym):
a = self.tramp.get(sym)
if a is None:
a = self.tramp[sym] = TRAMP_BASE + 16 * len(self.tramp)
name = c_ident(sym)
self.hooks[a] = name
self.hook_syms[name] = sym
return a
def resolve(self, sym, weak):
hit = self.exports.get(sym)
if hit:
m, s = hit
return m.base + s["value"]
if weak and sym not in self.hle:
return 0
if sym not in self.hle:
self.unresolved[sym] = self.unresolved.get(sym, 0) + 1
return self.trampoline(sym)
def _relocate(self):
for m in self.modules:
bind = {s["name"]: s["bind"] for s in m.symbols}
for r in m.relocs:
at = m.base + r["offset"] - MAIN_BASE
if r["type"] == "RELATIVE":
v = m.base + r["addend"]
elif r["type"] in ("ABS64", "GLOB_DAT", "JUMP_SLOT"):
# S + A for all three (AArch64 ELF ABI; rtld writes the same: symbol address + r_addend)
v = self.resolve(r["sym"], bind.get(r["sym"]) == "weak") + r["addend"]
else:
raise SystemExit(f"{m.name}: relocation type {r['type']} at {r['offset']:#x} not supported")
struct.pack_into("<Q", self.mem, at, v & 0xFFFFFFFFFFFFFFFF)
# ---- entry candidates ------------------------------------------------------------------------------
def in_code(self, a):
if a & 3:
return False
for lo, hi, _ in self.code:
if lo <= a < hi:
return True
return False
def word(self, a):
return struct.unpack_from("<I", self.mem, a - MAIN_BASE)[0]
def read(self, a, n):
if not (MAIN_BASE <= a and a + n <= self.end):
raise ValueError("read outside the image: %#x" % a)
return bytes(self.mem[a - MAIN_BASE:a - MAIN_BASE + n])
def _entries(self):
e = set()
for m in self.modules:
lo, hi = m.code_range()
e.add(m.base + lo)
# DT_INIT / DT_FINI: the SDK crt's _init/_fini, which rtld calls per module (rtld+0xcac / +0xcbc)
e.update(m.base + m.dynamic[k][0] for k in ("INIT", "FINI") if k in m.dynamic)
e.update(m.base + f for f in m.eh_funcs)
e.update(m.base + s["value"] for s in m.symbols if s["defined"] and s["type"] == "func" and s["value"])
for r in m.relocs:
if r["type"] in ("RELATIVE", "ABS64"):
v = struct.unpack_from("<Q", self.mem, m.base + r["offset"] - MAIN_BASE)[0]
if self.in_code(v):
e.add(v)
# BL targets. Not ADR / ADRP+ADD targets: in TOTK 3,735 of those were nothing but jump-table base
# labels, and an entry there cuts a function in two with tail calls looping between the halves.
# Functions whose address is taken have .eh_frame entries anyway.
text = memoryview(self.mem)[m.base + lo - MAIN_BASE:m.base + hi - MAIN_BASE]
for i, w in enumerate(struct.unpack("<%dI" % (len(text) // 4), text)):
if (w & 0xFC000000) == 0x94000000:
off = w & 0x3FFFFFF
e.add(m.base + lo + 4 * i + 4 * (off - (1 << 26) if off & (1 << 25) else off))
self.init_arrays = {m.name: [struct.unpack_from("<Q", self.mem, m.base + off - MAIN_BASE)[0]
for off in self._init_array_offsets(m)] for m in self.modules}
for arr in self.init_arrays.values():
e.update(a for a in arr if self.in_code(a))
self.entries = {a for a in e if self.in_code(a)}
self.eh_starts = sorted(m.base + f for m in self.modules for f in m.eh_funcs)
def _init_array_offsets(self, m):
start = m.dynamic.get("INIT_ARRAY", [0])[0]
size = m.dynamic.get("INIT_ARRAYSZ", [0])[0]
return [start + 8 * i for i in range(size // 8)]
# ---- output ----------------------------------------------------------------------------------------
def symbol_names(self):
"""guest address -> mangled name, for comments in lifted code"""
names = {}
for m in self.modules:
for s in m.symbols:
if s["defined"] and s["type"] == "func" and s["name"]:
names.setdefault(m.base + s["value"], s["name"])
return names
def write(self, out):
os.makedirs(out, exist_ok=True)
open(os.path.join(out, "image.bin"), "wb").write(self.mem)
meta = {
"base": MAIN_BASE, "end": self.end, "tramp_base": TRAMP_BASE,
"modules": [{"name": m.name, "base": m.base, "size": len(m.image), "build_id": m.build_id,
"init": m.base + m.dynamic["INIT"][0] if "INIT" in m.dynamic else 0,
"fini": m.base + m.dynamic["FINI"][0] if "FINI" in m.dynamic else 0,
"segments": [{"name": n, "addr": m.base + o, "size": s} for o, s, n in m.segments],
"bss": [m.base + m.bss[0], m.base + m.bss[1]]} for m in self.modules],
"skipped": self.skipped,
"hooks": [{"addr": a, "c": n, "sym": self.hook_syms[n]} for a, n in sorted(self.hooks.items())],
"unresolved": self.unresolved,
"init_arrays": self.init_arrays,
"exports": {name: m.base + s["value"] for name, (m, s) in self.exports.items() if s["type"] == "func"},
}
json.dump(meta, open(os.path.join(out, "image.json"), "w"), indent=0)
return meta
def main():
args = sys.argv[1:]
skip, hle = [], []
if "--skip" in args:
i = args.index("--skip"); skip = args[i + 1].split(","); del args[i:i + 2]
if "--hle" in args:
i = args.index("--hle"); hle = [l.strip() for l in open(args[i + 1]) if l.strip() and not l.startswith("#")]; del args[i:i + 2]
img = NxImage(args[0], skip, hle)
meta = img.write(args[1])
for m in meta["modules"]:
print(f" {m['name']:<8} {m['base']:#010x} {m['size']:>12,}")
print(f"entries {len(img.entries):,} hooks {len(img.hooks):,} unresolved non-weak {len(img.unresolved)}")
if __name__ == "__main__":
main()

1848
third_party/a64-kit/lift/a64_lift.py vendored Normal file

File diff suppressed because it is too large Load Diff

75
third_party/a64-kit/lift/a64_rtgen.py vendored Normal file
View File

@@ -0,0 +1,75 @@
"""Write suyu's runtime pieces next to the lifted code, adapted to a64-kit's guest model (rt/a64.h).
a64_suyu.h suyu's runtime header (FP scan/fixed-point helpers, FPX1 fast paths, prototypes) without its
GuestContext, host memory bridge and layout pins: rt/a64.h defines the context and the memory
accessors before including this, so the accessor prototypes here inherit their static inline.
a64_suyu.c the out-of-line pieces the translated code calls: FPX1 exact bodies (recomp_fpe_*), the FP
reciprocal estimates, SMULH/UMULH and the AES S-box.
Both are GPL-2.0-or-later (from suyu/arm64_to_c.h). They are regenerated on every lift, so they always match the
a64emit build that produced the code.
"""
import os
import re
import a64emit
def _cut(text, start_marker, end_marker):
a = text.find(start_marker)
b = text.find(end_marker, a)
if a < 0 or b < 0:
raise SystemExit("a64_rtgen: suyu runtime layout changed (%r .. %r not found): update a64_rtgen.py"
% (start_marker, end_marker))
return text[:a] + text[b:]
def runtime_h():
h = a64emit.runtime_text(0)
h = _cut(h, "typedef struct RecompHostMem {", "/* Where this module is actually loaded")
h = h.replace("extern uint64_t g_module_base;\n", "")
for proto in ("int recomp_save_init", "int recomp_save_write", "int recomp_save_read", "int recomp_save_delete",
"int recomp_save_exists", "int recomp_load_segments"):
h = re.sub(r"^%s\(.*\n" % re.escape(proto), "", h, flags=re.M)
# (every context parameter A64_NOESC, rt/a64.h: these functions keep no pointer to it)
h = re.sub(r"([(,]\s*)GuestContext\s*\*\s*(?=(?:\w+\s*)?[,)])", r"\1GuestContext *A64_NOESC ", h)
return "/* Generated by a64-kit/lift/a64_rtgen.py from suyu/arm64_to_c.h (GPL-2.0-or-later). Do not edit. */\n" + h
def _function(src, signature):
"""The text of one top-level C function, from its signature to its closing brace at column 0."""
a = src.find(signature)
if a < 0:
raise SystemExit("a64_rtgen: %r not found in suyu's runtime C" % signature)
b = src.find("\n}\n", a)
return src[a:b + 3]
def runtime_c():
rc = a64emit.runtime_text(1)
aes = rc[rc.find("static uint8_t recomp_gmul"):]
aes = aes[:aes.find("\n}\n", aes.find("const uint8_t* recomp_aes_sbox")) + 3]
parts = [
"/* Generated by a64-kit/lift/a64_rtgen.py from suyu/arm64_to_c.h (GPL-2.0-or-later). Do not edit. */",
'#define A64_RT_IMPL /* (the out-of-line definitions: rt/a64.h inlines them elsewhere) */',
'#include "a64.h"',
aes,
_function(rc, "uint64_t recomp_umulh(uint64_t a,uint64_t b){"),
_function(rc, "uint64_t recomp_smulh(uint64_t a,uint64_t b){"),
a64emit.runtime_text(2),
a64emit.runtime_text(3),
]
return "\n".join(parts)
def write(out_dir):
os.makedirs(out_dir, exist_ok=True)
for name, text in (("a64_suyu.h", runtime_h()), ("a64_suyu.c", runtime_c())):
path = os.path.join(out_dir, name)
if not os.path.exists(path) or open(path, encoding="utf-8").read() != text:
open(path, "w", encoding="utf-8", newline="\n").write(text)
if __name__ == "__main__":
import sys
write(sys.argv[1])

60
third_party/a64-kit/lift/a64emit.cpp vendored Normal file
View File

@@ -0,0 +1,60 @@
// a64emit: the per-instruction AArch64 -> C translator of suyu's static recompiler (suyu/arm64_to_c.h,
// GPL-2.0-or-later), built as a DLL so the Python lifter (a64_lift.py) can call it through ctypes.
//
// The lifter owns everything around single instructions: functions, control flow, calls, jump tables, svc.
// It only asks this for the C of instructions that do not end a block, and treats a terminator answer as a
// lifter bug. Licensing: this file and every binary built from it are GPL-2.0-or-later (see suyu/).
//
// Build: python a64-kit/lift/build_emit.py -> a64-kit/lift/a64emit.dll
#include "suyu/arm64_to_c.h"
#if defined(_WIN32)
#define A64_EXPORT extern "C" __declspec(dllexport)
#else
#define A64_EXPORT extern "C" __attribute__((visibility("default")))
#endif
using namespace suyu::recomp;
// translate_all: translate the forms suyu leaves to its JIT in Hybrid mode (we have no JIT).
// fpx: 0 = exact integer FP bodies only, 1 = FPX1 (native fast path, exact body when it cannot prove equality).
A64_EXPORT void a64_config(int translate_all, int fpx) {
g_translate_all = translate_all != 0;
g_emit_fpx = fpx != 0;
g_emit_fpx_shadow = false;
g_emit_fastmem = false;
g_emit_guard_gen = false;
g_chain_blocks = nullptr;
g_chain_mod = nullptr;
}
// Translates n instructions. The C of instruction k is out[offs[k] .. offs[k+1]). flags[k]: bit 0 = unhandled
// (fell through to recomp_unhandled), bit 1 = terminator (Translate closed the block).
// Returns the number of bytes needed: if it is larger than cap, nothing past cap was written and the caller retries.
A64_EXPORT long long a64_translate_batch(const uint32_t* insns, const uint64_t* pcs, int n, char* out,
long long cap, long long* offs, int* flags) {
std::string s;
s.reserve((size_t)n * 96);
for (int k = 0; k < n; ++k) {
offs[k] = (long long)s.size();
bool unhandled = false;
const bool open = Translate(insns[k], pcs[k], s, &unhandled);
flags[k] = (unhandled ? 1 : 0) | (open ? 0 : 2);
}
offs[n] = (long long)s.size();
if ((long long)s.size() <= cap) memcpy(out, s.data(), s.size());
return (long long)s.size();
}
// Runtime texts the emitted C depends on, for the build to write next to the lifted code.
A64_EXPORT const char* a64_runtime_text(int which) {
static std::string keep[8];
switch (which) {
case 0: return RuntimeH();
case 1: return keep[1] = BuildRuntimeC(false, false), keep[1].c_str();
case 2: return EstimateRuntimeC();
case 3: return keep[3] = FpxExactC(), keep[3].c_str();
default: return "";
}
}

57
third_party/a64-kit/lift/a64emit.py vendored Normal file
View File

@@ -0,0 +1,57 @@
"""ctypes binding for a64emit (suyu's per-instruction AArch64 -> C translator, built by build_emit.py).
import a64emit
texts, flags = a64emit.translate([(pc, word), ...]) # flags: UNHANDLED, TERMINATOR bits
"""
import ctypes
import os
import build_emit
UNHANDLED = 1
TERMINATOR = 2
_lib = None
def lib(translate_all=True, fpx=True):
global _lib
if _lib is None:
_lib = ctypes.CDLL(build_emit.build())
_lib.a64_config.argtypes = [ctypes.c_int, ctypes.c_int]
_lib.a64_translate_batch.restype = ctypes.c_longlong
_lib.a64_translate_batch.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p,
ctypes.c_longlong, ctypes.c_void_p, ctypes.c_void_p]
_lib.a64_runtime_text.restype = ctypes.c_char_p
_lib.a64_runtime_text.argtypes = [ctypes.c_int]
_lib.a64_config(int(translate_all), int(fpx))
return _lib
def translate(items, batch=65536):
"""items: list of (pc, word). Returns (list of C texts, list of flag ints), in order."""
L = lib()
texts, flags = [], []
cap = 1 << 24
buf = ctypes.create_string_buffer(cap)
for start in range(0, len(items), batch):
part = items[start:start + batch]
n = len(part)
insns = (ctypes.c_uint32 * n)(*[w for _, w in part])
pcs = (ctypes.c_uint64 * n)(*[p for p, _ in part])
offs = (ctypes.c_longlong * (n + 1))()
fl = (ctypes.c_int * n)()
need = L.a64_translate_batch(insns, pcs, n, buf, cap, offs, fl)
if need > cap:
cap = int(need * 1.25)
buf = ctypes.create_string_buffer(cap)
need = L.a64_translate_batch(insns, pcs, n, buf, cap, offs, fl)
raw = buf.raw[:need].decode("latin-1")
texts += [raw[offs[k]:offs[k + 1]] for k in range(n)]
flags += list(fl)
return texts, flags
def runtime_text(which):
"""0 = suyu's runtime header, 1 = its runtime C, 2 = FP estimate C, 3 = FPX exact helpers C."""
return lib().a64_runtime_text(which).decode("utf-8")

32
third_party/a64-kit/lift/build_emit.py vendored Normal file
View File

@@ -0,0 +1,32 @@
"""Build a64emit (suyu's AArch64 -> C instruction translator) as a shared library for a64_lift.py.
Usage: python build_emit.py -> a64emit.dll (Windows) / liba64emit.so (elsewhere), next to this file
Rebuilds only when a64emit.cpp or suyu/arm64_to_c.h changed.
"""
import hashlib, os, subprocess, sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "tools"))
import toolchain
SRC = [os.path.join(HERE, "a64emit.cpp"), os.path.join(HERE, "suyu", "arm64_to_c.h")]
OUT = os.path.join(HERE, "a64emit.dll" if os.name == "nt" else "liba64emit.so")
def build(force=False):
key = hashlib.sha1(b"".join(open(f, "rb").read() for f in SRC)).hexdigest()
stamp = OUT + ".sha1"
if not force and os.path.exists(OUT) and os.path.exists(stamp) and open(stamp).read() == key:
return OUT
cmd = [toolchain.need(toolchain.find("clang++", host=True)), "-std=c++20", "-O2", "-shared", "-o", OUT, SRC[0],
"-Wno-everything"] + toolchain.native_target(host=True) + toolchain.native_link(host=True)
if os.name != "nt":
cmd += ["-fPIC"]
print("building", os.path.basename(OUT))
subprocess.run(cmd, check=True)
open(stamp, "w").write(key)
return OUT
if __name__ == "__main__":
print(build(force="--force" in sys.argv))

View File

@@ -0,0 +1,117 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

View File

@@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

8094
third_party/a64-kit/lift/suyu/arm64_to_c.h vendored Normal file

File diff suppressed because it is too large Load Diff

206
third_party/a64-kit/rt/a64.h vendored Normal file
View File

@@ -0,0 +1,206 @@
/* a64-kit guest model: what every lifted AArch64 function sees.
The instruction bodies come from suyu's translator (lift/suyu/arm64_to_c.h), which writes C against a
`GuestContext` and calls `recomp_load*` / `recomp_store*` / `recomp_ldxr` ...; this header supplies those
for Rexcomp: one flat guest memory below 4 GB (`A64_MEM + (uint32_t)addr`), no page table, no host bridge.
The FP helpers and the rest of suyu's runtime header are generated next to the lifted code
(a64_suyu.h, by lift/a64_rtgen.py) and included at the end. */
#ifndef A64_H
#define A64_H
#include <stdint.h>
#include <stddef.h>
#include <string.h>
typedef struct GuestContext {
uint64_t x[32]; /* x[31] is SP: suyu's translator spells SP as x[31] where the encoding means SP */
uint64_t pc; /* only written where the lifter stops a thread (traps, unhandled) */
uint8_t n, z, c, v; /* NZCV, one byte each */
int halted;
uint64_t vreg[32][2]; /* Q0-Q31 as two 64-bit halves */
uint64_t tpidr_el0; /* the guest's own thread pointer (C++ TLS) */
uint64_t tpidrro_el0; /* Horizon's thread-local region, set by the OS layer */
uint64_t fpcr, fpsr;
/* Exclusive monitor (LDXR/STXR): the address, size and value LDXR saw. STXR compare-and-swaps against
that value, so it works with real host threads (dynarmic's model). */
uint64_t excl_addr, excl_lo, excl_hi;
uint32_t excl_size;
int excl_valid;
void *thread; /* the OS layer's thread object */
} GuestContext;
typedef GuestContext Ctx;
/* A64_NOESC on every context parameter lifted code can call (the lifted functions, A64Fn, the runtime's and the OS
layer's entry points): none of them keeps the pointer past the call. Without it each call "captures" the context, and
LLVM must assume any guest load or store (an address made from an integer) might touch it: after every guest store
it reloaded guest registers, and it kept every store to them. It also needs the lifted code built with a higher
-capture-tracking-max-uses-to-explore (build.py): past 100 uses of the pointer LLVM stops looking and assumes
it escaped, and a large lifted function uses it thousands of times. (Its effect on one of TOTK's hot functions:
context loads 539 -> 278, stores 1068 -> 893, instructions -6%.) -DA64_NOESC= turns it off. */
#ifndef A64_NOESC
#if defined(__clang__)
#define A64_NOESC __attribute__((noescape))
#else
#define A64_NOESC
#endif
#endif
#if defined(_MSC_VER) && !defined(__clang__)
#define A64_INLINE static __forceinline
#else
#define A64_INLINE static inline __attribute__((always_inline))
#endif
/* Guest memory: the 4 GB guest window starts at a constant host address, so the base folds into every access
instead of being reloaded from a global (with -fno-strict-aliasing any guest byte store could have changed
that global). Natively the window is reserved at A64_HOST_BASE (hos_main.c); with A64_MEM_ZERO (web builds)
guest address = wasm address, which needs -fno-delete-null-pointer-checks because guest address 0 is real. */
#ifdef A64_MEM_ZERO
#define A64_MEM ((uint8_t *)0)
#else
#ifndef A64_HOST_BASE
#define A64_HOST_BASE 0x100000000000ULL /* 16 TB: far from anything Windows or glibc map by default */
#endif
#define A64_MEM ((uint8_t *)A64_HOST_BASE)
#endif
#define A64_PTR(a) (A64_MEM + (uint32_t)(a))
/* Browser builds (A64_WRITE_TRACK): wasm has no page write watch, so every guest store marks its 4 KB page (first
and last byte's: an unaligned store may cross a page); hos/web/win32.c's GetWriteWatch reads and clears the marks
for the renderer's buffer cache. */
#if defined(A64_NO_MARKS) /* (measurement only: build.py RX_NO_GUEST_MARKS) */
#define A64_MARK(a, n) ((void)0)
#elif defined(A64_WRITE_TRACK) && !defined(__EMSCRIPTEN__)
/* Native builds track the same way instead of with Windows' write watch (build.py: RX_SOFT_WRITE_WATCH=0), whose
GetWriteWatch over the ~2 GB the GPU sees took 20-50 ms while the game streamed (hitches at its fences). The mark is a
release store (a plain store on x86): the compiler may not move it above the data store, so a scan that clears a
mark has seen the data it marks. (The marks are ~1 ms of the castle's game-thread CPU a frame. Marking the last
byte's page only when a store crosses into it saved ~0.3 ms but made the code 20 MB bigger: not kept.) */
extern uint8_t a64_dirty[1u << 20];
/* (Tried 2026-10-21: reading a mark first and writing it only when clear, against cache lines moving between cores:
game threads +1.1 ms a frame, the code 18 MB bigger. Not kept.) */
#define A64_MARK(a, n) (__atomic_store_n(&a64_dirty[(uint32_t)(a) >> 12], 1, __ATOMIC_RELEASE), \
__atomic_store_n(&a64_dirty[(uint32_t)((a) + (n) - 1) >> 12], 1, __ATOMIC_RELEASE))
#elif defined(A64_WRITE_TRACK)
extern uint8_t a64_dirty[1u << 20];
#define A64_MARK(a, n) (a64_dirty[(uint32_t)(a) >> 12] = 1, a64_dirty[(uint32_t)((a) + (n) - 1) >> 12] = 1)
#else
#define A64_MARK(a, n) ((void)0)
#endif
A64_INLINE uint64_t recomp_load8(GuestContext *c, uint64_t a) { (void)c; return *(const uint8_t *)A64_PTR(a); }
A64_INLINE uint64_t recomp_load16(GuestContext *c, uint64_t a) { uint16_t v; (void)c; memcpy(&v, A64_PTR(a), 2); return v; }
A64_INLINE uint64_t recomp_load32(GuestContext *c, uint64_t a) { uint32_t v; (void)c; memcpy(&v, A64_PTR(a), 4); return v; }
A64_INLINE uint64_t recomp_load64(GuestContext *c, uint64_t a) { uint64_t v; (void)c; memcpy(&v, A64_PTR(a), 8); return v; }
A64_INLINE void recomp_store8(GuestContext *c, uint64_t a, uint64_t v) { (void)c; *(uint8_t *)A64_PTR(a) = (uint8_t)v; A64_MARK(a, 1); }
A64_INLINE void recomp_store16(GuestContext *c, uint64_t a, uint64_t v) { uint16_t t = (uint16_t)v; (void)c; memcpy(A64_PTR(a), &t, 2); A64_MARK(a, 2); }
A64_INLINE void recomp_store32(GuestContext *c, uint64_t a, uint64_t v) { uint32_t t = (uint32_t)v; (void)c; memcpy(A64_PTR(a), &t, 4); A64_MARK(a, 4); }
A64_INLINE void recomp_store64(GuestContext *c, uint64_t a, uint64_t v) { (void)c; memcpy(A64_PTR(a), &v, 8); A64_MARK(a, 8); }
/* Stores through SP (stack_stores in lift/a64_lift.py): the guest stack is never memory the GPU reads, so they mark no
page. They are a quarter of TOTK's store sites (prologue saves, nearly every STP). */
A64_INLINE void recomp_store8_sp(GuestContext *c, uint64_t a, uint64_t v) { (void)c; *(uint8_t *)A64_PTR(a) = (uint8_t)v; }
A64_INLINE void recomp_store16_sp(GuestContext *c, uint64_t a, uint64_t v) { uint16_t t = (uint16_t)v; (void)c; memcpy(A64_PTR(a), &t, 2); }
A64_INLINE void recomp_store32_sp(GuestContext *c, uint64_t a, uint64_t v) { uint32_t t = (uint32_t)v; (void)c; memcpy(A64_PTR(a), &t, 4); }
A64_INLINE void recomp_store64_sp(GuestContext *c, uint64_t a, uint64_t v) { (void)c; memcpy(A64_PTR(a), &v, 8); }
A64_INLINE void recomp_stp32_sp(GuestContext *c, uint64_t a, uint64_t v0, uint64_t v1) { recomp_store32_sp(c, a, v0); recomp_store32_sp(c, a + 4, v1); }
A64_INLINE void recomp_stp64_sp(GuestContext *c, uint64_t a, uint64_t v0, uint64_t v1) { recomp_store64_sp(c, a, v0); recomp_store64_sp(c, a + 8, v1); }
A64_INLINE void recomp_ldp32(GuestContext *c, uint64_t a, uint64_t *lo, uint64_t *hi) { *lo = recomp_load32(c, a); *hi = recomp_load32(c, a + 4); }
A64_INLINE void recomp_ldp64(GuestContext *c, uint64_t a, uint64_t *lo, uint64_t *hi) { *lo = recomp_load64(c, a); *hi = recomp_load64(c, a + 8); }
/* (a pair marks once, for its whole span) */
A64_INLINE void recomp_stp32(GuestContext *c, uint64_t a, uint64_t v0, uint64_t v1) { recomp_store32_sp(c, a, v0); recomp_store32_sp(c, a + 4, v1); A64_MARK(a, 8); }
A64_INLINE void recomp_stp64(GuestContext *c, uint64_t a, uint64_t v0, uint64_t v1) { recomp_store64_sp(c, a, v0); recomp_store64_sp(c, a + 8, v1); A64_MARK(a, 16); }
/* Everything is lifted at its final guest address, so the translator's module base is a constant 0. */
#define g_module_base ((uint64_t)0)
/* ---- control flow, as ppc-kit spells it -------------------------------------------------------------- */
#if defined(__wasm__) && !defined(__wasm_tail_call__)
#define TAILCALL(f) do { f(c); return; } while (0)
#else
#define TAILCALL(f) __attribute__((musttail)) return f(c)
#endif
/* ---- the lifter's runtime (rt/a64_rt.c) ------------------------------------------------------------- */
typedef void (*A64Fn)(Ctx *A64_NOESC);
A64Fn a64_lookup(uint64_t addr); /* function at a guest address, or NULL */
void a64_icall(Ctx *A64_NOESC c, uint64_t target); /* BLR: indirect call */
/* (hookshot) setjmp in lifted code: a call of a function that calls __setjmp is wrapped in a host __builtin_setjmp
on a slot (pushed per thread with that function's setjmp return addresses, popped after the call); the guest
longjmp's final BR to one of them comes back to the newest such slot through the host's a64_call_miss
(host/hos_setjmp.c), and the caller runs the function's code from that address (recomp_sj_target) */
void **recomp_sj_push(Ctx *A64_NOESC c, uint64_t r0, uint64_t r1, uint64_t r2, uint64_t r3);
uint64_t recomp_sj_target(void **slot);
void recomp_sj_pop(void **slot);
void a64_ijump(Ctx *A64_NOESC c, uint64_t target); /* BR that is not a jump table: indirect tail call */
/* The lifted BLR / BR: a cache per call site, filled by its first target (the guest address in the top 32 bits, the
function as an offset from a64_lookup in the low 32). A site calling that target again reads no shared table and
has an indirect branch of its own to predict; other targets go through a64_icall_site / a64_ijump_site, which try
the site's second slot (its second target) and else look them up as a64_icall does. A64_NO_SITE_CACHE: the plain
calls. */
void a64_icall_site(Ctx *A64_NOESC c, uint64_t target, uint64_t *site);
void a64_ijump_site(Ctx *A64_NOESC c, uint64_t target, uint64_t *site);
#ifdef A64_NO_SITE_CACHE
#define A64_ICALL(c, t) a64_icall(c, t)
#define A64_IJUMP(c, t) a64_ijump(c, t)
#else
#define A64_SITE_CALL(c, t, slow) do { \
static uint64_t a64_site_[2]; \
const uint64_t a64_site_t_ = (t), a64_site_e_ = __atomic_load_n(&a64_site_[0], __ATOMIC_RELAXED); \
if (__builtin_expect(a64_site_e_ >> 32 == a64_site_t_ && a64_site_e_ != 0, 1)) \
((A64Fn)((intptr_t)&a64_lookup + (int32_t)(uint32_t)a64_site_e_))(c); \
else slow(c, a64_site_t_, a64_site_); \
} while (0) /* (its names must not be ones the lifted code passes in, such as _t) */
#define A64_ICALL(c, t) A64_SITE_CALL(c, t, a64_icall_site)
#define A64_IJUMP(c, t) A64_SITE_CALL(c, t, a64_ijump_site)
#endif
void a64_svc(Ctx *A64_NOESC c, uint32_t imm); /* SVC #imm (sdk only) */
void a64_trap(Ctx *A64_NOESC c, uint64_t pc, uint32_t insn); /* BRK, HLT, UDF and words that are not code */
void a64_ret_mismatch(Ctx *A64_NOESC c, uint64_t pc); /* RET to something other than the caller (debug builds) */
#include "a64_suyu.h"
#include "a64_fpx.h"
/* ---- A64_INLINE_RT (experiment, off): LDXR/STXR, CLREX, DMB and the high multiplies inline in lifted code instead of
calls to a64_rt.c / a64_suyu.c. Measured 2026-10-21 (castle, 3 interleaved rounds at -O3): 69.5 -> 68.4 fps, game
threads +0.7 ms CPU a frame, though an LDXR/STXR pair becomes one inline lock cmpxchg: not kept. */
#if defined(A64_INLINE_RT) && !defined(A64_RT_IMPL)
A64_INLINE uint64_t a64_i_load_n(uint64_t a, uint32_t size) {
switch (size) {
case 1: return __atomic_load_n((uint8_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
case 2: return __atomic_load_n((uint16_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
case 4: return __atomic_load_n((uint32_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
default: return __atomic_load_n((uint64_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
}
}
A64_INLINE int a64_i_cas_n(uint64_t a, uint32_t size, uint64_t expect, uint64_t value) {
A64_MARK(a, size);
switch (size) {
case 1: { uint8_t e = (uint8_t)expect; return __atomic_compare_exchange_n((uint8_t *)A64_PTR(a), &e, (uint8_t)value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
case 2: { uint16_t e = (uint16_t)expect; return __atomic_compare_exchange_n((uint16_t *)A64_PTR(a), &e, (uint16_t)value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
case 4: { uint32_t e = (uint32_t)expect; return __atomic_compare_exchange_n((uint32_t *)A64_PTR(a), &e, (uint32_t)value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
default: { uint64_t e = expect; return __atomic_compare_exchange_n((uint64_t *)A64_PTR(a), &e, value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
}
}
A64_INLINE uint64_t a64_i_ldxr(GuestContext *c, uint64_t addr, uint32_t size) {
const uint64_t v = a64_i_load_n(addr, size);
c->excl_addr = addr; c->excl_size = size; c->excl_lo = v; c->excl_valid = 1;
return v;
}
A64_INLINE uint32_t a64_i_stxr(GuestContext *c, uint64_t addr, uint32_t size, uint64_t value) {
const int ok = c->excl_valid && c->excl_addr == addr && c->excl_size == size && a64_i_cas_n(addr, size, c->excl_lo, value);
c->excl_valid = 0;
return ok ? 0 : 1;
}
A64_INLINE void a64_i_clrex(GuestContext *c) { c->excl_valid = 0; }
A64_INLINE void a64_i_barrier(void) { __atomic_thread_fence(__ATOMIC_SEQ_CST); }
#if defined(__SIZEOF_INT128__)
A64_INLINE uint64_t a64_i_umulh(uint64_t a, uint64_t b) { return (uint64_t)((unsigned __int128)a * b >> 64); }
A64_INLINE uint64_t a64_i_smulh(uint64_t a, uint64_t b) { return (uint64_t)((__int128)(int64_t)a * (int64_t)b >> 64); }
#define recomp_umulh a64_i_umulh
#define recomp_smulh a64_i_smulh
#endif
#define recomp_ldxr a64_i_ldxr
#define recomp_stxr a64_i_stxr
#define recomp_clrex a64_i_clrex
#define recomp_barrier a64_i_barrier
#endif
#endif

333
third_party/a64-kit/rt/a64_rt.c vendored Normal file
View File

@@ -0,0 +1,333 @@
/* a64-kit runtime for lifted code: dispatch, indirect branches, traps, the exclusive monitor, the counter.
The OS layer (hos/) overrides the weak hooks: a64_svc, a64_on_trap, a64_cntpct_host. */
#define A64_RT_IMPL /* (the out-of-line exclusive monitor and barrier: rt/a64.h inlines them in lifted code) */
#include "a64.h"
#include <stdio.h>
#include <stdlib.h>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <time.h>
#endif
#if defined(_MSC_VER) && !defined(__clang__)
#define A64_WEAK
#else
#define A64_WEAK __attribute__((weak))
#endif
extern const uint32_t a64_fn_count;
extern const uint32_t a64_fn_addr[];
extern const A64Fn a64_fn_ptr[];
/* Indirect calls (C++ virtual calls above all) look their target up here. A direct-mapped cache in front of the
binary search over every function: each slot is one 64-bit word (address << 32 | the function's offset from a64_lookup), written and read
whole, so threads racing on a slot see an old entry or a new one, never a mix. */
static uint64_t lookup_cache[1 << 18];
#define A64_NO_FN 0x7FFFFFFF /* a cached slot's offset when the address has no lifted function */
/* Addresses the OS layer made at run time that are plain host functions (host calls without user data: every NVN proc)
are answered like lifted functions, so a64_lookup's cache and each call site's slots hold them and a call goes
straight to the handler. Before, every NVN call (tens of thousands a frame, on the game's recording threads) went
site_call -> a64_lookup -> a64_call_miss -> its handler. */
A64_WEAK A64Fn a64_lookup_host(uint64_t addr) { (void)addr; return NULL; }
A64Fn a64_lookup(uint64_t addr) {
if (addr >> 32 || !addr) return NULL;
uint32_t a = (uint32_t)addr, lo = 0, hi = a64_fn_count;
uint64_t *slot = &lookup_cache[(a >> 2 ^ a >> 20) & 0x3FFFF];
const uint64_t e = __atomic_load_n(slot, __ATOMIC_RELAXED);
const intptr_t anchor = (intptr_t)&a64_lookup;
if ((uint32_t)(e >> 32) == a) return (int32_t)(uint32_t)e == A64_NO_FN ? NULL : (A64Fn)(anchor + (int32_t)(uint32_t)e);
while (lo < hi) {
uint32_t mid = (lo + hi) >> 1;
if (a64_fn_addr[mid] < a) lo = mid + 1;
else hi = mid;
}
if (lo < a64_fn_count && a64_fn_addr[lo] == a) {
const intptr_t delta = (intptr_t)a64_fn_ptr[lo] - anchor;
if (delta == (int32_t)delta) __atomic_store_n(slot, (uint64_t)a << 32 | (uint32_t)(int32_t)delta, __ATOMIC_RELAXED);
return a64_fn_ptr[lo];
}
A64Fn h = a64_lookup_host(addr);
if (h) {
const intptr_t delta = (intptr_t)h - anchor;
if (delta == (int32_t)delta && (int32_t)delta != A64_NO_FN)
__atomic_store_n(slot, (uint64_t)a << 32 | (uint32_t)(int32_t)delta, __ATOMIC_RELAXED);
return h;
}
/* (remembered too: calls into the OS layer's other host calls searched the whole table each time) */
__atomic_store_n(slot, (uint64_t)a << 32 | (uint32_t)A64_NO_FN, __ATOMIC_RELAXED);
return NULL;
}
/* Called when a thread cannot continue (trap, missing function). The OS layer decides what that means. */
A64_WEAK void a64_on_trap(Ctx *c, uint64_t pc, uint32_t insn, const char *why) {
fprintf(stderr, "[a64] %s at %#llx (insn %08x), lr %#llx sp %#llx\n", why, (unsigned long long)pc, insn,
(unsigned long long)c->x[30], (unsigned long long)c->x[31]);
fflush(stderr);
abort();
}
void a64_trap(Ctx *c, uint64_t pc, uint32_t insn) {
c->pc = pc;
c->halted = 1;
a64_on_trap(c, pc, insn, insn ? "trap" : "branch to a non-function");
}
/* Addresses the OS layer made at run time (host calls: e.g. NVN procs handed out by nvnDeviceGetProcAddress) are
not in the lifted function table; the OS layer claims them here. Returns 1 if it ran the call. */
A64_WEAK int a64_call_miss(Ctx *c, uint64_t target) { (void)c; (void)target; return 0; }
/* (hookshot) every BR that is not a jump table and misses its site's cache asks this first: a longjmp's BR to a
setjmp return address (host/hos_setjmp.c), which is an entry as well, must unwind the host stack rather than
call that entry (it does not return when it is one). Targets it takes are never cached at the site. */
A64_WEAK void a64_ijump_hook(Ctx *c, uint64_t target) { (void)c; (void)target; }
void a64_icall(Ctx *c, uint64_t target) {
A64Fn f = a64_lookup(target);
if (!f) {
if (a64_call_miss(c, target)) return;
c->pc = target;
c->halted = 1;
a64_on_trap(c, target, 0, "indirect call to an address with no function");
return;
}
f(c);
}
void a64_ijump(Ctx *c, uint64_t target) {
a64_ijump_hook(c, target);
A64Fn f = a64_lookup(target);
if (!f) {
if (a64_call_miss(c, target)) return;
c->pc = target;
c->halted = 1;
a64_on_trap(c, target, 0, "indirect jump to an address with no function");
return;
}
f(c);
}
/* A64_SITE_PROFILE=<file> (profiling runs, for the lifter's A64_DEVIRT): call sites remember no targets, so every BLR
comes through here and counts as (call site, target), the site being the instruction before the return address the
lifted code put in x30. Every ~5 s the file is rewritten, "site target calls" a line (hex, hex, decimal);
scripts/devirt.py picks each site's dominant target from it. */
#define SITE_PROF_SLOTS (1u << 20)
static struct { uint64_t key, n; } *site_prof; /* key = site << 32 | target, open addressing */
static int site_prof_on = -1;
static volatile long site_prof_writing;
static uint64_t site_prof_last;
static uint64_t prof_ms(void) {
#if defined(_WIN32)
return GetTickCount64();
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
#endif
}
static void site_prof_write(void) {
if (__atomic_exchange_n(&site_prof_writing, 1, __ATOMIC_ACQUIRE)) return;
const uint64_t now = prof_ms();
if (now - site_prof_last >= 5000) {
site_prof_last = now;
FILE *f = fopen(getenv("A64_SITE_PROFILE"), "w");
if (f) {
for (uint32_t i = 0; i < SITE_PROF_SLOTS; i++) {
const uint64_t k = __atomic_load_n(&site_prof[i].key, __ATOMIC_RELAXED);
if (k) fprintf(f, "%x %x %llu\n", (uint32_t)(k >> 32), (uint32_t)k,
(unsigned long long)__atomic_load_n(&site_prof[i].n, __ATOMIC_RELAXED));
}
fclose(f);
}
}
__atomic_store_n(&site_prof_writing, 0, __ATOMIC_RELEASE);
}
static void site_prof_count(uint64_t site, uint64_t target) {
if (site >> 32 || target >> 32) return;
const uint64_t key = site << 32 | target;
uint32_t i = (uint32_t)((key * 0x9E3779B97F4A7C15ULL) >> 44);
for (uint32_t probe = 0; probe < 64; probe++, i = (i + 1) & (SITE_PROF_SLOTS - 1)) {
uint64_t k = __atomic_load_n(&site_prof[i].key, __ATOMIC_RELAXED);
if (!k && __atomic_compare_exchange_n(&site_prof[i].key, &k, key, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED)) k = key;
if (k == key) {
if ((__atomic_add_fetch(&site_prof[i].n, 1, __ATOMIC_RELAXED) & 0xFFFF) == 0) site_prof_write();
return;
}
}
}
static int site_profiling(void) {
if (site_prof_on < 0) {
int on = getenv("A64_SITE_PROFILE") != NULL;
if (on) {
site_prof = calloc(SITE_PROF_SLOTS, sizeof *site_prof);
on = site_prof != NULL;
site_prof_last = prof_ms();
}
site_prof_on = on;
}
return site_prof_on;
}
/* A64_ICALL / A64_IJUMP (a64.h) when the site's first slot does not hold the target: its second slot, else looked
up and remembered in a free slot (only the first two targets: a site calling many would otherwise keep rewriting a
line other threads read) */
static void site_call(Ctx *c, uint64_t target, uint64_t *site, int call, const char *why) {
if (site_prof_on && site_profiling()) { /* (A64_SITE_PROFILE: nothing remembered, every call counted) */
if (call) { /* (a BR's x30 is not its site) */
site_prof_count(c->x[30] - 4, target);
a64_icall(c, target);
} else a64_ijump(c, target);
return;
}
const uint64_t e = __atomic_load_n(&site[1], __ATOMIC_RELAXED);
if (e >> 32 == target && e) { /* (the site's second target) */
((A64Fn)((intptr_t)&a64_lookup + (int32_t)(uint32_t)e))(c);
return;
}
A64Fn f = a64_lookup(target);
if (!f) {
if (a64_call_miss(c, target)) return;
c->pc = target;
c->halted = 1;
a64_on_trap(c, target, 0, why);
return;
}
const intptr_t delta = (intptr_t)f - (intptr_t)&a64_lookup;
if (delta == (int32_t)delta) { /* (the first free slot of the two; a full site keeps its first two targets) */
const uint64_t entry = target << 32 | (uint32_t)(int32_t)delta;
if (!__atomic_load_n(&site[0], __ATOMIC_RELAXED)) __atomic_store_n(&site[0], entry, __ATOMIC_RELAXED);
else if (!e) __atomic_store_n(&site[1], entry, __ATOMIC_RELAXED);
}
f(c);
}
void a64_icall_site(Ctx *c, uint64_t target, uint64_t *site) {
site_call(c, target, site, 1, "indirect call to an address with no function");
}
void a64_ijump_site(Ctx *c, uint64_t target, uint64_t *site) {
a64_ijump_hook(c, target);
site_call(c, target, site, 0, "indirect jump to an address with no function");
}
A64_WEAK void a64_svc(Ctx *c, uint32_t imm) {
char why[32];
snprintf(why, sizeof why, "svc #%#x", imm);
a64_on_trap(c, c->pc, 0xD4000001u | (imm << 5), why);
}
void a64_ret_mismatch(Ctx *c, uint64_t pc) { a64_on_trap(c, pc, 0, "return to an address that is not the caller"); }
/* Generated import stubs (gen/a64_stubs.c) land here: log the first call, return 0. */
A64_WEAK void a64_unimplemented(Ctx *c, const char *sym, int *seen) {
if (!*seen) {
*seen = 1;
fprintf(stderr, "[a64] unimplemented import %s (lr %#llx)\n", sym, (unsigned long long)c->x[30]);
}
c->x[0] = 0;
}
void recomp_unhandled(GuestContext *c, uint32_t insn, uint64_t pc) { a64_trap(c, pc, insn); }
void recomp_ic_ivau(GuestContext *c, uint64_t address, int v) { (void)c; (void)address; (void)v; }
void recomp_barrier(void) { __atomic_thread_fence(__ATOMIC_SEQ_CST); }
/* ---- exclusive monitor --------------------------------------------------------------------------------
LDXR remembers (address, size, value). STXR succeeds only if the address and size match and memory still
holds that value, by compare-and-swap, so a lock taken by one host thread is respected by every other. */
static uint64_t load_n(uint64_t a, uint32_t size) {
switch (size) {
case 1: return __atomic_load_n((uint8_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
case 2: return __atomic_load_n((uint16_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
case 4: return __atomic_load_n((uint32_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
default: return __atomic_load_n((uint64_t *)A64_PTR(a), __ATOMIC_SEQ_CST);
}
}
#if defined(A64_WRITE_TRACK)
uint8_t a64_dirty[1u << 20]; /* (rt/a64.h A64_MARK) */
#endif
static int cas_n(uint64_t a, uint32_t size, uint64_t expect, uint64_t value) {
A64_MARK(a, size); /* (marked whether or not it stores: harmless) */
switch (size) {
case 1: { uint8_t e = (uint8_t)expect; return __atomic_compare_exchange_n((uint8_t *)A64_PTR(a), &e, (uint8_t)value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
case 2: { uint16_t e = (uint16_t)expect; return __atomic_compare_exchange_n((uint16_t *)A64_PTR(a), &e, (uint16_t)value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
case 4: { uint32_t e = (uint32_t)expect; return __atomic_compare_exchange_n((uint32_t *)A64_PTR(a), &e, (uint32_t)value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
default: { uint64_t e = expect; return __atomic_compare_exchange_n((uint64_t *)A64_PTR(a), &e, value, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); }
}
}
uint64_t recomp_ldxr(GuestContext *c, uint64_t addr, uint32_t size) {
uint64_t v = load_n(addr, size);
c->excl_addr = addr; c->excl_size = size; c->excl_lo = v; c->excl_valid = 1;
return v;
}
uint32_t recomp_stxr(GuestContext *c, uint64_t addr, uint32_t size, uint64_t value) {
int ok = c->excl_valid && c->excl_addr == addr && c->excl_size == size && cas_n(addr, size, c->excl_lo, value);
c->excl_valid = 0;
return ok ? 0 : 1;
}
void recomp_ldxp(GuestContext *c, uint64_t addr, uint32_t size, uint64_t *lo, uint64_t *hi) {
if (size == 4) {
uint64_t v = load_n(addr, 8);
*lo = (uint32_t)v; *hi = v >> 32;
} else {
/* 128-bit: two loads. Single-copy atomicity of the pair is not guaranteed here; the STXP below is. */
*lo = load_n(addr, 8); *hi = load_n(addr + 8, 8);
}
c->excl_addr = addr; c->excl_size = 2 * size; c->excl_lo = *lo; c->excl_hi = *hi; c->excl_valid = 1;
}
uint32_t recomp_stxp(GuestContext *c, uint64_t addr, uint32_t size, uint64_t lo, uint64_t hi) {
int ok = c->excl_valid && c->excl_addr == addr && c->excl_size == 2 * size;
if (ok && size == 4) {
ok = cas_n(addr, 8, (c->excl_lo & 0xFFFFFFFFu) | (c->excl_hi << 32), (lo & 0xFFFFFFFFu) | (hi << 32));
} else if (ok) {
#if defined(__SIZEOF_INT128__) && !defined(__wasm__)
unsigned __int128 e = ((unsigned __int128)c->excl_hi << 64) | c->excl_lo;
unsigned __int128 v = ((unsigned __int128)hi << 64) | lo;
ok = __atomic_compare_exchange_n((unsigned __int128 *)A64_PTR(addr), &e, v, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
#else
ok = load_n(addr, 8) == c->excl_lo && load_n(addr + 8, 8) == c->excl_hi;
if (ok) { recomp_store64(c, addr, lo); recomp_store64(c, addr + 8, hi); }
#endif
}
c->excl_valid = 0;
return ok ? 0 : 1;
}
void recomp_clrex(GuestContext *c) { c->excl_valid = 0; }
/* ---- CNTPCT_EL0: the 19.2 MHz counter ---------------------------------------------------------------- */
A64_WEAK uint64_t a64_cntpct_host(void) {
#if defined(_WIN32)
static LARGE_INTEGER base;
static uint64_t mult;
LARGE_INTEGER now;
if (!__atomic_load_n(&mult, __ATOMIC_ACQUIRE)) {
LARGE_INTEGER f, b;
QueryPerformanceFrequency(&f);
QueryPerformanceCounter(&b);
base = b;
__atomic_store_n(&mult, (19200000ULL << 32) / (uint64_t)f.QuadPart, __ATOMIC_RELEASE);
}
QueryPerformanceCounter(&now);
const uint64_t d = (uint64_t)(now.QuadPart - base.QuadPart);
return (uint64_t)(((unsigned __int128)d * mult) >> 32);
#else
static uint64_t base;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
uint64_t ns = (uint64_t)ts.tv_sec * 1000000000ULL + ts.tv_nsec;
if (!base) base = ns;
return (ns - base) * 192ULL / 10000ULL;
#endif
}
uint64_t recomp_cntpct(GuestContext *c) { (void)c; return a64_cntpct_host(); }

278
third_party/a64-kit/tests/insn_test.py vendored Normal file
View File

@@ -0,0 +1,278 @@
"""Every instruction form a game uses, run in Unicorn and as lifted C, compared (Rexcomp's test_insns.py method).
Samples real encodings from a game's code (up to --per encodings per mnemonic form, NEON keyed by arrangement),
gives each --states random register states (FPCR 0 and FPCR.FZ, as TOTK runs), runs one instruction in Unicorn's
AArch64 and in C from a64emit + rt/a64.h, and compares X0-X30, SP, NZCV, FPSR, V0-V31 and the scratch memory.
Memory operands get a base register inside the scratch area and a small index, so loads and stores are tested too.
Usage: python insn_test.py <image_dir from nso.py> [--modules main,sdk] [--per 6] [--states 12] [--seed 1]
[--fpsr] (also compare FPSR cumulative flags) [--list] (show every failing form)
Needs: unicorn, capstone, emsdk clang (native). Builds in a temp folder.
"""
import argparse
import collections
import hashlib
import json
import os
import random
import struct
import subprocess
import sys
import tempfile
import capstone
import unicorn
from unicorn import arm64_const as A
HERE = os.path.dirname(os.path.abspath(__file__))
KIT = os.path.join(HERE, "..")
sys.path.insert(0, os.path.join(KIT, "lift"))
sys.path.insert(0, os.path.join(KIT, "tools"))
import a64emit, a64_lift, a64_rtgen, toolchain
CODE = 0x10000
SCRATCH = 0x100000
SCRATCH_SIZE = 0x10000
MEM_SIZE = SCRATCH + SCRATCH_SIZE
FZ = 1 << 24
XREG = [getattr(A, "UC_ARM64_REG_X%d" % i) for i in range(29)] + [A.UC_ARM64_REG_X29, A.UC_ARM64_REG_X30]
QREG = [getattr(A, "UC_ARM64_REG_Q%d" % i) for i in range(32)]
STATE = struct.Struct("<32Q4B4xQQ64Q") # x0-x30, sp | n z c v | fpcr fpsr | v0-v31 (lo, hi)
def sample(image_dir, modules, per, rng):
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
groups = collections.defaultdict(list)
for mod in modules:
meta = json.load(open(os.path.join(image_dir, mod + ".json")))
img = open(os.path.join(image_dir, mod + ".bin"), "rb").read()
t = next(s for s in meta["segments"] if s["name"] == ".text")
words = set(struct.unpack_from("<%dI" % (t["size"] // 4), img, t["offset"]))
for w in words:
if a64_lift.classify(w, CODE)[0] != "op":
continue
ins = next(md.disasm(struct.pack("<I", w), CODE), None)
if ins is None or ins.mnemonic in ("msr", "mrs", "sys", "dc", "ic", "hint", "yield", "wfe", "wfi",
"sev", "sevl", "udf", "brk", "hlt", "prfm", "prfum", "clrex",
"dmb", "dsb", "isb", "nop"):
continue
arr = sorted(set(op.vas for op in ins.operands if getattr(op, "vas", 0)))
groups[(ins.mnemonic, tuple(arr))].append(w)
picked = []
for key in sorted(groups):
ws = groups[key]
rng.shuffle(ws)
picked += [(key, w) for w in ws[:per]]
return picked
def mem_regs(w):
"""(base register number or 'sp', index register number or None) of a memory operand, or None"""
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.detail = True
ins = next(md.disasm(struct.pack("<I", w), CODE), None)
for op in ins.operands if ins else ():
if op.type == capstone.arm64.ARM64_OP_MEM:
base = ins.reg_name(op.mem.base) if op.mem.base else None
idx = ins.reg_name(op.mem.index) if op.mem.index else None
num = lambda r: None if r is None else ("sp" if r in ("sp", "wsp") else int(r[1:]) if r[1:].isdigit() else None)
return num(base), num(idx)
return None
def rand_state(rng, w):
x = [rng.getrandbits(64) if rng.random() < 0.7 else rng.choice([0, 1, 0xFFFFFFFF, 0x80000000, 2 ** 63, 2 ** 64 - 1, rng.getrandbits(8)])
for _ in range(31)]
sp = SCRATCH + 0x8000 + 16 * rng.randrange(128)
m = mem_regs(w)
if m:
base, idx = m
addr = SCRATCH + 0x4000 + 16 * rng.randrange(512)
if base == "sp":
sp = addr
elif base is not None:
x[base] = addr
if idx is not None and idx != base:
x[idx] = rng.randrange(64)
v = []
for _ in range(32):
kind = rng.random()
if kind < 0.5:
v += [rng.getrandbits(64), rng.getrandbits(64)]
else: # lanes of "reasonable" floats, so FP paths see normal values too
lanes = [struct.unpack("<I", struct.pack("<f", rng.uniform(-1000, 1000)))[0] for _ in range(4)]
v += [lanes[0] | lanes[1] << 32, lanes[2] | lanes[3] << 32]
nzcv = [rng.getrandbits(1) for _ in range(4)]
fpcr = rng.choice([0, FZ])
return x + [sp], nzcv, fpcr, 0x10 if rng.random() < 0.5 else 0, v # fpsr: IXC set half the time (FPX1 gate)
def run_unicorn(w, state, mem):
x, nzcv, fpcr, fpsr, v = state
uc = unicorn.Uc(unicorn.UC_ARCH_ARM64, unicorn.UC_MODE_ARM)
uc.mem_map(0, MEM_SIZE)
uc.mem_write(CODE, struct.pack("<I", w))
uc.mem_write(SCRATCH, mem)
for i in range(31):
uc.reg_write(XREG[i], x[i])
uc.reg_write(A.UC_ARM64_REG_SP, x[31])
uc.reg_write(A.UC_ARM64_REG_NZCV, nzcv[0] << 31 | nzcv[1] << 30 | nzcv[2] << 29 | nzcv[3] << 28)
uc.reg_write(A.UC_ARM64_REG_FPCR, fpcr)
uc.reg_write(A.UC_ARM64_REG_FPSR, fpsr)
for i in range(32):
uc.reg_write(QREG[i], v[2 * i] | v[2 * i + 1] << 64)
try:
uc.emu_start(CODE, CODE + 4, count=1)
except unicorn.UcError as e:
return None, str(e)
ox = [uc.reg_read(XREG[i]) for i in range(31)] + [uc.reg_read(A.UC_ARM64_REG_SP)]
f = uc.reg_read(A.UC_ARM64_REG_NZCV)
on = [(f >> 31) & 1, (f >> 30) & 1, (f >> 29) & 1, (f >> 28) & 1]
ov = []
for i in range(32):
q = uc.reg_read(QREG[i])
ov += [q & (2 ** 64 - 1), q >> 64]
return (ox, on, uc.reg_read(A.UC_ARM64_REG_FPCR), uc.reg_read(A.UC_ARM64_REG_FPSR), ov,
hashlib.sha1(bytes(uc.mem_read(SCRATCH, SCRATCH_SIZE))).digest()), None
def pack(state):
x, nzcv, fpcr, fpsr, v = state
return STATE.pack(*(x + nzcv + [fpcr, fpsr] + v))
def build_harness(tmp, picked):
a64_rtgen.write(tmp)
texts, flags = a64emit.translate([(CODE, w) for _, w in picked])
used = set()
texts = [a64_lift.outline_fpx(t, used) for t in texts] # the same FPX helpers the lifter emits
open(os.path.join(tmp, "a64_fpx.h"), "w", newline="\n").write(a64_lift.fpx_header(used))
src = ['#include "a64.h"', "#include <stdio.h>", "#include <stdlib.h>", "#include <windows.h>"]
for i, ((key, w), t, f) in enumerate(zip(picked, texts, flags)):
body = "c->halted = 7;" if f else t
src.append("static void t%d(Ctx *__restrict c) { %s }" % (i, body))
src.append("static void (*const T[])(Ctx *) = {%s};" % ",".join("t%d" % i for i in range(len(picked))))
src.append(r"""
void a64_trap(Ctx *c, uint64_t pc, uint32_t insn) { (void)pc; (void)insn; c->halted = 9; }
void recomp_unhandled(GuestContext *c, uint32_t i, uint64_t pc) { (void)i; (void)pc; c->halted = 7; }
void recomp_barrier(void) {}
void recomp_ic_ivau(GuestContext *c, uint64_t a, int v) { (void)c; (void)a; (void)v; }
uint64_t recomp_cntpct(GuestContext *c) { (void)c; return 0; }
static uint64_t ex_addr; static int ex_valid;
uint64_t recomp_ldxr(GuestContext *c, uint64_t a, uint32_t s) { uint64_t v = 0; memcpy(&v, A64_PTR(a), s); ex_addr = a; ex_valid = 1; return v; }
uint32_t recomp_stxr(GuestContext *c, uint64_t a, uint32_t s, uint64_t v) { if (!ex_valid || ex_addr != a) return 1; ex_valid = 0; memcpy(A64_PTR(a), &v, s); return 0; }
void recomp_ldxp(GuestContext *c, uint64_t a, uint32_t s, uint64_t *lo, uint64_t *hi) { *lo = *hi = 0; memcpy(lo, A64_PTR(a), s); memcpy(hi, A64_PTR(a + s), s); ex_addr = a; ex_valid = 1; }
uint32_t recomp_stxp(GuestContext *c, uint64_t a, uint32_t s, uint64_t lo, uint64_t hi) { if (!ex_valid || ex_addr != a) return 1; ex_valid = 0; memcpy(A64_PTR(a), &lo, s); memcpy(A64_PTR(a + s), &hi, s); return 0; }
void recomp_clrex(GuestContext *c) { ex_valid = 0; }
int main(int argc, char **argv) {
FILE *in = fopen(argv[1], "rb"), *out = fopen(argv[2], "wb");
if (VirtualAlloc(A64_MEM, %d, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) != A64_MEM) return 3;
static uint8_t state[%d];
unsigned idx;
while (fread(&idx, 4, 1, in) == 1) {
fread(state, sizeof state, 1, in);
fread(A64_MEM + %d, %d, 1, in);
Ctx c; memset(&c, 0, sizeof c);
memcpy(c.x, state, 256);
memcpy(&c.n, state + 256, 4);
memcpy(&c.fpcr, state + 264, 8); memcpy(&c.fpsr, state + 272, 8);
memcpy(c.vreg, state + 280, 512);
ex_valid = 0;
T[idx](&c);
memcpy(state, c.x, 256); memcpy(state + 256, &c.n, 4);
memcpy(state + 264, &c.fpcr, 8); memcpy(state + 272, &c.fpsr, 8); memcpy(state + 280, c.vreg, 512);
fwrite(&c.halted, 4, 1, out);
fwrite(state, sizeof state, 1, out);
fwrite(A64_MEM + %d, %d, 1, out);
}
fclose(out);
return 0;
}""" % (MEM_SIZE, STATE.size, SCRATCH, SCRATCH_SIZE, SCRATCH, SCRATCH_SIZE))
path = os.path.join(tmp, "harness.c")
open(path, "w", newline="\n").write("\n".join(src))
exe = os.path.join(tmp, "harness.exe")
cmd = [toolchain.need(toolchain.find("clang"))] + toolchain.native_target() + toolchain.native_link() + \
["-O1", "-g0", "-Wno-everything", "-I" + tmp, "-I" + os.path.join(KIT, "rt"), path,
os.path.join(tmp, "a64_suyu.c"), "-o", exe]
subprocess.run(cmd, check=True)
return exe, flags
def main():
p = argparse.ArgumentParser()
p.add_argument("image_dir")
p.add_argument("--modules", default="main,sdk")
p.add_argument("--per", type=int, default=6)
p.add_argument("--states", type=int, default=12)
p.add_argument("--seed", type=int, default=1)
p.add_argument("--fpsr", action="store_true")
p.add_argument("--list", action="store_true")
a = p.parse_args()
rng = random.Random(a.seed)
picked = sample(a.image_dir, a.modules.split(","), a.per, rng)
print("%d encodings in %d forms" % (len(picked), len(set(k for k, _ in picked))), flush=True)
tmp = tempfile.mkdtemp(prefix="a64_insn_")
exe, flags = build_harness(tmp, picked)
cases, expect = [], []
base_mem = bytes(rng.getrandbits(8) for _ in range(4096)) * (SCRATCH_SIZE // 4096)
for i, (key, w) in enumerate(picked):
for _ in range(a.states):
st = rand_state(rng, w)
res, err = run_unicorn(w, st, base_mem)
if res is None:
continue # Unicorn faulted (e.g. an unmapped address): not a comparable case
cases.append((i, st))
expect.append(res)
inp = os.path.join(tmp, "in.bin")
with open(inp, "wb") as f:
for i, st in cases:
f.write(struct.pack("<I", i) + pack(st) + base_mem)
outp = os.path.join(tmp, "out.bin")
subprocess.run([exe, inp, outp], check=True)
fails = collections.defaultdict(list)
passes = collections.Counter()
rec = 4 + STATE.size + SCRATCH_SIZE
with open(outp, "rb") as f:
for (i, st), exp in zip(cases, expect):
blob = f.read(rec)
halted = struct.unpack_from("<i", blob, 0)[0]
vals = STATE.unpack_from(blob, 4)
mem = hashlib.sha1(blob[4 + STATE.size:]).digest()
key, w = picked[i]
got = (list(vals[:32]), list(vals[32:36]), vals[36], vals[37], list(vals[38:]), mem)
ex_x, ex_n, ex_fpcr, ex_fpsr, ex_v, ex_mem = exp
diffs = []
if halted:
diffs.append("halted %d (unhandled)" % halted)
else:
for r in range(32):
if got[0][r] != ex_x[r]:
diffs.append("%s %#x != %#x" % ("sp" if r == 31 else "x%d" % r, got[0][r], ex_x[r]))
if got[1] != ex_n:
diffs.append("nzcv %s != %s" % (got[1], ex_n))
for r in range(64):
if got[4][r] != ex_v[r]:
diffs.append("v%d.%s %#x != %#x" % (r // 2, "hi" if r & 1 else "lo", got[4][r], ex_v[r]))
if a.fpsr and (got[3] & 0x9F) != (ex_fpsr & 0x9F):
diffs.append("fpsr %#x != %#x" % (got[3], ex_fpsr))
if mem != ex_mem:
diffs.append("memory differs")
if diffs:
fails[key].append((w, st[2], diffs[:4]))
else:
passes[key] += 1
forms = set(k for k, _ in picked)
bad = sorted(fails, key=lambda k: -len(fails[k]))
print("%d cases, %d forms pass, %d forms with failures" % (len(cases), len(forms) - len(bad), len(bad)))
for k in bad if a.list else bad[:40]:
w, fpcr, d = fails[k][0]
name = k[0] + (" (%s)" % ",".join(map(str, k[1])) if k[1] else "")
print(" FAIL %-28s %3d/%-3d e.g. %08x fpcr=%#x: %s" % (name, len(fails[k]), len(fails[k]) + passes[k], w,
fpcr, "; ".join(d)))
print("PASS" if not bad else "FAIL")
return 0 if not bad else 1
if __name__ == "__main__":
sys.exit(main())

177
third_party/a64-kit/tools/nso.py vendored Normal file
View File

@@ -0,0 +1,177 @@
"""NSO (Switch executable) loader: segments, MOD0, dynamic section, symbols, relocations, unwind table.
NSO (switchbrew.org "NSO"):
- header 0x100: three segments (.text, .rodata, .data), each {file offset, memory offset, size}, LZ4-block
compressed when flags bit 0/1/2 is set; bss size at +0x3C; build ID at +0x40.
- .text + 4 holds the offset of the MOD0 header. MOD0 points (relative to itself) at the ELF dynamic section,
bss, .eh_frame_hdr and the module object.
- The dynamic section is ordinary AArch64 ELF: DT_SYMTAB/DT_STRTAB, DT_RELA (R_AARCH64_RELATIVE, GLOB_DAT,
ABS64), DT_JMPREL (JUMP_SLOT), DT_INIT_ARRAY. rtld binds the modules of one ExeFS to each other by symbol name,
so the sdk's exports are named (nn::*, nvn*) even in a stripped game.
- .eh_frame_hdr has a sorted table of (function start, FDE): one entry per function with unwind info.
Usage: python nso.py <exefs_dir | file.nso> [out_dir]
Prints a summary per module; with out_dir writes <module>.bin (the loaded image, bss zeroed) and <module>.json
(segments, symbols, relocations, eh_frame function starts) for the lifter.
"""
import json
import os
import struct
import sys
import lz4.block
DT = {1: "NEEDED", 2: "PLTRELSZ", 3: "PLTGOT", 4: "HASH", 5: "STRTAB", 6: "SYMTAB", 7: "RELA", 8: "RELASZ",
9: "RELAENT", 10: "STRSZ", 11: "SYMENT", 12: "INIT", 13: "FINI", 20: "PLTREL", 23: "JMPREL",
25: "INIT_ARRAY", 26: "FINI_ARRAY", 27: "INIT_ARRAYSZ", 28: "FINI_ARRAYSZ", 30: "FLAGS",
0x6FFFFEF5: "GNU_HASH", 0x6FFFFFF9: "RELACOUNT"}
R_AARCH64 = {257: "ABS64", 1025: "GLOB_DAT", 1026: "JUMP_SLOT", 1027: "RELATIVE", 1030: "TLSDESC"}
STT = {0: "notype", 1: "object", 2: "func", 3: "section", 4: "file", 6: "tls"}
STB = {0: "local", 1: "global", 2: "weak"}
MODULE_ORDER = ["rtld", "main"] + [f"subsdk{i}" for i in range(10)] + ["sdk"]
class Nso:
def __init__(self, path):
raw = open(path, "rb").read()
if raw[:4] != b"NSO0":
raise ValueError(f"{path}: not an NSO")
self.name = os.path.basename(path)
flags = struct.unpack_from("<I", raw, 0xC)[0]
segs = [struct.unpack_from("<III", raw, 0x10 + 0x10 * i) for i in range(3)]
csize = struct.unpack_from("<III", raw, 0x60)
self.bss_size = struct.unpack_from("<I", raw, 0x3C)[0]
self.build_id = raw[0x40:0x60].rstrip(b"\0").hex()
self.segments = []
end = 0
for i, ((foff, moff, size), cs) in enumerate(zip(segs, csize)):
data = raw[foff:foff + cs]
if flags & (1 << i):
data = lz4.block.decompress(data, uncompressed_size=size)
assert len(data) == size, f"{self.name} segment {i}: {len(data)} != {size}"
self.segments.append((moff, size, (".text", ".rodata", ".data")[i]))
end = max(end, moff + size)
self.image = bytearray(end)
for (moff, size, _), (foff, _, _), cs, i in zip(self.segments, segs, csize, range(3)):
data = raw[foff:foff + cs]
if flags & (1 << i):
data = lz4.block.decompress(data, uncompressed_size=size)
self.image[moff:moff + size] = data
self._mod0()
def u32(self, off):
return struct.unpack_from("<I", self.image, off)[0]
def u64(self, off):
return struct.unpack_from("<Q", self.image, off)[0]
def _mod0(self):
m = self.u32(4)
if self.image[m:m + 4] != b"MOD0":
raise ValueError(f"{self.name}: no MOD0")
dyn, bss_s, bss_e, eh_s, eh_e, modobj = struct.unpack_from("<6i", self.image, m + 4)
self.mod0 = m
self.bss = (m + bss_s, m + bss_e)
self.eh_frame_hdr = (m + eh_s, m + eh_e)
self.module_object = m + modobj
if len(self.image) < self.bss[1]:
self.image.extend(bytes(self.bss[1] - len(self.image)))
self.dynamic = {}
off = m + dyn
while True:
tag, val = struct.unpack_from("<qQ", self.image, off)
off += 16
if tag == 0:
break
self.dynamic.setdefault(DT.get(tag, tag), []).append(val)
d = lambda k: self.dynamic.get(k, [0])[0]
strtab, symtab, syment = d("STRTAB"), d("SYMTAB"), d("SYMENT") or 24
nsyms = (strtab - symtab) // syment if strtab > symtab else 0
self.symbols = []
for i in range(nsyms):
name, info, other, shndx, value, size = struct.unpack_from("<IBBHQQ", self.image, symtab + i * syment)
self.symbols.append({"name": _cstr(self.image, strtab + name), "type": STT.get(info & 0xF, info & 0xF),
"bind": STB.get(info >> 4, info >> 4), "defined": shndx != 0,
"value": value, "size": size})
self.relocs = []
for start_key, size_key in (("RELA", "RELASZ"), ("JMPREL", "PLTRELSZ")):
start, size = d(start_key), d(size_key)
for off in range(start, start + size, 24):
r_off, r_info, addend = struct.unpack_from("<QQq", self.image, off)
sym = r_info >> 32
self.relocs.append({"offset": r_off, "type": R_AARCH64.get(r_info & 0xFFFFFFFF, r_info & 0xFFFFFFFF),
"sym": self.symbols[sym]["name"] if sym else None, "addend": addend})
self.init_array = [self.u64(d("INIT_ARRAY") + 8 * i) for i in range(d("INIT_ARRAYSZ") // 8)]
self.eh_funcs = self._eh_frame_hdr_table()
def _eh_frame_hdr_table(self):
"""Function starts from .eh_frame_hdr's binary-search table (datarel sdata4 entries)."""
s, e = self.eh_frame_hdr
if e <= s:
return []
ver, ptr_enc, cnt_enc, tbl_enc = self.image[s:s + 4]
if ver != 1 or tbl_enc != 0x3B or cnt_enc != 0x03:
return []
p = s + 4 + 4 # eh_frame_ptr (sdata4, pcrel) assumed 4 bytes
if ptr_enc & 0x0F not in (0x0B, 0x03):
return []
count = self.u32(p)
p += 4
return [s + struct.unpack_from("<i", self.image, p + 8 * i)[0] for i in range(count)]
def code_range(self):
moff, size, _ = self.segments[0]
return moff, moff + size
def _cstr(buf, off):
end = buf.find(b"\0", off)
return bytes(buf[off:end]).decode("utf-8", "replace")
def load_exefs(path):
if os.path.isfile(path):
return [Nso(path)]
return [Nso(os.path.join(path, n)) for n in MODULE_ORDER if os.path.exists(os.path.join(path, n))]
def main():
mods = load_exefs(sys.argv[1])
exports = {}
for m in mods:
for s in m.symbols:
if s["defined"] and s["name"]:
exports.setdefault(s["name"], m.name)
for m in mods:
print(f"\n== {m.name} build {m.build_id[:16]}... image {len(m.image):,} bytes")
for moff, size, n in m.segments:
print(f" {n:<8} {moff:#010x} {size:>12,}")
print(f" .bss {m.bss[0]:#010x} {m.bss[1] - m.bss[0]:>12,}")
defined = [s for s in m.symbols if s["defined"] and s["name"]]
undef = [s for s in m.symbols if not s["defined"] and s["name"]]
resolved = {}
for s in undef:
resolved[exports.get(s["name"], "?")] = resolved.get(exports.get(s["name"], "?"), 0) + 1
print(f" symbols: {len(defined):,} exported, {len(undef):,} imported "
f"({', '.join(f'{k}: {v:,}' for k, v in sorted(resolved.items()))})")
rc = {}
for r in m.relocs:
rc[r["type"]] = rc.get(r["type"], 0) + 1
print(f" relocations: {', '.join(f'{k} {v:,}' for k, v in sorted(rc.items(), key=str))}")
print(f" init_array: {len(m.init_array)} eh_frame_hdr function starts: {len(m.eh_funcs):,}")
if len(sys.argv) > 2:
out = sys.argv[2]
os.makedirs(out, exist_ok=True)
for m in mods:
open(os.path.join(out, m.name + ".bin"), "wb").write(m.image)
json.dump({"name": m.name, "build_id": m.build_id,
"segments": [{"name": n, "offset": o, "size": s} for o, s, n in m.segments],
"bss": m.bss, "mod0": m.mod0, "init_array": m.init_array, "eh_funcs": m.eh_funcs,
"symbols": m.symbols, "relocs": m.relocs},
open(os.path.join(out, m.name + ".json"), "w"), indent=0)
print(f"\nwrote images + json to {out}")
if __name__ == "__main__":
main()

128
third_party/a64-kit/tools/survey.py vendored Normal file
View File

@@ -0,0 +1,128 @@
"""Instruction survey of NSO code: what an AArch64 emitter has to handle, by count.
Disassembles every .text word with Capstone (skipdata on, so data in code shows up as .byte/.word) and reports:
- mnemonics by count, split into integer, scalar FP, vector (NEON), atomics/exclusives, system, branches;
- system registers read and written (mrs/msr), svc numbers, hint/barrier forms;
- indirect branches (br/blr) and words Capstone could not decode.
Usage: python survey.py <image_dir> [module ...] [--top N] [--json out.json]
image_dir is what nso.py wrote (<module>.bin + <module>.json). Default modules: main.
"""
import collections
import json
import os
import re
import sys
from concurrent.futures import ProcessPoolExecutor
import capstone
VEC = re.compile(r"\bv\d+\.|\bv\d+\b")
FPREG = re.compile(r"\b[sdhbq]\d+\b")
EXCL = {"ldxr", "ldxrb", "ldxrh", "ldxp", "ldaxr", "ldaxrb", "ldaxrh", "ldaxp", "stxr", "stxrb", "stxrh", "stxp",
"stlxr", "stlxrb", "stlxrh", "stlxp", "ldar", "ldarb", "ldarh", "stlr", "stlrb", "stlrh", "clrex"}
SYSTEM = {"mrs", "msr", "svc", "hint", "nop", "yield", "wfe", "wfi", "sev", "sevl", "dmb", "dsb", "isb", "dc", "ic",
"sys", "brk", "hlt", "udf", "prfm", "prfum"}
BRANCH = {"b", "bl", "br", "blr", "ret", "cbz", "cbnz", "tbz", "tbnz"}
def classify(mn, ops):
base = mn.split(".")[0]
if base in EXCL or base.startswith(("cas", "ldadd", "swp", "ldclr", "ldset", "ldeor", "ldsmax", "ldumax")):
return "atomic"
if base in SYSTEM:
return "system"
if base in BRANCH or base.startswith("b."):
return "branch"
if base in (".byte", ".word", ".hword", ".quad"):
return "data"
if VEC.search(ops):
return "vector"
if base.startswith("f") or base in ("scvtf", "ucvtf") or FPREG.search(ops):
return "fp"
return "int"
def scan(args):
path, start, end = args
with open(path, "rb") as f:
f.seek(start)
code = f.read(end - start)
md = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
md.skipdata = True
mnem = collections.Counter()
sysreg = collections.Counter()
svc = collections.Counter()
cls = collections.Counter()
forms = collections.Counter()
for addr, size, mn, ops in md.disasm_lite(code, start):
c = classify(mn, ops)
cls[c] += 1
if c == "vector":
arr = sorted(set(re.findall(r"\.(\d*[bhsdq])\b", ops)))
mnem[f"{mn} ({','.join(arr) or 'v'})"] += 1
forms[mn] += 1
else:
mnem[mn] += 1
if mn in ("mrs", "msr"):
sysreg[f"{mn} {ops.split(',')[1 if mn == 'mrs' else 0].strip()}"] += 1
elif mn == "svc":
svc[ops] += 1
elif mn in ("dc", "ic", "sys"):
sysreg[f"{mn} {ops.split(',')[0]}"] += 1
return mnem, sysreg, svc, cls, forms
def survey(image_dir, module, workers=None):
meta = json.load(open(os.path.join(image_dir, module + ".json")))
text = next(s for s in meta["segments"] if s["name"] == ".text")
path = os.path.join(image_dir, module + ".bin")
n = (workers or os.cpu_count() or 4) * 4
step = ((text["size"] // n) + 3) & ~3
jobs = [(path, text["offset"] + i, min(text["offset"] + i + step, text["offset"] + text["size"]))
for i in range(0, text["size"], step)]
tot = [collections.Counter() for _ in range(5)]
with ProcessPoolExecutor(workers) as ex:
for part in ex.map(scan, jobs):
for t, p in zip(tot, part):
t.update(p)
return tot
def main():
args = sys.argv[1:]
top = 60
out_json = None
if "--top" in args:
i = args.index("--top")
top = int(args[i + 1])
del args[i:i + 2]
if "--json" in args:
i = args.index("--json")
out_json = args[i + 1]
del args[i:i + 2]
image_dir, modules = args[0], args[1:] or ["main"]
report = {}
for mod in modules:
mnem, sysreg, svc, cls, forms = survey(image_dir, mod)
total = sum(cls.values())
print(f"\n== {mod}: {total:,} instructions, {len(mnem):,} distinct mnemonic forms")
for k, v in cls.most_common():
print(f" {k:<8} {v:>12,} {100 * v / total:5.1f}%")
print(f" vector mnemonics (ignoring arrangement): {len(forms)}")
print(f"\n top {top} mnemonics:")
for k, v in mnem.most_common(top):
print(f" {v:>10,} {k}")
print("\n system registers / cache ops:")
for k, v in sysreg.most_common():
print(f" {v:>8,} {k}")
print(f" svc: {dict(svc) or 'none'}")
for k in ("br", "blr", "ret"):
print(f" {k}: {mnem.get(k, 0):,}")
report[mod] = {"classes": cls, "mnemonics": mnem, "sysregs": sysreg, "svc": svc, "vector_forms": forms}
if out_json:
json.dump(report, open(out_json, "w"), indent=1)
if __name__ == "__main__":
main()

105
third_party/a64-kit/tools/toolchain.py vendored Normal file
View File

@@ -0,0 +1,105 @@
import os, shutil
HERE = os.path.dirname(os.path.abspath(__file__))
def emsdk():
return os.environ.get("EMSDK") or (r"C:\emsdk" if os.name == "nt" else os.path.expanduser("~/emsdk"))
def windows():
"""(hookshot) the game is built for Windows: on Windows, or with RX_TARGET=windows on another system (a cross build, with
llvm-mingw's release for that system in HOOKSHOT_MINGW)"""
return os.name == "nt" or os.environ.get("RX_TARGET", "").lower() == "windows"
def mingw(host=False):
"""(hookshot) HOOKSHOT_MINGW=<llvm-mingw folder>: Windows builds with that toolchain's clang, headers and libraries (the GNU ABI
on the UCRT), as TotK Recomp's installer does: nothing of Visual Studio or the Windows SDK is needed. Empty: the MSVC target.
host: for a tool the build itself runs (zbic, a64emit), which a cross build makes for this PC, not for Windows"""
return os.environ.get("HOOKSHOT_MINGW", "") if windows() and not (host and os.name != "nt") else ""
def find(tool, host=False):
if mingw(host) and (tool in ("clang", "clang++", "lld") or tool.startswith("llvm-")):
path = os.path.join(mingw(host), "bin", ("ld.lld" if tool == "lld" else tool) + (".exe" if os.name == "nt" else ""))
if os.path.isfile(path):
return path
root = emsdk()
exts = (".exe", ".bat") if os.name == "nt" else ("",)
native = tool in ("clang", "clang++", "lld") or tool.startswith("llvm-")
folder = os.path.join(root, "upstream", "bin") if native else os.path.join(root, "upstream", "emscripten")
for ext in exts:
path = os.path.join(folder, tool + ext)
if os.path.isfile(path):
return path
return shutil.which(tool) or os.path.join(folder, tool + exts[0])
def need(path):
if not os.path.isfile(path):
raise SystemExit("%s not found: set EMSDK to an emsdk checkout (now %s), or put %s on PATH"
% (path, emsdk(), os.path.splitext(os.path.basename(path))[0]))
return path
def lld_link():
"""emsdk's lld under the name lld-link (lld picks its COFF linker from its own file name), made on first use"""
path = os.path.join(HERE, "lld-link-mingw.exe" if mingw() else "lld-link.exe")
if not os.path.exists(path):
shutil.copyfile(need(find("lld")), path)
return path
def native_target(host=False):
if mingw(host): # (-fms-extensions: __try/__except and __declspec, which clang takes on this target too)
return ["--target=x86_64-w64-mingw32", "-fms-extensions", "-D_CRT_SECURE_NO_WARNINGS"]
return ["--target=x86_64-pc-windows-msvc", "-fms-extensions", "-D_CRT_SECURE_NO_WARNINGS"] if os.name == "nt" else []
def native_link(host=False):
# (-fuse-ld=lld, found through -B: clang ignores --ld-path for the MSVC target and ran Microsoft's link.exe, which
# cannot read the renderer's ThinLTO bitcode)
if mingw(host): # (its own lld; the C++ runtime and winpthread linked in, so no DLLs of the toolchain go beside the game)
# (/nodefaultlib: libraries built with Microsoft's compiler, the CPM cache's FFmpeg, ask in their objects for its C runtime;
# the MinGW one stands in, with host/mingw_msvc_shims.c for what it lacks)
return ["-fuse-ld=lld", "-static"] + ["-Wl,-Xlink=/nodefaultlib:" + l for l in ("libcmt", "oldnames", "libvcruntime", "msvcrt")]
# (issue 439: clang names oldnames.lib as a default library for the MSVC target, and recent Windows SDKs no longer
# ship it (an older SDK has it in ucrt\x64; Visual Studio has its own copy in its lib folder). The game and host use
# no legacy non-underscore name; the ones the prebuilt static FFmpeg libraries ask for are host/msvc_oldnames.c)
return (["-fuse-ld=lld", "-B" + os.path.dirname(lld_link()), "-Wl,/nodefaultlib:oldnames"]
if os.name == "nt" else [])
def link_opt(opt):
"""A link.exe-style option ("/map:x"): as it is for the MSVC target, through lld's MinGW driver (-Xlink) for llvm-mingw"""
return "-Wl,-Xlink=" + opt if mingw() else "-Wl," + opt
def default_jobs(gb_per_job=3.5):
"""Parallel compiles that fit in memory: a -O3 compile of one of the game's big lifted chunks takes 3-8 GB, and one
job per logical core ran 16 GB machines out of memory (22 threads on an Ultra 7 155H). 80% of the physical memory
at gb_per_job each, at most one a core. RX_JOBS=<n> sets it. (After SkyboundTotk PR 14 by leonelalej.)"""
if os.environ.get("RX_JOBS"):
return max(1, int(os.environ["RX_JOBS"]))
total = 0
try:
if os.name == "nt":
import ctypes
class MemoryStatus(ctypes.Structure):
_fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong)] + \
[(f, ctypes.c_ulonglong) for f in ("phys", "avail_phys", "page", "avail_page", "virt",
"avail_virt", "avail_ext")]
m = MemoryStatus()
m.length = ctypes.sizeof(m)
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)):
total = m.phys
else:
total = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
except (OSError, ValueError, AttributeError):
pass
cores = os.cpu_count() or 1
if not total:
return cores
return max(1, min(cores, int(total / 2 ** 30 * 0.8 / gb_per_job)))