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 patch_nso pthread_sigmask, romfs normpath/sep, tool_lock spirv-cross and UTF-8 log decoding on Windows
LNPANDYae94dd683002
diff --git a/frontend-qt/nspb_qt/engine.py b/frontend-qt/nspb_qt/engine.pyindex 5a71f44b..cb11fac5 100644--- a/frontend-qt/nspb_qt/engine.py+++ b/frontend-qt/nspb_qt/engine.py@@ -151,7 +151,7 @@ def run_sync(cmd: list[str], cwd: str, line: Callable[[str], None], **popen) ->"""Run the sync command, pass its lines on, and return (ok, failure kind or None). Blocking: call it off the UI thread."""tail = ''try:- p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors='replace', **popen)+ p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding='utf-8', errors='replace', **popen)assert p.stdout is not Nonefor out in p.stdout:line(out)diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex f3493868..366c6e81 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -615,7 +615,8 @@ class Model(QObject):p = subprocess.Popen([git, 'clone', '--depth', '1', '--single-branch', '--progress',self.REPO_URL, target],stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,- errors='replace', env=pu.child_env(), **pu.no_window_kwargs())+ encoding='utf-8', errors='replace', env=pu.child_env(),+ **pu.no_window_kwargs())assert p.stdout is not Nonefor line in p.stdout:self.log(line.replace('\r', '\n'))@@ -764,7 +765,7 @@ class Model(QObject):try:p = subprocess.Popen(dep.install, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, text=True,- errors='replace', env=pu.child_env(),+ encoding='utf-8', errors='replace', env=pu.child_env(),**pu.no_window_kwargs())assert p.stdout is not Nonefor line in p.stdout:@@ -1061,8 +1062,8 @@ class Model(QObject):+ ('' if wheels else ' (from PyPI)') + '\n')try:p = subprocess.Popen([vpy, '-m', 'pip'] + args, stdout=subprocess.PIPE,- stderr=subprocess.STDOUT, text=True, errors='replace',- env=pu.child_env(), **pu.no_window_kwargs())+ stderr=subprocess.STDOUT, text=True, encoding='utf-8',+ errors='replace', env=pu.child_env(), **pu.no_window_kwargs())assert p.stdout is not Nonefor line in p.stdout:self.log(line)@@ -1396,7 +1397,8 @@ class Model(QObject):try:self._proc = subprocess.Popen([py] + args, cwd=cwd,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- text=True, errors='replace', bufsize=1, env=env,+ text=True, encoding='utf-8', errors='replace',+ bufsize=1, env=env,**pu.no_window_kwargs())assert self._proc.stdout is not Nonefor line in self._proc.stdout:@@ -1489,28 +1491,28 @@ class Model(QObject):else goes to the log (which is what the window shows)."""self.log(line + '\n')self.log_tail = (self.log_tail + line + '\n')[-12000:] # what the classifier reads on a failure+ body = re.sub(r'^\[\d\d:\d\d:\d\d\]\s*', '', line)# The last line that was not stage bookkeeping: a failed build's summary used to be the# bare exit code ("Build failed (exit code 1)"), which told the reporter nothing and sent# them looking for a log that a short window had below the fold (issue #52)- if line.strip() and not (line.startswith('[') and ']' in line and line.find(']') + 1 < len(line)):- self._last_error = line.strip()[:200]- if line.startswith('output IPA:'):- self.ipa_path = line.split(':', 1)[1].strip()- low = line.lower()+ is_stage = (body.startswith('[') and ']' in body+ and '/' in body[:body.find(']') + 1]+ and body.find(']') + 1 < len(body))+ if body.strip() and not is_stage:+ self._last_error = body.strip()[:200]+ if body.startswith('output IPA:'):+ self.ipa_path = body.split(':', 1)[1].strip()for st in self.stages:if st.state == 'running':- st.detail = line[:120]+ st.detail = body[:120]break- if '[' in line and ']' in line:- head = line[:line.find(']') + 1]- if '/' in head:- name = line[line.find(']') + 1:].strip()- if name:- if self.stages and self.stages[-1].state == 'running':- self.stages[-1].state = 'done'- self.stages.append(Stage(name=name, state='running'))- self.stagesChanged.emit()- del low+ if is_stage:+ name = body[body.find(']') + 1:].strip()+ if name and '✓' not in name:+ if self.stages and self.stages[-1].state == 'running':+ self.stages[-1].state = 'done'+ self.stages.append(Stage(name=name, state='running'))+ self.stagesChanged.emit()def _flush_lines(self) -> None:self._line_buf = ''@@ -1562,7 +1564,7 @@ class Model(QObject):'--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,+ text=True, encoding='utf-8', errors='replace', env=env,**pu.no_window_kwargs())assert p.stdout is not Nonefor line in p.stdout:diff --git a/frontend-qt/nspb_qt/platform_util.py b/frontend-qt/nspb_qt/platform_util.pyindex 2ac85cd9..7c671e4f 100644--- a/frontend-qt/nspb_qt/platform_util.py+++ b/frontend-qt/nspb_qt/platform_util.py@@ -357,6 +357,8 @@ def child_env(extra: dict[str, str] | None = None) -> dict[str, str]:# telemetry call can hang the very first run on a network that cannot reach Microsoft.env.setdefault('DOTNET_CLI_TELEMETRY_OPTOUT', '1')env.setdefault('DOTNET_NOLOGO', '1')+ env.setdefault('PYTHONUTF8', '1')+ env.setdefault('PYTHONIOENCODING', 'utf-8')if extra:env.update(extra)return envdiff --git a/frontend-qt/nspb_qt/win/shim.py b/frontend-qt/nspb_qt/win/shim.pyindex f016fc61..bc73ea31 100644--- a/frontend-qt/nspb_qt/win/shim.py+++ b/frontend-qt/nspb_qt/win/shim.py@@ -58,6 +58,24 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):if _p and _p not in sys.path:sys.path.insert(0, _p)+ # ---- POSIX signal & os.execve stubs for patch_nso.py+ # patch_nso.py's in_parallel() uses fork() + signal.pthread_sigmask when WORKERS >= 2;+ # rewrite() already runs one patch_nso.py process per NSO in parallel, so default+ # DM_REWRITE_J=1 on Windows and provide pthread_sigmask stubs in case it is called.+ os.environ.setdefault('DM_REWRITE_J', '1')+ import signal as _signal+ for _sig_attr, _sig_val in (('SIG_BLOCK', 1), ('SIG_UNBLOCK', 2), ('SIG_SETMASK', 3)):+ if not hasattr(_signal, _sig_attr):+ setattr(_signal, _sig_attr, _sig_val)+ if not hasattr(_signal, 'pthread_sigmask'):+ _signal.pthread_sigmask = lambda how, mask: set()++ def _win_execve(path, argv, env):+ r = subprocess.run([os.fspath(path)] + [os.fspath(a) for a in list(argv)[1:]], env=env)+ os._exit(r.returncode)++ os.execve = _win_execve+# ---- text files written the way the pipeline expects them# The host compares lines of the pipeline's tables byte for byte; an inputs.tsv line ending# in "\r" did not match on the device (found by the reference implementation the hard way).@@ -172,13 +190,22 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):mod.walk = _walkmod.os.walk = _walk+ mod._OS.sep = '/'+ mod._PathOps.sep = '/'_orig_join = os.path.join+ _orig_normpath = os.path.normpathdef _posix_join(*a):res = _orig_join(*a)return res.replace('\\', '/') if isinstance(res, str) else res+ def _posix_normpath(path):+ res = _orig_normpath(path)+ return res.replace('\\', '/') if isinstance(res, str) else res.replace(b'\\', b'/')+mod._PathOps.join = staticmethod(_posix_join)+ mod._PathOps.relpath = staticmethod(_posix_relpath)+ mod._PathOps.normpath = staticmethod(_posix_normpath)def _patch_sdk_patches_module(mod):jf = os.environ.get('NSPB_AUTO_SDK_CUTS')@@ -193,6 +220,21 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):except Exception:pass+ def _patch_tool_lock_module(mod):+ if getattr(mod, '_nspb_patched', False) or not hasattr(mod, 'check_tools'):+ return+ mod._nspb_patched = True+ _orig_check = mod.check_tools++ def _win_check_tools():+ bad = _orig_check()+ if os.environ.get('DM_ALLOW_SYSTEM_SPIRV_CROSS') == '1':+ bad = [b for b in bad+ if not (b.startswith('spirv-cross: ') and not b.endswith(' / actual missing'))]+ return bad++ mod.check_tools = _win_check_tools+import importlib.machinery as _machinery_exec_module = _machinery.SourceFileLoader.exec_module@@ -203,6 +245,8 @@ if os.name == 'nt' and not os.environ.get('NSPB_SHIM_OFF'):_patch_romfs_module(module)elif name == 'sdk_patches' or name.endswith('.sdk_patches'):_patch_sdk_patches_module(module)+ elif name == 'tool_lock' or name.endswith('.tool_lock'):+ _patch_tool_lock_module(module)_machinery.SourceFileLoader.exec_module = _win_exec_module@@ -469,6 +513,7 @@ def build_env(base: dict[str, str] | None = None, python_exe: str | None = None)env['NSPB_PYTHON'] = str(python_exe)env.setdefault('DM_ALLOW_SYSTEM_SPIRV_CROSS', '1')env.setdefault('DM_ALLOW_OTHER_METAL', '1')+ env.setdefault('DM_REWRITE_J', '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.diff --git a/frontend-qt/tests/test_win.py b/frontend-qt/tests/test_win.pyindex 95169104..ee37824f 100644--- a/frontend-qt/tests/test_win.py+++ b/frontend-qt/tests/test_win.py@@ -2106,6 +2106,7 @@ class WindowsBuildFixesTest(unittest.TestCase):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')+ self.assertEqual(env['DM_REWRITE_J'], '1')pkg_root = str(QT)self.assertIn(pkg_root, env['PYTHONPATH'].split(os.pathsep))@@ -2123,7 +2124,7 @@ class WindowsBuildFixesTest(unittest.TestCase):# Execute the shim's romfs patcher and _win_pread helper from _SITECUSTOMIZE_SRCns: dict = {'os': os, 'sys': sys}src = shim._SITECUSTOMIZE_SRC- start = src.index(' def _patch_romfs_module(mod):')+ start = src.index(' _relpath = os.path.relpath')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)@@ -2168,6 +2169,11 @@ class WindowsBuildFixesTest(unittest.TestCase):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')+ self.assertEqual(romfs.os.sep, '/')+ self.assertEqual(romfs.os.path.sep, '/')+ self.assertEqual(romfs.os.path.normpath('Shader\\sub\\test.bin'), 'Shader/sub/test.bin')+ self.assertEqual(romfs.os.path.relpath(str(src_path) + '/Shader/sub/test.bin', str(src_path)),+ 'Shader/sub/test.bin')def test_macho_sign_produces_valid_adhoc_signature_with_entitlements(self) -> None:from nspb_qt.win import macho_sign@@ -2290,6 +2296,59 @@ class WindowsBuildFixesTest(unittest.TestCase):mock.patch.object(tc, 'setting', return_value=None):self.assertEqual(tc.find_exe('glslangValidator'), spv)+ def test_shim_patches_signal_pthread_sigmask_and_tool_lock_spirv_cross(self) -> None:+ src = shim._SITECUSTOMIZE_SRC+ self.assertIn("os.environ.setdefault('DM_REWRITE_J', '1')", src)+ self.assertIn("pthread_sigmask", src)+ self.assertIn("os.execve = _win_execve", src)++ # Verify _patch_tool_lock_module filters out spirv-cross hash mismatches when allowed,+ # while still reporting missing spirv-cross or translator mismatches.+ start = src.index(' def _patch_tool_lock_module(mod):')+ end = src.index(' import importlib.machinery as _machinery')+ ns: dict = {'os': os}+ exec('\n'.join(ln[4:] for ln in src[start:end].splitlines()), ns)+ patch_tl = ns['_patch_tool_lock_module']++ import types+ fake_tl = types.ModuleType('tool_lock')+ fake_tl.check_tools = lambda: [+ 'spirv-cross: lock e37945d8e441d34d / actual 0123456789abcdef',+ 'dmsh_xlate.dll: lock aaaa / actual bbbb',+ ]+ patch_tl(fake_tl)+ with mock.patch.dict(os.environ, {'DM_ALLOW_SYSTEM_SPIRV_CROSS': '1'}, clear=False):+ self.assertEqual(fake_tl.check_tools(), ['dmsh_xlate.dll: lock aaaa / actual bbbb'])+ with mock.patch.dict(os.environ, {'DM_ALLOW_SYSTEM_SPIRV_CROSS': '0'}, clear=False):+ self.assertEqual(len(fake_tl.check_tools()), 2)++ # A missing spirv-cross must still be reported even when DM_ALLOW_SYSTEM_SPIRV_CROSS=1+ fake_tl2 = types.ModuleType('tool_lock')+ fake_tl2.check_tools = lambda: ['spirv-cross: lock e37945d8e441d34d / actual missing']+ patch_tl(fake_tl2)+ with mock.patch.dict(os.environ, {'DM_ALLOW_SYSTEM_SPIRV_CROSS': '1'}, clear=False):+ self.assertEqual(fake_tl2.check_tools(),+ ['spirv-cross: lock e37945d8e441d34d / actual missing'])++ def test_model_on_line_parses_timestamped_stage_lines(self) -> None:+ try:+ from nspb_qt.model import Model+ except ImportError:+ self.skipTest('PySide6 is not installed')+ with mock.patch.object(Model, 'check_deps', lambda self: None):+ m = Model()+ m._on_line('[04:35:01] [1/6] build nx_extract')+ self.assertEqual([s.name for s in m.stages], ['build nx_extract'])+ self.assertEqual(m.stages[-1].state, 'running')+ m._on_line('[04:35:01] [1/6] build nx_extract ✓ (0s)')+ self.assertEqual(len(m.stages), 1)+ m._on_line('[04:35:04] [3/7] rewrite · main, sdk')+ self.assertEqual([s.name for s in m.stages], ['build nx_extract', 'rewrite · main, sdk'])+ self.assertEqual(m.stages[0].state, 'done')+ self.assertEqual(m.stages[1].state, 'running')+ m._on_line('[04:35:04] [RED] patch_nso.py failed')+ self.assertEqual(m._last_error, '[RED] patch_nso.py failed')+if __name__ == '__main__':unittest.main(verbosity=2)