Triforce v0.8.0

Evil HD (SMAA Ultra, 16x filtering, full textures, ambient occlusion with bounce light, sunlight shafts, foliage drawn 4x as far, the remastered texture pack's loader and the launcher's download of it), FSR 3.1 frame generation for every GPU, Intel XeSS, FSR 4 model choice, ReShade presets, Auto (this PC), HUD placement, the options menu in 13 languages, a second input for every control, hold to toggle, DualSense speaker and haptics, NFC from the player's own dumps, the above-60 fps game fixes, the Debug tab's flight and Inventory fixes, the launcher's full settings, and over 250 fixes.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-25 10:21:32 -06:00
parent 861702476a
commit 4fa4f9188b
881 changed files with 179428 additions and 15581 deletions

File diff suppressed because it is too large Load Diff

96
nx2/build_jobs.py Normal file
View File

@@ -0,0 +1,96 @@
"""(Triforce) The workers a build was asked for (make_game.py --jobs, HOOKSHOT_JOBS), for every step that runs work side by side.
The launcher's build workers reached the compile alone: the lift's processes and the shader preparation's sized themselves from
the CPU count, so an update filled every thread whatever the player chose, and the PC was unusable while it built.
make_game.py now puts a count it was given in HOOKSHOT_JOBS for the steps it starts, and each step takes at most that many:
- nx2/chunks.py emit_jobs: the lift's emit processes;
- nx2/build.py: its --jobs, as before;
- the game's --prepare-shaders: started on that many of the CPUs make_game.py may use (children_on_cpus), and the game's
environment drops the HOOKSHOT_ build variables (make_game.py game_env), so the mask is how the count reaches it.
Nothing asked (no --jobs, HOOKSHOT_JOBS unset, empty or 0): every step keeps its own count, as before. A step's own
variable (HOOKSHOT_LIFT_JOBS) still wins over this one, and each step's memory limits still apply below it: this is a ceiling,
never a floor.
"""
import contextlib
import os
ERROR = "HOOKSHOT_JOBS must be a whole number: use 1 or more, or 0 for automatic."
def requested(value):
"""A count as given (--jobs, HOOKSHOT_JOBS): 1 or more, or None for automatic (None, "" or 0). ValueError otherwise"""
if value is None or str(value).strip() == "":
return None
try:
jobs = int(value)
except ValueError:
raise ValueError(ERROR) from None
if jobs < 0:
raise ValueError(ERROR)
return jobs or None
def asked(env_map=None):
"""The workers HOOKSHOT_JOBS asks for, or None (unset, automatic, or not a count: make_game.py refuses that one at its start)"""
value = os.environ.get("HOOKSHOT_JOBS") if env_map is None else env_map.get("HOOKSHOT_JOBS")
try:
return requested(value)
except ValueError:
return None
def cap(n, env_map=None):
"""n, at most the workers asked for (asked), never fewer than 1"""
limit = asked(env_map)
return max(1, min(n, limit)) if limit else n
def _windows_mask(mask=None):
"""The process's affinity mask, or with mask, set to it. None when it cannot be read or set"""
import ctypes
from ctypes import wintypes
k = ctypes.WinDLL("kernel32", use_last_error=True)
k.GetCurrentProcess.restype = wintypes.HANDLE
proc = k.GetCurrentProcess()
if mask is not None:
k.SetProcessAffinityMask.argtypes = [wintypes.HANDLE, ctypes.c_size_t]
return mask if k.SetProcessAffinityMask(proc, mask) else None
own, system = ctypes.c_size_t(), ctypes.c_size_t()
k.GetProcessAffinityMask.argtypes = [wintypes.HANDLE, ctypes.POINTER(ctypes.c_size_t), ctypes.POINTER(ctypes.c_size_t)]
return own.value if k.GetProcessAffinityMask(proc, ctypes.byref(own), ctypes.byref(system)) and own.value else None
def first_cpus(usable, n):
"""n of the usable CPUs (numbers), the lowest first: on Windows and Linux alike the performance cores of a hybrid CPU"""
return sorted(usable)[:max(1, n)]
@contextlib.contextmanager
def children_on_cpus(n):
"""The processes started inside run on n of the CPUs this one may use; this one is as it was after. A child takes its
parent's affinity when it is made (Linux: the thread that forks it; Windows: the process). n None, or as many as there are
or more: nothing changes. Where the mask cannot be read or set, nothing changes either: the child takes every CPU, as before"""
restore = None
try:
if n:
if hasattr(os, "sched_setaffinity"):
usable = os.sched_getaffinity(0)
if n < len(usable):
os.sched_setaffinity(0, first_cpus(usable, n))
restore = lambda: os.sched_setaffinity(0, usable) # noqa: E731
elif os.name == "nt":
mask = _windows_mask()
bits = [i for i in range(64) if mask and mask >> i & 1]
# (a mask covers one processor group, 64 CPUs at most: past that the game counts every CPU anyway, usable_cpus)
if mask and n < len(bits) < 64 and _windows_mask(sum(1 << i for i in first_cpus(bits, n))) is not None:
restore = lambda: _windows_mask(mask) # noqa: E731
except OSError:
restore = None
try:
yield
finally:
if restore:
with contextlib.suppress(OSError):
restore()

View File

@@ -21,12 +21,14 @@ process, as before, on every system.
"""
import bisect
import collections
import contextlib
import glob
import multiprocessing
import os
import re
import threading
import whole_write # (rewrites written beside and moved over: issue 1197)
import build_jobs # ((Triforce) the workers the build was asked for: HOOKSHOT_JOBS)
import a64_lift
import emit_pool # ((Triforce) the emit's processes where there is no fork)
@@ -67,13 +69,21 @@ def load(img_dir):
path = os.path.join(img_dir, FILE)
if not os.path.exists(path):
return []
return [int(l, 16) for l in open(path) if l.strip() and not l.startswith("#")]
try:
with open(path, encoding="utf-8") as f:
return [int(l, 16) for l in f if l.strip() and not l.startswith("#")]
except (OSError, UnicodeDecodeError, ValueError) as e:
print("chunks: %s could not be read (%s); ignoring" % (path, e), flush=True)
return []
def save(img_dir, starts):
with open(os.path.join(img_dir, FILE), "w") as f:
f.write("# first guest address of each lifted C chunk after the first (nx2/chunks.py)\n")
f.write("".join("%08x\n" % s for s in sorted(starts)))
# (lift.py --standalone writes this under <work>/image while its image.bin goes to <work>/sa/image, and nothing made
# that folder: a fresh work folder stopped the lift at its last step with FileNotFoundError. make_game.py prepares it)
os.makedirs(img_dir, exist_ok=True)
text = ("# first guest address of each lifted C chunk after the first (nx2/chunks.py)\n"
+ "".join("%08x\n" % s for s in sorted(starts)))
whole_write.write_whole(os.path.join(img_dir, FILE), text, sync=True) # (read by every later lift)
def seed_from_gen(gen_dir):
@@ -156,6 +166,7 @@ def emit_jobs():
n = len(os.sched_getaffinity(0))
except AttributeError:
n = os.cpu_count() or 1
n = build_jobs.cap(n) # ((Triforce) no more than the build was asked for: HOOKSHOT_JOBS, nx2/build_jobs.py)
if not FORK:
n = max(1, min(SPAWN_MOST, n // 2))
gb = _available_gb()
@@ -238,10 +249,49 @@ def gave_up(gen_dir):
drop_lifted(gen_dir)
def write(L, gen_dir, img_dir, rechunk=False, counters=(), jobs=None, setup=()):
@contextlib.contextmanager
def no_texts():
"""(Triforce) a64_lift.Lifter.write with no texts of its own (an empty one per instruction, no FPX shape): for an emit whose
spawned processes make their own (emit_pool.run_texts). Translating every instruction of OoT here took ~15 s and 1-2 GB, and
only sent them on"""
import a64emit
translate, op_text = a64emit.translate, a64_lift.op_text
a64emit.translate = lambda items, batch=65536: ([""] * len(items), [0] * len(items))
a64_lift.op_text = lambda text, fpx: text
try:
yield
finally:
a64emit.translate, a64_lift.op_text = translate, op_text
def fill_fpx(gen_dir, used):
"""(Triforce) a64_fpx.h as the lifter writes it under no_texts(): its helpers for no FPX shape, at its head, become those for
used, the shapes the emit's processes found (what the lifter's own texts would have given: every instruction is in one run)"""
path = os.path.join(gen_dir, "a64_fpx.h")
with open(path, encoding="utf-8", newline="") as f:
text = f.read()
empty = a64_lift.fpx_header(set())
if not text.startswith(empty):
raise SystemExit("chunks: %s does not begin with the lifter's FPX helpers for no shape" % path)
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(a64_lift.fpx_header(used) + text[len(empty):])
def _translator_ready():
"""(Triforce) The translator built and loaded here before the spawned processes start, when the lift translates with it (the
processes translate their runs at once: started before anything here translated, each would build it, into the same file)"""
import a64emit
if "a64emit.translate" in emit_pool.chain(a64emit.translate):
a64emit.lib()
def write(L, gen_dir, img_dir, rechunk=False, counters=(), jobs=None, setup=(), beside=None):
"""L.write(gen_dir) with stable boundaries; returns its files. counters: dicts the emit adds to besides the
lifter's own (poll.stats); jobs: emit processes (emit_jobs()); (Triforce) setup: what set the lifter's class up for
the emit in this process (poll.install), module-level functions the spawned processes call before they emit"""
the emit in this process (poll.install), module-level functions the spawned processes call before they emit.
(Triforce, 11-24) beside: a function run here first, while the spawned processes already emit (nx2/lift.py's coverage
report, which reads the functions and writes none of the C); without processes, before the write. Where they are spawned
this process makes no texts of its own (no_texts: they translate their runs) and writes a64_fpx.h from theirs (fill_fpx)"""
global _workers
starts = [] if rechunk else load(img_dir)
if not starts and not rechunk:
@@ -251,27 +301,38 @@ def write(L, gen_dir, img_dir, rechunk=False, counters=(), jobs=None, setup=()):
jobs = emit_jobs() if jobs is None else jobs
spawned = jobs > 1 and not FORK and len(L.funcs) >= SPAWN_LEAST
made = None
every = [L.stats, L.unhandled, L.ijump] + list(counters)
try:
if spawned: # ((Triforce) started now: they translate and emit their runs while this process makes the report)
_translator_ready()
stop_workers(kill=True) # (an earlier write()'s, which no edit_c() ended)
_workers = emit_pool.Workers(jobs, L, every, setup)
print("emit: %d processes (HOOKSHOT_LIFT_JOBS=<n> for another count, 1 for one process)" % _workers.jobs, flush=True)
made = emit_pool.emit(_workers, L, sorted(L.funcs), every)
if beside:
beside()
except BaseException:
if made is not None:
made.close()
if spawned:
gave_up(gen_dir)
raise
def emit_function(e, texts):
nonlocal made
global _workers
b.current = e
if made is None: # (the first call: write() has its texts now, and asks for the functions in sorted order)
every = [L.stats, L.unhandled, L.ijump] + list(counters)
if spawned:
stop_workers(kill=True) # (an earlier write()'s, which no edit_c() ended)
_workers = emit_pool.Workers(jobs, L, every, setup)
print("emit: %d processes (HOOKSHOT_LIFT_JOBS=<n> for another count, 1 for one process)" % _workers.jobs, flush=True)
made = emit_pool.emit(_workers, L, sorted(L.funcs), texts, every)
else:
made = parallel_emit(base_emit, sorted(L.funcs), texts, every, jobs)
made = parallel_emit(base_emit, sorted(L.funcs), texts, every, jobs)
got = next(made, None)
if got is None or got[0] != e:
raise SystemExit("chunks: write() asked for f_%08x, the emit made %s" % (e, "f_%08x" % got[0] if got else "nothing"))
return got[1], got[2]
L.emit_function = emit_function
try:
files = L.write(gen_dir, chunk_bytes=b)
with no_texts() if spawned else contextlib.nullcontext():
files = L.write(gen_dir, chunk_bytes=b)
if spawned:
fill_fpx(gen_dir, made.fpx)
except BaseException:
if spawned: # ((Triforce) a process failed, died or hung, or this one was stopped: no part of a lift is left behind)
gave_up(gen_dir)
@@ -361,15 +422,21 @@ def split_one(gen_dir, path, budget):
cuts.append(i)
k = run * parts // total + 1 # (past a giant function: the next share, not a sliver after it)
run += c
if len(cuts) < 2: # (no cut: a giant function last, past every share)
costs[os.path.basename(path)] = marks[0] + total
return made, costs, None
bounds = [marks[i] for i in cuts] + [len(text)]
preamble = text[:marks[0]]
for j in range(len(cuts)):
# (the chunk itself last: a process stopped part way leaves it whole, with every function, so whatever runs the split again
# cuts it again; written first, a stop left the chunk cut down to its first part beside only some of the others, and a second
# split of it made no parts and removed the ones written: their functions were gone from the lifted C without a word)
for j in reversed(range(len(cuts))):
out = path if j == 0 else os.path.join(gen_dir, "code_%s_%d.c" % (m.group(1), j))
piece = text[:bounds[1]] if j == 0 else preamble + text[bounds[j]:bounds[j + 1]]
whole_write.write_whole(out, piece)
costs[os.path.basename(out)] = len(preamble) + sum(cost[cuts[j]:cuts[j + 1] if j + 1 < len(cuts) else len(cost)])
if j:
made.append(out)
made.insert(0, out)
return made, costs, "chunks: %s (%d MB, cost %d MB) in %d parts" % (os.path.basename(path), len(text) >> 20, total >> 20, len(cuts))

102
nx2/cmpflags.py Normal file
View File

@@ -0,0 +1,102 @@
"""(Triforce) A subtraction's V flag as N xor (a < b, signed), so that clang folds a signed compare to one host compare (A64_SUB_V).
suyu's translator (third_party/a64-kit/lift/suyu/arm64_to_c.h SetFlags) writes every flag-setting subtraction's NZCV from its
operands and result: SUBS and CMP (immediate, shifted and extended register) and CCMP when its condition holds. V is the
overflow of a - b as bits, ((a ^ b) & (a ^ r)) >> 63 (31 at 32 bits), and the signed conditions read it against N: LT is
N != V, GE N == V, GT and LE the same with Z. clang does not see through that: CMP x1, x2; B.LT, the game's most common
signed loop and bounds test, became sub, xor, andn, and, or and a test of the sign (seven instructions and two registers
where the CPU has cmp and jl), at -O1 and at -O2 alike, in every function, hot or not.
For a subtraction N xor V is exactly a < b as signed integers of the operation's width: N is the sign of the wrapped
difference and V says whether the wrap flipped it (that is what Arm's LT condition means after a CMP). So V = N xor (a <s b),
for every a and b. Written that way, from the result's sign bit and the signed compare (never from c->n, so that dead_flags
sees no new read of N), a reader's N != V is (N xor N) xor (a <s b): clang folds it to the compare, and B.LT, B.GE, B.GT,
B.LE, CSEL and CSET on them become cmp and a jump, cmov or setcc. A reader of V alone (B.VS, B.VC: rare) costs about what it
did. Every flag keeps its value, bit for bit; only the C text of V changes.
The text replaced is SetFlags' subtraction V exactly, and SetFlags is its only writer: ADDS/CMN write V with a ~ in it, and
ADCS/SBCS write theirs in another form (c->v = (... & sign) ? 1 : 0), so neither is touched. Rekarina, another recompiler of
the game, compares a SUBS's operands directly where only that kind reaches the reader (its recomp/flags.py, runtime/cpu.h
fc_sub: https://git.rekarina.dev/rekarina/rekarina); the identity here needs no such analysis and is exact for every reader.
(Triforce) A second form, "ovf": V as the compiler's own signed-overflow test of the subtraction,
__builtin_sub_overflow((intN_t)a, (intN_t)b, ...), which is V by definition. clang makes it the subtraction's own overflow
flag (sub, seto) and a signed condition after it sub, seto, a shift and a compare of two bytes: five instructions where the
kit's text takes nine and the form above two. Its reason: the hot pieces are compiled with a recorded profile (nx2/build.py
RX_PGO), which the compiler matches to a function by a count of its conditions, comparisons, labels and jumps. The form
above adds a `<` to every function that compares, so every recorded function is compiled without its profile until a new
one is recorded with the new text; a builtin call is not counted, so with "ovf" the recorded profile still matches.
A64_SUB_V (lift time, so in the lift key: an A64_ variable): unset, empty or "0" off, and the lift's text is the kit's to the
byte (Triforce's default until it is measured in the game); "1" the form above (record a new profile with it); "ovf" the
overflow form. Game-free check: tests/test_cmpflags.py (each form against the old V on edge and random operands at both
widths, the substitution on translated words, and that it leaves ADDS/ADCS/SBCS alone). install() runs at nx2/lift.py's
module level, so the lift's emit processes (nx2/emit_pool.py) run it too.
"""
import os
import a64emit
# SetFlags' subtraction V, at 64 and 32 bits (arm64_to_c.h: "c->v=(int)((((_fa^_fb)&(_fa^_fr))>>" top ")&1); }")
OLD = {64: "c->v=(int)((((_fa^_fb)&(_fa^_fr))>>63)&1);", 32: "c->v=(int)((((_fa^_fb)&(_fa^_fr))>>31)&1);"}
# (_fa, _fb, _fr: the width's unsigned operands and result, as SetFlags declares them)
FORMS = {"lt": {64: "c->v=(int)(((_fr>>63)&1)^((int64_t)_fa<(int64_t)_fb));",
32: "c->v=(int)(((_fr>>31)&1)^((int32_t)_fa<(int32_t)_fb));"},
# (the difference itself goes into a temporary nobody reads; no ';' inside: dead_flags cuts a store at its first one)
"ovf": {64: "c->v=(int)__builtin_sub_overflow((int64_t)_fa,(int64_t)_fb,&(int64_t){0});",
32: "c->v=(int)__builtin_sub_overflow((int32_t)_fa,(int32_t)_fb,&(int32_t){0});"}}
def mode():
"""the form A64_SUB_V asks for: an empty string (off), 'lt' or 'ovf'"""
v = os.environ.get("A64_SUB_V", "").strip().lower()
if v in ("", "0", "off", "false", "no"):
return ""
if v in ("1", "on", "true", "yes", "lt"):
return "lt"
if v == "ovf":
return "ovf"
raise SystemExit("A64_SUB_V=%s: 0, 1 or ovf" % os.environ.get("A64_SUB_V"))
def on():
return bool(mode())
NEW = FORMS[mode() or "lt"] # (the form this process writes; "lt" where it writes none, for the tests' text checks)
def has_sub_v(text):
"""whether text has SetFlags' subtraction V: its exact text, since "_fa^_fb" alone is in ADDS/CMN's ~(_fa^_fb) too"""
return OLD[64] in text or OLD[32] in text
def rewrite(text):
"""an instruction's translated C with its subtraction V (if any) written as N xor (a <s b)"""
if not has_sub_v(text):
return text
for width in (64, 32):
text = text.replace(OLD[width], NEW[width])
return text
_installed = False
_base = [] # (the translate this one wraps: the tests take their reference from it)
def install():
"""a64emit.translate wrapped. Once; nothing with A64_SUB_V unset or 0"""
global _installed
if _installed or not on():
return
_installed = True
base_translate = a64emit.translate
_base.append(base_translate)
def translate(items, batch=65536):
texts, flags = base_translate(items, batch)
if not any(has_sub_v(t) for t in texts):
return texts, flags
return [rewrite(t) for t in texts], flags
a64emit.translate = translate

42
nx2/dead_flags.py Normal file
View File

@@ -0,0 +1,42 @@
"""(Triforce) a64_lift.Lifter.dead_flags, answered at once for a function none of whose instructions writes a flag.
dead_flags (the kit's) works out, per function, which flags each instruction stores that nothing reads, so emit_function can
drop those stores: one pass over the function's instructions to gather what each reads and writes, then a liveness fixpoint.
Only an instruction that writes a flag (a translated op whose text stores c->n, z, c or v: flag_masks' second half) can have a
dead store (the kit keeps only those: `kills[i] and body[pc][0][0] == "op"`), so a function without one has none, and the kit's
answer is {} after all that work. It ran on every one of OoT's 294,000 functions, more than half of which write no flag; here a
function is first looked over for a flag write (flag_masks, kept by the text in the kit), and only one that has one goes through
the kit's method. The answers are the kit's (tests/test_dead_flags.py).
install() is run by nx2/lift.py at its module level, so the emit's spawned processes (nx2/emit_pool.py) have it too.
"""
import a64_lift
import a64emit
_installed = False
def writes_flags(body, texts):
"""an instruction of body is a translated op whose text stores a flag (the only kind dead_flags can find dead)"""
relative, masks = a64_lift.pc_relative, a64_lift.flag_masks
for pc, (k, w) in body.items():
if k[0] == "op":
text, fl = texts[(w, pc) if relative(w) else w]
if not fl & a64emit.UNHANDLED and masks(text)[1]:
return True
return False
def install():
global _installed
if _installed:
return
_installed = True
base = a64_lift.Lifter.dead_flags
def dead_flags(self, body, pcs, texts):
if not writes_flags(body, texts):
return {}
return base(self, body, pcs, texts)
a64_lift.Lifter.dead_flags = dead_flags

183
nx2/discover.py Normal file
View File

@@ -0,0 +1,183 @@
"""(Triforce) The discovery's walks in spawned processes where there is no fork (Windows), with the kit's result.
a64_lift.Lifter.discover walks every entry in address order (~20 s of one core for OoT on a 16-thread PC, and more on a busy one,
while the other cores wait), then retries the jump tables it missed, finds the PLT stubs and the setjmp owners. Here its first
loop's walks are made by processes, the entries cut into parts of consecutive addresses (at unwind-range starts), each part walked
in order by a lifter of its own; the kit's discover then runs as it is, its first loop given those bodies (the rest, from the
retry on, walks as always, in this process).
What one function's walk finds depends on the others in one way: a jump table whose address is not in the window before its BR
is looked for along the code's predecessors (a64_lift reaching_constants, preds), which include the tables found so far in the
same unwind range. So the parts agree with the kit's single walk unless two parts meet in a range where that search ran: each
part reports the ranges it found tables in and the ranges where the search ran, and when one range has both from two parts, or
the search from two, the parts are thrown away and the kit's discover walks everything, as before (conflicts).
tests/test_discover.py checks the merge and the fallbacks on a made-up image.
The workers rebuild the image from <img_dir>/image.bin (what image.write wrote, after its relocations) and the entries, hooks
and unwind starts the lifter has; they are spawned processes, which run nx2/lift.py's module level again (nx2/insn.py's
classify, nx2/lift_fixes.py's jump tables, nx2/walk.py): a worker whose walk is not this process's (identities) stops, and the
kit's discover walks all. HOOKSHOT_LIFT_JOBS=1, a fork (Linux, macOS: unchanged there), another image layout, a Lifter subclass
or fewer than MIN_ENTRIES entries: the kit's discover, in this process.
"""
import bisect
import collections
import multiprocessing
import os
from concurrent.futures import ProcessPoolExecutor
import a64_lift
import nx_image
PARTS_PER_JOB = 3 # (parts are uneven: more parts than processes even them out)
MIN_ENTRIES = 4000 # (fewer: the processes' start costs more than the walks)
_view = None # (a worker's lifter)
def identities():
"""Where the callables the walk goes through come from, as (module, qualified name): a worker compares its own with the
lift's before it walks (as nx2/emit_pool.py's workers do for the emit)"""
L = a64_lift.Lifter
return [("__main__" if f.__module__ == "__mp_main__" else f.__module__, f.__qualname__)
for f in (a64_lift.classify, L.walk, L.jump_table, L.function_constant, L.reaching_constants, L.preds, L.add_jt_edges,
L.hoisted_constant, L.adr_targets)]
def parts_of(L, order, n):
"""order (sorted entries) cut into about n runs of consecutive entries, each cut where the unwind range changes"""
starts = L.eh_starts
def ext(e):
return bisect.bisect_right(starts, e)
cuts = [0]
for k in range(1, n):
i = max(cuts[-1] + 1, len(order) * k // n)
while i < len(order) and ext(order[i]) == ext(order[i - 1]):
i += 1
if i >= len(order):
break
cuts.append(i)
cuts.append(len(order))
return [order[a:b] for a, b in zip(cuts, cuts[1:]) if b > a]
def _init(path, base, end, code, entries, hooks, eh_starts, theirs):
global _view
import image
try:
import emit_pool
emit_pool._no_throttle() # (as the emit's processes: Windows slows a background window's processes to almost nothing)
emit_pool._leave_with_parent() # (and one whose lift was stopped from outside ends by itself)
except ImportError:
pass
nx_image.MAIN_BASE = base
img = object.__new__(image.EdenImage)
with open(path, "rb") as f:
img.mem = bytearray(f.read())
if len(img.mem) != end - base:
raise RuntimeError("%s is %d bytes, the lift's image %d" % (path, len(img.mem), end - base))
img.end, img.code = end, code
img.lookups()
img.entries, img.hooks, img.names, img.eh_starts = set(entries), dict(hooks), {}, eh_starts
if identities() != theirs:
raise RuntimeError("this process walks with %s, the lift's with %s" % (identities(), theirs))
_view = a64_lift.Lifter(img)
def walk_part(L, es):
"""The kit's first loop over es with L's state made fresh: (funcs, jt, jt_missing, stats, ranges with tables found,
ranges whose predecessors were read). The predecessors (a64_lift preds, with the tables found so far in the range) are
the only state of one walk that another walk's changes: reaching_constants reads them. (Tracked at preds, not at
reaching_constants, which nx2/lift_fixes.py replaces on the instance for a while and then deletes)"""
L.funcs, L.jt, L.jt_missing, L.stats = {}, {}, {}, collections.Counter()
L.__dict__.pop("_preds", None)
searched = set()
base = type(L).preds
def preds(lo, hi):
searched.add(lo)
return base(L, lo, hi)
L.preds = preds
try:
for e in es:
if e in L.hooks:
continue
L.funcs[e] = L.walk(e)
finally:
del L.preds
found = {L.function_extent(pc)[0] for pc in L.jt}
return L.funcs, L.jt, L.jt_missing, L.stats, found, searched
def _walk(es):
return walk_part(_view, es)
def conflicts(results):
"""The unwind ranges where two parts could have seen each other's tables: a range searched by one part (reaching_constants)
with tables found or searched by another"""
by = collections.defaultdict(set)
searched = set()
for i, r in enumerate(results):
for x in r[4] | r[5]:
by[x].add(i)
searched |= r[5]
return sorted(x for x in searched if len(by[x]) > 1)
def merge(L, results):
"""The parts' walks as the kit's first loop leaves them: their bodies by entry (for discover's first loop), and L's jt,
jt_missing and stats"""
bodies = {}
for funcs, jt, missing, stats, _, _ in results:
bodies.update(funcs)
L.jt.update(jt)
L.jt_missing.update(missing)
L.stats.update(stats)
return bodies
def discover(L, img_dir, jobs, max_insns=0, run=None):
"""L.discover(max_insns), its first loop's walks made by `jobs` spawned processes when they can be (the module's note).
run(fn, parts): how the parts are walked (the processes; a test's stand-in). Returns the processes used (1: none)"""
import chunks
import image
img = L.img
if run is None and (jobs <= 1 or chunks.FORK or type(L) is not a64_lift.Lifter
or type(img) is not image.EdenImage or len(L.entries) < MIN_ENTRIES):
L.discover(max_insns=max_insns)
return 1
order = sorted(L.entries)
parts = parts_of(L, order, max(1, jobs) * PARTS_PER_JOB)
try:
if run is not None:
results = run(walk_part, parts)
else:
path = os.path.join(img_dir, "image.bin")
args = (path, nx_image.MAIN_BASE, img.end, img.code, L.entries - set(L.hooks), L.hooks, L.eh_starts, identities())
with ProcessPoolExecutor(max_workers=jobs, mp_context=multiprocessing.get_context("spawn"),
initializer=_init, initargs=args) as pool:
results = list(pool.map(_walk, parts))
except Exception as e: # (BrokenProcessPool, a worker that stopped or could not start, anything raised in a walk)
print("discovery: the walks' processes stopped (%s): walked here" % str(e).strip().splitlines()[-1:], flush=True)
L.discover(max_insns=max_insns)
return 1
shared = conflicts(results)
if shared:
print("discovery: %d unwind ranges searched for jump tables by two parts (first at %#x): walked here, in order"
% (len(shared), shared[0]), flush=True)
L.discover(max_insns=max_insns)
return 1
bodies = merge(L, results)
walk = L.walk
def given(e): # (the kit's first loop takes each body walked already; any later walk is a real one)
b = bodies.pop(e, None)
return b if b is not None else walk(e)
L.walk = given
try:
L.discover(max_insns=max_insns)
finally:
del L.walk
print("discovery: %d parts walked in %d processes" % (len(parts), jobs), flush=True)
return jobs

View File

@@ -5,9 +5,12 @@ ahead on a hard drive.
spinning(path) -> True for a spinning disk, False for an SSD or flash, None when it cannot be told (a network share, an unknown
device, another operating system). Windows asks the volume for its seek penalty (IOCTL_STORAGE_QUERY_PROPERTY,
StorageDeviceSeekPenaltyProperty: a disk that seeks says so); Linux reads the kernel's queue/rotational for the device behind the
folder, through its partitions and device-mapper/RAID slaves.
folder, through its partitions and device-mapper/RAID slaves. A Btrfs folder's device number is no disk's, so its disks are
those its mount names.
"""
import glob
import os
import stat
import sys
@@ -72,34 +75,100 @@ def _windows_spinning(path):
kernel32.CloseHandle(handle)
def _linux_spinning(path):
def _linux_spinning(path, mountinfo="/proc/self/mountinfo", sysfs="/sys"):
"""queue/rotational of the block device behind path's file system"""
try:
st = os.stat(path)
except OSError:
return None
return _device_rotational("/sys/dev/block/%d:%d" % (os.major(st.st_dev), os.minor(st.st_dev)))
node = os.path.join(sysfs, "dev", "block", "%d:%d" % (os.major(st.st_dev), os.minor(st.st_dev)))
if os.path.exists(node):
return _device_rotational(node)
# (Btrfs numbers its files' device itself, a number a subvolume and none of them a disk's (0:38): sysfs has no such node, and
# the walk below ended at None, so a hard drive with Btrfs on it, as Fedora, Bazzite and CachyOS format one, never warned)
answers = [a for a in (_device_rotational(n) for n in _mounted_from(path, mountinfo, sysfs)) if a is not None]
return any(answers) if answers else None
def _device_rotational(node, depth=0):
def _unescaped(field):
"""A mountinfo field as the path it stands for: a space, tab, newline and backslash in it are written \\040, \\011, \\012, \\134"""
parts = field.split("\\")
return parts[0] + "".join(chr(int(p[:3], 8)) + p[3:] if p[:3].isdigit() else "\\" + p for p in parts[1:])
def _block_node(device, sysfs="/sys"):
"""sysfs's node of a block device file (/dev/sda2); None for anything else (a network share's or ZFS's name)"""
try:
st = os.stat(device)
except OSError:
return None
if not stat.S_ISBLK(st.st_mode):
return None
return os.path.join(sysfs, "dev", "block", "%d:%d" % (os.major(st.st_rdev), os.minor(st.st_rdev)))
def _mounted_from(path, mountinfo="/proc/self/mountinfo", sysfs="/sys"):
"""sysfs's nodes of the block devices path's file system was mounted from: the one its mount names, and for a Btrfs over
several disks every one of them (the mount names one; /sys/fs/btrfs/<id>/devices has them all)"""
path, found = os.path.realpath(path), None
with open(mountinfo, encoding="utf-8", errors="surrogateescape", newline="\n") as f:
for line in f: # (id, parent, device, root, mount point, options... - type, source, options)
mount, dash, source = line.rstrip("\n").partition(" - ")
mount, source = mount.split(" "), source.split(" ")
if not dash or len(mount) < 5 or len(source) < 2:
continue
point = _unescaped(mount[4])
inside = path == point or path.startswith(point.rstrip("/") + "/")
if inside and (found is None or len(point) >= len(found[0])): # (the deepest; of two at one point, the later is on top)
found = (point, source[0], _unescaped(source[1]))
node = _block_node(found[2], sysfs) if found else None
if not node:
return []
if found[1] == "btrfs":
for devices in glob.glob(os.path.join(glob.escape(sysfs), "fs", "btrfs", "*", "devices")):
nodes = [os.path.join(devices, n) for n in sorted(os.listdir(devices))]
if os.path.realpath(node) in [os.path.realpath(n) for n in nodes]:
return nodes
return [node]
def _device_rotational(node):
"""The device behind sysfs's node: its slaves decide for device-mapper and RAID (any spinning one makes it slow), and a
partition's own folder has no queue/rotational, so the disk above it is read"""
path = os.path.realpath(node)
if depth < 4:
slaves = os.path.join(path, "slaves")
try:
names = sorted(os.listdir(slaves))
except OSError:
names = []
answers = [a for a in (_device_rotational(os.path.join(slaves, n), depth + 1) for n in names) if a is not None]
if answers:
return any(answers)
while True:
try:
with open(os.path.join(path, "queue", "rotational"), encoding="ascii") as f:
return f.read().strip() == "1"
except OSError:
up = os.path.dirname(path)
if up == path:
return None
path = up
root = os.path.realpath(node)
answers, active = {}, set()
pending = [(root, None)]
while pending:
path, children = pending.pop()
if children is None:
if path in answers or path in active:
continue
active.add(path)
slaves = os.path.join(path, "slaves")
try:
names = sorted(os.listdir(slaves))
except OSError:
names = []
children = [os.path.realpath(os.path.join(slaves, n)) for n in names]
# Postorder without recursion or a depth cap. A back edge has no answer;
# completed nodes are cached so shared slaves are only read once.
pending.append((path, children))
pending.extend((child, None) for child in reversed(children))
continue
known = [answers[c] for c in children if answers.get(c) is not None]
answer = any(known) if known else None
if not known:
parent = path
while True:
try:
with open(os.path.join(parent, "queue", "rotational"), encoding="ascii") as f:
answer = f.read().strip() == "1"
break
except OSError:
up = os.path.dirname(parent)
if up == parent:
break
parent = up
answers[path] = answer
active.remove(path)
return answers[root]

View File

@@ -8,14 +8,19 @@ needs and no more:
- once, when it starts: every attribute of the lifter but NOT_SENT (the entries, the PLT stubs, the jump tables, the names, the
patches after instructions: 4 MB pickled), the functions that set the lifter's class up as this process did (poll.install),
and where the counters live;
- with each run of consecutive functions: those functions' bodies as the discovery left them and the texts of their
instructions as write() translated them (about 3 MB and 3.5 MB a run: 148 runs of 2000 functions were 425 and 513 MB).
- with each run of consecutive functions: those functions' bodies as the discovery left them (about 3 MB a run).
A worker emits its run with the lifter's own emit_function and sends back the texts, the names each calls and what the run added
to the counters. The lift's process takes the runs in order and hands write() the functions one by one, as if it had made them:
the C is the one-process C, byte for byte (tests/test_spawn_emit.py on authored code; the game's own lift was compared file by
file). Nothing a worker computes is taken from anywhere but these two messages, so discovery is done once and is not assumed to
repeat itself.
A worker translates its run's instructions itself, as a64_lift.Lifter.write does for all of them (each distinct word once, per pc
where its text reads the pc: run_texts), emits the run with the lifter's own emit_function and sends back the texts, the names
each calls, what the run added to the counters and the FPX shapes its instructions use (a64_fpx.h's helpers: the lift's process
writes that header from every run's, fill_fpx in nx2/chunks.py). The lift's process takes the runs in order and hands write() the
functions one by one, as if it had made them: the C is the one-process C, byte for byte (tests/test_spawn_emit.py on authored code;
the game's own lift was compared file by file). Nothing a worker computes is taken from anywhere but these two messages, so
discovery is done once and is not assumed to repeat itself.
(Triforce, 11-24) The lift's process no longer translates every instruction for itself on this path (nx2/chunks.py no_texts: ~15 s
and 1-2 GB, before, only to send the texts on), and the processes start when write() is called, before the coverage report, so
they work while the lift's process makes it (emit(): the first runs are asked for at once).
Measured on a 16-thread PC (the game: 294,523 functions, 17.6 million instructions, 185 runs): write()'s emit loop takes 46 s in
one process, 37 s of it in emit_function, and 13 s with 8 processes (21 s with 3, on a PC that was not idle). What is left is
@@ -44,7 +49,8 @@ import a64_lift
# (the lifter's attributes a worker is not sent: the image and the functions (each run brings its own), write()'s stand-in for
# emit_function, which exists only in the lift's process, and what only the discovery reads)
NOT_SENT = ("img", "funcs", "emit_function", "eh_starts", "_preds")
NOT_SENT = ("img", "funcs", "emit_function", "eh_starts", "_preds",
"_op_entries") # ((Triforce) nx2/walk.py's shared entries of the discovery's plain ops: a million, read by no emit)
RUN_FUNCS = 2000 # (a run: at most this many functions,
RUN_INSNS = 120000 # and no more once it holds this many instructions: 2000 functions are 120,000 on average, a few are 20,000 each)
AHEAD = 2 # (runs asked for beyond one a worker: none waits while the lift's process writes a chunk)
@@ -72,26 +78,42 @@ def plan(order, size, most_funcs=None, most_size=None):
return runs
def texts_of(funcs, es, texts):
"""The instruction texts the emit of the functions es reads, out of all of them: a64_lift's emit_function, dead_flags and
dirty_regs look a plain instruction's text up by its word, or by the word and its address where the text depends on the
address (pc_relative), and no other kind's"""
def run_texts(bodies, fpx):
"""The instruction texts the emit of the functions in bodies ({e: (body, labels)}) reads, made as a64_lift.Lifter.write makes
them for every function: a64_lift's emit_function, dead_flags and dirty_regs look a plain instruction's text up by its word,
or by the word and its address where the text depends on the address (pc_relative), and no other kind's. Each is translated
once, by a64emit.translate and a64_lift.op_text as they stand (nx2/insn.py's, nx2/vecfp.py's, nx2/fastvec.py's: this
process ran nx2/lift.py's module level as the lift's did). The FPX shapes the texts use are added to fpx"""
import a64emit
relative = a64_lift.pc_relative
need = {}
for e in es:
for pc, (k, w) in funcs[e][0].items():
keys = {}
for body, _ in bodies.values():
for pc, (k, w) in body.items():
if k[0] == "op":
key = (w, pc) if relative(w) else w
if key not in need:
need[key] = texts[key]
return need
keys.setdefault((w, pc) if relative(w) else w, (pc, w))
order = list(keys)
tx, fl = a64emit.translate([keys[x] for x in order])
op_text = a64_lift.op_text
return dict(zip(order, zip((op_text(t, fpx) for t in tx), fl)))
def emit_print(cls):
"""What the class's emit_function is made of: its own name and, through the closures, the names of the functions it wraps
(poll.install keeps the one before it in its closure). A worker whose class has another emit_function than the lift's
process (a wrapper installed there and not named in `setup`) would write other C, without a word: it compares this first"""
out, todo, seen = [], [getattr(cls, "emit_function", None)], set()
return chain(getattr(cls, "emit_function", None))
def lift_print(cls):
"""(Triforce) What a worker's emit and texts are made of: emit_print, and the same for the lifter's dead_flags and for the
translator (a64emit.translate) and a64_lift.op_text, which a worker now calls itself (run_texts)"""
import a64emit
return [emit_print(cls), chain(getattr(cls, "dead_flags", None)), chain(a64emit.translate), chain(a64_lift.op_text)]
def chain(f):
"""f's own name and, through the closures, the names of the functions it wraps"""
out, todo, seen = [], [f], set()
while todo:
f = todo.pop()
f = getattr(f, "__func__", f)
@@ -166,10 +188,12 @@ def _start(blob):
setup, cls, state, counters, want = pickle.loads(blob)
for f in setup:
f()
got = emit_print(cls)
if got != want:
raise RuntimeError("the lifter's emit_function here is %s, the lift's process has %s: what set it up there must be "
"named in `setup` (nx2/chunks.py write)" % (" over ".join(got), " over ".join(want)))
got = lift_print(cls)
for what, mine, theirs in zip(("the lifter's emit_function", "the lifter's dead_flags", "the translator (a64emit.translate)",
"a64_lift.op_text"), got, want):
if mine != theirs:
raise RuntimeError("%s here is %s, the lift's process has %s: what set it up there must be named in `setup` "
"(nx2/chunks.py write)" % (what, " over ".join(mine), " over ".join(theirs)))
L = cls.__new__(cls)
vars(L).update(state)
_mine = (L, [vars(L)[k] if m == "L" else getattr(importlib.import_module(m), k) for m, k in counters])
@@ -177,19 +201,21 @@ def _start(blob):
_mine = traceback.format_exc()
def _emit_run(bodies, texts):
"""A run's functions emitted: [(e, text, refs)], and each counter's keys with what this run added (every key the counter
holds, in its order: the lift's process adds them in the runs' order, so its counters get their keys in the order one
process gives them)"""
def _emit_run(bodies):
"""A run's functions emitted: [(e, text, refs)], each counter's keys with what this run added (every key the counter holds,
in its order: the lift's process adds them in the runs' order, so its counters get their keys in the order one process gives
them), and (Triforce) the FPX shapes of the run's instructions (run_texts)"""
if not isinstance(_mine, tuple):
raise RuntimeError("a process of the emit could not be set up:\n%s" % _mine)
L, counters = _mine
fpx = set()
texts = run_texts(bodies, fpx)
L.funcs = bodies
for c in counters:
for k in c:
c[k] = 0
out = [(e,) + tuple(L.emit_function(e, texts)) for e in bodies]
return out, [list(c.items()) for c in counters]
return out, [list(c.items()) for c in counters], fpx
# ---- in the lift's process ----------------------------------------------------------------------------------------------------
@@ -199,7 +225,7 @@ class Workers:
def __init__(self, jobs, L, counters=(), setup=()):
blob = pickle.dumps((list(setup), type(L), {k: v for k, v in vars(L).items() if k not in NOT_SENT},
[where(L, c) for c in counters], emit_print(type(L))), pickle.HIGHEST_PROTOCOL)
[where(L, c) for c in counters], lift_print(type(L))), pickle.HIGHEST_PROTOCOL)
self.jobs = max(1, min(int(jobs), MOST))
self.pool = concurrent.futures.ProcessPoolExecutor(max_workers=self.jobs, mp_context=multiprocessing.get_context("spawn"),
initializer=_start, initargs=(blob,))
@@ -210,11 +236,13 @@ class Workers:
except BrokenProcessPool as e: # (a process died since the last answer: the pool takes nothing more)
raise SystemExit(GONE % (call[0], e)) from None
def each(self, fn, calls, wait=None):
def each(self, fn, calls, wait=None, primed=False):
"""fn(*args) in the processes for every (what, args) of calls, the results in the calls' order. calls is read as the
processes come free (AHEAD more than there are), so what it makes for a call is not held for all of them at once.
A call that raises, a process that dies and one that gives no answer for `wait` seconds (WAIT) end it with SystemExit
and what was said, and with the processes ended; so does leaving it before its end"""
and what was said, and with the processes ended; so does leaving it before its end.
(Triforce) primed: the first calls are asked for at the first next(), which gives None, so the processes start (they are
started as calls come) and work while the caller does something else before it takes the answers"""
pending, calls, done = collections.deque(), iter(calls), False
try:
while True:
@@ -224,6 +252,10 @@ class Workers:
calls = None
else:
pending.append(self._ask(fn, call))
if primed:
primed = False
yield None
continue
if not pending:
done = True
return
@@ -287,22 +319,61 @@ class Workers:
pool.shutdown(wait=True, cancel_futures=True)
def emit(workers, L, order, texts, counters, need=texts_of, runs=None):
"""(e, text, refs) for every function of order, in order, emitted by the workers; counters (the dicts Workers was given)
get each run's additions. need(funcs, es, texts): the texts a run is sent; runs: the runs, when not plan()'s"""
class Emitted:
"""emit()'s (e, text, refs), an iterator; fpx: the FPX shapes of the runs taken so far (all of them once it is read to its
end); close() ends what it asked for when it is not read to its end (the processes are ended then, as each() does)"""
def __init__(self, answers, counters):
self.fpx = set()
self._answers = answers
self._frozen = True
self._made = self._take(answers, counters)
def _take(self, answers, counters):
for out, counts, shapes in answers:
for c, added in zip(counters, counts):
for k, v in added:
c[k] = c.get(k, 0) + v
self.fpx |= shapes
yield from out
self._thaw()
def _thaw(self):
if self._frozen:
self._frozen = False
gc.unfreeze()
def __iter__(self):
return self
def __next__(self):
return next(self._made)
def close(self):
try:
self._made.close()
self._answers.close()
finally:
self._thaw()
def emit(workers, L, order, counters, runs=None):
"""(e, text, refs) for every function of order, in order, emitted by the workers (an Emitted); counters (the dicts Workers
was given) get each run's additions; runs: the runs, when not plan()'s. (Triforce) The first runs are asked for now: the
processes start and translate them while the lift's process goes on (nx2/chunks.py write: the coverage report, then the
lifter's write())"""
funcs = L.funcs
if runs is None:
runs = plan(order, lambda e: len(funcs[e][0]))
def calls():
for es in runs:
yield ("the emit of f_%08x to f_%08x" % (es[0], es[-1]), ({e: funcs[e] for e in es}, need(funcs, es, texts)))
yield ("the emit of f_%08x to f_%08x" % (es[0], es[-1]), ({e: funcs[e] for e in es},))
gc.freeze() # (the lift's millions of objects out of the collector's sight while the runs' short-lived ones come and go)
answers = workers.each(_emit_run, calls(), primed=True)
try:
for out, counts in workers.each(_emit_run, calls()):
for c, added in zip(counters, counts):
for k, v in added:
c[k] = c.get(k, 0) + v
yield from out
finally:
next(answers)
except BaseException:
gc.unfreeze()
raise
return Emitted(answers, counters)

