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/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/tests/installer_test.py b/tests/installer_test.py index a45843f9..a00a21b2 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 @@ -1357,5 +1359,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()