Files
seeddsandSeif Ateek cac1293b45 host: load exlaunch mod code plugins (PR #3178)
Load Atmosphère exefs/subsdk<N> code plugins (such as exlaunch plugins beside a mod's romfs/) on the Mac, and answer the Horizon SVCs their start-up requires:

- Rewriter (patch_nso.py, mod_layout.py): walk raw .eh_frame when MOD0's .eh_frame_hdr range is empty (devkitA64-linked plugins), indexing CIEs by offset, supporting CIE v1/v3/v4 and all pointer formats, skipping empty (0, 0) MOD0 ranges, and relocating raw .eh_frame pointers on 16 KB data relayout.
- Offline preparation (scripts/prepare_mod.py): rewrite a mod's subsdk<N> NSOs into <mod>/exefs/nxnative/ in numeric order without DM_GAME, validating NSO0 magic and warning on exefs/main.
- Loader & shared code writes (loader.c, code_write.h, hle_cheats.c): reserve one contiguous PROT_NONE span on macOS for non-JIT startup modules (with a 3-page rtld slot below main and 1-page guards between modules) so modules sit in Horizon load order; sync open MapProcessMemory views after each module's DT_INIT; share mach_vm_remap writable alias and BUILD_ID-verified changed.tsv helpers between cheats and exlaunch plugins.
- Exlaunch HLE & SVCs (hle_exl.c, hle_svc.c, main.c): load prepared subsdk<N> plugins from DM_ROMFS_OVERLAY mods before sdk (skipped safely on iOS); populate the stand-in rtld only when mod plugins are loaded (or on a .rodata-only exlaunch signature match for manually loaded subsdks); answer GetInfo(65001) with the current-process handle; implement MapProcessMemory / UnmapProcessMemory with ASLR-only destination bounds, key_page_off source bounds, changed.tsv refusal, lock-safe sync, and guest_release on unmap; fix svcGetSystemTick (0x1E) to return the 64-bit tick in x0.
- Tests & docs: add t_exl.c and test_exl_mod.py, add dm_exl_* stubs to t_heap_size.c and t_svc_memory.c, document DM_EXL_TRACE and DM_ROMFS_OVERLAY, and update docs/reference/rewriter.md and docs/agents/symptoms.md.

Checked: Mac host build, iOS SDK -fsyntax-only -Wall -Werror on changed C files, host tests (exl, cheats, heap_size under ASan/UBSan; memory, nro, symbols), Python tool tests (23/23), clang-tidy ratchet (0 new findings), ruff/pyright ratchet (0 new findings in changed files), and quick regression check on Hades (0100535012974000, PASS).

Front-ends: new: on the Mac, a mod with exefs/subsdk<N> code plugins runs its code once scripts/prepare_mod.py <mod> has prepared it into <mod>/exefs/nxnative/; enabling the mod (its romfs in DM_ROMFS_OVERLAY) loads the plugins and disabling it leaves them out

Fixes #1133
Co-authored-by: Seif Ateek <[email protected]>
2026-11-23 15:06:24 +08:00

93 lines
3.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""Rewrite Atmosphère mod code plugins (exefs/subsdk<N>) once into <mod>/exefs/nxnative/.
The Mac host loads prepared plugins from <mod>/exefs/nxnative/ whenever the mod's RomFS folder is
listed in DM_ROMFS_OVERLAY (dm/host/hle_exl.c). Run this script again after updating the rewriter.
Usage:
python3 scripts/prepare_mod.py <mod folder> [<mod folder> ...]
"""
from __future__ import annotations
import argparse
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
REPO = Path(__file__).resolve().parents[1]
PATCH_NSO = REPO / 'dm/tools/patch_nso.py'
SUBSDK_RE = re.compile(r'^subsdk([0-9]+)$')
def find_plugins(exefs: Path) -> list[Path]:
"""Return regular subsdk<N> files under exefs in numeric order."""
found: list[tuple[int, str, Path]] = []
for entry in exefs.iterdir():
m = SUBSDK_RE.match(entry.name)
if not m or not entry.is_file():
continue
if len(entry.name) >= 16:
raise ValueError(f'{entry}: module name is too long ({len(entry.name)} >= 16)')
found.append((int(m.group(1)), entry.name, entry))
found.sort()
return [p for _, _, p in found]
def prepare_mod(mod_dir: Path, python: str = sys.executable) -> int:
"""Rewrite every subsdk<N> NSO in <mod_dir>/exefs into <mod_dir>/exefs/nxnative."""
exefs = mod_dir / 'exefs'
if not exefs.is_dir():
raise FileNotFoundError(f'{mod_dir} has no exefs folder')
if (exefs / 'main').is_file():
print(f'[RED] {exefs / "main"} replaces the game binary, which is not supported: skipping main', file=sys.stderr)
plugins = find_plugins(exefs)
if not plugins:
raise FileNotFoundError(f'{exefs} has no subsdk<N> plugin')
for plugin in plugins:
with plugin.open('rb') as f:
magic = f.read(4)
if magic != b'NSO0':
raise ValueError(f'{plugin} is not an NSO binary (magic {magic!r})')
out = exefs / 'nxnative'
tmp = exefs / 'nxnative.tmp'
if tmp.exists():
shutil.rmtree(tmp)
tmp.mkdir(parents=True)
# Clear DM_GAME so a game's MATCH_CUTS / build rows never attach to a mod's subsdk plugin.
env = {k: v for k, v in os.environ.items() if k != 'DM_GAME'}
try:
for plugin in plugins:
subprocess.run([python, str(PATCH_NSO), str(plugin), str(tmp), plugin.name], env=env, check=True)
except Exception:
shutil.rmtree(tmp, ignore_errors=True)
raise
if out.exists():
shutil.rmtree(out)
tmp.rename(out)
print(f'prepared {len(plugins)} plugin(s) in {out}')
return len(plugins)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description='Rewrite Atmosphère mod exefs/subsdk<N> plugins for nxnative.')
parser.add_argument('mods', nargs='+', type=Path, help='Mod folder(s) containing exefs/ (and optionally romfs/)')
args = parser.parse_args(argv)
for mod in args.mods:
try:
prepare_mod(mod)
except (FileNotFoundError, ValueError, subprocess.CalledProcessError) as exc:
print(f'[RED] {exc}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main())