786
nx2/fastfp.py Normal file
View File

@@ -0,0 +1,786 @@
"""(Triforce) Fast float regions in lifted code (A64_FASTFP at lift time; off by default), outside the vendored kit's method.
A straight run of single-precision float math is lifted twice: a fast copy of plain SSE ops checked once by MXCSR, and the
exact copy (the lifted code as before) as the fallback. The rules and the header the fast copies compile against are below
(ff_region, FASTFP_HEADER); see the comment above FF_CALL.
This module:
- replaces a64_lift.Lifter.emit_function with emit_function below: a copy of the kit's, with the lines that gather a run of
joinable instructions and emit it through ff_region added, each tagged "# (fastfp)". tests/test_fastfp_override.py checks
that the copy without its tagged lines is the kit's method, line for line: a change of the kit's method fails it until
this copy follows;
- wraps a64_lift.Lifter.write: FASTFP_HEADER appended to a64_fpx.h after the kit writes it, and the regions' count printed.
install() runs before nx2/lift_fixes.py's and nx2/poll.py's wrappers of emit_function (nx2/lift.py), so they wrap this one.
The lift's emit processes (nx2/emit_pool.py) run nx2/lift.py's module level again, so they emit with it too.
Triforce's rules on top:
- off unless A64_FASTFP is set (1: every function; hot: the A64_HOT_FUNCS list only; check: both copies every time,
compared, the exact one's result kept): it has not run in the game here. With it unset or 0 the kit's own method stays
installed and the lift's C is the kit's to the byte;
- no region at all in a function that holds an address the game's patches name (nx2/oot_patches.py and the other files
that edit the lifted text after the lift, patch_sources): those edits match the lift's exact text, once, and a region
writes its instructions twice, the fast copy's float ops under other names. An edit would change the exact copy alone
and the fast copy, the one that runs, would keep the game's own arithmetic (the frame-rate fixes are such edits);
- nx2/vecfp.py's helpers (A64_VECFP: a64_vfpx_q_...) end a run: they have not been checked inside the MXCSR window.
"""
import os
import re
import a64_lift
import a64emit
# (the kit's names the copied method reads; nothing in nx2 rebinds them: nx2/insn.py replaces a64_lift.classify and
# a64emit.translate, which the method does not name, or names through the module. fp_is_frame is the kit's, its answers
# kept below)
from a64_lift import (COND, FLAG_REF, FP_STORE, FP_STORE_PRE, MG_NOT_STRAIGHT, REG_REF, SYNC_ALL, SYNC_BACK, SYNC_CALL,
SYNC_RELOAD, SYNC_RET, drop_flag_stores, frame_stores, local_here, local_regs, localize_regs,
pc_relative)
_frame = {}
def fp_is_frame(text):
"""a64_lift.fp_is_frame, kept by the text: the copied method below asks it of every instruction (14 million in a lift
of OoT, two regex searches each), of far fewer distinct texts"""
f = _frame.get(text)
if f is None:
f = _frame[text] = a64_lift.fp_is_frame(text)
return f
# (Triforce) Fast float regions (A64_FASTFP at lift time: off unless set; "1" on; "hot" the A64_HOT_FUNCS list only; "check"
# both copies every time, compared: see ff_region).
# Each float op on the exact path carries its own tests (~25 instructions around one SSE op). A straight run of
# instructions with no label, call, branch or system access inside (and no guest load after a guest store: see
# FF_STORE below; with A64_FASTFP_STORES=0 no store at all), holding at least A64_FASTFP_MIN (8) single-
# precision adds, subtracts, multiplies, divides or square roots, is emitted twice: a fast copy whose ops are plain SSE,
# with MXCSR's flags cleared before it and read once after, and the exact copy. A clean fast run is the Arm result: with
# no invalid operation (no NaN made), no denormal operand and no underflow (FTZ on under FPCR.FZ: a tiny result is
# flushed and flagged), IEEE single precision round-to-nearest is the same on both, except for a NaN result or a
# product, quotient or multiply-add of exactly 2^-126, which raise the invalid flag on purpose (a64_ff_guard_; the ops
# are asm with Arm's operand order all the same). Divide-by-zero and overflow give the same infinities; they and inexact
# are or-ed into FPSR. On an invalid, denormal or underflow flag the registers the run names are put back and the exact
# copy runs. Measured
# 2026-11-11 on OoT's f_820e1d60 in game (both run per call, compared): 0 mismatches in 150,000 calls, 1.79x faster.
# HOS_NO_FASTFP (run time, any value): the exact copies only, for comparisons.
FF_CALL = re.compile(r"\b((?:recomp|a64|A64|RECOMP)_\w+)\s*\(")
FF_PURE = {"recomp_load8", "recomp_load16", "recomp_load32", "recomp_load64", "recomp_ldp32", "recomp_ldp64",
"a64_vset64", "a64_vset128", "a64_vset_lo", "a64_vst16", "a64_fcmp32", "a64_fcmp64", "a64_vfcmp",
"recomp_fixed_to_fp", "recomp_fp_to_int", "recomp_fp_to_fixed", "recomp_umulh", "recomp_smulh",
"recomp_fp_estimate", "recomp_aes_sbox", "RECOMP_LIKELY", "RECOMP_UNLIKELY", "RECOMP_FPX_OPEN",
"RECOMP_FPX_FZ", "a64_fcmp32k", "a64_fcmp64k"}
# ((Triforce) nx2/fastvec.py's whole-register moves and byte shuffles: LDR Q as a64_vld16 (a guest load: FF_LOAD),
# DUP by element as a64_vdup, EXT as A64_EXT16 / A64_EXT8, TBL as a64_tbl1. Integer SSE on the registers, no float flag;
# before those rewrites the same instructions were recomp_ldp64 and memcpy / a64_vst16 blocks, which joined. Named after FF_PURE was
# written, they ended runs: in the lifted C of that lift, ~23,700 run ends within 6 statements of float ops on both
# sides in the functions play runs (8,100 a64_vld16, 7,500 a64_vdup, 6,700 A64_EXT16). A64_FASTFP_VMOVES=0 at lift time:
# they end a run again)
FF_VMOVES = {"a64_vld16", "a64_vdup", "A64_EXT16", "A64_EXT8", "a64_tbl1"}
FF_BAD = ("c->fpcr", "c->fpsr", "c->excl", "c->pc", "c->halted", "c->poll", "c->tpidr", "\x01", "goto ", "return",
"switch", "A64_PTR", "A64_MARK")
# (the exact blocks' own uses, safe in a region: FPCR read in a test (it doesn't change inside one: no MSR there), and
# FPSR's cumulative bits or-ed in (put back with the registers when the region runs again exactly). An MSR, or an MRS of
# FPSR, which would see a value the fast copy has not finished, still ends the run.)
FF_FP_OK = re.compile(r"c->fpcr\s*&|c->fpsr\s*\|=")
# ((Triforce) fma32_fma32: FMADD/FMSUB/FNMADD/FNMSUB and FMLA/FMLS S lanes, an FMA3 op where the build has one; see
# a64_ff_fma32_fma32 in FASTFP_HEADER)
FF_CONV = re.compile(r"\ba64_vfpx_(add32|sub32|mul32)\(|"
r"\ba64_fpx_(add32_add32|sub32_sub32|mul32_fma32|fma32_fma32|div32_div32|sqrt32_sqrt32)\(")
VREG_REF = re.compile(r"c->vreg\[(\d+)\]")
def fastfp_mode():
"""the mode: empty when A64_FASTFP is unset, empty or 0 (off: Triforce's default), else 1 (every function), hot or
check; anything else stops the lift, so a typo cannot turn the regions on or off unnoticed"""
v = os.environ.get("A64_FASTFP", "").strip().lower()
if v in ("", "0", "off", "false", "no"):
return ""
if v in ("1", "on", "true", "yes"):
return "1"
if v in ("hot", "check"):
return v
raise SystemExit("A64_FASTFP=%s: 0, 1, hot or check" % os.environ.get("A64_FASTFP"))
def ff_min():
v = os.environ.get("A64_FASTFP_MIN", "")
return int(v) if v.isdigit() else 8
# (Triforce) Guest stores inside a region (A64_FASTFP_STORES at lift time: on unless "0"). A plain store (STR, STP, with
# or without writeback, through any base: recomp_storeN / recomp_stpN and their _sp forms) may join a run, and the run is
# cut before a guest load that follows a store in it (ff_split), so every load of a region comes before every store of
# it. The exact copy is the lifted text as before. The fast copy does not store: each store's address and values go
# into locals (_ffaK, _ffdK, and _ffeK for a pair's second value) where the store stood, and once a64_ff_end has passed
# the stores run from them, in their order, with the same helpers (so the same page marks), before the jump past the
# exact copy. On a flag that sends the run to its exact copy nothing has been stored, the registers are put back and the
# exact copy stores as before. The guest's memory sees the same accesses in the same order either way (the region's
# loads, then its stores), only later by the region's register work; another thread could see a store a few
# instructions later, never a different one or out of order. A store through x29 that the function's frame stores would
# make an unmarked _sp store (a64_lift.frame_stores) names its locals _ffp..., and ff_frame_stores does the same to the
# deferred one. Not joined: STLR (a plain recomp_storeN(c,c->x[N],...), as mark_groups reads it), a store under a
# condition (MG_NOT_STRAIGHT), and a text whose own load follows its store; exclusive, atomic and memcpy (A64_PTR)
# stores stay out by FF_BAD.
FF_STORE = re.compile(r"\brecomp_(store8|store16|store32|store64|stp32|stp64)(_sp)?\(")
FF_STORE_SIZE = {"store8": 8, "store16": 16, "store32": 32, "store64": 64, "stp32": 32, "stp64": 64}
FF_LOAD = re.compile(r"\b(?:recomp_(?:load(?:8|16|32|64)|ldp(?:32|64))|a64_vld16)\(")
FF_STLR = re.compile(r"\brecomp_(?:store|stp)\d+(?:_sp)?\(c,c->x\[\d+\],")
FF_FRAME = re.compile(r"\brecomp_(store8|store16|store32|store64|stp32|stp64)\(c,_ffp")
def ff_stores():
"""A64_FASTFP_STORES: guest stores may sit inside a region (on unless "0")"""
return os.environ.get("A64_FASTFP_STORES", "1") != "0"
def ff_args(text, at):
"""the top-level arguments of the call whose "(" is at text[at], and the index after its ")"; None if unbalanced"""
depth, args, start = 0, [], at + 1
for j in range(at, len(text)):
ch = text[j]
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
args.append(text[start:j].strip())
return args, j + 1
elif ch == "," and depth == 1:
args.append(text[start:j].strip())
start = j + 1
return None
def ff_store_ok(text):
"""a text with guest stores may join a region (ff_stores on): plain stores, each a whole statement of its own that
always runs, no load after the first one"""
if FF_STLR.search(text) or MG_NOT_STRAIGHT.search(text):
return False
first = None
for m in FF_STORE.finditer(text):
first = m.start() if first is None else first
p = ff_args(text, m.end() - 1)
if p is None or p[0][0] != "c" or len(p[0]) != (4 if m.group(1).startswith("stp") else 3):
return False
if not text[p[1]:].lstrip().startswith(";") or text[:m.start()].rstrip()[-1:] not in ("", ";", "{", "}"):
return False
return first is None or not FF_LOAD.search(text, first)
def ff_vmoves():
"""A64_FASTFP_VMOVES: nx2/fastvec.py's vector moves and shuffles (FF_VMOVES) may sit inside a region (on unless "0")"""
return os.environ.get("A64_FASTFP_VMOVES", "1") != "0"
def ff_eligible(text, stores=None):
"""an instruction's C text may sit inside a fast float region: no control flow or system state; only pure calls, and
guest stores when stores (ff_stores() unless given) and ff_store_ok"""
rest = FF_FP_OK.sub("", text)
if any(b in rest for b in FF_BAD):
return False
names = FF_CALL.findall(text)
if any(n.startswith("a64_vfpx_q_") for n in names): # ((Triforce) nx2/vecfp.py's fast paths: not inside a region)
return False
pure = FF_PURE | FF_VMOVES if ff_vmoves() else FF_PURE
if all(n in pure or n.startswith(("a64_fpx_", "a64_vfpx_")) for n in names):
return True
if not (ff_stores() if stores is None else stores):
return False
return all(n in pure or n.startswith(("a64_fpx_", "a64_vfpx_")) or FF_STORE.match(n + "(") for n in names) and \
ff_store_ok(text)
def ff_split(items):
"""a run cut into the parts a region may hold: a new part before each instruction with a guest load that follows a
guest store of the part so far (no load after a store inside a region, so the stores can wait for its end)"""
parts, cur, stored = [], [], False
for item in items:
t = item[1]
if stored and ("recomp_l" in t or "a64_vld16" in t) and FF_LOAD.search(t):
parts.append(cur)
cur, stored = [], False
cur.append(item)
if "recomp_st" in t and FF_STORE.search(t):
stored = True
if cur:
parts.append(cur)
return parts
def ff_defer(text, k, record=False):
"""one instruction's text with its guest stores written as assignments of their address and values to the region's
locals, numbered from k: (the text, [(helper, locals' prefix, number, pair)]). record: the stores kept, each after its
assignment (the check copy's exact text, A64_FASTFP=check)"""
if "recomp_st" not in text:
return text, []
out, stores, at = [], [], 0
for m in FF_STORE.finditer(text):
if m.start() < at:
continue
args, end = ff_args(text, m.end() - 1)
name = "recomp_%s%s" % (m.group(1), m.group(2) or "")
frame = not m.group(2) and (FP_STORE.match(text, m.start()) is not None or
any(p.end(1) == m.start() for p in FP_STORE_PRE.finditer(text)))
pre = ("_ffp" if frame else "_ff") + ("o" if record else "")
vals = ["%sa%d=(%s)" % (pre, k, args[1]), "%sd%d=(%s)" % (pre, k, args[2])]
if len(args) == 4:
vals.append("%se%d=(%s)" % (pre, k, args[3]))
if record:
vals.append("%s(c,%sa%d,%sd%d%s)" % (name, pre, k, pre, k, ",%se%d" % (pre, k) if len(args) == 4 else ""))
out.append(text[at:m.start()] + "(" + ",".join(vals) + ")")
stores.append((name, pre, k, len(args) == 4))
at, k = end, k + 1
out.append(text[at:])
return "".join(out), stores
def ff_frame_stores(text):
"""the deferred stores through x29 (their locals named _ffp...) as frame_stores makes their exact copies: _sp, unmarked.
Run where emit_function runs frame_stores"""
return FF_FRAME.sub(r"recomp_\1_sp(c,_ffp", text) if "(c,_ffp" in text else text
_patched_addrs = [None] # (set_patched: mentioned_addresses below, asked once a process)
_patched = [] # (those addresses: [sorted list, set]; made on first use)
def ff_patched(e, body, pcs):
"""the function at e (its body, pcs: its addresses in order) holds an address the game's patches name, its entry or
an instruction's (patch_sources: an edit of the lifted text pins its place by one). (Triforce) Such a function gets
no region: an edit's text must stay one text, in the one copy that runs"""
if not _patched:
addrs = sorted(_patched_addrs[0]()) if _patched_addrs[0] else []
_patched[:] = [addrs, set(addrs)]
addrs, aset = _patched
if not addrs or not pcs:
return False
if e in aset:
return True
import bisect
for i in range(bisect.bisect_left(addrs, pcs[0]), bisect.bisect_right(addrs, pcs[-1])):
if addrs[i] in body:
return True
return False
def ff_regions(items, least=None, stores=None):
"""a run's C text, cut by ff_split and each part through ff_region: (text, regions made, float ops made fast). stores:
the run may hold guest stores (ff_stores() unless given; emit_function: not in a function the game's patches edit)"""
least = ff_min() if least is None else least
if not (ff_stores() if stores is None else stores) or len(items) < 2 or \
not any("recomp_st" in t for _, t in items) or sum(ff_convs(t) for _, t in items) < least:
text, n = ff_region(items, least) # (no store, or too few ops for any part of it: as before)
return text, int(n > 0), n
texts, regions, ops = [], 0, 0
for part in ff_split(items):
text, n = ff_region(part, least)
texts.append(text)
regions, ops = regions + (n > 0), ops + n
return "\n".join(texts), regions, ops
# (the emit asks these of every instruction of every function, ~13 million times in a lift of OoT, but there are far fewer
# distinct instruction texts: each answer is kept by its text. Before, ff_eligible ran its FF_FP_OK.sub once for each of
# FF_BAD's 13 words, on every instruction, and emit and write took 106 s where it took ~46 s without the regions)
_joins = {}
_convs = {}
def ff_joins(text, dead, stores=False):
"""ff_eligible of an instruction's text with the flag stores dead there (dead_flags' mask) dropped, by (text, dead,
stores)"""
j = _joins.get((text, dead, stores))
if j is None:
j = _joins[(text, dead, stores)] = ff_eligible(drop_flag_stores(text, dead) if dead else text, stores)
return j
def ff_convs(text):
"""the float ops ff_region can make fast in one instruction's text (FF_CONV's matches)"""
n = _convs.get(text)
if n is None:
n = _convs[text] = len(FF_CONV.findall(text))
return n
def ff_region(items, least=None):
"""a run's C text ([(pc, text)], every text ff_eligible): the fast and exact copies, or the exact text alone when the
run has too few float ops to pay for its check. (text, number of ops made fast). least: ff_min(), read once by the
caller (emit_function: once a function, not for each of the 3.8 million runs of OoT)"""
exact = "\n".join(t for _, t in items)
# (FF_CONV's matches are in one instruction's text each, so the run's count is their sum: most runs are a few
# instructions with no float op, and only a run with enough of them is searched again below)
n = sum(ff_convs(t) for _, t in items)
if n < (ff_min() if least is None else least):
return exact, 0
# (guest stores, FF_STORE: the fast copy's assign their address and values to locals, stored once a64_ff_end passed)
stores = []
if "recomp_st" in exact:
fast_items = []
for _, t in items:
t, s = ff_defer(t, len(stores))
fast_items.append(t)
stores += s
fast = "\n".join(fast_items)
else:
fast = exact
fast = FF_CONV.sub(lambda m: "a64_ff_v%s(" % m.group(1) if m.group(1) else "a64_ff_%s(" % m.group(2), fast)
xs = sorted({int(r) for r in REG_REF.findall(exact)})
vs = sorted({int(r) for r in VREG_REF.findall(exact)})
fl = sorted(set(FLAG_REF.findall(exact)))
save = ("".join("const uint64_t _ffx%d = c->x[%d]; " % (r, r) for r in xs) +
"".join("const uint64_t _ffv%d0 = c->vreg[%d][0], _ffv%d1 = c->vreg[%d][1]; " % (r, r, r, r) for r in vs) +
"".join("const uint8_t _fff%s = c->%s; " % (f, f) for f in fl) + "const uint64_t _ffsr = c->fpsr; ")
restore = ("".join("c->x[%d] = _ffx%d; " % (r, r) for r in xs) +
"".join("c->vreg[%d][0] = _ffv%d0; c->vreg[%d][1] = _ffv%d1; " % (r, r, r, r) for r in vs) +
"".join("c->%s = _fff%s; " % (f, f) for f in fl) + "c->fpsr = _ffsr; ")
label = "L_ff_%08x" % items[0][0]
# (the stores' locals, declared with the saved registers; and the stores, run once the fast copy is kept)
temps = "".join("uint64_t %sa%d, %sd%d%s; " % (p, k, p, k, ", %se%d" % (p, k) if pair else "")
for _, p, k, pair in stores)
deferred = "".join("%s(c,%sa%d,%sd%d%s); " % (h, p, k, p, k, ",%se%d" % (p, k) if pair else "")
for h, p, k, pair in stores)
if fastfp_mode() == "check":
# (A64_FASTFP=check: both copies every time, the exact one's result kept, the registers the run names compared,
# and each store's address and values (the exact copy's noted as it stores, _ffo...); a64_ff_check counts and
# prints the first mismatches with the run's guest address. The fast copy stores nothing here)
keep = ("".join("const uint64_t _ffox%d = c->x[%d]; " % (r, r) for r in xs) +
"".join("const uint64_t _ffov%d0 = c->vreg[%d][0], _ffov%d1 = c->vreg[%d][1]; " % (r, r, r, r) for r in vs) +
"".join("const uint8_t _ffof%s = c->%s; " % (f, f) for f in fl))
same = " && ".join(["1"] + ["_ffox%d == c->x[%d]" % (r, r) for r in xs] +
["_ffov%d0 == c->vreg[%d][0] && _ffov%d1 == c->vreg[%d][1]" % (r, r, r, r) for r in vs] +
["_ffof%s == c->%s" % (f, f) for f in fl])
checked = exact
if stores:
checked, k = [], 0
for _, t in items:
t, s = ff_defer(t, k, record=True)
checked.append(t)
k += len(s)
checked = "\n".join(checked)
temps += "".join("uint64_t %soa%d, %sod%d%s; " % (p, k, p, k, ", %soe%d" % (p, k) if pair else "")
for _, p, k, pair in stores)
for h, p, k, pair in stores:
ty = "uint%d_t" % FF_STORE_SIZE[h[len("recomp_"):].replace("_sp", "")]
same += " && %sa%d == %soa%d && (%s)%sd%d == (%s)%sod%d" % (p, k, p, k, ty, p, k, ty, p, k)
if pair:
same += " && (%s)%se%d == (%s)%soe%d" % (ty, p, k, ty, p, k)
# (the "}" of its else not at the start of a line: one there closes the function, nx2/oot_patches.py and nx2/chunks.py)
return ("{ if (A64_FF_ON(c)) { %s%sconst unsigned _ffm = a64_ff_begin(c);\n%s\n"
"const int _ffok = a64_ff_end(c, _ffm);\n%s%s\n%s\na64_ff_check(0x%xu, _ffok, %s); } else {\n%s\n } }"
% (save, temps, fast, keep, restore, checked, items[0][0], same, exact)), n
if stores:
return ("{ if (A64_FF_ON(c)) { %s%sconst unsigned _ffm = a64_ff_begin(c);\n%s\n"
"if (RECOMP_LIKELY(a64_ff_end(c, _ffm))) { %sgoto %s; }\n%s}\n%s\n%s:; }"
% (save, temps, fast, deferred, label, restore, exact, label)), n
return ("{ if (A64_FF_ON(c)) { %sconst unsigned _ffm = a64_ff_begin(c);\n%s\n"
"if (RECOMP_LIKELY(a64_ff_end(c, _ffm))) goto %s;\n%s}\n%s\n%s:; }"
% (save, fast, label, restore, exact, label)), n
FASTFP_HEADER = r"""
/* ---- (Triforce) fast float regions (A64_FASTFP, ff_region in a64_lift.py) ---- */
#if RECOMP_FPX_HOST == 2 && defined(__x86_64__) && !defined(__EMSCRIPTEN__)
#include <stdlib.h>
#include <stdio.h>
static inline __attribute__((always_inline)) int a64_ff_enabled_(void) { static int v = -1; if (v < 0) v = !getenv("HOS_NO_FASTFP"); return v; }
#define A64_FF_ON(c) (RECOMP_FPX_OPEN(c) && a64_ff_enabled_())
/* MXCSR: exceptions masked, round to nearest, DAZ off, FTZ as FPCR.FZ, flags cleared; the old value returned */
static inline __attribute__((always_inline)) unsigned a64_ff_begin(const Ctx *c) {
unsigned m, n;
__asm__ volatile("stmxcsr %0" : "=m"(m));
n = (m & ~0xE07Fu) | 0x1F80u | (RECOMP_FPX_FZ(c) ? 0x8000u : 0u);
__asm__ volatile("ldmxcsr %0" : : "m"(n));
return m;
}
/* 0: an invalid, denormal or underflow flag (the exact copy runs); else inexact, overflow, divide-by-zero to FPSR */
static inline __attribute__((always_inline)) int a64_ff_end(Ctx *c, unsigned m) {
unsigned f;
__asm__ volatile("stmxcsr %0" : "=m"(f));
__asm__ volatile("ldmxcsr %0" : : "m"(m));
if (f & 0x13u) return 0;
c->fpsr |= (f & 0x20u ? 0x10u : 0u) | (f & 0x08u ? 0x04u : 0u) | (f & 0x04u ? 0x02u : 0u);
return 1;
}
/* (asm volatile: kept inside the MXCSR window and in Arm's operand order, see ff_region) */
#ifdef __AVX__
#define A64_FF_OP(ins, d, a, b) __asm__ volatile("v" ins " %2, %1, %0" : "=x"(d) : "x"(a), "x"(b))
#define A64_FF_SQRT(d, a) __asm__ volatile("vsqrtss %1, %1, %0" : "=x"(d) : "x"(a))
#define A64_FF_SPOIL "vcomiss %0, %0"
#else
#define A64_FF_OP(ins, d, a, b) do { (d) = (a); __asm__ volatile(ins " %1, %0" : "+x"(d) : "x"(b)); } while (0)
#define A64_FF_SQRT(d, a) __asm__ volatile("sqrtss %1, %0" : "=x"(d) : "x"(a))
#define A64_FF_SPOIL "comiss %0, %0"
#endif
/* The invalid flag raised on purpose (a signalling compare of a NaN), sending the run to its exact copy, for two results
whose value x86 gets right but not Arm's flags, or under FZ not Arm's value (found by tests/test_fastfp_fma.py):
- a NaN: x86 raises no denormal flag for a subnormal next to a NaN operand, where Arm under FZ flushes it and sets
IDC; and a multiply-add's 0 * inf + a quiet NaN gives that NaN with no flag (Arm: the default NaN, IOC);
- exactly 2^-126, the smallest normal, from a multiply, divide or multiply-add: x86 detects tininess after rounding,
Arm before, so a result rounded up to 2^-126 sets UFC on Arm, and is a zero under FZ. (A sum this small is exact.)
The tests are integer compares on the bits: a float compare would raise the denormal flag on a subnormal result. */
static inline __attribute__((always_inline)) void a64_ff_spoil_(void) {
__asm__ volatile(A64_FF_SPOIL : : "x"(_mm_castsi128_ps(_mm_cvtsi32_si128(0x7fc00000))) : "cc");
}
static inline __attribute__((always_inline)) void a64_ff_guard_(uint64_t v, int tiny) {
const uint32_t m = (uint32_t)v & 0x7fffffffu;
if (__builtin_expect(m > 0x7f800000u || (tiny && m == 0x00800000u), 0)) a64_ff_spoil_();
}
static inline __attribute__((always_inline)) void a64_ff_vguard_(__m128 r, int k, int tiny) { /* (the k lanes kept) */
const __m128i m = _mm_and_si128(_mm_castps_si128(r), _mm_set1_epi32(0x7fffffff));
__m128i bad = _mm_cmpgt_epi32(m, _mm_set1_epi32(0x7f800000));
if (tiny) bad = _mm_or_si128(bad, _mm_cmpeq_epi32(m, _mm_set1_epi32(0x00800000)));
if (__builtin_expect(_mm_movemask_ps(_mm_castsi128_ps(bad)) & (k == 4 ? 15 : 3), 0)) a64_ff_spoil_();
}
/* (2 lanes: the upper two are loaded as zeros, so they raise no flag of their own) */
static inline __attribute__((always_inline)) __m128 a64_ff_vld(const uint64_t *s, int k) {
return k == 4 ? _mm_loadu_ps((const float *)s) : _mm_castsi128_ps(_mm_loadl_epi64((const __m128i *)s));
}
static inline __attribute__((always_inline)) void a64_ff_vst(uint64_t *d, __m128 r, int k) {
if (k == 4) _mm_storeu_ps((float *)d, r); else _mm_storeu_si128((__m128i *)d, _mm_move_epi64(_mm_castps_si128(r)));
}
#define A64_FF_V(name, ins, tiny) \
static inline __attribute__((always_inline)) void a64_ff_v##name(Ctx *c, uint64_t *d, const uint64_t *n, const uint64_t *m, int k) { \
__m128 r; (void)c; A64_FF_OP(ins, r, a64_ff_vld(n, k), a64_ff_vld(m, k)); \
a64_ff_vguard_(r, k, tiny); a64_ff_vst(d, r, k); }
A64_FF_V(add32, "addps", 0)
A64_FF_V(sub32, "subps", 0)
A64_FF_V(mul32, "mulps", 1)
static inline __attribute__((always_inline)) __m128 a64_ff_ss(uint64_t a) { return _mm_castsi128_ps(_mm_cvtsi32_si128((int)(uint32_t)a)); }
static inline __attribute__((always_inline)) uint64_t a64_ff_bits(__m128 r) { return (uint32_t)_mm_cvtsi128_si32(_mm_castps_si128(r)); }
#define A64_FF_S(name, ins, tiny) \
static inline __attribute__((always_inline)) uint64_t a64_ff_##name(Ctx *c, uint64_t a, uint64_t b) { \
__m128 r; (void)c; A64_FF_OP(ins, r, a64_ff_ss(a), a64_ff_ss(b)); a64_ff_guard_(a64_ff_bits(r), tiny); return a64_ff_bits(r); }
A64_FF_S(add32_add32, "addss", 0)
A64_FF_S(sub32_sub32, "subss", 0)
/* (A subnormal over a zero also takes the exact copy: x86 raises no denormal flag beside divide-by-zero and gives an
infinity, where Arm under FZ flushes the subnormal first, 0 / 0: the default NaN and IOC.) */
static inline __attribute__((always_inline)) uint64_t a64_ff_div32_div32(Ctx *c, uint64_t a, uint64_t b) {
__m128 r;
(void)c;
if (__builtin_expect(((uint32_t)b << 1) == 0 && ((uint32_t)a << 1) - 1u < 0x00ffffffu, 0)) a64_ff_spoil_();
A64_FF_OP("divss", r, a64_ff_ss(a), a64_ff_ss(b));
a64_ff_guard_(a64_ff_bits(r), 1);
return a64_ff_bits(r);
}
A64_FF_S(mul32_, "mulss", 1)
static inline __attribute__((always_inline)) uint64_t a64_ff_mul32_fma32(Ctx *c, uint64_t a, uint64_t b, uint64_t z) { (void)z; return a64_ff_mul32_(c, a, b); }
static inline __attribute__((always_inline)) uint64_t a64_ff_sqrt32_sqrt32(Ctx *c, uint64_t a) { __m128 r; (void)c; A64_FF_SQRT(r, a64_ff_ss(a)); return a64_ff_bits(r); }
/* (Triforce) FMADD/FMSUB/FNMADD/FNMSUB and FMLA/FMLS S lanes: a64_fpx_fma32_fma32(c, a, b, z) is a*b + z, the lifted
code having already flipped the signs the op negates. FMA3's vfmadd231ss rounds once, as Arm does, and takes its
NaN in Arm's order (the addend, then a, then b). Two cases differ, and both raise the invalid flag here (a64_ff_guard_),
which sends the run to its exact copy:
- 0 * inf + a quiet NaN: x86 returns that NaN with no flag, Arm the default NaN with IOC (so: any NaN result);
- a result rounded up to the smallest normal, 2^-126: x86 detects tininess after rounding and raises no underflow,
Arm detects it before, sets UFC, and under FZ returns a zero.
Without FMA3 (x86-64-v2), the exact helper. */
#ifdef __FMA__
static inline __attribute__((always_inline)) uint64_t a64_ff_fma32_fma32(Ctx *c, uint64_t a, uint64_t b, uint64_t z) {
__m128 r = a64_ff_ss(z);
(void)c;
__asm__ volatile("vfmadd231ss %2, %1, %0" : "+x"(r) : "x"(a64_ff_ss(a)), "x"(a64_ff_ss(b)));
a64_ff_guard_(a64_ff_bits(r), 1);
return a64_ff_bits(r);
}
#else
#define a64_ff_fma32_fma32 a64_fpx_fma32_fma32
#endif
/* (A64_FASTFP=check) a run's result: counts per file, and the first mismatches of a clean fast run (which must not
happen) with the run's guest address, on stderr (the game's log) */
static volatile long long a64_ff_n_[3]; /* runs, clean, mismatched when clean */
static __attribute__((noinline, cold)) void a64_ff_check_print_(unsigned pc, long long bad) {
if (bad < 16) fprintf(stderr, "fastfp check: MISMATCH in the run at %#x (%s)\n", pc, __BASE_FILE__);
}
static inline __attribute__((always_inline)) void a64_ff_check(unsigned pc, int clean, int same) {
const long long n = __atomic_add_fetch(&a64_ff_n_[0], 1, __ATOMIC_RELAXED);
if (clean) __atomic_add_fetch(&a64_ff_n_[1], 1, __ATOMIC_RELAXED);
if (clean && !same) a64_ff_check_print_(pc, __atomic_fetch_add(&a64_ff_n_[2], 1, __ATOMIC_RELAXED));
if (!(n & ((1LL << 22) - 1)))
fprintf(stderr, "fastfp check: %s: %lld runs, %lld clean, %lld mismatched when clean\n", __BASE_FILE__, n, a64_ff_n_[1], a64_ff_n_[2]);
}
#else
/* (no x86 MXCSR here: the fast copies are never run, and name the exact helpers) */
#define A64_FF_ON(c) 0
#define a64_ff_begin(c) 0u
#define a64_ff_end(c, m) 1
#define a64_ff_vadd32 a64_vfpx_add32
#define a64_ff_vsub32 a64_vfpx_sub32
#define a64_ff_vmul32 a64_vfpx_mul32
#define a64_ff_add32_add32 a64_fpx_add32_add32
#define a64_ff_sub32_sub32 a64_fpx_sub32_sub32
#define a64_ff_mul32_fma32 a64_fpx_mul32_fma32
#define a64_ff_fma32_fma32 a64_fpx_fma32_fma32
#define a64_ff_div32_div32 a64_fpx_div32_div32
#define a64_ff_sqrt32_sqrt32 a64_fpx_sqrt32_sqrt32
#define a64_ff_check(pc, clean, same) ((void)0)
#endif
"""
_ff_only = []
def ff_only():
"""A64_FASTFP=hot: the names of the hot functions (A64_HOT_FUNCS), whose runs alone are made regions; else None. Read here
rather than kept on the lifter, so the lift's new processes, which get only its tables, decide as the lift does"""
if not _ff_only:
_ff_only.append(a64_lift.hot_functions() if fastfp_mode() == "hot" else None)
return _ff_only[0]
# ---- the kit's Lifter.emit_function, with the run gathering (a copy: see the module's note) ----
def emit_function(self, e, texts):
"""C text of one function, and the set of C names it calls."""
body, labels = self.funcs[e]
self.cur = e
self.refs = set()
out = ["void f_%08x(Ctx *__restrict A64_NOESC c) {" % e]
if e in self.names and self.comments:
out[0] = "/* %s */\n" % self.names[e] + out[0]
if e in self.plt: # a PLT stub reached indirectly: x16 = GOT slot, x17 = target, as the stub leaves them
t, slot = self.plt[e]
name = self.fname(self.callee(t))
self.refs.add(name)
out.append("c->x[16] = 0x%xULL; c->x[17] = 0x%xULL; TAILCALL(%s);\n}" % (slot, t, name))
return "\n".join(out) + "\n", self.refs
pcs = sorted(body)
dead = {} if os.environ.get("A64_KEEP_FLAGS") else self.dead_flags(body, pcs, texts)
frame = not os.environ.get("A64_MARK_FRAME")
local = local_regs() and e not in self.no_local and local_here(self.fname(e))
dirty = self.dirty_regs(body, pcs, texts) if local else None
# (the run of joinable instructions so far, [(pc, text)]: ff_region) # (fastfp)
# ((Triforce) and none in a function the game's patches name: ff_patched) # (fastfp)
ff = bool(fastfp_mode()) and (ff_only() is None or self.fname(e) in ff_only()) and not ff_patched(e, body, pcs) # (fastfp)
least = ff_min() # (fastfp)
# (guest stores may join a run (A64_FASTFP_STORES)) # (fastfp)
stores = ff and ff_stores() # (fastfp)
run = [] # (fastfp)
def flush(): # (fastfp)
if run: # (fastfp)
text, k, n = ff_regions(run, least, stores) # (fastfp)
out.append(text) # (fastfp)
if n: # (fastfp)
self.stats["ff_regions"] = self.stats.get("ff_regions", 0) + k # (fastfp)
self.stats["ff_ops"] = self.stats.get("ff_ops", 0) + n # (fastfp)
del run[:] # (fastfp)
for i, pc in enumerate(pcs):
self.cur_i = i
(k, w) = body[pc]
kind = k[0]
# (an instruction joins the run when nothing can enter or leave between it and the next: no label, no patch after # (fastfp)
# it, an op a64emit handled, whose text ff_eligible takes; what it appends below goes to the run instead) # (fastfp)
joins = False # (fastfp)
if ff and kind == "op" and pc not in self.after and not (pc in labels or (pc == e and e in labels)): # (fastfp)
t, f = texts[(w, pc) if pc_relative(w) else w] # (fastfp)
if not f & (a64emit.UNHANDLED | a64emit.TERMINATOR): # (fastfp)
joins = ff_joins(t, dead.get(pc, 0), stores) # (fastfp)
if not joins: # (fastfp)
flush() # (fastfp)
mark = len(out) # (fastfp)
if pc in labels or (pc == e and e in labels):
out.append("L_%08x:;" % pc)
if self.comments:
out.append("/* %08x: %08x */" % (pc, w))
nxt = pc + 4
falls = True
if kind == "op":
text, flags = texts[(w, pc) if pc_relative(w) else w]
if flags & a64emit.UNHANDLED:
self.unhandled[w] += 1
out.append(SYNC_ALL % i + "a64_trap(c, 0x%xULL, 0x%08xu); return;" % (pc, w))
falls = False
elif flags & a64emit.TERMINATOR:
raise SystemExit("a64emit closed a block at %#x (%08x): classify() must handle it" % (pc, w))
else:
if frame and not fp_is_frame(text):
frame = False
if pc in dead:
text = drop_flag_stores(text, dead[pc])
self.stats["dead_flag_stores"] += bin(dead[pc]).count("1")
out.append(text.rstrip("\n"))
if pc in self.after:
out.append(self.after[pc])
self.stats["after_patches"] = self.stats.get("after_patches", 0) + 1
elif kind == "b":
out.append(self.transfer(pc, k[1], labels, body))
falls = False
elif kind == "bcond":
out.append("if %s { %s }" % (COND[k[2]], self.transfer(pc, k[1], labels, body)))
elif kind == "cbz":
_, t, rt, sf, nz = k
v = "0" if rt == 31 else ("c->x[%d]" % rt if sf else "(uint32_t)c->x[%d]" % rt)
out.append("if (%s %s 0) { %s }" % (v, "!=" if nz else "==", self.transfer(pc, t, labels, body)))
elif kind == "tbz":
_, t, rt, bit, nz = k
v = "0" if rt == 31 else "((c->x[%d] >> %d) & 1)" % (rt, bit)
out.append("if (%s%s) { %s }" % ("" if nz else "!", v, self.transfer(pc, t, labels, body)))
elif kind == "bl":
t = self.callee(k[1])
if t in self.entries and t in getattr(self, "setjmp_owner", {}):
# (hookshot) a call of a function that calls __setjmp: this frame takes a host setjmp. A guest
# longjmp's BR to one of the owner's setjmp return addresses comes back here (host/hos_setjmp.c),
# with the registers it restored, and runs the owner's code from there, as the owner would.
# (recomp_sj_setjmp, not __builtin_setjmp: on Win64 clang's frame pointer sits above the frame
# address the builtin saves, and its longjmp restored rbp to that, so the frame's spill slots
# were read 128 bytes off: c and _sj came back as garbage)
rets = (self.setjmp_owner[t] + [0, 0, 0, 0])[:4]
out.append("c->x[30] = 0x%xULL; %s{ void **_sj = recomp_sj_push(c, 0x%xULL, 0x%xULL, 0x%xULL, 0x%xULL); "
"if (recomp_sj_setjmp(_sj) == 0) %s(c); else a64_icall(c, recomp_sj_target(_sj)); "
"recomp_sj_pop(_sj); }%s"
% (nxt, SYNC_CALL % i, rets[0], rets[1], rets[2], rets[3], self.fname(t), SYNC_BACK % i))
self.refs.add(self.fname(t))
self.stats["setjmp_call_sites"] = self.stats.get("setjmp_call_sites", 0) + 1
elif t in self.entries:
out.append("c->x[30] = 0x%xULL; %s%s(c);%s" % (nxt, SYNC_CALL % i, self.fname(t), SYNC_BACK % i))
self.refs.add(self.fname(t))
else:
self.stats["bad_target"] += 1
out.append(SYNC_ALL % i + "a64_trap(c, 0x%xULL, 0x%08xu); return;" % (pc, w))
elif kind == "blr":
usual = self.devirt.get(pc)
if usual in self.entries:
name = self.fname(self.callee(usual))
self.refs.add(name)
self.stats["devirt_sites"] += 1
out.append("{ uint64_t _t = c->x[%d]; c->x[30] = 0x%xULL; %sif (RECOMP_LIKELY(_t == 0x%xULL)) %s(c); "
"else A64_ICALL(c, _t); %s}" % (k[1], nxt, SYNC_CALL % i, usual, name, SYNC_BACK % i))
else:
out.append("{ uint64_t _t = c->x[%d]; c->x[30] = 0x%xULL; %sA64_ICALL(c, _t); %s}"
% (k[1], nxt, SYNC_CALL % i, SYNC_BACK % i))
elif kind == "ret":
out.append(SYNC_RET % i + "return;")
falls = False
elif kind == "br":
targets = self.jt.get(pc)
if targets:
cases = " ".join("case 0x%xULL: %s" % (t, self.transfer(pc, t, labels, body))
for t in sorted(set(targets)))
out.append("switch (c->x[%d]) { %s default: %sA64_IJUMP(c, c->x[%d]); return; }"
% (k[1], cases, SYNC_ALL % i, k[1]))
else:
self.ijump[pc] += 1
out.append(SYNC_ALL % i + "A64_IJUMP(c, c->x[%d]); return;" % k[1])
falls = False
elif kind == "svc":
out.append(SYNC_ALL % i + "a64_svc(c, %du);" % k[1] + SYNC_RELOAD % i)
elif kind == "trap":
out.append(SYNC_ALL % i + "a64_trap(c, 0x%xULL, 0x%08xu); return;" % (pc, w))
falls = False
elif kind == "isb":
out.append("recomp_barrier();")
elif kind == "ic":
out.append("/* ic ivau: no self-modifying code */")
if joins: # (fastfp)
run.extend((pc, t) for t in out[mark:]) # (fastfp)
del out[mark:] # (fastfp)
if falls and (i + 1 == len(pcs) or pcs[i + 1] != nxt): # (fastfp)
flush() # (fastfp)
if falls and (i + 1 == len(pcs) or pcs[i + 1] != nxt):
out.append(self.transfer(pc, nxt, labels, body))
flush() # (fastfp)
out.append("}")
text = "\n".join(out)
if frame:
text = frame_stores(text)
text = ff_frame_stores(text) # (fastfp)
return localize_regs(text, local, dirty) + "\n", self.refs
_installed = False
def set_patched(addresses):
"""addresses(): the guest addresses the game's patches name (mentioned_addresses below; ff_patched)"""
_patched_addrs[0] = addresses
del _patched[:]
# (Triforce) The files of nx2/ that edit the lifted C by its exact text after the lift (nx2/chunks.py edit_c runs them), or
# splice C after an instruction at lift time: every guest code address one of them names is taken as a place an edit may
# change. All of them are files of the lift key (nx2/make_game.py lift_key), so a change of one lifts again.
# tests/test_fastfp_override.py holds this list to the files of nx2/ that name a lifted function or label.
PATCH_SOURCES = ("oot_patches.py", "oot_native_resolution.py", "oot_wide.py", "oot_jitter.py", "oot_occlusion.py")
_ADDRESS = re.compile(r"(?:f_|L_|0x)(8[0-9a-fA-F]{7})(?![0-9a-fA-F])")
def mentioned_addresses():
"""Every guest code address PATCH_SOURCES name: a function (f_8...), a label (L_8...), a hex address (a call's return
address 0x8...ULL, a table of sites, an entry given as a number). An address named for another reason costs one
function its regions"""
here = os.path.dirname(os.path.abspath(__file__))
out = set()
for name in PATCH_SOURCES:
path = os.path.join(here, name)
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
out |= {int(a, 16) for a in _ADDRESS.findall(f.read())}
return out
_patched_addrs[0] = mentioned_addresses
# (Triforce) The rule above goes by the addresses the patches' files name. The check below goes by what the patches did: a
# function that has a region and that nx2/oot_patches.py's apply then changed stops the lift, with its name. An edit that
# finds its place by text alone, in a function none of those files names, would otherwise change one copy of a region's
# instructions and leave the other. The lift of the supported game is the same on every PC, so a lift that passes here
# passes there.
_FN_HEAD = re.compile(r"^void (f_[0-9a-f]{8})\(Ctx \*__restrict A64_NOESC c\) \{", re.M)
def region_functions(gen):
"""{function name: a hash of its text} for the lifted functions of gen's code files that hold a region"""
import glob
import hashlib
out = {}
for path in sorted(glob.glob(os.path.join(glob.escape(gen), "code_*.c"))):
with open(path, encoding="utf-8", newline="") as f:
text = f.read()
if "A64_FF_ON(c)" not in text:
continue
heads = [(m.start(), m.group(1)) for m in _FN_HEAD.finditer(text)]
for (a, name), (b, _) in zip(heads, heads[1:] + [(len(text), None)]):
if text.find("A64_FF_ON(c)", a, b) >= 0:
out[name] = hashlib.sha1(text[a:b].encode("utf-8"), usedforsecurity=False).digest()
return out
def guard_patches(patches):
"""patches (the module nx2/oot_patches.py): its apply wrapped, for a lift with regions (nothing otherwise). Once"""
if not fastfp_mode() or getattr(patches.apply, "_fastfp_guard", False):
return
base_apply = patches.apply
def apply(gen, *args, **kw):
before = region_functions(gen)
result = base_apply(gen, *args, **kw)
after = region_functions(gen)
changed = sorted(n for n, h in before.items() if after.get(n) != h)
if changed:
raise SystemExit("fastfp: the game's patches changed %d function(s) that hold a fast float region (%s): an edit "
"there reaches one copy of the region's instructions only. Name their addresses in a file of "
"nx2/fastfp.py's PATCH_SOURCES (or lift with A64_FASTFP=0)" % (len(changed), ", ".join(changed[:8])))
print("fast float regions: %d functions hold one; the game's patches changed none of them" % len(before), flush=True)
return result
apply._fastfp_guard = True
patches.apply = apply
def install():
"""emit_function above in place of the kit's, and Lifter.write wrapped (the header, the count). Once; before
nx2/lift_fixes.py's and nx2/poll.py's install(). (Triforce) Nothing with A64_FASTFP unset or 0: the kit's own method
stays, and the lift's C and a64_fpx.h are the kit's to the byte"""
global _installed
if _installed or not fastfp_mode():
return
_installed = True
a64_lift.Lifter.emit_function = emit_function
base_write = a64_lift.Lifter.write
def write(self, out_dir, chunk_bytes=a64_lift.CHUNK_BYTES):
files = base_write(self, out_dir, chunk_bytes=chunk_bytes)
mode = fastfp_mode()
if mode:
with open(os.path.join(out_dir, "a64_fpx.h"), "a", newline="\n") as f: # (after the kit's fpx and FCMP parts)
f.write(FASTFP_HEADER)
print("fast float regions (A64_FASTFP=%s): %d, %d float ops in them" % (
mode, self.stats.get("ff_regions", 0), self.stats.get("ff_ops", 0)))
return files
a64_lift.Lifter.write = write

