diff --git a/docs/launcher.md b/docs/launcher.md index 14debdc5..7c36f563 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -574,7 +574,8 @@ files), `start.pyw` on a version that cannot be imported (exit code 86 at once, back to), a cut RomFS image and the free space, the object cache written while the compile runs and kept when it is cut, a RomFS step that does not repeat the lift, the update's duration text and the warm-up's bar, a damaged dump named by its file and an unexpected error by its message, the file check's result in its row and on home, the -game's FATAL line after exit codes 70 and 71, an end with code 0 noted in the game's log when it has no line of the +game's FATAL line after exit codes 70, 71 and 72, the copy the game's own Restart starts followed for its exit code +and its FATAL line, an end with code 0 noted in the game's log when it has no line of the game's own end, the job count by free memory and the build's priority class, a line handler that raises and a log that cannot be written, one forced update check a minute and GitHub's reset time, a game folder with characters outside the Basic Multilingual Plane (its `modules.c` compiled when a C compiler is diff --git a/launcher/ui/app.py b/launcher/ui/app.py index d483eb89..ca772511 100644 --- a/launcher/ui/app.py +++ b/launcher/ui/app.py @@ -25,6 +25,7 @@ rows, a new screen slides in, sparks drift over the backdrop and Navi bobs in th plays the game's own decide and cancel sounds, read from the player's game, for a choice and for going back. """ import argparse +import collections import colorsys import math import os @@ -115,14 +116,19 @@ def free_gb(path): return 0.0 -# Exit codes that end the game, and what they mean. The game exits with 70 after a FATAL line of its own: an error it -# cannot go on from, most often an allocation that failed because the memory ran out (runtime/dispatch.c rt_fatal), or -# a failed re-run of itself (runtime/platform/win32.c plat_reexec). Its crash report exits with 71 after writing its -# FATAL lines (runtime/main.c crash_handler). The others come from Windows when something ends the process before or +# Exit codes that end the game, and what they mean. The game exits with 70 (runtime/dispatch.h RT_FATAL_EXIT) after a +# FATAL line of its own: an error it cannot go on from, most often an allocation that failed because the memory ran +# out (runtime/dispatch.c rt_fatal), or a failed re-run of itself (runtime/platform/win32.c plat_reexec). Its crash +# report exits with 71 after writing its FATAL lines (runtime/main.c crash_handler). A lost graphics device ends it +# with 72 (runtime/dispatch.h RT_LOST_EXIT, runtime/vk_device.c vk_device_lost_check), after a FATAL line too, unless +# the report before that line hangs: then its watchdog (vk_device.c lost_wait_exit) ends the run with 72 and no FATAL +# line, so 72's text stands without one. The others come from Windows when something ends the process before or # around that report. EXIT_CODES = { 70: 'a fatal error: the FATAL line near the end of its log says which, often memory that ran out', 71: 'the crash report ended the game', + 72: 'the graphics device was lost: the GPU or its driver stopped, and the vk: lines near the end of its log say ' + 'what it was doing; a graphics driver update may help', 0xC0000005: 'access violation', 0xC00000FD: 'stack overflow', 0xC0000142: 'a DLL failed to start', @@ -132,6 +138,7 @@ EXIT_CODES = { 0xC000041D: 'a fault inside a Windows callback', 0xE06D7363: 'a C++ exception no one caught', } +FATAL_CODES = (70, 71, 72) # the codes that follow a FATAL line of the game's own (EXIT_CODES' comment) def exit_code_text(code): @@ -148,9 +155,10 @@ FATAL_SHOWN = 240 # characters of a FATAL line the home screen shows; the def last_fatal(game_dir): """The last FATAL line of the game's latest run, without its "FATAL: ", or ''. The game writes one before it - exits with 70 (runtime/dispatch.c rt_fatal) or 71 (runtime/main.c crash_handler) into logs/nx2navi.log, which - each run starts anew (runtime/main.c log_open). A line this launcher added for an earlier run's end - (note_exit_in_log) ends the search: what stands before it is not this run's.""" + exits with 70 (runtime/dispatch.c rt_fatal), 71 (runtime/main.c crash_handler) or 72 (runtime/vk_device.c + vk_device_lost_check) into logs/nx2navi.log, which each run starts anew (runtime/main.c log_open). A line this + launcher added for an earlier run's end (note_exit_in_log) ends the search: what stands before it is not this + run's.""" if not game_dir: return '' try: @@ -171,12 +179,15 @@ def last_fatal(game_dir): # game's own exit (runtime/svc.c, ExitProcess), a timed run's end (runtime/boot.c), a fatal error and the crash report's # line for a fault on the way out (runtime/main.c). OWN_EXIT_LINES = ('gfx: window closed', 'guest ExitProcess', 'boot: frames', 'FATAL: ', 'exit: ') +# The line a log stops with once it reached its size cap (runtime/main.c log_sink, LOG_CAP): the rest of that run, +# its end lines too, went to stderr only. +LOG_CUT_LINE = 'log: the file reached 64 MiB' def log_has_own_exit(game_dir): """Whether the end of logs/nx2navi.log holds a line of the game's own end (OWN_EXIT_LINES) for its latest run; None - when the log cannot be read. A line this launcher added for an earlier run's end (note_exit_in_log) ends the - search.""" + when the log cannot be read, or when it was cut at its size cap (LOG_CUT_LINE) and so cannot tell. A line this + launcher added for an earlier run's end (note_exit_in_log) ends the search.""" if not game_dir: return None try: @@ -191,6 +202,8 @@ def log_has_own_exit(game_dir): body = line.split('] ', 1)[1] if line.startswith('[') and '] ' in line else line if body.startswith(OWN_EXIT_LINES): return True + if body.startswith(LOG_CUT_LINE): + return None return False @@ -207,6 +220,104 @@ def note_exit_in_log(game_dir, text): pass +def log_is_new(game_dir, started): + """Whether logs/nx2navi.log was written at or after started (time.time() before the game was started). A run that + ends before it moves and opens its log (runtime/main.c log_open) leaves the log of a run before it in place. FAT + and exFAT drives keep a file's time to 2 s, hence the slack.""" + if not game_dir or started is None: + return False + try: + return (Path(game_dir) / 'logs' / 'nx2navi.log').stat().st_mtime >= started - 2 + except OSError: + return False + + +LOG_WHERE = 'Its log is logs\\nx2navi.log in the game folder.' +GameEnd = collections.namedtuple('GameEnd', 'log message note alarm') + + +def shown_fatal(fatal): + return fatal if len(fatal) <= FATAL_SHOWN else fatal[:FATAL_SHOWN].rstrip() + '…' + + +def game_end(game_dir, code, started=None, restarted=False): + """What the launcher says about an end of the game (App.watch_game): a GameEnd of the line for launcher.log, the + sentence for the player ('' for none), the text note_exit_in_log adds to the game's log ('' for none), and alarm: + whether the end is worth a message box where no window shows the sentence (a FATAL line, a code of FATAL_CODES or + a Windows status; not 0, nor 1, which Task Manager's End task gives). code is the exit code of the run's last + process, or None when it is not known, which happens only for a copy the game's own Restart started that could not + be followed (GameRun). started is time.time() before the game was started, restarted whether it restarted itself + on the way.""" + how = ' after restarting itself' if restarted else '' + if code not in (0, None): + code &= 0xFFFFFFFF + text = exit_code_text(code) + # 70, 71 and 72 follow a FATAL line of the game's own, which names the error: the player gets that line and the + # launcher's log too, where the exit code alone said only that there was one + fatal = last_fatal(game_dir) if code in FATAL_CODES else '' + if fatal: + return GameEnd(f'the game ended with code {code}{how}; its log says: FATAL: {fatal}', + f'The game ended with a fatal error (code {code}): {shown_fatal(fatal)}. {LOG_WHERE}', + text, True) + return GameEnd(f'the game ended with code {text}{how}', f'The game ended with code {text}. {LOG_WHERE}', text, + code in FATAL_CODES or code >= 0x80000000) + # No process of the game writes a FATAL line and exits with 0 (runtime/dispatch.c fatal_end, runtime/main.c + # crash_handler). After code 0, or a code not known, a FATAL line in a log written since the start is a copy's that + # the game's own Restart started (runtime/gfx_present.c gfx_window_closed): one that ended before the launcher saw + # it run, or one it could not follow. That copy's log is logs/nx2navi.log and holds the line already: no note. + fatal = last_fatal(game_dir) if log_is_new(game_dir, started) else '' + if fatal: + return GameEnd(f'the game ended after restarting itself; its log says: FATAL: {fatal}', + f"A copy started by the game's Restart ended with a fatal error: {shown_fatal(fatal)}. " + f'{LOG_WHERE}', '', True) + # Every end of a run the launcher started is logged, and when the game's log has no line of its own end, the end + # goes into that log: a session of 2026-11-13 stopped in play with code 0, no FATAL line and none of the game's exit + # lines, and nothing said how it had ended. + own = log_has_own_exit(game_dir) + if code is None: + return GameEnd('the game ended after restarting itself; the exit code of its last run is not known', '', + "unknown (the game had restarted itself; the log has no line of the game's own end before " + 'this one)' if own is False else '', False) + if own is False: + return GameEnd(f'the game ended with code 0{how}, and its log has no line of its own end', '', + "0 (the log has no line of the game's own end before this one)", False) + return GameEnd(f'the game ended with code 0{how}', '', '', False) + + +class GameRun: + """A Play of the game, followed through the copies its own Restart starts. The Restart (runtime/gfx_present.c + gfx_window_closed) starts the exe again (runtime/platform/win32.c plat_restart) and ends the process before it + with code 0, so the code the game really ended with is its last copy's: once the process followed has ended with + 0 while the exe still runs, the copy is looked for (winsys.game_copy) and followed from then on. proc is the + process followed, None once a copy could not be found (it ended before the next look, or the system did not show + it); the end's code is then not known. started is time.time() before the start (game_end's log_is_new).""" + + def __init__(self, proc, game_dir, started): + self.proc, self.game_dir, self.started, self.restarted = proc, game_dir, started, False + + def alive(self): + """Whether the process followed runs; nothing else is looked at. A winsys.GameCopy whose exit code could not + be read has ended all the same.""" + return self.proc is not None and self.proc.poll() is None and getattr(self.proc, 'ended', False) is not True + + def running(self): + """Whether the game still runs, this launcher's process or another of the same exe (build.game_running); + asked once a second until it says False.""" + if self.alive(): + return True + if not (self.game_dir and saves.game_running(self.game_dir)): + return False + if self.proc is not None and self.proc.returncode == 0: + self.restarted = True + self.proc = winsys.game_copy(Path(self.game_dir) / 'ocarina.exe', skip=self.proc.pid) + return True + + def end(self): + """game_end for this run, once running() said False.""" + return game_end(self.game_dir, None if self.proc is None else self.proc.returncode, self.started, + self.restarted) + + def partial_image_gb(game_dir): """The size of what an install that was cut short left of the RomFS image (romfs/romfs.bin.part, up to 26 GB). The next install writes the image anew (tools/make_game.py step_romfs), so that space is the install's to use: @@ -282,7 +393,7 @@ class App: self.dumps = None self.dump_search = None self.uninstall_game = False - self.game_proc = None + self.game_run = None # the Play being followed (GameRun), until watch_game sees its end self.cursor_frames, self.cursor_k = [], 0 self.last_second = 0 self.gamepad = winsys.Gamepad() @@ -1557,7 +1668,7 @@ class App: gd = self.settings.get('game_dir') if not gd or not Path(gd).is_dir(): self.save_message = 'Install the game first.' - elif (self.game_proc and self.game_proc.poll() is None) or saves.game_running(gd): + elif (self.game_run and self.game_run.alive()) or saves.game_running(gd): self.save_message = 'Quit the game first: it keeps its save open while it runs.' else: try: @@ -1705,7 +1816,7 @@ class App: return {'title': m.name, 'text': lines} def game_busy(self, gd): - return bool((self.game_proc and self.game_proc.poll() is None) or (gd and saves.game_running(gd))) + return bool((self.game_run and self.game_run.alive()) or (gd and saves.game_running(gd))) def switch_mod(self, m, on): gd = self.settings.get('game_dir') @@ -1899,7 +2010,7 @@ class App: self.message = 'The game is not built yet.' self.render() return - if self.game_proc and self.game_proc.poll() is None: + if self.game_run and self.game_run.alive(): return if saves.game_running(gd): # a copy this launcher did not start (another launcher, a shortcut, a test run) self.message = 'The game is already running.' @@ -1918,8 +2029,9 @@ class App: return if waiting: self.ctx.log(f'play: without the code of {", ".join(waiting)}, whose build did not finish') + started = time.time() try: - self.game_proc = winsys.start_game(exe) + self.game_run = GameRun(winsys.start_game(exe), gd, started) except OSError as e: self.message = f'The game could not start: {e}' self.render() @@ -1931,39 +2043,23 @@ class App: self.root.after(1000, self.watch_game) def watch_game(self): - # The game's own Restart ends the process started here and starts another (gfx_present.c gfx_window_closed) - gd = self.settings.get('game_dir') - if (self.game_proc and self.game_proc.poll() is None) or (gd and saves.game_running(gd)): + """Once a second while the game Play started runs, its Restart's copies too (GameRun.running); then the window + comes back and the end goes into launcher.log, into the game's log when that has no line of it, and on home + when there is something to tell (game_end).""" + run = self.game_run + if run and run.running(): self.root.after(1000, self.watch_game) return - code = self.game_proc.returncode if self.game_proc else 0 - started = self.game_proc is not None - self.game_proc = None + self.game_run = None self.root.deiconify() self.root.lift() - if code not in (0, None): - text = exit_code_text(code) - # 70 and 71 follow a FATAL line of the game's own, which names the error: the player gets that line - # and the launcher's log too, where the exit code alone said only that there was one - fatal = last_fatal(self.game_dir()) if code & 0xFFFFFFFF in (70, 71) else '' - if fatal: - shown = fatal if len(fatal) <= FATAL_SHOWN else fatal[:FATAL_SHOWN].rstrip() + '…' - self.ctx.log(f'the game ended with code {code & 0xFFFFFFFF}; its log says: FATAL: {fatal}') - self.message = (f'The game ended with a fatal error (code {code & 0xFFFFFFFF}): {shown}. Its log is ' - 'logs\\nx2navi.log in the game folder.') - else: - self.ctx.log(f'the game ended with code {text}') - self.message = f'The game ended with code {text}. Its log is logs\\nx2navi.log in the game folder.' - note_exit_in_log(self.game_dir(), text) - elif started: - # A run this launcher started that ended with code 0 is logged too, and when the game's log has no line of - # its own end, the end goes into that log: a session of 2026-11-13 stopped in play with code 0, no FATAL - # line and none of the game's exit lines, and nothing said how it had ended. - if log_has_own_exit(self.game_dir()) is False: - self.ctx.log('the game ended with code 0, and its log has no line of its own end') - note_exit_in_log(self.game_dir(), "0 (the log has no line of the game's own end before this one)") - else: - self.ctx.log('the game ended with code 0') + if run: + end = run.end() + self.ctx.log(end.log) + if end.note: + note_exit_in_log(run.game_dir, end.note) + if end.message: + self.message = end.message if self.install_staged('the game exited'): return self.show('home', self.focus) @@ -2002,7 +2098,7 @@ class App: for the restart into it; True when it was installed.""" if self.job and self.job.result is None: return False - running = bool(self.game_proc and self.game_proc.poll() is None) + running = bool(self.game_run and self.game_run.alive()) ver = self.bg.install(self.settings.get('game_dir'), self.release, why, asked=asked, running=running) if not ver: return False @@ -2025,7 +2121,7 @@ class App: self.bg.asked = False gd = self.settings.get('game_dir') if (self.screen == 'home' and self.release and jobs.update_available(self.ctx, self.release) - and not (self.game_proc and self.game_proc.poll() is None) + and not (self.game_run and self.game_run.alive()) and not (gd and build.game_running(gd))): self.run_job(jobs.UpdateDownloadJob(self.ctx, self.release), 'home') return @@ -2314,7 +2410,7 @@ class App: last = max(self.settings.get('last_check', 0.0), self.check_started) if self.settings.get('auto_check') and time.time() - last >= jobs.RECHECK: self.check_now() - if self.bg.waiting and not (self.game_proc and self.game_proc.poll() is None): + if self.bg.waiting and not (self.game_run and self.game_run.alive()): self.install_staged('the game closed') except Exception as e: self.ctx.log(f'minute: {e!r}') diff --git a/launcher/winsys.py b/launcher/winsys.py index e0cd91e5..ec36d8c3 100644 --- a/launcher/winsys.py +++ b/launcher/winsys.py @@ -214,6 +214,99 @@ def start_game(exe): stderr=subprocess.DEVNULL, close_fds=True, **flags) +SYNCHRONIZE = 0x00100000 +PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 +WAIT_TIMEOUT = 0x102 + + +_k32 = None + + +def _kernel32(): + global _k32 + if _k32: + return _k32 + k = ctypes.WinDLL('kernel32') + k.OpenProcess.restype = ctypes.c_void_p + k.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong] + k.CloseHandle.argtypes = [ctypes.c_void_p] + k.WaitForSingleObject.restype = ctypes.c_ulong + k.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + k.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)] + k.QueryFullProcessImageNameW.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_wchar_p, + ctypes.POINTER(ctypes.c_ulong)] + k.K32EnumProcesses.argtypes = [ctypes.POINTER(ctypes.c_ulong), ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong)] + _k32 = k + return k + + +class GameCopy: + """A process of the game this launcher did not start, held by a handle so that its exit code can still be read + once it has ended (game_copy). poll(), returncode and pid as subprocess.Popen has them; ended is True once it has + ended, also when its code could not be read (returncode then stays None).""" + + def __init__(self, handle, pid): + self.handle, self.pid, self.returncode, self.ended = handle, pid, None, False + + def poll(self): + if self.handle: + k = _kernel32() + if k.WaitForSingleObject(self.handle, 0) == WAIT_TIMEOUT: + return None + code = ctypes.c_ulong() + if k.GetExitCodeProcess(self.handle, ctypes.byref(code)): + self.returncode = code.value + k.CloseHandle(self.handle) + self.handle, self.ended = None, True + return self.returncode + + +def game_copy(exe, skip=None): + """Windows: the running process whose image is the file exe, other than the process id skip, as a GameCopy; None + when there is none or it cannot be opened. The game's own Restart (runtime/gfx_present.c gfx_window_closed) starts + the exe again (runtime/platform/win32.c plat_restart) and ends the process before it with code 0: following the + copy is how the launcher learns the code the game really ended with. The image is compared as a file, not as a + name, so the game of another install is not taken for this one.""" + if os.name != 'nt': + return None + try: + k = _kernel32() + n = 1024 + while True: + pids, got = (ctypes.c_ulong * n)(), ctypes.c_ulong() + if not k.K32EnumProcesses(pids, ctypes.sizeof(pids), ctypes.byref(got)): + return None + if got.value < ctypes.sizeof(pids): + break + n *= 4 + want = os.path.normcase(os.path.abspath(str(exe))) + name = ctypes.create_unicode_buffer(32768) + for pid in pids[:got.value // ctypes.sizeof(ctypes.c_ulong)]: + if not pid or pid == skip: + continue + h = k.OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, False, pid) + if not h: + continue + size = ctypes.c_ulong(len(name)) + image = name.value if k.QueryFullProcessImageNameW(h, 0, name, ctypes.byref(size)) else '' + if (image and os.path.basename(os.path.normcase(image)) == os.path.basename(want) + and _same_file(image, want) and k.WaitForSingleObject(h, 0) == WAIT_TIMEOUT): + return GameCopy(h, pid) + k.CloseHandle(h) + except (AttributeError, OSError): + pass + return None + + +def _same_file(a, b): + if os.path.normcase(a) == b: + return True + try: + return os.path.samefile(a, b) + except OSError: + return False + + def start_detached(cmd, cwd=None): flags = {'creationflags': DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP} if os.name == 'nt' \ else {'start_new_session': True} diff --git a/tests/launcher_test.py b/tests/launcher_test.py index 1cc2ac4a..e9cfae56 100644 --- a/tests/launcher_test.py +++ b/tests/launcher_test.py @@ -5059,21 +5059,101 @@ class SteamTest(Tmp): class WhilePlayingTest(Tmp): def test_the_games_restart_does_not_bring_the_launcher_back(self): try: - from launcher.ui.app import App + from launcher.ui import app except ImportError as e: self.skipTest(f'no window toolkit: {e}') + App, GameRun = app.App, app.GameRun a = mock.MagicMock() a.settings = {'game_dir': str(self.tmp)} - a.game_proc = mock.MagicMock(returncode=0) - a.game_proc.poll.return_value = 0 # the process started here has ended - with mock.patch('launcher.ui.app.saves.game_running', return_value=True): + a.game_run = GameRun(mock.MagicMock(returncode=0, pid=11), str(self.tmp), time.time()) + a.game_run.proc.poll.return_value = 0 # the process started here has ended + with mock.patch('launcher.ui.app.saves.game_running', return_value=True), \ + mock.patch('launcher.ui.app.winsys.game_copy', return_value=None) as copy: App.watch_game(a) # but the restarted game runs from the same exe + copy.assert_called_once_with(self.tmp / 'ocarina.exe', skip=11) a.root.deiconify.assert_not_called() a.root.after.assert_called_once() with mock.patch('launcher.ui.app.saves.game_running', return_value=False): App.watch_game(a) a.root.deiconify.assert_called_once() + def test_the_restarted_copy_is_followed_for_its_exit_code(self): + """The game's Restart ends the process the launcher started with code 0 and starts the exe again: the launcher + follows that copy (winsys.game_copy) and reports the code it ends with, and its FATAL line.""" + try: + from launcher.ui import app + except ImportError as e: + self.skipTest(f'no window toolkit: {e}') + App, GameRun = app.App, app.GameRun + log = self.tmp / 'logs' / 'nx2navi.log' + log.parent.mkdir() + log.write_text('[host] gfx: window closed; restarting\n', encoding='utf-8') + a = mock.MagicMock() + a.message = '' + a.settings = {'game_dir': str(self.tmp)} + a.install_staged.return_value = False + a.game_run = GameRun(mock.MagicMock(returncode=0, pid=11), str(self.tmp), time.time() - 60) + a.game_run.proc.poll.return_value = 0 + copy = mock.MagicMock(returncode=None, pid=12, ended=False) + copy.poll.return_value = None + with mock.patch('launcher.ui.app.saves.game_running', return_value=True), \ + mock.patch('launcher.ui.app.winsys.game_copy', return_value=copy): + App.watch_game(a) # the copy is found and followed + App.watch_game(a) # it runs: no further look for one + self.assertIs(a.game_run.proc, copy) + a.root.deiconify.assert_not_called() + log.write_text('[host] boot\nFATAL: vk: the GPU device was lost (seen at: q). The run ends here\n', + encoding='utf-8') # the copy's own log (main.c log_open) + copy.returncode = 72 + copy.poll.return_value = 72 + with mock.patch('launcher.ui.app.saves.game_running', return_value=False): + App.watch_game(a) + a.ctx.log.assert_called_once_with('the game ended with code 72 after restarting itself; its log says: FATAL: ' + 'vk: the GPU device was lost (seen at: q). The run ends here') + self.assertIn('(code 72): vk: the GPU device was lost', a.message) + self.assertIn('[launcher] the game ended with code 72 (the graphics device was lost', + log.read_text(encoding='utf-8')) + self.assertIsNone(a.game_run) + + def test_a_restarted_copy_that_could_not_be_followed_ends_with_its_code_unknown(self): + """A copy the launcher could not find (it ended before the next look): its code is not known, so neither + launcher.log nor the game's log says code 0, and its FATAL line is still shown.""" + try: + from launcher.ui import app + except ImportError as e: + self.skipTest(f'no window toolkit: {e}') + App, GameRun = app.App, app.GameRun + log = self.tmp / 'logs' / 'nx2navi.log' + log.parent.mkdir() + + def run(text): + log.write_text(text, encoding='utf-8') + a = mock.MagicMock() + a.message = '' + a.settings = {'game_dir': str(self.tmp)} + a.install_staged.return_value = False + a.game_run = GameRun(mock.MagicMock(returncode=0, pid=11), str(self.tmp), time.time() - 60) + a.game_run.proc.poll.return_value = 0 + with mock.patch('launcher.ui.app.saves.game_running', return_value=True), \ + mock.patch('launcher.ui.app.winsys.game_copy', return_value=None): + App.watch_game(a) + with mock.patch('launcher.ui.app.saves.game_running', return_value=False): + App.watch_game(a) + return a + + a = run('[host] log: x\n[host] perf: the last line of play\n') + a.ctx.log.assert_called_once_with('the game ended after restarting itself; the exit code of its last run is ' + 'not known') + self.assertEqual(a.message, '') + text = log.read_text(encoding='utf-8') + self.assertIn('[launcher] the game ended with code unknown (the game had restarted itself;', text) + self.assertNotIn('code 0', text) + a = run('[host] log: x\nFATAL: fs: another copy of the game is running\n') + a.ctx.log.assert_called_once_with('the game ended after restarting itself; its log says: FATAL: fs: another ' + 'copy of the game is running') + self.assertIn("A copy started by the game's Restart ended with a fatal error: fs: another copy", a.message) + self.assertNotIn('[launcher]', log.read_text(encoding='utf-8')) # the FATAL line says it already + def test_the_games_settings_file_is_left_alone_while_it_runs(self): """The game writes nx2navi.ini when a menu setting changes, so the launcher's Discord Status switch (the one setting of that file the Settings screen has) changes nothing while the game runs and says why; the mods' @@ -5105,23 +5185,114 @@ class WhilePlayingTest(Tmp): self.assertEqual(gameini.get(game, 'MODS_DISABLED'), '') self.assertIn('Quit the game first', a.mods_message) - def ended(self, code, log_text): - """watch_game after the game ended with code, its log holding log_text; (the stand-in window, the log).""" - from launcher.ui.app import App + def ended(self, code, log_text, started=None): + """watch_game after the game ended with code, its log holding log_text; started is the time Play started it, + a minute ago unless given; (the stand-in window, the log).""" + from launcher.ui.app import App, GameRun log = self.tmp / 'logs' / 'nx2navi.log' log.parent.mkdir(exist_ok=True) if log_text is not None: log.write_text(log_text, encoding='utf-8') a = mock.MagicMock() + a.message = '' a.settings = {'game_dir': str(self.tmp)} a.game_dir.return_value = str(self.tmp) - a.game_proc = mock.MagicMock(returncode=code) - a.game_proc.poll.return_value = code + proc = mock.MagicMock(returncode=code) + proc.poll.return_value = code + a.game_run = GameRun(proc, str(self.tmp), time.time() - 60 if started is None else started) a.install_staged.return_value = False with mock.patch('launcher.ui.app.saves.game_running', return_value=False): App.watch_game(a) return a, log + @unittest.skipUnless(os.name == 'nt', 'Windows processes') + def test_a_game_copy_is_found_by_its_exe_file(self): + """winsys.game_copy finds a running process by its image file, not by its name, and reads the code it ended + with after it ended. A sleeper compiled here stands in for the game, under a name that no game runner + watches.""" + cc = next((c for c in (r'C:\msys64\ucrt64\bin\clang.exe', shutil.which('clang')) if c and Path(c).is_file()), + None) + if not cc: + self.skipTest('needs a C compiler') + src = self.tmp / 'sleeper.c' + src.write_text('#include \nint main(void) { Sleep(4000); return 72; }\n', encoding='utf-8') + mine, other = self.tmp / 'mine' / 'sleeper.exe', self.tmp / 'other' / 'sleeper.exe' + mine.parent.mkdir() + other.parent.mkdir() + subprocess.run([cc, '-O1', '-o', str(mine), str(src)], check=True, capture_output=True, timeout=300) + shutil.copy(mine, other) + proc = winsys.start_game(mine) + try: + copy = winsys.game_copy(mine) + self.assertIsNotNone(copy) + self.assertEqual(copy.pid, proc.pid) + self.assertIsNone(copy.poll()) + self.assertIsNone(winsys.game_copy(mine, skip=proc.pid)) + self.assertIsNone(winsys.game_copy(other)) # the same name in another folder: another install + upper = winsys.game_copy(Path(str(mine).upper())) # Windows paths ignore case + self.assertEqual(upper.pid, proc.pid) + proc.wait(30) + self.assertEqual(upper.poll(), 72) + self.assertEqual(copy.poll(), 72) + self.assertTrue(copy.ended) + self.assertIsNone(copy.handle) + finally: + if proc.poll() is None: + proc.kill() + proc.wait(10) + + def test_a_lost_device_shows_the_games_fatal_line(self): + """Exit code 72 (runtime/vk_device.c vk_device_lost_check) follows a FATAL line as 70 and 71 do; when its + watchdog ended the run before that line, the code's own text says what happened.""" + try: + from launcher.ui import app + except ImportError as e: + self.skipTest(f'no window toolkit: {e}') + fatal = 'vk: the GPU device was lost (seen at: q). The run ends here' + a, log = self.ended(72, f'[host] x\nFATAL: {fatal}\n[host] fatal: memory commit: this process 9000 MB\n') + self.assertEqual(a.message, f'The game ended with a fatal error (code 72): {fatal}. Its log is ' + 'logs\\nx2navi.log in the game folder.') + a.ctx.log.assert_called_once_with(f'the game ended with code 72; its log says: FATAL: {fatal}') + self.assertIn('[launcher] the game ended with code 72 (the graphics device was lost', + log.read_text(encoding='utf-8')) + self.assertTrue(app.exit_code_text(72).startswith('72 (the graphics device was lost')) + a, _ = self.ended(72, '[host] vk: device fault: none\n') + self.assertIn('The game ended with code 72 (the graphics device was lost', a.message) + + def test_a_fatal_line_after_code_0_is_the_restarted_copys(self): + """No process of the game writes a FATAL line and exits with 0: after code 0 such a line is a copy's that the + game's Restart started and that ended before the launcher saw it, and the player is told. A log older than + the start is an earlier run's and tells nothing.""" + try: + from launcher.ui import app # noqa: F401 + except ImportError as e: + self.skipTest(f'no window toolkit: {e}') + a, log = self.ended(0, '[host] x\nFATAL: vk: the GPU device was lost (seen at: x)\n') + self.assertEqual(a.message, "A copy started by the game's Restart ended with a fatal error: vk: the GPU device " + 'was lost (seen at: x). Its log is logs\\nx2navi.log in the game folder.') + a.ctx.log.assert_called_once_with('the game ended after restarting itself; its log says: FATAL: vk: the GPU ' + 'device was lost (seen at: x)') + self.assertNotIn('[launcher]', log.read_text(encoding='utf-8')) + old = time.time() - 3600 + log.write_text('FATAL: an earlier run started without the launcher\n', encoding='utf-8') + os.utime(log, (old, old)) + a, _ = self.ended(0, None, started=time.time()) + self.assertEqual(a.message, '') + a.ctx.log.assert_called_once_with('the game ended with code 0') + + def test_a_log_cut_at_its_cap_says_nothing_of_its_end(self): + """A log that reached its 64 MiB cap (runtime/main.c log_sink) wrote its end lines to stderr only: it is + not taken for a run without its own end.""" + try: + from launcher.ui import app + except ImportError as e: + self.skipTest(f'no window toolkit: {e}') + a, log = self.ended(0, '[host] perf: x\n[host] log: the file reached 64 MiB, the rest of this run goes to ' + 'stderr only\n') + self.assertIsNone(app.log_has_own_exit(self.tmp)) + a.ctx.log.assert_called_once_with('the game ended with code 0') + self.assertNotIn('[launcher]', log.read_text(encoding='utf-8')) + def test_a_fatal_exit_shows_the_games_fatal_line(self): """Exit codes 70 and 71 follow a FATAL line in the game's log: the home screen and launcher.log name it.""" try: