Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
frontend-qt: fix Windows build pipeline, bundle spirv-cross, and sign entitlements
LNPANDYa7d774f40552
diff --git a/.github/workflows/build-qt.yml b/.github/workflows/build-qt.ymlindex 7b74561e..8c3439ea 100644--- a/.github/workflows/build-qt.yml+++ b/.github/workflows/build-qt.yml@@ -54,6 +54,25 @@ jobs:python tools/engine.py tree --out engine-treedu -sh engine-tree+ - name: Build Windows spirv-cross.exe for the bundled engine+ shell: bash+ run: |+ # The engine tree ships a macOS Mach-O spirv-cross binary in dm/gfx/tools/spirv_cross_bin/.+ # Build the Windows executable from the exact commit build.sh pins so every NVN, Vulkan and+ # OpenGL shader build works out of the box without a manual Vulkan SDK install.+ TAG=$(sed -n 's/^TAG=\([^ ]*\).*/\1/p' engine-tree/dm/gfx/tools/spirv_cross_bin/build.sh)+ COMMIT=$(sed -n 's/^COMMIT=\([^ ]*\).*/\1/p' engine-tree/dm/gfx/tools/spirv_cross_bin/build.sh)+ git clone --quiet --depth 1 --branch "$TAG" https://github.com/KhronosGroup/SPIRV-Cross.git spirv-cross-src+ got=$(git -C spirv-cross-src rev-parse HEAD)+ [ "$got" = "$COMMIT" ] || { echo "SPIRV-Cross $TAG is $got, expected $COMMIT" >&2; exit 1; }+ cmake -S spirv-cross-src -B spirv-cross-build -DSPIRV_CROSS_ENABLE_TESTS=OFF -DSPIRV_CROSS_SKIP_INSTALL=ON+ cmake --build spirv-cross-build --config Release --target spirv-cross --parallel+ SPV_EXE=$(find spirv-cross-build -name "spirv-cross.exe" | head -1)+ [ -n "$SPV_EXE" ] && [ -f "$SPV_EXE" ]+ cp "$SPV_EXE" engine-tree/dm/gfx/tools/spirv_cross_bin/spirv-cross.exe+ engine-tree/dm/gfx/tools/spirv_cross_bin/spirv-cross.exe --revision+ rm -rf spirv-cross-src spirv-cross-build+- name: Buildworking-directory: frontend-qtshell: bash@@ -126,6 +145,7 @@ jobs:--add-data "../frontend/fonts/Manrope.ttf${PATHSEP}fonts" \--add-data "../frontend/fonts/Manrope-OFL.txt${PATHSEP}fonts" \--add-data "../frontend/l10n${PATHSEP}l10n" \+ --add-data "nspb_qt${PATHSEP}nspb_qt" \--paths . \run_gui.pydiff --git a/frontend-qt/nspb_qt/engine.py b/frontend-qt/nspb_qt/engine.pyindex 5ecc9982..5a71f44b 100644--- a/frontend-qt/nspb_qt/engine.py+++ b/frontend-qt/nspb_qt/engine.py@@ -89,11 +89,20 @@ def is_stale(repo: str) -> bool:def bundled_engine() -> str:"""The engine tree the Actions zip puts beside the app folder (`<exe_dir>/../engine/`).- None when it is not there or does not look like an engine tree."""- if not getattr(sys, 'frozen', False):- return '' # a PyInstaller bundle sets sys.frozen; a python -m run never does- exe = Path(sys.executable).resolve()- for base in (exe.parent, exe.parent.parent):+ Empty string when it is not there or does not look like an engine tree.++ Also resolves when imported from an external Python (the build's venv) inside a PyInstaller+ on-dir layout (`<root>/NS Port Builder/_internal/nspb_qt/engine.py`), where `sys.frozen` is+ False in the child interpreter.+ """+ bases: list[Path] = []+ if getattr(sys, 'frozen', False):+ exe = Path(sys.executable).resolve()+ bases.extend((exe.parent, exe.parent.parent))+ here = Path(__file__).resolve()+ if len(here.parents) >= 4 and here.parents[1].name == '_internal':+ bases.extend((here.parents[2], here.parents[3]))+ for base in bases:cand = base / 'engine'if cand.joinpath('dm', 'games').is_dir() and cand.joinpath('scripts', 'build_ipa_from_nsp.py').is_file():return str(cand)diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex 542f80d8..f3493868 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -1346,6 +1346,7 @@ class Model(QObject):# A Mac app is a different output, not a different pipeline: --platform mac-app runs the# same steps and then packs dm/mac/pack_app.py's result. Its -o names the .app, and the# RomFS is inside it, so the archive step is skipped below.+ self.ipa_path = self.archive_path = self.mac_app_path = ''mac_app = self.target == 'mac-app'if mac_app:args += ['--platform', 'mac-app']@@ -1361,7 +1362,6 @@ class Model(QObject):self.running = Trueself.runningChanged.emit(True)self.stages = []- self.ipa_path = self.archive_path = self.mac_app_path = ''self.log_tail = ''self._last_error = ''self.failure = None@@ -1523,7 +1523,8 @@ class Model(QObject):versions = []if extract.is_dir():for d in sorted(extract.iterdir()):- if d.is_dir() and d.name.startswith('v') and (d / 'RomFS').is_dir():+ if d.is_dir() and d.name.startswith('v') and (+ (d / 'RomFS').is_dir() or (d / 'RomFS.img').is_file()):try:versions.append((int(d.name[1:]), d))except ValueError:@@ -1531,7 +1532,9 @@ class Model(QObject):if not versions:self.finished.emit(True, self.t('msg.archiveSkipped', str(extract)))return- romfs = str(versions[-1][1] / 'RomFS')+ ver_dir = versions[-1][1]+ romfs_img = ver_dir / 'RomFS.img'+ romfs = str(ver_dir / 'RomFS')# games/<id>/ is the per-game layout main.m looks in first, and the file inside it is# romfs.img — one file, which copies to a phone at full speed where 300,000 did notdest = str(Path(self.out_dir or Path(self.base_path).parent, 'romfs'))@@ -1539,19 +1542,38 @@ class Model(QObject):self.stagesChanged.emit()def work_() -> None:- args = [self.python_path, str(Path(self.engine_path, 'dm', 'tools', 'romfs_image.py')),- '--reuse', romfs, str(Path(dest, 'romfs.img'))]- env = pu.child_env({'PYTHONPATH': str(Path(self.engine_path, 'dm', 'tools'))})ok = True+ out_img = Path(dest, 'romfs.img')try:- p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- text=True, errors='replace', env=env,- **pu.no_window_kwargs())- assert p.stdout is not None- for line in p.stdout:- self.log(line)- p.wait()- ok = p.returncode == 0+ Path(dest).mkdir(parents=True, exist_ok=True)+ if romfs_img.is_file():+ reused = (out_img.is_file()+ and out_img.stat().st_size == romfs_img.stat().st_size+ and abs(out_img.stat().st_mtime - romfs_img.stat().st_mtime) < 1)+ if not reused:+ out_img.unlink(missing_ok=True)+ try:+ os.link(romfs_img, out_img)+ except OSError:+ shutil.copy2(romfs_img, out_img)+ else:+ args = [self.python_path,+ str(Path(self.engine_path, 'dm', 'tools', 'romfs_image.py')),+ '--reuse', romfs, str(out_img)]+ env = pu.child_env({'PYTHONPATH': str(Path(self.engine_path, 'dm', 'tools'))})+ p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, errors='replace', env=env,+ **pu.no_window_kwargs())+ assert p.stdout is not None+ for line in p.stdout:+ self.log(line)+ p.wait()+ ok = p.returncode == 0+ aoc_src = Path(work, 'aoc')+ if ok and aoc_src.is_dir() and any(aoc_src.iterdir()):+ aoc_dst = Path(dest, 'aoc')+ shutil.rmtree(aoc_dst, ignore_errors=True)+ shutil.copytree(aoc_src, aoc_dst)except OSError as e:self.log(f'{e}\n')ok = Falsediff --git a/frontend-qt/nspb_qt/win/build_app.py b/frontend-qt/nspb_qt/win/build_app.pyindex bd0106b8..f8dbce95 100644--- a/frontend-qt/nspb_qt/win/build_app.py+++ b/frontend-qt/nspb_qt/win/build_app.py@@ -36,20 +36,27 @@ from pathlib import Pathif __package__:from . import toolchain as tcfrom . import fix_ipa_modes+ from . import macho_signfrom . import IOS_CPU, IOS_DEPLOYMENTelse: # pragma: no cover - script modesys.path.insert(0, str(Path(__file__).resolve().parents[2]))from nspb_qt.win import toolchain as tcfrom nspb_qt.win import fix_ipa_modes+ from nspb_qt.win import macho_signfrom nspb_qt.win import IOS_CPU, IOS_DEPLOYMENTHERE = Path(__file__).resolve().parentdef _engine_root() -> str:- """The engine's folder when NSPB_REPO is unset: the checkout's engine/ (LNPANDY/NX2Apple#214, made by tools/engine.py sync)."""+ """The engine's folder when NSPB_REPO is unset: the checkout's or bundled engine/."""from nspb_qt import engine- return engine.engine_root(str(Path(__file__).resolve().parents[3]))+ for depth in (3, 4):+ if len(HERE.parents) > depth:+ cand = engine.engine_root(str(HERE.parents[depth]))+ if (Path(cand) / 'scripts' / 'build_ipa_from_nsp.py').is_file():+ return cand+ return engine.engine_root(str(HERE.parents[2]))#: Frameworks the app links. `Cocoa` is a macOS framework and is dropped; the rest is#: `dm/host/Makefile`'s link line minus Cocoa, plus what the UIKit side and the launcher use@@ -327,11 +334,13 @@ _HOST_MAIN: Path | None = Nonedef link(clang: Path, sdk: Path, objs: list[Path], frameworks: list[str], out: Path,deployment: str, embed_flags: list[str], rt_obj: Path | None,- lld_dir: Path | None) -> None:- """Link the app, then prove the result is an unsigned iOS executable."""+ lld_dir: Path | None, bundle_id: str = 'org.nxnative.app') -> None:+ """Link the app, then prove the result is an arm64 iOS executable and sign its entitlements."""+ entitle = os.environ.get('NSPB_ENTITLEMENTS', '1') != '0'args = [str(clang), '-target', f'arm64-apple-ios{deployment}', '-isysroot', str(sdk),'-fuse-ld=lld', '-fobjc-arc', '-o', str(out), *map(str, objs),'-Wl,-rpath,@executable_path/Frameworks', '-lobjc', '-lSystem',+ *(('-Wl,-adhoc_codesign',) if entitle else ()),*[x for fw in frameworks for x in ('-framework', fw)], *embed_flags]if rt_obj:args.append(str(rt_obj))@@ -344,6 +353,10 @@ def link(clang: Path, sdk: Path, objs: list[Path], frameworks: list[str], out: Pprint((r.stderr or r.stdout)[-6000:], file=sys.stderr)die('link failed (see the linker output above)')check_executable(out)+ if entitle:+ ents = {'com.apple.developer.kernel.increased-memory-limit': True}+ sig_n = macho_sign.sign(out, bundle_id, ents)+ t(f'sign: ad-hoc with Increased Memory Limit entitlement ({sig_n} B)')def check_executable(path: Path) -> None:@@ -488,13 +501,17 @@ def main(argv: list[str] | None = None) -> int:pkg = gp('package')patched = Path(env.get('PATCHED') or w / f'build/patched_{pkg}')- romfs = Path(env.get('ROMFS') or w / f'data/{pkg}/RomFS')+ default_romfs = (w / f'data/{pkg}/RomFS.img'+ if (w / f'data/{pkg}/RomFS.img').is_file() else w / f'data/{pkg}/RomFS')+ romfs = Path(env.get('ROMFS') or default_romfs)msl_ios = Path(env.get('MSL_IOS') or w / 'build/ios/dmsh_b')aoc = Path(env['AOC']) if env.get('AOC') else (None if 'AOC' in env else w / 'data/aoc')out_ipa = Path(args[0]) if args and not args[0].startswith('-') else \w.parent / gp('ipa')- mods = gp('modules').split()+ mods = (prof.modules_in(patched)+ if hasattr(prof, 'modules_in') and prof.modules_in(patched)+ else gp('modules').split())marker = gp('romfs_marker')# --- inputs, checked with the same wording as build_ipa.sh@@ -504,11 +521,11 @@ def main(argv: list[str] | None = None) -> int:if not romfs_has(repo, romfs, marker):die(f'no RomFS at {romfs} (missing {marker})')+ nacp = Path(env['CONTROL']) if env.get('CONTROL') else (w / 'data/v0/control.nacp')+ if not nacp.exists():+ nacp = romfs.parent / 'control.nacp'name = env.get('DM_DISPLAY_NAME') or ''if not name:- nacp = w / 'data/v0/control.nacp'- if not nacp.exists():- nacp = romfs.parent / 'control.nacp'try:name = py(repo / 'dm/tools/nacp.py', nacp)except SystemExit:@@ -593,7 +610,9 @@ def main(argv: list[str] | None = None) -> int:t('generate Gen/ (profile header, embedded modules, tables)')py(repo / 'dm/games/game.py', 'header', game, gen / 'profile/game_profile.h')es = gen / 'embed.S'- flags = py(repo / 'dm/ios/tools/gen_embed.py', patched, es, *mods)+ jit_img = romfs.parent / 'jit' / 'jit.img'+ embed_extra = [jit_img] if jit_img.is_file() else []+ flags = py(repo / 'dm/ios/tools/gen_embed.py', patched, es, *mods, *embed_extra)# the assembler treats '\' as an escape in .incbin pathses.write_text(re.sub(r'\.incbin "([^"]*)"',lambda mm: '.incbin "' + mm.group(1).replace('\\', '/') + '"',@@ -623,11 +642,15 @@ def main(argv: list[str] | None = None) -> int:if (gd / f).exists():shutil.copy2(gd / f, dmres)- launcher = py(repo / 'dm/games/settings.py', game, patched,- (romfs.parent / 'control.nacp') if (romfs.parent / 'control.nacp').exists()- else (w / 'data/v0/control.nacp'),+ launcher = py(repo / 'dm/games/settings.py', game, patched, nacp,gen / 'launcher.json', env=dict(env, GFXAPI=gfx))shutil.copy2(gen / 'launcher.json', dmres / 'launcher.json')+ if not env.get('DM_LANG'):+ try:+ import json+ lang = json.loads((gen / 'launcher.json').read_text(encoding='utf-8')).get('language') or lang+ except Exception:+ passt(f'launcher: {launcher}')if env.get('DM_ENV_FILE'):shutil.copy2(env['DM_ENV_FILE'], dmres / 'env.txt')@@ -668,7 +691,7 @@ def main(argv: list[str] | None = None) -> int:objs = compile_all(clang, sdk, files, incs, base / 'obj', deployment)link(clang, sdk, objs, frameworks, app / 'DmIOS', deployment,- flags.split() if flags else [], rt_obj, lld_dir)+ flags.split() if flags else [], rt_obj, lld_dir, bundle_id=bundle_id)# --- icon + Info.plisticon = Path(env.get('DM_ICON') or '')@@ -696,6 +719,13 @@ def main(argv: list[str] | None = None) -> int:maps.append(f'Payload/DmIOS.app/{resource}={romfs}')t('packing the full IPA with the RomFS (only sensible for small games)')else:+ if romfs.is_file():+ rid_file = base / 'romfs.id'+ r_id = subprocess.run([sys.executable, str(repo / 'dm/tools/romfs_image.py'),+ '--identity', str(romfs)], capture_output=True)+ if r_id.returncode == 0 and r_id.stdout:+ rid_file.write_bytes(r_id.stdout)+ maps.append(f'Payload/DmIOS.app/romfs.id={rid_file}')t('packing a slim IPA without the RomFS (the game files come from Documents/romfs)')store = gp('zip_store') or ''t('pack IPA')@@ -704,6 +734,9 @@ def main(argv: list[str] | None = None) -> int:pack += ['--store', ':'.join(store.split(':'))]for skip in PACK_SKIPS:pack += ['--skip', skip]+ prof_h = (gen / 'profile/game_profile.h').read_text(encoding='utf-8', errors='replace')+ if '#define DM_GAME_PSO_MTL4 1' not in prof_h:+ pack += ['--skip-suffix', '_bp.metallib']pack += mapsr = subprocess.run(pack, capture_output=True, text=True, errors='replace')if r.returncode:diff --git a/frontend-qt/nspb_qt/win/driver.py b/frontend-qt/nspb_qt/win/driver.pyindex b22dbdda..56887934 100644--- a/frontend-qt/nspb_qt/win/driver.py+++ b/frontend-qt/nspb_qt/win/driver.py@@ -56,9 +56,19 @@ REFUSED_OPTIONS = {def repo_dir() -> Path:- """The engine's folder: the checkout's engine/ (LNPANDY/NX2Apple#214, made by tools/engine.py sync)."""+ """The engine's folder: NSPB_REPO when set, else the checkout's or bundled engine/."""+ if env_repo := os.environ.get('NSPB_REPO'):+ p = Path(env_repo)+ if p.is_dir():+ return pfrom .. import engine- return Path(engine.engine_root(str(Path(__file__).resolve().parents[3])))+ here = Path(__file__).resolve()+ for depth in (3, 4):+ if len(here.parents) > depth:+ cand = Path(engine.engine_root(str(here.parents[depth])))+ if (cand / 'scripts' / 'build_ipa_from_nsp.py').is_file():+ return cand+ return Path(engine.engine_root(str(here.parents[3])))def load_upstream(repo: Path) -> ModuleType:@@ -183,6 +193,7 @@ def patch(mod: ModuleType, repo: Path, *, j: int | None = None) -> None:# ---------------------------------------------------------------- APFS clonesmod.can_clone = lambda d: Falsemod.apple_silicon = lambda: True # only the heap estimate below asks+ mod.ALLOW_OTHER_METAL = True # Windows Metal Tools version differs from Xcode's# ---------------------------------------------------------------- the Mac hostdef build_mac_host(repo_, out, env, logs, g):@@ -229,6 +240,107 @@ def patch(mod: ModuleType, repo: Path, *, j: int | None = None) -> None:return type(g)(g.dir)mod.heap_check = heap_check+ def region_skip(repo_, d, patched, work, env, logs, g):+ """The address-region check without the Mac host.++ Upstream boots the game in the Mac host to report where its address regions reach against+ the profile's alias region. Skipped on Windows and stamped with the rewrite ID so later+ builds do not ask again.+ """+ mod.PROG.stage('address regions (no Mac host)')+ say('no address region check: it boots the game in the Mac host, which needs a Mac; '+ 'the profile keeps its address-region keys')+ p = Path(g.dir) / 'game.tsv'+ old = [ln for ln in p.read_text(encoding='utf-8').rstrip('\n').split('\n')+ if not ln.startswith('# address regions: ')]+ rid = mod.rewrite_id(patched) if hasattr(mod, 'rewrite_id') else 'windows'+ p.write_text('\n'.join(old).rstrip('\n')+ + f'\n\n# address regions: {time.strftime("%Y-%m-%d")}, '+ f'not checked (no Mac host on this PC) (rewrite {rid})\n',+ encoding='utf-8')+ mod.PROG.end('skipped: needs the Mac host')+ return type(g)(g.dir)+ mod.region_check = region_skip++ # ---------------------------------------------------------------- derived romfs_marker & auto SDK cuts+ if not hasattr(mod, '_nspb_orig_derive_profile') and hasattr(mod, 'derive_profile'):+ mod._nspb_orig_derive_profile = mod.derive_profile++ if hasattr(mod, '_nspb_orig_derive_profile'):+ _orig_derive = mod._nspb_orig_derive_profile++ def derive_profile(g, pdir, ver, d, mods, *rest, **kw):+ disp = _orig_derive(g, pdir, ver, d, mods, *rest, **kw)+ tsv = Path(pdir) / 'game.tsv'+ lines = tsv.read_text(encoding='utf-8').splitlines()+ old = next((ln.split('\t', 1)[1] for ln in lines if ln.startswith('romfs_marker\t')), None)+ romfs = mod.rfs.source(d)+ if old and not (romfs / old).exists():+ files = [p for p in romfs.rglob('*') if p.is_file()]+ new = ('main.lua' if (romfs / 'main.lua').exists()+ else os.path.relpath(max(files, key=lambda p: p.stat().st_size),+ romfs).replace('\\', '/') if files else None)+ if new:+ tsv.write_text(+ '\n'.join(f'romfs_marker\t{new}' if ln.startswith('romfs_marker\t') else ln+ for ln in lines) + '\n',+ encoding='utf-8')+ say(f'romfs_marker: {old} is not in {ver}\'s RomFS; the derived profile uses {new}')+ return disp+ mod.derive_profile = derive_profile++ if not hasattr(mod, '_nspb_orig_rewrite') and hasattr(mod, 'rewrite'):+ mod._nspb_orig_rewrite = mod.rewrite+ mod._nspb_orig_patch_files = mod.patch_files++ if hasattr(mod, '_nspb_orig_rewrite'):+ _orig_rewrite = mod._nspb_orig_rewrite+ _orig_patch_files = mod._nspb_orig_patch_files++ def rewrite(py_, repo_, exe_dir, out, env, logs, g, provisional=False):+ import json+ from . import sdk_auto_cuts+ sdk_nso = Path(exe_dir) / 'sdk'+ jf = Path(out).with_name(Path(out).name + '.auto_sdk_cuts.json')+ if jf.exists():+ jf.unlink()+ try:+ sysres = int(g.get('sys_resource', '0') or '0', 0)+ except ValueError:+ sysres = 0+ if sdk_nso.is_file() and sysres:+ tools_dir = str(Path(repo_) / 'dm' / 'tools')+ if tools_dir not in sys.path:+ sys.path.insert(0, tools_dir)+ try:+ import importlib+ registered = importlib.import_module('sdk_patches').CUTS+ bid = mod.build_id(sdk_nso)+ if bid not in registered:+ _, cuts = sdk_auto_cuts.for_nso(sdk_nso, log=say, repo=repo_)+ if cuts:+ jf.parent.mkdir(parents=True, exist_ok=True)+ jf.write_text(json.dumps({bid: [list(c) for c in cuts]}, indent=1),+ encoding='utf-8')+ say(f'sdk {bid[:12]} is not in dm/tools/sdk_patches.py: '+ f'{len(cuts)} address-region cut(s) found in its code')+ except Exception:+ pass+ if jf.exists():+ os.environ['NSPB_AUTO_SDK_CUTS'] = env['NSPB_AUTO_SDK_CUTS'] = str(jf)+ else:+ os.environ.pop('NSPB_AUTO_SDK_CUTS', None)+ env.pop('NSPB_AUTO_SDK_CUTS', None)+ return _orig_rewrite(py_, repo_, exe_dir, out, env, logs, g, provisional)++ def patch_files(repo_, exe_dir, mods, game_id=None):+ f = _orig_patch_files(repo_, exe_dir, mods, game_id)+ j = os.environ.get('NSPB_AUTO_SDK_CUTS')+ return f + ([Path(j)] if j and Path(j).exists() else [])++ mod.rewrite = rewrite+ mod.patch_files = patch_files+# ---------------------------------------------------------------- the shader cache keydef toolchain_probe(repo_=None, env=None):"""What the shader-stage cache keys record as "the compilers".@@ -263,6 +375,13 @@ def patch(mod: ModuleType, repo: Path, *, j: int | None = None) -> None:mod.capture_glslc = _refuse_capture('this game')mod.capture_shaders = _refuse_capture('this game')+ def capture_jit(py_, repo_, d, patched, work, env, logs, g):+ if (Path(d) / 'jit' / 'jit.img').is_file():+ say(f'reusing the captured JIT image: {Path(d) / "jit/jit.img"}')+ return+ _refuse_capture('this game (nn::jit)')()+ mod.capture_jit = capture_jit+# ---------------------------------------------------------------- Mac outputsdef mac_app(*a, **k):raise BuildError('--platform mac-app packs a macOS app: it needs a Mac')diff --git a/frontend-qt/nspb_qt/win/macho_sign.py b/frontend-qt/nspb_qt/win/macho_sign.pynew file mode 100644index 00000000..20be46ae--- /dev/null+++ b/frontend-qt/nspb_qt/win/macho_sign.py@@ -0,0 +1,151 @@+"""An ad-hoc code signature with entitlements for the app's executable, made on Windows.++macOS has `codesign` / `ldid`. The IPA stays for the player's signing tool to sign (Sideloadly,+SideStore, AltStore): those keep the entitlements the executable asks for, filtered by what the+Apple ID's App ID allows. An executable with no signature asks for none, so SideStore installed+the app without Increased Memory Limit even after SideInstaller had enabled it for the App ID.++The executable must have been linked with `-Wl,-adhoc_codesign` (`ld64.lld` writes an+`LC_CODE_SIGNATURE` and a placeholder signature at the end of `__LINKEDIT`); this replaces that+signature with: a CodeDirectory (SHA-256, 4 KB pages, the main-binary exec segment, special+slots for the requirements, the entitlements and their DER form), an empty requirements set,+the entitlements plist and the DER entitlements.+"""+from __future__ import annotations++import hashlib+import plistlib+import struct+import sys+from pathlib import Path++CSMAGIC_REQUIREMENTS = 0xFADE0C01+CSMAGIC_CODEDIRECTORY = 0xFADE0C02+CSMAGIC_EMBEDDED_SIGNATURE = 0xFADE0CC0+CSMAGIC_ENTITLEMENTS = 0xFADE7171+CSMAGIC_ENTITLEMENTS_DER = 0xFADE7172+CSSLOT_CODEDIRECTORY, CSSLOT_REQUIREMENTS, CSSLOT_ENTITLEMENTS, CSSLOT_DER = 0, 2, 5, 7+LC_SEGMENT_64, LC_CODE_SIGNATURE = 0x19, 0x1D+PAGE = 12 # log2 of the code page size the hashes cover+++def der_len(n: int) -> bytes:+ if n < 0x80:+ return bytes([n])+ b = n.to_bytes((n.bit_length() + 7) // 8, 'big')+ return bytes([0x80 | len(b)]) + b+++def der(tag: int, body: bytes) -> bytes:+ return bytes([tag]) + der_len(len(body)) + body+++def der_value(v) -> bytes:+ if isinstance(v, bool):+ return der(0x01, b'\xff' if v else b'\x00')+ if isinstance(v, int):+ return der(0x02, v.to_bytes(max(1, (v.bit_length() + 8) // 8), 'big', signed=True))+ if isinstance(v, str):+ return der(0x0C, v.encode())+ if isinstance(v, (list, tuple)):+ return der(0x30, b''.join(der_value(x) for x in v))+ if isinstance(v, dict):+ return der(0xB0, b''.join(+ der(0x30, der(0x0C, k.encode()) + der_value(v[k])) for k in sorted(v)))+ raise ValueError(f'entitlement value {v!r}')+++def der_entitlements(ents: dict) -> bytes:+ """Apple's form: [APPLICATION 16] { INTEGER 1, [CONTEXT 16] { SEQUENCE { key, value } ... } }."""+ return der(0x70, der(0x02, b'\x01') + der_value(ents))+++def blob(magic: int, body: bytes) -> bytes:+ return struct.pack('>II', magic, 8 + len(body)) + body+++def sign(path: str | Path, ident: str, ents: dict) -> int:+ p = Path(path)+ b = bytearray(p.read_bytes())+ magic, _cpu, _sub, _ftype, ncmds, _sizeofcmds, _flags, _ = struct.unpack_from('<IiiIIIII', b, 0)+ if magic != 0xFEEDFACF:+ raise ValueError(f'{path}: not a 64-bit Mach-O')+ o, sig_lc, linkedit, text = 32, None, None, None+ for _ in range(ncmds):+ cmd, cs = struct.unpack_from('<II', b, o)+ if cmd == LC_CODE_SIGNATURE:+ sig_lc = o+ if cmd == LC_SEGMENT_64:+ name = bytes(b[o + 8:o + 24]).rstrip(b'\0')+ if name == b'__LINKEDIT':+ linkedit = o+ if name == b'__TEXT':+ text = o+ o += cs+ if sig_lc is None or linkedit is None:+ raise ValueError(f'{path}: no LC_CODE_SIGNATURE (link with -Wl,-adhoc_codesign)')+ dataoff = struct.unpack_from('<I', b, sig_lc + 8)[0]+ code_limit = dataoff+ xml = plistlib.dumps(ents, fmt=plistlib.FMT_XML)+ reqs = blob(CSMAGIC_REQUIREMENTS, struct.pack('>I', 0))+ ent = blob(CSMAGIC_ENTITLEMENTS, xml)+ entd = blob(CSMAGIC_ENTITLEMENTS_DER, der_entitlements(ents))+ nslots = CSSLOT_DER+ npages = (code_limit + (1 << PAGE) - 1) >> PAGE+ ident_b = ident.encode() + b'\0'+ hdr = 88 # CodeDirectory version 0x20400 header (through execSegFlags)+ hash_off = hdr + len(ident_b) + nslots * 32+ cd_len = hash_off + npages * 32+ text_fo, text_fs = struct.unpack_from('<QQ', b, text + 40) if text is not None else (0, 0)++ def superblob(cd: bytes) -> bytes:+ items = [(CSSLOT_CODEDIRECTORY, cd), (CSSLOT_REQUIREMENTS, reqs),+ (CSSLOT_ENTITLEMENTS, ent), (CSSLOT_DER, entd)]+ off = 12 + 8 * len(items)+ index = b''+ body = b''+ for slot, bl in items:+ index += struct.pack('>II', slot, off + len(body))+ body += bl+ return (struct.pack('>III', CSMAGIC_EMBEDDED_SIGNATURE,+ 12 + len(index) + len(body), len(items))+ + index + body)++ # the signature's final size is known before hashing: write the load command and __LINKEDIT+ # sizes first (they are inside the hashed pages)+ total = len(superblob(b'\0' * cd_len))+ size = (total + 15) & ~15+ struct.pack_into('<I', b, sig_lc + 12, size)+ le_fo = struct.unpack_from('<Q', b, linkedit + 40)[0]+ new_le = dataoff + size - le_fo+ # segment_command_64: cmd, cmdsize, segname[16], vmaddr @24, vmsize @32, fileoff @40, filesize @48+ struct.pack_into('<Q', b, linkedit + 32, (new_le + 0x3FFF) & ~0x3FFF) # vmsize, 16 KB pages+ struct.pack_into('<Q', b, linkedit + 48, new_le) # filesize+ del b[dataoff:]+ special = {CSSLOT_REQUIREMENTS: reqs, CSSLOT_ENTITLEMENTS: ent, CSSLOT_DER: entd}+ slots = b''.join(+ hashlib.sha256(special[i]).digest() if i in special else b'\0' * 32+ for i in range(nslots, 0, -1))+ hashes = b''.join(+ hashlib.sha256(bytes(b[i << PAGE:min((i + 1) << PAGE, code_limit)])).digest()+ for i in range(npages))+ cd = struct.pack(+ '>IIIIIIIIIBBBBIIIIQQQQ',+ CSMAGIC_CODEDIRECTORY, cd_len, 0x20400, 0x2, # magic, length, version, flags (adhoc)+ hash_off, hdr, nslots, npages, code_limit, # hashOffset, identOffset, nSpecialSlots, nCodeSlots, codeLimit+ 32, 2, 0, PAGE, 0, # hashSize, hashType SHA-256, platform, pageSize, spare2+ 0, 0, 0, 0, # scatterOffset, teamOffset, spare3, codeLimit64+ text_fo, text_fs, 1) # execSegBase, execSegLimit, execSegFlags (main binary)+ assert len(cd) == hdr, len(cd)+ cd += ident_b + slots + hashes+ sb = superblob(cd)+ b += sb + b'\0' * (size - len(sb))+ p.write_bytes(bytes(b))+ return len(sb)+++if __name__ == '__main__':+ exe, ident, ents_path = sys.argv[1:4]+ ents = plistlib.loads(Path(ents_path).read_bytes())+ n = sign(exe, ident, ents)+ print(f'signed {exe}: ad-hoc, {len(ents)} entitlements, signature {n} bytes')diff --git a/frontend-qt/nspb_qt/win/sdk_auto_cuts.py b/frontend-qt/nspb_qt/win/sdk_auto_cuts.pynew file mode 100644index 00000000..ec925243--- /dev/null+++ b/frontend-qt/nspb_qt/win/sdk_auto_cuts.py@@ -0,0 +1,127 @@+"""Find the address-region cuts of `dm/tools/sdk_patches.py` in an unregistered SDK build.++Upstream registers these cuts per `sdk` build ID (each found by hand: `docs/reference/memory.md`,+"The SDK's address-region node area" and "1 GB alignment of regions of 1 GB and more"). Without+them a Unity game's `nninitStartup` breaks in `StandardAllocator::Initialize` (e.g. Megabyte+Punch, SDK 8.3.1, on an iPad). This finds the same instructions from the code itself:++* node area: in the function the dynamic symbol `AddressRegionManager::AddressRegionManager`+ (C1/C2) names: exactly two loads of `#0x3fe00000` into `w8` / `w9` (`mov` or `orr` form),+ the node area limit and the length registered as occupied -> `#0x3e00000` (62 MB), as every+ registered build.+* alignment: in the code that follows that constructor (to its module's next 16 KB): exactly+ one load of `#0x40000000` into a register, preceded within six instructions by a load of+ `#0x2000000` and a right shift by 30 (the size class "1 GB and more"), as+ `AllocateAddressRegion`'s placement on SDK 7.3.2 / 8.2.1 / 10.4.x -> `#0x2000000` (32 MB).++Anything ambiguous (another count of matches, no symbol) gives no cut for that part, and the+build log says so. Registered builds keep their reviewed `CUTS`.+"""+from __future__ import annotations++import os+import struct+import sys+from pathlib import Path++NODE_OLD = {+ '08fca752': 'mov w8,#0x3fe00000',+ '09fca752': 'mov w9,#0x3fe00000',+ 'e8230b32': 'orr w8,wzr,#0x3fe00000',+ 'e9230b32': 'orr w9,wzr,#0x3fe00000',+}+NODE_NEW = {'w8': '087ca052', 'w9': '097ca052'} # mov w8 / w9, #0x3e00000+++def dyn_symbols(img: bytes) -> dict[str, tuple[int, int]]:+ """{name: (offset, size)} of the defined dynamic symbols."""+ mod0 = struct.unpack_from('<I', img, 4)[0]+ dyn = mod0 + struct.unpack_from('<i', img, mod0 + 4)[0]+ tags: dict[int, int] = {}+ for i in range(4096):+ t, v = struct.unpack_from('<qQ', img, dyn + i * 16)+ if t == 0:+ break+ tags.setdefault(t, v)+ symtab, strtab = tags[6], tags[5]+ out: dict[str, tuple[int, int]] = {}+ for i in range(1, (strtab - symtab) // 24):+ name, _info, _other, shndx, value, size = struct.unpack_from('<IBBHQQ', img, symtab + i * 24)+ if shndx:+ end = img.index(b'\0', strtab + name)+ out[img[strtab + name:end].decode('latin1')] = (value, size)+ return out+++def find(img: bytes, text_end: int, log=print) -> list[tuple[int, str, str, str]]:+ from capstone import CS_ARCH_ARM64, CS_MODE_ARM, Cs+ syms = dyn_symbols(img)+ ctor = next(((n, v) for n, v in syms.items()+ if 'AddressRegionManagerC2E' in n or 'AddressRegionManagerC1E' in n), None)+ if not ctor:+ log('sdk auto cuts: no AddressRegionManager constructor symbol: none')+ return []+ name, (start, size) = ctor+ size = size or 0x200+ cuts: list[tuple[int, str, str, str]] = []+ hits = [o for o in range(start, start + size, 4) if img[o:o + 4].hex() in NODE_OLD]+ if len(hits) == 2:+ for o in hits:+ w = img[o:o + 4].hex()+ reg = NODE_OLD[w].split()[1].split(',')[0]+ what = ('node area limit' if o == hits[0]+ else 'length of the node area registered as an occupied region')+ cuts.append((o, w, NODE_NEW[reg],+ f'AddressRegionManager constructor: {what} {NODE_OLD[w]} -> '+ f'mov {reg},#0x3e00000 (found by sdk_auto_cuts.py)'))+ else:+ log(f'sdk auto cuts: {len(hits)} loads of #0x3fe00000 in {name} (two expected): '+ 'no node area cut')+ md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)+ md.detail = False+ lo = start+ hi = min(text_end,+ (start + 0x4000) & ~0x3FFF if ((start + 0x4000) & ~0x3FFF) > start + size+ else start + 0x4000)+ ins = list(md.disasm(img[lo:hi], lo))+ align = []+ for i, x in enumerate(ins):+ if (x.mnemonic in ('mov', 'orr') and x.op_str.endswith('#0x40000000')+ and x.op_str.startswith('w')):+ back = ins[max(0, i - 6):i]+ if (any(b.mnemonic == 'mov' and b.op_str.endswith('#0x2000000') for b in back)+ and any(b.mnemonic == 'lsr' and b.op_str.endswith('#0x1e') for b in back)):+ align.append(x)+ if len(align) == 1:+ x = align[0]+ reg = x.op_str.split(',')[0]+ # movz wN, #0x200, lsl #16 = #0x2000000+ new = struct.pack('<I', 0x52A00000 | (0x200 << 5) | int(reg[1:])).hex()+ cuts.append((x.address, img[x.address:x.address + 4].hex(), new,+ f'AllocateAddressRegion: alignment of regions of 1 GB and more '+ f'{x.mnemonic} {x.op_str} -> mov {reg},#0x2000000 '+ f'(32 MB, as from 32 MB up; found by sdk_auto_cuts.py)'))+ else:+ log(f'sdk auto cuts: {len(align)} 1 GB alignment loads after {name} (one expected): '+ 'no alignment cut')+ return cuts+++def for_nso(path: str | Path, log=print, repo: str | Path | None = None) -> tuple[str, list[tuple[int, str, str, str]]]:+ if repo is None:+ repo = os.environ.get('NSPB_REPO')+ if repo:+ tools = str(Path(repo) / 'dm' / 'tools')+ if tools not in sys.path:+ sys.path.insert(0, tools)+ import nso_syms+ d = Path(path).read_bytes()+ text_end = struct.unpack_from('<III', d, 0x10)[2]+ return d[0x40:0x50].hex(), find(nso_syms.load(path), text_end, log)+++if __name__ == '__main__':+ bid, cuts = for_nso(sys.argv[1])+ print(bid)+ for c in cuts:+ print(f'{c[0]:#x}\t{c[1]}\t{c[2]}\t{c[3]}')diff --git a/frontend-qt/nspb_qt/win/shim.py b/frontend-qt/nspb_qt/win/shim.pyindex 7f8edb8d..f016fc61 100644--- a/frontend-qt/nspb_qt/win/shim.py+++ b/frontend-qt/nspb_qt/win/shim.py@@ -54,7 +54,7 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):# the package root goes on sys.path so `import toolchain` / `import xcrun_shim` resolve, and# so `import nspb_qt.win` works from a child that wants the whole package- for _p in (_PKG, os.path.dirname(_PKG)):+ for _p in (_PKG, os.path.dirname(_PKG), os.path.dirname(os.path.dirname(_PKG))):if _p and _p not in sys.path:sys.path.insert(0, _p)@@ -72,6 +72,140 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):io.open = builtins.open = _lf_open+ # ---- os.open binary mode & os.pread (POSIX-only on CPython for Windows)+ _os_open = os.open++ def _win_os_open(path, flags, mode=0o777, *, dir_fd=None):+ if not (flags & getattr(os, 'O_TEXT', 0)):+ flags |= getattr(os, 'O_BINARY', 0)+ if dir_fd is not None:+ return _os_open(path, flags, mode, dir_fd=dir_fd)+ return _os_open(path, flags, mode)++ os.open = _win_os_open++ if not hasattr(os, 'pread'):+ import threading as _threading+ _pread_lock = _threading.Lock()++ def _win_pread(fd, n, offset):+ with _pread_lock:+ cur = os.lseek(fd, 0, os.SEEK_CUR)+ try:+ os.lseek(fd, offset, os.SEEK_SET)+ out = bytearray()+ while len(out) < n:+ chunk = os.read(fd, n - len(out))+ if not chunk:+ break+ out.extend(chunk)+ return bytes(out)+ finally:+ try:+ os.lseek(fd, cur, os.SEEK_SET)+ except OSError:+ pass++ os.pread = _win_pread++ # ---- os.symlink fallback when Developer Mode is off (WinError 1314)+ _os_symlink = os.symlink++ def _win_symlink(src, dst, target_is_directory=False, *, dir_fd=None):+ try:+ if dir_fd is not None:+ return _os_symlink(src, dst, target_is_directory=target_is_directory, dir_fd=dir_fd)+ return _os_symlink(src, dst, target_is_directory=target_is_directory)+ except OSError:+ real_src = src+ if not os.path.isabs(src):+ real_src = os.path.normpath(os.path.join(os.path.dirname(os.fspath(dst)), src))+ if os.path.isdir(real_src):+ shutil.copytree(real_src, dst, dirs_exist_ok=True)+ else:+ shutil.copy2(real_src, dst)++ os.symlink = _win_symlink++ # ---- POSIX slashes in os.path.relpath and romfs.py+ # Upstream's shader_split.py, gl_shaders.py, vk_shaders.py, uepak.py and nro_collect.py+ # sort and record RomFS-relative paths with '/' (and compare them against shader_map.tsv).+ _relpath = os.path.relpath++ def _posix_relpath(path, start=None):+ r = _relpath(path, start) if start is not None else _relpath(path)+ return r.replace('\\', '/') if isinstance(r, str) else r.replace(b'\\', b'/')++ os.path.relpath = _posix_relpath++ def _patch_romfs_module(mod):+ if getattr(mod, '_nspb_patched', False):+ return+ mod._nspb_patched = True+ _orig_find = mod.Image.find+ mod.Image.find = lambda self, rel: _orig_find(self, rel.replace('\\', '/'))++ def _resolve(path):+ p = os.path.abspath(os.fsdecode(path)).replace('\\', '/')+ parts = p.split('/')+ for i, part in enumerate(parts):+ if not part.endswith('.img'):+ continue+ image = '/'.join(parts[:i + 1])+ try:+ st = os.stat(image)+ except OSError:+ continue+ if not mod._stat.S_ISREG(st.st_mode):+ continue+ loaded = mod._image(image, (st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns))+ if loaded is not None:+ return loaded, '/'.join(parts[i + 1:])+ return None++ mod._resolve = _resolve+ _orig_walk = mod.walk++ def _walk(top, *a, **k):+ for root, dirs, files in _orig_walk(top, *a, **k):+ yield (root.replace('\\', '/') if isinstance(root, str) else root), dirs, files++ mod.walk = _walk+ mod.os.walk = _walk+ _orig_join = os.path.join++ def _posix_join(*a):+ res = _orig_join(*a)+ return res.replace('\\', '/') if isinstance(res, str) else res++ mod._PathOps.join = staticmethod(_posix_join)++ def _patch_sdk_patches_module(mod):+ jf = os.environ.get('NSPB_AUTO_SDK_CUTS')+ if not jf or not hasattr(mod, 'CUTS') or not os.path.isfile(jf):+ return+ try:+ import json+ with open(jf, 'r', encoding='utf-8') as f:+ data = json.load(f)+ for bid, cuts in data.items():+ mod.CUTS.setdefault(bid, [tuple(c) for c in cuts])+ except Exception:+ pass++ import importlib.machinery as _machinery+ _exec_module = _machinery.SourceFileLoader.exec_module++ def _win_exec_module(self, module):+ _exec_module(self, module)+ name = getattr(module, '__name__', '')+ if name == 'romfs' or name.endswith('.romfs'):+ _patch_romfs_module(module)+ elif name == 'sdk_patches' or name.endswith('.sdk_patches'):+ _patch_sdk_patches_module(module)++ _machinery.SourceFileLoader.exec_module = _win_exec_module+# ---- os.replace as on a Mac# Windows refuses to replace a file another thread has open. The shader caches are# content-addressed, so two workers finishing the same entry is a legitimate race that@@ -188,8 +322,13 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):dn = tc.dotnet_dir()dotnet = str(dn / 'dotnet.exe') if dn else (shutil.which('dotnet') or 'dotnet')return [dotnet, args[0] + '.dll'] + args[1:]- if base in ('python3', 'python3.exe'):- return [sys.executable] + args[1:]+ if base in ('python3', 'python3.exe') or base in ('python', 'python.exe'):+ py_exe = os.environ.get('NSPB_PYTHON') or sys.executable+ return [py_exe] + [a for a in args[1:] if a != '-I']+ if base in ('spirv-cross', 'spirv-cross.exe'):+ sc = os.environ.get('NSPB_SPIRV_CROSS') or os.environ.get('SPIRV_CROSS')+ if sc and os.path.isfile(sc):+ return [sc] + args[1:]if base in ('bash', 'bash.exe') and len(args) > 1 and \args[1].replace('\\', '/').endswith('dm/ios/tools/build_ipa.sh'):return [sys.executable, _BUILD_APP] + args[2:]@@ -325,6 +464,11 @@ def build_env(base: dict[str, str] | None = None, python_exe: str | None = None)parts.append(str(p.parent))if name == 'spirv-cross':env.setdefault('SPIRV_CROSS', str(p))+ env['NSPB_SPIRV_CROSS'] = str(p)+ if python_exe:+ env['NSPB_PYTHON'] = str(python_exe)+ env.setdefault('DM_ALLOW_SYSTEM_SPIRV_CROSS', '1')+ env.setdefault('DM_ALLOW_OTHER_METAL', '1')# tc.dotnet_dir() first: it knows about the SDK the app installed for itself, which is not on# PATH and not in Program Files. `which` alone missed it, so `dotnet build` and the shader# translator failed on a machine that had just installed .NET through this app.@@ -334,9 +478,11 @@ def build_env(base: dict[str, str] | None = None, python_exe: str | None = None)elif dn := shutil.which('dotnet'):parts.append(str(Path(dn).parent))+ pkg_root = str(Path(__file__).resolve().parents[2])env['PATH'] = os.pathsep.join(dict.fromkeys(parts + [env.get('PATH', '')]))env['PYTHONPATH'] = os.pathsep.join(- dict.fromkeys([str(sd)] + [p for p in env.get('PYTHONPATH', '').split(os.pathsep) if p]))+ dict.fromkeys([str(sd), pkg_root]+ + [p for p in env.get('PYTHONPATH', '').split(os.pathsep) if p]))env.setdefault('PYTHONUTF8', '1') # the pipeline reads and writes UTF-8 without naming itenv.setdefault('PYTHONIOENCODING', 'utf-8')@@ -364,7 +510,7 @@ def verify_shim(env: dict[str, str]) -> tuple[bool, str]:try:r = subprocess.run([env.get('NSPB_PYTHON') or sys.executable, '-c','import sys; sys.exit(0 if "sitecustomize" in sys.modules else 3)'],- capture_output=True, text=True, env=env, timeout=60)+ capture_output=True, text=True, env=env, timeout=60, **tc.no_window())except (OSError, subprocess.SubprocessError) as e:return False, f'cannot run a probe interpreter: {e}'if r.returncode == 0:diff --git a/frontend-qt/nspb_qt/win/toolchain.py b/frontend-qt/nspb_qt/win/toolchain.pyindex abaadb36..188311ad 100644--- a/frontend-qt/nspb_qt/win/toolchain.py+++ b/frontend-qt/nspb_qt/win/toolchain.py@@ -815,6 +815,25 @@ def find_exe(name: str) -> Path | None:own = tools_dir() / f'zstd-{ZSTD_VERSION}' / f'{name}.exe'if name == 'zstd' and own.is_file():return own+ if name == 'spirv-cross':+ if env_sc := os.environ.get('NSPB_SPIRV_CROSS'):+ p = Path(env_sc)+ if p.is_file():+ return p+ here = Path(__file__).resolve()+ roots = [os.environ.get('NSPB_REPO')]+ for anc in here.parents:+ roots.append(str(anc / 'engine'))+ try:+ from .. import engine as _eng+ roots.extend((_eng.bundled_engine(), _eng.engine_root(str(here.parents[3]))))+ except Exception:+ pass+ for r in roots:+ if r:+ p = Path(r) / 'dm' / 'gfx' / 'tools' / 'spirv_cross_bin' / 'spirv-cross.exe'+ if p.is_file():+ return pfor cand in (f'{name}.exe', name):if w := shutil.which(cand):return Path(w)diff --git a/frontend-qt/tests/test_engine_layout.py b/frontend-qt/tests/test_engine_layout.pyindex c25e1514..eaa4ea8c 100644--- a/frontend-qt/tests/test_engine_layout.py+++ b/frontend-qt/tests/test_engine_layout.py@@ -176,6 +176,21 @@ class BundledEngine(unittest.TestCase):self.assertTrue(engine.is_stale(str(repo)))self.assertEqual(engine.engine_root(str(repo)), str(repo / 'engine'))+ def test_external_venv_python_finds_bundled_engine_via_internal_layout(self):+ """A child venv python has sys.frozen=False, but __file__ is inside _internal/nspb_qt/."""+ self.set_frozen(False)+ eng = self.tree(self.r)+ fake_file = self.app / '_internal' / 'nspb_qt' / 'engine.py'+ fake_file.parent.mkdir(parents=True, exist_ok=True)+ fake_file.write_text('x')+ orig_file = engine.__file__+ try:+ engine.__file__ = str(fake_file)+ self.assertEqual(engine.bundled_engine(), str(eng))+ self.assertEqual(engine.engine_root(''), str(eng))+ finally:+ engine.__file__ = orig_file+class OnlineSync(unittest.TestCase):"""A release carries no engine: the first start downloads it, and a failed fetch is a failure row (no Qt needed)."""diff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.pyindex a1a402d7..dd6b1215 100644--- a/frontend-qt/tests/test_win.py+++ b/frontend-qt/tests/test_win.py@@ -1728,7 +1728,7 @@ class PlatformIsolationTest(unittest.TestCase):code = ('import sys; sys.path.insert(0, %r)\n''from nspb_qt.win import toolchain, sdk_fetch, shim, fix_ipa_modes, fetch, '- 'doctor, build_app, driver, xcrun_shim\n'+ 'doctor, build_app, driver, xcrun_shim, macho_sign, sdk_auto_cuts\n''print("ok")\n') % str(QT)r = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True,@@ -2091,9 +2091,169 @@ class InstallFailureHintTest(unittest.TestCase):classify = ns['_classify_install_failure']self.assertEqual(classify('DownloadError: connection reset by peer'), 'dep.fix.network')self.assertEqual(classify('URLError: operation timed out'), 'dep.fix.network')- self.assertEqual(classify('OSError: [Errno 28] No space left on device'), 'dep.fix.diskspace')+ self.assertEqual( classify('OSError: [Errno 28] No space left on device'), 'dep.fix.diskspace')self.assertEqual(classify('KeyError: x'), 'dep.fix.log')+class WindowsBuildFixesTest(unittest.TestCase):+ """Regression tests for the Windows build pipeline fixes."""++ def test_shim_puts_package_parent_on_sys_path_and_passes_nspb_python(self) -> None:+ self.assertIn('os.path.dirname(os.path.dirname(_PKG))', shim._SITECUSTOMIZE_SRC)+ with tempfile.TemporaryDirectory() as td:+ with mock.patch.object(shim, 'shim_dir', return_value=Path(td)):+ env = shim.build_env({'PATH': '', 'PYTHONPATH': ''}, python_exe='C:\\venv\\python.exe')+ self.assertEqual(env['NSPB_PYTHON'], 'C:\\venv\\python.exe')+ self.assertEqual(env['DM_ALLOW_SYSTEM_SPIRV_CROSS'], '1')+ self.assertEqual(env['DM_ALLOW_OTHER_METAL'], '1')+ pkg_root = str(QT)+ self.assertIn(pkg_root, env['PYTHONPATH'].split(os.pathsep))++ def test_romfs_backslash_paths_and_pread_with_real_image(self) -> None:+ """Pack a real RomFS.img with romfs_image.py and verify backslash lookups and pread."""+ tools_dir = str(QT.parent / 'engine' / 'dm' / 'tools')+ if not Path(tools_dir, 'romfs_image.py').is_file():+ self.skipTest('engine/ is missing')+ if tools_dir not in sys.path:+ sys.path.insert(0, tools_dir)+ import importlib+ import romfs+ import romfs_image++ # Execute the shim's romfs patcher and _win_pread helper from _SITECUSTOMIZE_SRC+ ns: dict = {'os': os, 'sys': sys}+ src = shim._SITECUSTOMIZE_SRC+ start = src.index(' def _patch_romfs_module(mod):')+ end = src.index(' def _patch_sdk_patches_module(mod):')+ exec('\n'.join(ln[4:] for ln in src[start:end].splitlines()), ns)+ ns['_patch_romfs_module'](romfs)++ pread_start = src.index(' def _win_pread(fd, n, offset):')+ pread_end = src.index(' os.pread = _win_pread')+ import threading+ ns['_threading'] = threading+ ns['_pread_lock'] = threading.Lock()+ exec('\n'.join(ln[8:] for ln in src[pread_start:pread_end].splitlines()), ns)+ win_pread = ns['_win_pread']++ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ v0 = root / 'v0'+ rdir = v0 / 'RomFS'+ (rdir / 'Shader' / 'sub').mkdir(parents=True)+ payload = b'binary\x1a\r\ndata\x00end'+ (rdir / 'Shader' / 'sub' / 'test.bin').write_bytes(payload)+ img_path = v0 / 'RomFS.img'+ romfs_image.pack(str(rdir), str(img_path))+ shutil.rmtree(rdir)++ # Test _win_pread preserves fd offset and reads exact binary bytes+ fd = os.open(str(img_path), os.O_RDONLY | getattr(os, 'O_BINARY', 0))+ try:+ os.lseek(fd, 4, os.SEEK_SET)+ magic = win_pread(fd, 8, 0)+ self.assertEqual(magic, b'DMROMFS1')+ self.assertEqual(os.lseek(fd, 0, os.SEEK_CUR), 4)+ finally:+ os.close(fd)++ # Test backslash path resolution against RomFS.img+ romfs._image.cache_clear()+ src_path = romfs.source(v0)+ self.assertTrue(romfs.isfile(str(img_path) + r'\Shader\sub\test.bin'))+ with romfs.open(str(img_path) + r'\Shader\sub\test.bin', 'rb') as f:+ self.assertEqual(f.read(), payload)+ walked = list(romfs.walk(src_path))+ self.assertTrue(any(r.endswith('Shader/sub') and 'test.bin' in fs for r, _, fs in walked))+ self.assertFalse(any('\\' in r for r, _, _ in walked))+ joined = romfs.os.path.join('Shader\\sub', 'test.bin')+ self.assertEqual(joined, 'Shader/sub/test.bin')++ def test_macho_sign_produces_valid_adhoc_signature_with_entitlements(self) -> None:+ from nspb_qt.win import macho_sign+ if sys.platform != 'darwin' or not shutil.which('clang') or not shutil.which('codesign'):+ self.skipTest('macOS clang and codesign required for end-to-end verification')+ with tempfile.TemporaryDirectory() as td:+ c_file = Path(td) / 'main.c'+ exe = Path(td) / 'DmIOS'+ c_file.write_text('int main(void) { return 0; }\n', encoding='utf-8')+ r = subprocess.run(['clang', '-arch', 'arm64', '-Wl,-adhoc_codesign',+ str(c_file), '-o', str(exe)], capture_output=True, text=True)+ if r.returncode != 0:+ self.skipTest(f'clang could not build arm64 binary: {r.stderr}')+ ents = {'com.apple.developer.kernel.increased-memory-limit': True}+ sig_len = macho_sign.sign(exe, 'org.nxnative.test', ents)+ self.assertGreater(sig_len, 100)+ v = subprocess.run(['/usr/bin/codesign', '--verify', '-vvv', str(exe)],+ capture_output=True, text=True)+ self.assertEqual(v.returncode, 0, v.stderr + v.stdout)+ d = subprocess.run(['/usr/bin/codesign', '-d', '--entitlements', ':-', str(exe)],+ capture_output=True, text=True)+ self.assertEqual(d.returncode, 0, d.stderr)+ self.assertIn('com.apple.developer.kernel.increased-memory-limit', d.stdout)++ def test_driver_region_skip_stamps_rewrite_id_and_capture_jit_reuses_image(self) -> None:+ from nspb_qt.win import driver+ repo = QT.parent / 'engine'+ if not (repo / 'scripts/build_ipa_from_nsp.py').is_file():+ self.skipTest('engine/ is missing')+ mod = driver.load_upstream(repo)+ driver.patch(mod, repo)+ self.assertTrue(mod.ALLOW_OTHER_METAL)+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ gdir = root / 'profile'+ gdir.mkdir()+ (gdir / 'game.tsv').write_text('id\ttest\npackage\tv0\n', encoding='utf-8')+ patched = root / 'patched_v0'+ patched.mkdir()+ (patched / 'main.patched.bin').write_bytes(b'1234')++ class FakeGame:+ def __init__(self, d):+ self.dir = Path(d)++ g = mod.region_check(repo, root, patched, root, {}, root, FakeGame(gdir))+ self.assertTrue(mod.region_checked(g, patched))++ # capture_jit raises when jit.img is absent, succeeds when present+ with self.assertRaises(mod.BuildError):+ mod.capture_jit('py', repo, root, patched, root, {}, root, g)+ (root / 'jit').mkdir()+ (root / 'jit' / 'jit.img').write_bytes(b'jit')+ mod.capture_jit('py', repo, root, patched, root, {}, root, g)++ def test_pack_archive_handles_romfs_img_and_copies_aoc(self) -> None:+ import time+ try:+ from nspb_qt.model import Model+ except ImportError:+ self.skipTest('PySide6 is not installed')+ with tempfile.TemporaryDirectory() as td:+ root = Path(td)+ work = root / 'work'+ v0 = work / 'extract' / 'v0'+ v0.mkdir(parents=True)+ (v0 / 'RomFS.img').write_bytes(b'DMROMFS1_payload')+ aoc = work / 'aoc'+ aoc.mkdir(parents=True)+ (aoc / '0.img').write_bytes(b'dlc0')+ out = root / 'out'+ out.mkdir()+ with mock.patch.object(Model, 'check_deps', lambda self: None):+ m = Model()+ m.effective_work_dir = str(work)+ m.out_dir = str(out)+ m.base_path = str(root / 'game.nsp')+ m.pack_archive()+ for _ in range(50):+ if m.archive_path:+ break+ time.sleep(0.02)+ self.assertEqual(m.archive_path, str(out / 'romfs'))+ self.assertEqual((out / 'romfs' / 'romfs.img').read_bytes(), b'DMROMFS1_payload')+ self.assertEqual((out / 'romfs' / 'aoc' / '0.img').read_bytes(), b'dlc0')++if __name__ == '__main__':unittest.main(verbosity=2)