View File

@@ -15,9 +15,56 @@ def host_march():
if pf(40):
return "x86-64-v3"
return "x86-64-v2" if pf(38) else "x86-64"
flags = open("/proc/cpuinfo").read().split("flags", 1)[1].split(chr(10), 1)[0].split()
with open("/proc/cpuinfo") as f:
flags = f.read().split("flags", 1)[1].split(chr(10), 1)[0].split()
if all(f in flags for f in want):
return "x86-64-v3"
return "x86-64-v2" if all(f in flags for f in ("sse4_2", "popcnt", "ssse3")) else "x86-64"
except Exception:
return "x86-64-v3"
def host_mtune():
"""Tuning target for the host CPU (znver2 for the Steam Deck's APUs, 0405 and 0932: Zen 2 cores, which -march=x86-64-v3
alone leaves tuned for a generic CPU), or an empty string. RX_STEAMDECK=1 says so by hand; RX_MTUNE, read by build.py,
still chooses"""
if os.environ.get("RX_STEAMDECK") == "1":
return "znver2"
if os.name != "nt":
try:
with open("/proc/cpuinfo") as f:
info = f.read()
if "Custom APU 0405" in info or "Custom APU 0932" in info:
return "znver2"
except Exception:
pass
return ""
def native_cpu(cc, flags):
"""((Triforce) HOOKSHOT_NATIVE_CPU) What clang makes of -march=native here, from `clang -###`: its -target-cpu, -tune-cpu and
-target-feature list, as "<cpu>_<tune>_<sha1 of the features>" (e.g. "znver4_znver4_3f1c09a2b4"). The flag itself names
no CPU, so an object key made from it would stay the same when the CPU changes (a new CPU, the disk in another PC);
build.py puts this name in the flags instead. None if clang doesn't say."""
import hashlib
import subprocess
try:
quiet = {"creationflags": 0x08000000} if os.name == "nt" else {} # (CREATE_NO_WINDOW: no console from the launcher)
out = subprocess.run([cc] + flags + ["-###", "-x", "c", "-c", os.devnull, "-o", os.devnull],
capture_output=True, text=True, timeout=60, **quiet).stderr
except Exception:
return None
words = [w.strip('"') for w in out.split()]
cpu = tune = ""
feats = []
for i, w in enumerate(words[:-1]):
if w == "-target-cpu":
cpu = words[i + 1]
elif w == "-tune-cpu":
tune = words[i + 1]
elif w == "-target-feature":
feats.append(words[i + 1])
if not cpu or cpu == "native":
return None
feats = hashlib.sha1(" ".join(sorted(feats)).encode(), usedforsecurity=False).hexdigest()[:10]
return "%s_%s_%s" % (cpu, tune or cpu, feats)

View File

@@ -10,6 +10,8 @@ the same offset.
rtld is part of this image: in the emulator it runs first and binds the GOTs itself, to the same values this
builder binds them to (same module order, same lookup).
"""
import sys
import kit # noqa: F401 (sys.path)
import nso2 # noqa: F401 (DT_RELR)
import nso
@@ -62,5 +64,29 @@ class EdenImage(nx_image.NxImage):
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.lookups()
self._entries()
self.names = self.symbol_names()
def lookups(self):
"""(after self.mem and self.code are made) the lift's discovery reads every instruction it walks through word() and
in_code(), 40 million times each for OoT, where NxImage's unpack a word with struct and loop over self.code each time.
Here the words are a view of the image as 32-bit numbers and the code ranges a flat tuple, with the same answers
(tests/test_lift_lookups.py)"""
self._base = nx_image.MAIN_BASE
self._spans = tuple((lo, hi) for lo, hi, _ in self.code)
self._words = memoryview(self.mem).cast("I") if sys.byteorder == "little" and len(self.mem) % 4 == 0 else None
def in_code(self, a):
if a & 3:
return False
for lo, hi in self._spans:
if lo <= a < hi:
return True
return False
def word(self, a):
off = a - self._base
if self._words is not None and not off & 3 and 0 <= off < len(self.mem):
return self._words[off >> 2]
return super().word(a)

View File

@@ -18,6 +18,14 @@ Model:
- Pointer authentication is the identity, as in Eglantine's dynarmic: PAC*/AUT* (register forms) and XPAC* leave
Xd unchanged, PACGA writes 0. Nothing in the game's own code can tell, since no pointer is ever signed.
- MTE: tags are always 0. STG/ST2G only do their base-register writeback.
- SCVTF / UCVTF (scalar, fixed-point: Sd, Sn, #fbits and Dd, Dn, #fbits), which suyu's translator lacks and the
game's own code doesn't use (a mod's code may): the integer in Vn's low 32 or 64 bits over 2^fbits, through suyu's
own recomp_fixed_to_fp (the helper of its general-register fixed-point form: the FPCR's rounding, IXC), the rest
of Vd cleared.
One form suyu does know is written here too, because its C is wrong for one input:
- SDIV: suyu's C divides as C does, and the most negative number divided by -1 is undefined there. x86's idiv traps
on it (#DE), where AArch64 gives the dividend back. sdiv() writes suyu's text with that case added.
"""
import os
@@ -120,6 +128,29 @@ def stg(w):
rn, imm, "2" if opc == 2 else "")
def sdiv(w):
"""SDIV Xd, Xn, Xm and Wd, Wn, Wm, as suyu writes them (arm64_to_c.h: 0 for a divisor of 0, a W result
zero-extended) but for the one quotient that does not fit: the most negative number divided by -1. AArch64 wraps
it, which gives the dividend back; C leaves that division undefined and x86's idiv traps on it, so lifted code
dividing like that killed the game with no message (SIGFPE; 0xC0000095 on Windows). A divisor of -1 is therefore
a negation in unsigned arithmetic, which wraps to the same value for every dividend. tests/test_sdiv_overflow.py
(Triforce) Written without a new comparison or conditional: _m is 1 for a divisor of -1 and 0 otherwise, made by
arithmetic alone (_t = divisor + 1 is 0 only then; (_t | -_t) has its top bit set unless _t is 0); the division is
then by 1 (-1 + 2 * _m), and its quotient negated ((q ^ -_m) + _m). The compiler's profile of a function (the hot
pieces', nx2/build.py RX_PGO) is matched by a count of the function's conditions, comparisons, labels and jumps:
one more `==` or `?:` here and every recorded function with a division in it would be compiled without its
profile until a new one is recorded. Suyu's own `_b?...:0` stays the only condition, and there is no branch."""
sf, rm, rn, rd = w >> 31, (w >> 16) & 31, (w >> 5) & 31, w & 31
if rd == 31:
return None # (the result is dropped: suyu writes no division for it either)
if sf:
return (" { int64_t _a=(int64_t)%s,_b=(int64_t)%s; uint64_t _t=(uint64_t)_b+1,_m=((_t|(0-_t))>>63)^1; "
"c->x[%d]=(uint64_t)(_b?(((uint64_t)(_a/(_b+(int64_t)(_m<<1))))^(0-_m))+_m:0); }" % (xr(rn), xr(rm), rd))
return (" { int32_t _a=(int32_t)(uint32_t)%s,_b=(int32_t)(uint32_t)%s; uint32_t _t=(uint32_t)_b+1u,_m=((_t|(0u-_t))>>31)^1u; "
"c->x[%d]=(uint64_t)(uint32_t)(_b?(((uint32_t)(_a/(_b+(int32_t)(_m<<1))))^(0u-_m))+_m:0); }" % (xr(rn), xr(rm), rd))
# ---- the few SIMD forms suyu lacks that MKW's sdk uses (62 sites) -------------------------------------
# Saturations set FPSR.QC (bit 27), as the hardware does.
QC = "c->fpsr |= 1u << 27;"
@@ -261,9 +292,24 @@ def emit(w):
return "/* pac/aut: pointer authentication is the identity */"
if (w & 0xFF200000) == 0xD9200000:
return stg(w)
if (w & 0x7FE0FC00) == 0x1AC00C00: # SDIV (suyu's own C traps on x86 for INT_MIN / -1)
return sdiv(w)
if (w & 0xDF80FC00) == 0x5F00E400 and (w >> 21) & 3: # SCVTF / UCVTF (scalar, fixed-point), S or D
return fixed_to_fp(w)
return None
def fixed_to_fp(w):
"""SCVTF / UCVTF Sd, Sn, #fbits or Dd, Dn, #fbits: immh 01xx is S (fbits = 64 - immh:immb), 1xxx is D
(fbits = 128 - immh:immb); immh 001x (H) is not taken. U (bit 29) is UCVTF"""
width = 64 if (w >> 22) & 1 else 32
fbits = 2 * width - ((w >> 16) & 0x7F)
rd, rn, signed = w & 31, (w >> 5) & 31, 0 if (w >> 29) & 1 else 1
mask = "UINT64_MAX" if width == 64 else "UINT64_C(0xffffffff)"
return ("{ uint64_t _r = recomp_fixed_to_fp(c->vreg[%d][0] & %s, %d, %d, %d, %d, c->fpcr, &c->fpsr); "
"c->vreg[%d][0] = _r; c->vreg[%d][1] = 0; }" % (rn, mask, width, width, fbits, signed, rd, rd))
def is_identity_model(w):
"""Forms whose result here is by design not the hardware's (PAC, MTE): instruction tests skip them."""
return ((w & 0xFFE0FC00) == 0x9AC03000 or (w & 0xFFFFFBE0) == 0xDAC143E0 or (w & 0xFFFFC000) == 0xDAC10000
@@ -282,8 +328,16 @@ def install():
base_classify = a64_lift.classify
base_translate = a64emit.translate
ops = set() # (words that are ("op",) at any pc: neither classify reads the pc for them)
OP = ("op",)
def classify(w, pc):
return classify_ext(w, pc) or base_classify(w, pc)
if w in ops: # (most of the 18 million words the discovery walks: one set lookup instead of both classifies)
return OP
k = classify_ext(w, pc) or base_classify(w, pc)
if k == OP:
ops.add(w)
return k
def translate(items, batch=65536):
mine = {}

View File

@@ -33,6 +33,11 @@ import fastvec
import fma_soft
import fma_steps
import vecfp
import cmpflags
import fastfp
import dead_flags
import walk
import discover
import chunks
import standalone
import adr_entries # noqa: E402
@@ -45,11 +50,15 @@ import a64_lift
import a64_rtgen
insn.install()
fastfp.install() # ((Triforce) fast float regions, with A64_FASTFP=1, hot or check: its emit_function in the kit's place, so before lift_fixes' and poll's wrappers of it: nx2/fastfp.py)
lift_fixes.install()
fastvec.install() # ((Triforce, 11-21, LIFT-02) TBL, EXT, 128-bit loads and DUP as one instruction each: nx2/fastvec.py)
fma_soft.install() # ((Triforce, 11-22, LIFT-06) the exact FMA bodies' short way out where the CPU has no FMA3: nx2/fma_soft.py)
fma_steps.install() # ((Triforce, 11-22, LIFT-05) FRECPS and FRSQRTS S as one fused instruction where the build has FMA3: nx2/fma_steps.py)
vecfp.install() # ((Triforce, 11-22, LIFT-03) SSE fast paths before float forms lifted lane by lane, with A64_VECFP=1: nx2/vecfp.py)
cmpflags.install() # ((Triforce) a subtraction's V flag in a form the compiler folds, with A64_SUB_V=1 or ovf: nx2/cmpflags.py)
dead_flags.install() # ((Triforce, 11-24) the kit's dead_flags answered at once for a function that writes no flag: nx2/dead_flags.py)
walk.install() # ((Triforce, 11-24) the kit's walk, one shared entry per plain op's word: nx2/walk.py)
def module_of(img, pc):
@@ -173,26 +182,35 @@ def main():
oot_jitter.install(L, img)
import oot_occlusion # (no occlusion queries when HOOKSHOT_OCCLUSION_OFF=1: Fritchii's Occlusion Off)
oot_occlusion.install(L, img)
L.discover(max_insns=a.max_func)
# ((Triforce, 11-24) its first loop's walks in spawned processes where there is no fork, the kit's result: nx2/discover.py)
discover.discover(L, img_dir, chunks.emit_jobs(), max_insns=a.max_func)
print("discovered %d functions (%.0fs)" % (len(L.funcs), time.time() - t0))
total = coverage(L, img, img_dir)
jt = L.stats
print("jump tables %d (bounded %d, bounded by function %d, ADR table %d), BR without a table %d, PLT stubs %d" % (
len(L.jt), jt["jt_bounded"], jt["jt_unbounded"], jt["jt_adr_table"], len(L.jt_missing), len(L.plt)))
if jt["jt_table_reg_reused"]:
print("jump tables whose table register is reused before the br: %d" % jt["jt_table_reg_reused"])
for pc, reg in sorted(L.jt_missing.items()):
print(" BR without a table: %#x (x%d)" % (pc, reg))
with open(os.path.join(img_dir, "functions.json"), "w") as f:
json.dump({"%x" % e: [len(b), module_of(img, e)] for e, (b, _) in L.funcs.items()}, f)
if a.write:
def report(): # (reads the functions, writes none of the C)
coverage(L, img, img_dir)
jt = L.stats
print("jump tables %d (bounded %d, bounded by function %d, ADR table %d), BR without a table %d, PLT stubs %d" % (
len(L.jt), jt["jt_bounded"], jt["jt_unbounded"], jt["jt_adr_table"], len(L.jt_missing), len(L.plt)))
if jt["jt_table_reg_reused"]:
print("jump tables whose table register is reused before the br: %d" % jt["jt_table_reg_reused"])
for pc, reg in sorted(L.jt_missing.items()):
print(" BR without a table: %#x (x%d)" % (pc, reg))
with open(os.path.join(img_dir, "functions.json"), "w") as f:
json.dump({"%x" % e: [len(b), module_of(img, e)] for e, (b, _) in L.funcs.items()}, f)
print("coverage report (%.0fs)" % (time.time() - t0), flush=True)
if not a.write:
report()
else:
if not a.no_polls:
poll.install()
gen = os.path.join(out_dir, "gen")
# ((Triforce) setup: what the emit's spawned processes do to the lifter's class before they emit, as this one did above)
# ((Triforce) setup: what the emit's spawned processes do to the lifter's class before they emit, as this one did above.
# (11-24) beside: the report is made while those processes already emit, where there are any: nx2/chunks.py write)
files = chunks.write(L, gen, os.path.join(a.work, "image"), a.rechunk and not a.standalone,
counters=[] if a.no_polls else [poll.stats], setup=[] if a.no_polls else [poll.install])
counters=[] if a.no_polls else [poll.stats], setup=[] if a.no_polls else [poll.install],
beside=report)
import oot_patches
fastfp.guard_patches(oot_patches) # ((Triforce) a lift with regions: no patch may change a function that holds one)
main_build = next((m["build_id"] for m in meta["modules"] if m["name"] == "main"), "")
# ((Triforce) wait=False: where the emit's processes were spawned they share the page marks while the files below are
# written, which read none of the C; marks_done() waits for them before the report says their counts)
@@ -207,6 +225,8 @@ def main():
print("standalone: nvn2_exports.c (%d sdk NVN functions routed to host/nvn2.c)" % len(nvn))
chunks.marks_done()
L.report()
if L.stats["entry_gotos"]: # (nx2/lift_fixes.py, 4)
print("functions with code below their entry, started at it by a goto: %d" % L.stats["entry_gotos"])
print("interrupt polls: %d loop headers in %d functions" % (poll.stats["polls"], poll.stats["functions"]))
print("wrote %d code files to %s (%.0fs)" % (len(files), gen, time.time() - t0))
print("done (%.0fs)" % (time.time() - t0))

