From 767f2f66633df42465ad0af4eb43f4bda7735b20 Mon Sep 17 00:00:00 2001 From: ICUMADETHIS Date: Sun, 22 Nov 2026 19:37:46 +0000 Subject: [PATCH 1/2] Protect the original profile during scripted runs --- tests/run_all.py | 1 + tests/run_game_test.py | 83 ++++++++++++++++++++++++++++++++++++++++++ tools/run_game.py | 21 ++++++++++- 3 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 tests/run_game_test.py diff --git a/tests/run_all.py b/tests/run_all.py index fc74a277..3761cf6a 100644 --- a/tests/run_all.py +++ b/tests/run_all.py @@ -56,6 +56,7 @@ TESTS = { 'pack_shader_cache_test': ('.venv', None, [], ''), 'spin_waits_test': ('.venv', None, [], ''), 'worktree_test': ('.venv', None, [], ''), + 'run_game_test': ('.venv', None, [], ''), 'installer_test': ('.venv-py314', None, [], ''), 'ncz_test': ('.venv-py314', None, [], ''), 'romfs_prompts_test': ('.venv-py314', None, [], ''), diff --git a/tests/run_game_test.py b/tests/run_game_test.py new file mode 100644 index 00000000..814a97b8 --- /dev/null +++ b/tests/run_game_test.py @@ -0,0 +1,83 @@ +"""Run-profile copying and CLI rejection with disposable marker files; never launches a game.""" +import contextlib +import io +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tools')) +import run_game as run # noqa: E402 + + +class ProfileTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.folder = Path(tmp.name) + self.profile = self.folder / 'profile' + self.profile.mkdir() + (self.profile / 'marker').write_text('original profile') + source = patch.object(run, 'PROFILE', self.profile) + source.start() + self.addCleanup(source.stop) + + def test_overlapping_copies_fail_before_cleanup_or_copying(self): + for target in (self.profile, self.profile.parent, self.profile / 'nested'): + with self.subTest(target=target), \ + patch.object(run.shutil, 'rmtree', side_effect=AssertionError('cleanup ran before overlap check')), \ + patch.object(run.shutil, 'copytree', side_effect=AssertionError('copy ran before overlap check')): + with self.assertRaisesRegex(ValueError, 'profile'): + run.profile_copy(target, None) + self.assertEqual((self.profile / 'marker').read_text(), 'original profile') + + def test_separate_copy_refreshes_only_the_disposable_destination(self): + target = self.folder / 'build' / 'prof-run' + target.mkdir(parents=True) + (target / 'stale').write_text('old copy') + run.profile_copy(target, None) + self.assertEqual((self.profile / 'marker').read_text(), 'original profile') + self.assertEqual((target / 'marker').read_text(), 'original profile') + self.assertFalse((target / 'stale').exists()) + + def test_path_like_tags_are_rejected_before_files_or_locks_are_touched(self): + for tag in ('../escape', '../../profile', '../../../profile', '..\\escape', 'nested/run', '/absolute'): + with self.subTest(tag=tag), \ + patch.object(sys, 'argv', ['run_game.py', str(self.folder / 'build'), '--seconds', '1', '--tag', tag]), \ + patch.object(Path, 'mkdir', side_effect=AssertionError('created a folder before checking tag')), \ + patch.object(run, 'take_slot', side_effect=AssertionError('took a slot before checking tag')), \ + contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as error: + run.main() + self.assertEqual(error.exception.code, 2) + + def test_build_inside_the_original_profile_is_rejected_before_writes(self): + with patch.object(sys, 'argv', ['run_game.py', str(self.profile), '--seconds', '1']), \ + patch.object(Path, 'mkdir', side_effect=AssertionError('created a folder before overlap check')), \ + contextlib.redirect_stderr(io.StringIO()): + with self.assertRaises(SystemExit) as error: + run.main() + self.assertEqual(error.exception.code, 2) + self.assertEqual((self.profile / 'marker').read_text(), 'original profile') + + def test_normal_run_cleans_its_copy_and_keeps_the_source(self): + build = self.folder / 'build' + proc = unittest.mock.Mock() + proc.wait.return_value = 0 + with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--tag', 'bench-1', '--show']), \ + patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \ + patch.object(run.subprocess, 'Popen', return_value=proc) as launch, \ + contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit) as error: + run.main() + self.assertEqual(error.exception.code, 0) + self.assertEqual((self.profile / 'marker').read_text(), 'original profile') + self.assertFalse((build / 'prof-bench-1').exists()) + self.assertIn('rc=0', (build / 'logs' / 'bench-1.log').read_text()) + launch.assert_called_once() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/tools/run_game.py b/tools/run_game.py index f0062b48..cd0a2383 100644 --- a/tools/run_game.py +++ b/tools/run_game.py @@ -137,7 +137,20 @@ def release_gpu_lock(f): f.close() +def tag_name(value): + if '/' in value or '\\' in value: + raise argparse.ArgumentTypeError('run tag must be a name without path separators') + return value + + +def check_profile_destination(dest): + source, target = PROFILE.resolve(), Path(dest).resolve() + if source.is_relative_to(target) or target.is_relative_to(source): + raise ValueError('profile copy must not overlap the original profile') + + def profile_copy(dest, save): + check_profile_destination(dest) if dest.exists(): shutil.rmtree(dest) shutil.copytree(PROFILE, dest) @@ -157,7 +170,7 @@ def main(): ap.add_argument('--seconds', type=float, required=True, help='game time to run: the run ends once the world clock (game time since the save loaded) passed ' 'this many seconds (shot is taken of that frame)') - ap.add_argument('--tag', default='run', help='names the profile copy and the log') + ap.add_argument('--tag', type=tag_name, default='run', help='names the profile copy and the log (no path separators)') ap.add_argument('--shot', type=Path, help='PNG of the last frame; turns async pipeline builds off (boot.c)') ap.add_argument('--log', type=Path, help='default: /logs/.log') ap.add_argument('--env', action='append', default=[], metavar='KEY=VALUE', help='extra environment, repeatable') @@ -166,6 +179,11 @@ def main(): a = ap.parse_args() exe_dir = a.exe_dir.resolve() + prof = exe_dir / f'prof-{a.tag}' + try: + check_profile_destination(prof) + except ValueError as e: + ap.error(str(e)) log = (a.log or exe_dir / 'logs' / f'{a.tag}.log').resolve() log.parent.mkdir(parents=True, exist_ok=True) gpu = take_gpu_lock(exe_dir) if a.quiet else None @@ -174,7 +192,6 @@ def main(): if a.quiet: while busy(): time.sleep(10) - prof = exe_dir / f'prof-{a.tag}' profile_copy(prof, a.save) env = dict(os.environ, TOTK_ASSUME_FOCUS='1', TOTK_INPUT='none', TOTK_INPUT_SCRIPT=str(a.script.resolve())) From d7c408c4d7f75a9c233434d4819b07c322508616 Mon Sep 17 00:00:00 2001 From: ICUMADETHIS Date: Sun, 22 Nov 2026 19:43:19 +0000 Subject: [PATCH 2/2] Stop interrupted runs before removing their profile copy --- tests/run_game_test.py | 47 ++++++++++++++++++++++++++++++++++++++++++ tools/run_game.py | 21 ++++++++++++++++--- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/tests/run_game_test.py b/tests/run_game_test.py index 814a97b8..0953113b 100644 --- a/tests/run_game_test.py +++ b/tests/run_game_test.py @@ -2,6 +2,7 @@ import contextlib import io from pathlib import Path +import subprocess import sys import tempfile import unittest @@ -66,6 +67,7 @@ class ProfileTest(unittest.TestCase): build = self.folder / 'build' proc = unittest.mock.Mock() proc.wait.return_value = 0 + proc.poll.return_value = 0 with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--tag', 'bench-1', '--show']), \ patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \ patch.object(run.subprocess, 'Popen', return_value=proc) as launch, \ @@ -77,6 +79,51 @@ class ProfileTest(unittest.TestCase): self.assertFalse((build / 'prof-bench-1').exists()) self.assertIn('rc=0', (build / 'logs' / 'bench-1.log').read_text()) launch.assert_called_once() + proc.terminate.assert_not_called() + + def test_interrupted_wait_stops_the_owned_child_before_cleanup(self): + child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + proxy = unittest.mock.Mock(wraps=child) + interrupted = False + + def wait(*args, **kwargs): + nonlocal interrupted + if not interrupted: + interrupted = True + raise KeyboardInterrupt + return child.wait(*args, **kwargs) + proxy.wait.side_effect = wait + build = self.folder / 'build' + remove = run.shutil.rmtree + + def remove_after_exit(path, *args, **kwargs): + if Path(path) == build / 'prof-run': + self.assertIsNotNone(child.poll(), 'profile cleanup ran while the child was alive') + return remove(path, *args, **kwargs) + try: + with patch.object(sys, 'argv', ['run_game.py', str(build), '--seconds', '1', '--show']), \ + patch.object(run, 'take_slot', return_value=None), patch.object(run, 'count', return_value=0), \ + patch.object(run.shutil, 'rmtree', side_effect=remove_after_exit), \ + patch.object(run.subprocess, 'Popen', return_value=proxy): + with self.assertRaises(KeyboardInterrupt): + run.main() + self.assertIsNotNone(child.poll(), 'interrupted run left its child alive') + self.assertFalse((build / 'prof-run').exists()) + self.assertEqual((self.profile / 'marker').read_text(), 'original profile') + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + def test_unresponsive_child_is_killed_after_termination_timeout(self): + proc = unittest.mock.Mock() + proc.poll.return_value = None + proc.wait.side_effect = [subprocess.TimeoutExpired('owned child', 5), 0] + run.stop_process(proc) + proc.terminate.assert_called_once() + proc.kill.assert_called_once() + self.assertEqual(proc.wait.call_args_list, [unittest.mock.call(timeout=5), unittest.mock.call()]) if __name__ == '__main__': diff --git a/tools/run_game.py b/tools/run_game.py index cd0a2383..e4984bf3 100644 --- a/tools/run_game.py +++ b/tools/run_game.py @@ -162,6 +162,18 @@ def profile_copy(dest, save): shutil.copytree(SAVES / save, users[0]) +def stop_process(proc): + """Stop this run's child before its disposable profile is removed, including an interrupted wait.""" + if proc.poll() is not None: + return + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument('exe_dir', type=Path, help='build directory holding totk.exe') @@ -209,9 +221,12 @@ def main(): f.flush() start = time.time() proc = subprocess.Popen(args, cwd=exe_dir, env=env, stdout=f, stderr=subprocess.STDOUT) - if not a.show: - threading.Thread(target=keep_in_background, args=(proc,), daemon=True).start() - rc = proc.wait() + try: + if not a.show: + threading.Thread(target=keep_in_background, args=(proc,), daemon=True).start() + rc = proc.wait() + finally: + stop_process(proc) f.write(f'run_game: rc={rc} wall={time.time() - start:.0f}s; others running after: ' f'totk.exe {count("totk.exe")}, ninja.exe {count("ninja.exe")}\n') finally: