rewriter/layout: give module data a 16 KB page of its own (PR #3138)

Horizon maps code modules at 4 KB, while macOS and iOS map at 16 KB
with W^X (loader.c seals [0, round16K(text_end)) read+execute and
gen_embed.py places it in __TEXT). Any NSO or NRO whose data starts
below round16K(text_end) (such as FINAL FANTASY VIII Remastered's
Math.nro at 0x2000 and Platform.nro at 0x3000) ends up with read-only
data and faults with SIGBUS in relocate().

Add dm/tools/mod_layout.py and invoke relayout_module() inside
patch_nso.py right after nso.load() for all NSO and NRO modules:
- Shift ro, data and bss up by whole 4 KB pages so data starts at or
  past round16K(text_end), keeping TEXT_END at the true code end and
  leaving on-disk .nro files and nro.tsv untouched.
- Rewrite the embedded NRO0 header (when present), MOD0 (+4 and its
  six offsets), dynamic pointer tags, .dynsym values (excluding
  STT_TLS), RELA/JMPREL/RELR, text adrp/adr/literal references into the
  moved range (skipping +4, MOD0 in text, in-text literal pools and
  unallocated 0xDC words), and .eh_frame_hdr/.eh_frame (including
  empty FDE augmentations, sdata4 counts, omitted search tables and
  explicit LSDA lpstart pointers).
- Check data_off >= round16K(text_end) in loader.c read_layout() for
  every module, and add mod_layout.py to the rewriter cache keys in
  build_ipa_from_nsp.py and regress.py.

Co-authored-by: Gabriel Tran <[email protected]>
This commit is contained in:
seeddsandGabriel Tran committed 2026-11-22 22:26:58 +08:00
1 parent 0cf3a70298
commit 17454fc314
9 files changed
+491 -5

No files matched your search

+4
View File
@@ -363,6 +363,10 @@ static void read_layout(module_t *m, const char *dir) {
if ((m->back_off || m->back_len) && (m->patch_off >= 0 || !m->back_len || m->back_off % 0x4000 || m->back_len % 0x4000 || m->back_off < m->key_page_off + m->key_page_size
|| m->back_off + m->back_len != m->image_size))
die("%s: back patch area, but BACK_OFF / BACK_LEN missing or wrong", path);
// map_image seals [0, text_end rounded up to 16 KB) read + execute (and gen_embed.py puts it in __TEXT on iOS): data below that would be read-only and SIGBUS in relocate()
// (FINAL FANTASY VIII Remastered's Math.nro and Platform.nro). patch_nso.py moves ro and data up (mod_layout.py); stop here on a copy rewritten before that
if (m->data_off < ((m->text_end + 0x3FFF) & ~0x3FFFull))
die("%s: data at %#llx shares a 16 KB page with code (text ends at %#llx): rewrite the module again with dm/tools/patch_nso.py", m->name, (unsigned long long)m->data_off, (unsigned long long)m->text_end);
}
// Frame step state (the page after the key page, read-write; layout in patch_nso.py FRAME_STEP): the rewriter's stubs step the game by the host's whole vsyncs capped at this
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Give a Switch module's data segment a 16 KB page of its own: move ro and data (and bss) up by whole 4 KB pages so data starts at or past the end of text rounded up to 16 KB.
Usage: mod_layout.py <in.nso|in.nro> [out.nro] (prints what it moves; writes out.nro only for an NRO)
Why: Horizon maps modules at 4 KB, the Mac and iOS hosts at 16 KB. loader.c seals [0, text_end rounded up to 16 KB) read + execute (and gen_embed.py puts the same range in __TEXT),
so a module whose data starts below that boundary has read-only data: the first R_AARCH64_RELATIVE into it stops the game with SIGBUS in relocate()
(FINAL FANTASY VIII Remastered: Math.nro is text 0x1000, ro 0x1000, data 0x1000; Platform.nro text 0x1000, ro 0x2000, data 0x1000). Moving ro with data keeps every ro <-> data
distance; only references between text and the moved part change, by D:
- the NRO header (when NRO0: module size, text / ro / data offsets), the MOD0 offset at +4, and MOD0's offsets whose target and MOD0 lie on different sides
- the dynamic section's address tags, symbol values (excluding STT_TLS), RELA / JMPREL offsets and RELATIVE (and symbol-less ABS64) addends, DT_RELR offsets and slot addends
- in text: adrp (D is whole 4 KB pages, so the low 12 bits an add / ldr supplies stay right), adr and literal loads whose target is in the moved part
- .eh_frame_hdr's table, .eh_frame's pc-relative / data-relative pointers, and any LSDA explicit lpstart pointer
patch_nso.py calls relayout_module() on every NSO and NRO right after nso.load(), leaving on-disk files and nro.tsv untouched."""
import os, struct, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import nso, nso_code
PAGE, HOST_PAGE = 0x1000, 0x4000
PTR_TAGS = {3, 4, 5, 6, 7, 12, 13, 17, 23, 25, 26, 32, 36, 0x6ffffef5, 0x6ffffff0, 0x6ffffffc, 0x6ffffffe} # PLTGOT HASH STRTAB SYMTAB RELA INIT FINI REL JMPREL INIT/FINI/PREINIT_ARRAY RELR GNU_HASH VERSYM VERDEF VERNEED
R_ABS64, R_GLOB_DAT, R_JUMP_SLOT, R_RELATIVE = 257, 1025, 1026, 1027
FMT_INFO = {
0x3: ('<I', 0, (1 << 32) - 1),
0xB: ('<i', -(1 << 31), (1 << 31) - 1),
0x0: ('<Q', 0, (1 << 64) - 1),
0x4: ('<Q', 0, (1 << 64) - 1),
0xC: ('<q', -(1 << 63), (1 << 63) - 1),
}
class Error(ValueError):
pass
def shift_needed(text_end, data_off):
"""D (bytes, a multiple of 4 KB) that moves data to a 16 KB page past the code, 0 when it already is"""
rx = (text_end + HOST_PAGE - 1) & ~(HOST_PAGE - 1)
return 0 if data_off >= rx else rx - data_off
def relayout_module(mod):
"""(new nso.Module, D, notes) for mod (NSO or NRO). Returns (mod, 0, []) unchanged when data already sits on its own 16 KB page"""
(to, tsz), (ro, rsz), (do, dsz) = mod.segments
D = shift_needed(tsz, do)
if not D: return mod, 0, []
if to or tsz > ro or ro + rsz > do or do + dsz != len(mod.image) or ro % PAGE or do % PAGE or D % PAGE:
raise Error(f'unexpected segments text {to:#x}+{tsz:#x} ro {ro:#x}+{rsz:#x} data {do:#x}+{dsz:#x} image {len(mod.image):#x}')
mv = lambda a: a + D if a >= ro else a
old = bytes(mod.image)
new = bytearray(old[:ro]) + bytearray(D) + bytearray(old[ro:])
n = {'adrp': 0, 'adr': 0, 'literal': 0, 'reloc': 0, 'relr': 0, 'sym': 0, 'eh': 0, 'dyn': 0}
def put(fmt, o_old, v): struct.pack_into(fmt, new, mv(o_old), v)
# NRO header (in text, not moved): update offsets so loader.c's NRO data check (m->base + 0x30 == m->data_off) agrees
if len(old) >= 0x40 and old[0x10:0x14] == b'NRO0':
size = struct.unpack_from('<I', old, 0x18)[0]
if size != len(old): raise Error(f'NRO header size {size:#x} != image {len(old):#x}')
struct.pack_into('<I', new, 0x18, size + D)
struct.pack_into('<I', new, 0x24, tsz + D)
struct.pack_into('<I', new, 0x28, ro + D)
struct.pack_into('<I', new, 0x30, do + D)
# MOD0: offset at +4, and six offsets relative to MOD0 itself
m0 = struct.unpack_from('<I', old, 4)[0]
if m0 + 28 > len(old) or old[m0:m0 + 4] != b'MOD0': raise Error(f'no MOD0 at {m0:#x}')
struct.pack_into('<I', new, 4, mv(m0))
mod0 = list(struct.unpack_from('<6i', old, m0 + 4))
for i, r in enumerate(mod0): put('<i', m0 + 4 + 4 * i, mv(m0 + r) - mv(m0))
# dynamic
dyn = m0 + mod0[0]; o = dyn; tags = {}
while True:
t, v = struct.unpack_from('<qQ', old, o)
if t == 0: break
tags[t] = v
if t in PTR_TAGS and mv(v) != v: put('<Q', o + 8, mv(v)); n['dyn'] += 1
o += 16
if 17 in tags: raise Error('DT_REL relocations (only RELA is expected on AArch64)')
# symbols: nchain of DT_HASH, else up to DT_STRTAB (STT_TLS values are TLS block offsets, not module addresses)
symtab, strtab = tags.get(6), tags.get(5)
if symtab is not None:
if 4 in tags: nsym = struct.unpack_from('<I', old, tags[4] + 4)[0]
elif strtab is not None: nsym = (strtab - symtab) // 24
else: raise Error('DT_SYMTAB without DT_HASH or DT_STRTAB')
for i in range(nsym):
s = symtab + 24 * i
st_type = old[s + 4] & 0xF
shndx = struct.unpack_from('<H', old, s + 6)[0]; val = struct.unpack_from('<Q', old, s + 8)[0]
if shndx and shndx < 0xff00 and st_type != 6 and mv(val) != val: put('<Q', s + 8, mv(val)); n['sym'] += 1
# RELA and JMPREL
for tab, sz in ((7, 8), (23, 2)):
if tab not in tags: continue
for k in range(tags[sz] // 24):
r = tags[tab] + 24 * k
off, info, add = struct.unpack_from('<QQq', old, r)
typ, si = info & 0xffffffff, info >> 32
if typ not in (R_ABS64, R_GLOB_DAT, R_JUMP_SLOT, R_RELATIVE): raise Error(f'relocation type {typ} at {r:#x}')
if typ == R_RELATIVE or (typ == R_ABS64 and si == 0): add = mv(add)
struct.pack_into('<QQq', new, mv(r), mv(off), info, add); n['reloc'] += 1
# DT_RELR: even entries are addresses, odd ones bitmaps; the addend is the slot's content
if 36 in tags:
where = None
for k in range(tags[35] // 8):
e = tags[36] + 8 * k; v = struct.unpack_from('<Q', old, e)[0]
if not v & 1:
put('<Q', e, mv(v)); slots = [v]; where = v + 8
else:
if where is None: raise Error(f'DT_RELR bitmap before start at {e:#x}')
slots = [where + 8 * b for b in range(63) if v >> (b + 1) & 1]; where += 63 * 8
for a in slots: put('<Q', a, mv(struct.unpack_from('<Q', old, a)[0])); n['relr'] += 1
# text: adrp / adr / literal loads into the moved part.
# +4 is the MOD0 u32 offset (never code); small inline literal pools in text (below nso_code.DATA_MIN) are collected from in-text literal loads so their bytes are not rewritten.
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
blocks = list(nso_code.data_blocks(bytearray(old), tsz, md)) + [(4, 8)]
if m0 < tsz: blocks.append((m0, min(tsz, m0 + 28))) # MOD0 in text: b'MOD0' (0x30444F4D) matches the adr bitmask
code = lambda a: not any(s <= a < e for s, e in blocks)
sx = lambda v, b: v - (1 << b) if v >> (b - 1) & 1 else v
lit_words = set()
for a in range(0, tsz, 4):
if not code(a): continue
w = struct.unpack_from('<I', old, a)[0]
if w & 0x3B000000 == 0x18000000 and (w >> 30) != 3: # ldr / ldrsw (literal), not prfm or unallocated opc=3 V=1
t = a + sx((w >> 5) & 0x7FFFF, 19) * 4
if 0 <= t < tsz:
opc, vec = w >> 30, (w >> 26) & 1
width = 4 if opc == 0 else 8 if opc == 1 else (16 if vec else 4)
for p in range(t & ~3, min(tsz, t + width), 4): lit_words.add(p)
for a in range(0, tsz, 4):
if not code(a) or a in lit_words: continue
w = struct.unpack_from('<I', old, a)[0]
if w & 0x1F000000 == 0x10000000: # adr / adrp
imm = sx(((w >> 5) & 0x7FFFF) << 2 | (w >> 29) & 3, 21)
if w >> 31:
t = (a & ~0xFFF) + (imm << 12)
if t < ro: continue
imm += D >> 12; n['adrp'] += 1
else:
t = a + imm
if t < ro: continue
imm += D; n['adr'] += 1
if not -(1 << 20) <= imm < 1 << 20: raise Error(f'adr(p) at {a:#x} out of range after the move')
imm &= 0x1FFFFF
w = (w & 0x9F00001F) | (imm & 3) << 29 | (imm >> 2) << 5
struct.pack_into('<I', new, a, w)
elif w & 0x3B000000 == 0x18000000 and (w & 0xFF000000) != 0xDC000000: # ldr / ldrsw / prfm (literal), excluding unallocated opc=3 V=1
imm = sx((w >> 5) & 0x7FFFF, 19); t = a + imm * 4
if t < ro: continue
imm += D >> 2
if not -(1 << 18) <= imm < 1 << 18: raise Error(f'literal load at {a:#x} out of range after the move')
struct.pack_into('<I', new, a, (w & 0xFF00001F) | (imm & 0x7FFFF) << 5); n['literal'] += 1
# .eh_frame_hdr and .eh_frame (old offsets; a pointer read at o from base b to target t is rewritten as mv(t) - mv(b))
ehs, ehe = m0 + mod0[3], m0 + mod0[4]
if ehe - ehs >= 8 and old[ehs] == 1:
def fix(o, enc, optional=False):
"""rewrite the encoded pointer at old offset o; returns (old target, size)"""
enc &= 0x7F # strip DW_EH_PE_indirect: adjust the stored pointer itself, not its dereference
fmt, app = enc & 0xF, enc & 0x70
info_f = FMT_INFO.get(fmt)
if not info_f: raise Error(f'pointer encoding {enc:#x} at {o:#x}')
f, lo_v, hi_v = info_f
v = struct.unpack_from(f, old, o)[0]; sz = struct.calcsize(f)
if optional and v == 0: return 0, sz
base = o if app == 0x10 else ehs if app == 0x30 else 0 if app == 0 else None
if base is None: raise Error(f'pointer application {app:#x} at {o:#x}')
t = base + v; nv = mv(t) - mv(base)
if not lo_v <= nv <= hi_v: raise Error(f'encoded pointer {enc:#x} at {o:#x} overflows after the move ({nv:#x})')
if nv != v: put(f, o, nv); n['eh'] += 1
return t, sz
_, penc, cenc, tenc = old[ehs:ehs + 4]
o = ehs + 4
ehf = None
if penc != 0xFF:
ehf, s = fix(o, penc); o += s
if cenc == 0xFF:
cnt = 0
elif (cenc & 0xF) in (0x3, 0xB):
cnt = struct.unpack_from('<I' if (cenc & 0xF) == 3 else '<i', old, o)[0]; o += 4
else:
raise Error(f'eh_frame_hdr count encoding {cenc:#x}')
if tenc not in (0xFF, 0):
for _ in range(cnt):
o += fix(o, tenc)[1]; o += fix(o, tenc)[1]
# walk .eh_frame
if ehf is not None:
cies, o = {}, ehf
while o + 4 <= len(old):
ln = struct.unpack_from('<I', old, o)[0]
if ln == 0: break
if ln == 0xFFFFFFFF: raise Error('64-bit eh_frame record')
cid = struct.unpack_from('<I', old, o + 4)[0]; end = o + 4 + ln
if cid == 0: # CIE
p = o + 9; ver = old[o + 8]
aug = old[p:old.index(b'\0', p)]; p += len(aug) + 1
_, p = nso_code._uleb(old, p)
while old[p] & 0x80: p += 1
p += 1
p = p + 1 if ver == 1 else nso_code._uleb(old, p)[1]
r_enc, l_enc, has_p = 0, None, False
if aug.startswith(b'z'):
_, p = nso_code._uleb(old, p)
for ch in aug[1:].decode():
if ch == 'R': r_enc = old[p]; p += 1
elif ch == 'L': l_enc = old[p]; p += 1
elif ch == 'P': pe = old[p]; p += 1; p += fix(p, pe)[1]; has_p = True
elif ch in 'SB': pass
else: raise Error(f'CIE augmentation {aug!r}')
cies[o] = (r_enc, l_enc, has_p, aug.startswith(b'z'))
else:
cie = o + 4 - cid
r_enc, l_enc, has_p, z = cies[cie]
p = o + 8
if r_enc != 0xFF:
p += fix(p, r_enc)[1]
rfmt = FMT_INFO.get(r_enc & 0xF)
if not rfmt: raise Error(f'FDE range encoding {r_enc:#x} at {p:#x}')
p += struct.calcsize(rfmt[0]) # pc range: no application
if z:
aug_len, p = nso_code._uleb(old, p)
if aug_len > 0 and l_enc is not None and l_enc != 0xFF:
lsda, _ = fix(p, l_enc, optional=True)
if lsda and has_p:
lpe = old[lsda]
if lpe != 0xFF: fix(lsda + 1, lpe)
o = end
notes = [f'moved ro and data by {D:#x}: ro {ro:#x} -> {ro + D:#x}, data {do:#x} -> {do + D:#x}',
', '.join(f'{k} {v}' for k, v in n.items())]
return nso.Module(new, ((0, tsz), (ro + D, rsz), (do + D, dsz)), mod.bss, mod.build_id), D, notes
def main():
src = sys.argv[1]
dst = sys.argv[2] if len(sys.argv) > 2 else None
with open(src, 'rb') as f: raw = f.read()
try:
mod = nso.load(raw, src)
out, D, notes = relayout_module(mod)
except (nso.Error, Error) as e:
sys.exit(f'[RED] {src}: {e}')
if dst:
if raw[0x10:0x14] != b'NRO0': sys.exit(f'[RED] {src}: writing an output file is only supported for NROs (NSOs are relaid out in memory by patch_nso.py)')
with open(dst, 'wb') as f: f.write(bytes(out.image) if D else raw)
print(f'{os.path.basename(src)}: ' + ('; '.join(notes) if D else 'data already on a 16 KB page of its own'))
if __name__ == '__main__': main()
+6 -2
View File
@@ -23,7 +23,7 @@ if capstone.cs_version()[0] != 5: # the rewriter uses Capstone 5's names (CS_A
sys.exit(f'[RED] Capstone {capstone.__version__} is unsupported; the rewriter requires Capstone 5.x. Run: {shlex.join([sys.executable, "-m", "pip", "install", "capstone>=5,<6"])}')
from capstone import *
from capstone.arm64 import ARM64_OP_IMM, ARM64_OP_MEM, ARM64_OP_REG
import nso, nso_asm, nso_syms
import mod_layout, nso, nso_asm, nso_syms
from nso_asm import * # the instruction encoders (B, ADRP, LDRX, ...), shared with the per-build patch files
# The NSP script terminates a failed or cancelled rewrite with SIGTERM. Exit through the pool's context manager so it reaps the workers too.
@@ -36,6 +36,11 @@ src, outdir, NAME = sys.argv[1], sys.argv[2], sys.argv[3]
# An NSO, or an NRO (a module the game loads at run time with nn::ro, Super Smash Bros. Ultimate's fighter code), rewritten as an NSO of the same layout would be. nso.py checks the file
# against its header before anything is allocated (a damaged module stops here with a [RED] line)
MOD = nso.cli_read(src)
ORIG_TEXT = bytes(MOD.image[:MOD.text_end]) # the text as the file has it, before any relayout, cut or site: <name>.changed.tsv compares against it
# Horizon maps modules at 4 KB, Apple hosts at 16 KB (W^X / signed __TEXT): move ro and data up by whole 4 KB pages when data would share the code's 16 KB page (mod_layout.py)
try: MOD, _relayout_D, _relayout_notes = mod_layout.relayout_module(MOD)
except mod_layout.Error as e: sys.exit(f'[RED] {NAME}: {e}')
if _relayout_D: print(f'{NAME}: ' + '; '.join(_relayout_notes))
bss = MOD.bss
# Every jump between the patch area and the code is a B (±128 MB). A patch area appended after the image (with bss) cannot reach the code when it would start beyond 112 MB (leaving 16 MB for the patch area): Metroid Dread's main has about 1.8 GB of bss (the engine's static heap); Engage's main starts its patch area at about 103 MB and keeps it after the image.
# The patch area then sits FRONT bytes before the module base (PATCH_OFF is negative), and the output file holds only text + ro + data (FILE_IMAGE_LEN) followed by the patch area; the loader supplies zero pages for bss and the key page (IMAGE_SIZE is the whole image).
@@ -63,7 +68,6 @@ if TWO:
elif BIG_TEXT: FRONT = int(os.environ.get('DM_PATCH_FRONT', '0'), 0) or (0x8000000 - 0x10000 - MOD.text_end) & ~0xFFFF
SPLIT = (0x8000000 - FRONT - 0x100000 if GAP else max(0x8000000 - FRONT - 0x100000, BACK_MIN)) if TWO else None
IMG = MOD.image
ORIG_TEXT = bytes(IMG[:MOD.text_end]) # the text as the file has it, before any cut or site: <name>.changed.tsv compares against it
if not FAR: IMG.extend(bytes(bss))
TEXT_END = MOD.text_end
RO_OFF, DATA_OFF = MOD.segments[1][0], MOD.segments[2][0]
+215
View File
@@ -0,0 +1,215 @@
"""mod_layout: any NSO or NRO whose data shares the code's 16 KB page gets ro and data moved up in patch_nso.py, with every reference between text and the moved part following them
(FINAL FANTASY VIII Remastered's Math.nro: text, ro and data of 4 KB each). Images here are built by hand."""
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
import mod_layout # noqa: E402
import nso # noqa: E402
import nso_code # noqa: E402
from nso_asm import ADRP # noqa: E402
RET = 0xd65f03c0
RO, DATA, SIZE = 0x1000, 0x2000, 0x3000
MOD0, DYN, EHH, EHF, RELA, SYMTAB, STRTAB, LIT = 0x1040, 0x2008, 0x1600, 0x1700, 0x1100, 0x1200, 0x1300, 0x1500
FN = 0x80
def adr(d, pc, to): imm = (to - pc) & 0x1FFFFF; return 0x10000000 | (imm & 3) << 29 | (imm >> 2) << 5 | d
def ldr_lit(t, pc, to): return 0x58000000 | (((to - pc) >> 2) & 0x7FFFF) << 5 | t
def math_nro():
out = bytearray(SIZE)
out[0x10:0x14] = b'NRO0'
struct.pack_into('<I', out, 4, MOD0)
struct.pack_into('<II', out, 0x18, SIZE, 0)
struct.pack_into('<6I', out, 0x20, 0, RO, RO, DATA - RO, DATA, SIZE - DATA)
# a function reaching ro and data, a text adrp, an in-text literal load to an inline pool whose word mimics adrp into ro, and an unallocated 0xDC word
pool = FN + 0x20
code = [ADRP(0, FN, 0x2100), ldr_lit(1, FN + 4, LIT), adr(2, FN + 8, LIT), ADRP(3, FN + 12, FN),
ldr_lit(4, FN + 16, pool), RET, 0xDC000000, 0, ADRP(5, pool, 0x2100), 0]
struct.pack_into(f'<{len(code)}I', out, FN, *code)
# MOD0 in ro: dynamic, bss start / end, eh_frame_hdr start / end, module object
out[MOD0:MOD0 + 4] = b'MOD0'
struct.pack_into('<6i', out, MOD0 + 4, DYN - MOD0, SIZE - MOD0, SIZE - MOD0, EHH - MOD0, EHH + 20 - MOD0, 0x2200 - MOD0)
for i, (tag, v) in enumerate(((7, RELA), (8, 48), (9, 24), (6, SYMTAB), (5, STRTAB), (10, 12), (12, FN), (0, 0))):
struct.pack_into('<qQ', out, DYN + 16 * i, tag, v)
struct.pack_into('<QQq', out, RELA, 0x2100, 1027, FN) # RELATIVE to text: stays
struct.pack_into('<QQq', out, RELA + 24, 0x2108, 1027, LIT) # RELATIVE to ro: moves
struct.pack_into('<IBBHQQ', out, SYMTAB + 24, 1, 0x11, 0, 1, 0x2100, 8) # data symbol: moves
struct.pack_into('<IBBHQQ', out, SYMTAB + 48, 3, 0x12, 0, 1, FN, 24) # function symbol: stays
struct.pack_into('<IBBHQQ', out, SYMTAB + 72, 5, 0x16, 0, 1, 0x1800, 8) # STT_TLS symbol (>= ro): must stay
out[STRTAB:STRTAB + 12] = b'\0d\0f\0t\0\0\0\0\0\0'
# .eh_frame_hdr (pcrel eh_frame pointer, datarel table) and one zR CIE + FDE for the function
out[EHH:EHH + 4] = bytes((1, 0x1b, 3, 0x3b))
struct.pack_into('<iI', out, EHH + 4, EHF - (EHH + 4), 1)
struct.pack_into('<ii', out, EHH + 12, FN - EHH, EHF + 20 - EHH)
struct.pack_into('<II', out, EHF, 16, 0)
out[EHF + 8:EHF + 17] = b'\x01zR\0\x04\x78\x1e\x01\x1b'
struct.pack_into('<IIiIB', out, EHF + 20, 16, EHF + 24 - EHF, FN - (EHF + 28), 24, 0)
return out
def pack_nso(text, ro, data, ro_off=None, data_off=None, bss=0):
"""Build an uncompressed NSO0 file from text, ro and data segments."""
ro_off = len(text) if ro_off is None else ro_off
data_off = ro_off + len(ro) if data_off is None else data_off
hdr = bytearray(0x100)
hdr[:4] = b'NSO0'
fo_t, fo_r, fo_d = 0x100, 0x100 + len(text), 0x100 + len(text) + len(ro)
struct.pack_into('<III', hdr, 0x10, fo_t, 0, len(text))
struct.pack_into('<III', hdr, 0x20, fo_r, ro_off, len(ro))
struct.pack_into('<IIII', hdr, 0x30, fo_d, data_off, len(data), bss)
struct.pack_into('<III', hdr, 0x60, len(text), len(ro), len(data))
return bytes(hdr) + bytes(text) + bytes(ro) + bytes(data)
def small_nso():
"""An NSO with text=0x11000, ro=0x1000, data=0x1000 (data at 0x12000 < 0x14000), MOD0 in text, .eh_frame_hdr and DT_RELR."""
tsz, ro, do, end = 0x11000, 0x11000, 0x12000, 0x13000
m0, fn = 0x40, 0x100
dyn, relr, symtab, strtab, ehh, ehf = do + 0x10, ro + 0x100, ro + 0x200, ro + 0x300, ro + 0x400, ro + 0x500
slot0, slot2 = do + 0x200, do + 0x210
img = bytearray(end)
struct.pack_into('<I', img, 4, m0)
img[m0:m0 + 4] = b'MOD0'
struct.pack_into('<6i', img, m0 + 4, dyn - m0, end - m0, end + 0x1000 - m0, ehh - m0, ehh + 20 - m0, do + 0x300 - m0)
struct.pack_into('<3I', img, fn, ADRP(0, fn, slot0), adr(1, fn + 4, ro + 0x20), RET)
for i, (tag, v) in enumerate(((36, relr), (35, 16), (6, symtab), (5, strtab), (10, 8), (0, 0))):
struct.pack_into('<qQ', img, dyn + 16 * i, tag, v)
# DT_RELR: slot0 (start) + bitmap bit 2 -> slot0 + 16 = slot2
struct.pack_into('<QQ', img, relr, slot0, (1 << 2) | 1)
struct.pack_into('<Q', img, slot0, fn) # points into text: stays
struct.pack_into('<Q', img, slot2, ro + 0x20) # points into ro: moves
struct.pack_into('<IBBHQQ', img, symtab + 24, 1, 0x11, 0, 1, slot0, 8)
img[strtab:strtab + 8] = b'\0g\0\0\0\0\0\0'
img[ehh:ehh + 4] = bytes((1, 0x1b, 3, 0x3b))
struct.pack_into('<iI', img, ehh + 4, ehf - (ehh + 4), 1)
struct.pack_into('<ii', img, ehh + 12, fn - ehh, ehf + 20 - ehh)
struct.pack_into('<II', img, ehf, 16, 0)
img[ehf + 8:ehf + 17] = b'\x01zR\0\x04\x78\x1e\x01\x1b'
struct.pack_into('<IIiIB', img, ehf + 20, 16, ehf + 24 - ehf, fn - (ehf + 28), 12, 0)
return pack_nso(img[:tsz], img[ro:do], img[do:end], ro_off=ro, data_off=do, bss=0x1000), (tsz, ro, do, m0, fn, dyn, relr, slot0, slot2)
class Layout(unittest.TestCase):
def setUp(self):
self.old_bytes = bytes(math_nro())
self.old_mod = nso.load(self.old_bytes, 'Math')
self.new_mod, self.D, _ = mod_layout.relayout_module(self.old_mod)
def test_data_on_its_own_16k_page(self):
self.assertEqual(self.D, 0x2000)
(t, tsz), (ro, _), (do, dsz) = self.new_mod.segments
self.assertEqual((t, tsz, ro, do, dsz), (0, 0x1000, 0x3000, 0x4000, 0x1000))
self.assertGreaterEqual(do, (tsz + 0x3FFF) & ~0x3FFF)
self.assertEqual(self.new_mod.image[RO:RO + self.D], bytes(self.D))
# The embedded NRO header stays self-consistent and loadable by nso.load()
reloaded = nso.load(bytes(self.new_mod.image), 'Math')
self.assertEqual(reloaded.segments, ((0, 0x3000), (0x3000, 0x1000), (0x4000, 0x1000)))
self.assertEqual(mod_layout.relayout_module(self.new_mod)[1], 0)
def test_code_references_and_inline_pool(self):
D = self.D
pool = FN + 0x20
got = struct.unpack_from('<10I', self.new_mod.image, FN)
self.assertEqual(got[:6], (ADRP(0, FN, 0x2100 + D), ldr_lit(1, FN + 4, LIT + D), adr(2, FN + 8, LIT + D),
ADRP(3, FN + 12, FN), ldr_lit(4, FN + 16, pool), RET))
self.assertEqual(got[6], 0xDC000000) # unallocated opc=3 V=1 untouched
self.assertEqual(got[8], ADRP(5, pool, 0x2100)) # inline literal pool word untouched
def test_tables_and_tls_symbol(self):
D, n = self.D, self.new_mod.image
m0 = struct.unpack_from('<I', n, 4)[0]
self.assertEqual(m0, MOD0 + D)
self.assertEqual(struct.unpack_from('<i', n, m0 + 4)[0], DYN - MOD0) # MOD0 and dynamic moved together
tags = dict(struct.unpack_from('<qQ', n, DYN + D + 16 * i) for i in range(7))
self.assertEqual((tags[7], tags[6], tags[5], tags[12]), (RELA + D, SYMTAB + D, STRTAB + D, FN))
self.assertEqual(struct.unpack_from('<QQq', n, RELA + D), (0x2100 + D, 1027, FN))
self.assertEqual(struct.unpack_from('<QQq', n, RELA + D + 24), (0x2108 + D, 1027, LIT + D))
self.assertEqual(struct.unpack_from('<Q', n, SYMTAB + D + 24 + 8)[0], 0x2100 + D)
self.assertEqual(struct.unpack_from('<Q', n, SYMTAB + D + 48 + 8)[0], FN)
self.assertEqual(struct.unpack_from('<Q', n, SYMTAB + D + 72 + 8)[0], 0x1800) # STT_TLS not shifted
self.assertEqual(nso_code.fde_ranges(bytearray(n)), nso_code.fde_ranges(bytearray(self.old_bytes)))
self.assertEqual(nso_code.fde_ranges(bytearray(n)), [(FN, FN + 24)])
def test_nso_mod0_in_text_and_relr(self):
raw, (tsz, ro, do, m0, fn, dyn, relr, slot0, slot2) = small_nso()
mod = nso.load(raw, 'small')
out, D, _ = mod_layout.relayout_module(mod)
self.assertEqual(D, 0x2000)
self.assertEqual(out.segments, ((0, tsz), (ro + D, 0x1000), (do + D, 0x1000)))
self.assertEqual(struct.unpack_from('<I', out.image, 4)[0], m0) # MOD0 in text stays
self.assertEqual(struct.unpack_from('<i', out.image, m0 + 4)[0], dyn + D - m0) # MOD0 -> dynamic shifts
self.assertEqual(struct.unpack_from('<2I', out.image, fn), (ADRP(0, fn, slot0 + D), adr(1, fn + 4, ro + 0x20 + D)))
self.assertEqual(struct.unpack_from('<QQ', out.image, relr + D), (slot0 + D, (1 << 2) | 1))
self.assertEqual(struct.unpack_from('<Q', out.image, slot0 + D)[0], fn)
self.assertEqual(struct.unpack_from('<Q', out.image, slot2 + D)[0], ro + 0x20 + D)
def test_eh_frame_empty_aug_lsda_lpstart_and_omitted_table(self):
d = bytearray(math_nro())
lsda, cfi_magic = 0x1800, 0xCAFEBABE
# Header: penc=0x1b (pcrel sdata4), cenc=0x0b (sdata4), tenc=0xff (omitted search table)
d[EHH:EHH + 4] = bytes((1, 0x1b, 0x0b, 0xff))
struct.pack_into('<ii', d, EHH + 4, EHF - (EHH + 4), 2)
# CIE: zPLR (P=0x1b pcrel to FN, L=0x1b pcrel, R=0x1b pcrel)
cie_body = bytearray(b'\x01zPLR\0\x04\x78\x1e')
aug_data = bytearray([0x1b]) + struct.pack('<i', FN - (EHF + 8 + len(cie_body) + 2)) + bytes([0x1b, 0x1b])
cie_body += bytes([len(aug_data)]) + aug_data
while (len(cie_body) + 4) % 4: cie_body.append(0)
struct.pack_into('<II', d, EHF, len(cie_body) + 4, 0)
d[EHF + 8:EHF + 8 + len(cie_body)] = cie_body
# FDE 1: aug_len=0 followed by CFI magic (must NOT be touched)
fde1 = EHF + 8 + len(cie_body)
struct.pack_into('<IIiIBI', d, fde1, 20, fde1 + 4 - EHF, FN - (fde1 + 8), 12, 0, cfi_magic)
# FDE 2: aug_len=4 pointing to LSDA with lpe=0x1b (pcrel lpstart -> FN)
fde2 = fde1 + 24
struct.pack_into('<IIiIBi', d, fde2, 20, fde2 + 4 - EHF, FN + 12 - (fde2 + 8), 12, 4, lsda - (fde2 + 17))
struct.pack_into('<I', d, fde2 + 24, 0)
d[lsda] = 0x1b
struct.pack_into('<i', d, lsda + 1, FN - (lsda + 1))
out, D, _ = mod_layout.relayout_module(nso.load(bytes(d), 'eh'))
self.assertEqual(D, 0x2000)
# FDE 1 CFI magic preserved; FDE 1 pc_begin moved by -D; LSDA lpstart moved by -D
self.assertEqual(struct.unpack_from('<I', out.image, fde1 + D + 17)[0], cfi_magic)
self.assertEqual(struct.unpack_from('<i', out.image, fde1 + D + 8)[0], FN - (fde1 + D + 8))
self.assertEqual(struct.unpack_from('<i', out.image, lsda + D + 1)[0], FN - (lsda + D + 1))
def test_fitting_module_unchanged(self):
ok = bytearray(0x5000); ok[0x10:0x14] = b'NRO0'
struct.pack_into('<II', ok, 0x18, 0x5000, 0)
struct.pack_into('<6I', ok, 0x20, 0, 0x2000, 0x2000, 0x2000, 0x4000, 0x1000)
mod = nso.load(bytes(ok), 'ok')
self.assertEqual(mod_layout.relayout_module(mod), (mod, 0, []))
def test_patch_nso_end_to_end_nro_and_nso(self):
tmp = tempfile.TemporaryDirectory(); self.addCleanup(tmp.cleanup)
root = Path(tmp.name)
nro_path = root / 'nro0.nro'; nro_path.write_bytes(self.old_bytes)
nso_raw, _ = small_nso()
nso_path = root / 'subsdk9'; nso_path.write_bytes(nso_raw)
env = dict(os.environ, DM_GAME='01008B900DC0A000', DM_REWRITE_J='1')
for path, name, exp_te, exp_ro, exp_do in ((nro_path, 'nro0', 0x1000, 0x3000, 0x4000),
(nso_path, 'subsdk9', 0x11000, 0x13000, 0x14000)):
out_dir = root / f'out_{name}'; out_dir.mkdir()
p = subprocess.run([sys.executable, str(TOOLS / 'patch_nso.py'), str(path), str(out_dir), name],
env=env, capture_output=True, text=True)
self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
hdr = dict(ln[2:].split() for ln in (out_dir / f'{name}.fixups.tsv').read_text().splitlines() if ln.startswith('# '))
self.assertEqual((int(hdr['TEXT_END'], 16), int(hdr['RO_OFF'], 16), int(hdr['DATA_OFF'], 16)), (exp_te, exp_ro, exp_do))
self.assertGreaterEqual(exp_do, (exp_te + 0x3FFF) & ~0x3FFF)
if name == 'nro0':
self.assertEqual(nro_path.read_bytes(), self.old_bytes) # on-disk NRO untouched
patched = (out_dir / 'nro0.patched.bin').read_bytes()
self.assertEqual(struct.unpack_from('<I', patched, 0x30)[0], exp_do)
if __name__ == '__main__': unittest.main()
+2 -1
View File
@@ -25,13 +25,14 @@ class NroHeader(unittest.TestCase):
def check_rewrite(self, first_fde, header_word):
# A real function starts immediately after the NRO header. Both it and the build ID name x18.
raw = image({first_fde: [0xaa0003f2, RET]})
raw.extend(bytes(0x1000)) # data on its own 16 KB page (0x4000), so patch_nso.py does not relayout the header offsets
struct.pack_into('<II', raw, 0x80, 0xaa0003f2, RET) # mov x18, x0; ret, with or without an FDE
raw[0x1100:0x111c] = raw[0x20:0x3c]
struct.pack_into('<I', raw, 4, 0x1100)
struct.pack_into('<ii', raw, 0x1110, 0x3000 - 0x1100, 0x3014 - 0x1100)
raw[0x10:0x14] = b'NRO0'
struct.pack_into('<I', raw, 0x18, len(raw))
struct.pack_into('<6I', raw, 0x20, 0, 0x1000, 0x1000, 0x2000, 0x3000, 0x1000)
struct.pack_into('<6I', raw, 0x20, 0, 0x1000, 0x1000, 0x3000, 0x4000, 0x1000)
struct.pack_into('<I', raw, 0x38, 0)
struct.pack_into('<I', raw, 0x44, header_word)
with tempfile.TemporaryDirectory() as tmp:
+1
View File
@@ -185,6 +185,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `SetHeapSize OOM: req 0x600000 > cap 0`, followed by an SDK abort in `nninitStartup` on the first provisional boot. → [Provisional Unreal layout leaves no heap](../reference/memory.md#provisional-unreal-layout-leaves-no-heap)
- `nnMain` returns right after `nv::InitializeGraphics`, with no error (Hyrule Warriors: Age of Calamity); `[mem] SetHeapSize … + modules … > app pool` (Monster Hunter Rise), `[mem] SetHeapSize … + modules 0x5c00000 > app pool` (Catherine: Full Body), an `nn::diag` abort in `nninitStartup` after `[mem] SetHeapSize 0xc9400000 + modules 0x4400000 > app pool 0xcd500000` (MIO: Memories in Orbit; the host now logs `[mem] SetHeapSize … > app pool … less used memory …`); `SetHeapSize` asks for almost the whole application pool and fails at boot (Metroid Dread: 0xc9400000, larger than the heap region); the memory pool for the game's 96 MB GPU heap has no storage (`MemoryPoolInitialize` red line), then a null read at `main+0x2eb954` (Catherine: Full Body); heap allocations fail late in a busy scene. → [Heap sized from the application pool less used memory](../reference/memory.md#heap-sized-from-the-application-pool-less-used-memory)
- `SetHeapSize OOM: req 0xffffffffe0000000 > cap 0xd0000000`, followed by an abort when allocating the launcher NRO. → [Offline NRO copies are not additional guest memory](../reference/memory.md#offline-nro-copies-are-not-additional-guest-memory)
- `CRASH sig=10 addr=nro<N>+0x… pc=relocate+…` with `lr=nro_load+…` under `h_ro_LoadModule` (or in `relocate` at startup for an NSO), at the first load of a module whose data starts below `text_end` rounded up to 16 KB; `x9` points at a RELA entry of type `0x403` (`R_AARCH64_RELATIVE`). → [Module data on the code's 16 KB page](../reference/memory.md#module-data-on-the-codes-16-kb-page)
- repeated `[RED] MapMemory refused (0xd401)` for a stack source inside a loaded NRO's writable data, then an abort in `MapAliasStack` / `CreateThread`. → [Thread stacks backed by active NRO data](../reference/memory.md#thread-stacks-backed-by-active-nro-data)
- `SetHeapSize OOM: req 0x120000000 > cap 0xd0000000`, then `Break#1 reason=0` in `nninitStartup`, with a backtrace through `nn::os::SetMemoryHeapSize` (`sdk+0x967a4`). → [A heap request beyond the heap region returns ResultOutOfMemory](../reference/memory.md#a-heap-request-beyond-the-heap-region-returns-resultoutofmemory)
- a provisional profile's heap check reports "the heap request did not fit; set mem_reserve", the build finishes, and the game still stops at its first run: `SetHeapSize OOM: req 0x18ce00000 > cap 0xb8000000`, then `CRASH sig=10` (SIGBUS) in `nninitStartup` on the heap it never got. → [The heap check grows the block around the profile's alias region](../reference/memory.md#the-heap-check-grows-the-block-around-the-profiles-alias-region)
+8
View File
@@ -71,6 +71,14 @@ The guest address space, heaps, pools, virtual address memory and the allocators
- **Found on:** [FINAL FANTASY X/X-2 HD Remaster](../../dm/games/0100BC300CB48000/README.md); after the fix its startup heap is 3.08 GB.
- **Check:** the memory SVC tests compare used-memory queries with an ordinary large-bss module and a larger NRO present together.
### Module data on the code's 16 KB page
- **Symptom:** `CRASH sig=10 addr=nro<N>+0x… pc=relocate+…` with `lr=nro_load+…` under `h_ro_LoadModule` (or in `relocate` at startup for an NSO), at the first load of a module whose data starts below `text_end` rounded up to 16 KB; `x9` points at a RELA entry of type `0x403` (`R_AARCH64_RELATIVE`).
- **Cause:** Horizon maps modules at 4 KB, the hosts at 16 KB. `map_image` (`loader.c`) seals `[0, text_end rounded up to 16 KB)` read + execute, and `gen_embed.py` puts the same range in the iOS executable's `__TEXT`, so any NSO or NRO whose data starts below that boundary has read-only data, and the first relocation into it faults. FINAL FANTASY VIII Remastered's Math.nro is text, ro and data of 4 KB each (data at `0x2000`); its Platform.nro has data at `0x3000`.
- **Fix:** `dm/tools/mod_layout.py`, run by `patch_nso.py` on every NSO and NRO right after `nso.load()`, moves ro and data (and bss) up by whole 4 KB pages until data starts on a 16 KB page of its own, keeping `TEXT_END` at the true end of code and leaving on-disk `.nro` files and `nro.tsv` untouched. It rewrites the NRO header (when `NRO0`), `MOD0`, the dynamic tags, symbol values (excluding `STT_TLS`), RELA / JMPREL / RELR, the text's `adrp` / `adr` / literal loads into the moved part (skipping the `MOD0` offset at `+4` and in-text literal pools), and `.eh_frame_hdr` / `.eh_frame` (including LSDA `lpstart`). `read_layout` in `loader.c` stops with a message naming the module, not a SIGBUS, on a module rewritten before the fix.
- **Found on:** FINAL FANTASY VIII Remastered (`01008B900DC0A000`; Math.nro and Platform.nro of its 14 NROs).
- **Check:** `dm/tools/tests/test_mod_layout.py` covers synthetic NRO and NSO images, `patch_nso.py` end-to-end, `MOD0` in text, `DT_RELR`, inline literal pools, `STT_TLS`, and `.eh_frame` / LSDA edge cases.
### Thread stacks backed by active NRO data
- **Symptom:** repeated `[RED] MapMemory refused (0xd401)` for a stack source inside a loaded NRO's writable data, then an abort in `MapAliasStack` / `CreateThread`.
+1 -1
View File
@@ -1689,7 +1689,7 @@ def rewrite(py, repo, exe_dir, out, env, logs, g, provisional=False):
# the repository profile's build rows decide which builds the rewriter treats as the game's own (SDK-wide function patches skip those), and its snowdrop_pools the sizes of those cuts, so they are inputs too
try: own = [l for l in (repo / 'dm/games' / Path(env.get('DM_GAME') or '-').name / 'game.tsv').read_text(encoding='utf-8').splitlines() if l.startswith(('build\t', 'snowdrop_pools\t'))]
except OSError: own = []
key = fingerprint(('files', [repo / 'dm/tools' / f for f in ('patch_nso.py', 'jump_solver.py', 'nso.py', 'nso_code.py', 'nso_asm.py', 'nso_syms.py', 'nso_match.py', 'ue_cvar.py', 'ue_malloc.py', 'ue_region.py', 'ue_ring.py', 'snowdrop_pools.py', 'loader_census.py', 'fps_target.py', 'monolith_fps.py', 'ue_fixed_rate.py', 'unity_fps.py', 'unity_bucket.py')] + patch_files(repo, exe_dir, mods, env.get('DM_GAME')) + list(src.values()) + ([manifest] if manifest.is_file() else [])), names, capstone.__version__,
key = fingerprint(('files', [repo / 'dm/tools' / f for f in ('patch_nso.py', 'jump_solver.py', 'nso.py', 'mod_layout.py', 'nso_code.py', 'nso_asm.py', 'nso_syms.py', 'nso_match.py', 'ue_cvar.py', 'ue_malloc.py', 'ue_region.py', 'ue_ring.py', 'snowdrop_pools.py', 'loader_census.py', 'fps_target.py', 'monolith_fps.py', 'ue_fixed_rate.py', 'unity_fps.py', 'unity_bucket.py')] + patch_files(repo, exe_dir, mods, env.get('DM_GAME')) + list(src.values()) + ([manifest] if manifest.is_file() else [])), names, capstone.__version__,
{k: env.get(k) for k in ('DM_PATCH_FRONT', 'DM_GAME')}, own)
if all((out / f'{m}.patched.bin').is_file() for m in names) and reused(kf, key) is not None:
PROG.end(f'{", ".join(mods)}{f" and {len(nros)} NROs" if nros else ""}, reused (inputs unchanged)')
+1 -1
View File
@@ -97,7 +97,7 @@ rfs = shader_lib.romfs
ROOT = Path(os.environ.get('REGRESS_ROOT', ''))
GAMES = Path(os.environ.get('REGRESS_GAMES', ''))
HOST_DIRS = ('dm/host', 'dm/gfx', 'dm/gfx/nvn', 'dm/gfx/nvn/include', 'dm/gfx/tex', 'dm/gfx/vk', 'dm/gfx/gl') # as build_ipa_from_nsp.py: the host's sources and headers
REWRITER = ('dm/tools/patch_nso.py', 'dm/tools/jump_solver.py', 'dm/tools/nso.py', 'dm/tools/nso_code.py', 'dm/tools/nso_asm.py', 'dm/tools/nso_match.py', 'dm/tools/sdk_patches.py', 'dm/tools/engine_patches.py', 'dm/tools/ue_cvar.py', 'dm/tools/ue_malloc.py', 'dm/tools/ue_region.py', 'dm/tools/ue_ring.py', 'dm/tools/fps_target.py', 'dm/tools/monolith_fps.py', 'dm/tools/loader_census.py', 'dm/tools/ue_fixed_rate.py', 'dm/tools/unity_fps.py', 'dm/tools/unity_bucket.py', 'dm/tools/snowdrop_pools.py')
REWRITER = ('dm/tools/patch_nso.py', 'dm/tools/jump_solver.py', 'dm/tools/nso.py', 'dm/tools/mod_layout.py', 'dm/tools/nso_code.py', 'dm/tools/nso_asm.py', 'dm/tools/nso_match.py', 'dm/tools/sdk_patches.py', 'dm/tools/engine_patches.py', 'dm/tools/ue_cvar.py', 'dm/tools/ue_malloc.py', 'dm/tools/ue_region.py', 'dm/tools/ue_ring.py', 'dm/tools/fps_target.py', 'dm/tools/monolith_fps.py', 'dm/tools/loader_census.py', 'dm/tools/ue_fixed_rate.py', 'dm/tools/unity_fps.py', 'dm/tools/unity_bucket.py', 'dm/tools/snowdrop_pools.py')
HEAVY_EXE = {'clang', 'make', 'xcodebuild', 'ld', 'ld64', 'swift-frontend', 'dotnet', 'metal', 'metal-tt', 'air-tt', 'applegpu-nt', 'dmsh_xlate', 'spirv-cross'} # jobs that skew a measurement
HEAVY_PY = r'(dmsh_build|shader_split|own_compilers|patch_nso|vk_shaders)\.py' # (the shared measuring rule)
# Tolerances, from runs of one revision against itself (docs/development.md, The regression harness)