View File

@@ -16,6 +16,15 @@
(RETAA/RETAB, BRAA/BRAB and their Z forms), so register values from the block before a `retab` leaked into
the dispatch block. zlib's inflate (main+0x1105e70) loses its table register x0 that way, to the
`mov w0, #-2` before the `retab` above the dispatch. The window now starts after the last such instruction.
4. A function with code below its entry. emit_function writes a function's instructions in address order, and the C
function starts at the first of them: at its entry only when the entry is its lowest address. A function is its
entry and everything reachable from it without crossing another entry, so that is not always so. Where a module
has no unwind entry per function (main's libcurl: one entry for 238 KB at main+0x24a21e0), a function that
branches to code at a lower address which is no entry of its own has that code below its entry. So has the
return address of a setjmp call, an entry since find_setjmp_owners, when the code after the call loops back
(main+0x165ab04). Each such function began at an instruction that was not its first. It now starts with
`goto L_<entry>;` (stats: entry_gotos), written after the function's local declarations (A64_LOCAL_REGS,
A64_LOCAL_FLAGS: a goto before them would skip their first values).
"""
import a64_lift
@@ -112,3 +121,20 @@ def install():
return out
a64_lift.Lifter.jump_table = jump_table
base_emit_function = a64_lift.Lifter.emit_function
def emit_function(self, e, texts):
body, labels = self.funcs[e]
if e in self.plt or min(body) == e: # (a PLT stub is written without its body)
return base_emit_function(self, e, texts)
labels.add(e) # (the base writes "L_<entry>:;" at an entry that is a label)
text, refs = base_emit_function(self, e, texts)
head = "void f_%08x(Ctx *__restrict A64_NOESC c) {\n" % e
at = text.index(head) + len(head)
while text.startswith((" uint64_t x", " uint8_t fn_"), at): # (localize_regs' declarations stay first)
at = text.index("\n", at) + 1
self.stats["entry_gotos"] += 1
return text[:at] + "goto L_%08x;\n" % e + text[at:], refs
a64_lift.Lifter.emit_function = emit_function

203
nx2/lift_store.py Normal file
View File

@@ -0,0 +1,203 @@
"""(Triforce) Translations kept for every work folder on this PC (HOOKSHOT_LIFT_STORE=<folder>; off when unset, empty or 0).
The lift (nx2/lift.py and split_hot.py, make_game.py translate) writes the same C for the same game, translator, hot list,
chunk boundaries, settings and Python, whatever the work folder: make_game.py lift_key covers all of that and, since LIFT-27
and the hot list hashed by its contents (11-24), no folder's path (lift_share_key: the key a snapshot is kept under). After a
lift, its output is saved here under the key taken as the lift started (save): the lifted C and the image (<work>/sa/gen,
<work>/sa/image) and the two files the lift writes for the next one (image/chunks.txt, image/hot_pieces.txt), so a folder that
takes it (restore) has the boundaries that folder had after its lift, as if it had lifted the game itself. A work folder whose
key finds a snapshot takes it instead of lifting: a second work folder (a second checkout, a test install), or a game folder
built again after another version was built in the same work folder.
Every file is copied, never hard-linked: the later steps write in the lifted C's folder. On a file system with copy-on-write
(btrfs, XFS: Linux's FICLONE) the copy is a clone and shares the blocks. A snapshot is complete or absent: it is written under
a temporary name with its list of files and sizes last, then renamed in, and a restore checks every file against that list
first. The newest HOOKSHOT_LIFT_STORE_KEEP (3) are kept, by last use; one used in the last hour is never taken. A snapshot is
about 1.6 GB (a plain copy on Windows and on file systems without clones).
"""
import os
import shutil
import time
STORE_ENV = "HOOKSHOT_LIFT_STORE"
DIRS = (("sa", "gen"), ("sa", "image"))
FILES = (("image", "chunks.txt"), ("image", "hot_pieces.txt"))
SKIP = (".lift_key",) # (make_game.py LIFT_KEY: not the lift's; the snapshot is taken right after the lift, before the compile)
MANIFEST = "snapshot.txt"
KEEP = 3
RECENT_S = 3600
def root():
r = os.environ.get(STORE_ENV, "").strip()
return None if r in ("", "0") else os.path.abspath(os.path.expanduser(r))
def _clone(src, dst):
"""A copy of src at dst, a copy-on-write clone where the file system has them"""
if hasattr(os, "O_BINARY") or not hasattr(os, "fork"): # (Windows: a plain copy)
shutil.copyfile(src, dst)
return
import fcntl
with open(src, "rb") as s, open(dst, "wb") as d:
try:
fcntl.ioctl(d.fileno(), 0x40049409, s.fileno()) # (FICLONE)
return
except OSError:
pass
shutil.copyfileobj(s, d, 1 << 20)
def _entries(base):
"""(relative path, absolute path) of every file a snapshot holds, read from base (a work folder or a snapshot)"""
out = []
for parts in DIRS:
top = os.path.join(base, *parts)
for d, dirs, fs in os.walk(top):
dirs.sort()
for f in sorted(fs):
if d == top and f in SKIP:
continue
p = os.path.join(d, f)
out.append((os.path.relpath(p, base).replace(os.sep, "/"), p))
for parts in FILES:
p = os.path.join(base, *parts)
if os.path.isfile(p):
out.append(("/".join(parts), p))
return out
def save(store, name, work, keep=None):
"""work's lift as the snapshot name. False when there was one already or it could not be written"""
snap = os.path.join(store, name)
if os.path.isdir(snap):
return False
tmp = os.path.join(store, ".%s.%d.tmp" % (name, os.getpid()))
try:
os.makedirs(store, exist_ok=True)
shutil.rmtree(tmp, ignore_errors=True)
listed = []
for rel, src in _entries(work):
dst = os.path.join(tmp, *rel.split("/"))
os.makedirs(os.path.dirname(dst), exist_ok=True)
_clone(src, dst)
listed.append("%d %s" % (os.path.getsize(dst), rel))
with open(os.path.join(tmp, MANIFEST), "w", encoding="utf-8", newline="\n") as f:
f.write("\n".join(listed) + "\n")
os.rename(tmp, snap)
except OSError as e:
shutil.rmtree(tmp, ignore_errors=True)
if not os.path.isdir(snap):
print("the translation was not kept for other work folders (%s)" % e, flush=True)
return False
prune(store, keep)
return True
def _listed(snap):
"""The snapshot's files and sizes, or None when it is not complete"""
try:
with open(os.path.join(snap, MANIFEST), encoding="utf-8") as f:
rows = [line.rstrip("\n").split(" ", 1) for line in f if line.strip()]
listed = {rel: int(size) for size, rel in rows}
except (OSError, ValueError, UnicodeDecodeError):
return None
if not any(rel.startswith("sa/gen/") for rel in listed) or not any(rel.startswith("sa/image/") for rel in listed):
return None
for rel, size in listed.items():
try:
if os.path.getsize(os.path.join(snap, *rel.split("/"))) != size:
return None
except OSError:
return None
return listed
def forget(store, name):
"""A snapshot that turned out bad, gone: the next folder lifts the game itself"""
shutil.rmtree(os.path.join(store, name), ignore_errors=True)
def restore(store, name, work, bad=None):
"""The snapshot name into work, in place of its lifted C, image and the lift's two files. False (and work's lifted C and image
gone, the two files as they were) when there is none or it could not be copied. bad(): a check of the copied C (make_game.py
lifted_cut_short); one that finds anything forgets the snapshot"""
snap = os.path.join(store, name)
listed = _listed(snap) if os.path.isdir(snap) else None
if listed is None:
return False
try:
os.utime(snap)
except OSError:
pass
try:
for parts in DIRS:
shutil.rmtree(os.path.join(work, *parts), ignore_errors=True)
if os.path.exists(os.path.join(work, *parts)):
raise OSError("could not clear %s" % os.path.join(work, *parts))
later = []
for rel in sorted(listed):
src, dst = os.path.join(snap, *rel.split("/")), os.path.join(work, *rel.split("/"))
if tuple(rel.split("/")) in FILES:
later.append((src, dst))
continue
os.makedirs(os.path.dirname(dst), exist_ok=True)
_clone(src, dst)
if any(os.path.getsize(os.path.join(work, *rel.split("/"))) != size for rel, size in listed.items()
if tuple(rel.split("/")) not in FILES):
raise OSError("a file came out another size")
found = bad() if bad else None
if found:
forget(store, name)
raise OSError("its lifted C is cut short (%s), so it is let go" % ", ".join(found[:6]))
for parts in FILES: # (last: until here the folder keeps its own, and lifts from them if this fails)
dst = os.path.join(work, *parts)
src = next((s for s, d in later if d == dst), None)
if src is None:
if os.path.exists(dst):
os.remove(dst)
continue
os.makedirs(os.path.dirname(dst), exist_ok=True)
tmp = dst + ".%d.tmp" % os.getpid()
_clone(src, tmp)
os.replace(tmp, dst)
except OSError as e:
for parts in DIRS:
shutil.rmtree(os.path.join(work, *parts), ignore_errors=True)
print("the translation of another work folder could not be copied (%s): the game is translated here" % e, flush=True)
return False
return True
def prune(store, keep=None, now=None):
"""The newest snapshots kept (by last use), the rest gone; a snapshot used in the last hour stays, and a temporary folder a
stopped save left goes after a day. Returns how many went"""
if not store or not os.path.isdir(store):
return 0
if keep is None:
try:
keep = max(1, int(os.environ.get("HOOKSHOT_LIFT_STORE_KEEP", "") or KEEP))
except ValueError:
keep = KEEP
now = time.time() if now is None else now
snaps, gone = [], 0
for f in os.listdir(store):
p = os.path.join(store, f)
try:
used = os.stat(p).st_mtime
except OSError:
continue
if not os.path.isdir(p):
continue
if f.startswith("."):
if now - used > 86400:
shutil.rmtree(p, ignore_errors=True)
gone += 1
continue
snaps.append((used, p))
snaps.sort(reverse=True)
for used, p in snaps[keep:]:
if now - used >= RECENT_S:
shutil.rmtree(p, ignore_errors=True)
gone += 1
return gone

File diff suppressed because it is too large Load Diff

View File

@@ -35,6 +35,55 @@ ZSTD = b"\x28\xb5\x2f\xfd"
WINDOWS_DEVICES = {"CON", "CONIN$", "CONOUT$", "PRN", "AUX", "NUL"} | {p + n for p in ("COM", "LPT") for n in "123456789¹²³"}
# ((Triforce, 11-24, after Source A's) (Windows) a read refused because another program holds part of the file:
# ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION
LOCKED = {32, 33}
# (Windows) a drive that cannot give back what it holds
DRIVE_ERRORS = {21: "the drive is not ready (unplugged, or asleep)", 23: "a read failed its data check",
27: "the drive could not find a sector", 30: "the drive could not read", 31: "the drive stopped responding",
1117: "the drive reported an I/O error", 1392: "the file is corrupted and unreadable"}
# (Windows) the C runtime's _get_doserrno, found now: importing ctypes after a failed read runs file calls of its own, which
# replace the error it holds
_get_doserrno = None
if os.name == "nt":
try:
import ctypes
_get_doserrno = ctypes.CDLL("ucrtbase")._get_doserrno
except (ImportError, OSError, AttributeError):
pass
def windows_error(error):
"""The Windows error behind an OSError, or None. A file object's read goes through the C runtime, which turns every
Windows error from 19 to 36 (a lock, a sharing violation, a bad sector, a drive gone) into errno 13 and keeps the error
itself apart (its _doserrno): read straight after the failure, before anything else can fail and replace it"""
code = getattr(error, "winerror", None)
if code is None and _get_doserrno is not None and error.errno == errno.EACCES:
value = ctypes.c_ulong()
if _get_doserrno(ctypes.byref(value)) == 0 and value.value:
code = value.value
return code
def unreadable(path, at, size, error, code=None):
"""What to say when the .nup could not be read at byte at, in plain words with what to do. code: the Windows error
(windows_error), else read from error"""
code = code if code is not None else windows_error(error)
name = os.path.basename(path)
where = "%s at %d of %d MB" % (name, at >> 20, size >> 20) if size else "%s at %d MB" % (name, at >> 20)
said = " (Windows error %d)" % code if code is not None else " (%s)" % (error.strerror or error)
if code in LOCKED:
return ("Windows would not let the build read %s: another program has that part of the file locked%s. A backup "
"or sync program, or a virus scan, can do this. Close it and build again, or copy the .nup to another "
"folder and build from the copy." % (where, said))
if code in DRIVE_ERRORS or code is None and error.errno == errno.EIO:
return ("Your drive could not read %s: %s%s. Copy the .nup to another drive and build from the copy. If Windows "
"cannot copy it either, that part of the drive is damaged: check the drive for errors, or dump the game "
"again onto another drive." % (where, DRIVE_ERRORS.get(code, "the drive reported an I/O error"), said))
return ("The build could not read %s%s. Close any program that may be using the file and build again, or copy the "
".nup to another drive and build from the copy." % (where, said))
def frame_content_size(head):
"""The content size a zstd frame header states, None when it states none"""
if head[:4] != ZSTD or len(head) < 18:
@@ -209,12 +258,27 @@ class Nup:
r = self.files[k - self.nd]
yield prefix + self.name(r[0], r[1]), r
def _data(self, n):
"""((Triforce, 11-24, after Source A's) Up to n bytes of the package from where it stands. A read the system refuses
partway through the file (another program's lock on that part of it, a drive that cannot read it back) stops with what
that means and what to do, not as a bare "PermissionError: [Errno 13] Permission denied"."""
at = self.f.tell()
try:
return self.f.read(n)
except OSError as error:
code = windows_error(error) # (first: a later call that fails would replace the error it reads)
try:
size = os.fstat(self.f.fileno()).st_size
except OSError:
size = None
raise SystemExit(unreadable(self.path, at, size, error, code)) from error
def inner_is_zstd(self, r):
"""Whether what this frame holds is itself a zstd frame"""
import zstandard
self.f.seek(r[3])
try:
return zstandard.ZstdDecompressor().decompressobj().decompress(self.f.read(min(r[2], 1 << 20)))[:4] == ZSTD
return zstandard.ZstdDecompressor().decompressobj().decompress(self._data(min(r[2], 1 << 20)))[:4] == ZSTD
except zstandard.ZstdError: # (made with one of the game's dictionaries: the game's own file)
return False
@@ -227,7 +291,7 @@ class Nup:
if not name:
name = self.name(r[0], r[1])
self.f.seek(r[3])
head = self.f.read(18)
head = self._data(18)
if head[:4] != ZSTD:
return False
size = frame_content_size(head)
@@ -242,7 +306,7 @@ class Nup:
left = r[2]
try:
while left and got <= r[2] and not d.eof:
b = self.f.read(min(left, 1 << 20))
b = self._data(min(left, 1 << 20))
if not b:
break
left -= len(b)
@@ -264,7 +328,7 @@ class Nup:
d = zstandard.ZstdDecompressor().decompressobj()
got = 0
while left and not getattr(d, "eof", False):
b = self.f.read(min(left, 8 << 20))
b = self._data(min(left, 8 << 20))
if not b:
break
left -= len(b)
@@ -284,7 +348,7 @@ class Nup:
raise SystemExit("a compressed file came out as %d bytes, %d expected" % (got, r[2]))
return
while left:
b = self.f.read(min(left, 8 << 20))
b = self._data(min(left, 8 << 20))
if not b:
raise SystemExit("the .nup file ends early (short read at %d of %d MB): it is incomplete. Download or copy it again"
% (self.f.tell() >> 20, os.fstat(self.f.fileno()).st_size >> 20))
@@ -692,6 +756,21 @@ def zstd_start(head):
return head == ZSTD or (len(head) == 4 and head[1:] == b"\x2a\x4d\x18" and head[0] & 0xf0 == 0x50)
def still_in_nup_frame(f, head):
"""((Triforce, 11-24, after Source A's) Whether a .zs file that starts as zstd (head: its first 18 bytes) is the .nup's own
frame round a damaged file, as older builders wrote them: a frame whose content is as large as the file, and that starts
with zeros or does not decompress. Only those are decompressed, and only their start: a game .zs file's content is larger
than the file, and most of them need the game's dictionary to decompress at all"""
if frame_content_size(head) != os.fstat(f.fileno()).st_size:
return False
import zstandard
f.seek(0)
try:
return not any(zstandard.ZstdDecompressor().stream_reader(f, read_size=1 << 14).read(16))
except zstandard.ZstdError:
return True
def damaged_game_files(romfs, progress=None):
"""The romfs .zs files that do not start as zstd: in the 23.3 GB dumps three of them begin with zeros (the complete
dump is about 23.8 GB), and the game then leaves out every model that uses one: the Water Temple's walls and floors,
@@ -707,48 +786,70 @@ def damaged_game_files(romfs, progress=None):
found = []
for i, (path, given) in enumerate(paths):
with open(path, "rb") as f:
if not zstd_start(f.read(4)):
head = f.read(18)
if not zstd_start(head[:4]) or still_in_nup_frame(f, head): # ((Triforce, 11-24) or still in the .nup's frame
found.append(given)
if progress:
progress(i + 1, len(paths))
return found
def stand_in_for(path, damaged=()):
def folder_listing(folder):
"""(name, size) of each file in folder, in the listing's order: one listing, whose entries carry the sizes on Windows"""
with os.scandir(long_path(folder)) as entries:
return [(entry.name, entry.stat().st_size) for entry in entries if entry.is_file()]
def stand_in_for(path, damaged=(), listings=None):
"""A whole file of the same kind beside a damaged one, to load in its place: the same last part of the name
(_Nrm.bntx.zs: a normal map for a normal map), the longest common start of the name, then the nearest size. Never
one of the damaged files, even one already given a stand-in"""
one of the damaged files, even one already given a stand-in. ((Triforce, 11-24, after Source A's) The files of its kind
are ranked by name and size first, then opened in that order until a whole one: one or two opens, not one for each file
of its kind (PreComputedCulling/RuntimeId holds about 35,000 .bcul.zs, each opened for each damaged file). listings:
folder -> folder_listing, kept across one pass's calls so that a folder is listed once)"""
folder, name = os.path.split(path)
suffix = re.search(r"(_[A-Za-z]+\d*)?(\.[^_]*)$", name).group(0)
size = os.path.getsize(long_path(path))
best = None
for other in os.listdir(long_path(folder)):
if other == name or not other.endswith(suffix):
continue
listing = None if listings is None else listings.get(folder)
if listing is None:
listing = folder_listing(folder)
if listings is not None:
listings[folder] = listing
# (ties go to the first in the listing, as when each was opened in turn)
ranked = sorted((-len(os.path.commonprefix((name, other))), abs(other_size - size), i, other)
for i, (other, other_size) in enumerate(listing)
if other != name and other.endswith(suffix) and os.path.join(folder, other) not in damaged)
for *_, other in ranked:
candidate = os.path.join(folder, other)
if candidate in damaged:
continue
with open(long_path(candidate), "rb") as f:
if not zstd_start(f.read(4)):
continue
score = (len(os.path.commonprefix((name, other))), -abs(os.path.getsize(long_path(candidate)) - size))
if best is None or score > best[0]:
best = (score, candidate)
return best and best[1]
if zstd_start(f.read(4)):
return candidate
return None
# ((Triforce, 11-24, after Source A's) An incomplete dump has a few damaged files (three textures in the 23.3 GB dumps). Past
# this many the dump is damaged throughout: no stand-in is looked for, and the build stops at once (one with 1,896 sat
# overnight looking first)
MOST_STAND_INS = 100
def stand_in_damaged(romfs, progress=None, known=None):
"""Each damaged .zs file in an unpacked romfs replaced by a copy of its stand-in: (damaged, stand-in or None) each.
Only for a romfs this tool unpacked: the player's own folder is never written to. progress: damaged_game_files'.
known: the damaged files as the unpack itself found them (extract's zs, paths under romfs with "/"): they are taken
as they are and no file is opened to look for them"""
as they are and no file is opened to look for them. More than MOST_STAND_INS damaged: none is given a stand-in (each is
None) and nothing is written"""
done = []
if known is None:
damaged = damaged_game_files(romfs, progress)
else:
damaged = [os.path.normpath(os.path.join(romfs, *rel.split("/"))) for rel in known]
if len(damaged) > MOST_STAND_INS:
return [(path, None) for path in damaged]
excluded = set(damaged)
listings = {}
for path in damaged:
other = stand_in_for(path, set(damaged))
other = stand_in_for(path, excluded, listings)
if other:
shutil.copyfile(long_path(other), long_path(path + ".part"))
os.replace(long_path(path + ".part"), long_path(path))

181
nx2/object_store.py Normal file
View File

@@ -0,0 +1,181 @@
"""One store of compiled objects for every work folder on this PC (HOOKSHOT_OBJ_STORE=<folder>; off when unset, empty or 0).
A work folder keeps its own object cache (<work>/objcache: nx2/build.py's cache_put and compile_one, make_game.py's
prune_object_cache) as before. With a store, build.py takes the objects this build needs and the folder lacks from the store
(fetch), and gives the store the folder's objects it lacks (share). Both are hard links, so an object is on the disk once
whatever number of folders use it; a copy where the store and the work folder are on two volumes (or a file system without
hard links), made under a temporary name and renamed in. The object keys hold no folder path (build.py flag_text, object_key),
so another work folder's object of the same key is the one this build would compile.
The keys do not name the compiler and the system headers: a work folder notes them in system_headers.txt (make_game.py
drop_stale_objects) and lets its objects go when they change. The store keeps a folder of its own per note (its first 16
characters), and a work folder without the note uses no store.
Nothing writes an object in place: the compiler writes a new file and renames it over the old one, and the folder's clean-up
only removes its own links, so a store object stays whole while any folder uses it. The store's own clean-up (prune, after each
make_game.py build): an object only the store holds (one link, or every object where there are none) goes once it has not been
used for HOOKSHOT_OBJ_STORE_DAYS (14), and the oldest go first while those come to more than HOOKSHOT_OBJ_STORE_GB (8). An
object used in the last hour is never taken, so a build that is fetching it keeps it.
"""
import os
import shutil
import time
STORE_ENV = "HOOKSHOT_OBJ_STORE"
NOTE = "system_headers.txt"
KEEP_DAYS, KEEP_GB = 14.0, 8.0
RECENT_S = 3600
def root():
"""The store's folder, or None when there is none"""
r = os.environ.get(STORE_ENV, "").strip()
return None if r in ("", "0") else os.path.abspath(os.path.expanduser(r))
def folder(work, store_root=None):
"""The store's folder for the compiler and headers work was last built with, or None (no store, no note)"""
r = store_root or root()
if not r:
return None
try:
with open(os.path.join(work, NOTE), encoding="utf-8") as f:
stamp = f.read().strip()
except (OSError, UnicodeDecodeError):
return None
if len(stamp) < 16 or any(c not in "0123456789abcdef" for c in stamp[:16]):
return None
return os.path.join(r, stamp[:16])
def _place(src, dst):
"""src at dst: a hard link, else a copy renamed in. False when dst is there already or src is not"""
if os.path.exists(dst):
return False
try:
os.link(src, dst)
return True
except FileExistsError:
return False
except FileNotFoundError:
return False
except OSError:
pass
tmp = "%s.%d.tmp" % (dst, os.getpid())
try:
shutil.copyfile(src, tmp)
os.rename(tmp, dst) # (POSIX: over one that came in meanwhile, the same object; Windows: FileExistsError)
return True
except OSError:
try:
os.remove(tmp)
except OSError:
pass
return False
def _touch(path):
try:
os.utime(path)
except OSError:
pass
def fetch(store, cache, keys):
"""The objects named by keys that cache lacks and store has, into cache. Returns how many"""
if not store or not os.path.isdir(store):
return 0
os.makedirs(cache, exist_ok=True)
n = 0
for key in sorted(set(keys)):
dst = os.path.join(cache, key + ".o")
if os.path.exists(dst):
continue
src = os.path.join(store, key + ".o")
if _place(src, dst):
_touch(src)
n += 1
return n
def share(cache, store):
"""The objects of cache that store lacks, into store. Returns how many"""
if not store or not os.path.isdir(cache):
return 0
try:
os.makedirs(store, exist_ok=True)
have = set(os.listdir(store))
except OSError:
return 0
n = 0
for f in os.listdir(cache):
if f.endswith(".o") and f not in have and _place(os.path.join(cache, f), os.path.join(store, f)):
_touch(os.path.join(store, f))
n += 1
return n
def forget(store, keys):
"""Those objects out of the store (a link that failed with them): the next build compiles them again. A work folder's own
links stay as they are"""
if not store:
return
for key in keys:
try:
os.remove(os.path.join(store, key + ".o"))
except OSError:
pass
def _number(name, default):
try:
return max(0.0, float(os.environ.get(name, "") or default))
except ValueError:
return default
def prune(store_root=None, now=None):
"""The store's own clean-up (the module's notes). Returns (objects removed, bytes freed)"""
r = store_root or root()
if not r or not os.path.isdir(r):
return 0, 0
now = time.time() if now is None else now
days, limit = _number("HOOKSHOT_OBJ_STORE_DAYS", KEEP_DAYS), _number("HOOKSHOT_OBJ_STORE_GB", KEEP_GB) * (1 << 30)
alone = [] # (last used, size, path) of the objects only the store holds
try:
subs = os.listdir(r)
except OSError: # (a store that cannot be read: nothing to clean, the build stands)
return 0, 0
for sub in subs:
d = os.path.join(r, sub)
if not os.path.isdir(d):
continue
try:
names = os.listdir(d)
except OSError: # (a namespace that cannot be listed, or removed meanwhile: skipped)
continue
for f in names:
p = os.path.join(d, f)
try:
st = os.stat(p)
except OSError:
continue
if f.endswith(".tmp") and now - st.st_mtime > RECENT_S: # (a copy a stopped build left)
alone.append((0.0, st.st_size, p))
elif f.endswith(".o") and st.st_nlink <= 1:
alone.append((st.st_mtime, st.st_size, p))
alone.sort()
total = sum(size for _, size, _ in alone)
removed = freed = 0
for used, size, p in alone:
age = now - used
if age < RECENT_S or (age < days * 86400 and total <= limit):
continue
try:
os.remove(p)
except OSError:
continue
total -= size
removed += 1
freed += size
return removed, freed

File diff suppressed because it is too large Load Diff

View File

@@ -3,8 +3,8 @@
The game draws a 2560x1440 picture whatever the screen and renders its scene at 1920x1080; its cameras use a 16:9 ratio.
With these patches the picture takes the window's shape (the height stays the game's, the width grows on an ultrawide
screen and shrinks on a 16:10 or 4:3 one), the 16:9 cameras take the picture's ratio, the HUD and menus keep their 16:9
shape in the middle of a wider picture (a narrower one: its whole width), story movies play in that middle 16:9,
title movies fill the picture up to 12:5,
shape in the middle of a wider picture (a narrower one: its whole width), story movies keep their 16:9 shape (in that
middle 16:9, or across a narrower picture with bars above and below), title movies fill the picture up to 12:5,
and the picture a save keeps shows that middle 16:9 (a narrower picture: its middle band, at the texture's shape). Every patch reads host globals
(host/hos_wide.c) that stay 0 for a 16:9 window, so the game runs as shipped then.
@@ -25,6 +25,10 @@ UI_M00, UI_M11 = "(2.0f / 3840.0f)", "(2.0f / 2160.0f)" # (the UI's full-scree
# it all: bit 0 cleared, that capture went into the middle at twice its width, and a fade in the middle alone left the
# picture showing at its sides while a place loaded)
KEEP_VTABLES = (MAIN + 0x4bed098, MAIN + 0x4be4fb0, MAIN + 0x4be61c8, MAIN + 0x4be7b30)
# ((Triforce) and bit 4, UISystemOverlayScreen (MAIN + 0x4bef4a0): the system menus' header and button guides, and from the
# item wheel's first opening on its background too. host/oot_wide_hud.h keeps it whole only while the wheel's background is
# drawn (vk_framegen.cpp wide_sides): kept whole always, the header and guides that this game's options line up with
# (gpu/vk/game_grid.h) would be stretched over the whole picture)
def _ratio(vreg, base=None):
@@ -37,6 +41,20 @@ def _ratio(vreg, base=None):
% (vreg, vreg, store))
def _clearance(vreg):
"""The camera's near-plane clearance sphere keeps the game's ratio, not the picture's: a ratio just loaded into s<vreg>
that is exactly the picture's becomes 16:9 for that calculation alone. The camera sizes the sphere it keeps clear of walls
from h = tan(fov / 2) * near, w = h * ratio and sqrt(w * w + h * h); fed a 32:9 picture's ratio (which the camera
carries since _ratio gave it the picture's) the sphere was 1.8 times its 16:9 size, too big for a crawl passage, and the
camera stayed at the entrance while Link crawled away. The stored ratio, its other readers, the drawing matrices and
culling stay the picture's."""
return ("{ extern volatile float hos_wide_ratio; const float _w = hos_wide_ratio; "
"if (_w > 0.0f && _w != (16.0f / 9.0f)) { float _r; memcpy(&_r, c->vreg[%d], 4); "
"if (_r == _w) { "
"const float _normal = 16.0f / 9.0f; uint32_t _u; memcpy(&_u, &_normal, 4); "
"a64_vset64(c->vreg[%d], _u); } } } /* (nx2/oot_wide.py: camera clearance) */" % (vreg, vreg))
def _size(name):
return ("{ extern volatile uint64_t %s; const uint64_t _s = %s; if (_s) c->x[8] = _s; } /* (nx2/oot_wide.py: %s) */"
% (name, name, name))
@@ -52,15 +70,35 @@ HUD = ("{ extern volatile float hos_wide_squeeze; if (hos_wide_squeeze > 0.0f) {
" /* (nx2/oot_wide.py: HUD in the middle 16:9, or at the screen's edges) */"
% (UI_M00, UI_M11))
# The speech bubble over a talking NPC (BalloonMessage_00): the game anchors it at the speaker's place on the screen times the
# canvas's half size (x * 1920 in s0, y * 1080 in s1, then stp s0, s1 to the bubble), but its screen draws through the HUD's
# projection, which on a picture wider than 16:9 is squeezed across into the middle (HUD, above: times hos_wide_squeeze), so
# the bubble was pulled toward the middle of the screen, away from its speaker. The anchor's x is divided by the squeeze, and
# the bubble lands over its speaker. (The site is the ultrawide IPS mod's, there 1920 / squeeze in place of 1920. A picture
# narrower than 16:9 has a squeeze of 1: nothing changes there, nor at 16:9, where it is 0)
BUBBLE = ("{ extern volatile float hos_wide_squeeze; const float _q = hos_wide_squeeze; "
"if (_q > 0.0f && _q < 1.0f) { float _x; memcpy(&_x, c->vreg[0], 4); _x /= _q; memcpy(c->vreg[0], &_x, 4); } }"
" /* (nx2/oot_wide.py: the speech bubble over its speaker) */")
# Within f_83b7c710 the movie site (main+0x3b5c758) and its SetViewport (main+0x284824) run
# on the same thread. Between 0x83b7c758 and the unconditional call at 0x83b7c78c, only f_809ebaf0 runs; it calls no viewport helper.
# Leave the scissor full width and consume the mark only at SetViewport.
# Keep the movie at 16:9. Inset its left and right bounds on wider pictures, or its top and bottom bounds on
# narrower pictures (16:10, 4:3: the movie filled the whole picture there, squeezed across). The viewport is at
# x29 - 40, with float bounds in left, top, right, bottom order from +8.
MOVIE = ("{ extern int hos_movie_cover_begin(float); extern volatile float hos_wide_ratio; "
"extern volatile float hos_wide_margin; const float _m = hos_wide_margin; if (!hos_movie_cover_begin(hos_wide_ratio) && _m > 0.0f) { "
"extern volatile float hos_wide_margin; const float _m = hos_wide_margin; const int _cover = hos_movie_cover_begin(hos_wide_ratio); "
"if (!_cover && _m > 0.0f) { "
"const uint64_t _vp = c->x[29] - 40; uint32_t _ua = (uint32_t)recomp_load32(c, _vp + 8), _ub = (uint32_t)recomp_load32(c, _vp + 16); "
"float _a, _b; memcpy(&_a, &_ua, 4); memcpy(&_b, &_ub, 4); const float _in = (_b - _a) * _m; _a += _in; _b -= _in; "
"memcpy(&_ua, &_a, 4); memcpy(&_ub, &_b, 4); recomp_store32(c, _vp + 8, _ua); recomp_store32(c, _vp + 16, _ub); } }"
" /* (nx2/oot_wide.py: movies in the middle 16:9) */")
"memcpy(&_ua, &_a, 4); memcpy(&_ub, &_b, 4); recomp_store32(c, _vp + 8, _ua); recomp_store32(c, _vp + 16, _ub); } "
"else if (!_cover) { const float _r = hos_wide_ratio; const float _game = 16.0f / 9.0f; "
"if (_r > 0.0f && _r < _game * 0.99f) { const uint64_t _vp = c->x[29] - 40; "
"uint32_t _ua = (uint32_t)recomp_load32(c, _vp + 12), _ub = (uint32_t)recomp_load32(c, _vp + 20); "
"float _a, _b; memcpy(&_a, &_ua, 4); memcpy(&_b, &_ub, 4); const float _in = (_b - _a) * (1.0f - _r / _game) / 2.0f; "
"_a += _in; _b -= _in; memcpy(&_ua, &_a, 4); memcpy(&_ub, &_b, 4); "
"recomp_store32(c, _vp + 12, _ua); recomp_store32(c, _vp + 20, _ub); } } }"
" /* (nx2/oot_wide.py: movies at 16:9, with side bars on wider pictures or top and bottom bars on narrower ones) */")
# The save's picture (issue 952): the pause menu draws the whole picture into a 543 x 306 texture, the save's JPEG, through the
# game's viewport-and-scissor helper (f_802a46e0: SetScissor, then SetViewport(x, y, w, h) in w1-w4 from [x8], called by blr x8).
@@ -77,6 +115,52 @@ THUMB = ("{ extern int hos_movie_cover_viewport(uint64_t *, uint64_t *); "
"c->x[2] = (uint32_t)((306 - _h) / 2); c->x[4] = (uint32_t)_h; } } }"
" /* (nx2/oot_wide.py: the save's picture, the middle 16:9) */")
# ((Triforce) The HUD's layout for a wider screen, and the menus' with Menu sides at Extended (host/hos_wide_ui.c; the sites are
# ozwaldorf's, NotRexed/Hookshot pull request 2843). A 2D layout pane's final transform is made by f_8154cab0 (main+0x152cab0) when
# its dirty bit 6 is set (f_8154caa0 checks it and falls into it); the pane is x0 there and x19 in it. The parent it multiplies
# by is x0 after main+0x152cdd4; main+0x152cd98 is where every path without one joins. The translation is stored at
# main+0x152ce64, before the stored transform is read back to tell whether the children need theirs remade. f_8154ac30 reads a
# pane's size as drawn (ldp s0, s1, [x0, #0x58]). f_8154a730, the calculate pass, skips a pane with no dirty bits at all.
# A picture's draw: f_815505b0 packs its record into the frame's constants (the call to f_8154f1c0 returns them at sp + 8,
# read into x8, x9 at main+0x15306f4), the drawer keeps them at +0x48; f_81550720 (main+0x1530720) draws with them. The pause
# menu's background is drawn in pieces there (Ultrawide menus: Extended). f_81545d60 builds a layout's panes (the layout x19
# after it, main+0x1525ca0).
UI_FORCE = ("{ extern volatile uint32_t hos_wide_ui_force; if (hos_wide_ui_force) c->x[8] |= 0x40; }"
" /* (nx2/oot_wide.py: every pane remakes its transform) */")
# (the calculate pass, f_8154a730, returns at once for a pane with no dirty bits: a pane that never changes would never remake
# its transform. While forced its bit 6 is set where the pass reads the bits, so it reaches f_8154caa0)
UI_FORCE_PASS = ("{ extern volatile uint32_t hos_wide_ui_force; if (hos_wide_ui_force) { c->x[8] |= 0x40; "
"recomp_store32(c, c->x[0], (uint32_t)c->x[8]); } } /* (nx2/oot_wide.py: every pane remakes its transform) */")
UI_PARENT = ("{ extern void hos_wide_ui_parent(uint64_t parent); hos_wide_ui_parent(%s); }"
" /* (nx2/oot_wide.py: the pane's parent) */")
UI_PLACED = ("{ extern void hos_wide_ui_placed(Ctx *c, uint64_t pane); hos_wide_ui_placed(c, c->x[19]); }"
" /* (nx2/oot_wide.py: the HUD's side panes at the screen's edges) */")
UI_SIZE = ("{ extern void hos_wide_ui_size(Ctx *c, uint64_t pane); hos_wide_ui_size(c, c->x[0]); }"
" /* (nx2/oot_wide.py: spanning panes the screen's width) */")
UI_BG = ("{ extern void hos_wide_ui_bg(Ctx *c); hos_wide_ui_bg(c); }"
" /* (nx2/oot_wide.py: the pause menu's background in pieces) */")
UI_BG_DRAW = ("{ extern void hos_wide_ui_bg_draw(Ctx *c); hos_wide_ui_bg_draw(c); }"
" /* (nx2/oot_wide.py: the pause menu's background in pieces) */")
UI_BUILT = ("{ extern void hos_wide_ui_built(Ctx *c, uint64_t layout); hos_wide_ui_built(c, c->x[19]); }"
" /* (nx2/oot_wide.py: a list widened as it is built) */")
UI_SITES = (
(0x152a730, 0xb9400008, UI_FORCE_PASS), # ldr w8, [x0]: the calculate pass's first look at the dirty bits
(0x152caa0, 0xb9400008, UI_FORCE), # ldr w8, [x0]: the pane's dirty bits
(0x152cd98, 0xad4207e0, UI_PARENT % "0"), # ldp q0, q1, [sp, #0x40]: no parent
(0x152cdd4, 0xb9403008, UI_PARENT % "c->x[0]"), # ldr w8, [x0, #0x30]: the parent's transform
(0x152ce64, 0xfc04c263, UI_PLACED), # stur d3, [x19, #0x4c]: the translation stored
(0x152ac40, 0x2d4b0400, UI_SIZE), # ldp s0, s1, [x0, #0x58]: the size as drawn
(0x15306f4, 0xa940a7e8, UI_BG), # ldp x8, x9, [sp, #8]: a picture's constants packed, before the drawer keeps them
(0x1530740, 0xaa0003f6, UI_BG_DRAW), # mov x22, x0: a picture drawn (the drawer x0, x1 what it draws with)
(0x1525ca0, 0x91004260, UI_BUILT), # add x0, x19, #0x10: a layout's panes built (f_81545d60 returned)
)
# AArch64 LDR (immediate, unsigned offset), 32-bit SIMD/FP: fixed fields and
# imm12 scaled by four, Rn and Rt, from the Arm Architecture Reference Manual.
def _ldr_s(rt, rn, offset):
return (0b1011110101 << 22) | ((offset // 4) << 10) | (rn << 5) | rt
# (main offset, the original instruction word there, the C after it)
SITES = (
# the picture: the graphics setup and the display settings object build {2560, 1440} in x8 (mov, then this movk)
@@ -91,13 +175,18 @@ SITES = (
(0x4f1e8, 0x2d558ea0, _ratio(3, 21)),
(0x23b9a8, 0x2d558c00, _ratio(3, 0)),
(0x33b82c, 0x2d558440, _ratio(1, 2)),
# the near-plane clearance sphere and its follow-up branch (f_8073a4a0): ldr s10/s14, [x19, #0x51c]
(0x71a844, _ldr_s(10, 19, 0x51c), _clearance(10)),
(0x71b624, _ldr_s(14, 19, 0x51c), _clearance(14)),
# the 2D canvas setup: the layout's projection rows (ldp q1, q4, [x2]); the canvas is x0, its screen 0x1b8 before it
(0x774368, 0xad401041, HUD),
# the speech bubble's anchor: after fmul s1, s2, s1 (y * 1080; x * 1920 already in s0)
(0x20c2c8, 0x1e210841, BUBBLE),
# the movie layer's draw: its viewport (min x at x29 - 32, max x at x29 - 24) after ldp x9, x8, [x19, #0x18]
(0x3b5c758, 0xa941a269, MOVIE),
# the viewport helper's SetViewport, after the call's address is loaded (ldr x8, [x8]), before blr x8
(0x284824, 0xf9400108, THUMB),
)
) + UI_SITES # ((Triforce) host/hos_wide_ui.c's: each returns at once while nothing is planned)
def install(lifter, img):

View File

@@ -4,6 +4,7 @@ triforce_pipeline_states_shipped.bin, whose pipelines the first start's shader p
python -I nx2/pipeline_states.py <list>... what they hold
python -I nx2/pipeline_states.py --out work/pipeline_states.bin <list>... merged, each pipeline once
python -I nx2/pipeline_states.py --v2 --out <file> <list>... the same, version 1 lists converted to version 2
python -I nx2/pipeline_states.py --check <list>... each list checked (exit 1 when one is not sound)
python -I nx2/pipeline_states.py --out work/pipeline_states.bin --contrib contrib <list>...
and the players' lists in contrib/ (*.bin.xz, a note each), checked one by one,
@@ -20,13 +21,39 @@ Point-list records are counted as suspect: --check refuses them and --contrib le
A list holds no game code: each record is a pipeline's stage code keys (hashes of the game's shaders, which the player's own
triforce_shaders.bin turns back into the shaders), the program variant's hash, and the formats and draw state baked into the pipeline.
Any list is read plain or xz-packed (told by its first bytes).
Version 2 (HKSTATE2, written by builds since it) holds what the game asked for, the same on every GPU and with any settings: the
targets' NVN formats, whether the draw was a mesh draw, the draw's own topology, and the program variant's texture answers with its
stages numbered without the mesh fallback's generated vertex stage. Each GPU's shader preparation maps them through the rules its
draws follow (the formats it makes of the NVN ones, its mesh shaders or the mesh fallback). Version 1 (HKSTATE1, older builds) held
the recording GPU's choices: the Vulkan formats it rendered in, and on a GPU with the mesh fallback the fallback's topology and
stage numbering; the game still reads it.
<list>: "HKSTATE2", u32 record size (552), then the records:
u64 code[4] (vertex or mesh, fragment, task, the header-only stage), u64 variant (of the answers below),
u32 mesh, topology (a mesh draw's: triangle list), targets, samples, has depth, depth NVN format,
u32 colour NVN texture formats[8] (0: none), u32 colour NVN view formats[8] (the format each is drawn in),
u64 blend[8], u32 vertex attributes[16], u32 attribute count, u32 strides[16], u32 divisors[16],
u32 blend enables, channel mask, polygon mode, depth clamp, alpha to coverage,
u32 answers, u32 questions, u32 answers[24] (stage, descriptor, image, type), u8 questions[32], u32 kind, u32 pad
(variant 0 with no answers and no questions: the variant nothing bound makes, each texture as its instruction
declares it; lists converted from records without texture answers hold those)
kind 0: a graphics or mesh pipeline, as above.
kind 1 (COMPUTE): a compute program, code[0] its compute stage's code key and every other field 0 (the game
writes one at a program's first dispatch; its pipelines' reader leaves them out, vk_draw.cpp state_list_computes
reads them)
<list>: "HKSTATE1", u32 record size (528), then the records:
u64 code[4] (vertex or mesh, fragment, task, the header-only stage), u64 variant,
u32 mesh, topology, targets, samples, depth format, has depth, u32 color formats[8], u8 color types[8],
u64 code[4], u64 variant,
u32 mesh, topology, targets, samples, depth format, has depth, u32 color formats[8] (Vulkan), u8 color types[8],
u64 blend[8], u32 vertex attributes[16], u32 attribute count, u32 strides[16], u32 divisors[16],
u32 blend enables, channel mask, polygon mode, depth clamp, alpha to coverage, pad,
u32 answers, u32 questions, u32 answers[24] (stage, descriptor, image, type), u8 questions[32] (each answer as asked)
Lists of both versions merge into version 2 (version 1 alone stays version 1; --v2 converts it too). A version 1 record is
converted: each Vulkan format back to an NVN format every GPU renders in it (V1_NVN: no format a GPU chooses itself), a mesh record
made with the mesh fallback numbered as the native one. A record that cannot be (a format the table lacks, a fallback record whose
answers were left out) is left out, and counted.
"""
import argparse
import collections
@@ -39,15 +66,147 @@ import zipfile
MAGIC = b"HKSTATE1"
SIZE = 528
MAGIC2 = b"HKSTATE2"
SIZE2 = 552
XZ_MAGIC = b"\xfd7zXZ\x00"
TRIANGLE_LIST = 3 # (VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: what a mesh draw is given, vk_draw.cpp kMeshDrawTopology)
# A version 1 record's Vulkan format -> an NVN format vk_format (gpu/vk/vk_formats.cpp) makes it on every GPU: the formats a
# target can be, ASTC and BC (no GPU renders into them) left out. tests/test_pipeline_states.py checks it against vk_formats.cpp,
# gpu/render/nvn_api.h and the Vulkan headers
V1_NVN = {
4: 0x95, 5: 0x3c, 7: 0x3a, 8: 0x3b, 9: 0x01, 10: 0x02, 13: 0x03, 14: 0x04, 16: 0x0d, 17: 0x0e, 20: 0x0f, 21: 0x10,
23: 0x19, 24: 0x1a, 27: 0x1b, 28: 0x1c, 37: 0x6d, 38: 0x6e, 41: 0x6f, 42: 0x70, 43: 0x37, 44: 0x99, 50: 0x9b,
64: 0x3d, 68: 0x3e, 70: 0x06, 71: 0x07, 74: 0x08, 75: 0x09, 76: 0x05, 77: 0x12, 78: 0x13, 81: 0x14, 82: 0x15,
83: 0x11, 91: 0x72, 92: 0x73, 95: 0x74, 96: 0x75, 97: 0x29, 98: 0x0b, 99: 0x0c, 100: 0x0a, 101: 0x17, 102: 0x18,
103: 0x16, 106: 0x22, 107: 0x77, 108: 0x78, 109: 0x76, 122: 0x3f, 123: 0x40, 124: 0x32, 125: 0x33, 126: 0x34,
127: 0x31, 129: 0x35, 130: 0x36, 1000340001: 0x39,
}
# the records as struct layouts (vk_draw.cpp StateRec, StateRec2)
_V1 = struct.Struct("<4QQ6I8I8s8Q16II16I16I6III24I32s4x")
_V2 = struct.Struct("<4QQ6I8I8I8Q16II16I16I5III24I32s2I")
assert _V1.size == SIZE and _V2.size == SIZE2
KIND_AT = SIZE2 - 8 # (a version 2 record's kind: vk_draw.cpp StateRec2::kind)
COMPUTE = 1 # (StateRec2::kCompute)
HEADS = {MAGIC: SIZE, MAGIC2: SIZE2}
def read_any(path):
"""A list's bytes, plain or xz-packed (told by its first bytes)"""
with open(path, "rb") as f:
data = f.read()
return lzma.decompress(data) if data[:6] == XZ_MAGIC else data
def head_size(data):
"""The record size a list's head names, None when its head is not one of a version this reads"""
if len(data) < 12 or HEADS.get(data[:8]) != struct.unpack_from("<I", data, 8)[0]:
return None
return HEADS[data[:8]]
def read(path):
with open(path, "rb") as f:
data = f.read()
if data[:8] != MAGIC or struct.unpack_from("<I", data, 8)[0] != SIZE:
raise SystemExit("%s: not a pipeline state list" % path)
data = read_any(path)
size = head_size(data)
if not size:
raise SystemExit("%s: not a pipeline state list (%s, %d-byte records, or %s, %d)" % (path, MAGIC2.decode(), SIZE2,
MAGIC.decode(), SIZE))
body = data[12:]
return [body[i:i + SIZE] for i in range(0, len(body) - SIZE + 1, SIZE)]
return [body[i:i + size] for i in range(0, len(body) - size + 1, size)]
def kind(r):
"""A record's kind: 0 a graphics or mesh pipeline (every version 1 record), COMPUTE a compute program"""
return struct.unpack_from("<I", r, KIND_AT)[0] if len(r) == SIZE2 else 0
def compute_record(key):
"""The record of a compute program: its compute stage's code key and nothing else"""
r = bytearray(SIZE2)
struct.pack_into("<Q", r, 0, key)
struct.pack_into("<I", r, KIND_AT, COMPUTE)
return bytes(r)
# ---- version 1 records as version 2
def answers_hash(answers):
"""Program::variant of packed answers (vk_shader.cpp answers_hash)"""
h = 0
for a in answers:
stage, desc, image, typ = a >> 28, a >> 12 & 0xFFFF, a >> 8 & 1, a & 0xFF
h = ((h ^ (stage << 32 | desc << 16 | typ << 1 | image)) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
return h
def v1_to_v2(r):
"""A version 1 record as version 2, or None when it cannot be (vk_draw.cpp state_v1_portable does the same in the game)"""
f = list(_V1.unpack(r))
code, variant = f[0:4], f[4]
mesh, topo, n, samples, depth_format, has_depth = f[5:11]
colors = f[11:19]
blend, vattr, nvattr = f[20:28], f[28:44], f[44]
stride, divisor = f[45:61], f[61:77]
blend_en, chmask, poly, clamp, a2c = f[77:82]
nanswers, nquestions = f[83], f[84]
answers, questions = list(f[85:109]), f[109]
if nanswers > 24 or nquestions > 32 or n > 8:
return None
if mesh: # (made with the mesh fallback: its generated vertex stage after (task,) mesh, and the fallback's topology)
g = 2 if code[2] else 1
fallback = topo != TRIANGLE_LIST or any(a >> 28 > g for a in answers[:nanswers])
if fallback:
if not nanswers:
return None
for i in range(nanswers):
if answers[i] >> 28 > g:
answers[i] = (answers[i] & 0x0FFFFFFF) | ((answers[i] >> 28) - 1) << 28
variant, topo = answers_hash(answers[:nanswers]), TRIANGLE_LIST
nvn = []
for k in range(8):
if k >= n or not colors[k]:
nvn.append(0)
elif colors[k] in V1_NVN:
nvn.append(V1_NVN[colors[k]])
else:
return None
depth_nvn = 0
if has_depth and depth_format:
if depth_format not in V1_NVN:
return None
depth_nvn = V1_NVN[depth_format]
return _V2.pack(*code, variant, mesh, topo, n, samples, has_depth, depth_nvn, *nvn, *nvn, *blend, *vattr, nvattr,
*stride, *divisor, blend_en, chmask, poly, clamp, a2c, nanswers, nquestions, *answers, questions, 0, 0)
def as_v2(lists, force=False):
"""Lists of records of one version: as they are when all are version 1 (and not force), else each version 1 record converted
(those that cannot be left out). (lists, how many were left out from each)"""
if not force and all(len(r) == SIZE for recs in lists for r in recs):
return lists, [0] * len(lists)
out, lost = [], []
for recs in lists:
conv, n = [], 0
for r in recs:
r = v1_to_v2(r) if len(r) == SIZE else r
if r is None:
n += 1
else:
conv.append(r)
out.append(conv)
lost.append(n)
return out, lost
def pack(recs):
"""A list's bytes, unpacked: what the game reads. Version 2 when any record is (the version 1 ones converted)"""
(recs,), lost = as_v2([recs])
if lost[0]:
print("%d version 1 pipelines could not be converted to version 2: left out" % lost[0], file=sys.stderr)
if recs and len(recs[0]) == SIZE2:
return MAGIC2 + struct.pack("<I", SIZE2) + b"".join(recs)
return MAGIC + struct.pack("<I", SIZE) + b"".join(recs)
# ---- (Triforce, 11-22, PIPE-11) checking a list
@@ -57,12 +216,23 @@ POINT_LIST = 0 # (VK_PRIMITIVE_TOPOLOGY_POINT_LIST)
def record_faults(r):
"""What is wrong with one record, as words (none: sound). Its counts within their arrays, a first stage, flags 0 or 1"""
"""What is wrong with one record of either version, as words (none: sound). Its counts within their arrays, a first stage,
flags 0 or 1; a version 2 record of a kind this knows (a compute program's: its key and nothing else)"""
faults = []
code0 = struct.unpack_from("<Q", r, 0)[0]
mesh, topo, n, samples, _depth, has_depth = struct.unpack_from("<6I", r, 40)
nvattr = struct.unpack_from("<I", r, 232)[0]
nanswers, nquestions = struct.unpack_from("<2I", r, 388)
if len(r) == SIZE2:
k = kind(r)
if k == COMPUTE:
return [] if code0 and r == compute_record(code0) else ["a compute program's record holding more than its key, or none"]
if k:
return ["kind %d" % k]
mesh, topo, n, samples, has_depth = struct.unpack_from("<5I", r, 40)
nvattr = struct.unpack_from("<I", r, 256)[0]
nanswers, nquestions = struct.unpack_from("<2I", r, 408)
else:
mesh, topo, n, samples, _depth, has_depth = struct.unpack_from("<6I", r, 40)
nvattr = struct.unpack_from("<I", r, 232)[0]
nanswers, nquestions = struct.unpack_from("<2I", r, 388)
if not code0:
faults.append("no vertex or mesh stage")
if mesh > 1 or has_depth > 1:
@@ -81,21 +251,24 @@ def record_faults(r):
def is_point(r):
return struct.unpack_from("<I", r, 44)[0] == POINT_LIST
"""A pipeline drawing point lists (the topology at the same place in both versions; a compute program is no pipeline)"""
return kind(r) == 0 and struct.unpack_from("<I", r, 44)[0] == POINT_LIST
def check_bytes(data, name="list"):
"""(records, faults, points): the records of a list's bytes, what is wrong with it (empty: sound), and how many records
draw point lists"""
if data[:8] != MAGIC:
return [], ["%s: not a pipeline state list (no %s head)" % (name, MAGIC.decode())], 0
if len(data) < 12 or struct.unpack_from("<I", data, 8)[0] != SIZE:
return [], ["%s: record size %s, not %d" % (name, struct.unpack_from("<I", data, 8)[0] if len(data) >= 12 else "?", SIZE)], 0
if data[:8] not in HEADS:
return [], ["%s: not a pipeline state list (no %s or %s head)" % (name, MAGIC2.decode(), MAGIC.decode())], 0
size = head_size(data)
if not size:
return [], ["%s: record size %s, not %d" % (name, struct.unpack_from("<I", data, 8)[0] if len(data) >= 12 else "?",
HEADS[data[:8]])], 0
body = data[12:]
faults = []
if len(body) % SIZE:
faults.append("%s: %d bytes past its last whole record (cut short)" % (name, len(body) % SIZE))
recs = [body[i:i + SIZE] for i in range(0, len(body) - SIZE + 1, SIZE)]
if len(body) % size:
faults.append("%s: %d bytes past its last whole record (cut short)" % (name, len(body) % size))
recs = [body[i:i + size] for i in range(0, len(body) - size + 1, size)]
bad = 0
for k, r in enumerate(recs):
f = record_faults(r)
@@ -108,13 +281,6 @@ def check_bytes(data, name="list"):
return recs, faults, sum(1 for r in recs if is_point(r))
def read_any(path):
"""A list's bytes, plain or xz-packed (.xz)"""
with open(path, "rb") as f:
data = f.read()
return lzma.decompress(data) if path.endswith(".xz") else data
def contrib_sources(folder):
"""The players' lists in a folder: (name, path, note), by name; a list's note is <name>.note beside it ("" without)"""
out = []
@@ -130,15 +296,20 @@ def contrib_sources(folder):
return out
def merge_sources(sources, keep_points=False):
def merge_sources(sources, keep_points=False, force_v2=False):
"""sources: (name, bytes, note) in order. The merged records (each once, in the order first met) and a report line a
source: its records, what it added, its repeats, the point-list records left out, or why it was left out whole"""
merged, seen, report = [], set(), []
for name, data, note in sources:
recs, faults, points = check_bytes(data, name)
source: its records, what it added, its repeats, the point-list records left out, or why it was left out whole. Version 2
when any sound source is (or force_v2): each version 1 record converted first, those that cannot be counted"""
checked, report = [], [None] * len(sources)
for i, (name, data, note) in enumerate(sources):
recs, faults, _points = check_bytes(data, name)
if faults:
report.append("%s: left out: %s" % (name, "; ".join(faults)))
report[i] = "%s: left out: %s" % (name, "; ".join(faults))
continue
checked.append((i, name, recs, note))
lists, lost = as_v2([recs for _i, _name, recs, _note in checked], force_v2)
merged, seen = [], set()
for (i, name, given, note), recs, gone in zip(checked, lists, lost):
added = repeats = dropped = 0
for r in recs:
if is_point(r) and not keep_points:
@@ -150,8 +321,9 @@ def merge_sources(sources, keep_points=False):
seen.add(r)
merged.append(r)
added += 1
report.append("%s: %d pipelines, %d added, %d already in, %d point-list records left out%s" %
(name, len(recs), added, repeats, dropped, (" (" + note + ")") if note else ""))
report[i] = "%s: %d pipelines, %d added, %d already in, %d point-list records left out%s%s" % (
name, len(given), added, repeats, dropped, (", %d not converted to version 2" % gone) if gone else "",
(" (" + note + ")") if note else "")
return merged, report
@@ -168,7 +340,7 @@ def export_zip(list_path, zip_path):
report.write("Triforce pipeline state list, for the shipped list (hashes and draw state only, no game code)\n")
report.write("%s\n" % describe(recs))
report.write("point-list records: %d\n" % points)
report.write("record size %d, %s\n" % (SIZE, MAGIC.decode()))
report.write("record size %d, %s\n" % (head_size(data), data[:8].decode()))
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as z:
z.writestr("triforce_pipeline_states.bin.xz", lzma.compress(data))
z.writestr("report.txt", report.getvalue())
@@ -176,20 +348,30 @@ def export_zip(list_path, zip_path):
def describe(recs):
versions = collections.Counter(1 if len(r) == SIZE else 2 for r in recs)
programs = collections.Counter()
kinds = collections.Counter()
for r in recs:
code = struct.unpack_from("<4Q", r, 0)
mesh = struct.unpack_from("<I", r, 40)[0]
programs[(code, mesh)] += 1
kinds["mesh" if mesh else "graphics"] += 1
return "%d pipelines (%s) of %d programs" % (len(recs), ", ".join("%s %d" % kv for kv in sorted(kinds.items())), len(programs))
compute = kind(r) == COMPUTE
programs[(code, mesh, compute)] += 1
kinds["compute" if compute else "mesh" if mesh else "graphics"] += 1
return "%d pipelines (%s) of %d programs%s" % (len(recs), ", ".join("%s %d" % kv for kv in sorted(kinds.items())), len(programs),
"".join(", version %d" % v for v in sorted(versions)))
def write(path, recs):
data = pack(recs)
with open(path, "wb") as f:
f.write(lzma.compress(data) if path.endswith(".xz") else data)
def main():
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
p.add_argument("lists", nargs="*")
p.add_argument("--out")
p.add_argument("--v2", action="store_true", help="version 2 out even from version 1 lists alone (converted)")
p.add_argument("--check", action="store_true", help="check each list: exit 1 when one is not sound")
p.add_argument("--contrib", help="a folder of players' lists (*.bin.xz, a .note each), checked and merged after the lists")
p.add_argument("--keep-points", action="store_true", help="keep point-list records (refused by --check, left out by --contrib)")
@@ -209,27 +391,32 @@ def main():
if a.contrib:
sources = [(os.path.basename(x), read_any(x), "") for x in a.lists]
sources += [(name, read_any(path), note) for name, path, note in contrib_sources(a.contrib)]
merged, report = merge_sources(sources, a.keep_points)
merged, report = merge_sources(sources, a.keep_points, a.v2)
for line in report:
print(line)
if a.out:
with open(a.out, "wb") as f:
f.write(MAGIC + struct.pack("<I", SIZE) + b"".join(merged))
write(a.out, merged)
print("%s: %s" % (a.out, describe(merged)))
return 0
if not a.lists:
p.error("no list")
merged, seen = [], set()
lists = []
for path in a.lists:
recs = read(path)
print("%s: %s" % (path, describe(recs)))
for r in recs:
if r not in seen:
seen.add(r)
merged.append(r)
lists.append(recs)
if a.out:
with open(a.out, "wb") as f:
f.write(MAGIC + struct.pack("<I", SIZE) + b"".join(merged))
lists, lost = as_v2(lists, force=a.v2)
if sum(lost):
print("%d version 1 pipelines not converted (a format no table entry has, or a mesh fallback record without its "
"answers): left out" % sum(lost))
merged, seen = [], set()
for recs in lists:
for r in recs:
if r not in seen:
seen.add(r)
merged.append(r)
write(a.out, merged)
print("%s: %s" % (a.out, describe(merged)))

View File

@@ -8,7 +8,9 @@ from Font2/Scalable/External.*.bfotf (dialogue, the control hints, menus): A B X
and Minus at E04B and E04C, the stick presses at E056 and E057, the d-pad at E060..E063. Each written font has one icon per pad
input at U+F700 + HOS_PAD_* (gpu/vk/vk_api.h), and each of those Switch buttons' code points in a cmap segment of its own: the
game (host/prompts.c) points each one at the icon of the pad input bound to that button when it serves the font, so the icons
follow the controls, changed ones too. (Triforce) The keyboard face (the keyboard and mouse; nx2/prompt_keys.py draws it, from
follow the controls, changed ones too. (Triforce) Each controller face's font also has every controller face's icons
(faces_font: FACE_BASE, BIND_BASE), the same glyphs in each, so the game points the font it has at another face or new
controls while it runs (host/prompts.c's live part). The keyboard face (the keyboard and mouse; nx2/prompt_keys.py draws it, from
nothing but a font of the repository's) has an icon per key that can be bound instead, at U+F700 + its key code, and what is
said of a pad input below is a key code's there.
@@ -27,7 +29,8 @@ rsizetable.zs is the game's table with the font's entry raised to fit the larges
(Triforce) The title screen's Options entry ("Options / ZELDA NOTES Setting") the same way: <out>/mals/<language>.product.110
.sarc.zs is each language's messages with that entry made the game's word for Options, its separator and TITLE_TEXT, and the
host serves the one of the language the game runs in (title_messages).
host serves the one of the language the game runs in (title_messages). The same file has the texts that name the
console in the PC's words (PC_TEXTS: the ocarina's microphone hint says your microphone, not the console's), at the same size.
A .bfotf is an OpenType font behind an 8-byte header and XORed per little-endian word: the header is the magic 0x18029a7f and the
font's size (big-endian), each XORed with the same key as the font. The .zs files are zstd frames made with the dictionary zs.zsdic
@@ -155,20 +158,38 @@ def cmap4(mapping, single):
return struct.pack(">HHHHIHHI", 0, 2, 0, 3, 20, 3, 1, 20) + sub
def face_font(otf, face):
"""the game's font (decrypted) with this face's icons: a pad icon per input at PAD_BASE + its number, and the Switch buttons'
code points on the default controls' icons"""
# ((Triforce) the button prompts changed while the game runs, host/prompts.c's live part) Every controller face's font has every
# controller face's icons (LIVE_FACES, HOS_PROMPT_*'s order up to the keyboard's), so a new face or new controls are a change of
# the cmap of the font the game has (the same glyphs, the same size): face n's icon of pad input i at FACE_BASE + FACE_CODES x n
# + i, its d-pad icons (STATIC) at FACE_BASE + FACE_CODES x n + STATIC_AT.., and a code of its own for each Switch button b on
# each pad input i of each face at BIND_BASE + (n x 16 + b) x 17 + i, which a text's button codes are rewritten to (the game
# keeps a code's glyph once drawn: a new icon gets a code never drawn with another). All in the Private Use Area the game's font
# leaves free (checked: face_font)
LIVE_FACES = ["switch"] + [f for f in FACES if not FACES[f].get("keys")]
FACE_BASE = 0xF800
FACE_CODES = 32
STATIC_AT = 24
BIND_BASE = 0xF000
_FACES_CACHE = {}
def faces_font(otf):
"""(Triforce) the game's font (decrypted) with every controller face's icons added (LIVE_FACES), once for each game font:
(the font's bytes, {code: glyph name} of the codes added, {face: [its glyph per pad input]}, {face: {STATIC code: glyph}})"""
key = hash(otf)
if key in _FACES_CACHE:
return _FACES_CACHE[key]
from fontTools.pens.boundsPen import BoundsPen
from fontTools.pens.t2CharStringPen import T2CharStringPen
from fontTools.pens.transformPen import TransformPen
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables.DefaultTable import DefaultTable
game = TTFont(io.BytesIO(otf))
gset, cmap = game.getGlyphSet(), dict(game.getBestCmap())
top = game["CFF "].cff.topDictIndex[0]
chars = top.CharStrings
order = list(game.getGlyphOrder())
hmtx = game["hmtx"]
def bounds(glyphset, name):
p = BoundsPen(glyphset)
@@ -180,68 +201,103 @@ def face_font(otf, face):
chars.charStrings[name] = len(chars.charStringsIndex) - 1
top.charset.append(name)
order.append(name)
game["hmtx"].metrics[name] = (width, 0)
hmtx.metrics[name] = (width, 0)
return name
if face == "switch":
icon = {p: cmap[SWITCH_ICON[p]] for p in PADS}
for i, p in enumerate(PADS):
src = chars[icon[p]]
src.decompile()
add(f"pad_{p}", src, game["hmtx"][icon[p]][0])
else:
f = FACES[face]
prefix, names = f["prefix"], f["icons"]
kenney = TTFont(os.path.join(KENNEY, f["font"]))
kset = kenney.getGlyphSet()
def copy(name, target):
src = chars[target]
src.decompile()
return add(name, src, hmtx[target][0])
def kname(s):
return s[1:] if s.startswith("/") else prefix + s
assert BIND_BASE + len(LIVE_FACES) * len(SWITCH) * len(PADS) <= PAD_BASE
assert FACE_BASE + FACE_CODES * len(LIVE_FACES) <= 0x10000 and len(PADS) <= STATIC_AT and STATIC_AT + len(STATIC) <= FACE_CODES
placed, pads, statics = {}, {}, {}
for n, face in enumerate(LIVE_FACES):
base = FACE_BASE + FACE_CODES * n
if face == "switch": # (the game's own icons, a glyph of their own each as the other faces' are)
pads[face] = [copy(f"pad_{face}_{p}", cmap[SWITCH_ICON[p]]) for p in PADS]
statics[face] = {c: cmap[c] for c in STATIC if c in cmap}
else:
f = FACES[face]
prefix, names = f["prefix"], f["icons"]
kenney = TTFont(os.path.join(KENNEY, f["font"]))
kset = kenney.getGlyphSet()
def draw(target, kn):
"""the Kenney glyph scaled into the box of the game's glyph `target` (as a square around its centre); a wide one (the
Menu and View pills on the square Plus and Minus) as high as the box, up to WIDE times as wide, the glyph widened"""
gb, kb = bounds(gset, target), bounds(kset, kn)
side = max(gb[2] - gb[0], gb[3] - gb[1])
s = min(side * WIDE / (kb[2] - kb[0]), side / (kb[3] - kb[1]))
over = max(0, s * (kb[2] - kb[0]) - side)
dx = (gb[0] + gb[2] + over) / 2 - s * (kb[0] + kb[2]) / 2
dy = (gb[1] + gb[3]) / 2 - s * (kb[1] + kb[3]) / 2
width = game["hmtx"][target][0] + round(over)
pen = T2CharStringPen(width, gset)
kset[kn].draw(TransformPen(pen, (s, 0, 0, s, dx, dy)))
cs = chars[target]
return pen.getCharString(private=cs.private, globalSubrs=cs.globalSubrs), width
def kname(s):
return s[1:] if s.startswith("/") else prefix + s
for p in PADS:
kn = kname(names[p]) if p in names else None
if kn not in kset: # (no such button on this face, the PlayStation's PS button: the game's own icon)
kn = None
target = cmap[SWITCH_ICON[p]]
if kn:
add(f"pad_{p}", *draw(target, kn))
else:
src = chars[target]
src.decompile()
add(f"pad_{p}", src, game["hmtx"][target][0])
for c, s in STATIC.items():
kn = prefix + s
if c in cmap and kn in kset:
cs, _ = draw(cmap[c], kn)
chars[cmap[c]] = cs
def draw(target, kn):
"""the Kenney glyph scaled into the box of the game's glyph `target` (as a square around its centre); a wide one
(the Menu and View pills on the square Plus and Minus) as high as the box, up to WIDE times as wide, the glyph
widened"""
gb, kb = bounds(gset, target), bounds(kset, kn)
side = max(gb[2] - gb[0], gb[3] - gb[1])
s = min(side * WIDE / (kb[2] - kb[0]), side / (kb[3] - kb[1]))
over = max(0, s * (kb[2] - kb[0]) - side)
dx = (gb[0] + gb[2] + over) / 2 - s * (kb[0] + kb[2]) / 2
dy = (gb[1] + gb[3]) / 2 - s * (kb[1] + kb[3]) / 2
width = hmtx[target][0] + round(over)
pen = T2CharStringPen(width, gset)
kset[kn].draw(TransformPen(pen, (s, 0, 0, s, dx, dy)))
cs = chars[target]
return pen.getCharString(private=cs.private, globalSubrs=cs.globalSubrs), width
pads[face] = []
for p in PADS:
kn = kname(names[p]) if p in names else None
target = cmap[SWITCH_ICON[p]]
# (no such button on this face, the PlayStation's PS button: the game's own icon)
pads[face].append(add(f"pad_{face}_{p}", *draw(target, kn)) if kn in kset else
copy(f"pad_{face}_{p}", target))
statics[face] = {}
for c, s in STATIC.items():
kn = prefix + s
if c in cmap:
statics[face][c] = add(f"static_{face}_{c:04x}", *draw(cmap[c], kn)) if kn in kset else cmap[c]
for i in range(len(PADS)):
placed[base + i] = pads[face][i]
for k, c in enumerate(STATIC):
if c in statics[face]:
placed[base + STATIC_AT + k] = statics[face][c]
for b in range(len(SWITCH)):
for i in range(len(PADS)):
placed[BIND_BASE + (n * len(SWITCH) + b) * len(PADS) + i] = pads[face][i]
taken = sorted(c for c in placed if c in cmap)
if taken:
raise SystemExit("prompts: the game's font already has code points %s: no room for the faces' icons" %
", ".join("U+%04X" % c for c in taken[:4]))
game.setGlyphOrder(order)
gid = {n: i for i, n in enumerate(order)}
mapping = {c: gid[n] for c, n in cmap.items() if c <= 0xFFFF}
for i, p in enumerate(PADS):
mapping[PAD_BASE + i] = gid[f"pad_{p}"]
out = io.BytesIO()
game.save(out)
_FACES_CACHE[key] = got = (out.getvalue(), placed, pads, statics)
return got
def face_font(otf, face):
"""the game's font (decrypted) with every controller face's icons (faces_font) and this face's on the codes the game and the
overlay read: a pad icon per input at PAD_BASE + its number, the Switch buttons' code points on the default controls' icons,
the d-pad's (STATIC) on the face's. (the font, the glyph of each pad input's icon: write_hint's names)"""
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables.DefaultTable import DefaultTable
plain, placed, pads, statics = faces_font(otf)
game = TTFont(io.BytesIO(plain))
gid = {n: i for i, n in enumerate(game.getGlyphOrder())}
mapping = {c: gid[n] for c, n in TTFont(io.BytesIO(otf)).getBestCmap().items() if c <= 0xFFFF}
mapping.update({c: gid[n] for c, n in placed.items()})
own = pads[face]
for i in range(len(PADS)):
mapping[PAD_BASE + i] = gid[own[i]]
for c, p in zip(SWITCH, DEFAULT):
mapping[c] = gid[f"pad_{p}"]
mapping[c] = gid[own[PADS.index(p)]]
for c, n in statics[face].items():
mapping[c] = gid[n]
t = DefaultTable("cmap")
t.data = cmap4(mapping, set(SWITCH))
t.data = cmap4(mapping, set(SWITCH) | set(STATIC)) # (each a segment of its own: host/prompts.c points them anew)
game["cmap"] = t
out = io.BytesIO()
game.save(out)
return out.getvalue()
return out.getvalue(), own
# ---- the textures with button icons (UI/Layout2Archive/Common.*.bntx: 878 textures, ASTC 4x4 and BC4, the Switch 2's block-linear
@@ -576,8 +632,8 @@ def guide_widened(stays):
def guide_route(size, bar, row, where, pad, stays, frame=None):
"""the way (points, the lines' pixels) of a line from a bar's row to the pad input's part, round the picture's other parts and
with the fewest bends, crossing the lines that stay (L) as little as it can: it comes to a stick's centre, to a part just off
its edge (above it best), or to a frame's corner (frame: centre, corners' distance)"""
with the fewest bends, crossing the lines that stay (L) as little as it can: it comes to a stick's centre, to a part's edge
(from above best), or to a frame's corner (frame: centre, corners' distance)"""
import heapq
import math
import numpy as np
@@ -631,9 +687,10 @@ def guide_route(size, bar, row, where, pad, stays, frame=None):
elif pad in ("lstick", "rstick"):
for d in range(4):
goal(x, y, d, 0)
else:
for (ex, ey), d, extra in (((x, y - r - 13), 2, 0), ((x, y + r + 13), 3, GUIDE_SIDE), ((x - r - 13, y), 0, GUIDE_SIDE),
((x + r + 13, y), 1, GUIDE_SIDE)):
else: # (on its edge, as the game's own lines end: 2 pixels into it)
e = max(r - 2, 0)
for (ex, ey), d, extra in (((x, y - e), 2, 0), ((x, y + e), 3, GUIDE_SIDE), ((x - e, y), 0, GUIDE_SIDE),
((x + e, y), 1, GUIDE_SIDE)):
if r or d >= 2:
goal(ex, ey, d, extra)
start = (0, 0, 0 if bar == 0 else 1)
@@ -700,9 +757,10 @@ def guide_draw(size, way, dot):
def guide_line(size, bar, row, where, pad, stays):
"""a leader line (L, size) from a bar's row to the pad input's part (where: the picture's parts), ending on a dot"""
way = guide_route(size, bar, row, where, pad, stays)
if not way: # (no way round: straight along the row, then up or down)
if not way: # (no way round: straight along the row, then up or down to the part's edge, as guide_route ends)
x, y, r = guide_at(where[pad])
y += 0 if pad in ("lstick", "rstick") else -(r + 13) if row < y else r + 13
e = 0 if pad in ("lstick", "rstick") else max(r - 2, 0)
y += -e if row < y else e
way = [(BARS[0] if bar == 0 else BARS[1], row + 3), (x, row + 3), (x, y)]
return guide_draw(size, way, True)
@@ -726,10 +784,33 @@ def guide_frame(size, bar, row, where, group, stays):
return ImageChops.lighter(im, guide_draw(size, way, False))
def game_line(im, bar, row):
"""where the game's line from bar (0 left, 1 right) at row is drawn in im (L, a guide texture): the shape it makes between
the bars, as it is (the router's route to the same part runs elsewhere: taking that out left pieces of the game's line), a
little wider for its soft edge. The whole shape the line's pixels touch: a game line touching another between the bars
would be taken with it (the game's do not touch). None found near the label: an empty mask, said on stderr"""
from PIL import Image, ImageDraw, ImageFilter
x0, x1 = BARS[0] + 3, BARS[1] - 3 # (off the bars: they join the lines of one side)
lit = im.point(lambda v: 255 if v > 24 else 0)
inner = Image.new("L", im.size, 0)
inner.paste(lit.crop((x0, 0, x1, im.height)), (x0, 0))
x = x0 + 2 if bar == 0 else x1 - 3
y = min((y for y in range(row - 12, row + 13) if 0 <= y < im.height and inner.getpixel((x, y))), key=lambda y: abs(y - row),
default=None)
out = Image.new("L", im.size, 0)
if y is None:
print(f"prompts: no game line from bar {bar} at row {row}: nothing taken out there", file=sys.stderr)
return out
ImageDraw.floodfill(inner, (x, y), 128)
out.paste(inner.point(lambda v: 255 if v == 128 else 0).filter(ImageFilter.MaxFilter(7)).crop((BARS[0] + 1, 0, BARS[1], im.height)),
(BARS[0] + 1, 0))
return out
def guide_layers(game, face):
"""the page's leader lines for this face's picture, from the game's (L images, GUIDES): each texture's lines that stay (the
Switch face: the game's), and {texture: [(Switch button, {pad input: its line})]}"""
from PIL import Image, ImageChops, ImageFilter
from PIL import Image, ImageChops
where, size = parts(face), game[0].size
keep = [] # (the game's bars, or on the Switch face all the game's but the lines that move)
for im in game:
@@ -756,9 +837,7 @@ def guide_layers(game, face):
guide_line(size, bar, row, where, pad, stays)) for pad in PADS if pad in where}
if face == "switch": # (the game's own line where the pad input's is hookshot's default's: taken out of what stays)
own = lines[DEFAULT[SW[end]]]
around = Image.new("L", size, 0)
grown = own.filter(ImageFilter.MaxFilter(25 if DEFAULT[SW[end]] in sum(GUIDE_GROUPS, ()) else 15))
around.paste(grown.crop((BARS[0] + 1, 0, BARS[1], size[1])), (BARS[0] + 1, 0))
around = game_line(game[tx], bar, row)
game_own = ImageChops.multiply(game[tx], around)
for pad, im in lines.items():
if im is own:
@@ -789,23 +868,29 @@ def guide_layers_of(b, tex, face):
def picture_layers(b, tex, im):
"""the layers putting a face's controller picture (1160x680 RGBA, drawn like Controller_Pro) in place of the Pro Controller:
the picture, the page's tinted copy (each channel a line of the grey level, fitted on the game's pair) and the shadow (the
outline's left part squeezed into ControllerSh_Pro1 and blurred, fitted on the game's)"""
"""the layers putting a face's controller picture (1160x680 RGBA, drawn in grey like Controller_Pro) in place of the Pro
Controller: the picture, the page's tinted copy (each grey the colour the game's own pair gives it) and the shadow (the
outline's left part squeezed into ControllerSh_Pro1 and blurred, fitted on the game's). ((Triforce) 11-24) The game's tint
is no straight line of the grey: its black outlines turn a brown lighter than the #333333 body, which turns almost black,
so a line fitted through the pair crushed a hand-drawn picture's outlines, lit its body and dimmed its buttons"""
import numpy as np
from PIL import Image, ImageFilter
plain, tinted = (np.asarray(decode(b, tex[n]).convert("RGBA")).astype(float) for n in (PICTURES[0], PICTURE_TINT))
solid = plain[..., 3] > 250
grey = plain[solid][:, :3].sum(1)
lines = [np.polyfit(grey, tinted[solid][:, c], 1) for c in range(3)]
solid = (plain[..., 3] > 250) & (tinted[..., 3] > 250)
grey, colour = np.rint(plain[solid][:, :3].mean(1)).astype(int), tinted[solid][:, :3]
levels, counts = np.unique(grey, return_counts=True)
levels = levels[counts >= 20] # (the greys the game drew enough of: not a few blended edge pixels)
if not len(levels):
raise SystemExit(f"prompts: no grey of the game's {PICTURES[0]} has its colour in {PICTURE_TINT}: not the pair known")
table = np.array([np.median(colour[grey == v], 0) for v in levels])
px = np.asarray(im).astype(float)
level = px[..., :3].sum(2)
tint = np.dstack([np.clip(np.polyval(lines[c], level), 0, 255) for c in range(3)] + [px[..., 3]])
level = px[..., :3].mean(2)
tint = np.dstack([np.interp(level, levels, table[:, c]) for c in range(3)] + [px[..., 3]])
sh = tex[PICTURE_SHADOW]
shadow = im.getchannel("A").crop((40, 0, 480, 680)).resize((sh[2], sh[3])).filter(ImageFilter.GaussianBlur(24))
shadow = shadow.point(lambda v: round(v * 0.7))
return [Layer(PICTURES[0] + ".png", PICTURES[0], 0xFF, 0, im),
Layer(PICTURE_TINT + ".png", PICTURE_TINT, 0xFF, 0, Image.fromarray(tint.astype("uint8"))),
Layer(PICTURE_TINT + ".png", PICTURE_TINT, 0xFF, 0, Image.fromarray(np.rint(tint).astype("uint8"))),
Layer(PICTURE_SHADOW + ".png", PICTURE_SHADOW, 0xFF, 0, shadow)]
@@ -1465,6 +1550,98 @@ def size_entry(table, path):
return None
# ---- (Triforce) the game's texts that name the console, in the PC's words. One does: the hint for playing the ocarina by
# microphone ("Ocarina Audio Input") says to use the console's built-in one; on a PC the game listens to the microphone the
# Insert menu's Microphone row chooses. It is reworded in the same messages archive as the title's entry (title_messages
# writes the one file a language), in the string's own room: the string's bytes from start to end become the replacement,
# the rest (the other sentences, the tags, the reading aids over the kanji) stays the game's, and what is left of its room is
# filled with NULs, so no offset moves and the archive keeps its size. A wording is known by its fingerprint (no game text in
# this file); a string that is not one of them (another version, a mod's text) is left as it is and said
# [(msbt, label, {a wording's fingerprint: (start, end, replacement)})]
PC_TEXTS = [
# the "Ocarina Audio Input" hint: the console's built-in microphone -> your microphone (the languages that have that wording)
("LayoutMsg/ActionGuide_00.msbt", "Pa_ActionGuide_01-T_Description_00", {
"b816b30394a86b8a": (4, 38, "your microphone"), # USen, EUen
"9925b429328b1fd2": (21, 69, "votre microphone\n"), # USfr, EUfr
"e4bd22fcea2f8529": (16, 60, "un micrófono"), # USes, EUes
"0dd1fb25d15aec84": (4, 46, "o seu microfone"), # USpt
"3179003a18de9124": (9, 64, "dein Mikrofon"), # EUde
"7fa2434137fc436c": (11, 54, "il tuo microfono"), # EUit
"7f5339bb84e3bb77": (8, 56, "je microfoon"), # EUnl
"21bce07f220b2409": (8, 57, "mikrofonowi"), # EUpl
"54935b14b603297c": (0, 55, "Микрофон"), # EUru
"ed6bdf6d1550bdad": (0, 50, ""), # JPja: "the console's" goes, the microphone stays
"01467ba53d125ec9": (0, 28, ""), # KRko: the same
"cd07456de7b137ad": (6, 32, ""), # CNzh: the same
"c52f433f130e10eb": (6, 32, ""), # TWzh: the same
}),
]
def text_fingerprint(text):
"""a wording's name in PC_TEXTS: of the string's whole room, its terminator too"""
import hashlib
return hashlib.sha1(bytes(text)).hexdigest()[:16]
def msbt_rooms(m):
"""an MSBT's strings by label: {label: (start, end)}, each string's room in m (its bytes, tags and terminator, up to the
next string's start); None when it is not a UTF-8 MSBT with labels and texts"""
if len(m) < 0x20 or m[:8] != b"MsgStdBn" or m[8:10] != b"\xff\xfe" or m[12] != 0: # (little-endian, UTF-8)
return None
at, sections = 0x20, {}
while at + 16 <= len(m):
size = struct.unpack_from("<I", m, at + 4)[0]
sections[bytes(m[at:at + 4])] = (at + 16, size)
at = (at + 16 + size + 15) & ~15
if b"LBL1" not in sections or b"TXT2" not in sections:
return None
lbl, _ = sections[b"LBL1"]
txt, txt_size = sections[b"TXT2"]
count = struct.unpack_from("<I", m, txt)[0]
starts = list(struct.unpack_from("<%dI" % count, m, txt + 4)) + [txt_size]
out = {}
for slot in range(struct.unpack_from("<I", m, lbl)[0]):
n, at = struct.unpack_from("<II", m, lbl + 4 + 8 * slot)
at += lbl
for _ in range(n):
length = m[at]
index = struct.unpack_from("<I", m, at + 1 + length)[0]
if index < count:
out[bytes(m[at + 1:at + 1 + length]).decode("utf-8")] = (txt + starts[index], txt + starts[index + 1])
at += 5 + length
return out
def pc_texts(sarc, strings=None):
"""a language's messages (Mals/*.sarc, decompressed) with PC_TEXTS' edits made: (the new bytes, the same length; the
labels reworded; the labels left as they are, each with why)"""
out, done, left = bytearray(sarc), [], []
for msbt, label, edits in PC_TEXTS if strings is None else strings:
at = sarc_member(out, msbt)
if not at:
left.append((label, "no %s" % msbt))
continue
base, end = at
rooms = msbt_rooms(out[base:end])
if rooms is None or label not in rooms:
left.append((label, "no such string"))
continue
a, b = (base + x for x in rooms[label])
text = bytes(out[a:b])
if text_fingerprint(text) not in edits:
left.append((label, "its text is not one this was written for"))
continue
start, stop, new = edits[text_fingerprint(text)]
new = new.encode("utf-8")
if not 0 <= start <= stop < len(text) or len(new) > stop - start:
raise ValueError("%s: the replacement does not fit what it replaces" % label)
text = text[:start] + new + text[stop:]
out[a:b] = text + b"\0" * (b - a - len(text)) # (in its own room: nothing after it moves)
done.append(label)
return bytes(out), done, left
def title_messages(romfs, dictionary, out, text=TITLE_TEXT):
"""writes <out>/mals/<language>.product.110.sarc.zs for each language whose messages are the ones known and whose
rewritten archive is no larger than the game's file (and within its entry in the size table, where it has one); the
@@ -1474,7 +1651,7 @@ def title_messages(romfs, dictionary, out, text=TITLE_TEXT):
the game has it (the build says so) rather than raising the entry"""
import zstandard
_, table = read_size_table(romfs, dictionary)
done = []
done, worded_in = [], []
for name in sorted(os.listdir(os.path.join(romfs, MALS))):
if not name.endswith(".sarc.zs"):
continue
@@ -1482,17 +1659,27 @@ def title_messages(romfs, dictionary, out, text=TITLE_TEXT):
new = title_sarc(game, text)
if not new:
print(f"prompts: {MALS}/{name}: the title keeps its text (its messages are not the ones known)", file=sys.stderr)
continue
entry = size_entry(table, f"{MALS}/{name[:-3]}")
fits = len(game) if entry is None else min(len(game), entry) # (the entry's allowance over the file kept)
if len(new) > fits:
if new and len(new) > fits:
print(f"prompts: {MALS}/{name}: the title keeps its text ({len(new)} bytes; the game's file is {len(game)}, "
f"its size table entry {entry}: a shorter TITLE_TEXT fits)", file=sys.stderr)
new = None
# ((Triforce) the texts that name the console, in the PC's words, in the same file: they keep its size)
worded, said, left = pc_texts(new or game)
for label, why in left:
print(f"prompts: {MALS}/{name}: {label} left as it is ({why})", file=sys.stderr)
if not new and not said:
continue
os.makedirs(os.path.join(out, "mals"), exist_ok=True)
with open(os.path.join(out, "mals", name.lower()), "wb") as f:
f.write(zstandard.ZstdCompressor(level=3).compress(new))
done.append(name.split(".")[0])
f.write(zstandard.ZstdCompressor(level=3).compress(worded))
if new:
done.append(name.split(".")[0])
if said:
worded_in.append(name.split(".")[0])
if worded_in:
print("prompts: the ocarina's microphone hint says your microphone in " + " ".join(worded_in), file=sys.stderr)
return done
@@ -1515,8 +1702,8 @@ def main():
import PIL # noqa: F401
import texture2ddecoder # noqa: F401
textures = read_zs(a.romfs, TEXTURES, dictionary)
except ImportError:
print("prompts: the textures keep the Switch's icons (no astc_encoder, Pillow or texture2ddecoder)", file=sys.stderr)
except ImportError as e: # (the module that is missing: a package's own dependency too, astc_encoder's archspec)
print(f"prompts: the textures keep the Switch's icons (no {e.name or e})", file=sys.stderr)
if textures:
os.makedirs(a.out, exist_ok=True)
with open(os.path.join(a.out, "Common.bntx"), "wb") as f:
@@ -1543,7 +1730,7 @@ def main():
prompt_keys.write_binds(os.path.join(d, "keys.bin"), binds)
names = prompt_keys.hint_names()
else:
plain = face_font(otf, face)
plain, names = face_font(otf, face)
font = wrap(key, plain)
if hint:
write_hint(os.path.join(d, "hint.bin"), plain, hint, names)

