Android port (Adreno): Vulkan backend, GameActivity app, touch HUD, lifecycle, minimap quest goals

- host/android: Vulkan replay backend (nvn_vk.c) with pipeline/descriptor caching, ADPF,
  AChoreographer present link; Linux compat layer; Makefile.android (headless dmhost + APK lib)
- android/app: GameActivity shell without Gradle (build_apk.sh), AAudio output, touch HUD port
  (touch_app.c + TouchOverlay.java, three layers: body / joystick / minimap goals),
  lifecycle save-on-background like iOS, art_from_ipa.py for touch / HUD / mapgoal art
- touch: shared touch controls moved from ios/Sources to dm/touch
- patch_nso.py Android ruleset, dmsh_vk.py shader pack, DM_TOUCH_PRODUCT defaults
- hle_audio: AAudio resume waits through STARTING and reopens once on failure
- .gitignore: local resources/ (original game data) never committed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-14 14:55:05 +09:00
co-authored by Claude Opus 5.5
parent 5bc5a01087
commit 4d91f80bae
106 changed files with 7009 additions and 181 deletions
+1
View File
@@ -55,6 +55,7 @@ def build(out, names):
text, wsegs = [], []
for n in names:
hdr = dict(l[2:].split() for l in open(os.path.join(out, n + '.fixups.tsv')) if l.startswith('# '))
assert hdr.get('ABI', 'apple') == 'apple', f'{n}: 非苹果 ABI 产物({hdr["ABI"]}),不能打进苹果包 | non-Apple ABI build output, cannot go into an Apple package'
te, po = int(hdr['TEXT_END'], 16), int(hdr['PATCH_OFF'], 16)
img = open(os.path.join(out, n + '.patched.bin'), 'rb').read(); sz = len(img); a, end = r16(te), r16(sz)
assert po % PG == 0 and a <= po <= end, (n, hex(te), hex(po), hex(sz))
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
# 从苹果包(IPA)里的 Guest.framework 反推改写前的模块映像,写成未压缩 NSO:给拿不到原 ExeFS、只有可运行 IPA 的场合重出别的 ABI(如 DM_ABI=android)。
# 做法:按 guest_dylib.py 的节布局拼回 patched.bin;text 里每条跳进补丁区的 b 按补丁块形态还原原指令(patch_nso.py 各 site_* 的逆);
# 参数位按 patch_nso.py 的 PARAMS 表还原两条原字;最后按包内 <名>.cuts.tsv 把剪口(含代码 / 数据)还原成原字节。
# 判据:用同一规则域(IPA 为 touch:DM_RULESET=touch-run-v4)苹果 ABI 重新改写,patched.bin / fixups / gates / cuts 须与包内逐字节一致(--check 自动做)。
# 局限:NSO 文件本身(lz4 压缩、表头校验值)复原不出,extract_game.sh 里的原文件 SHA256 对不上;包里没有 subsdk0(视频库,宿主不加载);
# sdk 的构建号包里没有,写全 0(改写器只按构建号查 main 的登记表)。
# 用法:ipa_unpatch.py <IPA 或解开的 DmIOS.app 目录> <输出目录> [--check] 输出 <输出目录>/{main,sdk}
# Reconstruct the pre-rewrite module images from Guest.framework inside an Apple package (IPA) and write them as uncompressed NSOs: for when the original ExeFS is unavailable and only a runnable IPA is, so another ABI (e.g. DM_ABI=android) can be built.
# Method: reassemble patched.bin from the section layout of guest_dylib.py; for every b in text that jumps into the patch area, restore the original instruction from the patch block's shape (the inverse of each site_* in patch_nso.py);
# parameter slots get both original words back from patch_nso.py's PARAMS table; finally the package's <name>.cuts.tsv restores cuts (code / data) to their original bytes.
# Criterion: rewriting again with the same rule domain (the IPA is touch: DM_RULESET=touch-run-v4) and the Apple ABI must reproduce patched.bin / fixups / gates / cuts byte for byte (--check does this).
# Limits: the NSO file itself (lz4 compression, header hashes) cannot be recovered, so the original-file SHA256 in extract_game.sh will not match; the package has no subsdk0 (video library, not loaded by the host);
# the package does not carry sdk's build ID, so it is written as all zeros (the rewriter only looks up main's registries by build ID).
# Usage: ipa_unpatch.py <IPA or unpacked DmIOS.app directory> <output dir> [--check] writes <output dir>/{main,sdk}
import os, re, struct, subprocess, sys, tempfile, zipfile
from itertools import combinations
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
HERE = os.path.dirname(os.path.abspath(__file__))
MODS = ('main', 'sdk')
BUILD_IDS = {'main': 'db0507f36b84200ac05f75d76ed5026f'}
PG = 0x4000
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM); md.detail = True
W = lambda b, o: struct.unpack_from('<I', b, o)[0]
r16 = lambda x: (x + PG - 1) & ~(PG - 1)
def dis(w, pc):
l = list(md.disasm(struct.pack('<I', w), pc)); assert l, f'{pc:#x} {w:08x}'; return l[0]
def bt(w, pc):
"""b / bl 目标;不是 b 返回 None。 | Target of a b; None if not a b."""
if w & 0xFC000000 != 0x14000000: return None
return pc + 4 * (((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000)
def read_app(src):
"""{相对路径: 字节},只取 dm/ 与 Guest。 | {relative path: bytes}, dm/ and Guest only."""
want = lambda p: p.startswith('dm/') or p == 'Frameworks/Guest.framework/Guest'
out = {}
if os.path.isdir(src):
for p in ['Frameworks/Guest.framework/Guest'] + ['dm/' + f for f in os.listdir(os.path.join(src, 'dm'))]:
out[p] = open(os.path.join(src, p), 'rb').read()
else:
with zipfile.ZipFile(src) as z:
for n in z.namelist():
m = re.match(r'Payload/[^/]+\.app/(.*)$', n)
if m and want(m.group(1)) and not n.endswith('/'): out[m.group(1)] = z.read(n)
return out
def sections(guest):
"""Mach-O 节 → {节名: 字节}(guest_dylib.py 写法:文件偏移 = 地址)。 | Mach-O sections → {name: bytes} (guest_dylib.py layout: file offset = address)."""
assert W(guest, 0) == 0xFEEDFACF
ncmds = W(guest, 16); o = 32; out = {}
for _ in range(ncmds):
cmd, sz = struct.unpack_from('<II', guest, o)
if cmd == 0x19:
seg = guest[o + 8:o + 24].rstrip(b'\0').decode(); ns = W(guest, o + 64)
for i in range(ns):
so = o + 72 + 80 * i
sn = guest[so:so + 16].rstrip(b'\0').decode()
addr, size = struct.unpack_from('<QQ', guest, so + 32)
out[sn if sn != '__img' else seg] = guest[addr:addr + size]
o += sz
return out
def header(txt):
return {k: int(v, 0) for k, v in (l[2:].split() for l in txt.splitlines() if l.startswith('# ') and l.split()[1] != 'BUILD_ID')}
def params_table():
"""patch_nso.py 的 PARAMS:[(A, 原字 A, B, 原字 B)]。 | patch_nso.py's PARAMS: [(A, word A, B, word B)]."""
s = open(os.path.join(HERE, 'patch_nso.py'), encoding='utf-8').read()
body = s[s.index('PARAMS = {'):s.index('params = PARAMS.get')]
return [(int(a, 16), int(wa, 16), int(b, 16), int(wb, 16)) for a, wa, b, wb in re.findall(r"\((0x[0-9a-f]+), '([0-9a-f]{8})', (0x[0-9a-f]+), '([0-9a-f]{8})'", body)]
def regs_in(ins):
"""与 patch_nso.regs_in 同。 | Same as patch_nso.regs_in."""
s = {int(n) for n in re.findall(r'\b[xw](\d+)\b', ins.op_str)}
try:
r, w = ins.regs_access()
s |= {int(m.group(1)) for m in (re.fullmatch(r'[xw](\d+)', ins.reg_name(x) or '') for x in r + w) if m}
except Exception: pass
return s
def unsubst(nw, S, pc, T=None):
"""patch_nso.subst 的逆:xS/wS → x18/w18,只在 4 个寄存器字段里找,再用 subst 的判据正向核对。
S、T 是改写器 pick() 挑的「原指令没用到的最小两个寄存器」:候选不得用到 S / T;给了 T(单条指令的块)时还须 pick(候选) == (S, T)。
Inverse of patch_nso.subst. S, T are the two lowest registers unused by the original instruction (patch_nso pick()): a candidate must not use S / T,
and when T is given (single-instruction block) pick(candidate) must equal (S, T)."""
pos = [p for p in (0, 5, 10, 16) if (nw >> p) & 31 == S]
got = []
for k in range(len(pos), 0, -1):
for c in combinations(pos, k):
w = nw
for p in c: w = (w & ~(31 << p)) | (18 << p)
try: ins = dis(w, pc)
except AssertionError: continue
if not re.search(r'\b[xw]18\b', ins.op_str): continue
want = re.sub(r'\b([xw])18\b', lambda m: f'{m.group(1)}{S}', ins.op_str)
if dis(nw, pc).mnemonic != ins.mnemonic or dis(nw, pc).op_str != want: continue
used = regs_in(ins)
if S in used or (T is not None and (T in used or [r for r in range(16) if r not in used and r != 18][:2] != [S, T])): continue
got.append((k, w))
if not got: return None
# 多个候选正向改写都得 nw 时(立即数字段恰为 S,如逻辑立即数的 immr)取替换字段最少的:编码器给的规范编码;--check 的重改写仍须逐字节一致
# When several candidates all rewrite forward to nw (an immediate field happens to equal S, e.g. immr of a logical immediate), take the one with the fewest
# substituted fields: the canonical encoding an assembler emits; --check still requires the re-rewrite to match byte for byte
kmin = min(k for k, _ in got); best = {w for k, w in got if k == kmin}
assert len(best) == 1, f'{pc:#x} {nw:08x} S=x{S}:候选 {[hex(x) for x in best]}'
if len(got) > 1: AMBIG.append(pc)
return best.pop()
AMBIG = []
class Block:
"""补丁块读取器:跳过槽块基址前缀(apple:mrs tpidrro)+ 键页三条,返回 (基址寄存器, 键下标, 后续偏移)。 | Patch block reader."""
def __init__(self, pat, key_idx): self.pat, self.kv = pat, {v: k for k, v in key_idx.items()}
def w(self, o): return W(self.pat, o)
def slot(self, o):
w = self.w(o); assert w & 0xFFFFFFE0 == 0xD53BD060, f'{o:#x} 不是 mrs tpidrro:{w:08x}'
T = w & 31; ldr = self.w(o + 8)
assert self.w(o + 4) & 0x9F000000 == 0x90000000 and ldr & 0xFFC00000 == 0xF9400000 and self.w(o + 12) & 0xFFE0FFFF == 0x8B000000 | (T << 5) | T, f'{o:#x} 键页序列不符'
return T, self.kv[(ldr >> 10) & 0xFFF], o + 16
def restore(name, app, gates):
hdr = header(app[f'dm/{name}.fixups.tsv'].decode())
se = sections(app['Frameworks/Guest.framework/Guest'])
te, po, ko = hdr['TEXT_END'], hdr['PATCH_OFF'], hdr['KEY_PAGE_OFF']
pat = bytearray(se[f'__dm{name}x0'] + se[f'__DM{name}W'] + se[f'__dm{name}x1'])
assert len(se[f'__dm{name}x0']) == r16(te) and len(se[f'__dm{name}x0']) + len(se[f'__DM{name}W']) == po
assert pat[ko:ko + PG] == bytes(PG), '键页不是全 0'
key_idx = {k[4:-4]: v for k, v in hdr.items() if k.startswith('KEY_') and k.endswith('_IDX')}
B = Block(pat, key_idx)
img = bytearray(pat[:ko])
gate_at = {orig: (k, arg) for ret, k, arg, orig in gates}
params = {a: (wa, b, wb) for a, wa, b, wb in params_table()} if name in BUILD_IDS else {}
cuts = []
if f'dm/{name}.cuts.tsv' in app:
for l in app[f'dm/{name}.cuts.tsv'].decode().splitlines():
if l.startswith('#') or not l.strip(): continue
f = l.split('\t'); cuts.append((int(f[0], 16), bytes.fromhex(f[1]), bytes.fromhex(f[2])))
cut_b = {off: nb for off, ob, nb in cuts if len(nb) == 4 and bt(W(nb, 0), off) is not None and bt(W(nb, 0), off) >= po}
st = {}
def put(o, w, kind): struct.pack_into('<I', img, o, w); st[kind] = st.get(kind, 0) + 1
for o in range(0, te & ~3, 4):
w = W(img, o); s = bt(w, o)
if s is None or s < po: continue
if o in cut_b and cut_b[o] == struct.pack('<I', w): st['cut_b'] = st.get('cut_b', 0) + 1; continue # 剪口自带的跳板:最后按 cuts.tsv 还原 | trampoline belonging to a cut: restored from cuts.tsv at the end
if o in params:
wa, b, wb = params[o]; assert W(img, b) == 0xD503201F, f'参数位 B {b:#x} 不是 nop'
put(o, wa, 'param'); struct.pack_into('<I', img, b, wb); continue
h = B.w(s)
if h == 0xA9BF7FE8 or h == 0xA9BF7BFD: # 分支门 / 门 / 观测门 | branch gate / gate / observation gate
q = s + (4 if h == 0xA9BF7FE8 else 0)
assert B.w(q) == 0xA9BF7BFD
T, key, n = B.slot(q + 4); assert T == 30 and key == 'KGATE'
assert B.w(n) == 0xF94003DE and B.w(n + 4) == 0xF94003FD and B.w(n + 8) == 0xD63F03C0 and B.w(n + 12) == 0xA8C17BFD
n += 16
if h == 0xA9BF7FE8: # cbz w8; ldp; b 目标; ldp; 原字; b o+4
assert B.w(n) == 0x34000068 and bt(B.w(n + 20), n + 20) == o + 4; put(o, B.w(n + 16), 'branch_gate')
elif bt(B.w(n), n) == o + 4: # 宿主门:svc / cntpct / cntvct
k, arg = gate_at[o]
put(o, {'svc': 0xD4000001 | arg << 5, 'cntpct': 0xD53BE020 | arg, 'cntvct': 0xD53BE040 | arg}[k], k)
else:
assert bt(B.w(n + 4), n + 4) == o + 4; put(o, B.w(n), 'obs')
continue
if h & 0xFFFFFFE0 == 0xF81F03E0: # stur xR,[sp,#-16]
R = h & 31; h2 = B.w(s + 4)
if R == 16 and h2 == 0xF81E83F1: # 跳转表 br x18
put(o, 0xD61F0240, 'br'); continue
if h2 & 0xFFFFFFE0 == 0xF81E83E0: # msr tpidr_el0, xN:stur T / stur tmp / 基址 T / str N,[T]
T, key, n = B.slot(s + 8); assert key == 'KTLS' and B.w(n) & 0xFFFFFFE0 == 0xF9000000 | (T << 5)
put(o, 0xD51BD040 | (B.w(n) & 31), 'tpidr_w'); continue
N, key, n = B.slot(s + 4) # mrs xN, tpidr_el0 / tpidrro_el0
put(o, {'KTLS': 0xD53BD040, 'KTLR': 0xD53BD060}[key] | N, 'sysreg_r'); continue
assert h & 0xFFC003E0 == 0xA90003E0, f'{o:#x} → {s:#x} 未知块头 {h:08x}' # stp xS, xT, [sp, #save]
S = h & 31; T, key, n = B.slot(s + 4); assert key == 'K18' and T == (h >> 10) & 31
w1 = B.w(n)
if w1 & 0x9F00001F == 0x90000000 | S: # adrp xS → adr / adrp x18
tgt = (n & ~0xFFF) + (((((w1 >> 5) & 0x7FFFF) << 2 | (w1 >> 29) & 3) ^ 0x100000) - 0x100000 << 12)
if B.w(n + 4) & 0xFFC003FF == 0x91000000 | (S << 5) | S:
tgt += (B.w(n + 4) >> 10) & 0xFFF; d = tgt - o
put(o, 0x10000000 | ((d & 3) << 29) | (((d >> 2) & 0x7FFFF) << 5) | 18, 'adr')
else:
d = (tgt >> 12) - (o >> 12)
put(o, 0x90000000 | ((d & 3) << 29) | (((d >> 2) & 0x7FFFF) << 5) | 18, 'adrp')
continue
assert w1 == 0xF9400000 | (T << 5) | S, f'{s:#x} 读槽不符'
n += 4; w2 = B.w(n); m = dis(w2, n).mnemonic
if B.w(n + 4) == 0xF9000000 | (T << 5) | S and B.w(n + 8) & 0xFFC07FFF == 0xA9400000 | (T << 10) | (31 << 5) | S and bt(B.w(n + 12), n + 12) == o + 4:
w0 = unsubst(w2, S, o, T); assert w0 is not None, f'{o:#x} 普通块还原不出 x18'
put(o, w0, 'plain'); continue
if m in ('cbz', 'cbnz', 'tbz', 'tbnz') and w2 & 31 == S and bt(B.w(n + 8), n + 8) == o + 4:
tgt = bt(B.w(n + 16), n + 16); off = (tgt - o) >> 2
nw = ((w2 & 0xFF000000) | ((off & 0x7FFFF) << 5) | 18) if m in ('cbz', 'cbnz') else ((w2 & 0xFFF80000) | ((off & 0x3FFF) << 5) | 18)
put(o, nw, 'cond'); continue
# 独占窗口:块里依次是窗口指令的拷贝,首条即原处那条(窗口首条是独占读,不是分支)
# Exclusive window: the block holds copies of the window instructions in order; the first is the one at the original site (an exclusive load, not a branch)
assert dis(w2, o).mnemonic.startswith(('ldxr', 'ldaxr', 'ldxp', 'ldaxp')), f'{o:#x} 窗口首条 {dis(w2, o).mnemonic}'
w0 = unsubst(w2, S, o); put(o, w2 if w0 is None else w0, 'window')
for off, ob, nb in cuts:
assert bytes(img[off:off + len(nb)]) == nb, f'剪口 {off:#x} 现值 {bytes(img[off:off + len(nb)]).hex()} ≠ 新字节 {nb.hex()}'
img[off:off + len(ob)] = ob
st['cut'] = len(cuts)
return img, hdr, st, pat
def write_nso(path, img, hdr, build_id):
te, ro, da, ko = hdr['TEXT_END'], hdr['RO_OFF'], hdr['DATA_OFF'], hdr['KEY_PAGE_OFF']
segs = [(0, te), (ro, da - ro), (da, ko - da)] # data 拉到键页前、bss 0:映像长 = KEY_PAGE_OFF,改写器算出同一 KEY_PAGE_OFF / PATCH_OFF
h = bytearray(0x100); h[0:4] = b'NSO0'
off = 0x100
for i, (mo, sz) in enumerate(segs): struct.pack_into('<III', h, 0x10 + 0x10 * i, off, mo, sz); off += sz
h[0x40:0x50] = bytes.fromhex(build_id)
struct.pack_into('<III', h, 0x60, *(sz for _, sz in segs))
with open(path, 'wb') as f:
f.write(h)
for mo, sz in segs: f.write(img[mo:mo + sz])
def check(name, out, app, pat):
with tempfile.TemporaryDirectory() as td:
env = dict(os.environ, DM_RULESET='touch-run-v4', DM_ABI='apple'); env.pop('DM_PRIVATE_GATES', None)
r = subprocess.run([sys.executable, os.path.join(HERE, 'patch_nso.py'), os.path.join(out, name), td, name], env=env, capture_output=True, text=True)
if r.returncode: print(r.stdout, r.stderr); return False
got = open(os.path.join(td, f'{name}.patched.bin'), 'rb').read()
ok = got.rstrip(b'\0') == bytes(pat).rstrip(b'\0')
if not ok:
n = min(len(got), len(pat)); bad = [o for o in range(0, n, 4) if got[o:o + 4] != pat[o:o + 4]]
print(f' patched.bin 不一致:{len(bad)} 字,首个 {[hex(x) for x in bad[:8]]}')
for t in ('fixups', 'gates', 'cuts'):
if f'dm/{name}.{t}.tsv' not in app: continue
same = open(os.path.join(td, f'{name}.{t}.tsv'), 'rb').read() == app[f'dm/{name}.{t}.tsv']
print(f' {t}.tsv {"一致" if same else "不一致"}'); ok &= same
return ok
def main():
a = [x for x in sys.argv[1:] if not x.startswith('--')]
if len(a) != 2: sys.exit('用法:ipa_unpatch.py <IPA 或 DmIOS.app 目录> <输出目录> [--check]')
app = read_app(a[0]); os.makedirs(a[1], exist_ok=True); ok = True
for name in MODS:
gates = []
for l in app[f'dm/{name}.gates.tsv'].decode().splitlines():
r, k, arg, orig = l.split(); gates.append((int(r, 16), k, int(arg), int(orig, 16)))
img, hdr, st, pat = restore(name, app, gates)
write_nso(os.path.join(a[1], name), img, hdr, BUILD_IDS.get(name, '00' * 16))
print(name, st, '多候选取规范编码', len(AMBIG)); AMBIG.clear()
if '--check' in sys.argv:
c = check(name, a[1], app, pat); ok &= c; print(f' {name} 苹果 ABI 重改写 {"与包内逐字节一致" if c else "不一致"}')
sys.exit(0 if ok else 1)
if __name__ == '__main__':
main()
+156 -19
View File
@@ -7,6 +7,7 @@
# svc #n、mrs cntpct_el0 → 宿主门(门地址取自线程槽 KGATE,进 C 后按返回点查 gates.tsv)
# 已登记剪口(CUTS,按 NSO 构建号限定):改写前逐条断言原字节,不符即中止;结果列在 <名>.cuts.tsv
# 已登记观测门(OBS,按构建号限定):入口一条指令换成「进宿主观测回调 → 执行原指令 → 跳回」,诊断零运行时改代码;列在 <名>.obs.tsv
# DM_ABI=android:槽块基址改经 Bionic 线程指针取(mrs tpidr_el0 + ldr [tp,#DM_ANDROID_TP_OFF],Linux 把用户态 tpidrro_el0 清零),fixups.tsv 表头多 ABI / TP_SLOT_OFF 两行。
# 键页只在数据段末尾保存“实际键号 × 8”,补丁代码通过键页间接取线程槽:装载器可使用任意键号。
# 输出:<名>.patched.bin(键页与补丁区接在映像后 PATCH_OFF)、<名>.fixups.tsv(布局与键页下标表头)、<名>.gates.tsv、<名>.sites.tsv、<名>.cuts.tsv、<名>.obs.tsv
# Generic NSO rewriter: Switch aarch64 module → an image that can execute natively on Apple systems.
@@ -18,6 +19,7 @@
# svc #n, mrs cntpct_el0 → host gate (gate address taken from thread slot KGATE; once in C, gates.tsv is looked up by return point)
# Registered cuts (CUTS, restricted by NSO build ID): before rewriting, the original bytes are asserted one by one and any mismatch aborts; results are listed in <name>.cuts.tsv
# Registered observation gates (OBS, restricted by build ID): one instruction at the entry is replaced with "enter the host observation callback → execute the original instruction → jump back", so diagnostics modify zero code at runtime; listed in <name>.obs.tsv
# DM_ABI=android: the slot block base is fetched via the Bionic thread pointer instead (mrs tpidr_el0 + ldr [tp,#DM_ANDROID_TP_OFF]; Linux zeroes user tpidrro_el0), and the fixups.tsv header gains two lines, ABI / TP_SLOT_OFF.
# The key page only stores "actual key number × 8" at the end of the data segment, and patch code fetches thread slots indirectly through the key page: the loader may use any key number.
# Output: <name>.patched.bin (key page and patch area appended after the image at PATCH_OFF), <name>.fixups.tsv (layout and key page index header), <name>.gates.tsv, <name>.sites.tsv, <name>.cuts.tsv, <name>.obs.tsv
import struct, re, sys, os
@@ -178,6 +180,12 @@ cuts = list(CUTS.get(BUILD_ID, []))
# 触屏版规则域默认同时带宿主私有门;规则闸门可显式关闭,保留同一出包入口和规则域。
# The touchscreen rule domain by default also carries the host-private gates; the rule gate check can turn them off explicitly, keeping the same packaging entry point and rule domain.
PRIVATE_GATES = os.environ.get("DM_PRIVATE_GATES", "1") != "0"
# 目标 ABI:apple(iOS/macOS,默认,产物逐字节不变)/ android(Linux Bionic,槽块基址经 tpidr_el0 的 TLS 槽)。
# Target ABI: apple (iOS/macOS, default, output byte-identical) / android (Linux Bionic, slot block base via a TLS slot of tpidr_el0).
ABI = os.environ.get('DM_ABI', 'apple')
assert ABI in ('apple', 'android'), f'未知 ABI {ABI}'
ANDROID_TP_OFF = int(os.environ.get('DM_ANDROID_TP_OFF', '0x10'), 0) # Bionic TLS_SLOT_APP(tp[2])
assert ANDROID_TP_OFF % 8 == 0 and 0 <= ANDROID_TP_OFF < 0x8000, f'DM_ANDROID_TP_OFF {ANDROID_TP_OFF:#x}'
PRIVATE_AIM = RULE_RUN and PRIVATE_GATES
if PRIVATE_AIM:
cuts.append((0x2faf04, 'fde7fe97', 'c11000d4',
@@ -256,6 +264,16 @@ def emit(w, kind=None):
def emit_key_addr(reg, kind):
fix.append((len(patch), kind)); emit(ADRP(reg, here(), KEY_PAGE_OFF)); emit(LDRX(reg, reg, KEY_INDEX[kind]))
def emit_slot_base(reg):
"""reg = 本线程槽块基址。apple:tpidrro_el0 即基址(宿主每线程写入);android:Linux 把用户态 tpidrro_el0 清零,
改从 Bionic 线程指针取:reg = [tpidr_el0 + ANDROID_TP_OFF](宿主在该 TLS 槽放槽块指针)。客体自己的 tpidr_el0 读写已改写成槽 KTLS,
真 tpidr_el0 始终是 Bionic 的。
reg = base of this thread's slot block. apple: tpidrro_el0 is the base (written per thread by the host); android: Linux zeroes user tpidrro_el0,
so take it from the Bionic thread pointer instead: reg = [tpidr_el0 + ANDROID_TP_OFF] (the host stores the slot block pointer in that TLS slot). The guest's own tpidr_el0
reads/writes are already rewritten to slot KTLS, so the real tpidr_el0 is always Bionic's."""
if ABI == 'apple': emit(MRS_TPIDRRO(reg))
else: emit(MRS_TPIDR(reg)); emit(LDRX(reg, reg, ANDROID_TP_OFF // 8))
def emit_slot_addr(base, key_reg, kind):
emit_key_addr(key_reg, kind); emit(ADDR(base, base, key_reg))
@@ -273,6 +291,7 @@ def LDUR(t, n, off): return 0xF8400000 | ((off & 0x1FF) << 12) | (n << 5) | t
def LDRX(t, n, imm12=0): return 0xF9400000 | (imm12 << 10) | (n << 5) | t
def STRX(t, n, imm12=0): return 0xF9000000 | (imm12 << 10) | (n << 5) | t
def MRS_TPIDRRO(t): return 0xD53BD060 | t
def MRS_TPIDR(t): return 0xD53BD040 | t
def ADRP(dd, pc, target):
imm = ((target & ~0xFFF) - (pc & ~0xFFF)) >> 12; assert -(1 << 20) <= imm < (1 << 20)
return 0x90000000 | ((imm & 3) << 29) | (((imm >> 2) & 0x7FFFF) << 5) | dd
@@ -326,13 +345,87 @@ def sp_delta(ins):
assert not re.match(r'(sp|wsp),', ins.op_str), f'writes sp: {ins.address:x} {ins.op_str}'
return 0
# ---- android:没有红区 ----
# Linux / Bionic 不保留 sp 下方:信号(含 ART / 系统发来的、不走 sigaltstack 的)随时可能落在当前栈上把 sp 下方写坏。
# 所以 android 的跳板一律先减 sp 再存借用的寄存器,用完加回;被搬进跳板、又引用 sp 的原指令改用一个存着原 sp 的寄存器 U。
# apple 走原来的红区写法,产物逐字节不变。思路来自 dodola/d2r-mobile 的 Android 移植(MIT)。
# ---- android: no red zone ----
# Linux / Bionic does not reserve the area below sp: a signal (including ones from ART / the system that do not go through sigaltstack) may land on
# the current stack at any time and overwrite what is below sp. So android trampolines always lower sp first, store the borrowed registers, and
# add it back afterwards; an original instruction moved into a trampoline that references sp uses a register U holding the original sp instead.
# apple keeps the original red-zone form, output byte-identical. The approach comes from the Android port in dodola/d2r-mobile (MIT).
def save_pair(S, T):
emit(STP_PRE(S, T, 31, -16) if ABI == 'android' else STP(S, T, 31, -16))
def restore_pair(S, T):
emit(LDP_POST(S, T, 31, 16) if ABI == 'android' else LDP(S, T, 31, -16))
def uses_sp(ins): return re.search(r'\bw?sp\b', ins.op_str) is not None
def subst_sp(ins, w, reg):
"""把原指令里的 sp / wsp 操作数换成寄存器 reg。寄存器号 31 也编码 xzr / wzr,所以逐个组合反汇编核对,只换真正是 sp 的字段。
Replace the sp / wsp operand of the original instruction with register reg. Register number 31 also encodes xzr / wzr, so disassemble every
combination and check it, replacing only the fields that really are sp."""
orig = dis(w, ins.address)
if orig.mnemonic == 'mov' and orig.op_str.endswith(', sp'): # mov xd, sp = add xd, sp, #0;换基址后 capstone 不再写成 mov,改用寄存器 mov | mov xd, sp = add xd, sp, #0; with the base replaced capstone no longer prints mov, use the register mov
assert w & 0xFFC003E0 == 0x910003E0 and (w >> 10) & 0xFFF == 0, hex(ins.address)
return 0xAA0003E0 | (reg << 16) | (w & 31)
want = re.sub(r'\b(w?sp)\b', lambda m: ('w' if m.group(1) == 'wsp' else 'x') + str(reg), orig.op_str)
pos = [p for p in (0, 5, 10, 16) if (w >> p) & 31 == 31]
for k in range(1, len(pos) + 1):
for c in combinations(pos, k):
nw = w
for p in c: nw = (nw & ~(31 << p)) | (reg << p)
try: dd = dis(nw, ins.address)
except AssertionError: continue
if dd.mnemonic == orig.mnemonic and dd.op_str == want: return nw
raise RuntimeError(f'android sp 替换失败 {ins.address:x} {orig.mnemonic} {orig.op_str}')
def android_frame(ins, scratch=32):
"""借用寄存器的暂存区放在原指令所有静态 sp 访问(含负偏移、前变址写回)之下。
Place the scratch area for borrowed registers below every static sp access of the original instruction (including negative offsets and pre-index writeback)."""
from capstone.arm64 import ARM64_OP_MEM, ARM64_REG_SP, ARM64_REG_INVALID
floor = min(0, sp_delta(ins))
for op in ins.operands:
if op.type == ARM64_OP_MEM and op.mem.base == ARM64_REG_SP:
assert op.mem.index == ARM64_REG_INVALID, f'android 不支持 sp 加寄存器下标 {ins.address:x} {ins.op_str}'
floor = min(floor, op.mem.disp)
frame = (scratch - floor + 15) & ~15
assert frame <= 0xFFF, f'android 暂存帧过大 {ins.address:x} {frame}'
return frame
def site_plain_android(ins):
S, T = pick(regs_in(ins))
dlt = sp_delta(ins)
assert dlt % 16 == 0, f'android sp 写回破坏 16 字节对齐 {ins.address:x} {dlt}'
start = here()
w = subst(ins, S)
if uses_sp(ins):
(U,) = pick(regs_in(ins) | {S, T}, 1)
frame = android_frame(ins)
emit(SUBI(31, 31, frame)); emit(STP(S, T, 31, 0)); emit(STRX(U, 31, 2)); emit(ADDI(U, 31, frame))
emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(subst_sp(ins, w, U))
emit(STRX(S, T))
emit(LDRX(U, 31, 2)); emit(LDP(S, T, 31, 0))
assert 0 <= frame + dlt <= 0xFFF, f'android sp 收尾超范围 {ins.address:x} {frame + dlt}'
if frame + dlt: emit(ADDI(31, 31, frame + dlt))
else:
assert dlt == 0
save_pair(S, T); emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(w); emit(STRX(S, T))
restore_pair(S, T)
emit(B(here(), ins.address + 4))
return start
def site_plain(ins):
if ABI == 'android': return site_plain_android(ins)
S, T = pick(regs_in(ins))
dlt = sp_delta(ins)
save = -16 if dlt == 0 else -112 # 改 sp 的指令会写到 sp 下方,暂存放到保留区深处 | Instructions that modify sp write below sp, so the scratch save is placed deep in the reserved area
assert dlt == 0 or dlt >= -96, f'sp delta {dlt} at {ins.address:x}'
start = here()
emit(STP(S, T, 31, save)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(STP(S, T, 31, save)); emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(subst(ins, S))
emit(STRX(S, T)) # 一律写回:capstone 会漏报写入(adds w18 实例) | Always write back: capstone can miss reporting a write (the adds w18 instance)
emit(LDP(S, T, 31, save - dlt)); emit(B(here(), ins.address + 4))
@@ -343,34 +436,35 @@ def site_cond(ins):
S, T = pick(regs_in(ins))
tgt = ins.operands[-1].imm
start = here()
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
save_pair(S, T); emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
m = ins.mnemonic
taken = here() + 4 * 3
off = (taken - here()) >> 2
nw = ((w & 0xFF000000) | ((off & 0x7FFFF) << 5) | S) if m in ('cbz', 'cbnz') else ((w & 0xFFF80000) | ((off & 0x3FFF) << 5) | S)
pc = here(); emit(nw)
dd = dis(nw, pc); assert dd.mnemonic == m and dd.operands[-1].imm == taken
emit(LDP(S, T, 31, -16)); emit(B(here(), ins.address + 4))
restore_pair(S, T); emit(B(here(), ins.address + 4))
assert here() == taken
emit(LDP(S, T, 31, -16)); emit(B(here(), tgt))
restore_pair(S, T); emit(B(here(), tgt))
return start
def site_pcrel(ins):
tgt = ins.operands[1].imm
S, T = pick(set())
start = here()
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18') # S 先作键页偏移暂存,下一条再装目标值 | S first serves as a temporary for the key page offset; the next instruction then loads the target value
save_pair(S, T); emit_slot_base(T); emit_slot_addr(T, S, 'K18') # S 先作键页偏移暂存,下一条再装目标值 | S first serves as a temporary for the key page offset; the next instruction then loads the target value
pc = here(); emit(ADRP(S, pc, tgt))
if ins.mnemonic == 'adr': emit(ADDI(S, S, tgt & 0xFFF))
emit(STRX(S, T))
emit(LDP(S, T, 31, -16)); emit(B(here(), ins.address + 4))
restore_pair(S, T); emit(B(here(), ins.address + 4))
return start
def site_br(ins, base, count):
"""跳转表 br x18:目标 = base + 4i。x16 暂存红区 → 等距落地垫 → 恢复 x16 → 原目标。 | Jump table br x18: target = base + 4i. Stash x16 in the red zone → equally spaced landing pads → restore x16 → original target."""
start = here()
emit(STUR(16, 31, -16)); emit(STUR(17, 31, -24)) # x16 / x17 是函数内可存活的临时寄存器,借用前存红区 | x16 / x17 are temporary registers that can stay live within a function; save them to the red zone before borrowing
emit(MRS_TPIDRRO(16)); emit_slot_addr(16, 17, 'K18'); emit(LDRX(16, 16)); emit(LDUR(17, 31, -24))
if ABI == 'android': emit(STP_PRE(16, 17, 31, -16)) # 没有红区:先减 sp 再存 | No red zone: lower sp first, then store
else: emit(STUR(16, 31, -16)); emit(STUR(17, 31, -24)) # x16 / x17 是函数内可存活的临时寄存器,借用前存红区 | x16 / x17 are temporary registers that can stay live within a function; save them to the red zone before borrowing
emit_slot_base(16); emit_slot_addr(16, 17, 'K18'); emit(LDRX(16, 16)); emit(LDRX(17, 31, 1) if ABI == 'android' else LDUR(17, 31, -24))
padbase = start + 4 * 24
delta = padbase - base
op = ADDI if delta >= 0 else SUBI; dl = abs(delta)
@@ -380,20 +474,37 @@ def site_br(ins, base, count):
assert len(ops) <= 12
for o in ops: emit(o)
emit(BR(16))
assert here() <= padbase, f'跳转表块超出落地垫基址 {base:#x}'
while here() < padbase: emit(NOP)
tails = padbase + 4 * count
for i in range(count): emit(B(here(), tails + 8 * i))
for i in range(count):
emit(0xF85F0000 | (31 << 5) | 16) # ldur x16,[sp,#-16]
emit(LDP_POST(16, 17, 31, 16) if ABI == 'android' else 0xF85F0000 | (31 << 5) | 16) # android ldp x16,x17,[sp],#16 / apple ldur x16,[sp,#-16]
emit(B(here(), base + 4 * i))
return start
def emit_slot_read(N, tmp, kind):
"""xN = 线程槽 kind 的值,借 tmp。apple:tmp 存红区;android:先减 sp 存 tmp(与 xzr 成对保持 16 字节)。
xN = value of thread slot kind, borrowing tmp. apple: tmp is saved in the red zone; android: lower sp first and store tmp (paired with xzr to keep 16 bytes)."""
if ABI == 'android':
assert N not in (18, 31) and tmp != N
emit(STP_PRE(tmp, 31, 31, -16)); emit_slot_base(N); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDP_POST(tmp, 31, 31, 16))
else:
emit(STUR(tmp, 31, -16)); emit_slot_base(N); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDUR(tmp, 31, -16)) # tmp 存红区借用 | tmp is saved by borrowing the red zone
def site_sysreg_read(ins, kind):
"""mrs xN, tpidr_el0 / tpidrro_el0 → xN = 线程槽值。 | mrs xN, tpidr_el0 / tpidrro_el0 → xN = thread slot value."""
N = ins.bytes[0] & 31
tmp = 16 if N != 16 else 17
start = here()
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(N)); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDUR(tmp, 31, -16)) # tmp 存红区借用 | tmp is saved by borrowing the red zone
if ABI == 'android' and N == 31: pass # mrs xzr:无副作用 | mrs xzr: no effect
elif ABI == 'android' and N == 18:
# x18 是虚拟寄存器(槽 K18),不碰硬件 x18:槽 kind → 槽 K18 | x18 is virtual (slot K18), never touch hardware x18: slot kind -> slot K18
emit(SUBI(31, 31, 32)); emit(STP(16, 17, 31, 0)); emit(STRX(15, 31, 2))
emit_slot_base(17); emit_slot_addr(17, 16, kind); emit(LDRX(15, 17))
emit_slot_base(17); emit_slot_addr(17, 16, 'K18'); emit(STRX(15, 17))
emit(LDRX(15, 31, 2)); emit(LDP(16, 17, 31, 0)); emit(ADDI(31, 31, 32))
else: emit_slot_read(N, tmp, kind)
emit(B(here(), ins.address + 4))
return start
@@ -401,10 +512,19 @@ def site_tpidr_write(ins):
N = struct.unpack('<I', ins.bytes)[0] & 31
(T,) = pick({N}, 1)
start = here()
emit(0xF81F0000 | (31 << 5) | T) # stur xT,[sp,#-16]
tmp = next(x for x in (16, 17) if x not in (N, T))
emit(STUR(tmp, 31, -24)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDUR(tmp, 31, -24))
emit(0xF85F0000 | (31 << 5) | T) # ldur xT,[sp,#-16]
if ABI == 'android' and N == 18:
# msr tpidr_el0, x18:x18 的值在槽 K18 | msr tpidr_el0, x18: the value of x18 lives in slot K18
emit(SUBI(31, 31, 32)); emit(STP(16, 17, 31, 0)); emit(STRX(15, 31, 2))
emit_slot_base(17); emit_slot_addr(17, 16, 'K18'); emit(LDRX(15, 17))
emit_slot_base(17); emit_slot_addr(17, 16, 'KTLS'); emit(STRX(15, 17))
emit(LDRX(15, 31, 2)); emit(LDP(16, 17, 31, 0)); emit(ADDI(31, 31, 32))
elif ABI == 'android':
emit(STP_PRE(T, tmp, 31, -16)); emit_slot_base(T); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDP_POST(T, tmp, 31, 16))
else:
emit(0xF81F0000 | (31 << 5) | T) # stur xT,[sp,#-16]
emit(STUR(tmp, 31, -24)); emit_slot_base(T); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDUR(tmp, 31, -24))
emit(0xF85F0000 | (31 << 5) | T) # ldur xT,[sp,#-16]
emit(B(here(), ins.address + 4))
return start
@@ -417,7 +537,7 @@ def emit_gate_call():
Fetching the slot through the key page needs a second register to be borrowed; x29 is borrowed and then immediately restored from the stack: the x29 saved by _dm_gate must be the guest's original value --
the host identifies the caller by [x29+8] (skill binding observation gate 6, private aiming gate svc86), and the crash backtrace also walks the x29 chain
(since r24 plan C it was borrowed and not returned, the x29 the host got was the slot offset from the key page, and skill icons fell back to placeholder text)."""
emit(MRS_TPIDRRO(30)); emit_slot_addr(30, 29, 'KGATE'); emit(LDRX(30, 30)); emit(LDRX(29, 31))
emit_slot_base(30); emit_slot_addr(30, 29, 'KGATE'); emit(LDRX(30, 30)); emit(LDRX(29, 31))
def site_gate(ins, kind, arg):
"""svc / mrs cntpct_el0 → 宿主门。门地址取自线程槽 KGATE;门按返回点(本块 ldp 的地址)查 gates.tsv。 | svc / mrs cntpct_el0 → host gate. The gate address is taken from thread slot KGATE; the gate looks up gates.tsv by return point (the address of this block's ldp)."""
@@ -472,18 +592,30 @@ def site_window(seg):
S, T = pick(used)
lo, hi = seg[0].address, seg[-1].address + 4
start = here()
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
# android 没有红区:先减 sp 再存借用寄存器;窗口里有引用 sp 的指令时,sp 换成 U(= 原 sp),暂存帧放在它们的访问范围之下
# android has no red zone: lower sp first, then save the borrowed registers; when the window references sp, sp is replaced by U (= original sp) and the scratch frame goes below their accesses
U = frame = None
if ABI == 'android' and any(uses_sp(x) for x in seg):
assert all(sp_delta(x) == 0 for x in seg), f'android 独占窗口里改 sp {lo:#x}'
(U,) = pick(used | {S, T}, 1)
frame = max(android_frame(x) for x in seg)
emit(SUBI(31, 31, frame)); emit(STP(S, T, 31, 0)); emit(STRX(U, 31, 2)); emit(ADDI(U, 31, frame))
else:
save_pair(S, T)
emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
copy0 = here(); n = len(seg)
exits = copy0 + 4 * n
stride = 32 if U is not None else 16
ex_targets = []; words = []
for k, x in enumerate(seg):
w = struct.unpack('<I', x.bytes)[0]
if has18(x): w = subst(x, S)
if U is not None and uses_sp(x): w = subst_sp(x, w, U)
m = x.mnemonic
if m in ('cbz', 'cbnz', 'tbz', 'tbnz') or m.startswith('b.'):
tgt = x.operands[-1].imm
if lo <= tgt < hi: newt = copy0 + (tgt - lo)
else: ex_targets.append(tgt); newt = exits + 16 * len(ex_targets) # 出口桩第 0 个留给顺序落出(见下),窗口外的目标从第 1 个起 | Exit stub 0 is reserved for the sequential fall-out (see below); targets outside the window start from stub 1
else: ex_targets.append(tgt); newt = exits + stride * len(ex_targets) # 出口桩第 0 个留给顺序落出(见下),窗口外的目标从第 1 个起 | Exit stub 0 is reserved for the sequential fall-out (see below); targets outside the window start from stub 1
pc = copy0 + 4 * k; off = (newt - pc) >> 2
if m in ('tbz', 'tbnz'): w = (w & 0xFFF8001F) | ((off & 0x3FFF) << 5)
else: w = (w & 0xFF00001F) | ((off & 0x7FFFF) << 5)
@@ -501,7 +633,12 @@ def site_window(seg):
# (one operation done twice / a lock-free list popped more than once). The game has 6 such windows (main 0x1848eb8 / 0x1848f28 / 0x1848f84, sdk 0x2ea0fc / 0x2ea4cc / 0x2ea644);
# windows whose only branch is a cbnz back into the window are not affected. The equivalence check used to never draw the "compare equal" direction at random, so it stayed green (equiv.py now forces both directions of window branches).
for t in [hi] + ex_targets:
emit(STRX(S, T)); emit(LDP(S, T, 31, -16)); emit(B(here(), t)); emit(NOP)
e0 = here()
emit(STRX(S, T))
if U is not None: emit(LDRX(U, 31, 2)); emit(LDP(S, T, 31, 0)); emit(ADDI(31, 31, frame))
else: restore_pair(S, T)
emit(B(here(), t))
while here() < e0 + stride: emit(NOP)
return start, lo, hi
# ---- 函数边界(eh_frame_hdr)----
@@ -788,8 +925,7 @@ for oa, wa, ob_, wb, r, key, why in params:
ins = dis(struct.unpack_from('<I', IMG, o)[0], o)
assert r not in regs_in(ins), f'参数位中间用到 x{r}:{o:#x} {ins.mnemonic} {ins.op_str}'
start = here()
tmp = 16 if r != 16 else 17
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(r)); emit_slot_addr(r, tmp, key); emit(LDRX(r, r)); emit(LDUR(tmp, 31, -16)); emit(B(here(), oa + 4))
emit_slot_read(r, 16 if r != 16 else 17, key); emit(B(here(), oa + 4))
struct.pack_into('<I', IMG, oa, B(oa, start)); struct.pack_into('<I', IMG, ob_, NOP); stat('param')
# 既有三块原生规则跳板均只使用后继覆盖的死临时w8,不改w0/stat返回、sp或NZCV。
@@ -852,6 +988,7 @@ elif os.path.exists(P('rules.tsv')):
with open(P('fixups.tsv'), 'w') as f:
f.write(f'# PATCH_OFF\t{PATCH_OFF:#x}\n# KEY_PAGE_OFF\t{KEY_PAGE_OFF:#x}\n# KEY_PAGE_SIZE\t0x4000\n# TEXT_END\t{TEXT_END:#x}\n# RO_OFF\t{RO_OFF:#x}\n# DATA_OFF\t{DATA_OFF:#x}\n')
for k in KEY_INDEX: f.write(f'# KEY_{k}_IDX\t{KEY_INDEX[k]}\n')
if ABI == 'android': f.write(f'# ABI\tlinux-bionic\n# TP_SLOT_OFF\t{ANDROID_TP_OFF:#x}\n') # 苹果宿主读到非数值行即拒载 | the Apple host refuses to load on a non-numeric line
with open(P('gates.tsv'), 'w') as f:
for ret, k, arg, orig in gates: f.write(f'{ret:#x}\t{k}\t{arg}\t{orig:#x}\n')
with open(P('sites.tsv'), 'w') as f:
+7 -4
View File
@@ -4,23 +4,26 @@
# product.sh path <种类> → 本机缺省产物目录 $DM_ROOT/build/cache/dm/out/<name>
# product.sh rev → r28
# product.sh build → 重出三种产物(keypage / rules / touch)到本机缺省目录
# DM_ABI=android(缺省 apple)→ 以上名字 / 目录都带 -android 后缀,改写器出 Linux Bionic 版
# The codename of the current rewrite build output is written in exactly one place: dm/PRODUCT (one line, e.g. 3.3.94012-r28). A revision bump changes only that line.
# Usage: product.sh name <kind> → 3.3.94012-r28-<kind> (kind: touch / rules / keypage)
# product.sh path <kind> → local default build output directory $DM_ROOT/build/cache/dm/out/<name>
# product.sh rev → r28
# product.sh build → rebuild the three kinds of build output (keypage / rules / touch) into the local default directory
# DM_ABI=android (default apple) → the names / directories above get an -android suffix and the rewriter emits the Linux Bionic variant
set -u
P=$(head -1 "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/PRODUCT") || exit 2
[ -n "$P" ] || { echo "dm/PRODUCT 为空" >&2; exit 2; }
case "${DM_ABI:=apple}" in apple) X=;; android) X=-android;; *) echo "未知 DM_ABI=$DM_ABI" >&2; exit 2;; esac; export DM_ABI
case "${1:-}" in
name) echo "$P-${2:?种类}";;
path) echo "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-${2:?种类}";;
name) echo "$P-${2:?种类}$X";;
path) echo "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-${2:?种类}$X";;
rev) echo "${P##*-}";;
build) # 用本工作树的改写器重出三种产物到本机缺省目录(换代 / 改了 patch_nso.py 之后跑)。种类 → 规则集:keypage = 原生;rules = 触屏规则、不带宿主私有门;touch = 触屏规则 + 私有门 | Rebuild the three kinds of build output with this worktree's rewriter into the local default directory (run after a revision bump / after changing patch_nso.py). Kind → rule set: keypage = native; rules = touchscreen rules, without host-private gates; touch = touchscreen rules + private gates
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); PY=${DM_PY:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python3}; NSO=${DM_NSO_DIR:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/ExeFS}
for k in keypage rules touch; do O=${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-$k; mkdir -p "$O"
for k in keypage rules touch; do O=${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-$k$X; mkdir -p "$O"
case $k in keypage) E=(DM_RULESET=native);; rules) E=(DM_RULESET=touch-run-v4 DM_PRIVATE_GATES=0);; touch) E=(DM_RULESET=touch-run-v4);; esac
for m in main sdk subsdk0; do env "${E[@]}" "$PY" "$HERE/patch_nso.py" "$NSO/$m" "$O" "$m" > "$O/$m.patch.log" 2>&1 || { echo "🔴 $k $m 改写失败:$(tail -2 "$O/$m.patch.log")" >&2; exit 1; }; done
echo "$P-$k 已出:$(ls "$O" | wc -l | tr -d ' ') 个文件"; done;;
echo "$P-$k$X 已出:$(ls "$O" | wc -l | tr -d ' ') 个文件"; done;;
*) echo "用法:product.sh name|path <种类> | rev | build" >&2; exit 2;;
esac