diff --git a/docs/settings.md b/docs/settings.md index 14f8207b..5258f39c 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -244,6 +244,7 @@ These names are code patch sets built into the generated game code (`recomp/patc | `fixed_res_patch` (default `0`) | Patch set that holds the game's dynamic resolution at 100 percent (the scene tier). | The resolution code switches this set from `dynamic_res` (on at `0`); a manual value is replaced. | Unknown | | `freecam_patch` (default `0`) | Patch set of the hook in the camera component update behind the free camera (`freecam_pad`, `freecam_key`) on game 1.4.3; the *Free camera* row of the Controls tab. Read at start. | `1` puts the hook in the camera update: while the free camera is off it runs the game's own load and one compare. `0` runs the game's code as shipped: the combo and the key do nothing and the game gets the combo's buttons. | Safe | | `fov_patch` (default `0`) | Patch set that scales the camera's vertical view angle by the field-of-view setting. | The resolution code switches this set itself whenever the field of view is not 100 percent; a manual value is replaced. | Unknown | +| `lightning_fix` (default `1`) | Patch set on 1.2.1 and 1.4.3 (set `lightning`; 1.4.3 main+0x62b1fc, main+0x62b3d8, main+0x62b51c; 1.2.1 main+0xab8d50, main+0xab9014, main+0xab8f90): in a thunderstorm the world manager's lightning update runs once per frame and draws, each update, a random number for each of three fixed chances, 0.013333 for a distant bolt and 0.01 for a near strike and for the environment's lightning flag that near strikes also set (#1287). The set multiplies each chance by the frame ratio, at most 1, so above 30 fps a storm has as much lightning per second as at 30 fps; at 30 fps and below the chances are the game's own. Game 1.1.0 has no site and keeps the game's code. | `0` runs the game's code: the higher the frame rate, the more distant bolts and lightning flags. Counted on 1.4.3 in one storm (205 s, the reporter's save) with a local build that logs each draw that succeeds: distant bolts 22, 52 and 94 to 96 a minute at 30, 60 and 120 fps with `0`, and 26, 27 and 20 to 24 with `1`; the lightning flag 19, 34 and 64 to 80 a minute of the storm's lightning phase with `0`, 12 to 17 with `1`. Near strikes stayed at 14 to 18 per run at every rate with either value. On 1.2.1 counted from screenshots only (no logging build; a storm in Hyrule Field, one screenshot every 0.2 s, each counted bolt checked by eye): 19 screenshots with a distant bolt a minute at 30 fps, about 61 at 120 fps with `0`, 15 with `1`; the same count on 1.4.3 gives 25 to 26, 65 to 68 and 16 to 20. | Safe | | `mouse_direct_patch` (default `1`) | Patch set of the hooks in the game's camera code behind `mouse_mode = direct` on game 1.4.3. | `0` stops `mouse_mode = direct` from taking effect; other mouse modes are unaffected. | Safe | | `optref_guard` (default `1`) | Patch set that treats a negative value in the optional reference at object +0x6b0 (1.4.3 main+0x1bd01c0, 1.2.1 main+0x1622bec) as absent instead of loading through it (#1005). | `0` runs the game's code as shipped: the random crash reading `0xffffffffffffffff` after minutes to hours of play can return. | Risky | | `patch_output` (default `0`) | Patch set that makes the game use the configured output size for its swapchain and display configuration. | The resolution code switches this set whenever the output differs from the base size; a manual value is replaced. | Unknown | diff --git a/installer/gui.py b/installer/gui.py index a2e2f5ce..8dffaf2d 100644 --- a/installer/gui.py +++ b/installer/gui.py @@ -114,6 +114,73 @@ def use_sun_valley(root, ui_font): return True +class ScrollArea(ttk.Frame): + """A screen's content scrolls while its action bar stays outside the viewport.""" + + def __init__(self, parent): + super().__init__(parent) + background = ttk.Style(parent).lookup('TFrame', 'background') or parent.winfo_toplevel().cget('background') + self.canvas = tk.Canvas(self, width=1, height=1, borderwidth=0, highlightthickness=0, background=background) + self.scrollbar = ttk.Scrollbar(self, orient='vertical', command=self.canvas.yview) + self.canvas.configure(yscrollcommand=self.scrollbar.set) + self.canvas.pack(side='left', fill='both', expand=True) + self.content = ttk.Frame(self.canvas) + self.window = self.canvas.create_window((0, 0), window=self.content, anchor='nw') + self.content.bind('', lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox('all'))) + self.canvas.bind('', lambda e: self.canvas.itemconfigure(self.window, width=e.width)) + root = self.winfo_toplevel() + root.bind('', self.reveal_focus, add='+') + for sequence in ('',) + (('', '') if sys.platform.startswith('linux') else ()): + root.bind(sequence, self.wheel, add='+') + + def contains(self, widget): + return widget is self.canvas or str(widget).startswith(str(self.content) + '.') or widget is self.content + + def natural(self): + width = self.content.winfo_reqwidth() + if int(self.canvas.cget('width')) == width: + return False + self.canvas.configure(width=width) + return True + + def limit_height(self, height): + height = max(1, height) + scroll = height < self.content.winfo_reqheight() + changed = bool(self.scrollbar.winfo_manager()) != scroll + if changed: + if scroll: + self.scrollbar.pack(side='right', fill='y', before=self.canvas) + else: + self.scrollbar.pack_forget() + if int(self.canvas.cget('height')) != height: + self.canvas.configure(height=height) + changed = True + return changed + + def reveal_focus(self, event): + if not self.contains(event.widget) or event.widget is self.canvas: + return + top = event.widget.winfo_rooty() - self.content.winfo_rooty() + bottom = top + event.widget.winfo_height() + visible = self.canvas.canvasy(0) + height = self.canvas.winfo_height() + if top < visible: + self.canvas.yview_moveto(top / max(1, self.content.winfo_height())) + elif bottom > visible + height: + self.canvas.yview_moveto((bottom - height) / max(1, self.content.winfo_height())) + + def wheel(self, event): + if not self.contains(event.widget) or event.widget.winfo_class() in ('Text', 'Listbox', 'TCombobox'): + return + if self.canvas.yview() == (0.0, 1.0): + return + units = -1 if event.num == 4 else 1 if event.num == 5 else -int(event.delta / 120) + if not units and event.delta: + units = -1 if event.delta > 0 else 1 + self.canvas.yview_scroll(units, 'units') + return 'break' + + class App: def __init__(self, root, ui_lang, layout, run_args=None, rebuild=None): self.root, self.layout = root, layout @@ -180,6 +247,7 @@ class App: self.ui_box.pack(side='left') self.body = ttk.Frame(root, padding=PAD) self.body.pack(fill='both', expand=True) + self.scroll_areas = {} self.frames = {'form': self.build_form(), 'run': self.build_run(), 'finish': self.build_finish()} self.vars['lang'].set(self.lang_label(self.lang_code)) self.vars['dest'].trace_add('write', lambda *_: self.refresh_form()) @@ -267,13 +335,28 @@ class App: for), so a screen or language switch does not move the buttons sideways, and the height of the shown screen, so no screen carries the empty band of a taller one. Every text change that can add lines calls it again, or pack takes the missing height from the button bars. Without `shrink` the window only grows and a size the user - dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit.""" + dragged it to stays; a screen or language switch and closing the details or the log shrink it to fit. A screen + taller than the display scrolls its content while its action bar remains outside the viewport.""" self.root.update_idletasks() + widths_changed = [area.natural() for area in self.scroll_areas.values()] + if any(widths_changed): + self.root.update_idletasks() widths = [f.winfo_reqwidth() for f in self.frames.values()] shown = self.frames[self.screen] if self.screen else max(self.frames.values(), key=lambda f: f.winfo_reqheight()) chrome = self.root.winfo_reqheight() - self.body.winfo_reqheight() # the title row above the body w = max(self.root.winfo_reqwidth(), max(widths) + 2 * PAD) h = chrome + shown.winfo_reqheight() + 2 * PAD + area = self.scroll_areas.get(self.screen) + if area: + h += area.content.winfo_reqheight() - area.canvas.winfo_reqheight() + # Leave room for window decorations and the desktop's panels. Content scrolls; the footer stays visible. + limit = max(1, self.root.winfo_screenheight() - dpi.px(80)) + if area: + changed = area.limit_height(area.content.winfo_reqheight() - max(0, h - limit)) + h = min(h, limit) + if changed: + self.root.update_idletasks() + w = max(w, shown.winfo_reqwidth() + 2 * PAD) # refresh_run calls it on every poll: leave the window alone while nothing grew if (w, h) == self.fitted and (not shrink or self.root.winfo_height() == h): return @@ -281,6 +364,12 @@ class App: self.root.minsize(w, h) self.root.geometry(f'{max(w, self.root.winfo_width())}x{h if shrink else max(h, self.root.winfo_height())}') + def scroll_content(self, parent, name): + area = ScrollArea(parent) + area.pack(fill='both', expand=True) + self.scroll_areas[name] = area + return area.content + def notice(self, parent): w = ttk.Label(parent, style='Notice.TLabel', wraplength=WRAP, justify='left') self.bind_text(w, 'text', 'ui.notice') @@ -310,9 +399,10 @@ class App: self.form_error.pack(side='bottom', anchor='w', pady=(dpi.px(4), 0)) self.update_hint = ttk.Label(f, style='Status.TLabel', wraplength=WRAP, justify='left') self.update_hint.pack(side='bottom', anchor='w', pady=(dpi.px(8), 0)) - self.form_intro = self.label(f, 'ui.intro', wraplength=WRAP, justify='left') + content = self.scroll_content(f, 'form') + self.form_intro = self.label(content, 'ui.intro', wraplength=WRAP, justify='left') self.form_intro.pack(anchor='w', pady=(0, dpi.px(4))) - grid = ttk.Frame(f) + grid = ttk.Frame(content) grid.pack(fill='x') grid.columnconfigure(1, weight=1) self.section(grid, 0, 'ui.section_files', dpi.px(6)) @@ -344,16 +434,16 @@ class App: # On by default and named with its source and licence: the player sees what is downloaded and can untick it. # The source and licence line is the first one under More details. self.dlss_var = tk.BooleanVar(value=True) - dlss = ttk.Checkbutton(f, variable=self.dlss_var) + dlss = ttk.Checkbutton(content, variable=self.dlss_var) self.bind_text(dlss, 'text', 'ui.dlss') dlss.pack(anchor='w', pady=(dpi.px(12), 0)) # The explanations stay out of the way until asked for: a link opens them under it - self.details_toggle = ttk.Label(f, style='Link.TLabel', cursor='hand2', takefocus=True) + self.details_toggle = ttk.Label(content, style='Link.TLabel', cursor='hand2', takefocus=True) self.bind_text(self.details_toggle, 'text', 'ui.more_details') for seq in ('', '', ''): self.details_toggle.bind(seq, lambda _e: self.toggle_details()) self.details_toggle.pack(anchor='w', pady=(dpi.px(8), 0)) - self.details = ttk.Frame(f) # packed after the link when open; no holder frame, as an emptied Tk frame keeps + self.details = ttk.Frame(content) # packed after the link when open; no holder frame, as an emptied Tk frame keeps # the height its last child gave it for id in ('ui.dlss_help', 'ui.formats_help', 'ui.compressed_help', 'ui.firmware_help', 'ui.keys_private'): self.label(self.details, id, style='Muted.TLabel', wraplength=WRAP - dpi.px(16), @@ -379,14 +469,15 @@ class App: self.cancel_button.pack(side='right') self.log_toggle = self.button(bar, 'ui.show_log', self.toggle_log) self.log_toggle.pack(side='left') - self.run_header = ttk.Label(f, font=(self.ui_font, 11, 'bold')) + content = self.scroll_content(f, 'run') + self.run_header = ttk.Label(content, font=(self.ui_font, 11, 'bold')) self.run_header.pack(anchor='w') self.step_rows = {} - self.steps_box = ttk.Frame(f) + self.steps_box = ttk.Frame(content) self.steps_box.pack(fill='x', pady=dpi.px(8)) - self.phase_label = ttk.Label(f, wraplength=WRAP, justify='left') + self.phase_label = ttk.Label(content, wraplength=WRAP, justify='left') self.phase_label.pack(anchor='w') - bar_holder = ttk.Frame(f) + bar_holder = ttk.Frame(content) bar_holder.pack(fill='x', pady=(dpi.px(4), dpi.px(6))) self.bar = ttk.Progressbar(bar_holder, mode='determinate', maximum=1000) self.bar.pack(fill='both', expand=True) @@ -396,11 +487,11 @@ class App: # holder follows it. bar_holder.pack_propagate(False) bar_holder.configure(height=dpi.px(22)) - self.space_label = ttk.Label(f, wraplength=WRAP, justify='left') + self.space_label = ttk.Label(content, wraplength=WRAP, justify='left') self.space_label.pack(anchor='w') - self.warn_label = ttk.Label(f, wraplength=WRAP, justify='left', foreground='#9a6700') + self.warn_label = ttk.Label(content, wraplength=WRAP, justify='left', foreground='#9a6700') self.warn_label.pack(anchor='w') - self.log_frame = ttk.Frame(f) + self.log_frame = ttk.Frame(content) self.log = tk.Text(self.log_frame, height=10, wrap='word', state='disabled', font=(self.mono_font, 9)) scroll = ttk.Scrollbar(self.log_frame, command=self.log.yview) self.log.configure(yscrollcommand=scroll.set) @@ -420,13 +511,14 @@ class App: self.back_button.pack(side='left') if self.rebuild: # a failed or cancelled rebuild: the game starts with the code it has self.button(bar, 'ui.start_game', self.start_game).pack(side='right', padx=(0, dpi.px(8))) - self.finish_title = ttk.Label(f, style='Title.TLabel', wraplength=WRAP, justify='left') + content = self.scroll_content(f, 'finish') + self.finish_title = ttk.Label(content, style='Title.TLabel', wraplength=WRAP, justify='left') self.finish_title.pack(anchor='w') - self.finish_text = ttk.Label(f, wraplength=WRAP, justify='left') + self.finish_text = ttk.Label(content, wraplength=WRAP, justify='left') self.finish_text.pack(anchor='w', pady=dpi.px(8)) - self.finish_steps = ttk.Frame(f) + self.finish_steps = ttk.Frame(content) self.finish_steps.pack(fill='x', pady=(0, dpi.px(8))) - self.finish_notice = self.notice(f) + self.finish_notice = self.notice(content) self.finish_notice.pack(fill='x', pady=(dpi.px(8), 0)) return f diff --git a/installer/hostcheck.c b/installer/hostcheck.c index d3099271..0433a874 100644 --- a/installer/hostcheck.c +++ b/installer/hostcheck.c @@ -57,9 +57,12 @@ static int x86_64_v3(void) { return (c & (1u << 5)) != 0; // LZCNT (ABM) } +// stdout is a pipe, so it is fully buffered: each part is flushed before the next call that can crash, and a probe +// that a Vulkan layer or driver kills still hands the installer what it found (installer/steps.py Check.probe_host). int main(void) { printf("{\"x86_64_v2\": %s, \"x86_64_v3\": %s, ", x86_64_v2() ? "true" : "false", x86_64_v3() ? "true" : "false"); + fflush(stdout); void *lib = open_lib(); PFN_vkGetInstanceProcAddr gipa = lib ? (PFN_vkGetInstanceProcAddr)lib_sym(lib, "vkGetInstanceProcAddr") : NULL; if (!gipa) { @@ -67,6 +70,7 @@ int main(void) { return 0; } printf("\"loader\": true, "); + fflush(stdout); PFN_vkCreateInstance create = (PFN_vkCreateInstance)gipa(NULL, "vkCreateInstance"); VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "totk-install", .apiVersion = VK_API_VERSION_1_3}; diff --git a/installer/ini.py b/installer/ini.py index 5cad6f00..785e20df 100644 --- a/installer/ini.py +++ b/installer/ini.py @@ -1,7 +1,7 @@ """totk.ini: set the game language and keep everything else (keys and syntax as runtime/cfg.c reads them). A new file starts from totk.ini.example, whose lines are all commented defaults. The language goes into `lang` -(a Switch language code, runtime/ov_system.c): an active `lang = ...` line is rewritten in place, else the commented +(a Switch language code, runtime/ov_system.c): the last active `lang = ...` line is rewritten in place, else the commented `# lang = ...` line of the example is activated, else the line is added to [language] (created at the end if missing). Other lines, comments and line order stay as they are. """ @@ -32,8 +32,9 @@ def set_language(text, lang): """text with `lang = ` (an alias written as its canonical code); see the module docstring.""" lang = canonical_language(lang) lines = text.splitlines() - for i, line in enumerate(lines): - m = ACTIVE.match(line) + # runtime/cfg.c add gives the last non-empty value priority, regardless of section or the totk_ prefix. + for i in range(len(lines) - 1, -1, -1): + m = ACTIVE.match(lines[i]) if m: lines[i] = f'{m.group(1)}lang{m.group(2)}{lang}' return '\n'.join(lines) + '\n' @@ -53,10 +54,14 @@ def set_language(text, lang): def get_language(text): - for line in text.splitlines(): + for line in reversed(text.splitlines()): m = ACTIVE.match(line) if m: - return m.group(3) + value = m.group(3) + if len(value) >= 2 and value[0] == value[-1] == '"': + value = value[1:-1] + if value: # cfg.c add ignores empty values, including an empty quoted string + return value return None diff --git a/installer/recent.py b/installer/recent.py index 5ebe75cd..375ee906 100644 --- a/installer/recent.py +++ b/installer/recent.py @@ -1,4 +1,4 @@ -"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game +r"""The last install folder and source paths, in a per-user file, so an update, a reinstall or a switch to another game version starts with the form filled in. {"format": 1, "dest": ..., "base": ..., "update": ..., "keys": ..., "firmware": ...} diff --git a/installer/screens.py b/installer/screens.py index 02f3ede6..d4818e2a 100644 --- a/installer/screens.py +++ b/installer/screens.py @@ -132,11 +132,16 @@ def displays(): # ---- totk.ini (runtime/cfg.c reads the same keys, in any section, with or without the totk_ prefix) def ini_value(text, name): + """The last nonempty value, with matching quotes removed, as runtime/cfg.c cfg_load and add read it.""" value = None for line in text.splitlines(): - m = re.match(rf'^\s*(?:totk_)?{name}\s*=\s*([^\s#;]*)', line, re.IGNORECASE) + m = re.match(rf'^\s*(?:totk_)?{re.escape(name)}\s*=(.*)$', line, re.IGNORECASE) if m: - value = m.group(1) + candidate = m.group(1).strip() + if len(candidate) >= 2 and candidate[0] == candidate[-1] == '"': + candidate = candidate[1:-1] + if candidate: + value = candidate return value diff --git a/installer/state.py b/installer/state.py index be264654..e1722504 100644 --- a/installer/state.py +++ b/installer/state.py @@ -36,10 +36,23 @@ def load(dest): data = json.loads(path.read_text(encoding='utf-8')) except (OSError, ValueError): raise StateError('state.unreadable', path) from None - if not isinstance(data, dict) or not isinstance(data.get('steps'), dict): + if not isinstance(data, dict): raise StateError('state.unreadable', path) - if data.get('format', 0) > FORMAT: + version = data.get('format', 0) + if type(version) is not int or version < 0: + raise StateError('state.unreadable', path) + if version > FORMAT: raise StateError('state.newer_format', path) + # The GUI and resume planner read these fields before running a step. A JSON value of the wrong type must take + # the same error path as unreadable JSON, rather than raising from their comparisons or dict lookups. + for name in ('release', 'lang', 'version'): + if name in data and not isinstance(data[name], str): + raise StateError('state.unreadable', path) + for name in ('steps', 'inputs'): + records = data.get(name, {} if name == 'inputs' else None) + if not isinstance(records, dict) or any(not isinstance(record, dict) for record in records.values()): + raise StateError('state.unreadable', path) + data.setdefault('inputs', {}) # older records may omit it; the extraction step expects a dictionary return data diff --git a/installer/steps.py b/installer/steps.py index 12abed07..f231eec5 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -41,6 +41,11 @@ import time import urllib.request from pathlib import Path +if os.name == 'nt': + import winreg +else: + winreg = None + from . import ini, screens from . import layout as layouts from .layout import EXE, SUPPORTED, version_tag @@ -124,6 +129,79 @@ def kill_tree(proc): proc.kill() +def parse_host(text): + """The host check's JSON object, or None when it did not finish (a crash leaves the parts it flushed).""" + try: + host = json.loads(text) + except ValueError: + return None + return host if isinstance(host, dict) and 'devices' in host else None + + +def exit_code(code): + """A process exit code as Windows reports crashes (0xC0000005 for an access violation), else as a number.""" + if os.name == 'nt' and code is not None and (code < 0 or code >= 0xC0000000): + return f'0x{code & 0xFFFFFFFF:08X}' + return str(code) + + +def layer_manifests(): + """Implicit Vulkan layer manifests where the Khronos loader looks for them (its docs, LoaderLayerInterface.md, + "Layer Discovery"): the folders in VK_IMPLICIT_LAYER_PATH or VK_ADD_IMPLICIT_LAYER_PATH, then on Windows the + manifests HKLM and HKCU\\SOFTWARE\\Khronos\\Vulkan\\ImplicitLayers enable with a DWORD 0, read in the 64-bit view + the 64-bit probe and game use; elsewhere the implicit_layer.d folders. Layers a driver registers under its display + adapter's key are not listed.""" + found = [] + for var in ('VK_IMPLICIT_LAYER_PATH', 'VK_ADD_IMPLICIT_LAYER_PATH'): + for part in filter(None, os.environ.get(var, '').split(os.pathsep)): + p = Path(part) + found += sorted(p.glob('*.json')) if p.is_dir() else [p] + if winreg: + for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER): + try: + key = winreg.OpenKey(root, r'SOFTWARE\Khronos\Vulkan\ImplicitLayers', 0, + winreg.KEY_READ | winreg.KEY_WOW64_64KEY) + except OSError: + continue + with key: + i = 0 + while True: + try: + path, enabled, _ = winreg.EnumValue(key, i) + except OSError: + break + i += 1 + if enabled == 0: # a DWORD 0 enables the manifest, anything else skips it + found.append(Path(path)) + else: + home = Path.home() + config = [os.environ.get('XDG_CONFIG_HOME') or home / '.config', + *(os.environ.get('XDG_CONFIG_DIRS') or '/etc/xdg').split(':'), '/usr/local/etc', '/etc'] + data = [os.environ.get('XDG_DATA_HOME') or home / '.local' / 'share', + *(os.environ.get('XDG_DATA_DIRS') or '/usr/local/share:/usr/share').split(':')] + for base in filter(None, config + data): + found += sorted((Path(base) / 'vulkan' / 'implicit_layer.d').glob('*.json')) + return found + + +def implicit_vulkan_layers(): + """(layer name, manifest path) of each readable implicit Vulkan layer manifest of layer_manifests(), for the + search for the layer that crashes the host check. A manifest the loader cannot read loads no layer and is left + out; a manifest listed twice counts once.""" + layers = [] + for path in dict.fromkeys(layer_manifests()): + try: + manifest = json.loads(path.read_text(encoding='utf-8-sig')) + except (OSError, ValueError): + continue + entries = (manifest.get('layers') or [manifest.get('layer')]) if isinstance(manifest, dict) else [] + for entry in entries: + name = entry.get('name') if isinstance(entry, dict) else None + if isinstance(name, str) and (name, path) not in layers: + layers.append((name, path)) + return layers + + def linux_glibc(): """(major, minor) of the C library this Linux process runs on, None elsewhere or when it is not glibc.""" try: @@ -423,8 +501,19 @@ class Check(Step): return {} def host(self, ctx): + """Builds and runs the host check once per run: key() asks first and run() reports, so a failure is kept on + ctx and raised again rather than a crashing probe and its retries running twice.""" if getattr(ctx, 'host', None) is not None: return + if getattr(ctx, 'host_error', None) is not None: + raise ctx.host_error + try: + self.check_host(ctx) + except InstallError as e: + ctx.host_error = e + raise + + def check_host(self, ctx): layout, work = ctx.layout, ctx.temp / 'check' glibc = linux_glibc() if glibc and glibc < GLIBC_NEEDED and not layout.dev: @@ -443,12 +532,7 @@ class Check(Step): if r.returncode: ctx.reporter.log(r.stdout + r.stderr) raise InstallError('check.toolchain_broken', detail=(r.stderr or r.stdout).strip()[-400:]) - r = subprocess.run([str(exe)], capture_output=True, text=True, errors='replace') - try: - host = json.loads(r.stdout) - except ValueError: - raise InstallError('check.host_probe_failed', code=r.returncode) from None - ctx.reporter.log(f'host: {r.stdout.strip()}') + host = self.probe_host(ctx, exe) if not host['x86_64_v2']: raise InstallError('check.cpu_too_old') # v3 is the faster build; v2 runs on CPUs without AVX2/FMA (runtime/fma.c supplies the fused multiply-add). @@ -468,6 +552,60 @@ class Check(Step): ctx.reporter.warning('warn.kernel_old', version='.'.join(map(str, kernel))) ctx.host = host + # Windows refuses to start a program a policy does not trust (issue #875): Smart App Control and other App Control + # policies (4551 "An Application Control policy has blocked this file"; 4556-4559 and 4580-4583 the same with the + # reputation verdict, among them 4559 "Unable to contact reputation service for unknown file"), group policy (1260 + # "This program is blocked by group policy") and an antivirus that flags or removes the file (225, 226). hostcheck + # is the first program the setup builds on this PC; totk.exe is built the same way and unsigned too, so the install + # cannot go on. + BLOCKED_WINERRORS = {225, 226, 1260, 4551, 4556, 4557, 4558, 4559, 4580, 4581, 4582, 4583} + LAYER_TRIES = 16 # implicit layers tried one by one in the search for the one that crashes the probe + + def probe_host(self, ctx, exe): + """Runs the host check check_host() built and returns its JSON. A probe that crashes inside Vulkan is run again + with the implicit Vulkan layers off (VK_LOADER_LAYERS_DISABLE=~implicit~, Vulkan loader 1.3.234 or later): + overlays, recorders and tuning tools install such layers, and a broken one kills every Vulkan program at + vkCreateInstance (issue #1345, exit code 0xC0000005 after "Checking the processor and the graphics card"). + When that run passes, each listed layer is turned off alone to name the one that crashes. The install stops + either way: totk.exe --prepare-shaders in the prepare step and the game itself load the same layers + (runtime/vk_device.c create_instance), so going on would fail after lift and compile.""" + rep = ctx.reporter + r = self.run_probe(exe) + host = parse_host(r.stdout) + if host is not None: + rep.log(f'host: {r.stdout.strip()}') + return host + code = exit_code(r.returncode) + rep.log(f'host: the check stopped with exit code {code}; it printed {r.stdout.strip()!r}') + if '"loader": true' not in r.stdout: + raise InstallError('check.host_probe_failed', code=code) + retry = self.run_probe(exe, dict(os.environ, VK_LOADER_LAYERS_DISABLE='~implicit~')) + if parse_host(retry.stdout) is None: + rep.log(f'host: without implicit Vulkan layers too: exit code {exit_code(retry.returncode)}, ' + f'{retry.stdout.strip()!r}') + raise InstallError('check.vulkan_crash', code=code) + layers = implicit_vulkan_layers() + rep.log(f'host: passes with the implicit Vulkan layers off; installed: ' + f'{", ".join(f"{n} ({p})" for n, p in layers) or "none listed"}') + culprits = [(name, path) for name, path in layers[:self.LAYER_TRIES] + if parse_host(self.run_probe(exe, dict(os.environ, VK_LOADER_LAYERS_DISABLE=name)).stdout)] + if culprits: + rep.log(f'host: passes without {", ".join(n for n, _ in culprits)}') + raise InstallError('check.vulkan_layer_crash', code=code, + layers=', '.join(f'{n} ({p})' for n, p in culprits), + disable=','.join(n for n, _ in culprits)) + raise InstallError('check.vulkan_layers_crash', code=code, + layers=', '.join(f'{n} ({p})' for n, p in layers) or '?') + + def run_probe(self, exe, env=None): + try: + return subprocess.run([str(exe)], capture_output=True, text=True, errors='replace', env=env) + except OSError as e: + if getattr(e, 'winerror', None) in self.BLOCKED_WINERRORS: + raise InstallError('check.host_blocked', path=str(exe), detail=e.strerror or str(e)) from None + raise InstallError('check.host_probe_failed', + code=f'{getattr(e, "winerror", None) or e.errno}: {e.strerror or e}') from None + def inputs(self, ctx): """Open both files with the keys as the extraction will. Returns the bytes of both Program NCAs.""" o = ctx.options diff --git a/installer/text/de.json b/installer/text/de.json index 09f2d3d6..793eea13 100644 --- a/installer/text/de.json +++ b/installer/text/de.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "Der mitgelieferte Compiler funktioniert nicht: {detail}", "check.glibc_old": "Die C-Bibliothek dieses Systems ist glibc {version}; der Compiler des Setups braucht {need} oder neuer (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 und neuer haben sie). Ein Systemupdate behebt das.", "check.host_probe_failed": "Die Computerprüfung ist nicht gelaufen (Exit-Code {code}).", + "check.host_blocked": "Windows hat ein Programm blockiert, das das Setup auf diesem PC erstellt hat ({path}): {detail}. Smart App Control, eine App-Control-Richtlinie oder ein Virenscanner blockiert unsignierte Programme; das Spiel selbst wird genauso auf diesem PC erstellt und würde ebenfalls blockiert. Erlaube den Setup-Ordner in deinem Virenscanner oder schalte Smart App Control in der Windows-Sicherheit (App- und Browsersteuerung) aus und starte das Setup erneut.", + "check.vulkan_crash": "Der Grafiktreiber ist abgestürzt, als das Setup nach den Grafikkarten gefragt hat (Exit-Code {code}), auch mit ausgeschalteten Vulkan-Layern anderer Programme. Installiere den neuesten Treiber für deine Grafikkarte.", + "check.vulkan_layer_crash": "Ein Vulkan-Layer, den ein anderes Programm installiert hat, lässt Vulkan-Programme auf diesem PC abstürzen (Exit-Code {code}), und das Spiel würde beim Start genauso abstürzen. Der Layer: {layers}. Aktualisiere oder deinstalliere das Programm, zu dem er gehört (der Pfad zeigt seinen Ordner), oder schalte den Layer aus: Setze für dein Benutzerkonto die Umgebungsvariable VK_LOADER_LAYERS_DISABLE auf {disable}. Starte danach das Setup erneut.", + "check.vulkan_layers_crash": "Ein Vulkan-Layer, den ein anderes Programm installiert hat, lässt Vulkan-Programme auf diesem PC abstürzen (Exit-Code {code}): Mit allen solchen Layern ausgeschaltet läuft die Prüfung durch, und mit ihnen würde das Spiel beim Start genauso abstürzen. Die installierten Layer einzeln auszuschalten hat ihn nicht eingegrenzt. Installierte Layer: {layers}. Aktualisiere oder deinstalliere die Overlay-, Aufnahme- oder Tuning-Programme darunter, oder schalte alle solchen Layer aus: Setze für dein Benutzerkonto die Umgebungsvariable VK_LOADER_LAYERS_DISABLE auf ~implicit~ (das schaltet auch Overlays wie das von Steam in jedem Vulkan-Spiel aus). Starte danach das Setup erneut.", "check.cpu_too_old": "Diesem Prozessor fehlt x86-64-v2 (SSE4.2, POPCNT und CMPXCHG16B), die älteste Stufe, für die das Spiel gebaut wird. Intel Nehalem (2008) oder AMD Bulldozer (2011) und neuer haben sie.", "check.vulkan_missing": "Es ist kein Vulkan-Treiber installiert. Installiere den neuesten Treiber für deine Grafikkarte.", "check.vulkan_no_device": "Vulkan findet keine Grafikkarte. Installiere den neuesten Treiber für deine Grafikkarte.", diff --git a/installer/text/en.json b/installer/text/en.json index b643c5a6..e2ad5f93 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -57,6 +57,10 @@ "check.toolchain_broken": "The bundled compiler does not work: {detail}", "check.glibc_old": "This system's C library is glibc {version}; the setup's compiler needs {need} or later (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 and newer have it). Updating the system fixes this.", "check.host_probe_failed": "The computer check did not run (exit code {code}).", + "check.host_blocked": "Windows blocked a program the setup built on this PC ({path}): {detail}. Smart App Control, an App Control policy or an antivirus blocks unsigned programs; the game itself is built on this PC the same way, so it would be blocked too. Allow the setup folder in your antivirus, or turn off Smart App Control in Windows Security (App & browser control), then run the setup again.", + "check.vulkan_crash": "The graphics driver crashed while the setup asked it for the graphics cards (exit code {code}), also with the Vulkan layers of other programs turned off. Install the latest driver for your graphics card.", + "check.vulkan_layer_crash": "A Vulkan layer that another program installed crashes Vulkan programs on this PC (exit code {code}), and the game would crash at start the same way. The layer: {layers}. Update or uninstall the program it belongs to (the path shows its folder), or turn the layer off: set the environment variable VK_LOADER_LAYERS_DISABLE to {disable} for your user account. Then run the setup again.", + "check.vulkan_layers_crash": "A Vulkan layer that another program installed crashes Vulkan programs on this PC (exit code {code}): with all such layers off the check passes, and the game would crash at start the same way with them on. Turning the installed layers off one at a time did not single it out. Installed layers: {layers}. Update or uninstall the overlay, recorder or tuning programs among them, or turn all such layers off: set the environment variable VK_LOADER_LAYERS_DISABLE to ~implicit~ for your user account (this also turns off overlays such as Steam's in every Vulkan game). Then run the setup again.", "check.cpu_too_old": "This processor lacks x86-64-v2 (SSE4.2, POPCNT and CMPXCHG16B), the oldest level the game is built for. Intel Nehalem (2008) or AMD Bulldozer (2011) and newer have it.", "check.vulkan_missing": "No Vulkan driver is installed. Install the latest driver for your graphics card.", "check.vulkan_no_device": "Vulkan finds no graphics card. Install the latest driver for your graphics card.", diff --git a/installer/text/es.json b/installer/text/es.json index fb6d29bd..b3270249 100644 --- a/installer/text/es.json +++ b/installer/text/es.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "El compilador incluido no funciona: {detail}", "check.glibc_old": "La biblioteca C de este sistema es glibc {version}; el compilador del instalador necesita {need} o posterior (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 y posteriores la tienen). Actualizar el sistema lo soluciona.", "check.host_probe_failed": "La comprobación del equipo no se ejecutó (código de salida {code}).", + "check.host_blocked": "Windows bloqueó un programa que el instalador creó en este PC ({path}): {detail}. Smart App Control, una directiva de App Control o un antivirus bloquean los programas sin firmar; el propio juego se crea igual en este PC, así que también se bloquearía. Permite la carpeta del instalador en tu antivirus o desactiva Smart App Control en Seguridad de Windows (Control de aplicaciones y navegador) y vuelve a ejecutar el instalador.", + "check.vulkan_crash": "El controlador gráfico falló cuando el instalador le pidió las tarjetas gráficas (código de salida {code}), también con las capas Vulkan de otros programas desactivadas. Instala el controlador más reciente de tu tarjeta gráfica.", + "check.vulkan_layer_crash": "Una capa Vulkan que instaló otro programa hace fallar los programas Vulkan en este PC (código de salida {code}), y el juego fallaría igual al iniciar. La capa: {layers}. Actualiza o desinstala el programa al que pertenece (la ruta muestra su carpeta), o desactiva la capa: define para tu cuenta de usuario la variable de entorno VK_LOADER_LAYERS_DISABLE con el valor {disable}. Después vuelve a ejecutar el instalador.", + "check.vulkan_layers_crash": "Una capa Vulkan que instaló otro programa hace fallar los programas Vulkan en este PC (código de salida {code}): con todas esas capas desactivadas la comprobación pasa, y con ellas el juego fallaría igual al iniciar. Desactivar las capas instaladas una por una no permitió identificarla. Capas instaladas: {layers}. Actualiza o desinstala los programas de superposición, grabación o ajuste que haya entre ellas, o desactiva todas esas capas: define para tu cuenta de usuario la variable de entorno VK_LOADER_LAYERS_DISABLE con el valor ~implicit~ (esto también desactiva superposiciones como la de Steam en todos los juegos Vulkan). Después vuelve a ejecutar el instalador.", "check.cpu_too_old": "Este procesador no tiene x86-64-v2 (SSE4.2, POPCNT y CMPXCHG16B), el nivel más antiguo para el que se compila el juego. Intel Nehalem (2008) o AMD Bulldozer (2011) y posteriores lo tienen.", "check.vulkan_missing": "No hay ningún controlador Vulkan instalado. Instala el controlador más reciente de tu tarjeta gráfica.", "check.vulkan_no_device": "Vulkan no encuentra ninguna tarjeta gráfica. Instala el controlador más reciente de tu tarjeta gráfica.", diff --git a/installer/text/fr.json b/installer/text/fr.json index a0b1b2f1..4812f769 100644 --- a/installer/text/fr.json +++ b/installer/text/fr.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "Le compilateur fourni ne fonctionne pas : {detail}", "check.glibc_old": "La bibliothèque C de ce système est glibc {version} ; le compilateur de l'installation demande {need} ou plus récent (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 et plus récents l'ont). Mettre à jour le système corrige cela.", "check.host_probe_failed": "La vérification de l'ordinateur ne s'est pas exécutée (code de sortie {code}).", + "check.host_blocked": "Windows a bloqué un programme que l'installateur a compilé sur ce PC ({path}) : {detail}. Smart App Control, une stratégie App Control ou un antivirus bloque les programmes non signés ; le jeu lui-même est compilé de la même façon sur ce PC et serait bloqué aussi. Autorisez le dossier de l'installateur dans votre antivirus, ou désactivez Smart App Control dans Sécurité Windows (Contrôle des applications et du navigateur), puis relancez l'installateur.", + "check.vulkan_crash": "Le pilote graphique a planté quand l'installateur lui a demandé les cartes graphiques (code de sortie {code}), même avec les couches Vulkan des autres programmes désactivées. Installez le dernier pilote de votre carte graphique.", + "check.vulkan_layer_crash": "Une couche Vulkan installée par un autre programme fait planter les programmes Vulkan sur ce PC (code de sortie {code}), et le jeu planterait de la même façon au démarrage. La couche : {layers}. Mettez à jour ou désinstallez le programme auquel elle appartient (le chemin montre son dossier), ou désactivez la couche : définissez pour votre compte utilisateur la variable d'environnement VK_LOADER_LAYERS_DISABLE avec la valeur {disable}. Relancez ensuite l'installateur.", + "check.vulkan_layers_crash": "Une couche Vulkan installée par un autre programme fait planter les programmes Vulkan sur ce PC (code de sortie {code}) : avec toutes ces couches désactivées, la vérification réussit, et avec elles le jeu planterait de la même façon au démarrage. Désactiver les couches installées une par une n'a pas permis de l'identifier. Couches installées : {layers}. Mettez à jour ou désinstallez les programmes d'overlay, d'enregistrement ou de réglage parmi elles, ou désactivez toutes ces couches : définissez pour votre compte utilisateur la variable d'environnement VK_LOADER_LAYERS_DISABLE avec la valeur ~implicit~ (cela désactive aussi les overlays comme celui de Steam dans tous les jeux Vulkan). Relancez ensuite l'installateur.", "check.cpu_too_old": "Ce processeur ne prend pas en charge x86-64-v2 (SSE4.2, POPCNT et CMPXCHG16B), le niveau le plus ancien pour lequel le jeu est compilé. Intel Nehalem (2008) ou AMD Bulldozer (2011) et plus récents l'ont.", "check.vulkan_missing": "Aucun pilote Vulkan n'est installé. Installez le dernier pilote de votre carte graphique.", "check.vulkan_no_device": "Vulkan ne trouve aucune carte graphique. Installez le dernier pilote de votre carte graphique.", diff --git a/installer/text/it.json b/installer/text/it.json index b0323936..63b0dffd 100644 --- a/installer/text/it.json +++ b/installer/text/it.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "Il compilatore incluso non funziona: {detail}", "check.glibc_old": "La libreria C di questo sistema è glibc {version}; il compilatore dell'installazione richiede {need} o successiva (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e successivi la hanno). Aggiornare il sistema risolve il problema.", "check.host_probe_failed": "Il controllo del computer non è stato eseguito (codice di uscita {code}).", + "check.host_blocked": "Windows ha bloccato un programma che il programma di installazione ha compilato su questo PC ({path}): {detail}. Smart App Control, un criterio App Control o un antivirus bloccano i programmi non firmati; anche il gioco viene compilato così su questo PC e verrebbe bloccato. Consenti la cartella di installazione nell'antivirus oppure disattiva Smart App Control in Sicurezza di Windows (Controllo app e browser), poi esegui di nuovo l'installazione.", + "check.vulkan_crash": "Il driver grafico si è bloccato quando l'installazione gli ha chiesto le schede grafiche (codice di uscita {code}), anche con i livelli Vulkan degli altri programmi disattivati. Installa il driver più recente della tua scheda grafica.", + "check.vulkan_layer_crash": "Un livello Vulkan installato da un altro programma fa bloccare i programmi Vulkan su questo PC (codice di uscita {code}) e il gioco si bloccherebbe allo stesso modo all'avvio. Il livello: {layers}. Aggiorna o disinstalla il programma a cui appartiene (il percorso mostra la sua cartella), oppure disattiva il livello: imposta per il tuo account utente la variabile d'ambiente VK_LOADER_LAYERS_DISABLE con il valore {disable}. Poi esegui di nuovo l'installazione.", + "check.vulkan_layers_crash": "Un livello Vulkan installato da un altro programma fa bloccare i programmi Vulkan su questo PC (codice di uscita {code}): con tutti questi livelli disattivati il controllo riesce, e con essi il gioco si bloccherebbe allo stesso modo all'avvio. Disattivare i livelli installati uno alla volta non ha permesso di individuarlo. Livelli installati: {layers}. Aggiorna o disinstalla i programmi di overlay, registrazione o tuning tra questi, oppure disattiva tutti questi livelli: imposta per il tuo account utente la variabile d'ambiente VK_LOADER_LAYERS_DISABLE con il valore ~implicit~ (questo disattiva anche overlay come quello di Steam in tutti i giochi Vulkan). Poi esegui di nuovo l'installazione.", "check.cpu_too_old": "Questo processore non supporta x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), il livello più vecchio per cui il gioco viene compilato. Intel Nehalem (2008) o AMD Bulldozer (2011) e successivi lo supportano.", "check.vulkan_missing": "Non è installato alcun driver Vulkan. Installa il driver più recente della tua scheda grafica.", "check.vulkan_no_device": "Vulkan non trova alcuna scheda grafica. Installa il driver più recente della tua scheda grafica.", diff --git a/installer/text/ja.json b/installer/text/ja.json index 9d47ea4c..ad110fb8 100644 --- a/installer/text/ja.json +++ b/installer/text/ja.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "同梱のコンパイラーが動作しません: {detail}", "check.glibc_old": "このシステムの C ライブラリは glibc {version} です。セットアップのコンパイラーには {need} 以降が必要です (Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 以降にあります)。システムを更新すると解決します。", "check.host_probe_failed": "コンピューターの確認を実行できませんでした (終了コード {code})。", + "check.host_blocked": "セットアップがこの PC でビルドしたプログラム ({path}) を Windows がブロックしました: {detail}。スマート アプリ コントロール、App Control ポリシー、またはウイルス対策ソフトが署名のないプログラムをブロックしています。ゲーム本体も同じ方法でこの PC でビルドされるため、同じくブロックされます。ウイルス対策ソフトでセットアップのフォルダーを許可するか、Windows セキュリティ (アプリとブラウザー コントロール) でスマート アプリ コントロールをオフにしてから、セットアップをもう一度実行してください。", + "check.vulkan_crash": "セットアップがグラフィックカードを問い合わせたときにグラフィックドライバーがクラッシュしました (終了コード {code})。他のプログラムの Vulkan レイヤーをオフにしても同じでした。グラフィックカードの最新ドライバーをインストールしてください。", + "check.vulkan_layer_crash": "他のプログラムがインストールした Vulkan レイヤーが、この PC の Vulkan プログラムをクラッシュさせています (終了コード {code})。ゲームも起動時に同じようにクラッシュします。レイヤー: {layers}。そのレイヤーが属するプログラムを更新するかアンインストールするか (パスでフォルダーがわかります)、レイヤーをオフにしてください: ユーザー アカウントの環境変数 VK_LOADER_LAYERS_DISABLE に {disable} を設定します。その後、セットアップをもう一度実行してください。", + "check.vulkan_layers_crash": "他のプログラムがインストールした Vulkan レイヤーが、この PC の Vulkan プログラムをクラッシュさせています (終了コード {code})。そのようなレイヤーをすべてオフにすると確認は成功し、オンのままではゲームも起動時に同じようにクラッシュします。インストール済みのレイヤーを 1 つずつオフにしても特定できませんでした。インストール済みのレイヤー: {layers}。この中のオーバーレイ、録画、チューニングのプログラムを更新するかアンインストールするか、そのようなレイヤーをすべてオフにしてください: ユーザー アカウントの環境変数 VK_LOADER_LAYERS_DISABLE に ~implicit~ を設定します (Steam などのオーバーレイもすべての Vulkan ゲームでオフになります)。その後、セットアップをもう一度実行してください。", "check.cpu_too_old": "このプロセッサーは、ゲームのビルド対象となる最も古いレベルである x86-64-v2 (SSE4.2、POPCNT、CMPXCHG16B) に対応していません。Intel Nehalem (2008 年) または AMD Bulldozer (2011 年) 以降が対応しています。", "check.vulkan_missing": "Vulkan ドライバーがインストールされていません。グラフィックカードの最新ドライバーをインストールしてください。", "check.vulkan_no_device": "Vulkan がグラフィックカードを見つけられません。グラフィックカードの最新ドライバーをインストールしてください。", diff --git a/installer/text/ko.json b/installer/text/ko.json index 84c0034e..0e6d9557 100644 --- a/installer/text/ko.json +++ b/installer/text/ko.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "포함된 컴파일러가 작동하지 않습니다: {detail}", "check.glibc_old": "이 시스템의 C 라이브러리는 glibc {version}입니다. 설치 프로그램의 컴파일러에는 {need} 이상이 필요합니다(Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 이상에 있음). 시스템을 업데이트하면 해결됩니다.", "check.host_probe_failed": "컴퓨터 확인이 실행되지 않았습니다(종료 코드 {code}).", + "check.host_blocked": "설치 프로그램이 이 PC에서 빌드한 프로그램({path})을 Windows가 차단했습니다: {detail}. 스마트 앱 컨트롤, App Control 정책 또는 백신이 서명되지 않은 프로그램을 차단합니다. 게임 자체도 이 PC에서 같은 방식으로 빌드되므로 마찬가지로 차단됩니다. 백신에서 설치 프로그램 폴더를 허용하거나 Windows 보안(앱 및 브라우저 컨트롤)에서 스마트 앱 컨트롤을 끈 다음 설치 프로그램을 다시 실행하세요.", + "check.vulkan_crash": "설치 프로그램이 그래픽 카드를 조회하는 중에 그래픽 드라이버가 충돌했습니다(종료 코드 {code}). 다른 프로그램의 Vulkan 레이어를 끈 상태에서도 마찬가지였습니다. 그래픽 카드의 최신 드라이버를 설치하세요.", + "check.vulkan_layer_crash": "다른 프로그램이 설치한 Vulkan 레이어 때문에 이 PC의 Vulkan 프로그램이 충돌합니다(종료 코드 {code}). 게임도 시작할 때 같은 방식으로 충돌합니다. 레이어: {layers}. 그 레이어가 속한 프로그램을 업데이트하거나 제거하거나(경로에 폴더가 나옵니다), 레이어를 끄세요: 사용자 계정의 환경 변수 VK_LOADER_LAYERS_DISABLE을 {disable}(으)로 설정합니다. 그런 다음 설치 프로그램을 다시 실행하세요.", + "check.vulkan_layers_crash": "다른 프로그램이 설치한 Vulkan 레이어 때문에 이 PC의 Vulkan 프로그램이 충돌합니다(종료 코드 {code}). 그런 레이어를 모두 끄면 확인을 통과하고, 켜 두면 게임도 시작할 때 같은 방식으로 충돌합니다. 설치된 레이어를 하나씩 꺼 봐도 어느 것인지 찾지 못했습니다. 설치된 레이어: {layers}. 이 중 오버레이, 녹화 또는 튜닝 프로그램을 업데이트하거나 제거하거나, 그런 레이어를 모두 끄세요: 사용자 계정의 환경 변수 VK_LOADER_LAYERS_DISABLE을 ~implicit~(으)로 설정합니다(Steam 같은 오버레이도 모든 Vulkan 게임에서 꺼집니다). 그런 다음 설치 프로그램을 다시 실행하세요.", "check.cpu_too_old": "이 프로세서에는 게임이 빌드되는 가장 오래된 수준인 x86-64-v2(SSE4.2, POPCNT, CMPXCHG16B)가 없습니다. Intel Nehalem(2008) 또는 AMD Bulldozer(2011) 이후 프로세서에 있습니다.", "check.vulkan_missing": "Vulkan 드라이버가 설치되어 있지 않습니다. 그래픽 카드의 최신 드라이버를 설치하세요.", "check.vulkan_no_device": "Vulkan이 그래픽 카드를 찾지 못했습니다. 그래픽 카드의 최신 드라이버를 설치하세요.", diff --git a/installer/text/nl.json b/installer/text/nl.json index 703fc825..2039a550 100644 --- a/installer/text/nl.json +++ b/installer/text/nl.json @@ -54,6 +54,10 @@ "check.toolchain_broken": "De meegeleverde compiler werkt niet: {detail}", "check.glibc_old": "De C-bibliotheek van dit systeem is glibc {version}; de compiler van de installatie heeft {need} of nieuwer nodig (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 en nieuwer hebben die). Het systeem bijwerken lost dit op.", "check.host_probe_failed": "De computercontrole is niet uitgevoerd (afsluitcode {code}).", + "check.host_blocked": "Windows heeft een programma geblokkeerd dat de installatie op deze pc heeft gebouwd ({path}): {detail}. Slim app-beheer, een App Control-beleid of een virusscanner blokkeert niet-ondertekende programma's; het spel zelf wordt op dezelfde manier op deze pc gebouwd en zou ook worden geblokkeerd. Sta de installatiemap toe in je virusscanner, of zet Slim app-beheer uit in Windows-beveiliging (App- en browserbeheer), en start de installatie opnieuw.", + "check.vulkan_crash": "Het grafische stuurprogramma is gecrasht toen de installatie het om de videokaarten vroeg (afsluitcode {code}), ook met de Vulkan-lagen van andere programma's uitgeschakeld. Installeer het nieuwste stuurprogramma voor je videokaart.", + "check.vulkan_layer_crash": "Een Vulkan-laag die een ander programma heeft geïnstalleerd laat Vulkan-programma's op deze pc crashen (afsluitcode {code}), en het spel zou bij het starten op dezelfde manier crashen. De laag: {layers}. Werk het programma waar hij bij hoort bij of verwijder het (het pad toont de map), of zet de laag uit: stel voor je gebruikersaccount de omgevingsvariabele VK_LOADER_LAYERS_DISABLE in op {disable}. Start daarna de installatie opnieuw.", + "check.vulkan_layers_crash": "Een Vulkan-laag die een ander programma heeft geïnstalleerd laat Vulkan-programma's op deze pc crashen (afsluitcode {code}): met al zulke lagen uit slaagt de controle, en met die lagen aan zou het spel bij het starten op dezelfde manier crashen. De geïnstalleerde lagen één voor één uitzetten wees hem niet aan. Geïnstalleerde lagen: {layers}. Werk de overlay-, opname- of tuningprogramma's daartussen bij of verwijder ze, of zet al zulke lagen uit: stel voor je gebruikersaccount de omgevingsvariabele VK_LOADER_LAYERS_DISABLE in op ~implicit~ (dit zet ook overlays zoals die van Steam uit in elk Vulkan-spel). Start daarna de installatie opnieuw.", "check.cpu_too_old": "Deze processor mist x86-64-v2 (SSE4.2, POPCNT en CMPXCHG16B), het oudste niveau waarvoor het spel wordt gebouwd. Intel Nehalem (2008) of AMD Bulldozer (2011) en nieuwer hebben het.", "check.vulkan_missing": "Er is geen Vulkan-stuurprogramma geïnstalleerd. Installeer het nieuwste stuurprogramma voor je videokaart.", "check.vulkan_no_device": "Vulkan vindt geen videokaart. Installeer het nieuwste stuurprogramma voor je videokaart.", diff --git a/installer/text/pt-BR.json b/installer/text/pt-BR.json index f94e7c9a..5711ca4f 100644 --- a/installer/text/pt-BR.json +++ b/installer/text/pt-BR.json @@ -57,6 +57,10 @@ "check.toolchain_broken": "O compilador incluído não funciona: {detail}", "check.glibc_old": "A biblioteca C deste sistema é a glibc {version}; o compilador da instalação precisa da {need} ou mais nova (Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 e mais novos têm). Atualizar o sistema resolve.", "check.host_probe_failed": "A verificação do computador não rodou (código de saída {code}).", + "check.host_blocked": "O Windows bloqueou um programa que o instalador compilou neste PC ({path}): {detail}. O Controle Inteligente de Aplicativos, uma política de App Control ou um antivírus bloqueia programas sem assinatura; o próprio jogo é compilado do mesmo jeito neste PC e também seria bloqueado. Libere a pasta do instalador no seu antivírus ou desative o Controle Inteligente de Aplicativos na Segurança do Windows (Controle de aplicativos e do navegador) e rode o instalador de novo.", + "check.vulkan_crash": "O driver de vídeo travou quando o instalador pediu a lista de placas de vídeo (código de saída {code}), mesmo com as camadas Vulkan de outros programas desativadas. Instale o driver mais recente da sua placa de vídeo.", + "check.vulkan_layer_crash": "Uma camada Vulkan instalada por outro programa faz os programas Vulkan travarem neste PC (código de saída {code}), e o jogo travaria do mesmo jeito ao iniciar. A camada: {layers}. Atualize ou desinstale o programa ao qual ela pertence (o caminho mostra a pasta dele), ou desative a camada: defina para a sua conta de usuário a variável de ambiente VK_LOADER_LAYERS_DISABLE com o valor {disable}. Depois rode o instalador de novo.", + "check.vulkan_layers_crash": "Uma camada Vulkan instalada por outro programa faz os programas Vulkan travarem neste PC (código de saída {code}): com todas essas camadas desativadas a verificação passa, e com elas o jogo travaria do mesmo jeito ao iniciar. Desativar as camadas instaladas uma de cada vez não apontou qual é. Camadas instaladas: {layers}. Atualize ou desinstale os programas de overlay, gravação ou ajuste entre elas, ou desative todas essas camadas: defina para a sua conta de usuário a variável de ambiente VK_LOADER_LAYERS_DISABLE com o valor ~implicit~ (isso também desativa overlays como o da Steam em todos os jogos Vulkan). Depois rode o instalador de novo.", "check.cpu_too_old": "Este processador não tem x86-64-v2 (SSE4.2, POPCNT e CMPXCHG16B), o nível mais antigo para o qual o jogo é compilado. Intel Nehalem (2008) ou AMD Bulldozer (2011) e mais novos têm.", "check.vulkan_missing": "Nenhum driver Vulkan está instalado. Instale o driver mais recente da sua placa de vídeo.", "check.vulkan_no_device": "O Vulkan não encontra nenhuma placa de vídeo. Instale o driver mais recente da sua placa de vídeo.", diff --git a/installer/text/ru.json b/installer/text/ru.json index 7d36c372..3ee8d8a1 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -57,6 +57,10 @@ "check.toolchain_broken": "Встроенный компилятор не работает: {detail}", "check.glibc_old": "Библиотека C этой системы — glibc {version}; компилятору установщика нужна {need} или новее (она есть в Ubuntu 22.04, Debian 12, Fedora 35, SteamOS 3 и новее). Обновление системы это исправит.", "check.host_probe_failed": "Проверка компьютера не выполнилась (код выхода {code}).", + "check.host_blocked": "Windows заблокировала программу, которую установщик собрал на этом компьютере ({path}): {detail}. Интеллектуальное управление приложениями (Smart App Control), политика App Control или антивирус блокируют неподписанные программы; сама игра собирается на этом компьютере так же и тоже будет заблокирована. Разрешите папку установщика в антивирусе или отключите интеллектуальное управление приложениями в «Безопасности Windows» («Управление приложениями/браузером») и запустите установщик снова.", + "check.vulkan_crash": "Видеодрайвер аварийно завершился, когда установщик запросил список видеокарт (код выхода {code}), в том числе с отключёнными слоями Vulkan других программ. Установите свежий драйвер видеокарты.", + "check.vulkan_layer_crash": "Слой Vulkan, установленный другой программой, обрушивает Vulkan-программы на этом компьютере (код выхода {code}), и игра так же упадёт при запуске. Слой: {layers}. Обновите или удалите программу, которой он принадлежит (путь показывает её папку), или отключите слой: задайте для своей учётной записи переменную среды VK_LOADER_LAYERS_DISABLE со значением {disable}. Затем запустите установщик снова.", + "check.vulkan_layers_crash": "Слой Vulkan, установленный другой программой, обрушивает Vulkan-программы на этом компьютере (код выхода {code}): со всеми такими слоями отключёнными проверка проходит, а с ними игра так же упадёт при запуске. Отключение установленных слоёв по одному не выявило виновника. Установленные слои: {layers}. Обновите или удалите программы оверлея, записи или настройки среди них, или отключите все такие слои: задайте для своей учётной записи переменную среды VK_LOADER_LAYERS_DISABLE со значением ~implicit~ (это также отключит оверлеи вроде оверлея Steam во всех играх на Vulkan). Затем запустите установщик снова.", "check.cpu_too_old": "Этому процессору не хватает x86-64-v2 (SSE4.2, POPCNT и CMPXCHG16B) — минимального уровня, под который собрана игра. Он есть у Intel Nehalem (2008) и AMD Bulldozer (2011) и новее.", "check.vulkan_missing": "Драйвер Vulkan не установлен. Установите свежий драйвер видеокарты.", "check.vulkan_no_device": "Vulkan не находит видеокарту. Установите свежий драйвер видеокарты.", diff --git a/installer/text/zh-Hans.json b/installer/text/zh-Hans.json index 5833c798..dfe6bbab 100644 --- a/installer/text/zh-Hans.json +++ b/installer/text/zh-Hans.json @@ -57,6 +57,10 @@ "check.toolchain_broken": "自带的编译器无法工作:{detail}", "check.glibc_old": "此系统的 C 库为 glibc {version};安装程序的编译器需要 {need} 或更新版本(Ubuntu 22.04、Debian 12、Fedora 35、SteamOS 3 及更新版本都满足)。更新系统即可解决。", "check.host_probe_failed": "电脑检查未能运行(退出代码 {code})。", + "check.host_blocked": "Windows 阻止了安装程序在这台电脑上编译的程序({path}):{detail}。智能应用控制、App Control 策略或杀毒软件会阻止未签名的程序;游戏本身也以同样方式在这台电脑上编译,同样会被阻止。请在杀毒软件中允许安装程序所在的文件夹,或在 Windows 安全中心(应用和浏览器控制)中关闭智能应用控制,然后重新运行安装程序。", + "check.vulkan_crash": "安装程序向显卡驱动查询显卡时,驱动崩溃了(退出代码 {code}),关闭其他程序的 Vulkan 层后依然如此。请为你的显卡安装最新的驱动程序。", + "check.vulkan_layer_crash": "另一个程序安装的 Vulkan 层会让这台电脑上的 Vulkan 程序崩溃(退出代码 {code}),游戏启动时也会同样崩溃。该层:{layers}。请更新或卸载它所属的程序(路径显示了它的文件夹),或者关闭该层:为你的用户帐户设置环境变量 VK_LOADER_LAYERS_DISABLE,值为 {disable}。然后重新运行安装程序。", + "check.vulkan_layers_crash": "另一个程序安装的 Vulkan 层会让这台电脑上的 Vulkan 程序崩溃(退出代码 {code}):关闭所有此类层后检查通过,开着它们时游戏启动也会同样崩溃。逐个关闭已安装的层未能找出是哪一个。已安装的层:{layers}。请更新或卸载其中的叠加层、录制或调校程序,或者关闭所有此类层:为你的用户帐户设置环境变量 VK_LOADER_LAYERS_DISABLE,值为 ~implicit~(这也会在所有 Vulkan 游戏中关闭 Steam 等叠加层)。然后重新运行安装程序。", "check.cpu_too_old": "此处理器不支持 x86-64-v2(SSE4.2、POPCNT 和 CMPXCHG16B),这是游戏所需的最低指令集。Intel Nehalem(2008 年)或 AMD Bulldozer(2011 年)及更新的处理器都支持。", "check.vulkan_missing": "未安装 Vulkan 驱动。请为你的显卡安装最新的驱动程序。", "check.vulkan_no_device": "Vulkan 找不到显卡。请为你的显卡安装最新的驱动程序。", diff --git a/recomp/patches-v121.txt b/recomp/patches-v121.txt index ef68255e..a28a7592 100644 --- a/recomp/patches-v121.txt +++ b/recomp/patches-v121.txt @@ -1209,3 +1209,15 @@ site ability main 1622bf4 b4000155 aa0903f5 b4000155 # cbz x21 -> mov x21, x9; # the game with the set off in two runs of two, a pause of 1 s in none of one. set audiodrain TOTK_AUDIO_DRAIN_FIX 1 site audiodrain main 883780 17fffee6 17fffeda # b 0x883318 -> b 0x8832e8 + +# Thunderstorm lightning (issue #1287): as in patches-v143.txt, the same update (main+0xab849c, called from +# main+0xab7cf4) with the same chances and timers. The sites are the loads of 0.013333 (distant bolt) and of 0.01 (state +# 1, both draws through s9, which the prologue saves; state 5). The time object is loaded as the game's own trampoline +# check does (main+0xbda4bc): its global through the GOT slot main+0x462e038, then +0xc8. After each site x10, s2 and s3 +# are written, or a call comes, before any read. +set lightning TOTK_LIGHTNING_FIX 1 +site lightning main ab8d50 bd43fd01 bd43fd01 d001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0x3fc] (0.013333) +site lightning main ab9014 bd46f109 bd46f109 b001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220929 # ldr s9, [x8, #0x6f0] (0.01) +site lightning main ab8f90 bd46f101 bd46f101 d001dbaa f9401d4a f940014a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0x6f0] (0.01) +# each: the game's load; adrp x10, main+0x462e000; ldr x10, [x10, #0x38]; ldr x10, [x10]; ldr x10, [x10, #0xc8]; +# ldr s2, [x10, #0x38] (ratio); fmov s3, #1.0; fminnm s2, s2, s3; fmul (chance * ratio) diff --git a/recomp/patches-v143.txt b/recomp/patches-v143.txt index 9c3603dc..f1a417eb 100644 --- a/recomp/patches-v143.txt +++ b/recomp/patches-v143.txt @@ -1251,3 +1251,31 @@ site shutter main 25e55d0 bc605900 bc605900 f9402ea9 927ef529 39400129 1e230123 # keep their numbers. set freecam TOTK_FREECAM_PATCH 0 site freecam main 6286d4 f9400e68 94d2de1f # ldr x8, [x19, #0x18] + +# Thunderstorm lightning (issue #1287). While the current weather type has IsThunder (main+0x62a40c), the world +# manager's lightning update (main+0x62aac4, called once per frame from main+0x62a310) runs a state machine whose times +# advance by the world's frame step: near strikes for 150 to 450 units (state 1), a phase main+0x21c34d0 ends (2), 30 +# and 240 units without (3, 4), then 1 again; 5 takes over from 1 when main+0x21d2930 returns false and leads back to 0. +# On top of it the update draws, each update, a random number in [0, 1) for each of three fixed chances: 0.013333 in +# every state but 0 for a distant bolt (bit 0 of its +8 flags, which main+0x58b4d8 hands to the environment, where +# main+0x69fb98 starts the effect Far_Lightning 2000 m from the camera along its view, picked by main+0x21c3940), 0.01 +# in state 1 to pick a near strike (a point 90 m ahead of the camera, main+0x21c4c74, struck by main+0x21c3a6c once 90 +# units of frame step pass without another pick) and 0.01 in states 1 and 5 for bit 3, which sets the environment +# input's flag +0x2e4 as a near strike does (main+0x58b4fc). Counted in one storm with a local build that logs each +# draw that succeeds: with the set off 22 distant bolts a minute at 30 fps, 52 at 60 and 94 to 96 at 120, each one a +# Far_Lightning effect, and bit 3 19, 34 and 64 to 80 times a minute of state 1. Near strikes stayed at 14 to 18 in +# 205 s at every rate: state 1 lets its last pick strike in state 2, where nothing is drawn, and state 2 ends with a +# strike of its own, so the picks that start the countdown again at high frame rates change little. Each site +# multiplies the chance it loads by the frame ratio, time object +0x38 ([[main+0x3ad27c8] + 0xc8], as the sets bounce +# and shutter read it), at most 1: above 30 fps the rates per second of 30 fps (counted: 26, 27 and 20 to 24 distant +# bolts a minute at 30, 60 and 120 fps, bit 3 12 to 17 times a minute of state 1), and at 30 fps and below the game's +# own chances. After each site x10 and the two scratch registers (s3 and s4 at the first, +# where s2 is the chance; s2 and s3 at the others) are written, or a call comes, before any read; at the second the +# chance is s9, which the prologue saves and both draws of state 1 compare with. Its own switch, lightning_fix +# (TOTK_LIGHTNING_FIX); 0 runs the game's loads. +set lightning TOTK_LIGHTNING_FIX 1 +site lightning main 62b1fc bd472d02 bd472d02 f001a52a f943e54a f940654a bd403943 1e2e1004 1e247863 1e230842 # ldr s2, [x8, #0x72c] (0.013333) +site lightning main 62b3d8 bd4ccd09 bd4ccd09 f001a52a f943e54a f940654a bd403942 1e2e1003 1e237842 1e220929 # ldr s9, [x8, #0xccc] (0.01) +site lightning main 62b51c bd4ccd01 bd4ccd01 f001a52a f943e54a f940654a bd403942 1e2e1003 1e237842 1e220821 # ldr s1, [x8, #0xccc] (0.01) +# each: the game's load; adrp x10, main+0x3ad2000; ldr x10, [x10, #0x7c8]; ldr x10, [x10, #0xc8]; +# ldr s3 (s2), [x10, #0x38] (ratio); fmov s4 (s3), #1.0; fminnm (ratio, 1.0); fmul (chance * ratio) diff --git a/recomp/patches.py b/recomp/patches.py index d58353bd..ad738a68 100644 --- a/recomp/patches.py +++ b/recomp/patches.py @@ -1,7 +1,8 @@ """Code patch table for the generator: guest instructions replaced in the lifted C, switchable at run time. Lifted code cannot be byte-patched when the game runs, so a patch is applied when the C is generated. A patch file -(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace: +(gen.py --patches) has these kinds of lines; `#` starts a comment, fields are separated by whitespace. A plugin image +path may be a JSON double-quoted string to preserve spaces, `#` and escaped characters: set [ordered] a patch set: a run-time switch =0/1, when it is unset site
[ ...] @@ -78,6 +79,7 @@ entry the runtime watches: their lifted C starts with FN_ENTER (runtime/cpu.h), branch to fnprof_hit while the runtime sets it. A table with hook lines puts FN_ENTER into these functions only; a table without any keeps it in every function, as does gen.py --fn-enter-all (a whole-game function-entry profile). """ +import json from pathlib import Path PAGE = 0x1000 @@ -188,10 +190,23 @@ def load(path, mods): sets, index, sites, spins, hooks, ordered, plugins = [], {}, {}, {}, {}, set(), {} bases = {n: (b, s) for n, b, s in mods} for no, raw in enumerate(Path(path).read_text(encoding='utf-8').splitlines(), 1): - f = raw.split('#', 1)[0].split() + where = f'{path}:{no}' + prefix = raw.split(None, 4) + if len(prefix) == 5 and prefix[0] == 'plugin' and prefix[4].startswith('"'): + try: + image, end = json.JSONDecoder().raw_decode(prefix[4]) + except json.JSONDecodeError as e: + raise PatchError(f'{where}: invalid quoted plugin image: {e.msg}') from None + if not image: + raise PatchError(f'{where}: empty quoted plugin image') + tail = prefix[4][end:].strip() + if tail and not tail.startswith('#'): + raise PatchError(f'{where}: unexpected text after quoted plugin image') + f = prefix[:4] + [image] + else: + f = raw.split('#', 1)[0].split() if not f: continue - where = f'{path}:{no}' if f[0] == 'set' and (len(f) == 4 or len(f) == 5 and f[4] == 'ordered'): if f[1] in index: raise PatchError(f'{where}: set {f[1]} defined twice') diff --git a/runtime/cfg.c b/runtime/cfg.c index 4345978a..b3dcbb2b 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -53,7 +53,7 @@ static const char *const known[] = { "GPL", "GPL_DRAW_BUILD", "GPU", "GPU_INDEX", "GPU_NAME", "GRASS_RANGE", "GYRO_AUTO_BIAS", "GYRO_BIAS_PAD", "GYRO_BIAS_X", "GYRO_BIAS_Y", "GYRO_BIAS_Z", "GYRO_CALIBRATION", "HDR", "HDR_GAME_NITS", "HDR_HUE", "HDR_PEAK_NITS", "HDR_UI_NITS", "HIGHFPS_FIX", "HUD_WIDTH", "INPUT", "INPUT_RECORD", "INPUT_SCRIPT", "KSPIN_US", "LANG", "LIB_PREBUILD", - "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG", + "LIB_PREBUILD_KEEP", "LIB_PREBUILD_THREADS", "LIGHTNING_FIX", "LOCALE", "LOD_GUARD", "LOD_STEADY", "LSTICK_DEADZONE", "MAP_CLICK", "MEMORY", "MEMX", "MENU_LANG", "MENU_TEST", "MENU_FONT_FONTCONFIG", "MEM_RESERVE_MIB", "MENU_CURSOR", "MENU_CURSOR_LOG", "MENU_TEST_DIR", "MENU_TEST_SET", "MINIMAL_LAYOUT", "MIRROR_GAP", "MODS_DIR", "MODS_DISABLED", "MODS_NO_CODE", "MODS_ORDER", "MODS_REBUILD", "MODS_WITHOUT_CODE", "MOTION", "MOUSE_AIM_SCALE", "MOUSE_MODE", "MOUSE_DIRECT_PATCH", "MOUSE_SENS", "MOVIE_ASPECT", "MOVIE_HOST", "MOVIE_PACE", "MVOBJ_ALL", "MVOBJ_BANKS", "MVOBJ_EQUAL", "MVOBJ_EXACT", "MVOBJ_EXEC", "MVOBJ_NOC4", "MVOBJ_ONLY", "MVOBJ_TIMES", "MVPREV_CHECK", "MVPREV_GROW", "MVPREV_SKIP", "MVPREV_TRUST", "MV_CHECK", "MV_SURVEY", @@ -77,6 +77,7 @@ static const struct { const char *key, *section; } sections[] = { {"FPS_LIMIT", "frame rate"}, {"FPS60", "frame rate"}, {"FRAME_QUEUE", "frame rate"}, {"FRAME_GEN", "frame rate"}, {"REALTIME", "frame rate"}, {"CLOTH_REALTIME", "frame rate"}, {"HIGHFPS_FIX", "frame rate"}, {"CLIMB_FIX", "frame rate"}, {"AUDIO_DRAIN_FIX", "frame rate"}, {"SHUTTER_FIX", "frame rate"}, + {"LIGHTNING_FIX", "frame rate"}, {"FULLSCREEN", "display"}, {"WINDOW_SIZE", "display"}, {"PERF_OVERLAY", "display"}, {"VK_PRESENT", "display"}, {"GPU_INDEX", "display"}, {"OUTPUT_RES", "display"}, {"RENDER_SCALE", "display"}, {"UPSCALER", "display"}, {"HUD_WIDTH", "display"}, @@ -168,7 +169,7 @@ static const CfgMeta metas[] = { {"MODS_REBUILD", "auto", "auto|off", RESTART}, {"MODS_WITHOUT_CODE", "0", "0|1", RESTART}, // 1: a mod is used without the code module it cannot run (mods.c) {"HIGHFPS_FIX", "1", "0|1", RESTART}, {"CLIMB_FIX", "1", "0|1", RESTART}, {"AUDIO_DRAIN_FIX", "1", "0|1", RESTART}, - {"SHUTTER_FIX", "1", "0|1", RESTART}, + {"SHUTTER_FIX", "1", "0|1", RESTART}, {"LIGHTNING_FIX", "1", "0|1", RESTART}, {"LANG", "", "ja|en-US|fr|de|it|es|zh-CN|ko|nl|pt|ru|zh-TW|en-GB|fr-CA|es-419|zh-Hans|zh-Hant|pt-BR", RESTART}, {"OPERATION_MODE", "docked", "docked|handheld", RESTART}, {"ASSUME_FOCUS", "1", "0|1", LIVE}, // read on every focus change (ov_system.c) diff --git a/tests/check_isa_test.py b/tests/check_isa_test.py new file mode 100644 index 00000000..21e6d529 --- /dev/null +++ b/tests/check_isa_test.py @@ -0,0 +1,72 @@ +"""tools/check_isa.py finds instructions above x86-64-v2 in objects and in linked images. + + python tests/check_isa_test.py + +The disassembly below is llvm-objdump -d --no-show-raw-insn output for one AVX2 function, once from an object (short +indented addresses) and once from a linked .exe (9+ hex digits at the start of the line). Standard library only. +""" + +import subprocess +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +import check_isa # noqa: E402 + +OBJECT = ''' +avx.o:\tfile format coff-x86-64 + +Disassembly of section .text: + +0000000000000000 : + 0: \tvmovdqu\t(%rcx), %ymm0 + 4: \tvpaddd\t%ymm0, %ymm1, %ymm0 + 8: \tvzeroupper + b: \tretq +''' + +LINKED = ''' +avx.exe:\tfile format coff-x86-64 + +Disassembly of section .text: + +00000001400014b0 : +1400014b0: \tvmovdqu\t(%rcx), %ymm0 +1400014b4: \tvpshufd\t$0x55, %ymm0, %ymm1 # ymm1 = ymm0[1,1,1,1,5,5,5,5] +1400014b9: \tvpaddd\t%ymm0, %ymm1, %ymm0 +1400014bd: \tvzeroupper +1400014c0: \tretq + +00000001400014d0
: +1400014d0: \tsubq\t$0x28, %rsp +1400014d4: \tpopcntl\t%eax, %eax +1400014d8: \taddq\t$0x28, %rsp +1400014dc: \tretq +''' + + +def scan(text): + done = subprocess.CompletedProcess([], 0, text, '') + with mock.patch.object(check_isa.subprocess, 'run', return_value=done): + return check_isa.scan_one(Path('x'), 'llvm-objdump') + + +class ScanTest(unittest.TestCase): + def test_an_object_is_scanned(self): + hits = scan(OBJECT) + self.assertEqual(set(hits), {('avx.o', 'sum8')}) + self.assertEqual(hits[('avx.o', 'sum8')]['vpaddd'], 1) + + def test_a_linked_image_is_scanned(self): + hits = scan(LINKED) + self.assertEqual(set(hits), {('avx.exe', 'sum8')}) # main's popcnt is x86-64-v2 + self.assertEqual(sum(hits[('avx.exe', 'sum8')].values()), 4) + + def test_function_headers_and_blank_lines_are_not_instructions(self): + self.assertEqual(scan('\nDisassembly of section .text:\n\n00000001400014b0 :\n'), {}) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/compile_budget_test.py b/tests/compile_budget_test.py new file mode 100644 index 00000000..932813cd --- /dev/null +++ b/tests/compile_budget_test.py @@ -0,0 +1,37 @@ +"""tools/build_game.py compile_budget: the compile jobs fit the memory that is free, not only the RAM. + + python tests/compile_budget_test.py +""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools')) +from build_game import GiB, JOB_MEM, MEM_BUDGET, compile_budget # noqa: E402 + + +def jobs(budget, cpus=16): + return max(1, min(cpus, budget // JOB_MEM)) # as build_game.main + + +class CompileBudgetTest(unittest.TestCase): + def test_free_memory_limits_a_pc_whose_ram_other_programs_hold(self): + self.assertEqual(jobs(compile_budget(8 * GiB, None)), 8) # the RAM alone: 6.4 GiB, 8 jobs + self.assertEqual(jobs(compile_budget(8 * GiB, 3 * GiB)), 3) # 3 GiB free: 2.4 GiB, 3 jobs + self.assertEqual(compile_budget(8 * GiB, 3 * GiB), int(3 * GiB * 0.8)) + + def test_ram_still_limits_when_more_is_reported_free(self): + self.assertEqual(compile_budget(4 * GiB, 64 * GiB), int(4 * GiB * 0.8)) + + def test_unknown_free_memory_keeps_the_old_budget(self): + self.assertEqual(compile_budget(4 * GiB, None), int(4 * GiB * 0.8)) + self.assertEqual(compile_budget(128 * GiB, None), MEM_BUDGET) + + def test_no_free_memory_still_runs_one_job(self): + self.assertEqual(compile_budget(4 * GiB, 0), 0) + self.assertEqual(compile_budget(4 * GiB, -1), 0) + self.assertEqual(jobs(compile_budget(4 * GiB, 0)), 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/exefs_plugins_test.py b/tests/exefs_plugins_test.py index 4de41eff..4f5a39ce 100644 --- a/tests/exefs_plugins_test.py +++ b/tests/exefs_plugins_test.py @@ -10,6 +10,7 @@ Run with .venv (lz4 and numpy, as recomp/): python tests/exefs_plugins_test.py import hashlib import json import struct +import subprocess import sys import tempfile import unittest @@ -428,6 +429,47 @@ class Lines(unittest.TestCase): rec['modules'][2]['image'] = 'plugin0.img' return xp.plugin_lines(rec, xp.hooks_of(hooks, 'plugin0'), 'mod_x', d, 'plugin0') + def test_image_path_roundtrips_through_the_patch_table(self): + rec = record() + mods = [(m['name'], m['base'], m['size']) for m in rec['modules']] + with tempfile.TemporaryDirectory() as d: + for folder in ('plain', 'with spaces', 'with#hash', 'caf\u00e9 #1'): + with self.subTest(folder=folder): + dest = Path(d) / folder + dest.mkdir() + image = dest / 'plugin0.img' + image.write_bytes(rec['images']['plugin0']) + rec['modules'][2]['image'] = image.name + lines = xp.plugin_lines(rec, [], 'mod_x', dest, 'plugin0') + patch = dest / 'patches.txt' + patch.write_text('set mod_x TOTK_MODPATCH_X 0 ordered\n' + '\n'.join(lines), encoding='utf-8') + actual = patches.load(patch, mods).plugins['plugin0']['image'] + self.assertEqual(actual, image.resolve().as_posix()) + self.assertEqual(Path(actual).read_bytes(), rec['images']['plugin0']) + + def test_quoted_image_and_legacy_unquoted_paths(self): + mods = [('main', MAIN, 0x200000), ('plugin0', PLUGIN, 0x14000)] + with tempfile.TemporaryDirectory() as d: + patch = Path(d) / 'patches.txt' + for image, field in (('C:/folder #1/plugin.img', '"C:/folder #1/plugin.img" # comment'), + ('C:/plain/plugin.img', 'C:/plain/plugin.img # comment'), + (r'C:\with space\plugin.img', json.dumps(r'C:\with space\plugin.img')), + (r'C:\plain\plugin.img', r'C:\plain\plugin.img')): + with self.subTest(field=field): + patch.write_text(f'set x ENV 0\nplugin x plugin0 {"0" * 64} {field}\n') + self.assertEqual(patches.load(patch, mods).plugins['plugin0']['image'], image) + + def test_malformed_quoted_image_names_the_patch_line(self): + mods = [('main', MAIN, 0x200000), ('plugin0', PLUGIN, 0x14000)] + with tempfile.TemporaryDirectory() as d: + patch = Path(d) / 'patches.txt' + for field in ('"unfinished', '""', '"image.img" extra', '"image.img" "#not a comment"'): + with self.subTest(field=field): + patch.write_text(f'set x ENV 0\nplugin x plugin0 {"0" * 64} {field}\n') + with self.assertRaises(patches.PatchError) as error: + patches.load(patch, mods) + self.assertIn(f'{patch}:2:', str(error.exception)) + def test_inline(self): out = self.lines(record(original=0xAA0003F3)) self.assertIn(f'site mod_x main {SITE_OFF:x} aa0003f3 @call:plugin0+{STUB_OFF:x} aa0003f3', out) @@ -584,13 +626,34 @@ class Generator(unittest.TestCase): n = Nso(str(self.plugin_file)) self.sha = hashlib.sha256(bytes(img[n.text[0]:n.text[0] + n.text[1]])).hexdigest() - def table(self, site_line, extra=()): + def table(self, site_line, extra=(), image=None): + image = image or self.d / 'plugin0.img' text = '\n'.join(['set mod_x TOTK_MODPATCH_X 0 ordered', - f'plugin mod_x plugin0 {self.sha} {(self.d / "plugin0.img").as_posix()}', + f'plugin mod_x plugin0 {self.sha} {json.dumps(image.as_posix())}', f'expect mod_x main {FN:x} aa0003f3 14000000', site_line, *extra]) + '\n' (self.d / 'p.txt').write_text(text) return patches.load(self.d / 'p.txt', self.mods) + def test_generator_cli_reads_image_in_a_folder_with_spaces_and_hash(self): + # The direct-emitter fixture needs a discoverable caller for a full CLI lift. + main = self.d / 'exefs' / 'main' + raw = bytearray(main.read_bytes()) + struct.pack_into('', {'delta': -120}), ('', {})): + with self.subTest(event=event): + canvas.yview_moveto(0) + if event == '' and not sys.platform.startswith('linux'): + self.app.scroll_areas['form'].wheel(SimpleNamespace(widget=canvas, num=5, delta=0)) + else: + canvas.event_generate(event, **params) + self.root.update() + self.assertGreater(canvas.yview()[0], 0) + self.assert_start_visible() + + def test_content_that_fits_needs_no_scrollbar(self): + with unittest.mock.patch.object(self.root, 'winfo_screenheight', return_value=2000): + self.app.fit(shrink=True) + self.root.update() + area = self.app.scroll_areas['form'] + self.assertFalse(area.scrollbar.winfo_manager()) + self.assertEqual(area.canvas.yview(), (0.0, 1.0)) + + def test_progress_and_finish_actions_stay_visible_with_long_content(self): + self.app.phase_label.configure(text='Long progress detail\n' * 40) + self.app.show('run') + self.root.update() + self.assertLessEqual(self.root.winfo_height(), 700) + self.assertLessEqual(self.app.cancel_button.winfo_rooty() + self.app.cancel_button.winfo_height(), + self.root.winfo_rooty() + self.root.winfo_height()) + self.app.finish_text.configure(text='Long finish detail\n' * 40) + self.app.show('finish') + self.root.update() + close = next(w for w, _, id, _ in self.app.bound if id == 'ui.close') + self.assertLessEqual(self.root.winfo_height(), 700) + self.assertLessEqual(close.winfo_rooty() + close.winfo_height(), + self.root.winfo_rooty() + self.root.winfo_height()) + + class FakeVar: def __init__(self, value=''): self.value = value diff --git a/tests/installer_test.py b/tests/installer_test.py index 92de8b4d..5769b97c 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -6,7 +6,9 @@ Run: python tests/installer_test.py import http.client import io import json +import os import re +import subprocess import sys import tempfile import unittest @@ -199,6 +201,58 @@ class RunnerTest(unittest.TestCase): state.load(self.bed.dest) self.assertEqual(e.exception.id, 'state.newer_format') + def test_invalid_state_format_is_reported_as_unreadable(self): + self.bed.dest.mkdir() + path = self.bed.dest / state.NAME + for value in ('1', None, [], {}, True, 1.5, -1): + with self.subTest(value=value): + data = state.empty('r0') | {'format': value} + path.write_text(json.dumps(data)) + before = path.read_bytes() + with self.assertRaises(state.StateError) as error: + state.load(self.bed.dest) + self.assertEqual(error.exception.id, 'state.unreadable') + self.assertEqual(path.read_bytes(), before) + + def test_invalid_state_records_are_reported_as_unreadable(self): + self.bed.dest.mkdir() + for field in ('inputs', 'steps'): + for value in (None, [], 'bad', {'entry': None}, {'entry': 'bad'}): + with self.subTest(field=field, value=value): + path = self.bed.dest / state.NAME + path.write_text(json.dumps(state.empty('r0') | {field: value})) + with self.assertRaises(state.StateError) as error: + state.load(self.bed.dest) + self.assertEqual(error.exception.id, 'state.unreadable') + + def test_invalid_state_text_fields_are_reported_as_unreadable(self): + self.bed.dest.mkdir() + for field in ('release', 'lang', 'version'): + for value in (None, [], {}, 1): + with self.subTest(field=field, value=value): + (self.bed.dest / state.NAME).write_text(json.dumps(state.empty('r0') | {field: value})) + with self.assertRaises(state.StateError) as error: + state.load(self.bed.dest) + self.assertEqual(error.exception.id, 'state.unreadable') + + def test_legacy_state_without_inputs_can_be_resumed(self): + self.bed.run() + path = self.bed.dest / state.NAME + data = json.loads(path.read_text()) + del data['format'], data['inputs'] + path.write_text(json.dumps(data)) + self.assertEqual(state.load(self.bed.dest)['inputs'], {}) + result = self.bed.run() + self.assertEqual((result.result, result.ran), ('ok', ['check', 'cleanup'])) + + def test_newer_state_format_is_not_validated_as_the_current_schema(self): + self.bed.dest.mkdir() + data = {'format': state.FORMAT + 1, 'steps': {}, 'inputs': [], 'lang': {}} + (self.bed.dest / state.NAME).write_text(json.dumps(data)) + with self.assertRaises(state.StateError) as error: + state.load(self.bed.dest) + self.assertEqual(error.exception.id, 'state.newer_format') + class ReleaseFilesTest(unittest.TestCase): def test_release_ships_every_tool_the_steps_run(self): @@ -544,6 +598,21 @@ class IniTest(unittest.TestCase): self.assertEqual(out, '[display]\nvk_present = fifo\n[language]\n lang = de\nfps60 = 0\n') self.assertEqual(ini.get_language(out), 'de') + def test_the_last_active_language_is_rewritten(self): + text = 'lang = ru\n[language]\n# lang = fr\n TOTK_LANG = ja\nfps_limit = 60\n' + out = ini.set_language(text, 'de') + self.assertEqual(out, 'lang = ru\n[language]\n# lang = fr\n lang = de\nfps_limit = 60\n') + self.assertEqual(screens.ini_value(out, 'lang'), 'de') + self.assertEqual(ini.get_language(out), 'de') + + def test_language_reader_uses_runtime_order_quotes_and_empty_values(self): + for text, expected in [('lang = ru\nTOTK_LANG = "ja"\n', 'ja'), + ('lang = ru\nlang = \nTOTK_LANG = ""\n', 'ru'), + ('lang = \nTOTK_LANG = ""\n', None), + ('lang = " "\n', ' ')]: + with self.subTest(text=text): + self.assertEqual(ini.get_language(text), expected) + def test_missing_section_is_added(self): self.assertEqual(ini.set_language('fps60 = 0\n', 'fr'), 'fps60 = 0\n\n[language]\nlang = fr\n') self.assertEqual(ini.set_language('[language]\nlocale = de-DE\n', 'fr'), @@ -573,6 +642,107 @@ class IniTest(unittest.TestCase): self.assertEqual(ini.get_language(text), 'ja') +class ExtractMergeTest(unittest.TestCase): + """The real merge wrapper with synthetic inputs and hactool output; no game files or keys.""" + + LEVELS = '\n'.join(f' Level {i} (GOOD):' for i in range(6)) + LOG = ('NCA:\nFixed-Key Signature (FAIL): omitted\nNPDM Signature (GOOD): omitted\n' + 'NPDM:\n ACID:\n Signature Key (GOOD): 0\n Signature (FAIL): omitted\n' + + LEVELS + '\nDone!\n') + IMAGE = b'synthetic merged image' + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.output, self.logs = self.root / 'romfs', self.root / 'logs' + self.logs.mkdir() + self.base, self.update, self.keys = (self.root / name for name in ('base.nsp', 'update.nsp', 'prod.keys')) + self.log, self.code, self.base_log = self.LOG, 0, self.LEVELS + self.phases = [] + header = bytearray(0xc00) + header[0x404] = 4 # one BKTR section + inputs = [(source, {'size': 1, 'nca_offset': 0}, bytes(header)) for source in (self.base, self.update)] + self.enterContext(mock.patch.object(steps.extract, 'program_ncas', return_value=({}, inputs))) + self.enterContext(mock.patch.object(steps.extract, 'copy_range')) + self.enterContext(mock.patch.object(steps.extract, 'hactool_prod_keys')) + self.enterContext(mock.patch.object(steps.extract.shutil, 'disk_usage', + return_value=SimpleNamespace(free=100 * steps.GiB))) + self.enterContext(mock.patch.object(steps.extract, 'run_hactool', side_effect=self.hactool)) + self.index = self.enterContext(mock.patch.object(steps.extract, 'index_romfs', return_value=[])) + + def hactool(self, command, environment): + if '-x' not in command: + return 0, self.base_log # the extra verification that identifies a damaged input + image = Path(next(arg.split('=', 1)[1] for arg in command if arg.startswith('--section0='))) + image.write_bytes(self.IMAGE) + return self.code, self.log + + def merge(self): + steps.extract.merge_update_romfs(self.base, self.update, self.keys, self.root / 'hactool', self.output, + self.logs, phase=self.phases.append) + + def test_acid_signature_warning_keeps_a_verified_merge(self): + self.merge() + image = self.output / 'romfs.bin' + self.assertEqual(image.read_bytes(), self.IMAGE) + report = json.loads((self.output / 'index.json').read_text()) + self.assertEqual((report['status'], report['romfs_size'], report['romfs_sha256']), + ('pass', len(self.IMAGE), steps.extract.sha256(image))) + self.assertEqual(self.phases, ['copy', 'merge', 'index']) + self.assertEqual((self.logs / f'merge_romfs-{self.root.name}.log').read_text(), self.LOG) + + def test_existing_npdm_signature_warning_is_still_allowed(self): + self.log = self.LOG.replace('NPDM Signature (GOOD)', 'NPDM Signature (FAIL)') + self.merge() + self.assertTrue((self.output / 'index.json').is_file()) + + def test_data_hash_failures_still_identify_the_damaged_update(self): + for label in [*(f'Level {i}' for i in range(6)), 'Superblock Hash', 'Hash Table']: + with self.subTest(label=label): + self.log = self.LOG + f' {label} (FAIL): omitted\n' + with self.assertRaises(steps.extract.DamagedFile) as error: + self.merge() + self.assertEqual(error.exception.path, self.update) + self.assertIn('diagnose', self.phases) + self.index.assert_not_called() + self.assertFalse(self.output.exists()) + + def test_base_hash_failure_is_still_identified(self): + self.log = self.LOG.replace('Level 5 (GOOD)', 'Level 5 (FAIL)') + self.base_log = self.LEVELS.replace('Level 5 (GOOD)', 'Level 5 (FAIL)') + with self.assertRaises(steps.extract.DamagedFile) as error: + self.merge() + self.assertEqual(error.exception.path, self.base) + self.index.assert_not_called() + + def test_every_ivfc_level_is_still_required(self): + for level in range(6): + with self.subTest(level=level): + self.log = self.LOG.replace(f' Level {level} (GOOD):\n', '') + with self.assertRaisesRegex(ValueError, 'did not verify all six IVFC levels'): + self.merge() + self.index.assert_not_called() + self.assertFalse(self.output.exists()) + + def test_other_hactool_errors_are_still_rejected(self): + for message in ('Signature Key (FAIL): 0', 'Fixed-Key Index (FAIL): 0', 'Other Signature (FAIL): omitted', + 'Section (INVALID)', 'Failed to read section', 'Error: cannot save section'): + with self.subTest(message=message): + self.log = self.LOG + message + '\n' + with self.assertRaisesRegex(ValueError, 'hactool merge failed'): + self.merge() + self.index.assert_not_called() + self.assertFalse(self.output.exists()) + + def test_nonzero_exit_is_still_rejected(self): + self.code = 1 + with self.assertRaisesRegex(ValueError, 'hactool merge failed'): + self.merge() + self.index.assert_not_called() + self.assertFalse(self.output.exists()) + + class CleanupTest(unittest.TestCase): """The real Cleanup step on a finished install whose romfs/ is intact, emptied or gone (#107).""" @@ -610,6 +780,16 @@ class CleanupTest(unittest.TestCase): def test_intact_romfs_passes(self): self.assertEqual(self.run_cleanup(), 'ok') + def test_selected_language_overrides_the_last_duplicate(self): + path = self.dest / 'totk.ini' + path.write_text('lang = ru\n[language]\nTOTK_LANG = ja\n[display]\nfps_limit = 60\n') + self.assertEqual(self.run_cleanup(), 'ok') + text = path.read_text() + self.assertEqual(screens.ini_value(text, 'lang'), self.ctx.lang) + self.assertEqual(ini.get_language(text), self.ctx.state['lang']) + self.assertIn('lang = ru\n', text) + self.assertIn('fps_limit = 60\n', text) + def test_keeps_build_and_writes_rebuild_command(self): for name in ('gen', 'build', 'check'): (self.ctx.temp / name).mkdir() @@ -906,6 +1086,35 @@ class ShapesTest(unittest.TestCase): (['2560x1080', '3440x1440', '1280x800', '1920x1280'], 'pc')) self.assertEqual(screens.wanted(self.dest / 'none', [(2560, 1440)]), ([], None)) + def test_layout_settings_keep_the_last_nonempty_value(self): + for empty in ('', ' ', '""'): + with self.subTest(empty=empty): + text = f'prompts = xbox\nTOTK_PROMPTS = "pc"\nprompts = {empty}\n' + self.assertEqual(screens.ini_value(text, 'prompts'), 'pc') + self.assertEqual(screens.prompts_style(text), 'pc') + self.assertEqual(screens.ini_value('prompts = pc\n# prompts = xbox\n; prompts = xbox', 'prompts'), 'pc') + # cfg.c trims the whole value and removes matching quotes; it does not strip inline comments. + self.assertEqual(screens.ini_value('prompts = pc # comment', 'prompts'), 'pc # comment') + + def test_quoted_pad_layout_selects_the_matching_prompts(self): + self.assertEqual(screens.prompts_style('TOTK_PAD_LAYOUT = "nintendo"\nprompts = "PS"'), 'playstation') + self.assertEqual(screens.prompts_style('pad_layout = "xbox_prompts"'), 'xbox') + + def test_shapes_generate_the_layouts_selected_by_quoted_or_repeated_settings(self): + screens.displays = lambda: [] + (self.dest / 'romfs-patches-pc').mkdir() + (self.dest / 'romfs-patches-pc' / 'manifest.tsv').write_text('#\n') + for trailing in ('', '\noutput_res =\nTOTK_PROMPTS = ""\nhud_width = \n'): + with self.subTest(trailing=trailing): + (self.dest / 'totk.ini').write_text('[display]\nTOTK_OUTPUT_RES = "3840x1080"\n' + 'hud_width = "16:9"\n[input]\nprompts = "pc"\n' + trailing) + ctx = SimpleNamespace(**vars(self.ctx)) + record = steps.Shapes().run(ctx) + self.assertEqual(record['folders'], ['romfs-patches-3840x1080', 'romfs-patches-pc-3840x1080', + 'romfs-patches-3840x1080-hud16x9', + 'romfs-patches-pc-3840x1080-hud16x9']) + self.assertTrue(steps.Shapes().current(ctx, record)) + def test_run_writes_only_the_wanted_folders(self): screens.displays = lambda: [(2560, 1080)] (self.dest / 'totk.ini').write_text('pad_layout = nintendo\nprompts = xbox\n') @@ -1256,5 +1465,152 @@ class DlssTest(unittest.TestCase): self.assertEqual(self.warnings(), []) +class HostProbeTest(unittest.TestCase): + """Check.probe_host: the host check's crashes and refusals (issues #875, #1345).""" + GOOD = '{"x86_64_v2": true, "x86_64_v3": true, "loader": true, "instance": 0, "devices": [' \ + '{"name": "Intel(R) UHD Graphics", "api": [1, 3, 215], "type": 1}]}\n' + CRASHED_IN_VULKAN = '{"x86_64_v2": true, "x86_64_v3": true, "loader": true, ' + ACCESS_VIOLATION = 0xC0000005 + LAYERS = [('VK_LAYER_VALVE_steam_overlay_64', Path('C:/Steam/SteamOverlayVulkanLayer64.json')), + ('VK_LAYER_BAD_overlay', Path('C:/Bad/BadOverlay64.json'))] + + def setUp(self): + self.ctx = SimpleNamespace(reporter=Reporter(out=io.StringIO())) + self.calls = [] + + def tearDown(self): + self.ctx.reporter.close() + + def probe(self, *results, layers=()): + """Runs probe_host with subprocess.run answering each call with the next of results (an exception is raised, + a callable gets the run's VK_LOADER_LAYERS_DISABLE).""" + answers = iter(results) + + def run(command, **kwargs): + env = kwargs.get('env') + self.calls.append(env) + r = next(answers) + if callable(r): + r = r((env or {}).get('VK_LOADER_LAYERS_DISABLE')) + if isinstance(r, BaseException): + raise r + return subprocess.CompletedProcess(command, r[0], r[1], '') + + with mock.patch.object(steps.subprocess, 'run', run), \ + mock.patch.object(steps, 'implicit_vulkan_layers', lambda: list(layers)): + return steps.Check().probe_host(self.ctx, Path('hostcheck.exe')) + + def bad_layer(self, disabled): + """The probe on a PC whose VK_LAYER_BAD_overlay is broken, with the layers in disabled turned off.""" + if disabled in ('~implicit~', 'VK_LAYER_BAD_overlay'): + return 0, self.GOOD + return self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN + + def only_all_off(self, disabled): + """The probe on a PC whose broken layer is not in the list (a driver's, under its adapter key).""" + if disabled == '~implicit~': + return 0, self.GOOD + return self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN + + def events(self, kind): + return [e for e in map(json.loads, self.ctx.reporter.out.getvalue().splitlines()) if e['type'] == kind] + + def test_a_good_probe_runs_once(self): + host = self.probe((0, self.GOOD)) + self.assertEqual(host['devices'][0]['api'], [1, 3, 215]) + self.assertEqual(self.calls, [None]) + self.assertEqual(self.events('warning'), []) + + def test_a_crashing_layer_is_named_and_stops_the_install(self): + # totk.exe --prepare-shaders and the game load the same layer, so going on would fail after lift and compile + with self.assertRaises(steps.InstallError) as e: + self.probe(*[self.bad_layer] * 4, layers=self.LAYERS) + self.assertEqual(e.exception.id, 'check.vulkan_layer_crash') + self.assertEqual(e.exception.params['disable'], 'VK_LAYER_BAD_overlay') + self.assertIn('VK_LAYER_BAD_overlay (', e.exception.params['layers']) + self.assertNotIn('steam', e.exception.params['layers']) + self.assertEqual([c and c['VK_LOADER_LAYERS_DISABLE'] for c in self.calls], + [None, '~implicit~', 'VK_LAYER_VALVE_steam_overlay_64', 'VK_LAYER_BAD_overlay']) + if os.name == 'nt': + self.assertEqual(e.exception.params['code'], '0xC0000005') + + def test_a_crashing_layer_that_cannot_be_singled_out_lists_the_installed_ones(self): + with self.assertRaises(steps.InstallError) as e: + self.probe(*[self.only_all_off] * 4, layers=self.LAYERS) + self.assertEqual(e.exception.id, 'check.vulkan_layers_crash') + self.assertIn('VK_LAYER_VALVE_steam_overlay_64', e.exception.params['layers']) + self.assertIn('VK_LAYER_BAD_overlay', e.exception.params['layers']) + with self.assertRaises(steps.InstallError) as e: + self.probe(self.only_all_off, self.only_all_off) + self.assertEqual((e.exception.id, e.exception.params['layers']), ('check.vulkan_layers_crash', '?')) + + def test_a_driver_that_crashes_without_the_layers_too_stops_the_install(self): + with self.assertRaises(steps.InstallError) as e: + self.probe((self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN), (self.ACCESS_VIOLATION, self.CRASHED_IN_VULKAN), + layers=self.LAYERS) + self.assertEqual(e.exception.id, 'check.vulkan_crash') + self.assertEqual(len(self.calls), 2) + + def test_a_crash_before_vulkan_is_not_run_again(self): + with self.assertRaises(steps.InstallError) as e: + self.probe((self.ACCESS_VIOLATION, '')) + self.assertEqual(e.exception.id, 'check.host_probe_failed') + self.assertEqual(len(self.calls), 1) + if os.name == 'nt': + self.assertEqual(e.exception.params['code'], '0xC0000005') + + @unittest.skipUnless(os.name == 'nt', 'winerror is set on Windows only') + def test_a_probe_blocked_by_smart_app_control_names_the_policy(self): + for code in (4551, 4559, 1260, 225): + with self.subTest(code=code): + blocked = OSError(None, 'An Application Control policy has blocked this file', None, code) + with self.assertRaises(steps.InstallError) as e: + self.probe(blocked) + self.assertEqual(e.exception.id, 'check.host_blocked') + self.assertIn('Application Control', e.exception.params['detail']) + self.assertTrue(e.exception.params['path'].endswith('hostcheck.exe')) + + def test_another_start_failure_is_reported_not_raised(self): + with self.assertRaises(steps.InstallError) as e: + self.probe(OSError(2, 'The system cannot find the file specified')) + self.assertEqual(e.exception.id, 'check.host_probe_failed') + self.assertIn('cannot find', e.exception.params['code']) + + def test_a_failed_host_check_runs_once_per_install(self): + # key() probes first and run() reports: the crashing probe and its retries must not run twice + check, ctx = steps.Check(), SimpleNamespace() + failure = steps.InstallError('check.vulkan_crash', code='1') + with mock.patch.object(steps.Check, 'check_host', side_effect=failure) as probe: + check.key(ctx) + with self.assertRaises(steps.InstallError) as e: + check.host(ctx) + self.assertEqual(e.exception.id, 'check.vulkan_crash') + self.assertEqual(probe.call_count, 1) + + def test_layer_names_come_from_the_manifests_the_loader_reads(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + (folder / 'one.json').write_text(json.dumps({'file_format_version': '1.1.2', 'layer': { + 'name': 'VK_LAYER_TEST_one', 'library_path': 'one.dll'}}), encoding='utf-8-sig') + (folder / 'two.json').write_text(json.dumps({'file_format_version': '1.0.1', 'layers': [ + {'name': 'VK_LAYER_TEST_a'}, {'name': 'VK_LAYER_TEST_b'}]}), encoding='utf-8') + (folder / 'broken.json').write_text('{', encoding='utf-8') + with mock.patch.dict(os.environ, {'VK_ADD_IMPLICIT_LAYER_PATH': tmp}): + mine = [(n, p.name) for n, p in steps.implicit_vulkan_layers() if p.parent == folder] + self.assertEqual(mine, [('VK_LAYER_TEST_one', 'one.json'), ('VK_LAYER_TEST_a', 'two.json'), + ('VK_LAYER_TEST_b', 'two.json')]) + + def test_messages_in_every_language(self): + need = {'check.host_blocked': ('{path}', '{detail}'), 'check.vulkan_crash': ('{code}',), + 'check.vulkan_layer_crash': ('{code}', '{layers}', '{disable}', 'VK_LOADER_LAYERS_DISABLE'), + 'check.vulkan_layers_crash': ('{code}', '{layers}', 'VK_LOADER_LAYERS_DISABLE', '~implicit~')} + for path in sorted((ROOT / 'installer' / 'text').glob('*.json')): + text = json.loads(path.read_text(encoding='utf-8')) + self.assertNotIn('warn.vulkan_layer_crash', text, path.name) + for key, parts in need.items(): + for part in parts: + self.assertIn(part, text[key], f'{path.name} {key}') + + if __name__ == '__main__': unittest.main() diff --git a/tests/ncz_test.py b/tests/ncz_test.py index 106f1a0d..14554cc6 100644 --- a/tests/ncz_test.py +++ b/tests/ncz_test.py @@ -66,6 +66,35 @@ def ncz_file(nca, body, blocks=False): return out + b''.join(stored) +class BlocksTest(unittest.TestCase): + def read(self, data, plain=1 << 14): + header = b'NCZBLOCK' + bytes([2, 1, 0, 14]) + struct.pack(''], 'compiles its checks with clang'), 'cheats_vm_check': ('.venv', 'cc', ['--cc', ''], 'compiles runtime/cheats.c into a harness with clang'), - 'diff/atomic': ('.venv', None, [], ''), - 'diff/simd': ('.venv', None, [], ''), + 'romfs_shapes_check': ('.venv', 'cc', ['--cc', ''], 'compiles the production overlay selection helpers'), + 'frame_world_check': ('.venv', 'cc', ['--cc', ''], 'compiles the production world-clock player walk'), + 'sync_ahead_check': ('.venv', 'cc', ['--cc', ''], 'compiles the production sync-ahead wait selection'), + 'patches_v110_check': ('.venv', 'cc', [], 'compiles synthetic patch contracts for comparison with Unicorn'), + 'patches_v110_highfps_check': ('.venv', 'cc', [], 'compiles synthetic high-fps contracts for comparison with Unicorn'), + 'diff/atomic': ('.venv', 'cc', [], 'compiles generated atomic checks for comparison with Unicorn'), + 'diff/simd': ('.venv', 'cc', [], 'compiles generated SIMD checks for comparison with Unicorn'), # ---- read the game or a build ---- - 'diff/lift': ('.venv', 'exefs', ['--exefs', ''], + 'diff/lift': ('.venv', 'exefs+cc', ['--exefs', ''], 'samples instructions from the game modules; needs an unpacked exefs'), - 'diff/func': ('.venv', 'exefs', ['--exefs', ''], + 'diff/func': ('.venv', 'exefs+cc', ['--exefs', ''], 'lifts whole functions of the game modules; needs an unpacked exefs'), 'jumptables_check': ('.venv', 'exefs', ['--exefs', ''], 'replays the modules through Unicorn; needs an unpacked exefs'), @@ -100,10 +113,11 @@ def find_exefs(): def find_exe(): - """A built totk.exe: the plain v143 tree, else the newest variant (v143-heropath, ...).""" - if (ROOT / 'build' / 'v143' / 'totk.exe').exists(): - return ROOT / 'build' / 'v143' / 'totk.exe' - builds = sorted(ROOT.glob('build/v143-*/totk.exe'), + """A built totk[.exe]: the plain v143 tree, else the newest variant (v143-heropath, ...).""" + name = 'totk.exe' if WIN else 'totk' + if (ROOT / 'build' / 'v143' / name).exists(): + return ROOT / 'build' / 'v143' / name + builds = sorted(ROOT.glob('build/v143-*/' + name), key=lambda p: p.stat().st_mtime, reverse=True) return builds[0] if builds else None @@ -133,7 +147,11 @@ def find_embed(): def find_cc(): - """clang for the tests that compile C: MSYS2 UCRT64's on Windows, else the one on PATH.""" + """The compiler the differential harness uses: CC, MSYS2 UCRT64, or clang on PATH.""" + cc = os.environ.get('CC') + if cc: + found = shutil.which(cc) + return Path(found) if found else None c = MSYS_BIN / 'clang.exe' if WIN and c.exists(): return c @@ -153,7 +171,7 @@ def resolve(needs): else: vals[''] = str(p) elif need == 'exe': p = find_exe() - if p is None: missing.append('no built build/v143/totk.exe') + if p is None: missing.append('no built build/v143/totk' + ('.exe' if WIN else '')) else: vals[''] = str(p) elif need == 'romfs': p = find_romfs() diff --git a/tools/build_game.py b/tools/build_game.py index e8d2aaf3..d660f4cd 100644 --- a/tools/build_game.py +++ b/tools/build_game.py @@ -42,8 +42,9 @@ objects Ninja just rebuilt (new mtime). A mismatch deletes the object, Ninja rec summary line. A fork checks the hardlinked generated objects against build//obj/objects.sha256 (read-only; a bad shared object stops the fork and asks for a main build run, which recompiles it and breaks the shared inode). -Compile jobs share a memory budget (MEM_BUDGET, default the smaller of 50 GiB and 80% of RAM) at JOB_MEM per job, so a -big machine does not run out of memory on the largest chunks. Each phase reports its wall time and the peak memory +Compile jobs share a memory budget (compile_budget: the smaller of MEM_BUDGET = 50 GiB, 80% of RAM and, on Windows, +80% of the memory free at the start) at JOB_MEM per job, so a big machine does not run out of memory on the largest +chunks, nor a small one already running a browser and the setup. Each phase reports its wall time and the peak memory of its processes (Windows job object accounting: committed private bytes). --ninja PATH names the Ninja to run; without MSYS2 the bin/ninja.exe of the release folder (tools/make_release.py) is used. @@ -77,6 +78,7 @@ import urllib.request from pathlib import Path import check_isa +import hostmem import romfs_index from build_shaders import stale as stale_shaders from check_content import GENERATED_MARKER @@ -220,6 +222,18 @@ GiB = 1 << 30 # (295k-entry tables). 768 MiB leaves headroom for the largest file. JOB_MEM = 768 << 20 MEM_BUDGET = 50 * GiB # total for all compile jobs +MEM_SHARE = 0.8 # of the RAM, and of the free memory, the compile jobs may take + + +def compile_budget(total, free): + """Bytes the compile jobs may take together: MEM_BUDGET, MEM_SHARE of the RAM (total) and MEM_SHARE of the memory + free now (free: hostmem.available_ram, None when unknown). The total alone counted the RAM other programs hold: on + an 8 GiB PC with 3 GiB free it allowed 8 jobs of JOB_MEM (6 GiB), so the compile paged or a job ran out of memory. + recomp/gen.py sizes the lift workers from the free memory the same way.""" + budget = min(MEM_BUDGET, int(total * MEM_SHARE)) + if free is not None: + budget = min(budget, int(max(0, free) * MEM_SHARE)) + return budget def below_root(p): @@ -1179,8 +1193,12 @@ def main(): mods = {} if args.make_runtime_lib else {m: chunk_files(gen, m) for m in linked} cpus = os.cpu_count() or 1 - budget = min(MEM_BUDGET, int(total_ram() * 0.8)) + free = hostmem.available_ram() + budget = compile_budget(total_ram(), free) jobs = args.jobs or max(1, min(cpus, budget // JOB_MEM)) + if not args.jobs: + print(f'build_game: {cpus} CPUs, {mib(budget)} for compile jobs' + f'{"" if free is None else f" ({mib(free)} free memory)"}', flush=True) plugins = read_plugin_files(gen) missing = [n for n in names if n not in hashes and n not in plugins] if missing: diff --git a/tools/check_isa.py b/tools/check_isa.py index e6306fdd..0f53431d 100644 --- a/tools/check_isa.py +++ b/tools/check_isa.py @@ -33,6 +33,7 @@ NON_V2 = {'andn', 'bextr', 'blsi', 'blsmsk', 'blsr', 'bzhi', 'shlx', 'shrx', 'sa 'pclmulqdq', 'rdrand', 'rdseed'} PREFIXES = {'rep', 'repe', 'repz', 'repne', 'repnz', 'lock', 'notrack', 'data16', 'cs', 'ds', 'es', 'ss', 'fs', 'gs'} WIDE = re.compile(r'%[yz]mm\d|%k[0-7]\b') +INSN = re.compile(r'^\s*[0-9a-f]+:') # Function -> the runtime check that keeps it off CPUs without the instructions. DISPATCHED = { @@ -89,7 +90,10 @@ def scan_one(path, objdump): if m: func = m.group(1) continue - if not line[:1].isspace(): + # An instruction line starts with its address: short and indented in an object, 9+ hex digits at the start of + # the line in a linked .exe or .dll. Testing for leading whitespace alone skipped every instruction of a linked + # image and reported it clean. + if not INSN.match(line): continue mn = mnemonic(line) if mn and func not in DISPATCHED and is_non_v2(line, mn): diff --git a/tools/exefs_plugins.py b/tools/exefs_plugins.py index fefdc05e..ec584a30 100644 --- a/tools/exefs_plugins.py +++ b/tools/exefs_plugins.py @@ -495,7 +495,8 @@ def plugin_lines(rec, hooks, name, record_dir, module): p = mods[module] img = rec['images'][p['name']] text_sha = hashlib.sha256(img[:p['text_end']]).hexdigest() - lines.append(f'plugin {name} {p["name"]} {text_sha} {(Path(record_dir) / p["image"]).resolve().as_posix()}') + image = json.dumps((Path(record_dir) / p['image']).resolve().as_posix(), ensure_ascii=False) + lines.append(f'plugin {name} {p["name"]} {text_sha} {image}') own = {int(h['site'].split('+')[1], 16) for h in hooks} for w in rec['writes']: if w['module'] == 'main' and w['offset'] in own: diff --git a/tools/extract.py b/tools/extract.py index 5c9bf407..cb48eada 100644 --- a/tools/extract.py +++ b/tools/extract.py @@ -37,9 +37,9 @@ from extract_update_romfs import copy_range, hactool_prod_keys # noqa: E402 DATA = ROOT / 'tools' / 'data' EXEFS_CODE = ('main', 'sdk', 'subsdk0', 'rtld') LONG_HEX = re.compile(r'[0-9A-Fa-f]{32,}') -# hactool checks two signatures with Nintendo public keys it does not ship, so these two lines always read (FAIL) and -# say nothing about the data. The IVFC levels and the image hash decide. -UNSIGNED = re.compile(r'\s*(?:Fixed-Key Signature|NPDM Signature) \(FAIL\)') +# Signature warnings can occur on dumps whose data is intact. hactool's npdm.c npdm_print labels the ACID check simply +# "Signature", alongside nca.c nca_print's Fixed-Key and NPDM signatures. The IVFC levels and image hash still decide. +UNSIGNED = re.compile(r'\s*(?:Fixed-Key Signature|NPDM Signature|Signature) \(FAIL\):') HACTOOL_ERROR = re.compile(r'\(FAIL\)|\(INVALID\)|Failed to|Error:') # hactool lines of a hash check that failed: a RomFS level, a section's superblock or its hash table. HACTOOL_HASH_FAIL = re.compile(r'^\s*(?:Level \d|Superblock Hash|Hash Table) \(FAIL\)', re.M) diff --git a/tools/ncz.py b/tools/ncz.py index d41dfe4d..db9ce15c 100644 --- a/tools/ncz.py +++ b/tools/ncz.py @@ -35,6 +35,10 @@ class DamagedFile(ValueError): super().__init__(f'{self.path} is damaged or incomplete ({detail})') +class BlockSizeError(ValueError): + """An NCZBLOCK block whose data decompresses to more or fewer bytes than its header declares.""" + + def compressed(path): """('nsz' or 'xcz', entries) for a game file holding NCZ files, else None. Raises ValueError for a file that is neither an NSP nor an XCI.""" @@ -126,9 +130,18 @@ def blocks(f, pos, end, total): for i, length in enumerate(stored): plain = min(1 << exponent, size - (i << exponent)) require(pos + length <= end, 'Truncated NCZ block') - data = read_at(f, pos, length) + # nsz's BlockDecompressorReader.py __decompressBlock skips padding in a raw block: only plain bytes belong + # to the NCA, while the full stored length locates the next block. + data = read_at(f, pos, min(length, plain)) pos += length - yield zstd.decompress(data) if length < plain else data + if length < plain: + # Read at most one byte beyond the declared size: a damaged frame must not allocate its whole output. + # ZstdFile also preserves support for concatenated frames within a block. + with zstd.ZstdFile(io.BytesIO(data)) as z: + data = z.read(plain + 1) + if len(data) != plain: + raise BlockSizeError(f'NCZ block decompressed size does not match its header (block {i})') + yield data def stream(f, pos, end, total): @@ -176,7 +189,9 @@ def unpack_ncz(f, start, end, out, name, source, progress): progress(n) if at == total: break - except (zstd.ZstdError, EOFError) as e: # EOFError: the stream ends before its end-of-frame marker + # EOFError: the stream ends before its end-of-frame marker. BlockSizeError: a block's data is damaged; like the + # other two it is a damaged file, so the installer asks for a fresh copy (installer/steps.py, Check.unpack). + except (zstd.ZstdError, EOFError, BlockSizeError) as e: raise DamagedFile(source, f'{name}: {e}') from None if at != total or pending: raise DamagedFile(source, f'{name}: {at - HEADER:,} of {total - HEADER:,} bytes') diff --git a/tools/pack_shader_cache.py b/tools/pack_shader_cache.py index f41e2c3f..3271643d 100644 --- a/tools/pack_shader_cache.py +++ b/tools/pack_shader_cache.py @@ -26,6 +26,7 @@ PACK = 'shader-cache.pack' KINDS = {'.spv': 1, '.res.json': 2, '.use': 3, '.in': 4} NAME = re.compile(r'([0-9a-f]{64})(\.spv|\.res\.json|\.use|\.in)') USE_SIZE = 20 # gfx_shader.c use_store: magic, version, three masks +MAX_ENTRIES = 1 << 24 # gfx_shader.c pack_open's index limit def loose_files(cache): @@ -58,8 +59,13 @@ def read_pack(path): print(f'{path}: not a cache pack, rebuilt from the loose files only', flush=True) return {} count = struct.unpack_from(' MAX_ENTRIES or index_size > size - 16: + print(f'{path}: invalid index size, rebuilt from the loose files only', flush=True) + return {} + raw = f.read(index_size) + if len(raw) != index_size: print(f'{path}: truncated index, rebuilt from the loose files only', flush=True) return {} out = {} diff --git a/totk.ini.example b/totk.ini.example index c367228a..d773f1df 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -41,6 +41,9 @@ # Game 1.4.3: the two launchers in Tenbez Shrine throw the stone ball into the other launcher's seat above 30 fps. # 0 = the game's own speed, tuned for 30 fps. # shutter_fix = 1 +# Games 1.2.1 and 1.4.3: above 30 fps a thunderstorm has the lightning of 30 fps, instead of more distant bolts and +# lightning flashes the higher the frame rate. 0 = the game's own chances per frame, tuned for 30 fps. +# lightning_fix = 1 [performance] # The keys of this section and of [diagnostics] are for testing and troubleshooting, and take effect at the next start.