View File

@@ -48,6 +48,19 @@ def _parts(axis, sticks, dpad, face, small, home, shoulders, **boxes):
SWITCH_PARTS = _parts(1159, ((348, 227, 48), (683, 348, 48)), (455, 348, 45, 17),
((800, 168), (731, 227), (869, 227), (800, 286), 32), (477, 161, 19), (631, 227, 21), ((375, 39), (290, 60)))
# ((Triforce) 11-24) the pictures drawn by hand (nx2/prompt_faces/<face>/Controller_Pro.png), in place of the drawn ones: their
# parts, which the leader lines end on (the router draws every line, ControllerGuide_Pro_00 to 04, to them). The PlayStation
# faces' picture is one DualSense (ps4/ and ps5/)
_DUALSENSE = _parts(1158, ((442, 334, 44), (716, 334, 44)), (312, 213, 45, 21), ((848, 146), (786, 213), (910, 213), (848, 279), 27),
(379, 115, 11), (579, 327, 26), ((340, 49), (265, 68)), touchpad=(413, 57, 751, 240), mute=(559, 376, 599, 388))
# (an Xbox One pad: a bumper's end is under its trigger's, as the Menu line leaves no other way to RB without a crossing)
_XBOX = _parts(1158, ((357, 202, 44), (695, 335, 44)), (462, 346, 41, 17), ((805, 146), (746, 205), (865, 206), (805, 260), 28),
(516, 203, 18), (581, 116, 31), ((425, 39), (385, 69)))
# (the Steam Deck: L2 and R2 inward of View and Menu, so that their lines do not cross View's and Menu's)
_STEAMDECK = _parts(1162, ((287, 241, 35), (874, 241, 35)), (206, 228, 20, 9),
((955, 200), (930, 225), (981, 225), (955, 250), 12), (255, 196, 8), (303, 409, 10),
((272, 162), (212, 162)), screen=(355, 197, 810, 482), ltrackpad=(231, 288, 326, 383),
rtrackpad=(834, 288, 929, 383), more=(836, 399, 883, 418))
FACES = {
"xbox": dict(
@@ -57,8 +70,7 @@ FACES = {
("face", .700, .275, .080, "west"), ("face", .775, .375, .080, "south"), ("face", .775, .175, .080, "north"),
("face", .850, .275, .080, "east"), ("small", .498, .120, .090, "guide"), ("small", .420, .275, .052, "back"),
("small", .576, .275, .052, "start"), ("small", .498, .355, .044, None)]),
parts=_parts(1156, ((343, 210, 43), (696, 344, 43)), (451, 364, 44, 16), ((809, 160), (746, 218), (871, 218), (809, 275), 31),
(513, 218, 19), (578, 129, 34), ((330, 48), (470, 57)), share=(558, 243, 598, 283)),
parts=_XBOX,
icons=dict(_DPAD, south="button_a", east="button_b", west="button_x", north="button_y", back="button_view",
start="button_menu", lshoulder="lb", rshoulder="rb", ltrigger="lt", rtrigger="rt", lstick="ls", rstick="rs")),
"ps4": dict(
@@ -68,8 +80,7 @@ FACES = {
("pad", .499, .200, (.320, .280), None), ("face", .742, .285, .072, "west"), ("face", .814, .175, .072, "north"),
("face", .814, .395, .072, "south"), ("face", .886, .285, .072, "east"), ("small", .298, .130, .036, "back"),
("small", .702, .130, .036, "start"), ("small", .500, .510, .046, "guide")]),
parts=_parts(1160, ((447, 357, 40), (713, 357, 40)), (326, 237, 49, 18), ((841, 177), (781, 234), (901, 234), (841, 292), 28),
(412, 153, 12), (580, 352, 16), ((320, 67), (455, 92)), touchpad=(446, 117, 712, 263)),
parts=_DUALSENSE,
icons=dict(_DPAD, south="button_cross", east="button_circle", west="button_square", north="button_triangle",
back="/playstation4_button_share", start="/playstation4_button_options", lshoulder="trigger_l1",
rshoulder="trigger_r1", ltrigger="trigger_l2", rtrigger="trigger_r2", lstick="button_l3", rstick="button_r3")),
@@ -80,8 +91,7 @@ FACES = {
("pad", .498, .175, (.400, .300), None), ("face", .765, .265, .078, "west"), ("face", .840, .150, .078, "north"),
("face", .840, .380, .078, "south"), ("face", .915, .265, .078, "east"), ("small", .248, .080, .036, "back"),
("small", .750, .080, .036, "start"), ("small", .496, .480, .046, "guide"), ("small", .496, .575, .030, None)]),
parts=_parts(1158, ((430, 341, 39), (730, 341, 39)), (305, 217, 51, 19), ((863, 153), (800, 217), (925, 217), (863, 281), 30),
(370, 114, 12), (577, 336, 16), ((321, 52), (445, 64)), touchpad=(412, 84, 744, 250), mute=(563, 375, 591, 403)),
parts=_DUALSENSE,
icons=dict(_DPAD, south="button_cross", east="button_circle", west="button_square", north="button_triangle",
back="/playstation5_button_create", start="/playstation5_button_options", lshoulder="trigger_l1",
rshoulder="trigger_r1", ltrigger="trigger_l2", rtrigger="trigger_r2", lstick="button_l3", rstick="button_r3")),
@@ -93,9 +103,7 @@ FACES = {
("face", .935, .090, .036, "north"), ("face", .935, .270, .036, "south"), ("face", .900, .180, .036, "west"),
("face", .970, .180, .036, "east"), ("small", .125, .075, .024, "back"), ("small", .875, .075, .024, "start"),
("small", .150, .755, .030, "guide"), ("small", .850, .755, .030, None)]),
parts=_parts(1159, ((242, 230, 27), (917, 230, 27)), (157, 222, 25, 9), ((1009, 180), (974, 215), (1043, 215), (1009, 249), 16),
(209, 174, 9), (234, 437, 12), ((154, 144), (229, 142)), screen=(294, 159, 866, 491),
ltrackpad=(169, 290, 279, 394), rtrackpad=(880, 290, 990, 394), more=(908, 420, 942, 454)),
parts=_STEAMDECK,
icons=dict(_DPAD, south="button_a", east="button_b", west="button_x", north="button_y", back="button_view",
start="button_options", lshoulder="button_l1", rshoulder="button_r1", ltrigger="button_l2",
rtrigger="button_r2")),

View File

@@ -49,3 +49,7 @@ itself: draw it on black, the lines that stay are kept under it.
When a face's picture changes, its `parts` must follow it (the lines end on them): the pictures' pixels, `(x, y, r)` for each
control, see `_parts` in `nx2/prompt_faces.py`.
The ps4, ps5, xbox and steamdeck faces have a hand-drawn picture here (`<face>/Controller_Pro.png`, the PlayStation faces one
DualSense), drawn in the game's greys; their `parts` in `nx2/prompt_faces.py` are those pictures' own, so every leader line,
`ControllerGuide_Pro_00` to `_04`, is still drawn by the router to them and follows the controls.

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -1,253 +1,253 @@
{
"files": {
"compat/common/alignment.h": "7d387d1ea9b25d17",
"compat/common/assert.h": "263e8fcba7e74879",
"compat/common/bit_field.h": "9852d798d67c8a46",
"compat/common/bit_util.h": "11c767682c893025",
"compat/common/common_funcs.h": "d2c08a81d5764dbb",
"compat/common/alignment.h": "37bff579d5659579",
"compat/common/assert.h": "28c950a972284c01",
"compat/common/bit_field.h": "b559ca999e220617",
"compat/common/bit_util.h": "de746eafbe813edf",
"compat/common/common_funcs.h": "0a4740e8b98b3527",
"compat/common/common_types.h": "e138e55246d5aaee",
"compat/common/container/unordered_map.h": "5270aa23ee21fb13",
"compat/common/container/unordered_map.h": "6834e6f72055e371",
"compat/common/container/unordered_set.h": "de069bdadf0ed0c9",
"compat/common/container_hash.h": "7cd34c11c4e5bc83",
"compat/common/div_ceil.h": "c7bbba93fd23236d",
"compat/common/container_hash.h": "943db0c3bef8d5a7",
"compat/common/div_ceil.h": "fa9fb3f949418120",
"compat/common/logging.h": "1b35f168777d9f3b",
"compat/common/math_util.h": "173683402e47297b",
"compat/common/scope_exit.h": "f4ba153cac0aa19b",
"compat/common/settings.h": "7bfa6fc18167f151",
"compat/common/swap.h": "ed50c35a77dd3af1",
"eden/shader_recompiler/backend/bindings.h": "de612bc5c63a6a31",
"eden/shader_recompiler/backend/spirv/emit_spirv.cpp": "55e26ec1f7578449",
"eden/shader_recompiler/backend/spirv/emit_spirv.h": "8393e397a5ac3f89",
"eden/shader_recompiler/backend/spirv/emit_spirv_atomic.cpp": "fbdf4e9f07678581",
"eden/shader_recompiler/backend/spirv/emit_spirv_barriers.cpp": "9977b9035eb42dce",
"eden/shader_recompiler/backend/spirv/emit_spirv_bitwise_conversion.cpp": "0b52e452bd640043",
"eden/shader_recompiler/backend/spirv/emit_spirv_composite.cpp": "431db0f9217b97ab",
"eden/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp": "5fa23a97f994102b",
"eden/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp": "7a2837d46ed1edae",
"eden/shader_recompiler/backend/spirv/emit_spirv_convert.cpp": "ed43f65fbafc14c8",
"eden/shader_recompiler/backend/spirv/emit_spirv_floating_point.cpp": "7506b4658c0af39c",
"eden/shader_recompiler/backend/spirv/emit_spirv_image.cpp": "c345ed51d472a826",
"eden/shader_recompiler/backend/spirv/emit_spirv_image_atomic.cpp": "6315ecde1d6a0e66",
"eden/shader_recompiler/backend/spirv/emit_spirv_instructions.h": "d2c09949deff4979",
"eden/shader_recompiler/backend/spirv/emit_spirv_integer.cpp": "fd2664773e0a6146",
"eden/shader_recompiler/backend/spirv/emit_spirv_logical.cpp": "53ce945ef2a7d3be",
"eden/shader_recompiler/backend/spirv/emit_spirv_memory.cpp": "9ce368d381c1a5b3",
"eden/shader_recompiler/backend/spirv/emit_spirv_mesh.cpp": "2e485e471e8270f4",
"eden/shader_recompiler/backend/spirv/emit_spirv_select.cpp": "881436167c14fc6a",
"eden/shader_recompiler/backend/spirv/emit_spirv_shared_memory.cpp": "4b4758d356b6d171",
"eden/shader_recompiler/backend/spirv/emit_spirv_special.cpp": "b57f5f94c8b912ab",
"eden/shader_recompiler/backend/spirv/emit_spirv_undefined.cpp": "c47e1361fb3a587a",
"eden/shader_recompiler/backend/spirv/emit_spirv_warp.cpp": "65c0f77d9eb65698",
"compat/common/math_util.h": "88dd534bbafbb9c6",
"compat/common/scope_exit.h": "59067daefaefd89d",
"compat/common/settings.h": "e34c380adcfdfe79",
"compat/common/swap.h": "d25dc1078d451517",
"eden/shader_recompiler/backend/bindings.h": "95bf045f5ba5e553",
"eden/shader_recompiler/backend/spirv/emit_spirv.cpp": "1212787ae00a519f",
"eden/shader_recompiler/backend/spirv/emit_spirv.h": "9964f89e8e057e74",
"eden/shader_recompiler/backend/spirv/emit_spirv_atomic.cpp": "7fe5f796bd008679",
"eden/shader_recompiler/backend/spirv/emit_spirv_barriers.cpp": "c2cf474a5ee457f4",
"eden/shader_recompiler/backend/spirv/emit_spirv_bitwise_conversion.cpp": "bb54976ee313d626",
"eden/shader_recompiler/backend/spirv/emit_spirv_composite.cpp": "720ad81803829e27",
"eden/shader_recompiler/backend/spirv/emit_spirv_context_get_set.cpp": "7c7a9341ee8a09ef",
"eden/shader_recompiler/backend/spirv/emit_spirv_control_flow.cpp": "74f823950411d90f",
"eden/shader_recompiler/backend/spirv/emit_spirv_convert.cpp": "b54670ccec20955a",
"eden/shader_recompiler/backend/spirv/emit_spirv_floating_point.cpp": "2acebaaa88e8e41e",
"eden/shader_recompiler/backend/spirv/emit_spirv_image.cpp": "fee8a3943699705b",
"eden/shader_recompiler/backend/spirv/emit_spirv_image_atomic.cpp": "12e22a6ec61e9109",
"eden/shader_recompiler/backend/spirv/emit_spirv_instructions.h": "3428c6a7ea4ec33c",
"eden/shader_recompiler/backend/spirv/emit_spirv_integer.cpp": "7c1a7fc87fdacafd",
"eden/shader_recompiler/backend/spirv/emit_spirv_logical.cpp": "44fac347dba17c72",
"eden/shader_recompiler/backend/spirv/emit_spirv_memory.cpp": "9f4b04b0338e1c7c",
"eden/shader_recompiler/backend/spirv/emit_spirv_mesh.cpp": "cf725f3300f3db00",
"eden/shader_recompiler/backend/spirv/emit_spirv_select.cpp": "85a2835174d70ac1",
"eden/shader_recompiler/backend/spirv/emit_spirv_shared_memory.cpp": "8f3b0a6baa81347b",
"eden/shader_recompiler/backend/spirv/emit_spirv_special.cpp": "4d94b5070d4af640",
"eden/shader_recompiler/backend/spirv/emit_spirv_undefined.cpp": "5cf28b6889134487",
"eden/shader_recompiler/backend/spirv/emit_spirv_warp.cpp": "47d48e1e3a7948b9",
"eden/shader_recompiler/backend/spirv/mma_layout.h": "fafe05514871770d",
"eden/shader_recompiler/backend/spirv/spirv_emit_context.cpp": "330569ff0194ee94",
"eden/shader_recompiler/backend/spirv/spirv_emit_context.h": "99ce4aab9ee3bd63",
"eden/shader_recompiler/environment.h": "d7302bc595ef21f3",
"eden/shader_recompiler/exception.h": "f5539b4b90dfd29a",
"eden/shader_recompiler/frontend/ampere/geometry_exit.h": "cf8de70aca202571",
"eden/shader_recompiler/frontend/ampere/instruction.h": "33985cb7580db5c2",
"eden/shader_recompiler/frontend/ampere/lower_to_maxwell.h": "9f799680e5d681db",
"eden/shader_recompiler/frontend/ampere/lower_to_maxwell_regmap.h": "0fe477ec01307623",
"eden/shader_recompiler/frontend/ampere/program_address_map.h": "ef55da906829bbdb",
"eden/shader_recompiler/frontend/ampere/program_capture.h": "1fdd785fdd95cf7b",
"eden/shader_recompiler/frontend/ampere/program_override.h": "e3edf058fc879389",
"eden/shader_recompiler/frontend/ampere/register_pressure.h": "ffe3bd02a0303e91",
"eden/shader_recompiler/frontend/ir/abstract_syntax_list.h": "fef6028481d255ad",
"eden/shader_recompiler/frontend/ir/attribute.h": "397af914edcfcb41",
"eden/shader_recompiler/frontend/ir/basic_block.cpp": "ec1e1fa114f5f980",
"eden/shader_recompiler/frontend/ir/basic_block.h": "3cbd89d3fdff59fc",
"eden/shader_recompiler/frontend/ir/breadth_first_search.h": "3a471c3e0e132c1c",
"eden/shader_recompiler/frontend/ir/condition.cpp": "defd0599c6b93265",
"eden/shader_recompiler/frontend/ir/condition.h": "5921a88aa1f6020a",
"eden/shader_recompiler/frontend/ir/flow_test.h": "2c75cefea47a8f2b",
"eden/shader_recompiler/frontend/ir/ir_emitter.cpp": "da5c842a4b0cb452",
"eden/shader_recompiler/frontend/ir/ir_emitter.h": "87d12695ce52ac4e",
"eden/shader_recompiler/frontend/ir/microinstruction.cpp": "f8c6e0990e8cde9e",
"eden/shader_recompiler/frontend/ir/modifiers.h": "d23d8e54ee6e5f8c",
"eden/shader_recompiler/frontend/ir/opcodes.cpp": "e7b1df8bbd79e9c9",
"eden/shader_recompiler/frontend/ir/opcodes.h": "8422b96ab5365593",
"eden/shader_recompiler/frontend/ir/opcodes.inc": "86cd7c79963a4a43",
"eden/shader_recompiler/frontend/ir/patch.cpp": "ba0c2f74449791ae",
"eden/shader_recompiler/frontend/ir/patch.h": "47dd1e9d74cdab48",
"eden/shader_recompiler/frontend/ir/post_order.cpp": "3f8daf5fb2d59d24",
"eden/shader_recompiler/backend/spirv/spirv_emit_context.cpp": "612bf46e61c60792",
"eden/shader_recompiler/backend/spirv/spirv_emit_context.h": "ef535fc64acdd7df",
"eden/shader_recompiler/environment.h": "0d57ed5dc6a9954f",
"eden/shader_recompiler/exception.h": "24032722c4db4c03",
"eden/shader_recompiler/frontend/ampere/geometry_exit.h": "6ecbf5002380347c",
"eden/shader_recompiler/frontend/ampere/instruction.h": "a82af099c8f31efc",
"eden/shader_recompiler/frontend/ampere/lower_to_maxwell.h": "e8e0d478acbfc432",
"eden/shader_recompiler/frontend/ampere/lower_to_maxwell_regmap.h": "61cc80ed51d30d0e",
"eden/shader_recompiler/frontend/ampere/program_address_map.h": "9ebe48e8c8bdc239",
"eden/shader_recompiler/frontend/ampere/program_capture.h": "91aecee394d6748a",
"eden/shader_recompiler/frontend/ampere/program_override.h": "a18163514e1b96ef",
"eden/shader_recompiler/frontend/ampere/register_pressure.h": "26b9c1cf727986f4",
"eden/shader_recompiler/frontend/ir/abstract_syntax_list.h": "014cc2e34c923490",
"eden/shader_recompiler/frontend/ir/attribute.h": "17721de4f3d0871e",
"eden/shader_recompiler/frontend/ir/basic_block.cpp": "ec71e41c955f3130",
"eden/shader_recompiler/frontend/ir/basic_block.h": "51ea5d2ceb48335d",
"eden/shader_recompiler/frontend/ir/breadth_first_search.h": "dcc6e6fdca370d64",
"eden/shader_recompiler/frontend/ir/condition.cpp": "ae46703214cc1f12",
"eden/shader_recompiler/frontend/ir/condition.h": "fa6e6b55cb44127a",
"eden/shader_recompiler/frontend/ir/flow_test.h": "89e628c85ef2fa04",
"eden/shader_recompiler/frontend/ir/ir_emitter.cpp": "a13703bb3eb4ec91",
"eden/shader_recompiler/frontend/ir/ir_emitter.h": "25c9066c16956cc6",
"eden/shader_recompiler/frontend/ir/microinstruction.cpp": "b63715aecbecdac8",
"eden/shader_recompiler/frontend/ir/modifiers.h": "8d31e55840e0b4fa",
"eden/shader_recompiler/frontend/ir/opcodes.cpp": "744146bd26e4c792",
"eden/shader_recompiler/frontend/ir/opcodes.h": "b7b38dbfc9b73d54",
"eden/shader_recompiler/frontend/ir/opcodes.inc": "364fb553ff2f7489",
"eden/shader_recompiler/frontend/ir/patch.cpp": "cc5c9e010282fd07",
"eden/shader_recompiler/frontend/ir/patch.h": "708dd9bba2bcb0ec",
"eden/shader_recompiler/frontend/ir/post_order.cpp": "34a592ae5a7b1106",
"eden/shader_recompiler/frontend/ir/post_order.h": "9c691001fec7da4b",
"eden/shader_recompiler/frontend/ir/pred.h": "ddd5ffdc860bbb5a",
"eden/shader_recompiler/frontend/ir/program.cpp": "7a76542a00bac4f4",
"eden/shader_recompiler/frontend/ir/program.h": "092d88f2e4f08710",
"eden/shader_recompiler/frontend/ir/reg.h": "a2787047e15339d4",
"eden/shader_recompiler/frontend/ir/type.cpp": "aad38fae6ee5e677",
"eden/shader_recompiler/frontend/ir/type.h": "5f4002969424a081",
"eden/shader_recompiler/frontend/ir/value.cpp": "b84d9bca7d70253f",
"eden/shader_recompiler/frontend/ir/value.h": "9e6cc7675b9807c2",
"eden/shader_recompiler/frontend/maxwell/control_flow.cpp": "5fbbacf381dd68ab",
"eden/shader_recompiler/frontend/maxwell/control_flow.h": "4bb4e7231728149b",
"eden/shader_recompiler/frontend/maxwell/decode.cpp": "d7d5e9574987beed",
"eden/shader_recompiler/frontend/ir/pred.h": "dcb82ba0acc1605a",
"eden/shader_recompiler/frontend/ir/program.cpp": "b1943f6c09d73b57",
"eden/shader_recompiler/frontend/ir/program.h": "2f6250bbff0d8857",
"eden/shader_recompiler/frontend/ir/reg.h": "80a78c7760dc785b",
"eden/shader_recompiler/frontend/ir/type.cpp": "3512b1228943350a",
"eden/shader_recompiler/frontend/ir/type.h": "2adb4312e8c5527e",
"eden/shader_recompiler/frontend/ir/value.cpp": "d07643ac27b55c4d",
"eden/shader_recompiler/frontend/ir/value.h": "bab4f5df066cf4b7",
"eden/shader_recompiler/frontend/maxwell/control_flow.cpp": "0d4ffe69b35b1882",
"eden/shader_recompiler/frontend/maxwell/control_flow.h": "604dcc839a6b26b8",
"eden/shader_recompiler/frontend/maxwell/decode.cpp": "453b48cb4ae07fe2",
"eden/shader_recompiler/frontend/maxwell/decode.h": "ed24c1d16f77e1c0",
"eden/shader_recompiler/frontend/maxwell/indirect_branch_table_track.cpp": "2078e53ec55aa11e",
"eden/shader_recompiler/frontend/maxwell/indirect_branch_table_track.h": "842653f3083d7a4e",
"eden/shader_recompiler/frontend/maxwell/instruction.h": "d9a0d26ac7484961",
"eden/shader_recompiler/frontend/maxwell/location.h": "5ae9f65be2b55d34",
"eden/shader_recompiler/frontend/maxwell/maxwell.inc": "e93d6093764c7d51",
"eden/shader_recompiler/frontend/maxwell/opcodes.cpp": "319f6870a68fcf9a",
"eden/shader_recompiler/frontend/maxwell/opcodes.h": "a659c1db762bba11",
"eden/shader_recompiler/frontend/maxwell/structured_control_flow.cpp": "82b6533eeafff284",
"eden/shader_recompiler/frontend/maxwell/structured_control_flow.h": "ecc982366dd67163",
"eden/shader_recompiler/frontend/maxwell/translate/impl/atomic_operations_global_memory.cpp": "e2a304ff96e3d186",
"eden/shader_recompiler/frontend/maxwell/translate/impl/atomic_operations_shared_memory.cpp": "5886c578f8667874",
"eden/shader_recompiler/frontend/maxwell/translate/impl/attribute_memory_to_physical.cpp": "58c4dca102ad0f78",
"eden/shader_recompiler/frontend/maxwell/translate/impl/barrier_operations.cpp": "3f61bc9eded7f05a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/bitfield_extract.cpp": "c585607233a49be6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/bitfield_insert.cpp": "410327bcb364c1c8",
"eden/shader_recompiler/frontend/maxwell/translate/impl/branch_indirect.cpp": "7a00033cd0ba8d6d",
"eden/shader_recompiler/frontend/maxwell/translate/impl/common_encoding.h": "b8716913b2c6a590",
"eden/shader_recompiler/frontend/maxwell/translate/impl/common_funcs.cpp": "e327c1d28d71a31d",
"eden/shader_recompiler/frontend/maxwell/translate/impl/common_funcs.h": "048536ca8df9ee98",
"eden/shader_recompiler/frontend/maxwell/translate/impl/condition_code_set.cpp": "07f1f6de769c7bc4",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_add.cpp": "980f6e474c4fde88",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_compare_and_set.cpp": "2c3b1675b057def0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_fused_multiply_add.cpp": "8d58eee09eadc422",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_min_max.cpp": "5fa04d3a1fd4c97b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_multiply.cpp": "c53e962d369d4dfa",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_set_predicate.cpp": "3a846d52a3e7b228",
"eden/shader_recompiler/frontend/maxwell/translate/impl/exit_program.cpp": "5bc0b16a89496e17",
"eden/shader_recompiler/frontend/maxwell/translate/impl/find_leading_one.cpp": "cba019d1a31e6b65",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_add.cpp": "fa5f5ed146644c6b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_compare.cpp": "4a8a2d4c23174b3e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_compare_and_set.cpp": "74227337acc289a0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_floating_point.cpp": "26c2f481b6554e55",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp": "b107fc4879ae061a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_fused_multiply_add.cpp": "d7a79b111a829563",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_min_max.cpp": "9016345350f2a855",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_multi_function.cpp": "5ea5d8661c33df40",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_multiply.cpp": "8dde13bf3c46a358",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_range_reduction.cpp": "ff899b923022d074",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_set_predicate.cpp": "a5e48e78f951fcbf",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_swizzled_add.cpp": "8c2c4fa86a2cab40",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_add.cpp": "1f5d42e4875a25e3",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_fused_multiply_add.cpp": "0cd7b4f55b90ac92",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_helper.cpp": "604a5fa19d2377db",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_helper.h": "31b00138ca98c816",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_multiply.cpp": "1fa5f1b1de8e7ea8",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_set.cpp": "b3d612cc9dcb0b5d",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_set_predicate.cpp": "f95311c2b7ca80d6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/impl.cpp": "e27623569c72d93b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/impl.h": "4e9fa5a9b0754de7",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_add.cpp": "12f1452d77a0b8a8",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_add_three_input.cpp": "b2437c5405d96d0a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_compare.cpp": "edc5444d4cce70ac",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_compare_and_set.cpp": "9c2b51d25ee5706b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_floating_point_conversion.cpp": "40119cf8095471af",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_funnel_shift.cpp": "1f8ae764564f22c0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_minimum_maximum.cpp": "89ad27b7f07fad9e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_popcount.cpp": "699a2ddd9534a1c8",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_scaled_add.cpp": "be8a930e153a91f0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_set_predicate.cpp": "13867b1663c1563b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_shift_left.cpp": "f0e29e1298bec1c2",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_shift_right.cpp": "31b1efbc04d548a0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_short_multiply_add.cpp": "ee85aca3410afd22",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_to_integer_conversion.cpp": "64a6f2dbd600784b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/internal_stage_buffer_entry_read.cpp": "bf2e66fddd46accc",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_constant.cpp": "d8d5dc080cc19929",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_constant.h": "599c55d2ba4cadec",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_effective_address.cpp": "e8035bfd59364a7f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_store_attribute.cpp": "943968cc858deef9",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_store_local_shared.cpp": "9d3e8673fa45f5da",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_store_memory.cpp": "2189e38111a9836a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/logic_operation.cpp": "098484216a99c56f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/logic_operation_three_input.cpp": "1fcbf762c78c492d",
"eden/shader_recompiler/frontend/maxwell/indirect_branch_table_track.cpp": "0486a7913ae953fe",
"eden/shader_recompiler/frontend/maxwell/indirect_branch_table_track.h": "fb9a8d73c249590c",
"eden/shader_recompiler/frontend/maxwell/instruction.h": "6734f8ad13c8db1d",
"eden/shader_recompiler/frontend/maxwell/location.h": "bd45d6028ab3f974",
"eden/shader_recompiler/frontend/maxwell/maxwell.inc": "9409cb366efa62de",
"eden/shader_recompiler/frontend/maxwell/opcodes.cpp": "6a4169aceceb0c7e",
"eden/shader_recompiler/frontend/maxwell/opcodes.h": "6a5ace68dfa4a010",
"eden/shader_recompiler/frontend/maxwell/structured_control_flow.cpp": "992647e407a00736",
"eden/shader_recompiler/frontend/maxwell/structured_control_flow.h": "74efe41d7eceb75a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/atomic_operations_global_memory.cpp": "8da6be1667446a41",
"eden/shader_recompiler/frontend/maxwell/translate/impl/atomic_operations_shared_memory.cpp": "d5dc4abda4eca1e5",
"eden/shader_recompiler/frontend/maxwell/translate/impl/attribute_memory_to_physical.cpp": "443620d3a88c41bb",
"eden/shader_recompiler/frontend/maxwell/translate/impl/barrier_operations.cpp": "342bb2c1ead2178f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/bitfield_extract.cpp": "82780e6103011be5",
"eden/shader_recompiler/frontend/maxwell/translate/impl/bitfield_insert.cpp": "b5ed33b0e6f4fbf6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/branch_indirect.cpp": "dafa9ddc5e0e518e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/common_encoding.h": "a8419eddc015ab8a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/common_funcs.cpp": "13e184b36e1f2002",
"eden/shader_recompiler/frontend/maxwell/translate/impl/common_funcs.h": "a5256ee2fcc61dd3",
"eden/shader_recompiler/frontend/maxwell/translate/impl/condition_code_set.cpp": "c6ba8bd557e466f1",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_add.cpp": "8ab6cff13f656b73",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_compare_and_set.cpp": "dbd0717531c57c8b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_fused_multiply_add.cpp": "f99b7d75c5fb2a60",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_min_max.cpp": "70fdafda63d18d8b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_multiply.cpp": "4ee179ef0bd8f7da",
"eden/shader_recompiler/frontend/maxwell/translate/impl/double_set_predicate.cpp": "208e3a66e9d1f4a1",
"eden/shader_recompiler/frontend/maxwell/translate/impl/exit_program.cpp": "8e22c0ef4e499cbe",
"eden/shader_recompiler/frontend/maxwell/translate/impl/find_leading_one.cpp": "e62dced8275183e6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_add.cpp": "0a61499c8beaff5a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_compare.cpp": "23457cbfc2213ee5",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_compare_and_set.cpp": "f50d8639cc687bcb",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_floating_point.cpp": "0d74e0658e07c353",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_conversion_integer.cpp": "c59bf93acb240893",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_fused_multiply_add.cpp": "519f03afcf30d36f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_min_max.cpp": "82eccc8733f7c227",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_multi_function.cpp": "ad4c628cdf818d2b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_multiply.cpp": "fb4a10d26cdbb996",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_range_reduction.cpp": "882da881b50e54a3",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_set_predicate.cpp": "ad37e380177527f6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/floating_point_swizzled_add.cpp": "e5293a845a9395f2",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_add.cpp": "b24ea0f6401446bb",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_fused_multiply_add.cpp": "2fd4e7a251b17159",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_helper.cpp": "4bd4d9c46be4d40e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_helper.h": "4f076f7630c0fe81",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_multiply.cpp": "0e354ee5f7a6ef82",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_set.cpp": "eedf5ef067947fdf",
"eden/shader_recompiler/frontend/maxwell/translate/impl/half_floating_point_set_predicate.cpp": "ec63b0ec483cae7a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/impl.cpp": "cd8b89cac72f64b9",
"eden/shader_recompiler/frontend/maxwell/translate/impl/impl.h": "aee53c5d76b413ff",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_add.cpp": "03437345da18b1e7",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_add_three_input.cpp": "526c6eaeae733f8c",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_compare.cpp": "0bfc67266e33d71b",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_compare_and_set.cpp": "d8ba59c1ec558467",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_floating_point_conversion.cpp": "e2e35a4c571107fb",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_funnel_shift.cpp": "b8bc83de44e7cbd7",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_minimum_maximum.cpp": "6ec4fc29821c6357",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_popcount.cpp": "33931f37588361da",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_scaled_add.cpp": "bb71f45ec549e210",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_set_predicate.cpp": "06e26110cede79ec",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_shift_left.cpp": "66481ad2749c1ff6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_shift_right.cpp": "5b2910c2fb313829",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_short_multiply_add.cpp": "646b2662bff38324",
"eden/shader_recompiler/frontend/maxwell/translate/impl/integer_to_integer_conversion.cpp": "a54b746643776ea1",
"eden/shader_recompiler/frontend/maxwell/translate/impl/internal_stage_buffer_entry_read.cpp": "5d9d35f1a50db072",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_constant.cpp": "52c98a2e6169cfac",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_constant.h": "661258189dc5da56",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_effective_address.cpp": "c578fa7dfd3ccccf",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_store_attribute.cpp": "93475c336a9c21de",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_store_local_shared.cpp": "5d0a2f85e32e1075",
"eden/shader_recompiler/frontend/maxwell/translate/impl/load_store_memory.cpp": "df1761064b605208",
"eden/shader_recompiler/frontend/maxwell/translate/impl/logic_operation.cpp": "b73f6ec03ba7fccd",
"eden/shader_recompiler/frontend/maxwell/translate/impl/logic_operation_three_input.cpp": "f827fdd3e629eb0f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/logic_operation_three_input_lut3.py": "3e0d579a0d33a156",
"eden/shader_recompiler/frontend/maxwell/translate/impl/matrix_multiply_nx2.cpp": "7be63c09fc62e2ee",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_predicate_to_register.cpp": "ac67eef1bbca895f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_register.cpp": "cdb22778ecd326ff",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_register_to_predicate.cpp": "44529a40bfac9584",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_special_register.cpp": "6d33935e3f3ab580",
"eden/shader_recompiler/frontend/maxwell/translate/impl/not_implemented.cpp": "070ca57c5629c987",
"eden/shader_recompiler/frontend/maxwell/translate/impl/output_geometry.cpp": "20a8670a4cee695f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/pixel_load.cpp": "6c23cd9bc5da6e8c",
"eden/shader_recompiler/frontend/maxwell/translate/impl/predicate_set_predicate.cpp": "146602c84fde4fd9",
"eden/shader_recompiler/frontend/maxwell/translate/impl/predicate_set_register.cpp": "4b2eef64209d61ff",
"eden/shader_recompiler/frontend/maxwell/translate/impl/register_map_nx2.cpp": "9a7dbb7c946b8cf0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/select_source_with_predicate.cpp": "b829843ccc946c31",
"eden/shader_recompiler/frontend/maxwell/translate/impl/surface_atomic_operations.cpp": "ffea78763c263373",
"eden/shader_recompiler/frontend/maxwell/translate/impl/surface_load_store.cpp": "fb619d131fdac1d0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_fetch.cpp": "9b1c41b38581d0df",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_fetch_swizzled.cpp": "250555c785599402",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_gather.cpp": "399c7061ad2fc242",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_gather_swizzled.cpp": "c0fab8626aa5c508",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_gradient.cpp": "21f33baf3bc01e95",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_load.cpp": "0636b2825a5694c7",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_load_swizzled.cpp": "6ae3f31e146fc84a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_mipmap_level.cpp": "ade85c7e167ca673",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_query.cpp": "e2ca9633884220ae",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_helper.cpp": "664a30cbff9a0f2f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_helper.h": "3943eec4bf36ca94",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_minimum_maximum.cpp": "0f1861a48a7be844",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_multiply_add.cpp": "6a4da8e739111ad2",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_set_predicate.cpp": "2f739613e6c6fa2e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/vote.cpp": "b72a6ff6f13e7d68",
"eden/shader_recompiler/frontend/maxwell/translate/impl/warp_shuffle.cpp": "2fec4de48edcc3b2",
"eden/shader_recompiler/frontend/maxwell/translate/translate.cpp": "75cc18a9e12d4591",
"eden/shader_recompiler/frontend/maxwell/translate/impl/matrix_multiply_nx2.cpp": "34b5aaada7a0c6ac",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_predicate_to_register.cpp": "723356624bbde030",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_register.cpp": "c4ffed9bab3d4680",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_register_to_predicate.cpp": "9e8d2bea6dad00b7",
"eden/shader_recompiler/frontend/maxwell/translate/impl/move_special_register.cpp": "4fd89c5887890b0a",
"eden/shader_recompiler/frontend/maxwell/translate/impl/not_implemented.cpp": "6d4b7774293cdf87",
"eden/shader_recompiler/frontend/maxwell/translate/impl/output_geometry.cpp": "04bea0f922b38648",
"eden/shader_recompiler/frontend/maxwell/translate/impl/pixel_load.cpp": "8ed22aedbe6cad0f",
"eden/shader_recompiler/frontend/maxwell/translate/impl/predicate_set_predicate.cpp": "cc4c757c39ff58cf",
"eden/shader_recompiler/frontend/maxwell/translate/impl/predicate_set_register.cpp": "3ccbdb147a5f43a5",
"eden/shader_recompiler/frontend/maxwell/translate/impl/register_map_nx2.cpp": "e74d6da80301e9a1",
"eden/shader_recompiler/frontend/maxwell/translate/impl/select_source_with_predicate.cpp": "30c4c93c8d2fae5e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/surface_atomic_operations.cpp": "cc841f5562e3be90",
"eden/shader_recompiler/frontend/maxwell/translate/impl/surface_load_store.cpp": "832081120b3f64a5",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_fetch.cpp": "c5879bcecfa6f925",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_fetch_swizzled.cpp": "70bd0948cbb3c5fa",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_gather.cpp": "6810e15dc7ef03a4",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_gather_swizzled.cpp": "7208813f5a8c88a9",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_gradient.cpp": "a5d568ecf37c6797",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_load.cpp": "562c5f59774e6cb0",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_load_swizzled.cpp": "54f04be5cd59da64",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_mipmap_level.cpp": "b2d739f7c35db6f2",
"eden/shader_recompiler/frontend/maxwell/translate/impl/texture_query.cpp": "ce4ae1eb5ebbbc4e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_helper.cpp": "7bbff6587f8ee69e",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_helper.h": "05994619ee364406",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_minimum_maximum.cpp": "1b453ad4d7513ce6",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_multiply_add.cpp": "435c68640f8a32cf",
"eden/shader_recompiler/frontend/maxwell/translate/impl/video_set_predicate.cpp": "e0d87b0de49f4ed4",
"eden/shader_recompiler/frontend/maxwell/translate/impl/vote.cpp": "aa328e587a455803",
"eden/shader_recompiler/frontend/maxwell/translate/impl/warp_shuffle.cpp": "6d7ddd33f7a99679",
"eden/shader_recompiler/frontend/maxwell/translate/translate.cpp": "1b144492f8d0cf9d",
"eden/shader_recompiler/frontend/maxwell/translate/translate.h": "afcde4ed57784602",
"eden/shader_recompiler/frontend/maxwell/translate_program.cpp": "3a2e32b5456593eb",
"eden/shader_recompiler/frontend/maxwell/translate_program.h": "ceb2ec502ae3c225",
"eden/shader_recompiler/host_translate_info.h": "f407a356469f4201",
"eden/shader_recompiler/ir_opt/collect_shader_info_pass.cpp": "5e336b057eb3ef1d",
"eden/shader_recompiler/ir_opt/conditional_barrier_pass.cpp": "076e0ac28f2bf91d",
"eden/shader_recompiler/ir_opt/constant_propagation_pass.cpp": "86e60771cc2c1f67",
"eden/shader_recompiler/ir_opt/dead_code_elimination_pass.cpp": "475a169aa06527d2",
"eden/shader_recompiler/ir_opt/dual_vertex_pass.cpp": "f4fef4b0912c0bb9",
"eden/shader_recompiler/ir_opt/geometry_compaction_pass.cpp": "104921c870341f3c",
"eden/shader_recompiler/ir_opt/global_memory_to_storage_buffer_pass.cpp": "d56b968269f2c1fe",
"eden/shader_recompiler/ir_opt/identity_removal_pass.cpp": "2c0c7b5415416897",
"eden/shader_recompiler/ir_opt/layer_pass.cpp": "9f09c09a1aa34182",
"eden/shader_recompiler/ir_opt/lower_fp16_to_fp32.cpp": "8ad0c86b2b17f3ee",
"eden/shader_recompiler/ir_opt/lower_fp64_to_fp32.cpp": "a2772ec95b76e153",
"eden/shader_recompiler/ir_opt/lower_int64_to_int32.cpp": "c330525e9734b198",
"eden/shader_recompiler/ir_opt/oot_visual_workaround.h": "f17401a908d24575",
"eden/shader_recompiler/ir_opt/passes.h": "b98dbfa75d3a9f96",
"eden/shader_recompiler/ir_opt/position_pass.cpp": "c5dc8e0e8cc13607",
"eden/shader_recompiler/ir_opt/predicate_mask.h": "d581b3805110e641",
"eden/shader_recompiler/ir_opt/rescaling_pass.cpp": "887caa1aae84f47c",
"eden/shader_recompiler/ir_opt/ssa_rewrite_pass.cpp": "976122b6b8593660",
"eden/shader_recompiler/ir_opt/texture_pass.cpp": "0c6e8d25ff273914",
"eden/shader_recompiler/ir_opt/vendor_workaround_pass.cpp": "08ef34d84b4e457d",
"eden/shader_recompiler/ir_opt/verification_pass.cpp": "8c9a098dbe90a6af",
"eden/shader_recompiler/object_pool.h": "1f5715e1f064f39f",
"eden/shader_recompiler/profile.h": "17dd81c7ac6437e3",
"eden/shader_recompiler/program_header.h": "fb14e82dce78be2a",
"eden/shader_recompiler/runtime_info.h": "1a465aef19b1c378",
"eden/shader_recompiler/shader_info.h": "7aa8357521d61652",
"eden/shader_recompiler/stage.h": "7797bca3df1acd29",
"eden/shader_recompiler/varying_state.h": "ef18fb2b470636c1",
"eden/shader_recompiler/frontend/maxwell/translate_program.cpp": "152129fa4b57522b",
"eden/shader_recompiler/frontend/maxwell/translate_program.h": "7a10e39fea1bfac0",
"eden/shader_recompiler/host_translate_info.h": "a2f57739355f5bc5",
"eden/shader_recompiler/ir_opt/collect_shader_info_pass.cpp": "e3d2ad858c73047d",
"eden/shader_recompiler/ir_opt/conditional_barrier_pass.cpp": "ddbd91bc069c067a",
"eden/shader_recompiler/ir_opt/constant_propagation_pass.cpp": "f4ccc09b06a1789b",
"eden/shader_recompiler/ir_opt/dead_code_elimination_pass.cpp": "1e07576620ec4839",
"eden/shader_recompiler/ir_opt/dual_vertex_pass.cpp": "376369b3c76950b5",
"eden/shader_recompiler/ir_opt/geometry_compaction_pass.cpp": "a432886f156fc5f7",
"eden/shader_recompiler/ir_opt/global_memory_to_storage_buffer_pass.cpp": "db6a873402e29a78",
"eden/shader_recompiler/ir_opt/identity_removal_pass.cpp": "55f76b1987497e34",
"eden/shader_recompiler/ir_opt/layer_pass.cpp": "c650d49490086d78",
"eden/shader_recompiler/ir_opt/lower_fp16_to_fp32.cpp": "d4eaef61cb5aad42",
"eden/shader_recompiler/ir_opt/lower_fp64_to_fp32.cpp": "e44174355a0618ce",
"eden/shader_recompiler/ir_opt/lower_int64_to_int32.cpp": "7b34c8f759a6ffee",
"eden/shader_recompiler/ir_opt/oot_visual_workaround.h": "4473aa480af4da7e",
"eden/shader_recompiler/ir_opt/passes.h": "bec1a14de9d2cf44",
"eden/shader_recompiler/ir_opt/position_pass.cpp": "f15a644ff0b6c05e",
"eden/shader_recompiler/ir_opt/predicate_mask.h": "dec09ce80c18f801",
"eden/shader_recompiler/ir_opt/rescaling_pass.cpp": "4dd3a3816cae9e89",
"eden/shader_recompiler/ir_opt/ssa_rewrite_pass.cpp": "75c49fbddd961cf2",
"eden/shader_recompiler/ir_opt/texture_pass.cpp": "f927bb9006b928cb",
"eden/shader_recompiler/ir_opt/vendor_workaround_pass.cpp": "38f31aa9a92cf4c6",
"eden/shader_recompiler/ir_opt/verification_pass.cpp": "baaa58f3eb4ea73b",
"eden/shader_recompiler/object_pool.h": "ae950ea5b7e69f33",
"eden/shader_recompiler/profile.h": "d71399bc5c462942",
"eden/shader_recompiler/program_header.h": "9a06e37f22379437",
"eden/shader_recompiler/runtime_info.h": "1caf98468f6317fa",
"eden/shader_recompiler/shader_info.h": "4e2f6de3e3259b98",
"eden/shader_recompiler/stage.h": "c4ecd6532dfc0ddb",
"eden/shader_recompiler/varying_state.h": "6b0e270d7bc1d64b",
"sirit/LICENSE": "4c665f87b5dc2e7d",
"sirit/LICENSE.txt": "31a3d460bb3c7d98",
"sirit/include/sirit/sirit.h": "9038f4718f8d61e0",
"sirit/include/sirit/sirit.h": "bfe8609226ce98cc",
"sirit/src/.gitignore": "44fc6f5c57f35fae",
"sirit/src/CMakeLists.txt": "2284b3ca11d6cd27",
"sirit/src/common_types.h": "6377fdaa68cafd82",
"sirit/src/instructions/annotation.cpp": "70891bb1190db7e9",
"sirit/src/instructions/arithmetic.cpp": "bd798514516849b9",
"sirit/src/instructions/atomic.cpp": "5ce245873abb2904",
"sirit/src/instructions/barrier.cpp": "caf9e940084a3a7d",
"sirit/src/instructions/bit.cpp": "b247e5b7f41c66fa",
"sirit/src/instructions/constant.cpp": "68c473609e34a545",
"sirit/src/instructions/conversion.cpp": "0ff5ab1ecb557dfa",
"sirit/src/instructions/debug.cpp": "d582bf4f628326e1",
"sirit/src/instructions/derivatives.cpp": "d6551969a26dc1ef",
"sirit/src/instructions/extension.cpp": "b8cb642618ba2344",
"sirit/src/instructions/flow.cpp": "579314ad8d9367f5",
"sirit/src/instructions/function.cpp": "de2eeec04e0e41c0",
"sirit/src/instructions/group.cpp": "0cc6f6c42b26ed97",
"sirit/src/instructions/image.cpp": "28a8aaf18e3003e2",
"sirit/src/instructions/logical.cpp": "0afbc36d20389553",
"sirit/src/instructions/memory.cpp": "32af46d9f9736374",
"sirit/src/instructions/misc.cpp": "d8c8385ad5c60395",
"sirit/src/instructions/type.cpp": "11003c08097c1af7",
"sirit/src/sirit.cpp": "d7652fa5449680f1",
"sirit/src/instructions/annotation.cpp": "cb2f23fa82b30268",
"sirit/src/instructions/arithmetic.cpp": "c336d0b8c8dfa913",
"sirit/src/instructions/atomic.cpp": "45cd8c52689dde35",
"sirit/src/instructions/barrier.cpp": "ad91ac101443ce74",
"sirit/src/instructions/bit.cpp": "9bb33b15fb3645be",
"sirit/src/instructions/constant.cpp": "0572f076d19b18bc",
"sirit/src/instructions/conversion.cpp": "19ea6556f33af204",
"sirit/src/instructions/debug.cpp": "c58c10f1c91db722",
"sirit/src/instructions/derivatives.cpp": "ef60e184aafe6fa3",
"sirit/src/instructions/extension.cpp": "76695ecc45654b37",
"sirit/src/instructions/flow.cpp": "d913d10fae8bce45",
"sirit/src/instructions/function.cpp": "a82c9a8a116ca92f",
"sirit/src/instructions/group.cpp": "5fc7e94d746a2763",
"sirit/src/instructions/image.cpp": "4673c8f2888efbb1",
"sirit/src/instructions/logical.cpp": "29f3aac38f1eabb7",
"sirit/src/instructions/memory.cpp": "ea088cddabeb7f91",
"sirit/src/instructions/misc.cpp": "119ce3eed3fc2c4a",
"sirit/src/instructions/type.cpp": "c0e81f8602564b9d",
"sirit/src/sirit.cpp": "f8302a9d90b6fdbf",
"sirit/src/stream.cpp": "da39a3ee5e6b4b0d",
"sirit/src/stream.h": "de9cf8b6e1cae0c5",
"vk_bank.cpp": "65f8d91316a24552",
"vk_shader.cpp": "b04fcd697eaa44c6",
"vk_state.h": "b53ea61ecbbd77cf"
"sirit/src/stream.h": "f6ae4681e54dfb4c",
"vk_bank.cpp": "91d81489349a0dcf",
"vk_shader.cpp": "d5dd7cf741a9e62d",
"vk_state.h": "43330d70648502e4"
},
"release": "v0.5.1",
"stamp": "f6b970031161afbe"

64
nx2/reshade_fx.py Normal file
View File

@@ -0,0 +1,64 @@
"""(Triforce) The ReShade FX compiler in the Vulkan back end (the Graphics tab's ReShade preset row, gpu/vk/reshade): its jobs
for nx2/build.py, and the pinned ReShade preprocessor adapted to resolve includes through gpu/vk/reshade/fx_files.cpp's
confined reader."""
from pathlib import Path
def build_jobs(cxx, root, generated, objects, own_flags, vendor_flags, backend_headers, *, windows):
"""Keep the FX compiler's flags and dependencies away from the rest of the renderer: ReShade's own files (third_party/
reshade_fx/source, unmodified, and the adapted preprocessor made in the build's gen folder) with the renderer's flags but
not its profile (vendor_flags), its own files under gpu/vk/reshade with them (own_flags)."""
root, generated, objects = Path(root), Path(generated), Path(objects)
fx_source = root / "third_party" / "reshade_fx" / "source"
bridge = root / "gpu" / "vk" / "reshade"
images = root / "third_party" / "stb_image"
include = [f"-I{fx_source}", f"-I{bridge}"]
headers = b"".join(file.read_bytes() for file in sorted(fx_source.glob("*.hpp")))
headers += (fx_source / "effect_symbol_table_intrinsics.inl").read_bytes()
adapted = write_preprocessor(fx_source, generated / "reshade_preprocessor.cpp")
flags = vendor_flags + include + ["-fno-char8_t"] + (["-include", "share.h"] if windows else [])
jobs = []
for name in ("codegen_spirv", "expression", "lexer", "parser_exp", "parser_stmt", "preprocessor", "symbol_table"):
source = adapted if name == "preprocessor" else fx_source / f"effect_{name}.cpp"
# Optimizing the generated intrinsic table dominates the build. FX compilation runs on a worker.
options = flags + (["-O0"] if name == "symbol_table" else [])
jobs.append((cxx, str(source), str(objects / f"vk_reshade_vendor_{name}.o"), options,
headers))
for name in ("compile", "files", "pipeline_cache", "preset", "runtime", "texture"):
options, dependencies = own_flags + include, backend_headers + headers
if name == "texture":
options += [f"-I{images}"]
dependencies += (images / "stb_image.h").read_bytes()
jobs.append((cxx, str(bridge / f"fx_{name}.cpp"), str(objects / f"vk_reshade_fx_{name}.o"), options, dependencies))
return jobs
def write_preprocessor(source, output):
source = Path(source) / "effect_preprocessor.cpp"
text = source.read_text(encoding="utf-8")
def replace(old, new):
nonlocal text
if text.count(old) != 1:
raise ValueError(f"Update the ReShade include adapter for {source}: {old[:80]}")
text = text.replace(old, new)
replace('#include "effect_preprocessor.hpp"', '#include "effect_preprocessor.hpp"\n#include "fx_files.h"')
start = text.index("\t// Read file contents into memory\n", text.index("static bool read_file("))
end = text.index("\t// Append a new line feed", start)
replace(text[start:end], "\tif (!tf::reshade::read_fx_file(path, file_data))\n\t\treturn false;\n\tfile_data.push_back('\\n');\n\n")
start = text.index("\tstd::filesystem::path file_name =", text.index("void reshadefx::preprocessor::parse_include()"))
end = text.index("\tconst std::string file_path_string", start)
replace(text[start:end], """\tconst auto file_name = std::filesystem::u8path(_token.literal_as_string);
\tconst auto file_path = tf::reshade::resolve_fx_include(
\t\tstd::filesystem::u8path(_output_location.source), file_name, _include_paths);
\tif (file_path.empty())
\t\treturn error(keyword_location, "could not open included file '" + _token.literal_as_string + '\\'');
""")
output = Path(output)
if not output.exists() or output.read_text(encoding="utf-8") != text:
output.write_text(text, encoding="utf-8")
return output

View File

@@ -72,7 +72,20 @@ MARK_NATIVE_64 = r"""extern uint8_t a64_dirty[A64_DIRTY_PAGES];
/* (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_DIRTY_AT(a) (((uint64_t)(a) >> 12) & (A64_DIRTY_PAGES - 1))
#ifdef A64_MARK_ONE /* (triforce, build.py RX_MARK_ONE=1: the first byte's page alone. The collection takes a mark as "this page
#if defined(A64_MARK_BITMAP)
/* ((Triforce) build.py RX_MARK_BITMAP=1, host/mark_bitmap.c) only a store that starts on a GPU page marks: a bit per page,
set by the host when a GPU mapping is made, and for the page before it too, so that a store crossing into a mapping from
the page before is caught by its first byte; read-only on the store path. The marks themselves are as without it */
extern uint8_t a64_gpu_pages[A64_DIRTY_PAGES / 8];
#define A64_GPU_PAGE(a) ((a64_gpu_pages[A64_DIRTY_AT(a) >> 3] >> (A64_DIRTY_AT(a) & 7)) & 1)
#ifdef A64_MARK_ONE
#define A64_MARK(a, n) (A64_GPU_PAGE(a) ? (void)__atomic_store_n(&a64_dirty[A64_DIRTY_AT(a)], 1, __ATOMIC_RELEASE) : (void)0)
#else
#define A64_MARK(a, n) (A64_GPU_PAGE(a) ? \
(void)(__atomic_store_n(&a64_dirty[A64_DIRTY_AT(a)], 1, __ATOMIC_RELEASE), \
__atomic_store_n(&a64_dirty[A64_DIRTY_AT((a) + (n) - 1)], 1, __ATOMIC_RELEASE)) : (void)0)
#endif
#elif defined(A64_MARK_ONE) /* (triforce, build.py RX_MARK_ONE=1: the first byte's page alone. The collection takes a mark as "this page
and the next", host/rx_backend.c collect_in: a store of up to 4 KB reaches no further) */
#define A64_MARK(a, n) (__atomic_store_n(&a64_dirty[A64_DIRTY_AT(a)], 1, __ATOMIC_RELEASE))
#else

406
nx2/split_giants.py Normal file
View File

@@ -0,0 +1,406 @@
"""Giant lifted functions cut at their labels into piece functions and a dispatch loop, for the compile (nx2/build.py).
Why: clang's time on one function grows faster than its size (Machine LICM, register allocation, the IR passes on one flow
graph of tens of thousands of blocks): the lift's chunks of ~2 MB functions (code_023*/024*/025*) took ~30% of a first
build's lifted compile time at 4-7x the seconds per MB of ordinary chunks. The lifter's own cut (a64_lift.split_large: an
extra entry where no branch crosses) cannot cut these: each is one big loop nest.
Why it is exact: a lifted function keeps all guest state in the context (c->x[], c->vreg[], NZCV, FPCR/FPSR) and in guest
memory; each guest instruction is one top-level statement whose C locals live inside its own block, and labels are written
only at the top level (third_party/a64-kit/lift/a64_lift.py emit_function). So before any top-level label nothing but *c
and memory is live, and the body can be cut there:
- a piece `static uintptr_t s_<addr>_<n>(Ctx *c, uintptr_t k)` starts at the label whose id is k (or at its first
statement), runs its statements as written, and returns what comes next: 0 (the guest returned), a label id (a goto
into another piece, with its interrupt poll kept), or a tail-call id (a guest branch into another function);
- f_<addr> keeps its name and ABI: a loop calls the piece that owns k; a tail-call id leaves through TAILCALL(f_y),
exactly as before (musttail: the guest call depth is unchanged).
- direct (the default, HOOKSHOT_SPLIT_DIRECT=0 turns it off; macros()): where the compiler has preserve_none and
musttail, a goto into another piece is a jump straight to it, `musttail return s_<addr>_<m>(c, id, locals...)`,
and only 0 and tail-call ids come back to f_'s loop. A hop then costs a jump and the label switch at the piece's
head, where the loop costs a return, a switch, a call and the locals stored and loaded.
Interrupt polls go with their gotos (every cycle through the loop holds one of the function's own back edges); page-mark
groups end at labels (a64_lift.mark_groups), so no mark moves across a cut; a setjmp-wrapped call is one statement.
Guest locals (A64_LOCAL_REGS/FLAGS): the kit writes a function's register and flag locals as the
body's first lines (`uint64_t x8_ = c->x[8], ...;` then `uint8_t fn_ = c->n, ...;`), and they live across its labels:
a local is written back to the context only at the kit's marks (calls, returns, tail calls), so at a label it may be
newer than the context. Such a function is cut all the same: f_<addr> keeps the locals in a struct of its own
(s_<addr>_l, loaded from the context as the whole function loads them), each piece takes a pointer to it, loads the
locals from it when it starts and stores them back to it before a goto into another piece; a guest return or tail call
stores nothing more (the kit's mark before it wrote the context, as in the whole function). The context is written
exactly where the whole function writes it.
A function is left whole when any of this is not shown on its text: a top-level declaration other than those first
lines (a locals line after lift_fixes' entry goto too), a label inside a block, a goto to a label it lacks, a return
or computed goto of another shape, string or char literals.
Pieces are cut at labels after ~piece_bytes of C, preferring a cut that splits no short loop (a back edge spanning less
than 4 pieces: one hop per turn there would cost most); a long loop costs one hop per piece per turn, small against the
piece's own work.
"""
import collections
import re
HEAD = re.compile(r"^void (f_[0-9a-f]+)\(Ctx \*__restrict A64_NOESC c\) \{$")
BRACES = re.compile(r"[{}]")
HEAD_TEXT = re.compile(r"^void (f_[0-9a-f]+)\(Ctx \*__restrict A64_NOESC c\) \{\n", re.M)
LABEL = re.compile(r"^L_([0-9a-f]+):;")
GOTO = re.compile(r"\bgoto (L_[0-9a-f]+);")
TAIL = re.compile(r"\bTAILCALL\((\w+)\);")
RETURN_OK = re.compile(r"\breturn\b(?! \d+;)")
INNER_LABEL = re.compile(r"\bL_[0-9a-f]+\s*:(?!:)") # (a label anywhere but at the start of a top-level line)
ANY_GOTO = re.compile(r"\bgoto\b(?:\s+([A-Za-z_]\w*)\s*;)?") # (group 1 None: a computed goto or another shape)
TOP_LABEL = re.compile(r"L_[0-9a-f]+")
DECL = re.compile(r"^\s*(?:const\s+|static\s+|volatile\s+|unsigned\s+|signed\s+|register\s+)*"
r"(?:u?int(?:8|16|32|64)_t|u?intptr_t|int|unsigned|long|short|char|float|double|_Bool|bool|size_t|"
r"void\s*\*|Ctx|GuestContext)\b(?!\s*\))")
# (the kit's localize_regs: `uint64_t x8_ = c->x[8], x19_ = c->x[19];` and `uint8_t fn_ = c->n, ... fv_ = c->v;`)
LOCALS = (re.compile(r"^ uint64_t ((?:x\d+_ = c->x\[\d+\], )*x\d+_ = c->x\[\d+\]);$"),
re.compile(r"^ uint8_t ((?:f[nzcv]_ = c->[nzcv], )*f[nzcv]_ = c->[nzcv]);$"))
LOCAL = re.compile(r"(x(\d+)_|f([nzcv])_) = c->(?:x\[(\d+)\]|([nzcv]))")
PIECE_KB = 8 # (measured: 4-32 KB pieces all take a fraction of the whole function's time)
MIN_KB = 256 # (functions below this compile near-linearly: nothing to gain, a hop to pay)
class Refuse(Exception):
pass
def _braces(line, depth):
"""the block depth after a line (comments skipped); literals refuse: braces inside them are not counted"""
if "/" not in line and '"' not in line and "'" not in line: # (no comment, no literal: the braces alone, found in C)
for b in BRACES.findall(line):
depth += 1 if b == "{" else -1
if depth < 0:
raise Refuse("unbalanced braces")
return depth
i, n = 0, len(line)
while i < n:
ch = line[i]
if ch == "/" and line.startswith("/*", i):
j = line.find("*/", i + 2)
if j < 0:
raise Refuse("a comment over several lines")
i = j + 2
continue
if ch == "/" and line.startswith("//", i):
break
if ch == '"' or ch == "'":
raise Refuse("a string or char literal")
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth < 0:
raise Refuse("unbalanced braces")
i += 1
return depth
def _local_gotos(text):
"""A statement's gotos are to the function's own top-level labels (L_<hex>), or to a label of another name defined
inside this same statement, which stays whole in one piece (the fast float regions: `{ if (...) { ... goto
L_ff_<pc>; ... } <exact copy> L_ff_<pc>:; }`); anything else (a computed goto, a label elsewhere) refuses"""
for m in ANY_GOTO.finditer(text):
t = m.group(1)
if t is None:
raise Refuse("a goto of another shape")
if TOP_LABEL.fullmatch(t):
continue
if not re.search(r"(?<![\w.])%s\s*:(?!:)" % re.escape(t), text):
raise Refuse("a goto of another shape")
def items_of(body_lines):
"""The body as top-level items: (label, None) for each label, (None, text) for each statement (one or more lines)"""
items, cur, depth = [], [], 0
for ln in body_lines:
if depth == 0 and not cur:
m = LABEL.match(ln)
if m:
items.append(("L_" + m.group(1), None))
rest = ln[m.end():]
if rest.strip():
if _braces(rest, 0):
raise Refuse("a block opened after a label")
if INNER_LABEL.search(rest):
raise Refuse("a label inside a block")
_local_gotos(rest)
items.append((None, rest.lstrip()))
continue
if DECL.match(ln):
raise Refuse("a top-level declaration")
if "L_" in ln and INNER_LABEL.search(ln):
raise Refuse("a label inside a block")
cur.append(ln)
depth = _braces(ln, depth)
if depth == 0:
text = "\n".join(cur)
if "goto" in text:
_local_gotos(text)
items.append((None, text))
cur = []
if cur or depth:
raise Refuse("unbalanced body")
return items
def plan(items, piece, loop_max):
"""Indexes of the items where a piece starts: 0, then labels about `piece` bytes apart (up to 3x), choosing among
them the one that cuts the fewest back edges spanning at most loop_max bytes"""
n = len(items)
pos, size = {}, [0] * (n + 1)
for i, (lab, text) in enumerate(items):
size[i + 1] = size[i] + (len(text) + 1 if text is not None else len(lab) + 4)
if lab:
pos[lab] = i
diff = [0] * (n + 2)
for i, (lab, text) in enumerate(items):
if not text or "goto" not in text:
continue
for t in GOTO.findall(text):
if t not in pos:
raise Refuse("a goto to a label the function does not have")
j = pos[t]
if j <= i and size[i + 1] - size[j] <= loop_max:
diff[j + 1] += 1
diff[i + 1] -= 1
cross, run = [0] * (n + 1), 0
for m in range(n + 1):
run += diff[m]
cross[m] = run
cands = [m for m in range(1, n) if items[m][0]]
starts, last, k = [0], 0, 0
while True:
lo, hi = size[last] + piece, size[last] + 3 * piece
while k < len(cands) and size[cands[k]] < lo:
k += 1
if k >= len(cands) or size[n] - lo < piece // 2:
break
best, bk = None, k
j = k
while j < len(cands) and size[cands[j]] <= hi:
if best is None or cross[cands[j]] < best:
best, bk = cross[cands[j]], j
if best == 0:
break
j += 1
starts.append(cands[bk])
last = cands[bk]
k = bk + 1
return starts
def locals_of(body_lines):
"""(locals, the rest of the body): the guest locals the body's first lines declare, as [(C type, name, what loads
it)] in their order (registers, then flags), and the body after those lines"""
found, i = [], 0
for kind, rx in zip(("uint64_t", "uint8_t"), LOCALS):
m = rx.match(body_lines[i]) if i < len(body_lines) else None
if m:
for d in LOCAL.finditer(m.group(1)):
reg, flag = d.group(2), d.group(3)
if (reg or flag) != (d.group(4) or d.group(5)):
raise Refuse("a local loaded from another register")
found.append((kind, d.group(1), "c->x[%s]" % reg if reg else "c->" + flag))
i += 1
names = [n for _, n, _ in found]
if len(set(names)) != len(names):
raise Refuse("a local declared twice")
return found, body_lines[i:]
REG_T, FLAG_T = "uint64_t", "uint8_t"
DIRECT_IF = "#if __has_attribute(preserve_none) && __has_attribute(musttail)"
DIRECT_ARGS = 12 # (preserve_none's argument registers on x86-64, Windows and Linux alike; more go on the stack)
def macros(P, regs, flags, direct):
"""The five macros a function's pieces and dispatcher are written with (P: s_<addr>_):
CC the pieces' calling convention, ARGS their parameters, LOAD a piece's locals as it starts, HOP(K, F) a goto
into piece F at label id K, CALL(F) f_<addr> calling piece F at k.
The trampoline: a piece takes f_'s locals' struct (l), loads them from it and stores them back to it before
returning K to f_'s loop, which calls the piece that owns K.
Direct (when the compiler has preserve_none and musttail, and the locals fit in its argument registers): the pieces
jump to each other (musttail) with the locals as arguments in registers, the four flags in one (fl_, a byte each);
preserve_none keeps no register across the jump, so a hop stores and loads nothing"""
head = "Ctx *__restrict A64_NOESC c, uintptr_t k"
loc = bool(regs or flags)
tramp = ["#define %sCC" % P,
"#define %sARGS %s%s" % (P, head, ", %sl *__restrict A64_NOESC l" % P if loc else ""),
"#define %sLOAD %s" % (P, " ".join("%s %s;" % (t, ", ".join("%s = l->%s" % (n, n) for n in ns))
for t, ns in ((REG_T, regs), (FLAG_T, flags)) if ns)),
"#define %sHOP(K, F) do { %sreturn (K); } while (0)" % (P, "".join("l->%s = %s; " % (n, n) for n in regs + flags)),
"#define %sCALL(F) F(c, k%s)" % (P, ", &l" if loc else "")]
if not direct or 2 + len(regs) + bool(flags) > DIRECT_ARGS:
return "\n".join(tramp)
def pack(pre):
return " | ".join("(uint32_t)%s%s << %d" % (pre, n, 8 * i) for i, n in enumerate(flags))
unpack = "uint8_t %s;" % ", ".join("%s = (uint8_t)(fl_ >> %d)" % (n, 8 * i) for i, n in enumerate(flags)) if flags else ""
direct_ = ["#define %sCC __attribute__((preserve_none))" % P,
"#define %sARGS %s%s%s" % (P, head, "".join(", uint64_t %s" % n for n in regs), ", uint32_t fl_" if flags else ""),
"#define %sLOAD %s" % (P, unpack),
"#define %sHOP(K, F) __attribute__((musttail)) return F(c, (K)%s%s)" % (P, "".join(", " + n for n in regs),
", " + pack("") if flags else ""),
"#define %sCALL(F) F(c, k%s%s)" % (P, "".join(", l." + n for n in regs), ", " + pack("l.") if flags else "")]
return "\n".join([DIRECT_IF] + direct_ + ["#else"] + tramp + ["#endif"])
def split_function(name, body_lines, piece, loop_max, stats, direct=True):
"""The text of f_<addr>'s pieces and dispatcher (raises Refuse when the function must stay whole). direct: the pieces
jump to each other where the compiler can (macros())"""
locs, body_lines = locals_of(body_lines)
items = items_of(body_lines)
starts = plan(items, piece, loop_max)
if len(starts) < 2:
raise Refuse("too small to cut")
addr = name[2:]
labels = [lab for lab, _ in items if lab]
lid = {lab: i + 1 for i, lab in enumerate(labels)}
tails = {} # tail-call target -> id (after the label ids)
bounds = starts + [len(items)]
owner = {}
for p in range(len(starts)):
for lab, _ in items[bounds[p]:bounds[p + 1]]:
if lab:
owner[lab] = p
pieces, ranges = [], []
P = "s_%s_" % addr # (this function's pieces s_<addr>_<n>, its locals' struct s_<addr>_l and its macros)
regs = [n for kind, n, _ in locs if kind == "uint64_t"]
flags = [n for kind, n, _ in locs if kind == "uint8_t"]
if locs:
pieces.append("typedef struct { %s } %sl;" % (" ".join("%s %s;" % (k, ", ".join(ns)) for k, ns in
((REG_T, regs), (FLAG_T, flags)) if ns), P))
stats["functions_split_with_locals"] += 1
pieces.append(macros(P, regs, flags, direct))
for p in range(len(starts)):
pieces.append("static __attribute__((noinline)) %sCC uintptr_t %s%d(%sARGS);" % (P, P, p, P))
for p in range(len(starts)):
mine = items[bounds[p]:bounds[p + 1]]
mylabs = [lab for lab, _ in mine if lab]
out = ["static __attribute__((noinline)) %sCC uintptr_t %s%d(%sARGS) {" % (P, P, p, P)]
if locs:
out.append(" %sLOAD" % P)
if mylabs:
out.append(" switch (k) { %s default: break; }" % " ".join("case %d: goto %s;" % (lid[l], l) for l in mylabs))
def go(m, p=p):
t = m.group(1)
if owner[t] == p:
return m.group(0)
stats["cross_gotos"] += 1
return "{ %sHOP(%d, %s%d); }" % (P, lid[t], P, owner[t])
def tail(m):
stats["tail_calls"] += 1
return "return %d;" % tails.setdefault(m.group(1), len(labels) + 1 + len(tails))
for lab, text in mine:
if lab:
out.append(lab + ":;")
continue
if "goto *" in text or "&&L_" in text or "__label__" in text or "setjmp(" in text and "recomp_sj_setjmp(" not in text:
raise Refuse("a computed goto or a setjmp of another shape")
t = GOTO.sub(go, text) if "goto" in text else text
if "return" in t or "TAILCALL" in t:
t = TAIL.sub(tail, t).replace("return;", "return 0;")
if "TAILCALL" in t:
raise Refuse("a tail call of another shape")
if RETURN_OK.search(t):
raise Refuse("a return of another shape")
out.append(t)
out.append("%sHOP(%d, %s%d);" % (P, lid[items[bounds[p + 1]][0]], P, p + 1) if p + 1 < len(starts) else "return 0;")
out.append("}")
pieces.append("\n".join(out))
if mylabs:
ranges.append((lid[mylabs[0]], lid[mylabs[-1]], p))
d = ["void %s(Ctx *__restrict A64_NOESC c) {" % name]
if locs:
d.append(" %sl l = { %s };" % (P, ", ".join(load for _, _, load in locs)))
# (direct: the pieces go from one to the next themselves, so a piece returns only 0 or a tail call's id here and the
# label ids' cases are never taken; the trampoline: every goto into another piece comes back through them)
d += [" uintptr_t k = 0;",
" k = %sCALL(%s0);" % (P, P),
" for (;;) {",
" switch (k) {",
" case 0: return;"]
for a, b, p in ranges:
d.append(" case %d%s: k = %sCALL(%s%d); continue;" % (a, "" if a == b else " ... %d" % b, P, P, p))
for f, i in sorted(tails.items(), key=lambda x: x[1]):
d.append(" case %d: TAILCALL(%s);" % (i, f))
d += [" }", " return; /* (never: every id is a case) */", " }", "}"]
d.append("#undef %sCC\n#undef %sARGS\n#undef %sLOAD\n#undef %sHOP\n#undef %sCALL" % (P, P, P, P, P))
stats["pieces"] += len(starts)
stats["functions_split"] += 1
return "\n".join(pieces) + "\n" + "\n".join(d)
def split_text(src, piece_kb=PIECE_KB, min_kb=MIN_KB, only=None, notes=None, direct=True):
"""A lifted C file with each function of at least min_kb KB of C (or the ones named in `only`) split: (text, stats).
notes: a list that gets a line per function left whole and why; direct: the pieces jump to each other where the
compiler can (False: always through f_'s loop)"""
stats = collections.Counter()
piece, min_bytes = piece_kb * 1024, min_kb * 1024
out, pos = [], 0
# (each definition's body runs from its head's line to the first "}" at the start of a line: only the giants are read
# line by line; the rest of the file is copied as it is, 40 s -> a few s over a whole lift)
for m in HEAD_TEXT.finditer(src):
start = m.end()
if start < pos:
continue
end = src.find("\n}\n", start - 1)
if end < 0:
end = len(src) - 2 if src.endswith("\n}") else -1
if end < 0:
break
name, size = m.group(1), end + 1 - start
if not ((only is None and size >= min_bytes) or (only is not None and name in only)):
continue
try:
done = split_function(name, src[start:end].split("\n") if end >= start else [], piece, 4 * piece, stats, direct)
except Refuse as e:
stats["functions_left_whole"] += 1
if notes is not None:
notes.append("%s (%d KB) left whole: %s" % (name, size >> 10, e))
continue
out.append(src[pos:m.start()])
out.append(done)
stats["bytes_split"] += size
pos = end + 2
if not out:
return src, stats
out.append(src[pos:])
return "".join(out), stats
FLAG = "-DHOOKSHOT_SPLIT_GIANTS="
TRAMPOLINE = "_t" # (the flag's end when the pieces go through f_'s loop only: HOOKSHOT_SPLIT_DIRECT=0)
def flag(piece_kb=PIECE_KB, direct=True):
"""nx2/build.py: the flag on the lifted chunks' compiles: the piece size, this file's hash and the trampoline's mark when
direct is off (a change of any builds the chunks again: the flags are in their object keys)"""
import hashlib
with open(__file__, "rb") as f:
return FLAG + "%d_%s%s" % (piece_kb, hashlib.sha1(f.read(), usedforsecurity=False).hexdigest()[:10],
"" if direct else TRAMPOLINE)
def compile_copy(src, obj, fl):
"""nx2/build.py compile_one: what to compile for a job whose flags carry FLAG: a copy of src beside the object with its
giants split (obj's name + .split.c; compile_one removes it), or src itself when it has none"""
val = next((f[len(FLAG):] for f in fl if f.startswith(FLAG)), "")
kb = int(val.split("_")[0]) if val else 0
if not kb:
return src
with open(src, encoding="utf-8", newline="") as f:
text = f.read()
out, st = split_text(text, kb, direct=not val.endswith(TRAMPOLINE))
if not st["functions_split"]:
return src
copy = obj[:-2] + ".split.c"
with open(copy, "w", encoding="utf-8", newline="") as f:
f.write(out)
return copy

View File

@@ -21,6 +21,10 @@ def main():
used=source[start:stop]
begin=source.index('const uint32_t n =',stop);end=source.index(';',begin)+1
rounded=source[begin:end]
# ((Triforce) the simulated-turf lists' storage descriptors' encoding, which the range reads through: ir_opt/sim_turf_pool_pass.h)
info_h=(ROOT/'gpu/vk/eden/shader_recompiler/shader_info.h').read_text(encoding='utf-8')
private=info_h[info_h.index('inline constexpr u32 kSimTurfStorageBit'):]
private=private[:private.index(chr(10)+'}'+chr(10),private.index('constexpr u32 SimTurfStorageOrig('))+3]
fixture=r'''
#include <algorithm>
#include <array>
@@ -30,7 +34,9 @@ def main():
struct Descriptor { uint32_t cbuf_index,cbuf_offset,count; };
struct Info { static constexpr uint32_t MAX_CBUFS=18;bool uses_global_memory=false;
std::array<uint32_t,MAX_CBUFS> constant_buffer_used_sizes{};std::vector<Descriptor> storage_buffers_descriptors; };
namespace Shader { using Info=::Info; }
namespace Shader { using Info=::Info; using u32=uint32_t; using StorageBufferDescriptor=::Descriptor;
''' + private + r'''
}
struct Stage { Info info; };
uint32_t extent(const Stage& st,uint32_t index) {
''' + used + rounded + r'''

218
nx2/test_image_arrays.py Normal file
View File

@@ -0,0 +1,218 @@
"""Image buffer, storage image and texture buffer arrays are arrays in the SPIR-V, without game files or a GPU.
A handle the shader reads at a dynamic offset of a constant buffer is a descriptor array (Shader::Info's count), and the
renderer writes that many descriptors to its binding (vk_draw.cpp). tests/image_arrays_ir.cpp builds such programs and
the same ones with single descriptors, runs them through the real texture pass and SPIR-V back end, and writes their
modules. Each must translate, pass spirv-val (Vulkan 1.3) and declare every binding with the count Info gives it: an
OpTypeArray of that many images for a count above 1, the image itself for 1. Image buffers and storage images are read and
written or added to atomically, texture buffers and textures fetched (plain, and with the fetch bounds of vk_vendor.h).
Programs whose device indexes the arrays nonuniformly must carry NonUniform decorations (an atomic's texel pointer too)
and that kind's capability.
python -I -B nx2/test_image_arrays.py --headers <SPIRV-Headers/include> --spirv-val spirv-val [--cxx clang++]
[--tree <a checkout>] [--base-tree <a checkout>] [--keep <folder>]
--tree takes the back end from another checkout (main's: the test fails there). --base-tree builds the fixture against
that checkout's back end too, and requires every module of a program with single descriptors (the -1 cases) to be byte
for byte the same: a change that declares arrays leaves every other program as it was. --keep copies the modules.
Builds the same Eden IR/SPIR-V and Sirit sources as the renderer, with its compatibility headers.
"""
# SPDX-License-Identifier: GPL-3.0-or-later
import argparse
import concurrent.futures
import os
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{spirv_headers}", "--spirv-val", "{spirv_val}"]
# (spirv-val: SPIRV-Tools comes with the Linux runner's packages, not on Windows)
RUN_ALL_SKIP = {"windows": "needs spirv-val: checked on Linux"}
ROOT = Path(__file__).resolve().parents[1]
KINDS = ('texbuf', 'imgbuf', 'tex', 'img') # (Eden's binding order: texture buffers, image buffers, textures, images)
# The descriptor arrays (count above 1) each program has, in binding order; the -1 programs have none
ARRAYS = {
'imgbuf-2': [('imgbuf', 2)],
'img-3': [('img', 3)],
'texbuf-2': [('texbuf', 2)],
'imgbuf-atomic-2': [('imgbuf', 2)],
'img-atomic-3': [('img', 3)],
'mixed': [('texbuf', 2), ('imgbuf', 2), ('tex', 2), ('img', 3)],
}
# (each kind's capability for nonuniform indexing)
NONUNIFORM_CAPABILITY = {'texbuf': 5311, 'imgbuf': 5312, 'tex': 5307, 'img': 5309}
OP_CAPABILITY, OP_TYPE_IMAGE, OP_TYPE_SAMPLED_IMAGE, OP_TYPE_ARRAY = 17, 25, 27, 28
OP_TYPE_POINTER, OP_CONSTANT, OP_VARIABLE, OP_IMAGE_TEXEL_POINTER, OP_DECORATE = 32, 43, 59, 60, 71
DIM_BUFFER, UNIFORM_CONSTANT, DECORATION_BINDING, DECORATION_NON_UNIFORM = 5, 0, 33, 5300
CASES = 28 # (12 programs, each plain and nonuniform; texbuf-1, texbuf-2, mixed-1 and mixed also with fetch bounds)
def build_fixture(cxx, flags, sources, exe):
"""What one compiler call with every source builds, made one object a source, as many at once as there are CPUs,
then linked: the same program, faster, and each object one a compiler cache can keep"""
(exe.parent / 'obj').mkdir()
objs = [exe.parent / 'obj' / ('%03d.o' % i) for i in range(len(sources))]
with concurrent.futures.ThreadPoolExecutor(os.cpu_count() or 2) as pool:
list(pool.map(lambda job: subprocess.run([cxx, *flags, '-c', str(job[0]), '-o', str(job[1])], check=True),
zip(sources, objs)))
subprocess.run([cxx, *map(str, objs), '-o', str(exe)], check=True)
def emit(args, tree, folder):
"""The fixture built against tree's back end and run into folder: {case: (Info's counts by kind) or 'refused: ...'}"""
vk = tree / 'gpu/vk'
sources = sorted({p for directory in ('eden/shader_recompiler/backend/spirv',
'eden/shader_recompiler/frontend/ir', 'eden/shader_recompiler/ir_opt', 'sirit/src')
for p in (vk / directory).rglob('*.cpp')})
flags = ['-std=c++20', '-O1', '-D_CRT_SECURE_NO_WARNINGS',
'-DVK_NO_PROTOTYPES', '-DMKWVK_INCLUDES=2']
for header in ('algorithm', 'cstdio', 'cstdlib', 'cstring', 'functional', 'string', 'vector'):
flags += ['-include', header]
flags += ['-I' + str(p) for p in (vk / 'compat', tree / 'gpu/compat', vk / 'eden',
tree / 'gpu/third_party/suyu', vk / 'sirit/include', vk / 'sirit/src', args.headers)]
exe = folder / 'fixture.exe'
build_fixture(args.cxx, flags, [ROOT / 'tests/image_arrays_ir.cpp', *sources], exe)
modules = folder / 'modules'
run = subprocess.run([str(exe), str(modules)], check=True, capture_output=True, text=True)
cases = {}
for line in run.stdout.splitlines():
name, rest = line.split(' ', 1)
if rest.startswith('refused: '):
cases[name] = rest
continue
fields = dict(field.split(':') for field in rest.split()[1:])
cases[name] = {kind: [int(n) for n in fields[kind].split(',') if n] for kind in KINDS}
return modules, cases
def declared(path):
"""The module's descriptors of images (UniformConstant variables with a binding), in binding order:
{kind: [count, ...]}; its ids decorated NonUniform, its capabilities and its atomics' texel pointers"""
data = path.read_bytes()
words = struct.unpack('<%dI' % (len(data) // 4), data)
images, sampled, arrays, constants, pointers, variables, bindings = {}, set(), {}, {}, {}, {}, {}
capabilities, non_uniform, texel_pointers = set(), set(), []
i = 5
while i < len(words):
count, op = words[i] >> 16, words[i] & 0xFFFF
operands = words[i + 1:i + count]
if op == OP_CAPABILITY:
capabilities.add(operands[0])
elif op == OP_TYPE_IMAGE:
images[operands[0]] = (operands[2], operands[6]) # (dim, sampled: 1 sampled, 2 storage)
elif op == OP_TYPE_SAMPLED_IMAGE:
sampled.add(operands[0])
elif op == OP_TYPE_ARRAY:
arrays[operands[0]] = (operands[1], operands[2])
elif op == OP_CONSTANT:
constants[operands[1]] = operands[2]
elif op == OP_TYPE_POINTER:
pointers[operands[0]] = (operands[1], operands[2])
elif op == OP_VARIABLE:
variables[operands[1]] = (operands[0], operands[2])
elif op == OP_IMAGE_TEXEL_POINTER:
texel_pointers.append(operands[1])
elif op == OP_DECORATE and operands[1] == DECORATION_BINDING:
bindings[operands[0]] = operands[2]
elif op == OP_DECORATE and operands[1] == DECORATION_NON_UNIFORM:
non_uniform.add(operands[0])
i += count
found = {kind: [] for kind in KINDS}
for variable in sorted((v for v in variables if v in bindings), key=bindings.get):
pointer, storage = variables[variable]
if storage != UNIFORM_CONSTANT:
continue
element, count = pointers[pointer][1], 1
if element in arrays:
element, count = arrays[element][0], constants[arrays[element][1]]
if element in sampled:
kind = 'tex'
else:
dim, use = images[element]
kind = ('texbuf' if use == 1 else 'imgbuf') if dim == DIM_BUFFER else 'img'
found[kind].append(count)
return found, non_uniform, capabilities, texel_pointers
def program_of(case):
"""The program a case translates (its name without the profile's suffix)"""
return case.removesuffix('-nonuniform').removesuffix('-bounds')
def check(args, modules, cases):
"""What is wrong with each case's module, as lines"""
failures = []
for name, info in cases.items():
program = program_of(name)
if isinstance(info, str):
failures.append('%s: translation %s' % (name, info))
continue
module = modules / (name + '.spv')
valid = subprocess.run([args.spirv_val, '--target-env', 'vulkan1.3', str(module)], capture_output=True, text=True)
if valid.returncode:
said = (valid.stdout + valid.stderr).strip().splitlines() or ['exit %d' % valid.returncode]
failures.append('%s: spirv-val: %s' % (name, said[0]))
want = ARRAYS.get(program, [])
made = [(kind, count) for kind in KINDS for count in info[kind] if count > 1]
if made != want:
failures.append('%s: the texture pass made the arrays %s, not %s' % (name, made, want))
found, non_uniform, capabilities, texel_pointers = declared(module)
if found != info:
failures.append('%s: the module declares %s where Shader::Info has %s' % (name, found, info))
if name.endswith('-nonuniform') and want:
if not non_uniform:
failures.append('%s: no NonUniform decoration' % name)
if not set(texel_pointers) <= non_uniform:
failures.append('%s: an atomic\'s texel pointer is not decorated NonUniform' % name)
for kind in {kind for kind, _ in want} - {k for k, c in NONUNIFORM_CAPABILITY.items() if c in capabilities}:
failures.append('%s: no %s nonuniform indexing capability' % (name, kind))
elif non_uniform:
failures.append('%s: NonUniform decorations without arrays indexed nonuniformly' % name)
return failures
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--cxx', default='clang++')
parser.add_argument('--headers', type=Path, required=True)
parser.add_argument('--spirv-val', default='spirv-val')
parser.add_argument('--tree', type=Path, default=ROOT, help='the checkout whose back end is tested')
parser.add_argument('--base-tree', type=Path, help='a checkout whose single-descriptor modules must be the same')
parser.add_argument('--keep', type=Path, help='a folder to copy the modules to')
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='image-arrays-') as temp:
folder = Path(temp).resolve()
(folder / 'tree').mkdir()
modules, cases = emit(args, args.tree.resolve(), folder / 'tree')
if args.keep:
shutil.copytree(modules, args.keep, dirs_exist_ok=True)
failures = check(args, modules, cases)
if len(cases) != CASES:
failures.append('%d cases, not %d: %s' % (len(cases), CASES, sorted(cases)))
singles = sorted(name for name in cases if program_of(name).endswith('-1'))
if args.base_tree:
(folder / 'base').mkdir()
base_modules, base_cases = emit(args, args.base_tree.resolve(), folder / 'base')
for name in singles:
ours, theirs = modules / (name + '.spv'), base_modules / (name + '.spv')
if not theirs.exists() or not ours.exists() or ours.read_bytes() != theirs.read_bytes():
failures.append('%s: not byte for byte the base tree\'s module' % name)
for name in sorted(set(base_cases) - set(singles)):
base = base_cases[name]
print('base tree %s: %s' % (name, base if isinstance(base, str) else '%d bytes' % (
(base_modules / (name + '.spv')).stat().st_size)))
for name, info in sorted(cases.items()):
print('%s: %s' % (name, info if isinstance(info, str) else ' '.join(
'%s %s' % (kind, info[kind]) for kind in KINDS if info[kind])))
if failures:
for failure in failures:
print('FAIL: ' + failure)
raise SystemExit(1)
print('PASS: image buffer, storage image and texture buffer arrays declared as arrays; %d modules validate%s' % (
len(cases), '; %d single-descriptor modules byte for byte the base tree\'s' % len(singles) if args.base_tree else ''))
if __name__ == '__main__':
main()

View File

@@ -18,7 +18,8 @@ import subprocess
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SOURCES = ("host", "gpu", "nx2")
SOURCE_EXT = (".c", ".cc", ".cpp", ".h", ".hpp", ".inc", ".py", ".glsl", ".comp", ".vert", ".frag", ".spv")
# ((Triforce) .inl and .def: files an #include names besides headers, as nx2/build.py's HEADER_EXTS)
SOURCE_EXT = (".c", ".cc", ".cpp", ".h", ".hpp", ".inc", ".inl", ".def", ".py", ".glsl", ".comp", ".vert", ".frag", ".spv")
def release(root=ROOT):

98
nx2/walk.py Normal file
View File

@@ -0,0 +1,98 @@
"""(Triforce) a64_lift.Lifter.walk, the discovery's walk of one function, with the same result in less time and memory.
The kit's walk stores each instruction of a function as body[pc] = (kind, word): for OoT, 17.6 million entries, most of them
plain ops of far fewer distinct words. Each was a tuple of its own, about a gigabyte of the lift's process after the discovery;
that process holds them through the emit, and on Windows the emit's processes are one per GB of available memory
(nx2/chunks.py emit_jobs), so that gigabyte could be a process fewer on a 16 GB PC. Here every plain op of the same word is
one shared (("op",), word) tuple (nx2/insn.py's classify answers a plain op the same at every pc), and the image's lookups
(nx2/image.py EdenImage's word view and code ranges) are read inline. Shared after the fact, the duplicates' memory would stay
with Python's allocator: it is done as the walk makes them.
Everything else is the kit's walk, line for line in its order: the same instructions visited in the same order, the same jump
tables found and the same labels. tests/test_walk.py compares the two over a made-up image, and pins KIT_WALK, the sha256 of
the kit's own walk's source: a change to the kit's walk fails it until this copy is compared with it again.
install() is run by nx2/lift.py at its module level (so the emit's and the discovery's processes have it too).
"""
import a64_lift
KIT_WALK = "edf0c833a9b45d28848867ca0e7e1e982707f67efb6827db7f89fd4748f6149a" # (sha256 of a64_lift.Lifter.walk's source this copies)
_installed = False
def walk(self, entry):
"""a64_lift.Lifter.walk: (body {pc: (kind, word)}, labels) of the function at entry"""
img, entries = self.img, self.entries
classify = a64_lift.classify # (nx2/insn.py's, installed before any walk)
ops = self.__dict__.setdefault("_op_entries", {}) # (word -> the shared (("op",), word) entry; never sent: emit_pool NOT_SENT)
spans = getattr(img, "_spans", None)
words = getattr(img, "_words", None)
if spans is not None and words is not None:
base, size = img._base, len(img.mem)
def in_code(a):
if a & 3:
return False
for lo, hi in spans:
if lo <= a < hi:
return True
return False
def word(a): # (only asked after in_code: a is word aligned)
off = a - base
return words[off >> 2] if 0 <= off < size else img.word(a)
else:
in_code, word = img.in_code, img.word
body, labels, todo = {}, set(), [entry]
def visit(t):
if t != entry and t in entries:
return
if in_code(t):
labels.add(t)
todo.append(t)
while todo:
pc = todo.pop()
while pc not in body:
if (pc != entry and pc in entries) or not in_code(pc):
break
w = word(pc)
kw = ops.get(w)
if kw is not None: # (a word seen before as a plain op: one at every pc, nx2/insn.py classify)
body[pc] = kw
pc += 4
continue
k = classify(w, pc)
kind = k[0]
if kind == "op":
kw = ops[w] = (k, w)
body[pc] = kw
pc += 4
continue
body[pc] = (k, w)
if kind == "b":
visit(k[1])
break
if kind in ("bcond", "cbz", "tbz"):
visit(k[1])
elif kind == "br":
targets = self.jump_table(pc, k[1])
if targets:
self.jt[pc] = targets
self.add_jt_edges(pc, targets)
for t in targets:
visit(t)
break
elif kind in ("ret", "trap"):
break
pc += 4
return body, labels
def install():
global _installed
if _installed:
return
_installed = True
a64_lift.Lifter.walk = walk

View File

@@ -1,14 +1,21 @@
"""(issue 1197) A lifted C file rewritten in place (the patches, the chunk split) is written beside it and moved over it: a run
stopped mid-write (the builder closed, a second build stopping the first, a full disk) leaves the old file whole, never the first
megabytes of the new one, which the compile then stopped on at every try ("g_module_b" where g_module_base was)."""
megabytes of the new one, which the compile then stopped on at every try ("g_module_b" where g_module_base was).
The move only covers a process that stops: a PC that goes down (power, a crash) can keep the move and lose the data that was still
in memory, and Windows then shows the file at its size full of null bytes. sync=True writes the data to the disk before the move,
for a small file that later runs read back (chunks.txt). The lifted C is not synced (a gigabyte, every lift)."""
import os
import time
def write_whole(path, text, newline="\n"):
def write_whole(path, text, newline="\n", sync=False):
tmp = path + ".part"
with open(tmp, "w", encoding="utf-8", newline=newline) as f:
f.write(text)
if sync:
f.flush()
os.fsync(f.fileno())
for attempt in range(20): # (an antivirus reading the file holds it a moment: Windows refuses the move until it lets go)
try:
os.replace(tmp, path)