From 9feb7f2b4f7fedf95f91c9e961dcdede145431aa Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:12:57 +0100 Subject: [PATCH 1/4] speed up install and update --- .github/workflows/package.yml | 8 +- Launcher/Build-Installer.ps1 | 91 ++- Launcher/LocalBuild.ps1 | 120 ++- Launcher/Test-PayloadBoundary.ps1 | 40 +- .../ProductCurrency.cs | 663 ++++++++++++++++ .../ProductCurrencySelfTest.cs | 349 +++++++++ Launcher/WiiCompiled.Setup.Linux/Program.cs | 73 +- .../ConsoleCommands.cs | 68 +- .../InstallerEngine.cs | 421 ++++++++-- .../LocalBuildService.cs | 32 +- Launcher/WiiCompiled.Setup.Windows/Models.cs | 31 + .../PayloadArchive.cs | 92 ++- .../PayloadInventory.cs | 240 ++++++ .../ProductRepairService.cs | 75 +- .../SelfTests.Payload.cs | 718 ++++++++++++++++++ .../WiiCompiled.Setup.Windows/SelfTests.cs | 50 +- .../ToolkitFingerprint.cs | 493 +++++++++--- Launcher/build-appimage.sh | 17 + Launcher/build-cache.sh | 351 ++++++++- Launcher/local-build-macos.command | 10 +- Launcher/local-build.sh | 13 +- Launcher/macos/build-setup-pkg.command | 24 +- Launcher/macos/extract-disc.command | 43 +- Launcher/macos/sync-workspace.command | 12 +- runtime/cmake/PublicProducts.cmake | 21 +- translator/src/Translator.Cli/Program.cs | 237 ++++-- .../TranslationProjectConfig.cs | 55 +- .../Build/GeneratedOutputPruner.cs | 9 +- .../Build/TranslatedBuildShardEmitter.cs | 44 +- .../Build/TranslationSourceBundle.cs | 21 +- .../CodeGen/RuntimeConfigGenerator.cs | 2 +- .../src/Translator.Core/GuestAddressTable.cs | 5 +- .../Translator.Core/IO/AssemblyBlobWriter.cs | 6 +- .../Translator.Core/IO/FileAccessRecorder.cs | 275 +++++++ .../src/Translator.Core/IO/FileOutput.cs | 25 +- .../src/Translator.Core/IO/StepProvenance.cs | 433 +++++++++++ .../src/Translator.Core/IO/TrackedFs.cs | 280 +++++++ .../IO/TransactionalDirectoryOutput.cs | 24 +- .../Loading/ChecksumUtilities.cs | 3 +- .../Translator.Core/Loading/FunctionMap.cs | 5 +- .../src/Translator.Core/Mods/BaseManifest.cs | 3 +- .../Mods/BaseManifestBuilder.cs | 12 +- .../Mods/BaseTranslationModAwareness.cs | 4 +- .../Mods/BaseTranslationOutputMetadata.cs | 2 +- .../Mods/ModDataPatchWriter.cs | 2 +- .../Mods/ModDvdOverlayRoots.cs | 3 +- .../Mods/OverlayFunctionBuilder.cs | 9 +- .../Translator.Core/NativeSourceParsing.cs | 7 +- .../Translator.Core/Parsing/Dol/DolFile.cs | 2 +- .../Parsing/Kamek/KamekPulFile.cs | 3 +- .../Translator.Core/Parsing/Rel/RelFile.cs | 2 +- .../src/Translator.Core/RuntimeNativeIndex.cs | 11 +- .../Translator.Core/RuntimeNativeIndexFile.cs | 4 +- .../FileAccessRecorderTests.cs | 162 ++++ .../ListTranslationInputsTests.cs | 117 +++ .../StepProvenanceFacadeCoverageTests.cs | 255 +++++++ .../StepProvenanceGateTests.cs | 338 +++++++++ .../StepProvenanceWorkspace.cs | 255 +++++++ 58 files changed, 6227 insertions(+), 443 deletions(-) create mode 100644 Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs create mode 100644 Launcher/WiiCompiled.Setup.Linux/ProductCurrencySelfTest.cs create mode 100644 Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs create mode 100644 Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs create mode 100644 translator/src/Translator.Core/IO/FileAccessRecorder.cs create mode 100644 translator/src/Translator.Core/IO/StepProvenance.cs create mode 100644 translator/src/Translator.Core/IO/TrackedFs.cs create mode 100644 translator/tests/Translator.Tests/FileAccessRecorderTests.cs create mode 100644 translator/tests/Translator.Tests/ListTranslationInputsTests.cs create mode 100644 translator/tests/Translator.Tests/StepProvenanceFacadeCoverageTests.cs create mode 100644 translator/tests/Translator.Tests/StepProvenanceGateTests.cs create mode 100644 translator/tests/Translator.Tests/StepProvenanceWorkspace.cs diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index 1acefe9d4..91cbddf3c 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -140,11 +140,11 @@ jobs: run: | dotnet publish translator/src/Translator.Cli/Translator.Cli.csproj \ -c Release -r osx-arm64 --self-contained true \ - -p:PublishSingleFile=true \ + -p:PublishSingleFile=true -p:DebugType=None \ -o Launcher/artifacts/macos/translator-arm64 dotnet publish translator/src/Translator.Cli/Translator.Cli.csproj \ -c Release -r osx-x64 --self-contained true \ - -p:PublishSingleFile=true \ + -p:PublishSingleFile=true -p:DebugType=None \ -o Launcher/artifacts/macos/translator-x86_64 - name: Publish self-contained setup CLI @@ -152,11 +152,11 @@ jobs: run: | dotnet publish Launcher/WiiCompiled.Setup.Linux/WiiCompiled.Setup.Linux.csproj \ -c Release -r osx-arm64 --self-contained true \ - -p:PublishSingleFile=true \ + -p:PublishSingleFile=true -p:DebugType=None \ -o Launcher/artifacts/macos/setup-arm64 dotnet publish Launcher/WiiCompiled.Setup.Linux/WiiCompiled.Setup.Linux.csproj \ -c Release -r osx-x64 --self-contained true \ - -p:PublishSingleFile=true \ + -p:PublishSingleFile=true -p:DebugType=None \ -o Launcher/artifacts/macos/setup-x86_64 - name: Download pinned universal Ninja diff --git a/Launcher/Build-Installer.ps1 b/Launcher/Build-Installer.ps1 index 7be602f75..9f82577ce 100644 --- a/Launcher/Build-Installer.ps1 +++ b/Launcher/Build-Installer.ps1 @@ -114,6 +114,11 @@ if (-not (Test-Path -LiteralPath (Join-Path $portableTools 'llvm-mingw\bin\x86_6 } Assert-File (Join-Path $portableTools 'CMake\bin\cmake.exe') 'Portable CMake' Assert-File (Join-Path $portableTools 'Ninja\ninja.exe') 'Portable Ninja' +# PublicProducts.cmake copies the target runtime DLLs from the x86_64 sysroot, never from the host +# compiler's own bin directory, and fails configure if they are missing. +foreach ($runtimeDll in @('libc++.dll', 'libunwind.dll')) { + Assert-File (Join-Path $portableTools "llvm-mingw\x86_64-w64-mingw32\bin\$runtimeDll") "x86_64 target runtime $runtimeDll" +} # native_prebuilt carries the aurora/third-party archives the user no longer has # to compile (launcher/Prepare-NativePrebuilt.ps1). # Kept in step with InstalledLayout.DependencyNames by Test-PinnedFacts.ps1: the installed host @@ -225,17 +230,54 @@ $workspace = Join-Path $payloadRoot 'BuildWorkspace' Copy-Directory (Join-Path $portableTools 'llvm-mingw') (Join-Path $toolkit 'llvm-mingw') Copy-Directory (Join-Path $portableTools 'CMake') (Join-Path $toolkit 'CMake') Copy-Directory (Join-Path $portableTools 'Ninja') (Join-Path $toolkit 'Ninja') -# Debuggers, Python bindings, and the CMake GUI are not part of the local build graph. -# Leaving them out reduces the attack/dependency surface without removing compiler support files. -foreach ($unused in @( - (Join-Path $toolkit 'llvm-mingw\python'), - (Join-Path $toolkit 'CMake\bin\cmake-gui.exe') -)) { +# Only what is verified unused by the x86_64 build, with the precompiled package or from source, is +# left out: debuggers, Python, the CMake GUI/test/packaging tools and HTML/man documentation, the +# four foreign target sysroots and their cross wrappers, busybox, clangd/clang-tidy, and the +# sanitizer and non-x86_64 compiler runtimes. Licenses, the x86_64 sysroot, every x86_64 wrapper and +# config, the compiler/linker/archiver/resource tools and their DLLs, and the builtins runtimes stay. +# Test-PayloadBoundary.ps1 asserts the license files and target runtimes are still present. +$llvmMingw = Join-Path $toolkit 'llvm-mingw' +$cmakeRoot = Join-Path $toolkit 'CMake' +$unusedPaths = [Collections.Generic.List[string]]::new() +foreach ($relative in @( + 'llvm-mingw\python', 'llvm-mingw\busybox', + 'llvm-mingw\aarch64-w64-mingw32', 'llvm-mingw\arm64ec-w64-mingw32', + 'llvm-mingw\armv7-w64-mingw32', 'llvm-mingw\i686-w64-mingw32', + 'CMake\bin\cmake-gui.exe', 'CMake\bin\ctest.exe', 'CMake\bin\cpack.exe', 'CMake\bin\cmcldeps.exe', + 'CMake\man' +)) { $unusedPaths.Add((Join-Path $toolkit $relative)) } +foreach ($docs in @(Get-ChildItem -LiteralPath (Join-Path $cmakeRoot 'doc') -Directory -Filter 'cmake*' -ErrorAction SilentlyContinue)) { + foreach ($name in @('html', 'CMake.qch', 'cmake.org.html')) { $unusedPaths.Add((Join-Path $docs.FullName $name)) } +} +foreach ($share in @(Get-ChildItem -LiteralPath (Join-Path $cmakeRoot 'share') -Directory -Filter 'cmake-*' -ErrorAction SilentlyContinue)) { + $unusedPaths.Add((Join-Path $share.FullName 'Help')) +} +foreach ($unused in $unusedPaths) { if (Test-Path -LiteralPath $unused) { Remove-Item -LiteralPath $unused -Recurse -Force } } -Get-ChildItem -LiteralPath (Join-Path $toolkit 'llvm-mingw\bin') -File | - Where-Object { $_.Name -like 'lldb*' -or $_.Name -like 'liblldb*' } | +Get-ChildItem -LiteralPath (Join-Path $llvmMingw 'bin') -File | + Where-Object { + $_.Name -like 'lldb*' -or $_.Name -like 'liblldb*' -or + $_.Name -match '^(aarch64|arm64ec|armv7|i686)-' -or + $_.Name -in @('clangd.exe', 'clang-tidy.exe') -or + $_.Name -like 'libpython*' -or $_.Name -like 'libffi*' + } | Remove-Item -Force +# Compiler runtimes: keep every builtins archive and every non-sanitizer x86_64 runtime; the x86_64 +# sysroot is kept whole. +$x64Sysroot = (Join-Path $llvmMingw 'x86_64-w64-mingw32').TrimEnd('\') + '\' +Get-ChildItem -LiteralPath $llvmMingw -Recurse -File -Filter 'libclang_rt.*' | + Where-Object { + -not $_.FullName.StartsWith($x64Sysroot, [StringComparison]::OrdinalIgnoreCase) -and + $_.Name -notlike 'libclang_rt.builtins*' -and ( + $_.Name -match '^libclang_rt\.(asan|hwasan|msan|tsan|ubsan|lsan|dfsan|memprof|cfi|nsan|rtsan|tysan|safestack|scudo|gwp_asan|dd|dyndd)' -or + $_.Name -match '-(i386|i686|aarch64|arm64ec|arm64|armhf|armv7|arm)\.' + ) + } | + Remove-Item -Force +foreach ($runtimeDll in @('libc++.dll', 'libunwind.dll')) { + Assert-File (Join-Path $llvmMingw "x86_64-w64-mingw32\bin\$runtimeDll") "Staged x86_64 target runtime $runtimeDll" +} [IO.Directory]::CreateDirectory((Join-Path $toolkit 'Translator')) | Out-Null Copy-Item -LiteralPath $translator -Destination (Join-Path $toolkit 'Translator\Translator.Cli.exe') Copy-Item -LiteralPath $nodTool -Destination (Join-Path $toolkit 'nodtool.exe') @@ -260,6 +302,10 @@ foreach ($releaseProject in $releaseProjects) { Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'LocalBuild.ps1') -Destination (Join-Path $workspace 'LocalBuild.ps1') # LocalBuild.ps1 dot-sources the canonical configure flags from this sibling. Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'NativeBuildFlags.ps1') -Destination (Join-Path $workspace 'NativeBuildFlags.ps1') +# The native-toolchain identity hashes the configure flags themselves rather than the scripts' +# source text; LocalBuild.ps1 refuses to reuse a build directory when the two ever disagree. +[IO.File]::WriteAllText((Join-Path $workspace 'native-configure-flags.txt'), + ((Get-MkwNativeFixedConfigureFlags) -join "`n"), [Text.UTF8Encoding]::new($false)) [IO.Directory]::CreateDirectory((Join-Path $workspace 'Dependencies')) | Out-Null foreach ($name in $requiredDependencies) { Copy-Directory (Join-Path $dependencySources $name) (Join-Path $workspace "Dependencies\$name") } @@ -296,6 +342,10 @@ if ($LASTEXITCODE -ne 0) { throw "Windows PowerShell rejects the staged precompiled aurora package (exit $LASTEXITCODE); every installation would build aurora from source." } Remove-Item -LiteralPath $prebuiltGate -Force +# The gate's verdict depends only on bytes the compile identity covers (compiler, flags, Dawn, +# aurora-main, runtime/third_party) plus this provenance document. Recording which document it +# accepted lets a build whose compile identity was verified to be this release's skip re-proving it. +$nativePrebuiltGateProvenanceSha256 = Get-MkwFileSha256 (Join-Path $workspace 'Dependencies\native_prebuilt\provenance.json') [IO.Directory]::CreateDirectory((Join-Path $payloadRoot 'host')) | Out-Null Copy-Item $setupHost (Join-Path $payloadRoot 'host\WiiCompiled-Setup.exe') @@ -344,15 +394,28 @@ Microsoft license terms: https://visualstudio.microsoft.com/license-terms/ "@ | Set-Content (Join-Path $payloadRoot 'licenses\Microsoft-VC-Runtime.txt') -Encoding UTF8 # Compute the payload's content identities once, here, with the same code every installed host # uses. Shipping them in the manifest is what keeps user machines from re-hashing the toolkit -# during installation; only --repair-products re-derives content identity locally. +# during installation; only --repair-products re-derives content identity locally. This also +# writes payload-inventory.json (every shipped file's size and SHA-256, and the files each +# translation project reads, as the staged translator lists them) beside the manifest. Write-Host 'Computing the payload content identities (hashes the staged toolkit once)...' $identityJson = & $setupHost --emit-payload-identities --payload-root $payloadRoot if ($LASTEXITCODE -ne 0) { throw "Payload identity computation failed with exit code $LASTEXITCODE." } $identities = ($identityJson -join '') | ConvertFrom-Json foreach ($required in @('ToolkitFingerprint','TranslationFingerprint','NativeToolchainFingerprint', - 'ToolkitPackageFingerprint','RuntimeAssetsFingerprint')) { + 'ToolkitPackageFingerprint','RuntimeAssetsFingerprint','ToolchainPackageFingerprint', + 'TranslatorPackageFingerprint')) { if ([string]::IsNullOrWhiteSpace($identities.$required)) { throw "Payload identity output is missing $required." } } +$translationFingerprintsByRelease = [ordered]@{} +foreach ($property in $identities.TranslationFingerprintsByRelease.PSObject.Properties) { + $translationFingerprintsByRelease[$property.Name] = [string]$property.Value +} +foreach ($releaseProject in $releaseProjects) { + if (-not $translationFingerprintsByRelease.Contains($releaseProject.Name)) { + throw "Payload identity output has no translation identity for the $($releaseProject.Name) project." + } +} +Assert-File (Join-Path $payloadRoot 'payload-inventory.json') 'Payload file inventory' $productVersion = ((& $setupHost --version) -join '').Trim() if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($productVersion)) { throw 'The setup host did not report its version.' } @@ -369,6 +432,12 @@ $manifest = [ordered]@{ RuntimeAssetsFingerprint = $identities.RuntimeAssetsFingerprint TranslationFingerprint = $identities.TranslationFingerprint NativeToolchainFingerprint = $identities.NativeToolchainFingerprint + # Additive within schema 3: older readers ignore them, and setup falls back to the whole- + # toolkit identities above wherever one is absent. + ToolchainPackageFingerprint = $identities.ToolchainPackageFingerprint + TranslatorPackageFingerprint = $identities.TranslatorPackageFingerprint + TranslationFingerprintsByRelease = $translationFingerprintsByRelease + NativePrebuiltGateProvenanceSha256 = $nativePrebuiltGateProvenanceSha256 } $manifest | ConvertTo-Json -Depth 4 | Set-Content (Join-Path $payloadRoot 'payload-manifest.json') -Encoding UTF8 @@ -383,7 +452,7 @@ Write-Host '[4/6] Enforcing the copyright and generated-code boundary...' Write-Host '[5/6] Creating the canonical installer payload...' $payloadZip = Join-Path $workRoot 'payload.zip' Compress-Zip $payloadRoot $payloadZip @( - 'Toolkit','BuildWorkspace','host','licenses','payload-manifest.json') + 'Toolkit','BuildWorkspace','host','licenses','payload-manifest.json','payload-inventory.json') Write-Host '[6/6] Producing the single-file setup executable...' $outputSetup = Join-Path $outputRoot 'WiiCompiled-Setup.exe' diff --git a/Launcher/LocalBuild.ps1 b/Launcher/LocalBuild.ps1 index 5969cbe67..69558faca 100644 --- a/Launcher/LocalBuild.ps1 +++ b/Launcher/LocalBuild.ps1 @@ -18,6 +18,15 @@ param( # mismatched identity degrades that cache to a clean rebuild, never the other way around. [string]$TranslationFingerprint = '', [string]$NativeToolchainFingerprint = '', + # 'project=identity;...': the translation identity narrowed to the files each translation + # project reads. The entry of the project selected for the extracted disc replaces + # -TranslationFingerprint; without one, -TranslationFingerprint applies unchanged. + [string]$TranslationFingerprintsByRelease = '', + # The compile identity the caller proved for exactly this toolkit (hashed in full, or verified + # while installing it). Only with it may a recorded or release-proved precompiled-package gate + # verdict stand in for re-running the gate; a development workspace always runs it. + [string]$VerifiedCompileIdentity = '', + [string]$AcceptedNativePrebuiltProvenanceSha256 = '', # Discards every cache first. Used when a product was reported broken/blocked, so a possibly # corrupted translation or build directory can never contribute to the repaired product. [switch]$ForceCleanBuild, @@ -138,6 +147,15 @@ $selectedProject = Resolve-MkwProjectForAssets $Workspace $assets $project = $selectedProject.Path $pins = $selectedProject.Pins $retroWfcPayloadFile = "binary\payload.$(($pins.RetroWfcPayloadUri -split 'g=')[-1]).bin" +# The caller derives one translation identity per translation project; the one for the project +# this disc selects decides base-translation reuse. A malformed list simply falls back. +$projectName = Split-Path -Leaf (Split-Path -Parent $project) +foreach ($pair in @($TranslationFingerprintsByRelease -split ';')) { + if ($pair -cmatch '^([A-Za-z0-9._-]+)=([0-9a-f]{64})$' -and $Matches[1] -ceq $projectName) { + $TranslationFingerprint = $Matches[2] + break + } +} # Three independent knobs: $translatorThreads (the translator's own worker threads; peak memory is # one heap that barely moves with thread count, so clamping it only slows translation), $translatedJobs @@ -168,6 +186,10 @@ try { # The caller only supplies the identities to compare recorded provenance against. $translationProvenance = Join-Path $generated 'translation-provenance.json' $toolchainProvenance = Join-Path $build 'toolchain-provenance.json' + # Per-step records the translator itself writes and checks (--provenance-file): a step is + # skipped only when every input, scanned directory, probed path, output and the translator + # binary still match. Kept under generated/, so a forced clean build discards them too. + $stepProvenance = Join-Path $generated 'step-provenance' function Get-RecordedFingerprint([string]$Path, [string]$Property) { if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return '' } @@ -300,11 +322,15 @@ try { } else { throw 'Retro Rewind requires either -RetroWfcOfflineDirectory or -SkipRetroWfcPayload.' } + [IO.Directory]::CreateDirectory($stepProvenance) | Out-Null + $translateModArguments += @('--provenance-file', (Join-Path $stepProvenance 'translate-mod.json')) Invoke-Checked $translator $translateModArguments 'Translating the selected Retro Rewind Code.pul' ` -StepId 'translate-mod' -TimeoutSeconds $translatorTimeoutSeconds } - Invoke-Checked $translator @('generate-data-init', '--project', $project) ` + [IO.Directory]::CreateDirectory($stepProvenance) | Out-Null + Invoke-Checked $translator @('generate-data-init', '--project', $project, + '--provenance-file', (Join-Path $stepProvenance 'generate-data-init.json')) ` 'Generating local game data initialization' -StepId 'generate-data-init' ` -TimeoutSeconds $translatorTimeoutSeconds @@ -318,17 +344,86 @@ try { $shardArgs += @('--resolved-profile', (Join-Path $retroOut 'resolved_dispatch_profile.json'), '--retro-cpp-dir', (Join-Path $retroOut 'cpp')) } + $shardArgs += @('--provenance-file', (Join-Path $stepProvenance 'emit-build-shards.json')) Invoke-Checked $translator $shardArgs 'Preparing local native build shards' -StepId 'emit-build-shards' ` -TimeoutSeconds $translatorTimeoutSeconds + $dependencies = Join-Path $Workspace 'Dependencies' + # The precompiled-package gate re-hashes aurora-main and runtime/third_party under Windows + # PowerShell, which takes long. Its verdict depends only on bytes the compile identity + # covers (compiler, configure flags, Dawn, aurora-main, runtime/third_party) plus the + # package's provenance.json, so for a compile identity the caller verified it is taken from + # the release build (which ran this exact gate on this exact toolkit) or from this + # workspace's record of a previous run, keyed on both. Anything else runs the full gate. + $nativePrebuiltPackage = Join-Path $dependencies 'native_prebuilt' + $nativePrebuiltProvenance = Join-Path $nativePrebuiltPackage 'provenance.json' + $prebuiltGateRecord = Join-Path $stepProvenance 'native-prebuilt-gate.json' + $nativePrebuiltProvenanceSha = if (Test-Path -LiteralPath $nativePrebuiltProvenance -PathType Leaf) { + Get-MkwFileSha256 $nativePrebuiltProvenance + } else { '' } + $nativePrebuilt = $null + if ($VerifiedCompileIdentity -cmatch '^[0-9a-f]{64}$' -and $nativePrebuiltProvenanceSha) { + $releaseProved = $AcceptedNativePrebuiltProvenanceSha256 -ceq $nativePrebuiltProvenanceSha + $recorded = (Get-RecordedFingerprint $prebuiltGateRecord 'CompileIdentity') -ceq $VerifiedCompileIdentity -and + (Get-RecordedFingerprint $prebuiltGateRecord 'ProvenanceSha256') -ceq $nativePrebuiltProvenanceSha + if ($releaseProved -or $recorded) { + Write-Host 'MKWCBUILD: Using the precompiled aurora and third-party libraries (verified for this toolkit)' + $nativePrebuilt = $nativePrebuiltPackage + } + } + if ($null -eq $nativePrebuilt) { + if (Test-Path -LiteralPath $prebuiltGateRecord) { Remove-Item -LiteralPath $prebuiltGateRecord -Force } + $nativePrebuilt = Resolve-MkwNativePrebuiltDirectory $dependencies $toolchainBin ` + (Join-Path $Workspace 'aurora-main') (Join-Path $Workspace 'runtime\third_party') + if ($nativePrebuilt -and $VerifiedCompileIdentity -cmatch '^[0-9a-f]{64}$' -and $nativePrebuiltProvenanceSha) { + [IO.Directory]::CreateDirectory($stepProvenance) | Out-Null + $gateTemp = "$prebuiltGateRecord.tmp-$PID" + [ordered]@{ SchemaVersion = 1; CompileIdentity = $VerifiedCompileIdentity + ProvenanceSha256 = $nativePrebuiltProvenanceSha } | + ConvertTo-Json | Set-Content -LiteralPath $gateTemp -Encoding UTF8 + Move-Item -LiteralPath $gateTemp -Destination $prebuiltGateRecord -Force + } + } + if ($X86CpuProfile -eq 'v2') { + Write-Host 'MKWCBUILD: This CPU does not support x86-64-v3; building for x86-64-v2' + } + $configure = Get-MkwNativeConfigureArguments ` + -SourceDirectory (Join-Path $Workspace 'runtime') -BuildDirectory $build ` + -Ninja $ninja -CCompiler $cc -CxxCompiler $cxx -ResourceCompiler $windres ` + -DependenciesDirectory $dependencies -NativePrebuiltDirectory $nativePrebuilt ` + -AdditionalArguments @("-DMKW_TRANSLATED_COMPILE_JOBS=$translatedJobs", "-DMKW_X86_CPU_PROFILE=$X86CpuProfile") + + # The native-toolchain identity covers the compiler, CMake and its modules, Ninja, and the + # shipped fixed configure flags. What it cannot see is recorded here beside the cache: the + # names of every -D option this run passes (values are paths or per-machine settings that + # CMake already tracks; a vanished or new option would leave a stale cache entry) and the + # CPU profile. MKW_TRANSLATED_COMPILE_JOBS is a per-machine job count and is left out. + $optionNames = [Collections.Generic.SortedSet[string]]::new([StringComparer]::Ordinal) + foreach ($argument in $configure) { + if ("$argument" -cmatch '^-D([^:=]+)' -and $Matches[1] -cne 'MKW_TRANSLATED_COMPILE_JOBS') { + [void]$optionNames.Add($Matches[1]) + } + } + $configureOptionNames = @($optionNames) -join ',' + + $configureFlagsFile = Join-Path $Workspace 'native-configure-flags.txt' + $shippedFlagsCurrent = (Test-Path -LiteralPath $configureFlagsFile -PathType Leaf) -and + ([IO.File]::ReadAllText($configureFlagsFile) -ceq ((Get-MkwNativeFixedConfigureFlags) -join "`n")) + if (-not $shippedFlagsCurrent -and -not [string]::IsNullOrWhiteSpace($NativeToolchainFingerprint)) { + Write-Host 'MKWCBUILD: The shipped configure flags do not match the build script; the native build cache cannot be trusted' + } + # The build directory is kept whenever the exact toolchain that filled it is the one # installed now and its CMake cache still belongs to this workspace path. Object files are # only ever unsafe to reuse when the compiler/flags changed - source changes are what # CMake/Ninja exist to track, so a kept directory turns a small runtime or dependency # change into a recompile of just the affected objects instead of every shard. if (Test-Path -LiteralPath $build) { - $keepNativeBuild = -not [string]::IsNullOrWhiteSpace($NativeToolchainFingerprint) -and + $keepNativeBuild = $shippedFlagsCurrent -and + -not [string]::IsNullOrWhiteSpace($NativeToolchainFingerprint) -and (Get-RecordedFingerprint $toolchainProvenance 'NativeToolchainFingerprint') -eq $NativeToolchainFingerprint -and + (Get-RecordedFingerprint $toolchainProvenance 'ConfigureOptionNames') -ceq $configureOptionNames -and + (Get-RecordedFingerprint $toolchainProvenance 'X86CpuProfile') -ceq $X86CpuProfile -and (Test-Path -LiteralPath (Join-Path $build 'CMakeCache.txt') -PathType Leaf) if ($keepNativeBuild) { # A moved workspace invalidates every absolute path in the cache; CMake would hard @@ -350,21 +445,14 @@ try { Remove-Item -LiteralPath $build -Recurse -Force } } - $dependencies = Join-Path $Workspace 'Dependencies' - $nativePrebuilt = Resolve-MkwNativePrebuiltDirectory $dependencies $toolchainBin ` - (Join-Path $Workspace 'aurora-main') (Join-Path $Workspace 'runtime\third_party') - if ($X86CpuProfile -eq 'v2') { - Write-Host 'MKWCBUILD: This CPU does not support x86-64-v3; building for x86-64-v2' - } - $configure = Get-MkwNativeConfigureArguments ` - -SourceDirectory (Join-Path $Workspace 'runtime') -BuildDirectory $build ` - -Ninja $ninja -CCompiler $cc -CxxCompiler $cxx -ResourceCompiler $windres ` - -DependenciesDirectory $dependencies -NativePrebuiltDirectory $nativePrebuilt ` - -AdditionalArguments @("-DMKW_TRANSLATED_COMPILE_JOBS=$translatedJobs", "-DMKW_X86_CPU_PROFILE=$X86CpuProfile") Invoke-Checked $cmake $configure 'Configuring the bundled native toolchain' -StepId 'configure-native' - if (-not [string]::IsNullOrWhiteSpace($NativeToolchainFingerprint)) { - [ordered]@{ SchemaVersion = 1; NativeToolchainFingerprint = $NativeToolchainFingerprint } | - ConvertTo-Json | Set-Content -LiteralPath $toolchainProvenance -Encoding UTF8 + if ($shippedFlagsCurrent -and -not [string]::IsNullOrWhiteSpace($NativeToolchainFingerprint)) { + [ordered]@{ + SchemaVersion = 2 + NativeToolchainFingerprint = $NativeToolchainFingerprint + ConfigureOptionNames = $configureOptionNames + X86CpuProfile = $X86CpuProfile + } | ConvertTo-Json | Set-Content -LiteralPath $toolchainProvenance -Encoding UTF8 } $targets = switch ($Profile) { 'base' { @('WiiCompiled') } diff --git a/Launcher/Test-PayloadBoundary.ps1 b/Launcher/Test-PayloadBoundary.ps1 index 79bdc3f7d..49899eca3 100644 --- a/Launcher/Test-PayloadBoundary.ps1 +++ b/Launcher/Test-PayloadBoundary.ps1 @@ -40,4 +40,42 @@ foreach ($file in Get-ChildItem -LiteralPath $PayloadRoot -Recurse -File) { if ($violations.Count -gt 0) { throw "Release payload contains forbidden game-derived or precompiled artifacts:`n$($violations -join "`n")" } -Write-Host "Payload boundary audit passed: no translated game executable, game input, generated shard, or generated data was packaged." + +# Build-Installer.ps1 prunes unused tool payload; the license texts and the x86_64 target runtime +# files must survive it. +$toolkitRoot = Join-Path $PayloadRoot 'Toolkit' +$missingRequired = [Collections.Generic.List[string]]::new() +function Test-RequiredPattern([string]$Directory, [string]$Filter, [string]$Description, [switch]$Directories) { + $found = @() + if (Test-Path -LiteralPath $Directory -PathType Container) { + $found = @(Get-ChildItem -LiteralPath $Directory -Filter $Filter -Force | + Where-Object { $_.PSIsContainer -eq [bool]$Directories }) + if ($Directories) { + $found = @($found | Where-Object { @(Get-ChildItem -LiteralPath $_.FullName -Recurse -File -Force).Count -gt 0 }) + } else { + $found = @($found | Where-Object { $_.Length -gt 0 }) + } + } + if ($found.Count -eq 0) { $missingRequired.Add("$Description ($Directory\$Filter)") } +} +$cmakeDocs = @(Get-ChildItem -LiteralPath (Join-Path $toolkitRoot 'CMake\doc') -Directory -Filter 'cmake*' -ErrorAction SilentlyContinue) +if ($cmakeDocs.Count -eq 0) { $missingRequired.Add('CMake license documentation (Toolkit\CMake\doc\cmake*)') } +foreach ($docs in $cmakeDocs) { + Test-RequiredPattern $docs.FullName 'LICENSE.rst' 'CMake license' + Test-RequiredPattern $docs.FullName 'cm*' 'CMake bundled-library licenses' -Directories +} +$cmakeShares = @(Get-ChildItem -LiteralPath (Join-Path $toolkitRoot 'CMake\share') -Directory -Filter 'cmake-*' -ErrorAction SilentlyContinue) +if ($cmakeShares.Count -eq 0) { $missingRequired.Add('CMake modules (Toolkit\CMake\share\cmake-*)') } +foreach ($share in $cmakeShares) { + Test-RequiredPattern $share.FullName 'Licenses' 'CMake module licenses' -Directories + Test-RequiredPattern $share.FullName 'Modules' 'CMake modules' -Directories +} +$sysroot = Join-Path $toolkitRoot 'llvm-mingw\x86_64-w64-mingw32' +Test-RequiredPattern (Join-Path $toolkitRoot 'llvm-mingw') 'LICENSE.TXT' 'LLVM-MinGW license' +Test-RequiredPattern (Join-Path $sysroot 'share\mingw32') 'COPYING*' 'mingw-w64 licenses' +Test-RequiredPattern (Join-Path $sysroot 'bin') 'libc++.dll' 'x86_64 libc++ runtime' +Test-RequiredPattern (Join-Path $sysroot 'bin') 'libunwind.dll' 'x86_64 libunwind runtime' +if ($missingRequired.Count -gt 0) { + throw "Release payload is missing required license or runtime files:`n$($missingRequired -join "`n")" +} +Write-Host "Payload boundary audit passed: no translated game executable, game input, generated shard, or generated data was packaged; required licenses and target runtimes are present." diff --git a/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs b/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs new file mode 100644 index 000000000..126a70478 --- /dev/null +++ b/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs @@ -0,0 +1,663 @@ +using System.Globalization; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; + +namespace WiiCompiled.Setup.Linux; + +/// +/// The provenance record written after a fully successful Linux install: every input that decides +/// what the installed products contain, and the content of every file the build published. +/// Kept at ~/.local/share/WiiCompiled/product-provenance.json. +/// +internal sealed class ProductProvenanceRecord +{ + public int SchemaVersion { get; set; } + public string Kind { get; set; } = ""; + public Dictionary? Inputs { get; set; } + public List? Outputs { get; set; } +} + +internal sealed class ProductOutputRecord +{ + public string Path { get; set; } = ""; + public long Size { get; set; } + public string Sha256 { get; set; } = ""; +} + +/// Size and whole-second modification time, as stat's %s / %Y report them. +internal readonly record struct FileFacts(long Size, long UnixMtime); + +internal sealed record SyncStateEntry(string Path, string Sha256, long Size, long Mtime); + +/// A parsed .mkw-sync-state written by build-cache.sh's mkw_sync_tree. +internal sealed record SyncState(long Written, IReadOnlyList Directories, IReadOnlyList Entries); + +internal sealed record ManifestEntry(string Sha256, long Size); + +/// +/// Pure decision logic for skipping a rebuild when the installed products are provably current. +/// Every function fails closed: anything missing, malformed or different means "not current". +/// +internal static class ProductCurrency +{ + public const int SchemaVersion = 1; + public const string Kind = "wiicompiled-linux-product-provenance"; + public const string None = ""; + public const string SyncStateHeader = "mkw-sync-state-v1"; + public const string ManifestHeader = "mkw-sync-manifest-v1"; + + /// Exactly the same keys with exactly the same values. + public static bool InputsMatch(IReadOnlyDictionary? recorded, IReadOnlyDictionary? current) + { + if (recorded is null || current is null || current.Count == 0 || recorded.Count != current.Count) return false; + foreach (var (key, value) in current) + { + if (!recorded.TryGetValue(key, out var recordedValue) || + !string.Equals(recordedValue, value, StringComparison.Ordinal)) + return false; + } + return true; + } + + /// + /// True only when the record has this schema, its inputs equal , + /// it covers every , and every recorded output still has its + /// recorded size and SHA-256 according to . + /// + public static bool IsCurrent(ProductProvenanceRecord? recorded, IReadOnlyDictionary? currentInputs, + IEnumerable requiredOutputs, Func observe) + { + if (recorded is null || recorded.SchemaVersion != SchemaVersion || + !string.Equals(recorded.Kind, Kind, StringComparison.Ordinal)) + return false; + if (!InputsMatch(recorded.Inputs, currentInputs)) return false; + if (recorded.Outputs is null || recorded.Outputs.Count == 0) return false; + + var seen = new HashSet(StringComparer.Ordinal); + foreach (var output in recorded.Outputs) + { + if (output is null || string.IsNullOrEmpty(output.Path) || !output.Path.StartsWith('/') || + output.Size < 0 || !IsSha256(output.Sha256) || !seen.Add(output.Path)) + return false; + } + foreach (var required in requiredOutputs) + { + if (!seen.Contains(required)) return false; + } + foreach (var output in recorded.Outputs) + { + var actual = observe(output.Path); + if (actual is null || actual.Value.Size != output.Size || + !string.Equals(actual.Value.Sha256, output.Sha256, StringComparison.Ordinal)) + return false; + } + return true; + } + + public static ProductProvenanceRecord CreateRecord(IReadOnlyDictionary inputs, + IEnumerable outputs) => new() + { + SchemaVersion = SchemaVersion, + Kind = Kind, + Inputs = new Dictionary(inputs, StringComparer.Ordinal), + Outputs = outputs.ToList(), + }; + + /// Parses a sync state with the exact rules build-cache.sh's awk applies, or null. + public static SyncState? ParseSyncState(string text) + { + if (!text.EndsWith('\n')) return null; + var lines = text[..^1].Split('\n'); + if (lines.Length < 4 || lines[0] != SyncStateHeader) return null; + + var written = lines[1].Split('\t'); + if (written.Length != 2 || written[0] != "written" || !TryCount(written[1], out var writtenAt)) return null; + + var dirsLine = lines[2].Split('\t'); + if (dirsLine.Length < 2 || dirsLine[0] != "dirs") return null; + var directories = dirsLine[1..]; + for (var i = 0; i < directories.Length; i++) + { + if (!IsSafeRelativePath(directories[i])) return null; + for (var j = 0; j < directories.Length; j++) + { + // Overlapping directories would let one file count twice. + if (i != j && (directories[i] == directories[j] || + directories[j].StartsWith(directories[i] + "/", StringComparison.Ordinal))) + return null; + } + } + + var end = lines[^1].Split('\t'); + if (end.Length != 2 || end[0] != "end" || !TryCount(end[1], out var count)) return null; + var body = lines[3..^1]; + if (body.Length != count) return null; + + var entries = new List(body.Length); + var paths = new HashSet(StringComparer.Ordinal); + foreach (var line in body) + { + var fields = line.Split('\t', 4); + if (fields.Length != 4 || !IsSha256(fields[0]) || !TryCount(fields[1], out var size) || + !TryCount(fields[2], out var mtime) || !IsSafeRelativePath(fields[3]) || + !directories.Any(directory => fields[3].StartsWith(directory + "/", StringComparison.Ordinal)) || + !paths.Add(fields[3])) + return null; + entries.Add(new SyncStateEntry(fields[3], fields[0], size, mtime)); + } + return new SyncState(writtenAt, directories, entries); + } + + /// Parses a .mkw-sync-manifest / .mkw-toolkit-manifest, or null. + public static IReadOnlyDictionary? ParseManifest(string text) + { + if (!text.EndsWith('\n')) return null; + var lines = text[..^1].Split('\n'); + if (lines.Length < 2 || lines[0] != ManifestHeader) return null; + var end = lines[^1].Split('\t'); + if (end.Length != 2 || end[0] != "end" || !TryCount(end[1], out var count)) return null; + var body = lines[1..^1]; + if (body.Length != count) return null; + + var entries = new Dictionary(StringComparer.Ordinal); + foreach (var line in body) + { + var fields = line.Split('\t', 3); + if (fields.Length != 3 || !IsSha256(fields[0]) || !TryCount(fields[1], out var size) || + !IsSafeRelativePath(fields[2]) || !entries.TryAdd(fields[2], new ManifestEntry(fields[0], size))) + return null; + } + return entries; + } + + /// + /// The content identity of a synced workspace: the hashes its sync state recorded, but only if + /// every recorded file still has its recorded size and mtime and the synced directories hold + /// exactly the recorded files. A file whose mtime is not older than the record itself could + /// have been rewritten within that same second, so it must also still hash to the recorded + /// value. returns null for a missing or non-regular file; + /// returns its SHA-256 or null; returns + /// every non-directory entry under a synced directory as a workspace-relative path, or null + /// when that cannot be listed or holds a link. + /// + public static string? WorkspaceIdentity(SyncState state, Func facts, + Func hashOf, Func?> listFiles) + { + foreach (var entry in state.Entries) + { + var current = facts(entry.Path); + if (current is null || current.Value.Size != entry.Size || current.Value.UnixMtime != entry.Mtime) return null; + if (entry.Mtime >= state.Written && + !string.Equals(hashOf(entry.Path), entry.Sha256, StringComparison.Ordinal)) + return null; + } + + var expected = new HashSet(state.Entries.Select(entry => entry.Path), StringComparer.Ordinal); + var listed = 0; + foreach (var directory in state.Directories) + { + var files = listFiles(directory); + if (files is null) return null; + foreach (var file in files) + { + if (!expected.Contains(file)) return null; + listed++; + } + } + if (listed != expected.Count) return null; + + var identity = new StringBuilder("mkw-workspace-content-v1\n"); + identity.Append("dirs\t").Append(string.Join('\t', state.Directories)).Append('\n'); + foreach (var entry in state.Entries.OrderBy(entry => entry.Path, StringComparer.Ordinal)) + identity.Append(entry.Sha256).Append('\t').Append(entry.Size.ToString(CultureInfo.InvariantCulture)) + .Append('\t').Append(entry.Path).Append('\n'); + return Sha256Hex(Encoding.UTF8.GetBytes(identity.ToString())); + } + + /// + /// The toolkit identity (the manifest's own hash), but only if the manifest is well formed, + /// every listed file still has its listed size, and it lists every required file. + /// + public static string? ToolkitIdentity(byte[] manifestBytes, IEnumerable requiredFiles, Func sizeOf) + { + string text; + try { text = new UTF8Encoding(false, true).GetString(manifestBytes); } + catch (ArgumentException) { return null; } + var manifest = ParseManifest(text); + if (manifest is null) return null; + foreach (var required in requiredFiles) + { + if (!manifest.ContainsKey(required)) return null; + } + foreach (var (path, entry) in manifest) + { + if (sizeOf(path) != entry.Size) return null; + } + return Sha256Hex(manifestBytes); + } + + /// The path of inside , or null. + public static string? RelativeInside(string root, string resolved) + { + var prefix = root.EndsWith('/') ? root : root + "/"; + if (!resolved.StartsWith(prefix, StringComparison.Ordinal) || resolved.Length == prefix.Length) return null; + var relative = resolved[prefix.Length..]; + return IsSafeRelativePath(relative) ? relative : null; + } + + public static bool IsSafeRelativePath(string path) => + path.Length > 0 && path[0] != '/' && path.IndexOfAny(['\\', '\0', '\t', '\n', '\r']) < 0 && + path.Split('/').All(segment => segment.Length > 0 && segment != "." && segment != ".."); + + public static bool IsSha256(string? value) => + value is { Length: 64 } && value.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f'); + + public static string Sha256Hex(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + + private static bool TryCount(string text, out long value) + { + value = 0; + return text.Length > 0 && text.All(char.IsAsciiDigit) && + long.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value); + } +} + +/// Every input the currency check reads, as InstallAsync resolved them. +internal sealed record ProductCurrencyOptions( + string Workspace, + string AssetsDirectory, + string Profile, + IReadOnlyList<(string Directory, string Executable)> Products, + string InstallDirectory, + string? BaseInstallDirectory, + string? RetroDirectory, + string? RetroWfcOfflineDirectory, + bool SkipRetroWfcPayload, + string? TranslatorBin, + string? CcBin, + string? CxxBin, + string? FuseLd, + string? CmakeBin, + string? NinjaBin, + string? NativePrebuiltDir, + string? Sysroot); + +/// +/// File-system side of the currency check. Only a Linux run from a toolkit that ships +/// .mkw-toolkit-manifest (the AppImage) qualifies; everything else always builds. +/// +internal static class ProductCurrencyProbe +{ + public const string ToolkitManifestName = ".mkw-toolkit-manifest"; + public const string SyncStateName = ".mkw-sync-state"; + + // Published beside the executable by local-build.sh's publish_built_product. + private static readonly string[] CompanionFiles = + ["dsp_coef.bin", "initial_pipeline_cache.db", "cacert.pem", "local-build.json"]; + + public static IEnumerable RequiredOutputs(ProductCurrencyOptions options) => + options.Products.Select(product => Path.Combine(product.Directory, product.Executable)); + + /// The current inputs, or null (with a reason) when they cannot all be pinned down. + public static Dictionary? TryCollectInputs(ProductCurrencyOptions options, out string reason) + { + try + { + return CollectInputs(options, out reason); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException + or ArgumentException or NotSupportedException or PlatformNotSupportedException) + { + reason = ex.Message; + return null; + } + } + + private static Dictionary? CollectInputs(ProductCurrencyOptions options, out string reason) + { + if (!OperatingSystem.IsLinux()) { reason = "only Linux installs are checked"; return null; } + if (options.Sysroot is not null) { reason = "--sysroot contents are not tracked"; return null; } + + // The AppImage runs this from /usr/bin, and its manifest sits at . + var resolvedRoot = RealPath(Path.Combine(AppContext.BaseDirectory, "..", "..")); + if (resolvedRoot is null) { reason = "no toolkit manifest"; return null; } + string toolkitRoot = resolvedRoot; + var manifestPath = Path.Combine(toolkitRoot, ToolkitManifestName); + if (!File.Exists(manifestPath)) { reason = "no toolkit manifest"; return null; } + + var inputs = new Dictionary(StringComparer.Ordinal); + var required = new List(); + string? ToolkitFile(string key, string? path) + { + if (string.IsNullOrEmpty(path)) return null; + var resolved = RealPath(path); + var relative = resolved is null || !File.Exists(resolved) ? null : ProductCurrency.RelativeInside(toolkitRoot, resolved); + if (relative is null) return null; + required.Add(relative); + inputs[key] = relative; + return relative; + } + + if (ToolkitFile("setup.executable", Environment.ProcessPath) is null || + ToolkitFile("tool.translator", options.TranslatorBin) is null || + ToolkitFile("tool.cc", options.CcBin) is null || + ToolkitFile("tool.cxx", options.CxxBin) is null || + ToolkitFile("tool.cmake", options.CmakeBin) is null || + ToolkitFile("tool.ninja", options.NinjaBin) is null) + { + reason = "a build tool is not part of the toolkit"; + return null; + } + + if (string.IsNullOrEmpty(options.FuseLd)) + inputs["tool.fuse-ld"] = ProductCurrency.None; + else if (!options.FuseLd.Contains('/')) + inputs["tool.fuse-ld"] = "name:" + options.FuseLd; + else if (ToolkitFile("tool.fuse-ld", options.FuseLd) is { } linker) + inputs["tool.fuse-ld"] = "path:" + linker; + else { reason = "the linker is not part of the toolkit"; return null; } + + if (string.IsNullOrEmpty(options.NativePrebuiltDir)) + inputs["tool.native-prebuilt"] = ProductCurrency.None; + else + { + var resolved = RealPath(options.NativePrebuiltDir); + var relative = resolved is null || !Directory.Exists(resolved) ? null : ProductCurrency.RelativeInside(toolkitRoot, resolved); + if (relative is null) { reason = "the native prebuilt package is not part of the toolkit"; return null; } + inputs["tool.native-prebuilt"] = relative; + } + + var toolkit = ProductCurrency.ToolkitIdentity(File.ReadAllBytes(manifestPath), required, + relative => SizeOf(Path.Combine(toolkitRoot, relative))); + if (toolkit is null) { reason = "the toolkit does not match its manifest"; return null; } + inputs["toolkit.content"] = toolkit; + + var workspace = Path.GetFullPath(options.Workspace); + var stateText = ReadIfExists(Path.Combine(workspace, SyncStateName)); + var state = stateText is null ? null : ProductCurrency.ParseSyncState(stateText); + var workspaceIdentity = state is null ? null : ProductCurrency.WorkspaceIdentity(state, + relative => Facts(Path.Combine(workspace, relative)), + relative => Observe(Path.Combine(workspace, relative))?.Sha256, + directory => ListFiles(workspace, directory)); + if (workspaceIdentity is null) { reason = "the workspace no longer matches its last sync"; return null; } + inputs["workspace.path"] = workspace; + inputs["workspace.content"] = workspaceIdentity; + + inputs["setup.version"] = ProductInfo.Version; + inputs["host.rid"] = RuntimeInformation.RuntimeIdentifier; + inputs["host.architecture"] = RuntimeInformation.OSArchitecture.ToString(); + inputs["host.x86-cpu-profile"] = HostCpuRequirement.SelectBuildProfile().ToString(); + + inputs["profile"] = options.Profile; + inputs["install.dir"] = Path.GetFullPath(options.InstallDirectory); + inputs["install.base-dir"] = options.BaseInstallDirectory is null ? ProductCurrency.None : Path.GetFullPath(options.BaseInstallDirectory); + inputs["assets.main-dol.sha256"] = Sha256Of(Path.Combine(options.AssetsDirectory, "main.dol")); + inputs["assets.static-rel.sha256"] = Sha256Of(Path.Combine(options.AssetsDirectory, "StaticR.rel")); + + if (string.IsNullOrEmpty(options.RetroDirectory)) + { + inputs["retro.dir"] = ProductCurrency.None; + } + else + { + var retro = Path.GetFullPath(options.RetroDirectory); + inputs["retro.dir"] = retro; + inputs["retro.code-pul.sha256"] = Sha256Of(Path.Combine(retro, "Binaries", "Code.pul")); + // The translator mounts the pack root and its files/ folder as DVD overlays. + inputs["retro.files-dir"] = Directory.Exists(Path.Combine(retro, "files")) ? "present" : "absent"; + if (options.SkipRetroWfcPayload) + { + inputs["retro.wfc"] = "skip"; + } + else + { + if (string.IsNullOrEmpty(options.RetroWfcOfflineDirectory)) { reason = "no Retro-WFC payload"; return null; } + var payload = DirectoryDigest(options.RetroWfcOfflineDirectory); + if (payload is null) { reason = "the Retro-WFC payload cannot be read"; return null; } + inputs["retro.wfc"] = "payload:" + payload; + } + } + + reason = ""; + return inputs; + } + + /// Every file the build published for 's products, or null. + public static List? TryCollectOutputs(ProductCurrencyOptions options) + { + try + { + var outputs = new List(); + foreach (var (directory, executable) in options.Products) + { + if (!AddOutput(outputs, Path.Combine(directory, executable))) return null; + foreach (var companion in CompanionFiles) + { + var path = Path.Combine(directory, companion); + if (File.Exists(path) && !AddOutput(outputs, path)) return null; + } + var bootstrap = Path.Combine(directory, "wii_bootstrap"); + if (Directory.Exists(bootstrap)) + { + var files = ListFiles(directory, "wii_bootstrap"); + if (files is null) return null; + foreach (var file in files.Order(StringComparer.Ordinal)) + { + if (!AddOutput(outputs, Path.Combine(directory, file))) return null; + } + } + } + return outputs; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + /// Size and SHA-256 of a regular, non-link file, or null. + public static (long Size, string Sha256)? Observe(string path) + { + try + { + var info = new FileInfo(path); + if (!info.Exists || info.LinkTarget is not null) return null; + using var stream = File.OpenRead(path); + var sha = Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); + return (stream.Length, sha); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + /// Removes the record before a build, so a failed or interrupted build never leaves one. + public static void DeleteRecord(string recordPath, IInstallReporter? reporter) + { + try + { + if (File.Exists(recordPath)) File.Delete(recordPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + reporter?.Diagnostic($"Could not remove the product provenance record ({ex.Message.TrimEnd('.')})."); + } + } + + /// + /// Records the products just built, but only when the inputs read again now still equal the + /// ones read before the build. Never fails the install; without a record the next run builds. + /// + public static void TryRecord(string recordPath, ProductCurrencyOptions options, + IReadOnlyDictionary inputsBeforeBuild, IInstallReporter reporter) + { + try + { + var inputsAfterBuild = TryCollectInputs(options, out _); + if (!ProductCurrency.InputsMatch(inputsBeforeBuild, inputsAfterBuild)) return; + var outputs = TryCollectOutputs(options); + if (outputs is null || outputs.Count == 0) return; + JsonState.Write(recordPath, ProductCurrency.CreateRecord(inputsBeforeBuild, outputs)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException + or ArgumentException or NotSupportedException) + { + reporter.Diagnostic($"Could not record the product provenance ({ex.Message.TrimEnd('.')})."); + } + } + + /// + /// realpath(3) in managed code: resolves every symbolic link component. Null when the path does + /// not exist or cannot be resolved. + /// + public static string? RealPath(string path) + { + try + { + var full = Path.IsPathRooted(path) ? path : Path.Combine(Directory.GetCurrentDirectory(), path); + full = full.Replace('\\', '/'); + if (!full.StartsWith('/')) return null; + var remaining = new LinkedList(full.Split('/', StringSplitOptions.RemoveEmptyEntries)); + var current = "/"; + var links = 0; + while (remaining.First is { } first) + { + var part = first.Value; + remaining.RemoveFirst(); + if (part == ".") continue; + if (part == "..") + { + current = Path.GetDirectoryName(current)?.Replace('\\', '/') is { Length: > 0 } parent ? parent : "/"; + continue; + } + var candidate = current == "/" ? "/" + part : current + "/" + part; + var target = new FileInfo(candidate).LinkTarget; + if (target is not null) + { + if (++links > 40) return null; + var targetParts = target.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries); + for (var i = targetParts.Length - 1; i >= 0; i--) remaining.AddFirst(targetParts[i]); + if (target.StartsWith('/')) current = "/"; + continue; + } + if (!File.Exists(candidate) && !Directory.Exists(candidate)) return null; + current = candidate; + } + return current; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + /// Size and whole-second mtime of a regular, non-link file, or null. + public static FileFacts? Facts(string path) + { + try + { + var info = new FileInfo(path); + if (!info.Exists || info.LinkTarget is not null) return null; + return new FileFacts(info.Length, new DateTimeOffset(info.LastWriteTimeUtc).ToUnixTimeSeconds()); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + /// + /// Every non-directory entry under /, as + /// '/'-separated paths relative to . Empty for a missing directory; + /// null when anything is a link or cannot be read. + /// + public static IReadOnlyCollection? ListFiles(string root, string directory) + { + try + { + var top = new DirectoryInfo(Path.Combine(root, directory)); + if (top.LinkTarget is not null) return null; + if (!top.Exists) return File.Exists(top.FullName) ? null : Array.Empty(); + var files = new List(); + var options = new EnumerationOptions + { + RecurseSubdirectories = true, + AttributesToSkip = 0, + IgnoreInaccessible = false, + ReturnSpecialDirectories = false, + }; + foreach (var entry in top.EnumerateFileSystemInfos("*", options)) + { + if (entry.LinkTarget is not null) return null; + if (entry is DirectoryInfo) continue; + files.Add(Path.GetRelativePath(root, entry.FullName).Replace('\\', '/')); + } + return files; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + /// Digest of every file (path, size, SHA-256) under a directory, or null. + public static string? DirectoryDigest(string directory) + { + var full = Path.GetFullPath(directory); + var files = ListFiles(Path.GetDirectoryName(full) ?? full, Path.GetFileName(full)); + if (files is null || !Directory.Exists(full)) return null; + var digest = new StringBuilder("mkw-directory-v1\n"); + var parent = Path.GetDirectoryName(full) ?? full; + foreach (var file in files.Order(StringComparer.Ordinal)) + { + var observed = Observe(Path.Combine(parent, file)); + if (observed is null) return null; + digest.Append(observed.Value.Sha256).Append('\t') + .Append(observed.Value.Size.ToString(CultureInfo.InvariantCulture)).Append('\t') + .Append(file).Append('\n'); + } + return ProductCurrency.Sha256Hex(Encoding.UTF8.GetBytes(digest.ToString())); + } + + private static bool AddOutput(List outputs, string path) + { + var full = Path.GetFullPath(path); + var observed = Observe(full); + if (observed is null) return false; + outputs.Add(new ProductOutputRecord { Path = full, Size = observed.Value.Size, Sha256 = observed.Value.Sha256 }); + return true; + } + + private static long? SizeOf(string path) + { + try + { + var info = new FileInfo(path); + return info.Exists && info.LinkTarget is null ? info.Length : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + private static string? ReadIfExists(string path) + { + try + { + return File.Exists(path) ? File.ReadAllText(path, new UTF8Encoding(false, true)) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + private static string Sha256Of(string path) + { + using var stream = File.OpenRead(path); + return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); + } +} diff --git a/Launcher/WiiCompiled.Setup.Linux/ProductCurrencySelfTest.cs b/Launcher/WiiCompiled.Setup.Linux/ProductCurrencySelfTest.cs new file mode 100644 index 000000000..592247afc --- /dev/null +++ b/Launcher/WiiCompiled.Setup.Linux/ProductCurrencySelfTest.cs @@ -0,0 +1,349 @@ +using System.Text; + +namespace WiiCompiled.Setup.Linux; + +/// +/// `wiicompiled-setup self-test`: checks the product-currency match logic without a game, a build +/// or a toolchain. `--sync-state-workspace DIR` additionally validates a real .mkw-sync-state that +/// build-cache.sh's mkw_sync_tree wrote into DIR. Exit code 0 only when every check passes. +/// +internal static class ProductCurrencySelfTest +{ + private const string ShaA = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private const string ShaB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + + private static int _failures; + private static int _passes; + + public static int Run(string? syncStateWorkspace) + { + _failures = _passes = 0; + InputsMatchCases(); + IsCurrentCases(); + SyncStateCases(); + WorkspaceIdentityCases(); + ManifestCases(); + RelativeInsideCases(); + FileSystemCases(); + if (!OperatingSystem.IsWindows()) RealPathCases(); + if (!string.IsNullOrEmpty(syncStateWorkspace)) RealSyncStateCase(syncStateWorkspace); + Console.WriteLine($"{_passes} passed, {_failures} failed"); + return _failures == 0 ? 0 : 1; + } + + private static void Check(string name, bool condition) + { + if (condition) _passes++; + else _failures++; + Console.WriteLine($"{(condition ? "PASS" : "FAIL")} {name}"); + } + + private static Dictionary Inputs(params (string Key, string Value)[] pairs) => + pairs.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal); + + private static void InputsMatchCases() + { + var current = Inputs(("a", "1"), ("b", "2")); + Check("inputs: identical match", ProductCurrency.InputsMatch(Inputs(("b", "2"), ("a", "1")), current)); + Check("inputs: changed value", !ProductCurrency.InputsMatch(Inputs(("a", "1"), ("b", "3")), current)); + Check("inputs: extra recorded key", !ProductCurrency.InputsMatch(Inputs(("a", "1"), ("b", "2"), ("c", "3")), current)); + Check("inputs: missing recorded key", !ProductCurrency.InputsMatch(Inputs(("a", "1")), current)); + Check("inputs: renamed key", !ProductCurrency.InputsMatch(Inputs(("a", "1"), ("B", "2")), current)); + Check("inputs: null record", !ProductCurrency.InputsMatch(null, current)); + Check("inputs: null current", !ProductCurrency.InputsMatch(current, null)); + Check("inputs: both empty", !ProductCurrency.InputsMatch(Inputs(), Inputs())); + Check("inputs: case-sensitive value", !ProductCurrency.InputsMatch(Inputs(("a", "X"), ("b", "2")), Inputs(("a", "x"), ("b", "2")))); + } + + private static ProductProvenanceRecord Record(params ProductOutputRecord[] outputs) => + ProductCurrency.CreateRecord(Inputs(("a", "1")), outputs); + + private static void IsCurrentCases() + { + var exe = new ProductOutputRecord { Path = "/i/WiiCompiled", Size = 10, Sha256 = ShaA }; + var pem = new ProductOutputRecord { Path = "/i/cacert.pem", Size = 3, Sha256 = ShaB }; + var disk = new Dictionary(StringComparer.Ordinal) + { + ["/i/WiiCompiled"] = (10, ShaA), + ["/i/cacert.pem"] = (3, ShaB), + }; + (long Size, string Sha256)? Observe(string path) => disk.TryGetValue(path, out var value) ? value : null; + var inputs = Inputs(("a", "1")); + string[] required = ["/i/WiiCompiled"]; + + Check("current: everything matches", ProductCurrency.IsCurrent(Record(exe, pem), inputs, required, Observe)); + Check("current: no record", !ProductCurrency.IsCurrent(null, inputs, required, Observe)); + Check("current: no current inputs", !ProductCurrency.IsCurrent(Record(exe, pem), null, required, Observe)); + Check("current: inputs changed", !ProductCurrency.IsCurrent(Record(exe, pem), Inputs(("a", "2")), required, Observe)); + + var oldSchema = Record(exe, pem); oldSchema.SchemaVersion = 0; + Check("current: old schema", !ProductCurrency.IsCurrent(oldSchema, inputs, required, Observe)); + var otherKind = Record(exe, pem); otherKind.Kind = "something-else"; + Check("current: other kind", !ProductCurrency.IsCurrent(otherKind, inputs, required, Observe)); + var noInputs = Record(exe, pem); noInputs.Inputs = null; + Check("current: record without inputs", !ProductCurrency.IsCurrent(noInputs, inputs, required, Observe)); + var noOutputs = Record(exe, pem); noOutputs.Outputs = null; + Check("current: record without outputs", !ProductCurrency.IsCurrent(noOutputs, inputs, required, Observe)); + Check("current: empty outputs", !ProductCurrency.IsCurrent(Record(), inputs, Array.Empty(), Observe)); + Check("current: executable not recorded", !ProductCurrency.IsCurrent(Record(pem), inputs, required, Observe)); + Check("current: duplicate output", !ProductCurrency.IsCurrent(Record(exe, exe), inputs, required, Observe)); + Check("current: relative output path", !ProductCurrency.IsCurrent( + Record(new ProductOutputRecord { Path = "i/WiiCompiled", Size = 10, Sha256 = ShaA }), inputs, Array.Empty(), Observe)); + Check("current: malformed recorded hash", !ProductCurrency.IsCurrent( + Record(new ProductOutputRecord { Path = "/i/WiiCompiled", Size = 10, Sha256 = "AAAA" }), inputs, required, Observe)); + + disk["/i/WiiCompiled"] = (10, ShaB); + Check("current: executable content changed", !ProductCurrency.IsCurrent(Record(exe, pem), inputs, required, Observe)); + disk["/i/WiiCompiled"] = (11, ShaA); + Check("current: executable size changed", !ProductCurrency.IsCurrent(Record(exe, pem), inputs, required, Observe)); + disk["/i/WiiCompiled"] = (10, ShaA); + disk.Remove("/i/cacert.pem"); + Check("current: companion deleted", !ProductCurrency.IsCurrent(Record(exe, pem), inputs, required, Observe)); + } + + private static string State(long written, string dirs, params string[] entries) + { + var text = new StringBuilder("mkw-sync-state-v1\n").Append("written\t").Append(written).Append('\n') + .Append("dirs\t").Append(dirs).Append('\n'); + foreach (var entry in entries) text.Append(entry).Append('\n'); + return text.Append("end\t").Append(entries.Length).Append('\n').ToString(); + } + + private static void SyncStateCases() + { + var valid = State(1000, "runtime\tprojects", $"{ShaA}\t5\t900\truntime/a b.cpp", $"{ShaB}\t7\t901\tprojects/x/recomp.yml"); + var parsed = ProductCurrency.ParseSyncState(valid); + Check("state: valid state parses", parsed is { Written: 1000, Entries.Count: 2, Directories.Count: 2 } && + parsed.Entries[0].Path == "runtime/a b.cpp" && parsed.Entries[0].Size == 5 && + parsed.Entries[0].Mtime == 900); + Check("state: empty state parses", ProductCurrency.ParseSyncState(State(5, "runtime")) is { Entries.Count: 0 }); + Check("state: missing trailing newline", ProductCurrency.ParseSyncState(valid[..^1]) is null); + Check("state: truncated (no end line)", ProductCurrency.ParseSyncState(string.Join('\n', valid.Split('\n')[..4]) + "\n") is null); + Check("state: count mismatch", ProductCurrency.ParseSyncState(valid.Replace("end\t2", "end\t3")) is null); + Check("state: old header", ProductCurrency.ParseSyncState(valid.Replace("mkw-sync-state-v1", "mkw-sync-state-v0")) is null); + Check("state: empty file", ProductCurrency.ParseSyncState("") is null); + Check("state: bad written", ProductCurrency.ParseSyncState(valid.Replace("written\t1000", "written\t-1")) is null); + Check("state: bad hash", ProductCurrency.ParseSyncState(State(1000, "runtime", $"{ShaA[..63]}\t5\t900\truntime/a")) is null); + Check("state: uppercase hash", ProductCurrency.ParseSyncState(State(1000, "runtime", $"{ShaA.ToUpperInvariant()}\t5\t900\truntime/a")) is null); + Check("state: bad size", ProductCurrency.ParseSyncState(State(1000, "runtime", $"{ShaA}\t5x\t900\truntime/a")) is null); + Check("state: path outside dirs", ProductCurrency.ParseSyncState(State(1000, "runtime", $"{ShaA}\t5\t900\tother/a")) is null); + Check("state: parent traversal", ProductCurrency.ParseSyncState(State(1000, "runtime", $"{ShaA}\t5\t900\truntime/../x")) is null); + Check("state: duplicate path", ProductCurrency.ParseSyncState(State(1000, "runtime", $"{ShaA}\t5\t900\truntime/a", $"{ShaB}\t5\t900\truntime/a")) is null); + Check("state: overlapping dirs", ProductCurrency.ParseSyncState(State(1000, "runtime\truntime/src")) is null); + Check("state: no dirs", ProductCurrency.ParseSyncState("mkw-sync-state-v1\nwritten\t1\ndirs\nend\t0\n") is null); + Check("state: CRLF rejected", ProductCurrency.ParseSyncState(valid.Replace("\n", "\r\n")) is null); + } + + private static void WorkspaceIdentityCases() + { + var state = ProductCurrency.ParseSyncState(State(1000, "runtime\tprojects", + $"{ShaA}\t5\t900\truntime/a", $"{ShaB}\t7\t901\tprojects/b"))!; + var facts = new Dictionary(StringComparer.Ordinal) + { + ["runtime/a"] = new(5, 900), + ["projects/b"] = new(7, 901), + }; + var listing = new Dictionary>(StringComparer.Ordinal) + { + ["runtime"] = ["runtime/a"], + ["projects"] = ["projects/b"], + }; + var hashes = new Dictionary(StringComparer.Ordinal) + { + ["runtime/a"] = ShaA, + ["projects/b"] = ShaB, + }; + var hashCalls = 0; + FileFacts? Facts(string path) => facts.TryGetValue(path, out var value) ? value : null; + string? Hash(string path) { hashCalls++; return hashes.TryGetValue(path, out var value) ? value : null; } + IReadOnlyCollection? List(string directory) => listing.TryGetValue(directory, out var value) ? value : null; + + var identity = ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List); + Check("workspace: untouched workspace has an identity", identity is { Length: 64 }); + Check("workspace: settled files are not re-hashed", hashCalls == 0); + var reordered = ProductCurrency.ParseSyncState(State(2000, "runtime\tprojects", + $"{ShaB}\t7\t901\tprojects/b", $"{ShaA}\t5\t900\truntime/a"))!; + Check("workspace: identity ignores entry order and record time", + ProductCurrency.WorkspaceIdentity(reordered, Facts, Hash, List) == identity); + var otherContent = ProductCurrency.ParseSyncState(State(1000, "runtime\tprojects", + $"{ShaB}\t5\t900\truntime/a", $"{ShaB}\t7\t901\tprojects/b"))!; + Check("workspace: identity follows content", ProductCurrency.WorkspaceIdentity(otherContent, Facts, Hash, List) != identity); + + facts["runtime/a"] = new(6, 900); + Check("workspace: size changed", ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List) is null); + facts["runtime/a"] = new(5, 950); + Check("workspace: mtime changed", ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List) is null); + facts.Remove("runtime/a"); + Check("workspace: file deleted", ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List) is null); + facts["runtime/a"] = new(5, 900); + + listing["runtime"] = ["runtime/a", "runtime/new.cpp"]; + Check("workspace: extra file", ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List) is null); + listing["runtime"] = []; + Check("workspace: file missing from listing", ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List) is null); + listing.Remove("runtime"); + Check("workspace: unlistable directory", ProductCurrency.WorkspaceIdentity(state, Facts, Hash, List) is null); + listing["runtime"] = ["runtime/a"]; + + // runtime/a was written in the record's own second, so only its content can vouch for it. + var racy = ProductCurrency.ParseSyncState(State(900, "runtime\tprojects", + $"{ShaA}\t5\t900\truntime/a", $"{ShaB}\t7\t899\tprojects/b"))!; + facts["projects/b"] = new(7, 899); + hashCalls = 0; + Check("workspace: same-second file with recorded content is trusted", + ProductCurrency.WorkspaceIdentity(racy, Facts, Hash, List) is not null && hashCalls == 1); + hashes["runtime/a"] = ShaB; + Check("workspace: same-second file rewritten with same size and mtime", + ProductCurrency.WorkspaceIdentity(racy, Facts, Hash, List) is null); + hashes.Remove("runtime/a"); + Check("workspace: same-second file unreadable", ProductCurrency.WorkspaceIdentity(racy, Facts, Hash, List) is null); + } + + private static string Manifest(params string[] entries) + { + var text = new StringBuilder("mkw-sync-manifest-v1\n"); + foreach (var entry in entries) text.Append(entry).Append('\n'); + return text.Append("end\t").Append(entries.Length).Append('\n').ToString(); + } + + private static void ManifestCases() + { + var text = Manifest($"{ShaA}\t5\tusr/bin/wiicompiled-setup", $"{ShaB}\t7\tusr/toolchain/bin/clang-18"); + var bytes = Encoding.UTF8.GetBytes(text); + var sizes = new Dictionary(StringComparer.Ordinal) + { + ["usr/bin/wiicompiled-setup"] = 5, + ["usr/toolchain/bin/clang-18"] = 7, + }; + long? SizeOf(string path) => sizes.TryGetValue(path, out var size) ? size : null; + + Check("manifest: parses", ProductCurrency.ParseManifest(text) is { Count: 2 }); + Check("manifest: empty manifest parses", ProductCurrency.ParseManifest(Manifest()) is { Count: 0 }); + Check("manifest: count mismatch", ProductCurrency.ParseManifest(text.Replace("end\t2", "end\t1")) is null); + Check("manifest: duplicate path", ProductCurrency.ParseManifest(Manifest($"{ShaA}\t5\ta", $"{ShaB}\t5\ta")) is null); + Check("manifest: wrong header", ProductCurrency.ParseManifest(text.Replace("manifest-v1", "manifest-v2")) is null); + + var identity = ProductCurrency.ToolkitIdentity(bytes, ["usr/bin/wiicompiled-setup"], SizeOf); + Check("toolkit: identity is the manifest hash", identity == ProductCurrency.Sha256Hex(bytes)); + Check("toolkit: required tool not listed", ProductCurrency.ToolkitIdentity(bytes, ["usr/bin/other"], SizeOf) is null); + sizes["usr/toolchain/bin/clang-18"] = 8; + Check("toolkit: listed file changed size", ProductCurrency.ToolkitIdentity(bytes, [], SizeOf) is null); + sizes.Remove("usr/toolchain/bin/clang-18"); + Check("toolkit: listed file missing", ProductCurrency.ToolkitIdentity(bytes, [], SizeOf) is null); + Check("toolkit: malformed manifest", ProductCurrency.ToolkitIdentity(Encoding.UTF8.GetBytes("junk\n"), [], SizeOf) is null); + Check("toolkit: invalid UTF-8", ProductCurrency.ToolkitIdentity([0xff, 0xfe, 0x0a], [], SizeOf) is null); + } + + private static void RelativeInsideCases() + { + Check("inside: nested file", ProductCurrency.RelativeInside("/mnt/app", "/mnt/app/usr/bin/x") == "usr/bin/x"); + Check("inside: sibling with shared prefix", ProductCurrency.RelativeInside("/mnt/app", "/mnt/app2/usr/bin/x") is null); + Check("inside: the root itself", ProductCurrency.RelativeInside("/mnt/app", "/mnt/app") is null); + Check("inside: outside", ProductCurrency.RelativeInside("/mnt/app", "/usr/bin/clang") is null); + Check("inside: root with trailing slash", ProductCurrency.RelativeInside("/mnt/app/", "/mnt/app/x") == "x"); + } + + private static void FileSystemCases() + { + var root = Path.Combine(Path.GetTempPath(), "wiicompiled-selftest-" + Guid.NewGuid().ToString("N")); + try + { + Directory.CreateDirectory(Path.Combine(root, "runtime", "sub")); + File.WriteAllText(Path.Combine(root, "runtime", "a.cpp"), "alpha"); + File.WriteAllText(Path.Combine(root, "runtime", "sub", "b.h"), "beta!!"); + var old = DateTime.UtcNow.AddMinutes(-5); + File.SetLastWriteTimeUtc(Path.Combine(root, "runtime", "a.cpp"), old); + File.SetLastWriteTimeUtc(Path.Combine(root, "runtime", "sub", "b.h"), old); + var mtime = new DateTimeOffset(old).ToUnixTimeSeconds(); + var written = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var stateText = State(written, "runtime", + $"{ShaA}\t5\t{mtime}\truntime/a.cpp", $"{ShaB}\t6\t{mtime}\truntime/sub/b.h"); + var state = ProductCurrency.ParseSyncState(stateText)!; + string? IdentityOf(SyncState syncState) => ProductCurrency.WorkspaceIdentity(syncState, + relative => ProductCurrencyProbe.Facts(Path.Combine(root, relative)), + relative => ProductCurrencyProbe.Observe(Path.Combine(root, relative))?.Sha256, + directory => ProductCurrencyProbe.ListFiles(root, directory)); + string? Identity() => IdentityOf(state); + + // Recorded in the files' own second: trusted only because their bytes still hash right. + var alpha = ProductCurrency.Sha256Hex(Encoding.UTF8.GetBytes("alpha")); + var beta = ProductCurrency.Sha256Hex(Encoding.UTF8.GetBytes("beta!!")); + var sameSecond = ProductCurrency.ParseSyncState(State(mtime, "runtime", + $"{alpha}\t5\t{mtime}\truntime/a.cpp", $"{beta}\t6\t{mtime}\truntime/sub/b.h"))!; + Check("fs: same-second files with recorded content", IdentityOf(sameSecond) is not null); + var sameSecondWrong = ProductCurrency.ParseSyncState(State(mtime, "runtime", + $"{ShaA}\t5\t{mtime}\truntime/a.cpp", $"{beta}\t6\t{mtime}\truntime/sub/b.h"))!; + Check("fs: same-second file with other content", IdentityOf(sameSecondWrong) is null); + + Check("fs: listing finds nested files", + ProductCurrencyProbe.ListFiles(root, "runtime") is { Count: 2 } list && list.Contains("runtime/sub/b.h")); + Check("fs: missing directory lists empty", ProductCurrencyProbe.ListFiles(root, "absent") is { Count: 0 }); + Check("fs: untouched workspace has an identity", Identity() is not null); + + File.AppendAllText(Path.Combine(root, "runtime", "a.cpp"), "!"); + Check("fs: edited file invalidates", Identity() is null); + File.WriteAllText(Path.Combine(root, "runtime", "a.cpp"), "alpha"); + File.SetLastWriteTimeUtc(Path.Combine(root, "runtime", "a.cpp"), old); + Check("fs: restored file is trusted again", Identity() is not null); + + File.WriteAllText(Path.Combine(root, "runtime", "sub", "new.cpp"), "x"); + Check("fs: added file invalidates", Identity() is null); + File.Delete(Path.Combine(root, "runtime", "sub", "new.cpp")); + + File.WriteAllText(Path.Combine(root, "runtime", "sub", "b.h"), "BETA!!"); + Check("fs: same-size edit with a new mtime invalidates", Identity() is null); + + var observed = ProductCurrencyProbe.Observe(Path.Combine(root, "runtime", "a.cpp")); + Check("fs: observe hashes content", observed is { Size: 5 } o && + o.Sha256 == ProductCurrency.Sha256Hex(Encoding.UTF8.GetBytes("alpha"))); + Check("fs: observe missing file", ProductCurrencyProbe.Observe(Path.Combine(root, "nope")) is null); + + var before = ProductCurrencyProbe.DirectoryDigest(Path.Combine(root, "runtime")); + File.AppendAllText(Path.Combine(root, "runtime", "sub", "b.h"), "x"); + Check("fs: directory digest follows content", + before is not null && before != ProductCurrencyProbe.DirectoryDigest(Path.Combine(root, "runtime"))); + } + finally + { + try { Directory.Delete(root, recursive: true); } catch (IOException) { } + } + } + + private static void RealPathCases() + { + var root = Path.Combine(Path.GetTempPath(), "wiicompiled-selftest-" + Guid.NewGuid().ToString("N")); + try + { + Directory.CreateDirectory(Path.Combine(root, "real", "bin")); + File.WriteAllText(Path.Combine(root, "real", "bin", "clang-18"), "x"); + File.CreateSymbolicLink(Path.Combine(root, "real", "bin", "clang"), "clang-18"); + Directory.CreateSymbolicLink(Path.Combine(root, "link"), Path.Combine(root, "real")); + var realRoot = ProductCurrencyProbe.RealPath(root); + Check("realpath: resolves directory and file links", + realRoot is not null && + ProductCurrencyProbe.RealPath(Path.Combine(root, "link", "bin", "clang")) == realRoot + "/real/bin/clang-18"); + Check("realpath: resolves parent after a link", + ProductCurrencyProbe.RealPath(Path.Combine(root, "link", "bin", "..", "bin", "clang-18")) == realRoot + "/real/bin/clang-18"); + Check("realpath: missing path", ProductCurrencyProbe.RealPath(Path.Combine(root, "link", "nope")) is null); + Check("fs: listing refuses links", ProductCurrencyProbe.ListFiles(root, "real") is null); + } + finally + { + try { Directory.Delete(root, recursive: true); } catch (IOException) { } + } + } + + private static void RealSyncStateCase(string workspace) + { + var path = Path.Combine(workspace, ProductCurrencyProbe.SyncStateName); + var state = File.Exists(path) ? ProductCurrency.ParseSyncState(File.ReadAllText(path)) : null; + Check($"real state: {path} parses", state is not null); + if (state is null) return; + var identity = ProductCurrency.WorkspaceIdentity(state, + relative => ProductCurrencyProbe.Facts(Path.Combine(workspace, relative)), + relative => ProductCurrencyProbe.Observe(Path.Combine(workspace, relative))?.Sha256, + directory => ProductCurrencyProbe.ListFiles(workspace, directory)); + Check($"real state: workspace matches its sync state ({state.Entries.Count} files)", identity is not null); + if (identity is not null) Console.WriteLine($"workspace identity {identity}"); + } +} diff --git a/Launcher/WiiCompiled.Setup.Linux/Program.cs b/Launcher/WiiCompiled.Setup.Linux/Program.cs index 3eea85ba5..6ca4eacae 100644 --- a/Launcher/WiiCompiled.Setup.Linux/Program.cs +++ b/Launcher/WiiCompiled.Setup.Linux/Program.cs @@ -50,6 +50,9 @@ private static async Task RunAsync(string[] args, CancellationTokenSource c case "check-products": CheckProducts(); break; + case "self-test": + // Not listed in the usage text: a maintainer check of the product-currency logic. + return ProductCurrencySelfTest.Run(flags.GetValueOrDefault("sync-state-workspace")); default: Console.Error.WriteLine($"Unknown command: {command}"); PrintUsage(); @@ -177,12 +180,14 @@ downloadFailure is HttpRequestException or TimeoutException throw new ArgumentException("--sysroot requires a non-empty directory path."); } - await BuildRunner.RunAsync( - workspace, profile, installDir, baseInstallDir, - retroDir, - retroWfcOfflineDir, - skipPayload, - flags.ContainsKey("force-clean-build"), + var forceCleanBuild = flags.ContainsKey("force-clean-build"); + var products = profiles + .Select(p => (Directory: p == "base" ? (baseInstallDir ?? installDir) : installDir, + Executable: p == "base" ? "WiiCompiled" : "RetroRewind")) + .ToList(); + var currency = new ProductCurrencyOptions( + workspace, assetsDir, profile, products, installDir, baseInstallDir, + retroDir, retroWfcOfflineDir, skipPayload, flags.GetValueOrDefault("translator-bin"), flags.GetValueOrDefault("cc"), flags.GetValueOrDefault("cxx"), @@ -190,8 +195,46 @@ await BuildRunner.RunAsync( flags.GetValueOrDefault("cmake"), flags.GetValueOrDefault("ninja"), flags.GetValueOrDefault("native-prebuilt-dir"), - sysroot, - reporter, token); + sysroot); + + // Linux AppImage fast path: skip the build only when the recorded inputs and outputs of the + // last fully successful install match exactly. Anything missing or different builds as usual. + // A forced clean build never skips, but still records what it built. + Dictionary? currentInputs = null; + var productsCurrent = false; + if (OperatingSystem.IsLinux()) + { + currentInputs = ProductCurrencyProbe.TryCollectInputs(currency, out var notTrackedReason); + if (currentInputs is null) + reporter.Diagnostic($"Building: the installed products cannot be checked ({notTrackedReason})."); + else if (!forceCleanBuild) + productsCurrent = ProductCurrency.IsCurrent(JsonState.TryRead(ProvenancePath), + currentInputs, ProductCurrencyProbe.RequiredOutputs(currency), ProductCurrencyProbe.Observe); + } + + if (productsCurrent) + { + reporter.Progress(InstallStages.Build, "The installed game is already up to date; skipping the build", 96); + } + else + { + ProductCurrencyProbe.DeleteRecord(ProvenancePath, reporter); + await BuildRunner.RunAsync( + workspace, profile, installDir, baseInstallDir, + retroDir, + retroWfcOfflineDir, + skipPayload, + forceCleanBuild, + flags.GetValueOrDefault("translator-bin"), + flags.GetValueOrDefault("cc"), + flags.GetValueOrDefault("cxx"), + flags.GetValueOrDefault("fuse-ld"), + flags.GetValueOrDefault("cmake"), + flags.GetValueOrDefault("ninja"), + flags.GetValueOrDefault("native-prebuilt-dir"), + sysroot, + reporter, token); + } reporter.Progress(InstallStages.Shortcuts, "Creating shortcuts", 98); var dolSha = Sha256Of(Path.Combine(assetsDir, "main.dol")); @@ -204,6 +247,10 @@ await BuildRunner.RunAsync( // macOS builds a .app bundle (publish-app.command); launch/check-products want the binary inside it. var exeName = OperatingSystem.IsMacOS() ? $"{product}.app/Contents/MacOS/{product}" : product; var displayName = p == "base" ? "WiiCompiled (base game)" : "WiiCompiled (Retro Rewind)"; + var previous = state.Products.FirstOrDefault(r => r.Profile == p); + // A skipped build keeps the time the unchanged product was actually built. + var keepBuiltUtc = productsCurrent && previous is not null && previous.InstallDirectory == dir && + previous.ExecutableName == exeName && !string.IsNullOrEmpty(previous.BuiltUtc); state.Products.RemoveAll(r => r.Profile == p); state.Products.Add(new ProductInstallRecord { @@ -212,7 +259,7 @@ await BuildRunner.RunAsync( ExecutableName = exeName, DolSha256 = dolSha, RelSha256 = relSha, - BuiltUtc = DateTime.UtcNow.ToString("O"), + BuiltUtc = keepBuiltUtc ? previous!.BuiltUtc : DateTime.UtcNow.ToString("O"), }); DesktopEntry.Create(p, displayName, Path.Combine(dir, exeName)); } @@ -234,6 +281,10 @@ await BuildRunner.RunAsync( RuntimeConfiguration.SetRetroRewindRoot(configPath, retroDir!); } + // Only now, with the build published and every install step done, may a record vouch for it. + if (!productsCurrent && currentInputs is not null) + ProductCurrencyProbe.TryRecord(ProvenancePath, currency, currentInputs, reporter); + reporter.Progress(InstallStages.Shortcuts, "Install complete", 99); } @@ -253,6 +304,7 @@ private static void Uninstall() Console.WriteLine($"Removed {record.Profile} from {record.InstallDirectory}"); } JsonState.Write(StatePath, state); + ProductCurrencyProbe.DeleteRecord(ProvenancePath, reporter: null); } private static int Launch(string profile, Dictionary flags) @@ -315,6 +367,9 @@ private static string Sha256Of(string path) private static string StatePath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WiiCompiled", "install-state.json"); + private static string ProvenancePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WiiCompiled", "product-provenance.json"); + private static string DefaultInstallDir(string profile) => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WiiCompiled", "Install", profile == "base" ? "Base" : "RetroRewind"); diff --git a/Launcher/WiiCompiled.Setup.Windows/ConsoleCommands.cs b/Launcher/WiiCompiled.Setup.Windows/ConsoleCommands.cs index 02ab9a2a2..dee1eeef4 100644 --- a/Launcher/WiiCompiled.Setup.Windows/ConsoleCommands.cs +++ b/Launcher/WiiCompiled.Setup.Windows/ConsoleCommands.cs @@ -40,20 +40,80 @@ public static int EmitPayloadIdentities(CommandLine command) "directories."); } - var components = ToolkitFingerprint.ComputeComponents(root); + var inventory = BuildPayloadInventory(root, ToolkitFingerprint.RunTranslatorLister); + var hashes = inventory.Hashes(); + var components = ToolkitFingerprint.ComputeComponentsFromHashes(hashes, + relative => File.ReadAllText(Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar))), + inventory.TranslationInputLists()); + // The install path derives every identity from this inventory instead of the disk, so the + // release build proves on the real payload that the two derivations agree. + var disk = ToolkitFingerprint.ComputeComponents(root, lister: ToolkitFingerprint.RunTranslatorLister, + strictTranslationInputs: true); + if (!components.SameIdentities(disk)) + throw new InvalidDataException( + "The payload inventory and the staged payload produce different toolkit identities."); + var packages = ToolkitFingerprint.ComputePackageComponentsFromHashes(hashes); + if (packages.Package != ToolkitFingerprint.ComputePackage(root)) + throw new InvalidDataException( + "The payload inventory and the staged payload produce different package identities."); + + inventory.ToolkitFingerprint = components.Compile; + inventory.ToolkitPackageFingerprint = packages.Package; + inventory.Validate(); + inventory.Write(Path.Combine(root, PayloadInventory.FileName)); + var identities = new PayloadIdentities( components.Compile, components.Translation, components.NativeToolchain, - ToolkitFingerprint.ComputePackage(root), - ToolkitFingerprint.ComputeRuntimeAssets(root)); + packages.Package, + ToolkitFingerprint.ComputeRuntimeAssets(root), + packages.Toolchain, + packages.Translator, + new SortedDictionary(components.TranslationByRelease.ToDictionary(), + StringComparer.Ordinal)); Console.Out.WriteLine(JsonSerializer.Serialize(identities)); return 0; } + /// + /// Hashes every shipped Toolkit/BuildWorkspace file and records the files each translation + /// project reads, as the staged translator itself reports them. + /// + internal static PayloadInventory BuildPayloadInventory(string root, TranslationInputLister lister, + CancellationToken cancellationToken = default) + { + root = Path.GetFullPath(root); + var files = new System.Collections.Concurrent.ConcurrentBag(); + var all = new[] { InstalledLayout.Toolkit(root), InstalledLayout.Workspace(root) } + .Where(Directory.Exists) + .SelectMany(directory => Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories)) + .ToList(); + Parallel.ForEach(all, + new ParallelOptions { CancellationToken = cancellationToken, MaxDegreeOfParallelism = Math.Max(2, Environment.ProcessorCount) }, + file => + { + var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); + files.Add(new PayloadInventoryFile + { + Path = relative, Size = new FileInfo(file).Length, Sha256 = InputValidation.Sha256File(file) + }); + }); + var translationInputs = ToolkitFingerprint.ListTranslationInputs(root, lister, strict: true, + diagnostic: null, cancellationToken)!; + return new PayloadInventory + { + SchemaVersion = PayloadInventory.CurrentSchemaVersion, + Files = files.OrderBy(file => file.Path, StringComparer.Ordinal).ToList(), + TranslationInputs = translationInputs.ToDictionary(pair => pair.Key, pair => pair.Value.ToList(), + StringComparer.Ordinal) + }; + } + private sealed record PayloadIdentities(string ToolkitFingerprint, string TranslationFingerprint, string NativeToolchainFingerprint, string ToolkitPackageFingerprint, - string RuntimeAssetsFingerprint); + string RuntimeAssetsFingerprint, string ToolchainPackageFingerprint, + string TranslatorPackageFingerprint, SortedDictionary TranslationFingerprintsByRelease); public static int VerifyInputs(CommandLine command) { diff --git a/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs b/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs index d4467b77a..2cc82d26e 100644 --- a/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs +++ b/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs @@ -37,6 +37,7 @@ public async Task InstallAsync(InstallOptions options, CancellationToken cancell using var payload = PayloadArchive.OpenCurrent(); var manifest = payload.ReadManifest(); + var inventory = payload.TryReadInventory(manifest, _reporter.Diagnostic); var toolkit = InstalledLayout.Toolkit(staging); var workspace = InstalledLayout.Workspace(staging); @@ -79,31 +80,35 @@ public async Task InstallAsync(InstallOptions options, CancellationToken cancell var samePackageContent = existing.IsPresent && installedToolkitPackageFingerprint.Equals( candidateToolkitPackageFingerprint, StringComparison.Ordinal); - var sameToolkitPackage = sameToolkit && samePackageContent; var hadRetro = existing.HasRetroProduct || previousState?.RetroRewindInstalled == true; var runtimeAssetsCurrent = sameToolkit && RuntimeAssetsAreCurrent(existing, candidateRuntimeAssetsFingerprint, cancellationToken); var installedNodTool = Path.Combine(existing.ToolkitDirectory, "nodtool.exe"); - var extractToolkit = MustRefreshToolkit(sameToolkit, samePackageContent, - File.Exists(installedNodTool)); - var extractWorkspace = !sameToolkit || !runtimeAssetsCurrent; _reporter.Progress(InstallStages.ExtractToolkit, "Inspecting the release's local recompilation toolkit...", 4); - if (extractToolkit) payload.ExtractDirectory(InstalledLayout.ToolkitDirectoryName, toolkit); - if (extractWorkspace) - { - payload.ExtractDirectory(InstalledLayout.WorkspaceDirectoryName, workspace); - WorkspaceTimestamps.MarkChangedFiles(existing.WorkspaceDirectory, workspace, - _reporter.Diagnostic, cancellationToken); - } + var toolkitRefresh = DecideToolkitRefresh(existing, manifest, inventory, sameToolkit, + samePackageContent, File.Exists(installedNodTool), cancellationToken); + // An unchanged toolkit only ever needs the copied runtime assets refreshed: nothing else in + // the workspace is published on that path, so nothing else is extracted (or re-stamped). + var workspaceExtraction = !sameToolkit ? WorkspaceExtraction.Full + : runtimeAssetsCurrent ? WorkspaceExtraction.None + : WorkspaceExtraction.RuntimeAssetsOnly; + + var extracted = new Dictionary(StringComparer.Ordinal); + ExtractToolkit(payload, toolkitRefresh, toolkit, extracted); + ExtractWorkspace(payload, workspaceExtraction, existing, workspace, extracted, cancellationToken); + VerifyExtraction(inventory, toolkitRefresh, workspaceExtraction, extracted); payload.ExtractEntry("host/WiiCompiled-Setup.exe", Path.Combine(staging, ProductInfo.SetupCopyName)); payload.ExtractDirectory("licenses", Path.Combine(staging, "licenses")); payload.ExtractEntry(InstalledLayout.PayloadManifestFileName, Path.Combine(staging, InstalledLayout.PayloadManifestFileName)); + var install = new InstallContext(existing, staging, payload, manifest, inventory, release, + previousState, options, canonicalRetroRoot, retroCompileInputs, firstInstall); + if (sameToolkit) { var desiredInputDrift = ProductRepairService.FindDesiredInputDrift(existing, @@ -113,9 +118,22 @@ public async Task InstallAsync(InstallOptions options, CancellationToken cancell "This release changes the clean game inputs used by the installed Retro Rewind product. " + "Supply Wheel Wizard's current Retro Rewind folder explicitly so it can be rebuilt safely."); - var reconciliation = await ReconcileSameToolkitAsync(existing, retroCompileInputs, - canonicalRetroRoot, options.RetroWfcPayloadMode, Path.Combine(staging, "repair"), - release.DolSha256, release.RelSha256, cancellationToken); + ProductRepairService.ReconciliationResult reconciliation; + try + { + reconciliation = await ReconcileSameToolkitAsync(existing, retroCompileInputs, + canonicalRetroRoot, options.RetroWfcPayloadMode, Path.Combine(staging, "repair"), + release.DolSha256, release.RelSha256, cancellationToken); + } + catch (InvalidDataException ex) when (ToolkitIntegrity.IsFailure(ex)) + { + // Without this, re-running setup would find the same "current" toolkit and fail the + // same way forever. Nothing was published yet; publish the release's files and retry once. + _reporter.Diagnostic(ex.Message + " Publishing the release's toolkit again and retrying once."); + await RecoverToolkitAndReconcileAsync(install, + toolkitStaged: toolkitRefresh == ToolkitRefresh.Full, cancellationToken); + return; + } var remainingCancellation = reconciliation.PublicationCommitted ? CancellationToken.None : cancellationToken; @@ -135,9 +153,9 @@ public async Task InstallAsync(InstallOptions options, CancellationToken cancell remainingCancellation.ThrowIfCancellationRequested(); var releaseEntries = new List(); - if (!sameToolkitPackage) - AddComponent(releaseEntries, staging, installDirectory, - InstalledLayout.ToolkitDirectoryName); + // Keyed on what was extracted, so a toolkit refreshed only to restore a missing + // nodtool.exe is actually published. + AddToolkitEntries(releaseEntries, toolkitRefresh, staging, installDirectory); if (!runtimeAssetsCurrent) AddRuntimeAssetPublicationEntries(releaseEntries, staging, installDirectory, updatedState.RetroRewindInstalled, candidateRuntimeAssetsFingerprint, @@ -163,16 +181,154 @@ await ExtractGameAssetsAsync(nodTool, options.GamePath, Path.Combine(staging, "GameAssets"), release, cancellationToken); } - await PublishToolkitAndReconcileProductsAsync(existing, staging, workspace, manifest, - release, previousState, options, canonicalRetroRoot, retroCompileInputs, - publishGameAssets: reusableGameAssets is null, createShortcuts: firstInstall, - cancellationToken: cancellationToken); + await PublishToolkitAndReconcileProductsAsync(install, toolkitRefresh, + publishGameAssets: reusableGameAssets is null, cancellationToken); } + /// Everything one install operation shares between its publication paths. + internal sealed record InstallContext(Installation Existing, string Staging, PayloadArchive Payload, + PayloadManifest Manifest, PayloadInventory? Inventory, GameRelease Release, InstallState? PreviousState, + InstallOptions Options, string? CanonicalRetroRoot, RetroRewindCompileInputs? RetroCompileInputs, + bool FirstInstall); - internal static bool MustRefreshToolkit(bool sameToolkit, bool samePackageContent, - bool nodToolPresent) => - !sameToolkit || !samePackageContent || !nodToolPresent; + /// + /// Re-extract Toolkit/ if and only if its package identity changed, nodtool.exe is + /// missing, or the installed copy fails the stat check against the release inventory; when only + /// the translator changed and the installed toolchain passes, just Toolkit/Translator. + /// Without an inventory this is the original rule: refresh unless the whole toolkit is unchanged. + /// + internal static ToolkitRefresh PlanToolkitRefresh(bool inventoryAvailable, bool sameToolkit, + bool samePackageContent, bool nodToolPresent, Func toolkitStatOk, + bool sameToolchainPackage, Func toolchainStatOk) + { + if (!inventoryAvailable) + return sameToolkit && samePackageContent && nodToolPresent ? ToolkitRefresh.None : ToolkitRefresh.Full; + if (!nodToolPresent) return ToolkitRefresh.Full; + if (samePackageContent) return toolkitStatOk() ? ToolkitRefresh.None : ToolkitRefresh.Full; + if (sameToolchainPackage && toolchainStatOk()) return ToolkitRefresh.TranslatorOnly; + return ToolkitRefresh.Full; + } + + private ToolkitRefresh DecideToolkitRefresh(Installation existing, PayloadManifest manifest, + PayloadInventory? inventory, bool sameToolkit, bool samePackageContent, bool nodToolPresent, + CancellationToken cancellationToken) + { + bool StatOk(string description, IReadOnlyCollection? excluded) + { + var problems = inventory!.StatCheck(existing.Root, InstalledLayout.ToolkitEntryPrefix, + requireNormalizedTimestamp: true, excluded, cancellationToken); + if (problems.Count == 0) return true; + _reporter.Diagnostic($"The installed {description} cannot be reused as it is: " + + string.Join("; ", problems)); + return false; + } + + var state = existing.IsPresent && existing.ResolveToolkitPackageFingerprint().Length > 0 + ? existing.ReadToolkitState() + : null; + var sameToolchainPackage = state is not null && + !string.IsNullOrWhiteSpace(manifest.ToolchainPackageFingerprint) && + manifest.ToolchainPackageFingerprint.Equals( + state.ToolchainPackageFingerprint ?? "", StringComparison.Ordinal); + var refresh = PlanToolkitRefresh(inventory is not null, sameToolkit, samePackageContent, nodToolPresent, + () => StatOk("toolkit", null), + sameToolchainPackage, + () => StatOk("toolchain", [ToolkitFingerprint.TranslatorPrefix])); + _reporter.Diagnostic(refresh switch + { + ToolkitRefresh.None => "The installed toolkit is this release's and is reused.", + ToolkitRefresh.TranslatorOnly => "Only the translator changed; the installed toolchain is reused.", + _ => "The release's toolkit is extracted." + }); + return refresh; + } + + private static void ExtractToolkit(PayloadArchive payload, ToolkitRefresh refresh, string stagedToolkit, + IDictionary extracted) + { + if (refresh == ToolkitRefresh.Full) + payload.ExtractDirectory(InstalledLayout.ToolkitDirectoryName, stagedToolkit, extracted); + else if (refresh == ToolkitRefresh.TranslatorOnly) + payload.ExtractDirectory(ToolkitFingerprint.TranslatorPrefix, + Path.Combine(stagedToolkit, "Translator"), extracted); + } + + private void ExtractWorkspace(PayloadArchive payload, WorkspaceExtraction extraction, Installation existing, + string stagedWorkspace, IDictionary extracted, + CancellationToken cancellationToken) + { + if (extraction == WorkspaceExtraction.Full) + { + payload.ExtractDirectory(InstalledLayout.WorkspaceDirectoryName, stagedWorkspace, extracted); + WorkspaceTimestamps.MarkChangedFiles(existing.WorkspaceDirectory, stagedWorkspace, + _reporter.Diagnostic, cancellationToken); + } + else if (extraction == WorkspaceExtraction.RuntimeAssetsOnly) + { + // Only published as copied runtime support files, never compiled, so their timestamps + // carry no meaning for the incremental build. + payload.ExtractDirectory(RuntimeAssetsEntryPrefix, + Path.Combine(stagedWorkspace, "runtime", "assets"), extracted); + } + } + + private const string RuntimeAssetsEntryPrefix = InstalledLayout.WorkspaceEntryPrefix + "runtime/assets/"; + + /// Every byte streamed out of the payload must be exactly what the release inventory lists. + private static void VerifyExtraction(PayloadInventory? inventory, ToolkitRefresh toolkit, + WorkspaceExtraction workspace, IReadOnlyDictionary extracted) + { + if (inventory is null) return; + if (toolkit == ToolkitRefresh.Full) inventory.VerifyExtracted(InstalledLayout.ToolkitEntryPrefix, extracted); + else if (toolkit == ToolkitRefresh.TranslatorOnly) + inventory.VerifyExtracted(ToolkitFingerprint.TranslatorPrefix, extracted); + if (workspace == WorkspaceExtraction.Full) + inventory.VerifyExtracted(InstalledLayout.WorkspaceEntryPrefix, extracted); + else if (workspace == WorkspaceExtraction.RuntimeAssetsOnly) + inventory.VerifyExtracted(RuntimeAssetsEntryPrefix, extracted); + } + + /// + /// Never overlaps Toolkit and Toolkit/Translator: a transaction rejects overlapping + /// destinations, and the translator-only plan staged nothing else. + /// + internal static void AddToolkitEntries(List entries, ToolkitRefresh refresh, + string staging, string installDirectory) + { + if (refresh == ToolkitRefresh.Full) + AddComponent(entries, staging, installDirectory, InstalledLayout.ToolkitDirectoryName); + else if (refresh == ToolkitRefresh.TranslatorOnly) + entries.Add(InstallTransactionEntry.Directory( + Path.Combine(InstalledLayout.Toolkit(staging), "Translator"), + Path.Combine(InstalledLayout.Toolkit(installDirectory), "Translator"))); + } + + /// + /// The installed toolkit failed integrity verification although it is this release's. Extract + /// the release's Toolkit and BuildWorkspace afresh (keeping the build caches) and run the normal + /// publish-then-reconcile path, which itself re-verifies what it published and retries once. + /// + private async Task RecoverToolkitAndReconcileAsync(InstallContext install, bool toolkitStaged, + CancellationToken cancellationToken) + { + var toolkit = InstalledLayout.Toolkit(install.Staging); + var workspace = InstalledLayout.Workspace(install.Staging); + // A whole toolkit this operation already extracted (and verified) is complete; anything + // else staged so far was partial and is replaced. + if (!toolkitStaged && Directory.Exists(toolkit)) Directory.Delete(toolkit, recursive: true); + if (Directory.Exists(workspace)) Directory.Delete(workspace, recursive: true); + _reporter.Progress(InstallStages.ExtractToolkit, + "Restoring the release's local recompilation toolkit...", 4); + var extracted = new Dictionary(StringComparer.Ordinal); + var toolkitPlan = toolkitStaged ? ToolkitRefresh.None : ToolkitRefresh.Full; + ExtractToolkit(install.Payload, toolkitPlan, toolkit, extracted); + ExtractWorkspace(install.Payload, WorkspaceExtraction.Full, install.Existing, workspace, extracted, + cancellationToken); + VerifyExtraction(install.Inventory, toolkitPlan, WorkspaceExtraction.Full, extracted); + EnsureSufficientRemainingDiskSpace(install.Existing.Root, needsExtractedDisc: false, needsLocalBuild: true); + await PublishToolkitAndReconcileProductsAsync(install, ToolkitRefresh.Full, publishGameAssets: false, + cancellationToken); + } private static void AddComponent(List entries, string staging, string installDirectory, string name) => @@ -184,58 +340,209 @@ private static void AddComponent(List entries, string s /// the staged one, carrying the base translation, native build dir, verified inputs, and Retro-WFC payload cache /// across a toolkit update. Each is re-validated by the build, so stale caches degrade to a clean rebuild, never reuse. /// - private static readonly string[] WorkspaceCacheDirectories = - ["generated", "build", "native-build", "Assets", "PulsarPacks"]; - - private async Task PublishToolkitAndReconcileProductsAsync(Installation existing, string staging, - string stagedWorkspace, PayloadManifest manifest, GameRelease release, InstallState? previousState, - InstallOptions options, string? canonicalRetroRoot, - RetroRewindCompileInputs? retroCompileInputs, - bool publishGameAssets, bool createShortcuts, CancellationToken cancellationToken) + private static readonly string[] WorkspaceCacheDirectories = PayloadInventory.WorkspaceCacheDirectories; + + private async Task PublishToolkitAndReconcileProductsAsync(InstallContext install, + ToolkitRefresh toolkitRefresh, bool publishGameAssets, CancellationToken cancellationToken) { + var existing = install.Existing; + var staging = install.Staging; + var manifest = install.Manifest; + var release = install.Release; var installDirectory = existing.Root; + GraftWorkspaceCaches(existing.WorkspaceDirectory, InstalledLayout.Workspace(staging), cancellationToken); + + var state = BuildInstallState(install.PreviousState, installDirectory, manifest, release, + compileInputs: null, install.CanonicalRetroRoot, install.Options.RetroWfcPayloadMode); + PrepareMetadata(staging, manifest, state); + + cancellationToken.ThrowIfCancellationRequested(); + var entries = new List(); + + AddToolkitEntries(entries, toolkitRefresh, staging, installDirectory); + AddComponent(entries, staging, installDirectory, InstalledLayout.WorkspaceDirectoryName); + if (publishGameAssets) AddComponent(entries, staging, installDirectory, "GameAssets"); + + Publish(staging, installDirectory, install.CanonicalRetroRoot, state, + entries, cancellationToken, progressPercent: 8, completionPercent: 10, + createShortcuts: install.FirstInstall); + + var verified = EnsurePublishedToolkitIntact(install, cancellationToken); + _reporter.Progress(InstallStages.BuildBase, + "Producing the installed products with the published toolkit...", 11); + + var reconciliation = await ReconcileSameToolkitAsync(existing, install.RetroCompileInputs, + install.CanonicalRetroRoot, install.Options.RetroWfcPayloadMode, repairScratch: null, + release.DolSha256, release.RelSha256, cancellationToken, verified); + EnsureReconciliationCurrent(existing, manifest.ToolkitFingerprint, install.RetroCompileInputs, + release.DolSha256, release.RelSha256, reconciliation.CachedRetroWfcPayloadMatches); + } + + /// + /// Moves the installed workspace's build caches into a staged workspace, so a toolkit update + /// keeps the base translation, native build directory, verified inputs and payload cache. Each + /// is re-validated by the build, so stale caches degrade to a clean rebuild, never reuse. + /// + private static void GraftWorkspaceCaches(string installedWorkspace, string stagedWorkspace, + CancellationToken cancellationToken) + { foreach (var cacheDirectory in WorkspaceCacheDirectories) { cancellationToken.ThrowIfCancellationRequested(); - var source = Path.Combine(existing.WorkspaceDirectory, cacheDirectory); + var source = Path.Combine(installedWorkspace, cacheDirectory); if (!Directory.Exists(source)) continue; var destination = Path.Combine(stagedWorkspace, cacheDirectory); if (Directory.Exists(destination)) Directory.Delete(destination, recursive: true); Directory.Move(source, destination); } + } + /// + /// After publication, every shipped Toolkit/BuildWorkspace file must exist with its exact size + /// (and, for the toolkit, its payload timestamp) and nothing foreign may sit beside them. A root + /// that fails is extracted and published once more; a second failure is reported instead of + /// leaving the user in a loop. Returns the identities the compile may use without re-hashing, + /// derived from the verified inventory, or null to make the compile hash the toolkit itself. + /// + internal ToolkitFingerprintComponents? EnsurePublishedToolkitIntact(InstallContext install, + CancellationToken cancellationToken) + { + var inventory = install.Inventory; + if (inventory is null) return null; + var root = install.Existing.Root; + (List Toolkit, List Workspace) Check() => ( + inventory.StatCheck(root, InstalledLayout.ToolkitEntryPrefix, requireNormalizedTimestamp: true, + cancellationToken: cancellationToken), + inventory.StatCheck(root, InstalledLayout.WorkspaceEntryPrefix, requireNormalizedTimestamp: false, + cancellationToken: cancellationToken)); + + var problems = Check(); + if (problems.Toolkit.Count > 0 || problems.Workspace.Count > 0) + { + _reporter.Diagnostic("The published toolkit does not match the release; publishing it once more: " + + string.Join("; ", problems.Toolkit.Concat(problems.Workspace))); + RepublishDamagedRoots(install, problems.Toolkit.Count > 0, problems.Workspace.Count > 0, + cancellationToken); + problems = Check(); + if (problems.Toolkit.Count > 0 || problems.Workspace.Count > 0) + throw new InvalidOperationException( + "Setup published the release's recompilation toolkit twice, but its files still do not " + + "match the release (" + string.Join("; ", problems.Toolkit.Concat(problems.Workspace)) + + "). Security software may be removing or changing them; allow the installation folder " + + "and run setup again."); + } + return VerifiedComponents(install, cancellationToken); + } - var state = BuildInstallState(previousState, installDirectory, manifest, release, - compileInputs: null, canonicalRetroRoot, options.RetroWfcPayloadMode); - PrepareMetadata(staging, manifest, state); - - cancellationToken.ThrowIfCancellationRequested(); + private void RepublishDamagedRoots(InstallContext install, bool toolkit, bool workspace, + CancellationToken cancellationToken) + { + var installDirectory = install.Existing.Root; + var retry = Path.Combine(install.Staging, "republish"); + if (Directory.Exists(retry)) Directory.Delete(retry, recursive: true); + var extracted = new Dictionary(StringComparer.Ordinal); var entries = new List(); + if (toolkit) + { + ExtractToolkit(install.Payload, ToolkitRefresh.Full, InstalledLayout.Toolkit(retry), extracted); + VerifyExtraction(install.Inventory, ToolkitRefresh.Full, WorkspaceExtraction.None, extracted); + AddComponent(entries, retry, installDirectory, InstalledLayout.ToolkitDirectoryName); + } + if (workspace) + { + var stagedWorkspace = InstalledLayout.Workspace(retry); + ExtractWorkspace(install.Payload, WorkspaceExtraction.Full, install.Existing, stagedWorkspace, + extracted, cancellationToken); + VerifyExtraction(install.Inventory, ToolkitRefresh.None, WorkspaceExtraction.Full, extracted); + GraftWorkspaceCaches(install.Existing.WorkspaceDirectory, stagedWorkspace, cancellationToken); + AddComponent(entries, retry, installDirectory, InstalledLayout.WorkspaceDirectoryName); + } - AddComponent(entries, staging, installDirectory, InstalledLayout.ToolkitDirectoryName); - AddComponent(entries, staging, installDirectory, InstalledLayout.WorkspaceDirectoryName); - if (publishGameAssets) AddComponent(entries, staging, installDirectory, "GameAssets"); + cancellationToken.ThrowIfCancellationRequested(); + RunningProductGuard.EnsureProductsNotRunning(installDirectory); + using var transaction = InstallTransaction.Begin(installDirectory, _reporter, entries.ToArray()); + transaction.Publish(); + transaction.Commit(); + } - Publish(staging, installDirectory, canonicalRetroRoot, state, - entries, cancellationToken, progressPercent: 8, completionPercent: 10, - createShortcuts: createShortcuts); + /// + /// The toolkit identities of the just-verified installation, computed from the release + /// inventory exactly the way computes them + /// from disk. Any disagreement with the manifest discards them, so the compile hashes instead. + /// + private ToolkitFingerprintComponents? VerifiedComponents(InstallContext install, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + var components = ComputeInventoryComponents(install.Inventory!, install.Existing.Root, + install.Manifest, _reporter.Diagnostic); + return components; + } - _reporter.Progress(InstallStages.BuildBase, - "Producing the installed products with the published toolkit...", 11); + /// + /// Derives the toolkit identities from a release inventory whose files were verified to be the + /// ones at . The native index is the one document whose content (not only + /// its hash) the identities read; it is read back from disk and must hash to its inventory entry. + /// Returns null when the inventory does not reproduce the manifest's identities. + /// + internal static ToolkitFingerprintComponents? ComputeInventoryComponents(PayloadInventory inventory, + string root, PayloadManifest manifest, Action diagnostic) + { + string? ReadVerifiedText(string relative) + { + if (!inventory.ByPath.TryGetValue(relative, out var shipped)) return null; + try + { + var bytes = File.ReadAllBytes(Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar))); + var sha = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant(); + return sha.Equals(shipped.Sha256, StringComparison.OrdinalIgnoreCase) + ? System.Text.Encoding.UTF8.GetString(bytes) + : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } - var reconciliation = await ReconcileSameToolkitAsync(existing, retroCompileInputs, - canonicalRetroRoot, options.RetroWfcPayloadMode, repairScratch: null, - release.DolSha256, release.RelSha256, cancellationToken); - EnsureReconciliationCurrent(existing, manifest.ToolkitFingerprint, retroCompileInputs, - release.DolSha256, release.RelSha256, reconciliation.CachedRetroWfcPayloadMatches); + ToolkitFingerprintComponents components; + try + { + components = ToolkitFingerprint.ComputeComponentsFromHashes(inventory.Hashes(), ReadVerifiedText, + inventory.TranslationInputLists()); + } + catch (InvalidDataException ex) + { + diagnostic("The toolkit identities could not be derived from the release inventory: " + ex.Message); + return null; + } + if (!components.Compile.Equals(manifest.ToolkitFingerprint, StringComparison.Ordinal) || + (manifest.TranslationFingerprint.Length > 0 && + !components.Translation.Equals(manifest.TranslationFingerprint, StringComparison.Ordinal)) || + (manifest.NativeToolchainFingerprint.Length > 0 && + !components.NativeToolchain.Equals(manifest.NativeToolchainFingerprint, StringComparison.Ordinal))) + { + diagnostic("The release inventory does not reproduce the release's toolkit identities; " + + "the toolkit is hashed instead."); + return null; + } + var shippedByRelease = manifest.TranslationFingerprintsByRelease ?? new Dictionary(); + var sameByRelease = shippedByRelease.Count == components.TranslationByRelease.Count && + shippedByRelease.All(pair => + components.TranslationByRelease.TryGetValue(pair.Key, out var value) && + value == pair.Value); + return sameByRelease + ? components + : components with { TranslationByRelease = new SortedDictionary(StringComparer.Ordinal) }; } private Task ReconcileSameToolkitAsync(Installation existing, RetroRewindCompileInputs? retroCompileInputs, string? canonicalRetroRoot, RetroWfcPayloadMode payloadMode, string? repairScratch, string expectedDolSha256, - string expectedRelSha256, CancellationToken cancellationToken) + string expectedRelSha256, CancellationToken cancellationToken, + ToolkitFingerprintComponents? preverifiedToolkitComponents = null) { var repair = new ProductRepairService(existing, _reporter); var options = new ProductRepairService.ReconcileOptions @@ -243,7 +550,8 @@ private async Task PublishToolkitAndReconcileProductsAsync(Installation existing ScratchRoot = repairScratch, ExpectedDolSha256 = expectedDolSha256, ExpectedRelSha256 = expectedRelSha256, - CanonicalRetroRewindRoot = canonicalRetroRoot + CanonicalRetroRewindRoot = canonicalRetroRoot, + PreverifiedToolkitComponents = preverifiedToolkitComponents }; return retroCompileInputs is null @@ -348,7 +656,12 @@ private static void PrepareMetadata(string staging, PayloadManifest manifest, In RuntimeAssetsFingerprint = manifest.RuntimeAssetsFingerprint, TranslationFingerprint = manifest.TranslationFingerprint, NativeToolchainFingerprint = manifest.NativeToolchainFingerprint, - ToolkitReleaseTag = manifest.ToolkitReleaseTag + ToolkitReleaseTag = manifest.ToolkitReleaseTag, + ToolchainPackageFingerprint = manifest.ToolchainPackageFingerprint ?? "", + TranslatorPackageFingerprint = manifest.TranslatorPackageFingerprint ?? "", + TranslationFingerprintsByRelease = new Dictionary( + manifest.TranslationFingerprintsByRelease ?? new Dictionary(), StringComparer.Ordinal), + NativePrebuiltGateProvenanceSha256 = manifest.NativePrebuiltGateProvenanceSha256 ?? "" }); JsonState.Write(Path.Combine(staging, InstalledLayout.InstallStateFileName), state); } diff --git a/Launcher/WiiCompiled.Setup.Windows/LocalBuildService.cs b/Launcher/WiiCompiled.Setup.Windows/LocalBuildService.cs index 4a390ea10..f3cd1b5f8 100644 --- a/Launcher/WiiCompiled.Setup.Windows/LocalBuildService.cs +++ b/Launcher/WiiCompiled.Setup.Windows/LocalBuildService.cs @@ -25,7 +25,8 @@ public async Task BuildAsync(string installStaging, BuildProfile profile, string RetroWfcPayloadMode retroWfcPayloadMode, string? retroWfcOfflinePayloadDirectory, string? retroWfcGameId, CancellationToken cancellationToken, ToolkitFingerprintComponents? toolkitComponents = null, - bool forceCleanBuild = false, BuildProgressWindow? progress = null, + bool forceCleanBuild = false, string? nativePrebuiltGateProvenanceSha256 = null, + BuildProgressWindow? progress = null, string? retroRewindPackageDirectory = null, string? baseOutputDirectory = null) { var workspace = InstalledLayout.Workspace(installStaging); @@ -77,6 +78,24 @@ public async Task BuildAsync(string installStaging, BuildProfile profile, string arguments.Add(toolkitComponents.Translation); arguments.Add("-NativeToolchainFingerprint"); arguments.Add(toolkitComponents.NativeToolchain); + // The script picks the identity of the release it resolves from the extracted disc; + // one it cannot find falls back to -TranslationFingerprint. + var byRelease = FormatTranslationFingerprintsByRelease(toolkitComponents.TranslationByRelease); + if (byRelease.Length > 0) + { + arguments.Add("-TranslationFingerprintsByRelease"); + arguments.Add(byRelease); + } + // The compile identity was proved for exactly this toolkit (hashed in full, or verified + // while this operation installed it), which is what lets the script reuse a recorded, + // or release-proved, precompiled-package gate result instead of re-proving it. + arguments.Add("-VerifiedCompileIdentity"); + arguments.Add(toolkitComponents.Compile); + if (!string.IsNullOrWhiteSpace(nativePrebuiltGateProvenanceSha256)) + { + arguments.Add("-AcceptedNativePrebuiltProvenanceSha256"); + arguments.Add(nativePrebuiltGateProvenanceSha256); + } } if (forceCleanBuild) arguments.Add("-ForceCleanBuild"); @@ -139,6 +158,17 @@ void Observe(string line) } } + /// + /// project=identity;project=identity, sorted; entries whose project name could not be + /// passed through unambiguously are left out (the script then uses the whole-project identity). + /// + internal static string FormatTranslationFingerprintsByRelease(IReadOnlyDictionary byRelease) => + string.Join(";", byRelease + .Where(pair => pair.Key.Length > 0 && pair.Key.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.') && + pair.Value.Length == 64 && pair.Value.All(char.IsAsciiHexDigit)) + .OrderBy(pair => pair.Key, StringComparer.Ordinal) + .Select(pair => pair.Key + "=" + pair.Value)); + /// /// Records what this product was built from: ties it to the /// translator/workspace, to Retro Rewind's embedded Code.pul, so a diff --git a/Launcher/WiiCompiled.Setup.Windows/Models.cs b/Launcher/WiiCompiled.Setup.Windows/Models.cs index f94569369..fc2739216 100644 --- a/Launcher/WiiCompiled.Setup.Windows/Models.cs +++ b/Launcher/WiiCompiled.Setup.Windows/Models.cs @@ -60,6 +60,29 @@ internal sealed class PayloadManifest public string RuntimeAssetsFingerprint { get; set; } = ""; public string TranslationFingerprint { get; set; } = ""; public string NativeToolchainFingerprint { get; set; } = ""; + + // Optional, additive identities (schema 3 is unchanged: a reader that does not know them, and a + // payload that lacks them, both fall back to the whole-toolkit identities above). + + /// Toolkit/ minus Toolkit/Translator/. + public string ToolchainPackageFingerprint { get; set; } = ""; + + /// Toolkit/Translator/ alone. + public string TranslatorPackageFingerprint { get; set; } = ""; + + /// + /// The translation identity narrowed to the files each translation project (keyed by its + /// projects/ directory name) reads, so a change to one release's project keeps the + /// others' completed base translations. + /// + public Dictionary TranslationFingerprintsByRelease { get; set; } = new(StringComparer.Ordinal); + + /// + /// SHA-256 of the shipped native_prebuilt/provenance.json that Windows PowerShell 5.1 + /// accepted against this exact toolkit at release-build time, so a build verified to use this + /// compile identity can skip re-proving it. + /// + public string NativePrebuiltGateProvenanceSha256 { get; set; } = ""; } internal sealed class DiscHeader @@ -161,6 +184,14 @@ internal sealed class ToolkitState public string TranslationFingerprint { get; set; } = ""; public string NativeToolchainFingerprint { get; set; } = ""; public string ToolkitReleaseTag { get; set; } = ""; + + // Optional, additive fields (schema 2 is unchanged); an older installation without them falls + // back to refreshing the whole Toolkit and to the whole-toolkit identities. + public string ToolchainPackageFingerprint { get; set; } = ""; + public string TranslatorPackageFingerprint { get; set; } = ""; + public Dictionary TranslationFingerprintsByRelease { get; set; } = new(StringComparer.Ordinal); + public string NativePrebuiltGateProvenanceSha256 { get; set; } = ""; + public string SetupVersion { get; set; } = ProductInfo.Version; public DateTimeOffset UpdatedUtc { get; set; } = DateTimeOffset.UtcNow; diff --git a/Launcher/WiiCompiled.Setup.Windows/PayloadArchive.cs b/Launcher/WiiCompiled.Setup.Windows/PayloadArchive.cs index 8f9b1b4fa..256f2758b 100644 --- a/Launcher/WiiCompiled.Setup.Windows/PayloadArchive.cs +++ b/Launcher/WiiCompiled.Setup.Windows/PayloadArchive.cs @@ -1,4 +1,6 @@ +using System.Buffers; using System.IO.Compression; +using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -49,6 +51,55 @@ public static PayloadArchive OpenCurrent() } } + /// Opens a bare payload ZIP; used by self-tests that build a payload on disk. + internal static PayloadArchive OpenZip(string path) + { + var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + try + { + var slice = new SliceStream(stream, 0, stream.Length); + var zip = new ZipArchive(slice, ZipArchiveMode.Read, leaveOpen: true); + return new PayloadArchive(stream, slice, zip); + } + catch + { + stream.Dispose(); + throw; + } + } + + /// + /// The shipped per-file inventory, or null when this payload has none or it does not describe + /// the manifest's toolkit. Without it every install falls back to extracting and re-hashing. + /// + public PayloadInventory? TryReadInventory(PayloadManifest manifest, Action? diagnostic = null) + { + var entry = FindEntry(PayloadInventory.FileName); + if (entry is null) + { + diagnostic?.Invoke("This payload has no file inventory; installed files are re-hashed instead."); + return null; + } + try + { + using var stream = entry.Open(); + var inventory = PayloadInventory.Parse(stream); + if (!inventory.ToolkitFingerprint.Equals(manifest.ToolkitFingerprint, StringComparison.Ordinal) || + !inventory.ToolkitPackageFingerprint.Equals(manifest.ToolkitPackageFingerprint, + StringComparison.Ordinal)) + { + diagnostic?.Invoke("The payload inventory does not describe this release; it is ignored."); + return null; + } + return inventory; + } + catch (Exception ex) when (ex is InvalidDataException or JsonException or IOException) + { + diagnostic?.Invoke("The payload inventory is unreadable and is ignored: " + ex.Message); + return null; + } + } + public PayloadManifest ReadManifest() { var entry = FindEntry(InstalledLayout.PayloadManifestFileName) @@ -113,7 +164,14 @@ public void ExtractEntry(string entryName, string destination) NormalizeExtractedTimestamp(destination); } - public void ExtractDirectory(string prefix, string destination) + /// + /// Extracts every entry under . Each file's SHA-256 and size are computed + /// from the bytes as they stream out of the archive (never trusting the ZIP CRC) and, when + /// is given, recorded under the entry's payload path so the caller + /// can verify them against the shipped inventory. + /// + public void ExtractDirectory(string prefix, string destination, + IDictionary? identities = null) { prefix = NormalizeEntryName(prefix).TrimEnd('/') + "/"; var destinationRoot = Path.GetFullPath(destination).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; @@ -127,9 +185,37 @@ public void ExtractDirectory(string prefix, string destination) if (!outputPath.StartsWith(destinationRoot, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException($"Unsafe payload path: {entry.FullName}"); Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); - entry.ExtractToFile(outputPath, overwrite: true); - NormalizeExtractedTimestamp(outputPath); + var identity = ExtractHashed(entry, outputPath); + if (identities is not null) identities[normalizedEntry] = identity; + } + } + + private static PayloadFileIdentity ExtractHashed(ZipArchiveEntry entry, string outputPath) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + long size = 0; + var buffer = ArrayPool.Shared.Rent(1 << 16); + try + { + using (var input = entry.Open()) + using (var output = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None, + 1 << 16)) + { + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + hash.AppendData(buffer, 0, read); + output.Write(buffer, 0, read); + size += read; + } + } + } + finally + { + ArrayPool.Shared.Return(buffer); } + NormalizeExtractedTimestamp(outputPath); + return new PayloadFileIdentity(size, Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant()); } internal static void NormalizeExtractedTimestamp(string path) => diff --git a/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs b/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs new file mode 100644 index 000000000..ac56b39e3 --- /dev/null +++ b/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs @@ -0,0 +1,240 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using WiiCompiled.Setup.Common; + +namespace WiiCompiled.Setup.Windows; + +/// +/// The per-file identity of every shipped Toolkit/ and BuildWorkspace/ file, written +/// once at release-build time by --emit-payload-identities beside (never inside) the small +/// payload-manifest.json. It lets an install verify what it streams out of the payload, and +/// reuse an unchanged installed component after a cheap stat check, without re-hashing ~28,000 files. +/// +internal sealed class PayloadInventory +{ + public const int CurrentSchemaVersion = 1; + public const string FileName = "payload-inventory.json"; + + /// + /// Build-produced workspace directories (never shipped) that installs carry across updates. + /// They are not release content, so integrity checks of the workspace ignore them. + /// + public static readonly string[] WorkspaceCacheDirectories = + ["generated", "build", "native-build", "Assets", "PulsarPacks"]; + + /// + /// Extracted toolkit files keep this exact timestamp (see ). Nothing + /// a build runs writes into the toolkit, so any other timestamp means the file was replaced. + /// + public static readonly DateTime NormalizedTimestampUtc = new(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + // FAT32/exFAT record local time at two-second resolution: a portable install on such a volume + // reads back the normalized stamp shifted by the machine's UTC offset. Anything a program wrote + // since is decades away from 2000-01-01, so this tolerance cannot hide a replaced file. + private static readonly TimeSpan TimestampTolerance = TimeSpan.FromHours(15); + + public int SchemaVersion { get; set; } + + /// The compile identity this inventory was computed together with. + public string ToolkitFingerprint { get; set; } = ""; + public string ToolkitPackageFingerprint { get; set; } = ""; + public List Files { get; set; } = []; + + /// + /// Payload-relative files each translation project reads, as the shipped translator's + /// list-translation-inputs reported them at release-build time. + /// + public Dictionary> TranslationInputs { get; set; } = new(StringComparer.Ordinal); + + private Dictionary? _byPath; + + [JsonIgnore] + public IReadOnlyDictionary ByPath => + _byPath ??= Files.ToDictionary(file => file.Path, StringComparer.Ordinal); + + public IEnumerable Under(string prefix) => + Files.Where(file => file.Path.StartsWith(prefix, StringComparison.Ordinal)); + + public IReadOnlyDictionary Hashes() => + Files.ToDictionary(file => file.Path, file => file.Sha256, StringComparer.Ordinal); + + public IReadOnlyDictionary> TranslationInputLists() => + TranslationInputs.ToDictionary(pair => pair.Key, pair => (IReadOnlyList)pair.Value, + StringComparer.Ordinal); + + public static PayloadInventory Parse(Stream stream) + { + var inventory = JsonSerializer.Deserialize(stream, + new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) + ?? throw new InvalidDataException("The payload inventory is invalid."); + inventory.Validate(); + return inventory; + } + + public void Validate() + { + if (SchemaVersion != CurrentSchemaVersion) + throw new InvalidDataException($"Unsupported payload inventory schema {SchemaVersion}."); + if (Files is not { Count: > 0 }) + throw new InvalidDataException("The payload inventory lists no files."); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var file in Files) + { + if (string.IsNullOrEmpty(file.Path) || file.Path.Contains('\\') || file.Path.StartsWith('/') || + file.Path.Split('/').Any(part => part is "" or "." or "..") || + !(file.Path.StartsWith(InstalledLayout.ToolkitEntryPrefix, StringComparison.Ordinal) || + file.Path.StartsWith(InstalledLayout.WorkspaceEntryPrefix, StringComparison.Ordinal)) || + file.Size < 0 || file.Sha256.Length != 64 || !file.Sha256.All(char.IsAsciiHexDigit)) + throw new InvalidDataException($"The payload inventory has an invalid entry '{file.Path}'."); + if (!seen.Add(file.Path)) + throw new InvalidDataException($"The payload inventory lists '{file.Path}' twice."); + } + TranslationInputs ??= new Dictionary>(StringComparer.Ordinal); + } + + /// Compact on purpose: it lists every shipped file and is read once per install. + public void Write(string path) => File.WriteAllText(path, JsonSerializer.Serialize(this)); + + /// + /// Compares the files under in the installation at + /// with the inventory, without reading any content: every expected file must exist as a regular + /// file with its exact byte size (and, for the toolkit, the normalized payload timestamp), and + /// nothing else may be there. Paths under are skipped on both + /// sides; the workspace's build caches are always skipped. Returns the first few discrepancies; + /// an empty list means the component may be reused as the inventory describes it. + /// + public List StatCheck(string root, string prefix, bool requireNormalizedTimestamp, + IReadOnlyCollection? excludedPrefixes = null, CancellationToken cancellationToken = default, + int maxReported = 10) + { + excludedPrefixes ??= []; + var problems = new List(); + bool Excluded(string relative) => + excludedPrefixes.Any(excluded => relative.StartsWith(excluded, StringComparison.Ordinal)) || + IsWorkspaceCache(relative); + + var expected = Under(prefix).Where(file => !Excluded(file.Path)) + .ToDictionary(file => file.Path, StringComparer.OrdinalIgnoreCase); + var directory = Path.Combine(root, prefix.TrimEnd('/').Replace('/', Path.DirectorySeparatorChar)); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + void Report(string problem) + { + if (problems.Count < maxReported) problems.Add(problem); + else if (problems.Count == maxReported) problems.Add("..."); + } + + try + { + if (!Directory.Exists(directory)) + { + if (expected.Count > 0) Report($"{prefix} is missing"); + return problems; + } + var pending = new Stack(); + pending.Push(new DirectoryInfo(directory)); + while (pending.Count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + foreach (var entry in pending.Pop().EnumerateFileSystemInfos()) + { + var relative = Path.GetRelativePath(root, entry.FullName).Replace('\\', '/'); + if (Excluded(relative)) continue; + if ((entry.Attributes & FileAttributes.ReparsePoint) != 0) + { + Report($"{relative} is a link, not shipped content"); + continue; + } + if (entry is DirectoryInfo subdirectory) + { + pending.Push(subdirectory); + continue; + } + var file = (FileInfo)entry; + if (!expected.TryGetValue(relative, out var shipped)) + { + Report($"{relative} is not part of this release"); + continue; + } + seen.Add(relative); + if (!shipped.Path.Equals(relative, StringComparison.Ordinal)) + Report($"{relative} differs in case from {shipped.Path}"); + else if (file.Length != shipped.Size) + Report($"{relative} is {file.Length} bytes, expected {shipped.Size}"); + else if (requireNormalizedTimestamp && + (file.LastWriteTimeUtc - NormalizedTimestampUtc).Duration() > TimestampTolerance) + Report($"{relative} was modified after it was installed"); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Report($"{prefix} cannot be inspected: {ex.Message}"); + return problems; + } + + foreach (var missing in expected.Keys.Where(path => !seen.Contains(path)).Order(StringComparer.Ordinal)) + Report($"{missing} is missing"); + return problems; + } + + private static bool IsWorkspaceCache(string relative) + { + if (!relative.StartsWith(InstalledLayout.WorkspaceEntryPrefix, StringComparison.Ordinal)) return false; + var top = relative[InstalledLayout.WorkspaceEntryPrefix.Length..].Split('/')[0]; + return WorkspaceCacheDirectories.Contains(top, StringComparer.OrdinalIgnoreCase); + } + + /// + /// Throws unless the files streamed out of the payload under are + /// exactly what the inventory lists, byte size and SHA-256 included. + /// + public void VerifyExtracted(string prefix, IReadOnlyDictionary extracted) + { + var expected = Under(prefix).ToList(); + var problems = new List(); + foreach (var file in expected) + { + if (!extracted.TryGetValue(file.Path, out var actual)) + problems.Add($"{file.Path} is missing from the payload"); + else if (actual.Size != file.Size || + !actual.Sha256.Equals(file.Sha256, StringComparison.OrdinalIgnoreCase)) + problems.Add($"{file.Path} does not match its recorded identity"); + if (problems.Count >= 10) break; + } + foreach (var path in extracted.Keys) + { + if (problems.Count >= 10) break; + if (path.StartsWith(prefix, StringComparison.Ordinal) && !ByPath.ContainsKey(path)) + problems.Add($"{path} is not listed in the payload inventory"); + } + if (problems.Count > 0) + throw new InvalidDataException("The installation payload is damaged: " + + string.Join("; ", problems) + ". Download the setup again."); + } +} + +internal sealed class PayloadInventoryFile +{ + public string Path { get; set; } = ""; + public long Size { get; set; } + public string Sha256 { get; set; } = ""; +} + +/// The identity of one file as it was streamed out of the payload. +internal sealed record PayloadFileIdentity(long Size, string Sha256); + +/// How much of the shipped toolkit an operation extracts. +internal enum ToolkitRefresh +{ + /// The installed toolkit is the release's, verified by the stat check. + None, + + /// Only Toolkit/Translator changed; the installed toolchain is reused. + TranslatorOnly, + + /// The whole toolkit is extracted and published. + Full +} + +/// How much of the shipped build workspace an operation extracts. +internal enum WorkspaceExtraction { None, RuntimeAssetsOnly, Full } diff --git a/Launcher/WiiCompiled.Setup.Windows/ProductRepairService.cs b/Launcher/WiiCompiled.Setup.Windows/ProductRepairService.cs index c7e4e6bdc..d64eb57d4 100644 --- a/Launcher/WiiCompiled.Setup.Windows/ProductRepairService.cs +++ b/Launcher/WiiCompiled.Setup.Windows/ProductRepairService.cs @@ -29,6 +29,15 @@ internal sealed record ReconcileOptions /// snapshot lives in operation scratch, so it can never be the durable value. /// public string? CanonicalRetroRewindRoot { get; init; } + + /// + /// Identities the caller already proved for exactly the toolkit now installed: an install or + /// update verified every file it streamed out of the payload, and stat-checked every file it + /// reused, against the release's inventory. A compile then skips re-hashing the toolkit. + /// Standalone repair, a re-applied release, and every Broken/Blocked rebuild leave it null + /// (or ignore it) and hash the installed toolkit in full. + /// + public ToolkitFingerprintComponents? PreverifiedToolkitComponents { get; init; } } internal sealed record ReconciliationResult( @@ -215,16 +224,26 @@ private async Task ReconcileAsync(RetroRewindCompileInputs if (rebuildBase || rebuildRetro) { EnsureSufficientRepairDiskSpace(); - _reporter.Progress(InstallStages.PrepareRetro, - "Verifying the installed recompilation toolkit...", 4); - var toolkitComponents = VerifyToolkitForCompilation(toolkitFingerprint, cancellationToken); - RefreshTranslationAssets(expectedDolSha256, expectedRelSha256, cancellationToken); - // A broken or blocked product may mean the caches themselves are damaged, so nothing // recorded on disk is allowed to contribute to the repaired product. var forceCleanBuild = (rebuildBase && baseState.Status is ProductStatus.Broken or ProductStatus.Blocked) || (rebuildRetro && retroState.Status is ProductStatus.Broken or ProductStatus.Blocked); + // Not even a toolkit identity proved earlier in this operation is trusted then: the + // toolkit is hashed in full again. A product that was never produced at all (a fresh + // installation reports its missing executable as broken) has nothing that could be + // damaged, so the identities this operation proved still stand for it. + var damagedProduct = + (rebuildBase && baseState.Status is ProductStatus.Broken or ProductStatus.Blocked && + Directory.Exists(_installation.BaseDirectory)) || + (rebuildRetro && retroState.Status is ProductStatus.Broken or ProductStatus.Blocked && + Directory.Exists(_installation.RetroDirectory)); + _reporter.Progress(InstallStages.PrepareRetro, + "Verifying the installed recompilation toolkit...", 4); + var toolkitComponents = VerifyToolkitForCompilation(toolkitFingerprint, cancellationToken, + damagedProduct ? null : options.PreverifiedToolkitComponents); + RefreshTranslationAssets(expectedDolSha256, expectedRelSha256, cancellationToken); + var nativePrebuiltGate = _installation.ReadToolkitState()?.NativePrebuiltGateProvenanceSha256; var (dolSha, relSha) = TranslationInputHashes(); if (rebuildBase && rebuildRetro) @@ -241,7 +260,7 @@ private async Task ReconcileAsync(RetroRewindCompileInputs await BuildWithCleanRetryAsync(forceCleanBuild, clean => builder.BuildAsync(_installation.Root, BuildProfile.Both, retroOutput, requestedPayloadMode, payloadSnapshot?.Directory, payloadGameId, cancellationToken, - toolkitComponents, clean, + toolkitComponents, clean, nativePrebuiltGate, progress: new BuildProgressWindow(_reporter, InstallStages.BuildBase, 5, 92), retroRewindPackageDirectory: compileInputs.RetroRewindRoot, baseOutputDirectory: baseOutput)); @@ -260,7 +279,7 @@ await BuildWithCleanRetryAsync(forceCleanBuild, clean => await BuildWithCleanRetryAsync(forceCleanBuild, clean => builder.BuildAsync(_installation.Root, BuildProfile.Base, baseOutput, RetroWfcPayloadMode.NotApplicable, null, null, cancellationToken, - toolkitComponents, clean, + toolkitComponents, clean, nativePrebuiltGate, progress: new BuildProgressWindow(_reporter, InstallStages.BuildBase, 5, 92))); LocalBuildService.WriteFingerprint(baseOutput, BuildProfile.Base, toolkitFingerprint, dolSha, relSha, "", RetroWfcPayloadMode.NotApplicable); @@ -275,7 +294,7 @@ await BuildWithCleanRetryAsync(forceCleanBuild, clean => await BuildWithCleanRetryAsync(forceCleanBuild, clean => builder.BuildAsync(_installation.Root, BuildProfile.RetroRewind, retroOutput, requestedPayloadMode, payloadSnapshot?.Directory, payloadGameId, cancellationToken, - toolkitComponents, clean, + toolkitComponents, clean, nativePrebuiltGate, progress: new BuildProgressWindow(_reporter, InstallStages.BuildRetro, 5, 92), retroRewindPackageDirectory: compileInputs.RetroRewindRoot)); LocalBuildService.WriteFingerprint(retroOutput, BuildProfile.RetroRewind, @@ -496,8 +515,13 @@ private void EnsureSufficientRepairDiskSpace() localBuildAllowance + safetyAllowance, "Local recompilation"); } + /// + /// The toolkit identities a compile may use. The installed toolkit is hashed in full (a + /// standalone repair has no cheaper proof) unless carries + /// identities the calling install already proved for exactly this toolkit. + /// internal ToolkitFingerprintComponents VerifyToolkitForCompilation(string authoritativeFingerprint, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default, ToolkitFingerprintComponents? preverified = null) { var state = _installation.ReadToolkitState(); if (state is not { SchemaVersion: 2 } || @@ -508,10 +532,19 @@ internal ToolkitFingerprintComponents VerifyToolkitForCompilation(string authori "The installed toolkit provenance is missing or does not match this repair operation."); } - var components = ToolkitFingerprint.ComputeComponents(_installation.Root, cancellationToken); + if (preverified is not null && + preverified.Compile.Equals(authoritativeFingerprint, StringComparison.Ordinal)) + { + _reporter.Diagnostic( + "The toolkit was verified while it was installed by this operation; it is not hashed again."); + return preverified; + } + + var components = ToolkitFingerprint.ComputeComponents(_installation.Root, cancellationToken, + diagnostic: _reporter.Diagnostic); if (!components.Compile.Equals(authoritativeFingerprint, StringComparison.Ordinal)) { - throw new InvalidDataException( + throw ToolkitIntegrity.Failure( "The installed recompilation toolkit was modified or is incomplete. Apply the current setup release before compiling products."); } return components; @@ -670,3 +703,23 @@ private static void PreserveProductConfig(string currentProduct, string prepared FileSystemUtilities.CopyDirectory(config, Path.Combine(preparedProduct, "config")); } } + +/// +/// The installed toolkit's files no longer hash to its recorded identity (for example antivirus +/// quarantined one). Setup recovers from it by publishing the release's toolkit again; a repair +/// operation alone cannot. It stays an ordinary for every other +/// caller, marked so setup can tell it apart. +/// +internal static class ToolkitIntegrity +{ + private const string Marker = "WiiCompiled.ToolkitIntegrityFailure"; + + public static InvalidDataException Failure(string message) + { + var exception = new InvalidDataException(message); + exception.Data[Marker] = true; + return exception; + } + + public static bool IsFailure(Exception exception) => exception.Data[Marker] is true; +} diff --git a/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs b/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs new file mode 100644 index 000000000..21d272398 --- /dev/null +++ b/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs @@ -0,0 +1,718 @@ +using System.IO.Compression; +using System.Text.Json; +using WiiCompiled.Setup.Common; + +namespace WiiCompiled.Setup.Windows; + +/// +/// Self-tests of the payload inventory: streamed-hash extraction, the stat check that lets an +/// install reuse unchanged components, publication recovery, and the identities derived from it. +/// +internal static partial class SelfTests +{ + private static void RegisterPayloadTests(List failures) + { + Test("Stream and disk toolkit identity parity", TestStreamDiskIdentityParity, failures); + Test("Payload inventory stat check", TestPayloadInventoryStatCheck, failures); + Test("Asset-only and translator-only extraction", TestPartialPayloadExtraction, failures); + Test("Published toolkit retry recovery", TestPublishedToolkitRecovery, failures); + Test("Preverified toolkit identities", TestPreverifiedToolkitIdentities, failures); + Test("Narrowed cache identities", TestNarrowedCacheIdentities, failures); + Test("Progress JSON stays monotonic", TestProgressJsonMonotonic, failures); + Test("Upgrade from older toolkit state and manifest", TestUpgradeFixtures, failures); + } + + private static readonly string[] FakeProjects = ["mkwii", "mkwii-ntsc-u", "mkwii-ntsc-j"]; + + /// + /// Stands in for Translator.Cli list-translation-inputs: the regional projects port from + /// the PAL project, and one lists runtime files the native registrations already cover. + /// + private static IReadOnlyList FakeTranslationInputs(string translator, string project, + CancellationToken cancellationToken) + { + var directory = Path.GetDirectoryName(project)!; + var projects = Path.GetDirectoryName(directory)!; + var workspace = Path.GetDirectoryName(projects)!; + var pal = Path.Combine(projects, "mkwii"); + return Path.GetFileName(directory) switch + { + "mkwii" => + [ + project, Path.Combine(directory, "MAP.txt"), + // A profile's staged Code.pul: user-owned, only present on an installed workspace. + Path.Combine(workspace, "PulsarPacks", "completed", "RetroRewind", "Code.pul") + ], + "mkwii-ntsc-u" => + [ + project, Path.Combine(directory, "region_port.json"), Path.Combine(pal, "recomp.yml"), + Path.Combine(pal, "MAP.txt") + ], + _ => + [ + project, Path.Combine(workspace, "runtime", "include", "guest_abi", "guest_versions.inc"), + Path.Combine(workspace, "runtime", "src", "main.cpp"), + Path.Combine(workspace, "runtime", "native-index.json") + ] + }; + } + + /// The fake toolkit plus every file class the identities treat specially. + private static void CreateFakePayload(string root) + { + CreateFakeToolkit(root); + void Write(string relative, string content) + { + var path = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + } + Write("BuildWorkspace/projects/mkwii/MAP.txt", "map"); + Write("BuildWorkspace/projects/mkwii-ntsc-u/region_port.json", "{}"); + Write("BuildWorkspace/aurora-main/docs/notes.md", "notes"); + Write("BuildWorkspace/aurora-main/.github/workflow.yml", "ci"); + Write("BuildWorkspace/aurora-main/.clang-format", "style"); + Write("BuildWorkspace/aurora-main/extern/README", "extern"); + Write("BuildWorkspace/runtime/third_party/cryptopp/LICENSE", "license"); + Write("BuildWorkspace/runtime/third_party/.hidden/state.bin", "hidden"); + Write("BuildWorkspace/runtime/include/guest_abi/guest_versions.inc", "versions"); + Write("BuildWorkspace/" + ToolkitFingerprint.NativeConfigureFlagsFileName, "-DCMAKE_BUILD_TYPE=Release"); + Write("BuildWorkspace/Dependencies/native_prebuilt/provenance.json", "{\"BuiltUtc\":\"1\"}"); + Write("Toolkit/CMake/share/cmake-4.3/Modules/Foo.cmake", "module"); + Write("Toolkit/CMake/doc/cmake/LICENSE.rst", "cmake license"); + Write("Toolkit/Redist/vcruntime140.dll", "redist"); + Write("Toolkit/Translator/Translator.Cli.pdb", "symbols"); + WriteFakeNativeIndex(root, "\"a\""); + } + + /// A staged payload root plus its inventory, manifest and ZIP, built like Build-Installer.ps1. + private sealed record FakeRelease(string Root, string Zip, PayloadManifest Manifest, + ToolkitFingerprintComponents Disk); + + private static FakeRelease BuildFakeRelease(string directory, bool includeInventory = true) + { + var root = Path.Combine(directory, "payload"); + CreateFakePayload(root); + var disk = ToolkitFingerprint.ComputeComponents(root, lister: FakeTranslationInputs, + strictTranslationInputs: true); + var packages = ToolkitFingerprint.ComputePackageComponents(root); + var manifest = new PayloadManifest + { + SchemaVersion = PayloadManifest.CurrentSchemaVersion, + ToolkitFingerprint = disk.Compile, + ToolkitPackageFingerprint = packages.Package, + ToolchainPackageFingerprint = packages.Toolchain, + TranslatorPackageFingerprint = packages.Translator, + RuntimeAssetsFingerprint = ToolkitFingerprint.ComputeRuntimeAssets(root), + TranslationFingerprint = disk.Translation, + NativeToolchainFingerprint = disk.NativeToolchain, + TranslationFingerprintsByRelease = disk.TranslationByRelease.ToDictionary() + }; + if (includeInventory) + { + var inventory = ConsoleCommands.BuildPayloadInventory(root, FakeTranslationInputs); + inventory.ToolkitFingerprint = disk.Compile; + inventory.ToolkitPackageFingerprint = packages.Package; + inventory.Write(Path.Combine(root, PayloadInventory.FileName)); + } + var zip = Path.Combine(directory, "payload.zip"); + ZipFile.CreateFromDirectory(root, zip); + return new FakeRelease(root, zip, manifest, disk); + } + + private static Dictionary ExtractRelease(PayloadArchive payload, string install) + { + var extracted = new Dictionary(StringComparer.Ordinal); + payload.ExtractDirectory(InstalledLayout.ToolkitDirectoryName, InstalledLayout.Toolkit(install), extracted); + payload.ExtractDirectory(InstalledLayout.WorkspaceDirectoryName, InstalledLayout.Workspace(install), + extracted); + return extracted; + } + + private static void WithTempDirectory(string name, Action test) + { + var directory = Path.Combine(Path.GetTempPath(), $"mkwc-{name}-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try { test(directory); } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + /// + /// The install path derives every identity from the hashes it streamed out of the payload and + /// the shipped inventory; repair derives them from the disk. Both must agree bit for bit across + /// every selection rule (nodtool, runtime/assets, provenance.json, the widened aurora-main and + /// runtime/third_party sets, the native index replacement, and the per-release input lists). + /// + private static void TestStreamDiskIdentityParity() => WithTempDirectory("parity", directory => + { + var release = BuildFakeRelease(directory); + if (release.Disk.TranslationByRelease.Count != FakeProjects.Length) + throw new Exception("Not every translation project received a per-release identity."); + + using var payload = PayloadArchive.OpenZip(release.Zip); + var inventory = payload.TryReadInventory(release.Manifest) + ?? throw new Exception("The shipped inventory was not read back."); + var install = Path.Combine(directory, "install"); + var extracted = ExtractRelease(payload, install); + inventory.VerifyExtracted(InstalledLayout.ToolkitEntryPrefix, extracted); + inventory.VerifyExtracted(InstalledLayout.WorkspaceEntryPrefix, extracted); + foreach (var (path, identity) in extracted) + { + var file = Path.Combine(install, path.Replace('/', Path.DirectorySeparatorChar)); + if (new FileInfo(file).Length != identity.Size || + InputValidation.Sha256File(file) != identity.Sha256) + throw new Exception($"The streamed identity of {path} is not the extracted file's."); + } + + var streamed = InstallerEngine.ComputeInventoryComponents(inventory, install, release.Manifest, _ => { }) + ?? throw new Exception("The inventory did not reproduce the release identities."); + var stagedPul = Path.Combine(install, "BuildWorkspace", "PulsarPacks", "completed", "RetroRewind", "Code.pul"); + Directory.CreateDirectory(Path.GetDirectoryName(stagedPul)!); + File.WriteAllText(stagedPul, "user-owned pul"); + var installedDisk = ToolkitFingerprint.ComputeComponents(install, lister: FakeTranslationInputs, + strictTranslationInputs: true); + if (!streamed.SameIdentities(release.Disk) || !installedDisk.SameIdentities(release.Disk)) + throw new Exception("Stream-derived and disk-derived toolkit identities disagree."); + if (ToolkitFingerprint.ComputePackageComponentsFromHashes(inventory.Hashes()) != + ToolkitFingerprint.ComputePackageComponents(install)) + throw new Exception("Stream-derived and disk-derived package identities disagree."); + + // Tampering with what was streamed must be caught, not folded into an identity. + var tampered = new Dictionary(extracted) + { + ["Toolkit/Ninja/ninja.exe"] = new(5, new string('0', 64)) + }; + try + { + inventory.VerifyExtracted(InstalledLayout.ToolkitEntryPrefix, tampered); + throw new Exception("A payload file that does not match the inventory was accepted."); + } + catch (InvalidDataException) { } + var unlisted = new Dictionary(extracted) + { + ["Toolkit/extra.dll"] = new(1, new string('1', 64)) + }; + try + { + inventory.VerifyExtracted(InstalledLayout.ToolkitEntryPrefix, unlisted); + throw new Exception("A payload file missing from the inventory was accepted."); + } + catch (InvalidDataException) { } + + // A manifest the inventory cannot reproduce discards the shortcut instead of trusting it. + var foreign = new PayloadManifest + { + SchemaVersion = 3, ToolkitFingerprint = new string('9', 64), + ToolkitPackageFingerprint = release.Manifest.ToolkitPackageFingerprint + }; + if (InstallerEngine.ComputeInventoryComponents(inventory, install, foreign, _ => { }) is not null) + throw new Exception("Inventory identities were accepted for a different release."); + // A native index that no longer hashes to its entry must not be trusted for the shortcut. + File.AppendAllText(Path.Combine(install, "BuildWorkspace", "runtime", "native-index.json"), " "); + if (InstallerEngine.ComputeInventoryComponents(inventory, install, release.Manifest, _ => { }) is not null) + throw new Exception("A modified native index was trusted for the inventory identities."); + }); + + private static void TestPayloadInventoryStatCheck() => WithTempDirectory("statcheck", directory => + { + var release = BuildFakeRelease(directory); + using var payload = PayloadArchive.OpenZip(release.Zip); + var inventory = payload.TryReadInventory(release.Manifest)!; + var install = Path.Combine(directory, "install"); + ExtractRelease(payload, install); + + void Expect(bool clean, string description, string prefix = "Toolkit/", bool timestamps = true, + IReadOnlyCollection? excluded = null) + { + var problems = inventory.StatCheck(install, prefix, timestamps, excluded); + if (clean != (problems.Count == 0)) + throw new Exception(description + (problems.Count == 0 ? "" : ": " + string.Join("; ", problems))); + } + + Expect(true, "A freshly extracted toolkit failed its stat check"); + Expect(true, "A freshly extracted workspace failed its stat check", "BuildWorkspace/", timestamps: false); + + var cache = Path.Combine(install, "BuildWorkspace", "generated", "cache.bin"); + Directory.CreateDirectory(Path.GetDirectoryName(cache)!); + File.WriteAllText(cache, "cache"); + Expect(true, "A build cache was reported as foreign workspace content", "BuildWorkspace/", false); + + var foreign = Path.Combine(install, "BuildWorkspace", "runtime", "foreign.txt"); + File.WriteAllText(foreign, "foreign"); + Expect(false, "An unexpected workspace file was accepted", "BuildWorkspace/", false); + File.Delete(foreign); + var dependency = Path.Combine(install, "BuildWorkspace", "Dependencies", "zlib", ".mkwc-layout"); + File.Delete(dependency); + Expect(false, "A quarantined dependency file was accepted", "BuildWorkspace/", false); + File.WriteAllText(dependency, "zlib"); + Expect(true, "A restored dependency file was rejected", "BuildWorkspace/", false); + + var ninja = Path.Combine(install, "Toolkit", "Ninja", "ninja.exe"); + var ninjaBytes = File.ReadAllBytes(ninja); + File.Delete(ninja); + Expect(false, "A missing toolkit file was accepted"); + File.WriteAllBytes(ninja, ninjaBytes); + PayloadArchive.NormalizeExtractedTimestamp(ninja); + Expect(true, "A restored toolkit file was rejected"); + + var cmake = Path.Combine(install, "Toolkit", "CMake", "bin", "cmake.exe"); + File.AppendAllText(cmake, "!"); + PayloadArchive.NormalizeExtractedTimestamp(cmake); + Expect(false, "A toolkit file of the wrong size was accepted"); + File.WriteAllText(cmake, "cmake"); + PayloadArchive.NormalizeExtractedTimestamp(cmake); + + var clang = Path.Combine(install, "Toolkit", "llvm-mingw", "bin", "clang-22.exe"); + File.SetLastWriteTimeUtc(clang, DateTime.UtcNow); + Expect(false, "A toolkit file rewritten in place (same size) was accepted"); + Expect(true, "The timestamp rule was applied where it was not requested", timestamps: false); + PayloadArchive.NormalizeExtractedTimestamp(clang); + // A FAT32/exFAT volume reads the normalized stamp back shifted by the UTC offset. + File.SetLastWriteTimeUtc(clang, PayloadInventory.NormalizedTimestampUtc.AddHours(-9)); + Expect(true, "A normalized timestamp shifted by a UTC offset was rejected"); + PayloadArchive.NormalizeExtractedTimestamp(clang); + + var extra = Path.Combine(install, "Toolkit", "llvm-mingw", "bin", "injected.dll"); + File.WriteAllText(extra, "injected"); + PayloadArchive.NormalizeExtractedTimestamp(extra); + Expect(false, "A foreign toolkit file was accepted"); + File.Delete(extra); + + var translator = Path.Combine(install, "Toolkit", "Translator", "Translator.Cli.exe"); + File.WriteAllText(translator, "a different translator build"); + Expect(false, "A changed translator passed the whole-toolkit stat check"); + Expect(true, "The toolchain stat check looked at the translator", + excluded: [ToolkitFingerprint.TranslatorPrefix]); + + var link = Path.Combine(install, "Toolkit", "linked"); + if (TryCreateDirectoryLink(link, Path.Combine(install, "Toolkit", "Ninja"))) + { + try + { + Expect(false, "A linked directory inside the toolkit was accepted", + excluded: [ToolkitFingerprint.TranslatorPrefix]); + } + finally + { + Directory.Delete(link); + } + } + }); + + /// + /// An unchanged toolkit with stale runtime assets extracts only runtime/assets, and a + /// translator-only update extracts and publishes only Toolkit/Translator, leaving the installed + /// toolchain untouched. + /// + private static void TestPartialPayloadExtraction() => WithTempDirectory("partial", directory => + { + var release = BuildFakeRelease(directory); + using var payload = PayloadArchive.OpenZip(release.Zip); + var inventory = payload.TryReadInventory(release.Manifest)!; + + var assetsOnly = Path.Combine(directory, "assets-only"); + var extracted = new Dictionary(StringComparer.Ordinal); + payload.ExtractDirectory("BuildWorkspace/runtime/assets/", + Path.Combine(InstalledLayout.Workspace(assetsOnly), "runtime", "assets"), extracted); + inventory.VerifyExtracted("BuildWorkspace/runtime/assets/", extracted); + if (extracted.Count == 0 || extracted.Keys.Any(path => + !path.StartsWith("BuildWorkspace/runtime/assets/", StringComparison.Ordinal))) + throw new Exception("The asset-only extraction extracted something other than runtime/assets."); + if (Directory.EnumerateFiles(assetsOnly, "*", SearchOption.AllDirectories).Count() != extracted.Count || + ToolkitFingerprint.ComputeRuntimeAssets(assetsOnly) != release.Manifest.RuntimeAssetsFingerprint) + throw new Exception("The asset-only extraction does not reproduce the release's runtime assets."); + + // An installation with the previous translator. + var install = Path.Combine(directory, "install"); + ExtractRelease(payload, install); + var translator = Path.Combine(install, "Toolkit", "Translator", "Translator.Cli.exe"); + File.WriteAllText(translator, "previous translator"); + var compiler = Path.Combine(install, "Toolkit", "llvm-mingw", "bin", "clang-22.exe"); + var compilerStamp = File.GetLastWriteTimeUtc(compiler); + + var staging = Path.Combine(install, "staging"); + var stagedToolkit = InstalledLayout.Toolkit(staging); + extracted.Clear(); + payload.ExtractDirectory(ToolkitFingerprint.TranslatorPrefix, Path.Combine(stagedToolkit, "Translator"), + extracted); + inventory.VerifyExtracted(ToolkitFingerprint.TranslatorPrefix, extracted); + if (extracted.Keys.Any(path => !path.StartsWith(ToolkitFingerprint.TranslatorPrefix, StringComparison.Ordinal))) + throw new Exception("The translator-only extraction extracted toolchain files."); + var entries = new List(); + InstallerEngine.AddToolkitEntries(entries, ToolkitRefresh.TranslatorOnly, staging, install); + if (entries.Count != 1 || !entries[0].DestinationPath.EndsWith(Path.Combine("Toolkit", "Translator"), + StringComparison.Ordinal)) + throw new Exception("A translator-only update did not publish exactly Toolkit/Translator."); + using (var transaction = InstallTransaction.Begin(install, null, entries.ToArray())) + { + transaction.Publish(); + transaction.Commit(); + } + if (File.ReadAllText(translator) != "translator-v1" || File.GetLastWriteTimeUtc(compiler) != compilerStamp) + throw new Exception("The translator-only publication did not replace exactly the translator."); + if (inventory.StatCheck(install, InstalledLayout.ToolkitEntryPrefix, true).Count != 0) + throw new Exception("The toolkit is not the release's after a translator-only update."); + + // The transaction refuses overlapping roots, which is why the plans never combine them. + var overlapping = new[] + { + InstallTransactionEntry.Directory(Path.Combine(directory, "payload", "Toolkit"), + InstalledLayout.Toolkit(install)), + InstallTransactionEntry.Directory(Path.Combine(directory, "payload", "Toolkit", "Translator"), + Path.Combine(InstalledLayout.Toolkit(install), "Translator")) + }; + try + { + using var transaction = InstallTransaction.Begin(install, null, overlapping); + throw new Exception("Overlapping Toolkit and Toolkit/Translator entries were accepted."); + } + catch (Exception ex) when (ex is InvalidOperationException or ArgumentException or InvalidDataException) { } + }); + + /// + /// Security software removing published files (under Toolkit/ or BuildWorkspace/Dependencies/) + /// must be repaired by one more publication of just the damaged roots, keeping the build caches, + /// instead of leaving the user re-running setup into the same failure. + /// + private static void TestPublishedToolkitRecovery() => WithTempDirectory("recovery", directory => + { + var release = BuildFakeRelease(directory); + using var payload = PayloadArchive.OpenZip(release.Zip); + var inventory = payload.TryReadInventory(release.Manifest)!; + var install = Path.Combine(directory, "install"); + ExtractRelease(payload, install); + var cache = Path.Combine(install, "BuildWorkspace", "native-build", "CMakeCache.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(cache)!); + File.WriteAllText(cache, "kept"); + + var engine = new InstallerEngine(new DelegatingInstallReporter(_ => { })); + InstallerEngine.InstallContext Context() => new(new Installation(install), Path.Combine(install, "staging"), + payload, release.Manifest, inventory, new GameRelease(), null, + new InstallOptions { GamePath = "game.iso", InstallDirectory = install }, null, null, false); + + var intact = engine.EnsurePublishedToolkitIntact(Context(), CancellationToken.None) + ?? throw new Exception("An intact publication did not yield verified identities."); + if (!intact.SameIdentities(release.Disk)) + throw new Exception("The verified identities are not the release's."); + + var ninja = Path.Combine(install, "Toolkit", "Ninja", "ninja.exe"); + var dependency = Path.Combine(install, "BuildWorkspace", "Dependencies", "zlib", ".mkwc-layout"); + File.Delete(ninja); + File.Delete(dependency); + var recovered = engine.EnsurePublishedToolkitIntact(Context(), CancellationToken.None); + if (!File.Exists(ninja) || !File.Exists(dependency) || File.ReadAllText(cache) != "kept") + throw new Exception("The damaged roots were not republished with the build caches kept."); + if (recovered is null || !recovered.SameIdentities(release.Disk)) + throw new Exception("A recovered publication did not yield the release's identities."); + if (inventory.StatCheck(install, "Toolkit/", true).Count != 0 || + inventory.StatCheck(install, "BuildWorkspace/", false).Count != 0) + throw new Exception("The recovered installation still differs from the release."); + + // Damage only the workspace: the toolkit must not be republished needlessly. + var compiler = Path.Combine(install, "Toolkit", "llvm-mingw", "bin", "clang-22.exe"); + var toolkitNode = new FileInfo(compiler).CreationTimeUtc; + File.Delete(dependency); + engine.EnsurePublishedToolkitIntact(Context(), CancellationToken.None); + if (!File.Exists(dependency) || new FileInfo(compiler).CreationTimeUtc != toolkitNode) + throw new Exception("Workspace-only damage republished the toolkit too."); + }); + + private static void TestPreverifiedToolkitIdentities() => WithTempDirectory("preverified", root => + { + CreateFakeToolkit(root); + var fingerprint = ToolkitFingerprint.Compute(root); + var installation = new Installation(root); + installation.WriteToolkitState(fingerprint, ToolkitFingerprint.ComputePackage(root), "wiicompiled-v1", + ToolkitFingerprint.ComputeRuntimeAssets(root)); + var repair = new ProductRepairService(installation, new DelegatingInstallReporter(_ => { })); + var preverified = new ToolkitFingerprintComponents(fingerprint, "translation", "native"); + + File.WriteAllText(Path.Combine(root, "BuildWorkspace", "runtime", "src", "main.cpp"), "tampered"); + if (!ReferenceEquals(repair.VerifyToolkitForCompilation(fingerprint, preverified: preverified), preverified)) + throw new Exception("Identities proved by the installing operation were not used."); + try + { + repair.VerifyToolkitForCompilation(fingerprint); + throw new Exception("A modified toolkit was accepted without preverified identities."); + } + catch (InvalidDataException ex) + { + if (!ToolkitIntegrity.IsFailure(ex)) + throw new Exception("A toolkit integrity failure is not recognizable as one, so setup could not recover."); + } + try + { + repair.VerifyToolkitForCompilation(fingerprint, + preverified: preverified with { Compile = new string('0', 64) }); + throw new Exception("Preverified identities of a different toolkit skipped verification."); + } + catch (InvalidDataException) { } + }); + + /// + /// The native-toolchain identity follows what compiles objects, not the scripts' source text; + /// the compile identity covers every byte the precompiled-package gate hashes; the package halves + /// split exactly at Toolkit/Translator; and each release's translation identity follows only the + /// project files that release reads. + /// + private static void TestNarrowedCacheIdentities() => WithTempDirectory("narrowed", directory => + { + var root = Path.Combine(directory, "payload"); + CreateFakePayload(root); + ToolkitFingerprintComponents Components() => + ToolkitFingerprint.ComputeComponents(root, lister: FakeTranslationInputs, strictTranslationInputs: true); + string PathOf(string relative) => Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar)); + var before = Components(); + + void Change(string relative, bool compile, bool translation, bool native, string description) + { + var path = PathOf(relative); + var original = File.ReadAllText(path); + var previous = Components(); + File.WriteAllText(path, original + " changed"); + var after = Components(); + File.WriteAllText(path, original); + if ((after.Compile != previous.Compile) != compile || + (after.Translation != previous.Translation) != translation || + (after.NativeToolchain != previous.NativeToolchain) != native) + throw new Exception(description); + } + + Change("BuildWorkspace/LocalBuild.ps1", compile: true, translation: true, native: false, + "The build script's source text decided the native-toolchain identity."); + Change("BuildWorkspace/NativeBuildFlags.ps1", compile: true, translation: false, native: false, + "The flags script's source text decided the native-toolchain identity."); + Change("BuildWorkspace/" + ToolkitFingerprint.NativeConfigureFlagsFileName, compile: true, + translation: false, native: true, "A configure flag change kept the native build directory."); + Change("Toolkit/Redist/vcruntime140.dll", compile: true, translation: false, native: false, + "A copied runtime DLL decided the native-toolchain identity."); + Change("Toolkit/CMake/doc/cmake/LICENSE.rst", compile: true, translation: false, native: false, + "CMake documentation decided the native-toolchain identity."); + Change("Toolkit/CMake/share/cmake-4.3/Modules/Foo.cmake", compile: true, translation: false, native: true, + "A CMake module change kept the native build directory."); + Change("Toolkit/Ninja/ninja.exe", compile: true, translation: false, native: true, + "A Ninja change kept the native build directory."); + Change("BuildWorkspace/aurora-main/docs/notes.md", compile: true, translation: false, native: false, + "An aurora-main file the precompiled-package gate hashes is outside the compile identity."); + Change("BuildWorkspace/aurora-main/extern/README", compile: true, translation: false, native: false, + "An aurora-main/extern file is outside the compile identity."); + Change("BuildWorkspace/runtime/third_party/cryptopp/LICENSE", compile: true, translation: false, + native: false, "A vendored file the precompiled-package gate hashes is outside the compile identity."); + Change("BuildWorkspace/aurora-main/.github/workflow.yml", compile: true, translation: false, native: false, + "A source-extension aurora-main file left the compile identity."); + Change("BuildWorkspace/aurora-main/.clang-format", compile: false, translation: false, native: false, + "A dot file no identity consumes changed the compile identity."); + Change("BuildWorkspace/runtime/third_party/.hidden/state.bin", compile: false, translation: false, + native: false, "A vendored dot file changed the compile identity."); + Change("Toolkit/nodtool.exe", compile: false, translation: false, native: false, + "nodtool changed the compile identity."); + Change("BuildWorkspace/Dependencies/native_prebuilt/provenance.json", compile: false, translation: false, + native: false, "A native_prebuilt provenance rewrite changed the compile identity."); + + // Per-release translation identities follow only that release's project inputs. + void ChangeRelease(string relative, string[] changed, string description) + { + var path = PathOf(relative); + var original = File.ReadAllText(path); + var previous = Components(); + File.WriteAllText(path, original + " changed"); + var after = Components(); + File.WriteAllText(path, original); + foreach (var project in FakeProjects) + if ((after.TranslationByRelease[project] != previous.TranslationByRelease[project]) != + changed.Contains(project)) + throw new Exception(description + $" ({project})"); + if (after.Translation == previous.Translation) + throw new Exception("A translation project change kept the whole-project translation identity."); + } + + ChangeRelease("BuildWorkspace/projects/mkwii-ntsc-j/recomp.yml", ["mkwii-ntsc-j"], + "One release's project change invalidated another release's translation."); + ChangeRelease("BuildWorkspace/projects/mkwii/MAP.txt", ["mkwii", "mkwii-ntsc-u"], + "A PAL map change did not follow the regional project that ports from it."); + var registrations = Components(); + File.WriteAllText(PathOf("BuildWorkspace/runtime/src/main.cpp"), "int main_changed();"); + WriteFakeNativeIndex(root, "\"a\""); + var sameRegistrations = Components(); + if (!FakeProjects.All(project => + sameRegistrations.TranslationByRelease[project] == registrations.TranslationByRelease[project])) + throw new Exception("A runtime change with unchanged registrations invalidated a release translation."); + WriteFakeNativeIndex(root, "\"a\", \"b\""); + var newRegistrations = Components(); + if (FakeProjects.Any(project => + newRegistrations.TranslationByRelease[project] == registrations.TranslationByRelease[project])) + throw new Exception("A native registration change kept a release translation."); + + // A lister that fails, or names a file outside the toolkit, can only cost a retranslation. + var failed = ToolkitFingerprint.ComputeComponents(root, + lister: (_, _, _) => throw new InvalidDataException("unavailable")); + if (failed.TranslationByRelease.Count != 0 || failed.Compile != newRegistrations.Compile) + throw new Exception("A failing input lister produced per-release identities."); + try + { + ToolkitFingerprint.ComputeComponents(root, lister: (_, _, _) => [Path.Combine(directory, "outside.txt")], + strictTranslationInputs: true); + throw new Exception("A translation input outside the toolkit was accepted at release-build time."); + } + catch (InvalidDataException) { } + + // Package halves. + var packages = ToolkitFingerprint.ComputePackageComponents(root); + File.WriteAllText(PathOf("Toolkit/Translator/Translator.Cli.exe"), "translator-v9"); + var translatorChanged = ToolkitFingerprint.ComputePackageComponents(root); + if (translatorChanged.Package == packages.Package || translatorChanged.Translator == packages.Translator || + translatorChanged.Toolchain != packages.Toolchain) + throw new Exception("A translator change did not split exactly at Toolkit/Translator."); + File.WriteAllText(PathOf("Toolkit/nodtool.exe"), "nodtool-v9"); + var toolChanged = ToolkitFingerprint.ComputePackageComponents(root); + if (toolChanged.Toolchain == translatorChanged.Toolchain || + toolChanged.Translator != translatorChanged.Translator) + throw new Exception("A toolchain-side change did not split exactly at Toolkit/Translator."); + + // The selection is a superset of the precompiled-package gate's tree hash. + foreach (var relative in new[] + { + "BuildWorkspace/aurora-main/LICENSE", "BuildWorkspace/aurora-main/lib/x/font.ttf", + "BuildWorkspace/aurora-main/build/notes", "BuildWorkspace/runtime/third_party/a/b.bin" + }) + if (!ToolkitFingerprint.IsCompileInput(relative)) + throw new Exception($"{relative} is hashed by the precompiled-package gate but not by the compile identity."); + if (before.Compile == Components().Compile) + throw new Exception("The sequence of changes above did not change the compile identity."); + }); + + /// + /// Wheel Wizard renders the NDJSON stream as a progress bar: steps a release skips must never make + /// it walk backwards, and stage identifiers are passed through unchanged. + /// + private static void TestProgressJsonMonotonic() + { + var original = Console.Out; + var captured = new StringWriter(); + Console.SetOut(captured); + try + { + var reporter = new NdjsonInstallReporter("1.0.0"); + reporter.Progress(InstallStages.Validate, "a", 1); + reporter.Progress(InstallStages.ExtractToolkit, "b", 4); + reporter.Progress(InstallStages.PrepareRetro, "c", 3); + reporter.Progress(InstallStages.Publish, "d", 10); + reporter.Progress(InstallStages.BuildBase, "e", 5); + reporter.Progress(InstallStages.Publish, "f", 99); + reporter.Success("C:\\install"); + } + finally + { + Console.SetOut(original); + } + + var lines = captured.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries); + var progress = lines.Select(line => JsonDocument.Parse(line).RootElement) + .Where(element => element.GetProperty("type").GetString() == "progress").ToList(); + var percents = progress.Select(element => element.GetProperty("percent").GetInt32()).ToList(); + var stages = progress.Select(element => element.GetProperty("stage").GetString()).ToList(); + if (!percents.SequenceEqual([1, 4, 4, 10, 10, 99])) + throw new Exception("Progress percentages were not clamped monotonic: " + string.Join(",", percents)); + if (!stages.SequenceEqual([ + InstallStages.Validate, InstallStages.ExtractToolkit, InstallStages.PrepareRetro, + InstallStages.Publish, InstallStages.BuildBase, InstallStages.Publish + ])) + throw new Exception("Progress stage identifiers were not passed through unchanged."); + if (JsonDocument.Parse(lines[^1]).RootElement.GetProperty("type").GetString() != "result") + throw new Exception("The result line is not the last line."); + } + + /// + /// Installations and payloads from before the inventory and the split identities: everything + /// they lack must fall back to the whole-toolkit behaviour, never to a guess. + /// + private static void TestUpgradeFixtures() => WithTempDirectory("upgrade", directory => + { + // toolkit-state.json as v0.9.x wrote it. + var statePath = Path.Combine(directory, ToolkitState.FileName); + File.WriteAllText(statePath, """ + { + "SchemaVersion": 2, + "ToolkitFingerprint": "aaaa", + "ToolkitPackageFingerprint": "bbbb", + "RuntimeAssetsFingerprint": "cccc", + "TranslationFingerprint": "dddd", + "NativeToolchainFingerprint": "eeee", + "ToolkitReleaseTag": "v0.9.5", + "SetupVersion": "0.9.5", + "UpdatedUtc": "2026-01-01T00:00:00+00:00" + } + """); + var state = JsonState.TryRead(statePath) ?? throw new Exception("An older toolkit state was rejected."); + if (state.ToolkitPackageFingerprint != "bbbb" || state.ToolchainPackageFingerprint != "" || + state.TranslatorPackageFingerprint != "" || state.TranslationFingerprintsByRelease is not { Count: 0 } || + state.NativePrebuiltGateProvenanceSha256 != "") + throw new Exception("An older toolkit state did not read back with empty additive fields."); + // ...so a changed package can never take the translator-only path. + if (InstallerEngine.PlanToolkitRefresh(true, false, false, true, () => true, + sameToolchainPackage: !string.IsNullOrEmpty(state.ToolchainPackageFingerprint), () => true) != + ToolkitRefresh.Full) + throw new Exception("An installation without split package identities skipped a toolkit refresh."); + + // The current state round-trips its additive fields. + var current = new ToolkitState + { + ToolkitFingerprint = "a", ToolkitPackageFingerprint = "b", ToolchainPackageFingerprint = "c", + TranslatorPackageFingerprint = "d", NativePrebuiltGateProvenanceSha256 = "e", + TranslationFingerprintsByRelease = new Dictionary { ["mkwii"] = "f" } + }; + JsonState.Write(statePath, current); + var readBack = JsonState.TryRead(statePath)!; + if (readBack.ToolchainPackageFingerprint != "c" || readBack.TranslatorPackageFingerprint != "d" || + readBack.NativePrebuiltGateProvenanceSha256 != "e" || + readBack.TranslationFingerprintsByRelease.GetValueOrDefault("mkwii") != "f") + throw new Exception("The additive toolkit-state fields do not round-trip."); + + // A schema-3 manifest without the additive identities. + var manifestJson = """ + { + "SchemaVersion": 3, "ProductVersion": "0.9.5", + "SupportedReleases": [ { "GameId": "RMCP01", "DolSha256": "{{DOL}}", "RelSha256": "{{REL}}" } ], + "ToolkitReleaseTag": "", "BuildModel": "local-translation-and-compilation", + "ToolkitFingerprint": "toolkit", "ToolkitPackageFingerprint": "package", + "RuntimeAssetsFingerprint": "assets", "TranslationFingerprint": "translation", + "NativeToolchainFingerprint": "native" + } + """.Replace("{{DOL}}", new string('a', 64)).Replace("{{REL}}", new string('b', 64)); + using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(manifestJson))) + { + var manifest = PayloadArchive.ParseManifest(stream); + if (manifest.ToolchainPackageFingerprint != "" || manifest.TranslationFingerprintsByRelease is not { Count: 0 } || + manifest.NativePrebuiltGateProvenanceSha256 != "") + throw new Exception("A manifest without additive identities did not read back empty."); + } + + // A payload without an inventory, or with one for another release, gets no shortcut. + var release = BuildFakeRelease(Path.Combine(directory, "no-inventory"), includeInventory: false); + using (var payload = PayloadArchive.OpenZip(release.Zip)) + if (payload.TryReadInventory(release.Manifest) is not null) + throw new Exception("A payload without an inventory produced one."); + var withInventory = BuildFakeRelease(Path.Combine(directory, "inventory")); + using (var payload = PayloadArchive.OpenZip(withInventory.Zip)) + { + var other = new PayloadManifest + { + ToolkitFingerprint = withInventory.Manifest.ToolkitFingerprint, ToolkitPackageFingerprint = "other" + }; + if (payload.TryReadInventory(other) is not null) + throw new Exception("An inventory describing another toolkit package was trusted."); + } + + // The build-script argument carries only names it can pass through unambiguously. + var hex = new string('c', 64); + var formatted = LocalBuildService.FormatTranslationFingerprintsByRelease(new Dictionary + { + ["mkwii-ntsc-u"] = hex, ["mkwii"] = hex, ["bad;name"] = hex, ["mkwii-ntsc-j"] = "short" + }); + if (formatted != $"mkwii={hex};mkwii-ntsc-u={hex}") + throw new Exception("The per-release translation identities were not formatted canonically: " + formatted); + }); +} diff --git a/Launcher/WiiCompiled.Setup.Windows/SelfTests.cs b/Launcher/WiiCompiled.Setup.Windows/SelfTests.cs index f688a8acd..cfeb6f7d1 100644 --- a/Launcher/WiiCompiled.Setup.Windows/SelfTests.cs +++ b/Launcher/WiiCompiled.Setup.Windows/SelfTests.cs @@ -5,7 +5,7 @@ namespace WiiCompiled.Setup.Windows; -internal static class SelfTests +internal static partial class SelfTests { public static int Run() { @@ -64,6 +64,7 @@ public static int Run() Test("Toolkit fingerprint", TestToolkitFingerprint, failures); Test("Retro Rewind inspection state machine", TestCodePulStateMachine, failures); Test("Products report contract", TestProductsReport, failures); + RegisterPayloadTests(failures); foreach (var failure in failures) Console.Error.WriteLine("FAILED " + failure); return failures.Count == 0 ? 0 : 1; } @@ -282,19 +283,46 @@ private static void TestWorkspaceTimestampReconciliation() private static void TestToolkitRefreshDecision() { - if (!InstallerEngine.MustRefreshToolkit(sameToolkit: false, samePackageContent: true, - nodToolPresent: true)) - throw new Exception("A republished workspace kept the installed toolkit; the shipped " + - "translator and project file could come from different releases."); - if (!InstallerEngine.MustRefreshToolkit(sameToolkit: true, samePackageContent: false, - nodToolPresent: true)) + var statCalls = 0; + Func Stat(bool result) => () => { statCalls++; return result; }; + ToolkitRefresh Plan(bool inventory, bool sameToolkit, bool samePackage, bool nodTool, bool toolkitStat, + bool sameToolchain = false, bool toolchainStat = false) => + InstallerEngine.PlanToolkitRefresh(inventory, sameToolkit, samePackage, nodTool, Stat(toolkitStat), + sameToolchain, Stat(toolchainStat)); + + // Without a release inventory nothing can be proved cheaply: the original rule applies. + if (Plan(inventory: false, sameToolkit: false, samePackage: true, nodTool: true, toolkitStat: true) != + ToolkitRefresh.Full) + throw new Exception("Without an inventory, a republished workspace kept an unproven installed toolkit."); + if (Plan(false, true, false, true, true) != ToolkitRefresh.Full) throw new Exception("Changed toolkit package content was not extracted."); - if (!InstallerEngine.MustRefreshToolkit(sameToolkit: true, samePackageContent: true, - nodToolPresent: false)) + if (Plan(false, true, true, false, true) != ToolkitRefresh.Full) throw new Exception("A missing nodtool.exe did not force toolkit extraction."); - if (InstallerEngine.MustRefreshToolkit(sameToolkit: true, samePackageContent: true, - nodToolPresent: true)) + if (Plan(false, true, true, true, true) != ToolkitRefresh.None) throw new Exception("An unchanged toolkit was needlessly re-extracted."); + + // With the inventory, an unchanged package is reused exactly when its files pass the stat + // check - whether or not the workspace (sameToolkit) changed with it. + if (Plan(true, false, true, true, toolkitStat: true) != ToolkitRefresh.None) + throw new Exception("An unchanged, intact toolkit package was re-extracted for a workspace-only update."); + if (Plan(true, false, true, true, toolkitStat: false) != ToolkitRefresh.Full) + throw new Exception("A toolkit failing its stat check was reused."); + if (Plan(true, true, true, true, toolkitStat: false) != ToolkitRefresh.Full) + throw new Exception("A same-release toolkit failing its stat check was reused."); + if (Plan(true, true, true, nodTool: false, toolkitStat: true) != ToolkitRefresh.Full) + throw new Exception("A missing nodtool.exe did not force toolkit extraction."); + if (Plan(true, false, false, true, true, sameToolchain: true, toolchainStat: true) != + ToolkitRefresh.TranslatorOnly) + throw new Exception("A translator-only update re-extracted the whole toolchain."); + if (Plan(true, false, false, true, true, sameToolchain: true, toolchainStat: false) != ToolkitRefresh.Full) + throw new Exception("A translator-only update reused a toolchain failing its stat check."); + if (Plan(true, false, false, true, true, sameToolchain: false, toolchainStat: true) != ToolkitRefresh.Full) + throw new Exception("A changed toolchain was not extracted."); + statCalls = 0; + Plan(true, false, false, nodTool: false, toolkitStat: true, sameToolchain: true, toolchainStat: true); + Plan(false, true, true, true, true); + if (statCalls != 0) + throw new Exception("The stat check ran although its answer could not change the plan."); } /// diff --git a/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs b/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs index d7c83b428..b602bd7b6 100644 --- a/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs +++ b/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -6,27 +7,65 @@ namespace WiiCompiled.Setup.Windows; +/// +/// Lists the files one translation project reads (Translator.Cli list-translation-inputs). +/// Returns absolute paths; throws when the list cannot be produced. +/// +internal delegate IReadOnlyList TranslationInputLister(string translatorExecutable, string projectFile, + CancellationToken cancellationToken); + /// /// Content identity of everything that decides what the locally produced executables contain. /// First link of toolkit content -> toolkit-state.json -> per-product build-fingerprint.json: /// unchanged skips retranslation, any change forces a rebuild. Content-based so re-tags are free. /// +/// +/// Every identity is a pure function of a relative path -> SHA-256 map +/// (). The disk walk () and +/// the install path, which reads the same map from the shipped payload inventory it verified while +/// streaming the payload out, therefore cannot disagree about which files they cover. +/// internal static class ToolkitFingerprint { // v6/native-toolchain v2 forces one clean rebuild past a Ninja stale-object bug. + // compile v8 widened aurora-main and runtime/third_party to every non-dot file, a superset of + // what the precompiled-package gate (Get-MkwSourceTreeFingerprint) hashes, plus the shipped + // native configure flags. // translation v2 added runtime/src, which the translator regex-scans for native overrides; // v3 replaced it with the native index extracted from it, whenever that index is current. - private const string Version = "mkwc-toolkit-compile-v7"; + // native-toolchain v3 keeps only what compiles objects (compiler, CMake + its modules, Ninja, + // and the fixed configure flags), no longer the build scripts' source text or copied runtimes. + private const string Version = "mkwc-toolkit-compile-v8"; private const string TranslationVersion = "mkwc-toolkit-translation-v4"; - private const string NativeToolchainVersion = "mkwc-toolkit-native-toolchain-v2"; + private const string TranslationByReleaseVersion = "mkwc-toolkit-translation-release-v1"; + private const string NativeToolchainVersion = "mkwc-toolkit-native-toolchain-v3"; private const string PackageVersion = "mkwc-toolkit-package-v1"; + private const string ToolchainPackageVersion = "mkwc-toolkit-toolchain-package-v1"; + private const string TranslatorPackageVersion = "mkwc-toolkit-translator-package-v1"; private const string RuntimeAssetsVersion = "mkwc-product-runtime-assets-v3"; private const string RuntimeAssetsDescription = "The product runtime assets"; + /// + /// The output of Get-MkwNativeFixedConfigureFlags, written by Build-Installer.ps1 beside + /// LocalBuild.ps1. The native-toolchain identity hashes this rather than the scripts' source + /// text, and LocalBuild.ps1 refuses to reuse a build directory if it disagrees with the script. + /// + public const string NativeConfigureFlagsFileName = "native-configure-flags.txt"; + + private const string T = InstalledLayout.ToolkitEntryPrefix; + private const string W = InstalledLayout.WorkspaceEntryPrefix; + public const string TranslatorPrefix = T + "Translator/"; + private static readonly string[] SourceExtensions = [".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".inl", ".inc", ".s", ".asm", ".cmake", ".txt", ".yml", ".yaml", ".toml", ".json", ".ps1", ".in", ".def", ".patch"]; + private static readonly string[] WorkspaceRootFiles = + ["LocalBuild.ps1", "NativeBuildFlags.ps1", NativeConfigureFlagsFileName]; + + /// The workspace subtrees the compile identity walks. + private static readonly string[] WorkspaceTrees = ["projects", "runtime", "aurora-main", "Dependencies"]; + /// /// Inputs that decide translator output: translator, translation project, the native override /// registrations/effect contracts it extracts from runtime/src (see @@ -35,40 +74,89 @@ internal static class ToolkitFingerprint /// private static readonly string[] TranslationPrefixes = [ - InstalledLayout.ToolkitEntryPrefix + "Translator/", - InstalledLayout.WorkspaceEntryPrefix + "projects/" + TranslatorPrefix, + W + "projects/" ]; private static readonly string[] TranslationFiles = [ - InstalledLayout.WorkspaceEntryPrefix + "LocalBuild.ps1", + // The single source of the base-translation command lines. + W + "LocalBuild.ps1", // Maps the PAL-keyed native index to the installed release's addresses. - InstalledLayout.WorkspaceEntryPrefix + "runtime/include/guest_abi/guest_versions.inc" + W + "runtime/include/guest_abi/guest_versions.inc" ]; - private const string NativeSourcePrefix = InstalledLayout.WorkspaceEntryPrefix + "runtime/src/"; - private const string NativeIndexEntry = InstalledLayout.WorkspaceEntryPrefix + "runtime/native-index.json"; + private const string NativeSourcePrefix = W + "runtime/src/"; + private const string NativeIndexEntry = W + "runtime/native-index.json"; // The file set the translator's native index source digest covers. private static readonly string[] NativeIndexSourceExtensions = [".cpp", ".h", ".hpp"]; /// - /// Inputs that make compiled objects unsafe to reuse: the compiler/CMake/Ninja toolchain, the - /// shipped runtime DLLs, and the scripts owning configure flags. Source/dependency changes are - /// deliberately excluded, since CMake/Ninja already rebuild exactly the affected objects. + /// The relative-path rule of the compile identity. nodtool validates/extracts the user disc but + /// does not influence generated products; everything else in Toolkit can affect translation, + /// compilation, linking, or copied runtime support. runtime/assets is copied beside the + /// executable and tracked by the independent runtime-assets identity, so changing those bytes + /// does not recompile code. native_prebuilt's provenance.json is excluded: its Contents list + /// already identifies every shipped byte, while its BuiltUtc stamp would make a bit-identical + /// re-harvest look like a toolkit change and force a global user-side rebuild for nothing. + /// aurora-main and runtime/third_party cover every non-dot file (plus every source-extension + /// file, dot paths included), a byte-exact superset of the precompiled-package gate's hash. /// - private static readonly string[] NativeToolchainPrefixes = - [ - InstalledLayout.ToolkitEntryPrefix + "llvm-mingw/", - InstalledLayout.ToolkitEntryPrefix + "CMake/", - InstalledLayout.ToolkitEntryPrefix + "Ninja/", - InstalledLayout.ToolkitEntryPrefix + "Redist/" - ]; + internal static bool IsCompileInput(string relative) + { + if (relative.StartsWith(T, StringComparison.Ordinal)) + return !FileName(relative).Equals("nodtool.exe", StringComparison.OrdinalIgnoreCase); + if (!relative.StartsWith(W, StringComparison.Ordinal)) return false; + var rest = relative[W.Length..]; + if (!rest.Contains('/')) + return WorkspaceRootFiles.Contains(rest, StringComparer.Ordinal); + if (rest.StartsWith("projects/", StringComparison.Ordinal)) return true; + if (rest.StartsWith("runtime/", StringComparison.Ordinal)) + { + if (rest.StartsWith("runtime/assets/", StringComparison.OrdinalIgnoreCase)) return false; + if (HasSourceExtension(rest)) return true; + const string thirdParty = "runtime/third_party/"; + return rest.StartsWith(thirdParty, StringComparison.Ordinal) && + !HasDotSegment(rest[thirdParty.Length..]); + } + const string aurora = "aurora-main/"; + if (rest.StartsWith(aurora, StringComparison.Ordinal)) + return HasSourceExtension(rest) || !HasDotSegment(rest[aurora.Length..]); + if (rest.StartsWith("Dependencies/", StringComparison.Ordinal)) + return !rest.EndsWith("native_prebuilt/provenance.json", StringComparison.OrdinalIgnoreCase); + return false; + } - private static readonly string[] NativeToolchainFiles = - [ - InstalledLayout.WorkspaceEntryPrefix + "LocalBuild.ps1", - InstalledLayout.WorkspaceEntryPrefix + "NativeBuildFlags.ps1" - ]; + /// + /// Inputs that make compiled objects unsafe to reuse: the compiler, CMake and the modules it + /// generates build rules from, Ninja, and the fixed configure flags. Source/dependency changes + /// are deliberately excluded, since CMake/Ninja already rebuild exactly the affected objects; + /// LocalBuild.ps1 separately records the configure option names and CPU profile it used. + /// + internal static bool IsNativeToolchainInput(string relative) + { + if (relative.StartsWith(T + "llvm-mingw/", StringComparison.Ordinal)) return true; + if (relative.Equals(T + "CMake/bin/cmake.exe", StringComparison.Ordinal)) return true; + if (relative.Equals(T + "Ninja/ninja.exe", StringComparison.Ordinal)) return true; + if (relative.Equals(W + NativeConfigureFlagsFileName, StringComparison.Ordinal)) return true; + const string share = T + "CMake/share/"; + if (!relative.StartsWith(share, StringComparison.Ordinal)) return false; + var parts = relative[share.Length..].Split('/'); + return parts.Length > 2 && parts[0].StartsWith("cmake-", StringComparison.Ordinal) && + parts[1].Equals("Modules", StringComparison.Ordinal); + } + + private static bool HasSourceExtension(string relative) => + SourceExtensions.Contains(Path.GetExtension(relative), StringComparer.OrdinalIgnoreCase); + + private static bool HasDotSegment(string relative) => + relative.Split('/').Any(part => part.StartsWith('.')); + + private static string FileName(string relative) + { + var slash = relative.LastIndexOf('/'); + return slash < 0 ? relative : relative[(slash + 1)..]; + } /// /// Fingerprint of the toolkit at : the staged payload root at @@ -76,57 +164,219 @@ internal static class ToolkitFingerprint /// path itself never computes this, it compares manifest identity against toolkit-state.json. /// public static string Compute(string root, CancellationToken cancellationToken = default) => - ComputeComponents(root, cancellationToken).Compile; + ComputeComponents(root, cancellationToken, lister: NoTranslationInputs).Compile; /// - /// One walk, three identities: the compile identity plus its translation and native-toolchain + /// One walk, every identity: the compile identity plus its translation and native-toolchain /// subsets. The subsets never gate correctness, compile identity alone decides if products are /// current, they only decide how much completed work carries into the next build. + /// defaults to running the toolkit's own translator; when it fails the + /// per-release translation identities are omitted (or, with , + /// the failure is thrown), which only ever costs a retranslation. /// public static ToolkitFingerprintComponents ComputeComponents(string root, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default, TranslationInputLister? lister = null, + bool strictTranslationInputs = false, Action? diagnostic = null) { root = Path.GetFullPath(root); - var toolkit = InstalledLayout.Toolkit(root); + var hashes = new SortedDictionary(StringComparer.Ordinal); + var selected = new List(); + CollectFiles(selected, InstalledLayout.Toolkit(root), cancellationToken); var workspace = InstalledLayout.Workspace(root); - var entries = new SortedDictionary(StringComparer.Ordinal); - - // nodtool validates/extracts the user disc but does not influence generated products. - // Everything else in Toolkit can affect translation, compilation, linking, or copied - // runtime support and therefore belongs to the compile identity. - AddDirectory(entries, root, toolkit, null, - cancellationToken, - file => !Path.GetFileName(file).Equals("nodtool.exe", StringComparison.OrdinalIgnoreCase)); - AddFile(entries, root, Path.Combine(workspace, "LocalBuild.ps1"), cancellationToken); - AddFile(entries, root, Path.Combine(workspace, "NativeBuildFlags.ps1"), cancellationToken); - AddDirectory(entries, root, Path.Combine(workspace, "projects"), null, cancellationToken); - var runtime = Path.Combine(workspace, "runtime"); - var runtimeAssets = Path.Combine(runtime, "assets"); - // runtime/assets is copied beside the executable; it is deliberately tracked by the - // independent runtime-assets identity below so changing those bytes does not recompile code. - AddDirectory(entries, root, runtime, SourceExtensions, cancellationToken, - file => !FileSystemUtilities.PathContains(runtimeAssets, file)); - AddDirectory(entries, root, Path.Combine(workspace, "aurora-main"), SourceExtensions, + foreach (var name in WorkspaceRootFiles) + { + var file = Path.Combine(workspace, name); + if (File.Exists(file)) selected.Add(file); + } + foreach (var tree in WorkspaceTrees) + CollectFiles(selected, Path.Combine(workspace, tree), cancellationToken); + HashFiles(hashes, root, selected.Where(file => IsCompileInput(Relative(root, file))), cancellationToken); - // The shipped precompiled aurora archives and the pinned Dawn runtime are linked into the - // product, so a change there changes the binary just as surely as a translator change does. - // native_prebuilt's provenance.json is excluded: its Contents list already identifies every - // shipped byte, while its BuiltUtc stamp would make a bit-identical re-harvest look like a - // toolkit change and force a global user-side rebuild for nothing. - AddDirectory(entries, root, Path.Combine(workspace, "Dependencies"), null, cancellationToken, - file => !file.EndsWith( - Path.Combine("native_prebuilt", "provenance.json"), StringComparison.OrdinalIgnoreCase)); - if (entries.Count == 0) + if (hashes.Count == 0) throw new InvalidDataException($"No toolkit files were found under {root}; the installation is incomplete."); + var translationInputs = ListTranslationInputs(root, lister ?? RunTranslatorLister, + strictTranslationInputs, diagnostic, cancellationToken); + if (translationInputs is not null) + { + var listed = translationInputs.Values.SelectMany(files => files) + .Where(relative => !hashes.ContainsKey(relative) && IsPayloadContent(relative)) + .Distinct(StringComparer.Ordinal) + .Select(relative => Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar))) + .ToList(); + HashFiles(hashes, root, listed, cancellationToken); + } + + return ComputeComponentsFromHashes(hashes, relative => ReadText(root, relative), translationInputs); + } + + /// + /// The identities as a pure function of file hashes. may hold more + /// than the identities consume (a whole payload inventory); only the selection rules above + /// decide what counts. supplies the native index document, and + /// maps each translation project directory name to the + /// payload-relative files it reads. + /// + public static ToolkitFingerprintComponents ComputeComponentsFromHashes( + IReadOnlyDictionary hashes, Func readText, + IReadOnlyDictionary>? translationInputs) + { + var entries = new SortedDictionary(StringComparer.Ordinal); + foreach (var (relative, hash) in hashes) + if (IsCompileInput(relative)) entries[relative] = hash; + if (entries.Count == 0) + throw new InvalidDataException("No toolkit files were found; the installation is incomplete."); + + var nativeRegistrations = new SortedDictionary(StringComparer.Ordinal); + AddNativeRegistrations(nativeRegistrations, entries, readText); + var translation = SelectSubset(entries, TranslationPrefixes, TranslationFiles); - AddNativeRegistrations(translation, entries, root); + foreach (var (relative, hash) in nativeRegistrations) translation[relative] = hash; + + var byRelease = new SortedDictionary(StringComparer.Ordinal); + if (translationInputs is not null) + { + foreach (var (project, files) in translationInputs) + { + var identity = ComputeReleaseTranslation(entries, hashes, nativeRegistrations, files); + if (identity is not null) byRelease[project] = identity; + } + } + + var nativeToolchain = new SortedDictionary(StringComparer.Ordinal); + foreach (var (relative, hash) in entries) + if (IsNativeToolchainInput(relative)) nativeToolchain[relative] = hash; + return new ToolkitFingerprintComponents( BuildIdentity(Version, entries), BuildIdentity(TranslationVersion, translation), - BuildIdentity(NativeToolchainVersion, - SelectSubset(entries, NativeToolchainPrefixes, NativeToolchainFiles))); + BuildIdentity(NativeToolchainVersion, nativeToolchain)) + { + TranslationByRelease = byRelease + }; + } + + /// + /// The translation identity of one release: everything the legacy identity covers except the + /// translation projects, which are narrowed to the files that release's project actually reads. + /// Null when a listed input is outside the payload or unknown, so the caller falls back to the + /// whole-projects identity instead of trusting an incomplete list. + /// + private static string? ComputeReleaseTranslation(SortedDictionary entries, + IReadOnlyDictionary hashes, SortedDictionary nativeRegistrations, + IReadOnlyList files) + { + var subset = SelectSubset(entries, [TranslatorPrefix], TranslationFiles); + foreach (var (relative, hash) in nativeRegistrations) subset[relative] = hash; + foreach (var relative in files) + { + // Covered (or deliberately replaced) by the native registrations above. + if (relative.StartsWith(NativeSourcePrefix, StringComparison.Ordinal) || + relative.Equals(NativeIndexEntry, StringComparison.Ordinal)) + continue; + // User-owned inputs staged into the workspace's build caches (a profile's Code.pul under + // PulsarPacks) are not release content, exactly as for the whole-project identity: + // LocalBuild.ps1 decides their effect itself through the base translation's + // modPatchAwareness stamp and check-base-mod-awareness. + if (IsWorkspaceCacheContent(relative)) continue; + if (!IsPayloadContent(relative) || !hashes.TryGetValue(relative, out var hash)) return null; + subset[relative] = hash; + } + return BuildIdentity(TranslationByReleaseVersion, subset); + } + + /// Whether a payload-relative path names shipped Toolkit/BuildWorkspace content. + private static bool IsPayloadContent(string relative) => + relative.StartsWith(T, StringComparison.Ordinal) || + (relative.StartsWith(W, StringComparison.Ordinal) && !IsWorkspaceCacheContent(relative)); + + private static bool IsWorkspaceCacheContent(string relative) => + relative.StartsWith(W, StringComparison.Ordinal) && + PayloadInventory.WorkspaceCacheDirectories.Contains(relative[W.Length..].Split('/')[0], + StringComparer.OrdinalIgnoreCase); + + /// + /// Runs the translator's static input lister for every shipped translation project. Returns + /// null (or throws when strict) when the list cannot be produced. + /// + internal static SortedDictionary>? ListTranslationInputs(string root, + TranslationInputLister lister, bool strict, Action? diagnostic, + CancellationToken cancellationToken) + { + var projects = Path.Combine(InstalledLayout.Workspace(root), "projects"); + var translator = Path.Combine(InstalledLayout.Toolkit(root), "Translator", "Translator.Cli.exe"); + var result = new SortedDictionary>(StringComparer.Ordinal); + try + { + if (!Directory.Exists(projects)) return result; + foreach (var directory in Directory.EnumerateDirectories(projects).Order(StringComparer.Ordinal)) + { + cancellationToken.ThrowIfCancellationRequested(); + var project = Path.Combine(directory, "recomp.yml"); + if (!File.Exists(project)) continue; + var listed = lister(translator, project, cancellationToken); + var relatives = new SortedSet(StringComparer.Ordinal); + foreach (var path in listed) + { + var relative = Path.GetRelativePath(root, Path.GetFullPath(path)).Replace('\\', '/'); + if (Path.IsPathRooted(relative) || relative.StartsWith("../", StringComparison.Ordinal) || + relative == "..") + throw new InvalidDataException( + $"The translation project {Path.GetFileName(directory)} reads {path}, outside the toolkit."); + relatives.Add(relative); + } + if (relatives.Count == 0) + throw new InvalidDataException( + $"The translator listed no inputs for the translation project {Path.GetFileName(directory)}."); + result[Path.GetFileName(directory)] = relatives.ToList(); + } + return result; + } + catch (Exception ex) when (!strict && ex is not OperationCanceledException) + { + diagnostic?.Invoke("The per-release translation identities could not be derived; the " + + "whole-project translation identity applies instead: " + ex.Message); + return null; + } + } + + /// A lister that produces no per-release identities, for callers that only need Compile. + internal static readonly TranslationInputLister NoTranslationInputs = (_, _, _) => + throw new InvalidOperationException("Per-release translation inputs were not requested."); + + /// Runs Translator.Cli list-translation-inputs --project <recomp.yml>. + internal static IReadOnlyList RunTranslatorLister(string translatorExecutable, string projectFile, + CancellationToken cancellationToken) + { + if (!File.Exists(translatorExecutable)) + throw new FileNotFoundException("The bundled translator is missing.", translatorExecutable); + var start = new ProcessStartInfo + { + FileName = translatorExecutable, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + WorkingDirectory = Path.GetDirectoryName(projectFile)! + }; + start.ArgumentList.Add("list-translation-inputs"); + start.ArgumentList.Add("--project"); + start.ArgumentList.Add(projectFile); + using var process = Process.Start(start) + ?? throw new InvalidOperationException("The translator could not be started."); + var stderr = process.StandardError.ReadToEndAsync(cancellationToken); + var stdout = process.StandardOutput.ReadToEndAsync(cancellationToken); + if (!process.WaitForExit(TimeSpan.FromMinutes(2))) + { + try { process.Kill(entireProcessTree: true); } catch { } + throw new TimeoutException("Listing the translation inputs did not finish."); + } + process.WaitForExit(); + if (process.ExitCode != 0) + throw new InvalidDataException( + $"list-translation-inputs failed with exit code {process.ExitCode}: {stderr.Result.Trim()}"); + return stdout.Result.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } private static SortedDictionary SelectSubset(SortedDictionary entries, @@ -148,12 +398,13 @@ private static SortedDictionary SelectSubset(SortedDictionary private static void AddNativeRegistrations(SortedDictionary subset, - SortedDictionary entries, string root) + SortedDictionary entries, Func readText) { var sources = entries.Where(entry => entry.Key.StartsWith(NativeSourcePrefix, StringComparison.Ordinal)) .ToList(); - var registrations = TryHashCurrentNativeIndex( - Path.Combine(InstalledLayout.Workspace(root), "runtime", "native-index.json"), sources); + var registrations = entries.ContainsKey(NativeIndexEntry) + ? TryHashCurrentNativeIndex(readText(NativeIndexEntry), sources) + : null; if (registrations is not null) { subset[NativeIndexEntry] = registrations; @@ -162,12 +413,12 @@ private static void AddNativeRegistrations(SortedDictionary subs foreach (var (relative, hash) in sources) subset[relative] = hash; } - private static string? TryHashCurrentNativeIndex(string path, List> sources) + private static string? TryHashCurrentNativeIndex(string? text, List> sources) { - if (!File.Exists(path)) return null; + if (text is null) return null; JsonObject? document; - try { document = JsonNode.Parse(File.ReadAllText(path)) as JsonObject; } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + try { document = JsonNode.Parse(text) as JsonObject; } + catch (JsonException) { return null; } @@ -191,6 +442,15 @@ private static void AddNativeRegistrations(SortedDictionary subs return Sha256Hex(document.ToJsonString()); } + private static string? ReadText(string root, string relative) + { + try { return File.ReadAllText(Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar))); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + private static string Sha256Hex(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); @@ -249,40 +509,70 @@ public static bool ProductRuntimeAssetsMatch(string productDirectory, string exp } /// Identity of the shipped Toolkit directory, including installer-only tools. - public static string ComputePackage(string root, CancellationToken cancellationToken = default) + public static string ComputePackage(string root, CancellationToken cancellationToken = default) => + ComputePackageComponents(root, cancellationToken).Package; + + /// + /// The whole-Toolkit package identity plus its two halves: the toolchain (everything but the + /// translator) and the translator, so an update that only replaces the translator republishes + /// just Toolkit/Translator. + /// + public static ToolkitPackageComponents ComputePackageComponents(string root, + CancellationToken cancellationToken = default) { root = Path.GetFullPath(root); - var entries = new SortedDictionary(StringComparer.Ordinal); - AddDirectory(entries, root, InstalledLayout.Toolkit(root), null, cancellationToken); - if (entries.Count == 0) + var selected = new List(); + CollectFiles(selected, InstalledLayout.Toolkit(root), cancellationToken); + var hashes = new SortedDictionary(StringComparer.Ordinal); + HashFiles(hashes, root, selected, cancellationToken); + if (hashes.Count == 0) throw new InvalidDataException($"No toolkit package files were found under {root}."); - return BuildIdentity(PackageVersion, entries); + return ComputePackageComponentsFromHashes(hashes); } - /// - /// The toolkit is ~26,000 mostly tiny files (llvm-mingw's headers/libraries dominate), so this - /// walk is bound by per-file open/read overhead, not hashing throughput, minutes rather than - /// seconds on a cold cache under on-access antivirus. Hashing concurrently keeps a compiling - /// repair from taking longer to prove toolkit integrity than to translate with it. - /// - private static void AddDirectory(SortedDictionary entries, string root, string directory, - string[]? extensions, CancellationToken cancellationToken = default, - Func? include = null) + public static ToolkitPackageComponents ComputePackageComponentsFromHashes( + IReadOnlyDictionary hashes) + { + var package = new SortedDictionary(StringComparer.Ordinal); + var toolchain = new SortedDictionary(StringComparer.Ordinal); + var translator = new SortedDictionary(StringComparer.Ordinal); + foreach (var (relative, hash) in hashes) + { + if (!relative.StartsWith(T, StringComparison.Ordinal)) continue; + package[relative] = hash; + (relative.StartsWith(TranslatorPrefix, StringComparison.Ordinal) ? translator : toolchain)[relative] = hash; + } + if (package.Count == 0) + throw new InvalidDataException("No toolkit package files were found."); + return new ToolkitPackageComponents(BuildIdentity(PackageVersion, package), + BuildIdentity(ToolchainPackageVersion, toolchain), + BuildIdentity(TranslatorPackageVersion, translator)); + } + + private static void CollectFiles(List selected, string directory, CancellationToken cancellationToken) { if (!Directory.Exists(directory)) return; - var selected = new List(); foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories)) { cancellationToken.ThrowIfCancellationRequested(); - if (include is not null && !include(file)) continue; - if (extensions is not null && - !extensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase)) - continue; selected.Add(file); } + } + private static string Relative(string root, string file) => + Path.GetRelativePath(root, file).Replace('\\', '/'); + + /// + /// The toolkit is ~26,000 mostly tiny files (llvm-mingw's headers/libraries dominate), so this + /// walk is bound by per-file open/read overhead, not hashing throughput, minutes rather than + /// seconds on a cold cache under on-access antivirus. Hashing concurrently keeps a compiling + /// repair from taking longer to prove toolkit integrity than to translate with it. + /// + private static void HashFiles(SortedDictionary entries, string root, IEnumerable files, + CancellationToken cancellationToken) + { var hashed = new System.Collections.Concurrent.ConcurrentBag<(string Relative, string Hash)>(); - Parallel.ForEach(selected, + Parallel.ForEach(files, new ParallelOptions { CancellationToken = cancellationToken, @@ -291,21 +581,11 @@ private static void AddDirectory(SortedDictionary entries, strin file => { if (!File.Exists(file)) return; - var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); - hashed.Add((relative, InputValidation.Sha256File(file))); + hashed.Add((Relative(root, file), InputValidation.Sha256File(file))); }); foreach (var (relative, hash) in hashed) entries[relative] = hash; } - private static void AddFile(SortedDictionary entries, string root, string file, - CancellationToken cancellationToken = default) - { - if (!File.Exists(file)) return; - cancellationToken.ThrowIfCancellationRequested(); - var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); - entries[relative] = InputValidation.Sha256File(file); - } - private static void AddMappedDirectory(SortedDictionary entries, string directory, string identityRoot, CancellationToken cancellationToken) { @@ -344,9 +624,26 @@ private static string BuildIdentity(string version, SortedDictionary -/// Compile identity plus the two subsets deciding cache reuse: is the +/// Compile identity plus the subsets deciding cache reuse: is the /// authoritative freshness identity, decides if the base translation is -/// still current, decides if compiled objects may still be linked. +/// still current ( narrows it to the project that release +/// reads), decides if compiled objects may still be linked. /// internal sealed record ToolkitFingerprintComponents(string Compile, string Translation, - string NativeToolchain); + string NativeToolchain) +{ + /// Translation identity per translation project directory name; may be empty. + public IReadOnlyDictionary TranslationByRelease { get; init; } = + new SortedDictionary(StringComparer.Ordinal); + + /// Exact equality including the per-release map (records compare maps by reference). + public bool SameIdentities(ToolkitFingerprintComponents other) => + Compile == other.Compile && Translation == other.Translation && + NativeToolchain == other.NativeToolchain && + TranslationByRelease.Count == other.TranslationByRelease.Count && + TranslationByRelease.All(pair => + other.TranslationByRelease.TryGetValue(pair.Key, out var value) && value == pair.Value); +} + +/// The whole-Toolkit package identity and its toolchain/translator halves. +internal sealed record ToolkitPackageComponents(string Package, string Toolchain, string Translator); diff --git a/Launcher/build-appimage.sh b/Launcher/build-appimage.sh index f58b48ca7..a3bfdb44f 100755 --- a/Launcher/build-appimage.sh +++ b/Launcher/build-appimage.sh @@ -234,6 +234,14 @@ else date -u +%s > "$appdir/workspace/.bundle-version" fi +# Content hashes and sizes of the bundled workspace (never mtimes), so AppRun's mkw_sync_tree only +# compares cache files that may have changed. Written last, once the snapshot is final. +# shellcheck source=build-cache.sh +source "$script_dir/build-cache.sh" +echo "Writing the workspace sync manifest..." +mkw_write_sync_manifest "$appdir/workspace" || + { echo "build-appimage.sh: the workspace sync manifest could not be written" >&2; exit 1; } + echo "Writing AppRun..." cat > "$appdir/AppRun" <<'APPRUN' #!/bin/bash @@ -331,6 +339,15 @@ if [[ -z "$appimagetool" ]]; then fi fi +# The setup's product-currency check identifies this exact toolkit (installer, translator, +# toolchain, native prebuilt package and workspace snapshot) by this manifest. It must cover the +# final AppDir, so it is written after everything else is staged. Without it the setup simply +# always rebuilds, so a third-party file name it cannot represent only costs that fast path. +echo "Writing the toolkit manifest..." +if ! mkw_write_sync_manifest "$appdir" .mkw-toolkit-manifest; then + echo "build-appimage.sh: warning: the toolkit manifest could not be written; installs will always rebuild" >&2 +fi + mkdir -p "$output_dir" echo "Packaging..." # appimagetool detects the target architecture from the first ELF executable it finds in the diff --git a/Launcher/build-cache.sh b/Launcher/build-cache.sh index 30e7014c4..b3741fe8e 100644 --- a/Launcher/build-cache.sh +++ b/Launcher/build-cache.sh @@ -193,12 +193,313 @@ mkw_write_identity() { printf '{"SchemaVersion":1,"%s":"%s"}\n' "$2" "$3" > "$1" } +# --------------------------------------------------------------------------------------------- +# Sync manifests. A packaged source tree ships $mkw_sync_manifest_name, written at package time by +# mkw_write_sync_manifest: +# mkw-sync-manifest-v1 +# \t\t (one line per regular file, never mtimes) +# end\t +# After a successful mkw_sync_tree the destination keeps $mkw_sync_state_name, recording what that +# sync left behind: +# mkw-sync-state-v1 +# written\t +# dirs\t\t... +# \t\t\t +# end\t +# A file is only trusted without cmp when its shipped hash and size equal the recorded ones and +# its current size and mtime still equal the recorded ones, with that mtime older than the record +# (a later edit in the same second stays uncertain). Anything missing, malformed or unverifiable +# falls back to comparing every file. +# --------------------------------------------------------------------------------------------- +mkw_sync_manifest_name=.mkw-sync-manifest +mkw_sync_state_name=.mkw-sync-state +mkw_tab=$(printf '\t') +mkw_stat_mode="" + +# Picks a stat that prints "\t\t": GNU/busybox stat -c on Linux, the system BSD +# stat on macOS (a Homebrew GNU stat earlier on PATH must not decide the format). $1 = scratch dir. +mkw_sync_detect_stat() { + local probe="$1/stat-probe" line expected + [[ -n "$mkw_stat_mode" ]] && return 0 + printf 'abc' > "$probe" || return 1 + expected="^3${mkw_tab}[0-9][0-9]*\$" + if [[ "$(uname -s 2>/dev/null)" == Darwin ]]; then + if line=$(/usr/bin/stat -f "%z${mkw_tab}%m" "$probe" 2>/dev/null) && [[ $line =~ $expected ]]; then + mkw_stat_mode=bsd + fi + elif line=$(stat -c "%s${mkw_tab}%Y" "$probe" 2>/dev/null) && [[ $line =~ $expected ]]; then + mkw_stat_mode=gnu + fi + rm -f "$probe" + [[ -n "$mkw_stat_mode" ]] +} + +# Prints "\t\t" for each NUL-separated path on stdin. +mkw_sync_stat_files() { + case "$mkw_stat_mode" in + gnu) xargs -0 stat -c "%s${mkw_tab}%Y${mkw_tab}%n" ;; + bsd) xargs -0 /usr/bin/stat -f "%z${mkw_tab}%m${mkw_tab}%N" ;; + *) return 1 ;; + esac +} + +# Writes $2 with "\t\t" for every regular file under each named +# directory of $1. Fails unless every listed file produced exactly one line. $1 = root, $2 = out. +mkw_sync_stat_tree() { + local base=$1 out=$2 dir names lines; shift 2 + : > "$out.list" || return 1 + for dir in "$@"; do + [[ -d "$base/$dir" ]] || continue + (cd "$base" && find "$dir" -type f -print0) >> "$out.list" 2>/dev/null || return 1 + done + : > "$out" || return 1 + if [[ -s "$out.list" ]]; then + (cd "$base" && mkw_sync_stat_files) < "$out.list" > "$out" 2>/dev/null || return 1 + fi + names=$(tr -cd '\000' < "$out.list" | wc -c) || return 1 + lines=$(wc -l < "$out") || return 1 + (( names == lines )) +} + +# Writes $1/$2 (default $mkw_sync_manifest_name) for every regular file under $1 except itself. +# Paths holding a tab, newline or backslash cannot be represented, so no manifest is written and +# a sync of that tree keeps comparing every file. +mkw_write_sync_manifest() ( + set -o pipefail + root=$1 + name=${2:-$mkw_sync_manifest_name} + cd -- "$root" || exit 1 + rm -f -- "$name" + work=$(mktemp -d "${TMPDIR:-/tmp}/mkw-manifest.XXXXXX") || exit 1 + trap 'rm -rf "$work"' EXIT + mkw_sync_detect_stat "$work" || exit 1 + find . -type f ! -path "./$name" -print0 | LC_ALL=C sort -z > "$work/list" || exit 1 + names=$(tr -cd '\000' < "$work/list" | wc -c) || exit 1 + if (( names > 0 )); then + tr '\000' '\n' < "$work/list" > "$work/lines" || exit 1 + (( $(wc -l < "$work/lines") == names )) || exit 1 + if LC_ALL=C grep -q "[$mkw_tab\\\\]" "$work/lines"; then exit 1; fi + xargs -0 "${mkw_sha256_cmd[@]}" < "$work/list" > "$work/hashes" || exit 1 + mkw_sync_stat_files < "$work/list" > "$work/sizes" || exit 1 + else + : > "$work/hashes"; : > "$work/sizes" + fi + MKW_NAMES=$names awk ' + BEGIN { FS = "\t" } + FNR == 1 { file++ } + file == 1 { + # " " in text mode, " *" where the tool defaults to binary mode. + if (length($0) < 68 || (substr($0, 65, 2) != " " && substr($0, 65, 2) != " *")) { bad = 1; next } + path = substr($0, 67); sub(/^\.\//, "", path); sha[path] = substr($0, 1, 64); next + } + { + path = substr($0, length($1) + length($2) + 3); sub(/^\.\//, "", path) + if (!(path in sha) || $1 !~ /^[0-9][0-9]*$/) { bad = 1; next } + line[++n] = sha[path] "\t" $1 "\t" path + } + END { + if (bad || n != ENVIRON["MKW_NAMES"] + 0) exit 1 + print "mkw-sync-manifest-v1" + for (i = 1; i <= n; i++) print line[i] + print "end\t" n + } + ' "$work/hashes" "$work/sizes" > "$work/manifest" || exit 1 + # An empty hashes file never reaches FNR == 1, so an empty tree is only valid with no files. + if (( names == 0 )); then printf 'mkw-sync-manifest-v1\nend\t0\n' > "$work/manifest" || exit 1; fi + cp "$work/manifest" "$name.tmp.$$" && mv -f "$name.tmp.$$" "$name" || { rm -f "$name.tmp.$$"; exit 1; } +) + +# Plans (MKW_SYNC_MODE=plan) or records (MKW_SYNC_MODE=state) a sync from sections on stdin: +# @M the shipped manifest, @C the source tree's stat, @S the previous sync state (plan only), +# @D the destination tree's stat. MKW_SYNC_DIRS lists the synced directories, one per line. +# plan prints "T\t" (trusted unchanged) or "U\t" (needs cmp/copy) for every shipped +# file; state prints a complete sync state. Any inconsistency exits non-zero. +mkw_sync_awk=' +function hex64(s) { return length(s) == 64 && s !~ /[^0-9a-f]/ } +function count(s) { return s != "" && s !~ /[^0-9]/ } +function chosen(p, i) { + for (i = 1; i <= ndirs; i++) if (dirs[i] != "" && index(p, dirs[i] "/") == 1) return 1 + return 0 +} +function rest(n, i, skip) { + skip = 0 + for (i = 1; i <= n; i++) skip += length($i) + 1 + return substr($0, skip + 1) +} +BEGIN { + FS = "\t"; mode = ENVIRON["MKW_SYNC_MODE"] + ndirs = split(ENVIRON["MKW_SYNC_DIRS"], dirs, "\n") + if (mode != "plan" && mode != "state") bad = 1 +} +/^@[MCSD]$/ { section = substr($0, 2); line = 0; seen[section]++; next } +{ line++ } +section == "M" { + if (line == 1) { if ($0 != "mkw-sync-manifest-v1") bad = 1; next } + if (mend) { bad = 1; next } + if ($1 == "end") { if (NF != 2 || !count($2) || $2 + 0 != mtotal) bad = 1; mend = 1; next } + if (NF < 3 || !hex64($1) || !count($2)) { bad = 1; next } + path = rest(2); mtotal++ + if (path == "" || !chosen(path)) next + if (path in msha) { bad = 1; next } + msha[path] = $1; msize[path] = $2; order[++mn] = path + next +} +section == "C" { + if (NF < 3 || !count($1) || !count($2)) { bad = 1; next } + path = rest(2) + if (!(path in msha) || msize[path] != $1 || (path in cseen)) { bad = 1; next } + cseen[path] = 1; cn++ + next +} +section == "S" { + if (line == 1) { if ($0 != "mkw-sync-state-v1") bad = 1; next } + if (line == 2) { if ($1 != "written" || NF != 2 || !count($2)) bad = 1; else written = $2 + 0; next } + if (line == 3) { if ($1 != "dirs") bad = 1; next } + if (send) { bad = 1; next } + if ($1 == "end") { if (NF != 2 || !count($2) || $2 + 0 != stotal) bad = 1; send = 1; next } + if (NF < 4 || !hex64($1) || !count($2) || !count($3)) { bad = 1; next } + path = rest(3); stotal++ + if (path in ssha) { bad = 1; next } + ssha[path] = $1; ssize[path] = $2; smtime[path] = $3 + next +} +section == "D" { + if (NF < 3 || !count($1) || !count($2)) { bad = 1; next } + path = rest(2) + if (path in dsize) { bad = 1; next } + dsize[path] = $1; dmtime[path] = $2 + next +} +{ bad = 1 } +END { + if (bad || seen["M"] != 1 || !mend || seen["C"] != 1 || cn != mn || seen["D"] != 1) exit 1 + if (mode == "plan") { + if (seen["S"] != 1 || !send) exit 1 + for (i = 1; i <= mn; i++) { + path = order[i] + if ((path in ssha) && ssha[path] == msha[path] && ssize[path] == msize[path] && + (path in dsize) && dsize[path] == ssize[path] && dmtime[path] == smtime[path] && + smtime[path] + 0 < written) + print "T\t" path + else + print "U\t" path + } + exit 0 + } + if (seen["S"]) exit 1 + written = ENVIRON["MKW_SYNC_WRITTEN"] + if (!count(written)) exit 1 + dirline = "dirs" + for (i = 1; i <= ndirs; i++) if (dirs[i] != "") dirline = dirline "\t" dirs[i] + for (i = 1; i <= mn; i++) if (!(order[i] in dsize) || dsize[order[i]] != msize[order[i]]) exit 1 + print "mkw-sync-state-v1" + print "written\t" written + print dirline + for (i = 1; i <= mn; i++) print msha[order[i]] "\t" msize[order[i]] "\t" dmtime[order[i]] "\t" order[i] + print "end\t" mn +}' + +# Checks that $1 ships a manifest matching its tree (same files, same sizes, nothing but regular +# files and directories) and leaves the tree's stat in $2/src.stat. $1 = source, $2 = scratch. +mkw_sync_check_source() { + local source=$1 work=$2 dir; shift 2 + [[ -f "$source/$mkw_sync_manifest_name" ]] || return 1 + mkw_sync_detect_stat "$work" || return 1 + : > "$work/odd" || return 1 + for dir in "$@"; do + [[ -e "$source/$dir" || -L "$source/$dir" ]] || continue + (cd "$source" && find "$dir" ! -type f ! -type d -print) >> "$work/odd" 2>/dev/null || return 1 + done + [[ ! -s "$work/odd" ]] || return 1 + mkw_sync_stat_tree "$source" "$work/src.stat" "$@" +} + +# Writes $work/plan for a sync of the named directories. $4 = directories, one per line. +mkw_sync_plan() { + local source=$1 destination=$2 work=$3 dirs=$4; shift 4 + [[ -f "$work/state" ]] || return 1 + mkw_sync_check_source "$source" "$work" "$@" || return 1 + mkw_sync_stat_tree "$destination" "$work/dst.stat" "$@" || return 1 + { + printf '@M\n'; cat "$source/$mkw_sync_manifest_name" + printf '@C\n'; cat "$work/src.stat" + printf '@S\n'; cat "$work/state" + printf '@D\n'; cat "$work/dst.stat" + } > "$work/plan.in" || return 1 + MKW_SYNC_MODE=plan MKW_SYNC_DIRS=$dirs awk "$mkw_sync_awk" "$work/plan.in" > "$work/plan" 2>/dev/null +} + +# Atomically writes $2's sync state from $1's manifest and $2's current files. Must only run after +# a complete, successful sync. $3 = scratch dir, $4 = directories, one per line. +mkw_sync_write_state() { + local source=$1 destination=$2 work=$3 dirs=$4 written tmp; shift 4 + tmp="$destination/$mkw_sync_state_name.tmp.$$" + mkw_sync_check_source "$source" "$work" "$@" || return 1 + written=$(date +%s) || return 1 + [[ "$written" =~ ^[0-9]+$ ]] || return 1 + mkw_sync_stat_tree "$destination" "$work/final.stat" "$@" || return 1 + { + printf '@M\n'; cat "$source/$mkw_sync_manifest_name" + printf '@C\n'; cat "$work/src.stat" + printf '@D\n'; cat "$work/final.stat" + } > "$work/state.in" || return 1 + if MKW_SYNC_MODE=state MKW_SYNC_WRITTEN=$written MKW_SYNC_DIRS=$dirs awk "$mkw_sync_awk" "$work/state.in" > "$tmp" 2>/dev/null && + mv -f "$tmp" "$destination/$mkw_sync_state_name"; then + return 0 + fi + rm -f "$tmp" + return 1 +} + +# Records the sync state of a destination that was just populated by a complete copy of $1 (for +# example ditto of the whole packaged workspace). Best effort: without a state the next sync +# compares every file. $1 = source, $2 = destination, remaining = synced directories. +mkw_sync_record_state() { + local source=$1 destination=$2 dir dirs="" work status=1; shift 2 + rm -f "$destination/$mkw_sync_state_name" || return 1 + for dir in "$@"; do dirs="$dirs$dir"$'\n'; done + work=$(mktemp -d "${TMPDIR:-/tmp}/mkw-sync.XXXXXX" 2>/dev/null) || return 1 + if [[ "$work" == /* && -d "$work" ]] && mkw_sync_write_state "$source" "$destination" "$work" "$dirs" "$@"; then + status=0 + fi + rm -rf "$work" + return "$status" +} + +# Copies one file of a sync unless the destination already holds identical bytes. Updates the +# caller's changed/unchanged/failed counters. +mkw_sync_file() { + if [[ -f "$2" ]] && cmp -s "$1" "$2"; then + unchanged=$((unchanged + 1)) + else + rm -rf "$2" + cp "$1" "$2" + [[ $? -eq 0 ]] || failed=1 + changed=$((changed + 1)) + fi +} + # Mirrors each named directory from $1 into $2. Unchanged files are left untouched so their # timestamps (which clang's PCH validation and Ninja compare) survive; changed and new files are -# copied fresh and files no longer shipped are removed. +# copied fresh and files no longer shipped are removed. With a shipped manifest and the state of +# the previous sync, only files that may differ are compared (see the format notes above). mkw_sync_tree() { local source=$1 destination=$2; shift 2 - local dir relative changed=0 unchanged=0 removed=0 + local dir relative kind changed=0 unchanged=0 removed=0 failed=0 fast=0 planned=0 visited=0 + local work="" dirs="" state="$destination/$mkw_sync_state_name" + for dir in "$@"; do dirs="$dirs$dir"$'\n'; done + work=$(mktemp -d "${TMPDIR:-/tmp}/mkw-sync.XXXXXX" 2>/dev/null) || work="" + [[ "$work" == /* && -d "$work" ]] || work="" + if [[ -n "$work" && -f "$state" ]]; then + cp "$state" "$work/state" 2>/dev/null || rm -f "$work/state" + fi + # Invalidated before anything is touched: an interrupted sync must never leave a state that + # vouches for files it was rewriting. + rm -f "$state" + if [[ -n "$work" ]] && mkw_sync_plan "$source" "$destination" "$work" "$dirs" "$@"; then + fast=1 + planned=$(wc -l < "$work/plan") || fast=0 + fi for dir in "$@"; do if [[ ! -d "$source/$dir" ]]; then rm -rf "$destination/$dir" @@ -208,18 +509,34 @@ mkw_sync_tree() { rm -f "$destination/$dir" fi mkdir -p "$destination/$dir" - while IFS= read -r -d '' relative; do - relative=${relative#./} - if [[ -d "$source/$dir/$relative" ]]; then + if (( fast )); then + while IFS= read -r -d '' relative; do + relative=${relative#./} [[ -d "$destination/$dir/$relative" ]] || { rm -f "$destination/$dir/$relative"; mkdir -p "$destination/$dir/$relative"; } - elif [[ -f "$destination/$dir/$relative" ]] && cmp -s "$source/$dir/$relative" "$destination/$dir/$relative"; then - unchanged=$((unchanged + 1)) - else - rm -rf "$destination/$dir/$relative" - cp "$source/$dir/$relative" "$destination/$dir/$relative" - changed=$((changed + 1)) - fi - done < <(cd "$source/$dir" && find . -mindepth 1 -print0) + done < <(cd "$source/$dir" && find . -mindepth 1 -type d -print0) + while IFS="$mkw_tab" read -r kind relative; do + case "$relative" in + "$dir"/*) ;; + *) continue ;; + esac + visited=$((visited + 1)) + if [[ "$kind" == T ]]; then + unchanged=$((unchanged + 1)) + else + relative=${relative#"$dir"/} + mkw_sync_file "$source/$dir/$relative" "$destination/$dir/$relative" + fi + done < "$work/plan" + else + while IFS= read -r -d '' relative; do + relative=${relative#./} + if [[ -d "$source/$dir/$relative" ]]; then + [[ -d "$destination/$dir/$relative" ]] || { rm -f "$destination/$dir/$relative"; mkdir -p "$destination/$dir/$relative"; } + else + mkw_sync_file "$source/$dir/$relative" "$destination/$dir/$relative" + fi + done < <(cd "$source/$dir" && find . -mindepth 1 -print0) + fi while IFS= read -r -d '' relative; do relative=${relative#./} if [[ ! -e "$source/$dir/$relative" && ( -e "$destination/$dir/$relative" || -L "$destination/$dir/$relative" ) ]]; then @@ -228,5 +545,13 @@ mkw_sync_tree() { fi done < <(cd "$destination/$dir" && find . -mindepth 1 -depth -print0) done + # Every planned file must have been visited; otherwise the plan was not fully applied. + (( ! fast || visited == planned )) || failed=1 + if [[ -n "$work" ]]; then + if (( ! failed )); then + mkw_sync_write_state "$source" "$destination" "$work" "$dirs" "$@" || true + fi + rm -rf "$work" + fi printf 'Workspace refreshed: %d changed, %d unchanged, %d removed file(s).\n' "$changed" "$unchanged" "$removed" } diff --git a/Launcher/local-build-macos.command b/Launcher/local-build-macos.command index ecfdb03c0..0bd4e8f97 100755 --- a/Launcher/local-build-macos.command +++ b/Launcher/local-build-macos.command @@ -100,6 +100,9 @@ for tool in "$cmake_bin" "$ninja_bin" "$cc_bin" "$cxx_bin" shasum; do command -v assets="$workspace/Assets"; generated="$workspace/generated" functions="$generated/functions"; metadata="$generated/base_translation_output.json"; manifest_dir="$workspace/build/base" manifest="$manifest_dir/mkwii_base_manifest.json"; shards="$generated/build_shards" +# Per-step skip records (translator --provenance-file); same layout as LocalBuild.ps1. They live +# under generated/, so --force-clean-build discards them with everything else. +step_provenance="$generated/step-provenance" native_build="$workspace/native-build-macos-$macos_arch" x86_cpu_profile=v3 if [[ "$macos_arch" == x86_64 ]]; then @@ -179,13 +182,14 @@ else translator emit-base-manifest --project "$project" --out "$manifest_dir" --functions-dir "$functions" --translation-output-metadata "$metadata" --region "$region" mkw_write_identity "$translation_provenance" TranslationFingerprint "$translation_fingerprint" fi +mkdir -p "$step_provenance" if (( builds_retro )); then - mod_out="$workspace/build/mods/retro_rewind_full_cpp"; args=(translate-mod --project "$project" --profile retro-rewind --base-manifest "$manifest" --base-translation-output-metadata "$metadata" --code-pul "$retro_root/Binaries/Code.pul" --mod-root "$retro_root" --mod-name 'Retro Rewind' --region "$region" --out "$mod_out" --prefer-cached-inputs --emit-cpp --threads "$translator_threads") + mod_out="$workspace/build/mods/retro_rewind_full_cpp"; args=(translate-mod --project "$project" --profile retro-rewind --base-manifest "$manifest" --base-translation-output-metadata "$metadata" --code-pul "$retro_root/Binaries/Code.pul" --mod-root "$retro_root" --mod-name 'Retro Rewind' --region "$region" --out "$mod_out" --prefer-cached-inputs --emit-cpp --threads "$translator_threads" --provenance-file "$step_provenance/translate-mod.json") if (( skip_retro_wfc )); then args+=(--skip-retro-wfc); else payload_file=$(mkw_retro_wfc_payload_file "$project") || fail "$project pins no Retro-WFC payload"; offline_payload="$retro_wfc/$payload_file"; assert_file "$offline_payload" 'Offline Retro-WFC payload'; args+=(--retro-wfc-payload "$offline_payload"); fi step translate-mod 'Translating Retro Rewind'; translator "${args[@]}" fi -step generate-data-init 'Generating local game data initialization'; translator generate-data-init --project "$project" -args=(emit-build-shards --project "$project" --base-metadata "$metadata" --base-functions-dir "$functions" --native-source-dir "$workspace/runtime/src" --out "$shards") +step generate-data-init 'Generating local game data initialization'; translator generate-data-init --project "$project" --provenance-file "$step_provenance/generate-data-init.json" +args=(emit-build-shards --project "$project" --base-metadata "$metadata" --base-functions-dir "$functions" --native-source-dir "$workspace/runtime/src" --out "$shards" --provenance-file "$step_provenance/emit-build-shards.json") if (( builds_retro )); then args+=(--resolved-profile "$mod_out/resolved_dispatch_profile.json" --retro-cpp-dir "$mod_out/cpp"); fi step emit-build-shards 'Preparing native build shards'; translator "${args[@]}" diff --git a/Launcher/local-build.sh b/Launcher/local-build.sh index 326e04748..e13db67bc 100755 --- a/Launcher/local-build.sh +++ b/Launcher/local-build.sh @@ -234,6 +234,9 @@ base_manifest=$base_manifest_dir/mkwii_base_manifest.json shards=$generated/build_shards build=$workspace/native-build translation_provenance=$generated/translation-provenance.json +# Per-step skip records (translator --provenance-file); same layout as LocalBuild.ps1. They live +# under generated/, so --force-clean-build discards them with everything else. +step_provenance_dir=$generated/step-provenance toolchain_provenance=$build/toolchain-provenance.json retro_root=${retro_rewind_package_dir:-$workspace/PulsarPacks/completed/RetroRewind/RetroRewind6} @@ -386,6 +389,8 @@ else mkw_write_identity "$translation_provenance" TranslationFingerprint "$translation_fingerprint" fi +mkdir -p "$step_provenance_dir" + if (( builds_retro )); then code_pul=$retro_root/Binaries/Code.pul assert_file "$code_pul" "Retro Rewind Code.pul" @@ -394,7 +399,8 @@ if (( builds_retro )); then --base-manifest "$base_manifest" --base-translation-output-metadata "$base_metadata" --code-pul "$code_pul" --mod-root "$retro_root" --mod-name "Retro Rewind" --region "$region" --out "$retro_out" --prefer-cached-inputs --emit-cpp - --threads "$translator_threads") + --threads "$translator_threads" + --provenance-file "$step_provenance_dir/translate-mod.json") if (( skip_retro_wfc_payload )); then translate_mod_args+=(--skip-retro-wfc) else @@ -408,10 +414,11 @@ if (( builds_retro )); then fi log_step generate-data-init "Generating local game data initialization" -translator generate-data-init --project "$project" +translator generate-data-init --project "$project" --provenance-file "$step_provenance_dir/generate-data-init.json" shard_args=(emit-build-shards --project "$project" --base-metadata "$base_metadata" - --base-functions-dir "$functions" --native-source-dir "$workspace/runtime/src" --out "$shards") + --base-functions-dir "$functions" --native-source-dir "$workspace/runtime/src" --out "$shards" + --provenance-file "$step_provenance_dir/emit-build-shards.json") if (( builds_retro )); then retro_out=$workspace/build/mods/retro_rewind_full_cpp shard_args+=(--resolved-profile "$retro_out/resolved_dispatch_profile.json" diff --git a/Launcher/macos/build-setup-pkg.command b/Launcher/macos/build-setup-pkg.command index ee34ed9f0..cb38f463d 100755 --- a/Launcher/macos/build-setup-pkg.command +++ b/Launcher/macos/build-setup-pkg.command @@ -153,7 +153,8 @@ copy_clean "$script_dir/sync-workspace.command" "$resources/sync-workspace.comma # Copy only the build inputs. This deliberately avoids a maintainer's ignored # output directories, local disc extraction, and developer-only packaging. mkdir -p "$resources/workspace" -for source in aurora-main projects runtime translator; do +# No translator/ sources: setup.command and wiicompiled-setup both run the bundled Translator.Cli. +for source in aurora-main projects runtime; do [[ -d "$workspace/$source" ]] || fail "required workspace directory is missing: $source" [[ "$source" != aurora-main || -f "$workspace/$source/CMakeLists.txt" ]] || fail "aurora-main is empty; run git submodule update --init --recursive" @@ -177,12 +178,33 @@ chmod +x "$resources/workspace/Launcher/local-build-macos.command" "$resources/w # setup.command uses this marker to update source inputs in an existing user # workspace without replacing extracted game assets or Retro Rewind files. printf '%s\n' "$version" > "$resources/workspace/.bundle-version" +# Content hashes and sizes of the packaged workspace (never mtimes), so sync-workspace.command only +# compares workspace files that may have changed. Written last, once the workspace is final. +# shellcheck source=../build-cache.sh +source "$script_dir/../build-cache.sh" +mkw_write_sync_manifest "$resources/workspace" || fail 'the workspace sync manifest could not be written' mkdir -p "$resources/tools/cmake" "$resources/tools/arm64" "$resources/tools/x86_64" copy_clean "$nodtool_arm64" "$resources/tools/arm64/nodtool"; chmod +x "$resources/tools/arm64/nodtool" copy_clean "$nodtool_x86_64" "$resources/tools/x86_64/nodtool"; chmod +x "$resources/tools/x86_64/nodtool" copy_clean "$translator_arm64" "$resources/tools/arm64/Translator.Cli"; chmod +x "$resources/tools/arm64/Translator.Cli" copy_clean "$translator_x86_64" "$resources/tools/x86_64/Translator.Cli"; chmod +x "$resources/tools/x86_64/Translator.Cli" copy_clean "$cmake_root" "$resources/tools/cmake" +# Only the command-line tools are used. Drop the cmake-gui app (its executable, Qt frameworks and +# plug-ins), the man pages and the HTML documentation. Every license stays: doc/cmake-*/LICENSE.rst, +# the doc/cmake-*/cm*/ third-party notices and share/cmake-*/Licenses are never touched. +rm -rf "$resources/tools/cmake/bin/cmake-gui" "$resources/tools/cmake/MacOS" \ + "$resources/tools/cmake/Frameworks" "$resources/tools/cmake/PlugIns" "$resources/tools/cmake/man" +for cmake_doc in "$resources/tools/cmake/doc"/cmake*; do + [[ -d "$cmake_doc" ]] || continue + for doc_entry in "$cmake_doc"/*; do + [[ -e "$doc_entry" || -L "$doc_entry" ]] || continue + case "${doc_entry##*/}" in + LICENSE*|COPYING*|NOTICE*|Copyright*|cm*) ;; + *) rm -rf "$doc_entry" ;; + esac + done +done +run_for_arch "$host_arch" 'the pruned bundled cmake' "$resources/tools/cmake/bin/cmake" --version copy_clean "$ninja_arm64" "$resources/tools/arm64/ninja"; chmod +x "$resources/tools/arm64/ninja" copy_clean "$ninja_x86_64" "$resources/tools/x86_64/ninja"; chmod +x "$resources/tools/x86_64/ninja" copy_clean "$workspace/LICENSE" "$resources/LICENSE" diff --git a/Launcher/macos/extract-disc.command b/Launcher/macos/extract-disc.command index 7aaf3849c..b7d7409ea 100755 --- a/Launcher/macos/extract-disc.command +++ b/Launcher/macos/extract-disc.command @@ -44,6 +44,21 @@ done assets_dir=$(mkdir -p "$assets_dir" && cd "$assets_dir" && pwd) +# An interrupted earlier run can leave its stage or backup behind. Remove only those whose owning +# process is gone; backups named by older versions (no process id) are left alone. +stale_stage_pattern='^[.]extract-stage-([0-9]+)$' +stale_backup_pattern='^[.]previous-extraction-([0-9]+)-[0-9]{8}-[0-9]{6}$' +for stale in "$assets_dir"/.extract-stage-* "$assets_dir"/.previous-extraction-*; do + [[ -e "$stale" || -L "$stale" ]] || continue + stale_name=${stale##*/} + if [[ "$stale_name" =~ $stale_stage_pattern || "$stale_name" =~ $stale_backup_pattern ]]; then + stale_pid=${BASH_REMATCH[1]} + if ! kill -0 "$stale_pid" 2>/dev/null; then + rm -rf "$stale" + fi + fi +done + # The disc's game ID selects the release, so an existing extraction is only reused for the same one. printf 'MKWCBUILD:STEP:validate-disc Checking the selected disc image\n' disc_info=$("$nodtool" info "$game") || fail 'nodtool could not read the disc image' @@ -63,35 +78,33 @@ if [[ -d "$assets_dir/DATA/files" && -f "$assets_dir/.data-manifest" && -f "$ass printf 'MKWCBUILD:STEP:disc-ready Reusing the verified extracted game assets\n' exit 0 fi -scratch=$(mktemp -d "${TMPDIR:-/tmp}/wiicompiled-disc.XXXXXX") -cleanup() { rm -rf "$scratch"; } +# Extracted straight into a stage beside the destination, so the final replacement stays on one +# volume and the data partition is never copied a second time. +stage="$assets_dir/.extract-stage-$$" +cleanup() { rm -rf "$stage"; } trap cleanup EXIT +rm -rf "$stage" +mkdir -p "$stage" printf 'MKWCBUILD:STEP:extract-disc Extracting the user-owned disc image\n' -"$nodtool" extract "$game" "$scratch/extracted" +"$nodtool" extract "$game" "$stage/DATA" -dol=$(find "$scratch/extracted" -type f -path '*/sys/main.dol' -print -quit) -rel=$(find "$scratch/extracted" -type f -path '*/files/rel/StaticR.rel' -print -quit) -[[ -n "$dol" ]] || fail 'nodtool extraction did not contain sys/main.dol' -[[ -n "$rel" ]] || fail 'nodtool extraction did not contain files/rel/StaticR.rel' +dol="$stage/DATA/sys/main.dol" +rel="$stage/DATA/files/rel/StaticR.rel" +[[ -f "$dol" ]] || fail 'nodtool extraction did not contain sys/main.dol' +[[ -f "$rel" ]] || fail 'nodtool extraction did not contain files/rel/StaticR.rel' dol_sha=$(sha256 "$dol") rel_sha=$(sha256 "$rel") [[ $dol_sha == "$expected_dol_sha256" ]] || fail "main.dol does not match the clean $game_id image (expected $expected_dol_sha256, got $dol_sha)" [[ $rel_sha == "$expected_rel_sha256" ]] || fail "StaticR.rel does not match the clean $game_id image (expected $expected_rel_sha256, got $rel_sha)" -data_root=$(dirname "$(dirname "$dol")") -[[ -d "$data_root/files" ]] || fail 'nodtool extraction did not contain the Wii files directory' +[[ -d "$stage/DATA/files" ]] || fail 'nodtool extraction did not contain the Wii files directory' -# Stage beside the destination so the final replacement stays on one volume. -stage="$assets_dir/.extract-stage-$$" -rm -rf "$stage" -mkdir -p "$stage" -ditto "$data_root" "$stage/DATA" ditto "$dol" "$stage/main.dol" ditto "$rel" "$stage/StaticR.rel" data_manifest "$stage/DATA" > "$stage/.data-manifest" -backup="$assets_dir/.previous-extraction-$(date +%Y%m%d-%H%M%S)" +backup="$assets_dir/.previous-extraction-$$-$(date +%Y%m%d-%H%M%S)" if [[ -e "$assets_dir/DATA" || -e "$assets_dir/.data-manifest" || -e "$assets_dir/main.dol" || -e "$assets_dir/StaticR.rel" ]]; then mkdir -p "$backup" for item in DATA .data-manifest main.dol StaticR.rel; do diff --git a/Launcher/macos/sync-workspace.command b/Launcher/macos/sync-workspace.command index fba673825..01908481f 100755 --- a/Launcher/macos/sync-workspace.command +++ b/Launcher/macos/sync-workspace.command @@ -18,15 +18,21 @@ fi if (( needs_workspace_refresh )); then printf 'Preparing the local build workspace...\n' + # shellcheck source=../build-cache.sh + source "$workspace_source/Launcher/build-cache.sh" if [[ ! -d "$workspace" ]]; then /usr/bin/ditto "$workspace_source" "$workspace" + # Lets the next package update compare only files that may have changed. Best effort: + # without it that update compares every file, as before. + mkw_sync_record_state "$workspace_source" "$workspace" aurora-main projects runtime Launcher || true else # Refresh only packaged source inputs. Assets and the staged Retro # Rewind package belong to the user and stay in place; unchanged files # keep their timestamps so the incremental native build survives. - # shellcheck source=../build-cache.sh - source "$workspace_source/Launcher/build-cache.sh" - mkw_sync_tree "$workspace_source" "$workspace" aurora-main projects runtime translator Launcher + mkw_sync_tree "$workspace_source" "$workspace" aurora-main projects runtime Launcher + # Packages no longer ship the translator sources (the bundled Translator.Cli is used), + # so a copy left by an older package is removed like any other dropped input. + rm -rf "$workspace/translator" /usr/bin/ditto "$source_bundle_version" "$workspace_bundle_version" fi fi diff --git a/runtime/cmake/PublicProducts.cmake b/runtime/cmake/PublicProducts.cmake index 809f22e76..7663f8470 100644 --- a/runtime/cmake/PublicProducts.cmake +++ b/runtime/cmake/PublicProducts.cmake @@ -228,17 +228,20 @@ function(mkw_configure_product target) target_link_libraries(${target} PRIVATE mkw::libco ${CMAKE_DL_LIBS}) endif() if(MKW_PLATFORM_WINDOWS) + # The runtime DLLs the product loads come from the x86_64 target sysroot beside the + # compiler's bin directory (llvm-mingw/x86_64-w64-mingw32/bin), resolved from the compiler path + # instead of spawning the compiler for each DLL and product. The host compiler's own bin + # copies are deliberately never used: they belong to the compiler, not to the target. + if(NOT DEFINED MKW_LLVM_MINGW_TARGET_BIN) + get_filename_component(mkw_compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) + get_filename_component(mkw_llvm_mingw_root "${mkw_compiler_bin}" DIRECTORY) + set(MKW_LLVM_MINGW_TARGET_BIN "${mkw_llvm_mingw_root}/x86_64-w64-mingw32/bin") + endif() foreach(runtime_dll libc++.dll libunwind.dll) - execute_process( - COMMAND "${CMAKE_CXX_COMPILER}" "--print-file-name=${runtime_dll}" - OUTPUT_VARIABLE runtime_dll_path - OUTPUT_STRIP_TRAILING_WHITESPACE) - if(NOT EXISTS "${runtime_dll_path}") - get_filename_component(mkw_compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) - set(runtime_dll_path "${mkw_compiler_bin}/${runtime_dll}") - endif() + set(runtime_dll_path "${MKW_LLVM_MINGW_TARGET_BIN}/${runtime_dll}") if(NOT EXISTS "${runtime_dll_path}") - message(FATAL_ERROR "llvm-mingw runtime DLL not found: ${runtime_dll}") + message(FATAL_ERROR + "llvm-mingw x86_64 target runtime DLL not found: ${runtime_dll_path}") endif() add_custom_command(TARGET ${target} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different diff --git a/translator/src/Translator.Cli/Program.cs b/translator/src/Translator.Cli/Program.cs index ddb719c89..b529e8d67 100644 --- a/translator/src/Translator.Cli/Program.cs +++ b/translator/src/Translator.Cli/Program.cs @@ -39,6 +39,36 @@ var command = args.Length > 0 ? args[0] : "info"; var (optionValues, enabledFlags, firstCommandArgument, helpRequested, unrecognizedOption) = ParseCommandLineOptions(command, args); +// Static: it must work where the disc pins do not exist, so it runs before the project +// (and its pinned DOL/REL) is loaded and validated. +if (command == "list-translation-inputs") + return RunListTranslationInputs(optionValues.GetValueOrDefault("--project"), helpRequested, unrecognizedOption); +// Opt-in skip gate. Started before the project is loaded, so the project file, function map +// and pinned inputs are read under the recorder like everything else the step touches. +StepProvenanceSession? provenanceSession = null; +if (!helpRequested && unrecognizedOption is null) +{ + var provenanceFile = optionValues.GetValueOrDefault("--provenance-file"); + var accessLog = StepProvenance.AccessLogPathFromEnvironment(); + if (provenanceFile is not null && string.IsNullOrWhiteSpace(provenanceFile)) + { + Console.Error.WriteLine("--provenance-file requires a path."); + return 2; + } + if (provenanceFile is not null || accessLog is not null) + { + provenanceSession = StepProvenanceSession.Start( + provenanceFile, + accessLog, + StepInvocation.ForCurrentProcess(command, args, EffectiveThreadCount(optionValues.GetValueOrDefault("--threads"))), + Console.Error); + if (provenanceSession is { IsCurrent: true }) + { + Console.WriteLine($"MKWCBUILD: {command} is current; skipping"); + return 0; + } + } +} var projectOption = optionValues.GetValueOrDefault("--project"); var profileOption = optionValues.GetValueOrDefault("--profile"); var project = !string.IsNullOrWhiteSpace(projectOption) @@ -60,7 +90,7 @@ { GuestSaveRestoreThunks.Current = GuestSaveRestoreThunks.FromFunctionMap(functionMap); } -var root = project?.WorkspaceRoot ?? Directory.GetCurrentDirectory(); +var root = project?.WorkspaceRoot ?? TrackedFs.GetCurrentDirectory(); if (helpRequested) return ShowCommandHelp(command); if (unrecognizedOption is not null) @@ -166,20 +196,79 @@ BaseTranslationOutputMetadata ReadBaseMetadataCached(string path) // Argument registers checked for callback function pointers at every call site var argumentRegisters = new[] { "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10" }; -return command switch -{ - "help" or "--help" or "-h" or "-?" => ShowGlobalHelp(), - "info" or "--info" or "--version" => RunInfo(), - "generate-data-init" => RunGenerateDataInit(), - "translate-recursive" => RunTranslateRecursive(firstCommandArgument), - "translate-mod" => RunTranslateMod(), - "emit-build-shards" => RunEmitBuildShards(), - "emit-native-index" => RunEmitNativeIndex(), - "emit-base-manifest" => RunEmitBaseManifest(), - "check-base-mod-awareness" => RunCheckBaseModAwareness(), - "validate-retro-wfc-payload" => RunValidateRetroWfcPayload(), - _ => ShowHelp(command) -}; +// Anything but a normal zero return (a failure code or an exception) leaves no provenance record. +var commandExitCode = 1; +try +{ + commandExitCode = command switch + { + "help" or "--help" or "-h" or "-?" => ShowGlobalHelp(), + "info" or "--info" or "--version" => RunInfo(), + "generate-data-init" => RunGenerateDataInit(), + "translate-recursive" => RunTranslateRecursive(firstCommandArgument), + "translate-mod" => RunTranslateMod(), + "emit-build-shards" => RunEmitBuildShards(), + "emit-native-index" => RunEmitNativeIndex(), + "emit-base-manifest" => RunEmitBaseManifest(), + "check-base-mod-awareness" => RunCheckBaseModAwareness(), + "validate-retro-wfc-payload" => RunValidateRetroWfcPayload(), + _ => ShowHelp(command) + }; + return commandExitCode; +} +finally +{ + provenanceSession?.Finish(commandExitCode); +} + +/// +/// Every existing file a translation of the project at reads, +/// except the pinned disc inputs: one absolute path per line on stdout, ordinal order. +/// Static - nothing is translated and the DOL/REL are neither opened nor required. +/// +static int RunListTranslationInputs(string? projectPath, bool helpRequested, string? unrecognizedOption) +{ + if (helpRequested) return ShowCommandHelp("list-translation-inputs"); + if (unrecognizedOption is not null) + { + Console.Error.WriteLine($"Unrecognized option '{unrecognizedOption}' for command 'list-translation-inputs'."); + WriteUsage(Console.Error, new[] { "list-translation-inputs" }); + return 2; + } + if (string.IsNullOrWhiteSpace(projectPath)) + { + Console.Error.WriteLine("list-translation-inputs requires --project ."); + return 2; + } + IReadOnlyList inputs; + try + { + inputs = TranslationProjectConfig.ListTranslationInputs(projectPath); + } + catch (Exception ex) + { + Console.Error.WriteLine($"list-translation-inputs failed: {ex.Message}"); + return 1; + } + var output = new StringBuilder(); + foreach (var input in inputs) output.Append(input).Append('\n'); + Console.Out.Write(output.ToString()); + Console.Out.Flush(); + return 0; +} + +static int? EffectiveThreadCount(string? threadsText) +{ + if (threadsText is null) return Math.Max(1, Environment.ProcessorCount); + try + { + return Math.Max(1, ParseInt(threadsText)); + } + catch (Exception ex) when (ex is FormatException or OverflowException or ArgumentException) + { + return null; + } +} /// /// May the workspace's completed base translation be reused for the Code.pul about to build? @@ -201,7 +290,7 @@ int RunCheckBaseModAwareness() Console.Error.WriteLine("[translator] check-base-mod-awareness needs --profile."); return 1; } - if (!File.Exists(codePul)) + if (!TrackedFs.FileExists(codePul)) { Console.Error.WriteLine($"[translator] Code.pul not found: {codePul}"); return 1; @@ -234,7 +323,7 @@ RuntimeNativeIndex ResolveRegionalNativeIndex(string nativeSourceDirectory, stri var region = GuestRegions.FromGameId(RequireProject().Identity.GameId); var tablePath = GuestAddressTable.DefaultPath(nativeSourceDirectory); // A runtime without a table can only be built for PAL. - if (region == GuestRegion.Pal && !File.Exists(tablePath)) + if (region == GuestRegion.Pal && !TrackedFs.FileExists(tablePath)) return index; return index.ForRegion(GuestAddressTable.Load(tablePath), region); } @@ -263,7 +352,7 @@ int RunEmitBuildShards() Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(nativeSourcePath))!, RuntimeNativeIndexFile.DefaultFileName) : Path.GetFullPath(nativeIndexOption); - if (!Directory.Exists(nativeSourcePath) && !File.Exists(nativeIndexPath)) + if (!TrackedFs.DirectoryExists(nativeSourcePath) && !TrackedFs.FileExists(nativeIndexPath)) throw new DirectoryNotFoundException(nativeSourcePath); var nativeIndex = ResolveRegionalNativeIndex(nativeSourcePath, nativeIndexPath); var result = TranslatedBuildShardEmitter.Emit(new TranslatedBuildShardOptions( @@ -317,7 +406,7 @@ int RunEmitNativeIndex() } var nativeSourcePath = Path.GetFullPath( optionValues.GetValueOrDefault("--native-source-dir") ?? RequireProject().Runtime.NativeRegistrationRoot); - if (!Directory.Exists(nativeSourcePath)) + if (!TrackedFs.DirectoryExists(nativeSourcePath)) { Console.Error.WriteLine($"[translator] native source directory not found: {nativeSourcePath}"); return 1; @@ -339,29 +428,31 @@ byte[] LoadBinaryInput(string spec, string outDir, string downloadFileName) if (Uri.TryCreate(spec, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)) { - Directory.CreateDirectory(outDir); + TrackedFs.CreateDirectory(outDir); var downloadPath = Path.Combine(outDir, downloadFileName); var cachedPath = ResolveCachedTranslateModInput(downloadPath, downloadFileName, spec); if (preferCachedInputs && cachedPath is not null) { Console.Error.WriteLine($"[translator] using cached input {cachedPath}"); - var cachedBytes = File.ReadAllBytes(cachedPath); + var cachedBytes = TrackedFs.ReadAllBytes(cachedPath); if (!string.Equals(cachedPath, downloadPath, StringComparison.OrdinalIgnoreCase)) { - File.WriteAllBytes(downloadPath, cachedBytes); - File.WriteAllText(downloadPath + ".source", spec); + TrackedFs.WriteAllBytes(downloadPath, cachedBytes); + TrackedFs.WriteAllText(downloadPath + ".source", spec); } return cachedBytes; } Console.Error.WriteLine($"[translator] fetching {uri}"); + // A download can change under the same URL; no file record can prove it current. + TrackedFs.NoteUntrackedInput($"a download of {uri}"); using var client = new System.Net.Http.HttpClient(); var bytes = client.GetByteArrayAsync(uri).GetAwaiter().GetResult(); - File.WriteAllBytes(downloadPath, bytes); - File.WriteAllText(downloadPath + ".source", spec); + TrackedFs.WriteAllBytes(downloadPath, bytes); + TrackedFs.WriteAllText(downloadPath + ".source", spec); return bytes; } - return File.ReadAllBytes(Path.GetFullPath(Path.Combine(root, spec))); + return TrackedFs.ReadAllBytes(Path.GetFullPath(Path.Combine(root, spec))); } string? ResolveCachedTranslateModInput(string outputPath, string fileName, string spec) @@ -389,9 +480,9 @@ bool CachedTranslateModInputMatchesSpec(string path, string spec) // sidecar records that spec so a changed profile URL forces a re-fetch // instead of silently reusing bytes from the previous endpoint. var sourcePath = path + ".source"; - return File.Exists(path) && - File.Exists(sourcePath) && - string.Equals(File.ReadAllText(sourcePath).Trim(), spec.Trim(), StringComparison.Ordinal); + return TrackedFs.FileExists(path) && + TrackedFs.FileExists(sourcePath) && + string.Equals(TrackedFs.ReadAllText(sourcePath).Trim(), spec.Trim(), StringComparison.Ordinal); } static uint AlignUp(uint value, uint alignment) @@ -469,7 +560,7 @@ int RunTranslateRecursive(string? firstCommandArgument) var pruneStale = enabledFlags.Contains("--prune-stale"); if (pruneStale && outputMetadataPath is not null && - File.Exists(outputMetadataPath)) + TrackedFs.FileExists(outputMetadataPath)) { try { @@ -491,7 +582,7 @@ outputMetadataPath is not null && try { - Directory.CreateDirectory(outDir); + TrackedFs.CreateDirectory(outDir); var visited = new HashSet(); var translated = new HashSet(); @@ -1678,21 +1769,21 @@ int RunTranslateMod() void PreserveTranslateModFailureDiagnostics(string stagingDirectory, string publishedOutput, int exitCode) { var diagnosticsDirectory = publishedOutput + ".failed"; - if (Directory.Exists(diagnosticsDirectory)) + if (TrackedFs.DirectoryExists(diagnosticsDirectory)) { - Directory.Delete(diagnosticsDirectory, recursive: true); + TrackedFs.DeleteDirectory(diagnosticsDirectory, recursive: true); } - Directory.CreateDirectory(diagnosticsDirectory); + TrackedFs.CreateDirectory(diagnosticsDirectory); var copied = 0; - foreach (var source in Directory.EnumerateFiles(stagingDirectory, "*", SearchOption.TopDirectoryOnly) + foreach (var source in TrackedFs.EnumerateFiles(stagingDirectory, "*", SearchOption.TopDirectoryOnly) .Where(path => path.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))) { - File.Copy(source, Path.Combine(diagnosticsDirectory, Path.GetFileName(source)), overwrite: true); + TrackedFs.Copy(source, Path.Combine(diagnosticsDirectory, Path.GetFileName(source)), overwrite: true); copied++; } - File.WriteAllText( + TrackedFs.WriteAllText( Path.Combine(diagnosticsDirectory, "failure.txt"), $"translate-mod exited with code {exitCode}. Preserved {copied} top-level diagnostic file(s).{Environment.NewLine}"); Console.Error.WriteLine($"[translator] Preserved failure diagnostics: {diagnosticsDirectory}"); @@ -1728,7 +1819,7 @@ void LogModPhase(string label) // around the patch set it knew about; a base tree that never saw this Code.pul can splice // mod-patched callee bodies inline, silently running vanilla code where the mod's hooks must // win (this shipped once as a character-select LinkList.h:573 panic). - if (File.Exists(baseTranslationOutputMetadataPath) && File.Exists(codePul)) + if (TrackedFs.FileExists(baseTranslationOutputMetadataPath) && TrackedFs.FileExists(codePul)) { var guardedBaseMetadata = ReadBaseMetadataCached(baseTranslationOutputMetadataPath); var codePulSha256 = ChecksumUtilities.Sha256HexOfFile(codePul); @@ -1771,7 +1862,7 @@ void LogModPhase(string label) return 1; } } - else if (!File.Exists(baseTranslationOutputMetadataPath)) + else if (!TrackedFs.FileExists(baseTranslationOutputMetadataPath)) { Console.Error.WriteLine( $"[translator] Warning: no base translation output metadata at {baseTranslationOutputMetadataPath}; " + @@ -1805,7 +1896,7 @@ void LogModPhase(string label) var moduleLinkBase = moduleLinkBaseText is not null ? ParseAddress(moduleLinkBaseText) : profile?.ModuleLinkBase ?? 0x803992E0u; - Directory.CreateDirectory(outDir); + TrackedFs.CreateDirectory(outDir); var pul = KamekPulFile.Load(codePul); var selected = pul.SelectRegion(region); @@ -1830,7 +1921,7 @@ void LogModPhase(string label) $"[translator] Suppressed legacy Retro WFC payload bootstrap hook at 0x{legacyBootstrapHook:X8}; " + "the shared payload is initialized statically."); } - var baseManifest = JsonSerializer.Deserialize(File.ReadAllText(baseManifestPath)) + var baseManifest = JsonSerializer.Deserialize(TrackedFs.ReadAllText(baseManifestPath)) ?? throw new InvalidDataException($"Failed to parse base manifest: {baseManifestPath}"); RetroWfcContractLoweringPlan? retroWfcLoweringPlan = null; RetroWfcPayloadLoadResult? retroWfcPayload = null; @@ -1841,7 +1932,7 @@ void LogModPhase(string label) try { payloadImage = LoadBinaryInput(retroWfcPayloadSpec, outDir, "retro_wfc_payload.bin"); - File.WriteAllBytes(Path.Combine(outDir, "retro_wfc_payload.bin"), payloadImage); + TrackedFs.WriteAllBytes(Path.Combine(outDir, "retro_wfc_payload.bin"), payloadImage); } catch (Exception ex) when (ex is IOException or System.Net.Http.HttpRequestException or UnauthorizedAccessException) { @@ -1931,7 +2022,7 @@ void LogModPhase(string label) } var relocatedModuleImagePath = Path.Combine(outDir, "overlay_images", overlayBuild.ModuleImageFile); - var relocatedModuleImage = File.ReadAllBytes(relocatedModuleImagePath); + var relocatedModuleImage = TrackedFs.ReadAllBytes(relocatedModuleImagePath); continuationPlan = ContinuationPlanner.AddModuleTailJumpContinuations( continuationPlan, @@ -2087,25 +2178,25 @@ void WriteResolvedDispatchProfile( IEnumerable BaseFiles() { - if (File.Exists(baseFunctionsManifest)) + if (TrackedFs.FileExists(baseFunctionsManifest)) { - return File.ReadLines(baseFunctionsManifest) + return TrackedFs.ReadLines(baseFunctionsManifest) .Where(line => !string.IsNullOrWhiteSpace(line)) .Select(line => Path.IsPathRooted(line) ? line : Path.Combine(baseFunctionsDir, Path.GetFileName(line))); } - return Directory.EnumerateFiles(baseFunctionsDir, "*.cpp", SearchOption.AllDirectories); + return TrackedFs.EnumerateFiles(baseFunctionsDir, "*.cpp", SearchOption.AllDirectories); } static IEnumerable<(string File, string Text)> ReadFiles(IEnumerable files) { foreach (var file in files) - if (File.Exists(file)) yield return (file, File.ReadAllText(file)); + if (TrackedFs.FileExists(file)) yield return (file, TrackedFs.ReadAllText(file)); } IEnumerable<(string File, string Text)> BaseSources() { var metadataPath = baseTranslationOutputMetadataPath; - if (File.Exists(metadataPath)) + if (TrackedFs.FileExists(metadataPath)) { var metadata = ReadBaseMetadataCached(metadataPath); if (!string.IsNullOrWhiteSpace(metadata.SourceBundlePath)) @@ -2124,13 +2215,13 @@ IEnumerable BaseFiles() IEnumerable<(string File, string Text)> ModSources() { var bundlePath = Path.Combine(Path.GetDirectoryName(modCppDir)!, "translated_sources.bin"); - if (File.Exists(bundlePath)) + if (TrackedFs.FileExists(bundlePath)) { foreach (var entry in TranslationSourceBundle.Read(bundlePath).Entries) yield return (Path.Combine(modCppDir, entry.VirtualPath), entry.Source); yield break; } - foreach (var source in ReadFiles(Directory.EnumerateFiles(modCppDir, "*.cpp", SearchOption.AllDirectories))) + foreach (var source in ReadFiles(TrackedFs.EnumerateFiles(modCppDir, "*.cpp", SearchOption.AllDirectories))) yield return source; } @@ -2180,7 +2271,7 @@ uint AbiHex(string group, uint fallback = uint.MaxValue) => abi.Success void ReadBaseTranslated() { BaseTranslationOutputMetadata? metadata = null; - if (File.Exists(baseTranslationOutputMetadataPath)) + if (TrackedFs.FileExists(baseTranslationOutputMetadataPath)) { metadata = ReadBaseMetadataCached(baseTranslationOutputMetadataPath); } @@ -2241,9 +2332,9 @@ void AddNative(uint address, string symbol, string sourceFile) // the same resolved profile as runtime-native registrations so direct-call // traits and immutable indirect dispatch tables cannot bypass them. var modDataPatchesPath = Path.Combine(modCppDir, "mod_data_patches.cpp"); - if (File.Exists(modDataPatchesPath)) + if (TrackedFs.FileExists(modDataPatchesPath)) { - var text = Regex.Replace(File.ReadAllText(modDataPatchesPath), @"//[^\r\n]*", string.Empty); + var text = Regex.Replace(TrackedFs.ReadAllText(modDataPatchesPath), @"//[^\r\n]*", string.Empty); foreach (Match match in nativeRegistration.Matches(text)) { AddNative( @@ -2364,11 +2455,11 @@ int EmitModCpp( Console.WriteLine($" translating mod C++ with up to {maxThreads} worker thread(s)"); var cppRoot = Path.Combine(outDir, "cpp"); - if (Directory.Exists(cppRoot)) + if (TrackedFs.DirectoryExists(cppRoot)) { - Directory.Delete(cppRoot, recursive: true); + TrackedFs.DeleteDirectory(cppRoot, recursive: true); } - Directory.CreateDirectory(cppRoot); + TrackedFs.CreateDirectory(cppRoot); var bundledModSources = new Dictionary(StringComparer.OrdinalIgnoreCase); var unresolved = new List(); @@ -2635,7 +2726,7 @@ void DrainDiscoveredContinuations() DrainDiscoveredContinuations(); var moduleImagePath = Path.Combine(outDir, "overlay_images", overlayBuild.ModuleImageFile); - var moduleEnd = checked(overlayBuild.ModuleGuestBase + (uint)new FileInfo(moduleImagePath).Length); + var moduleEnd = checked(overlayBuild.ModuleGuestBase + (uint)TrackedFs.FileLength(moduleImagePath)); var moduleQueue = new Queue(kamekFunctionStarts.OrderBy(s => s.Address)); var queuedModuleStarts = new HashSet(kamekFunctionStarts.Select(s => s.Address)); var emittedModuleStarts = new HashSet(); @@ -2785,7 +2876,7 @@ ProgramImage BuildSyntheticModProgramImage(string outDir, OverlayBuildResult ove void CopyFileToGuest(byte[] memory, uint memoryBase, uint guestAddress, string path) { - var bytes = File.ReadAllBytes(path); + var bytes = TrackedFs.ReadAllBytes(path); if (guestAddress < memoryBase) { throw new InvalidDataException($"Mod image '{path}' at 0x{guestAddress:X8} precedes configured memory base 0x{memoryBase:X8}."); @@ -2940,7 +3031,7 @@ int RunGenerateDataInit() // Load the REL file for runtime embedding (apply relocations since runtime does not OSLink) RelImage? relImage = null; - if (!string.IsNullOrWhiteSpace(relPath) && loadedProject.Inputs.Rel is { } configuredRel && File.Exists(relPath)) + if (!string.IsNullOrWhiteSpace(relPath) && loadedProject.Inputs.Rel is { } configuredRel && TrackedFs.FileExists(relPath)) { relImage = RelFile.Load(relPath).BuildImage( configuredRel.LoadAddress, @@ -2951,7 +3042,7 @@ int RunGenerateDataInit() var outputDir = Path.GetDirectoryName(output); if (!string.IsNullOrEmpty(outputDir)) { - Directory.CreateDirectory(outputDir); + TrackedFs.CreateDirectory(outputDir); } DataSectionGenerator.Generate( dol, @@ -3681,7 +3772,8 @@ static string[] KnownCommands() => new[] "emit-build-shards", "emit-native-index", "check-base-mod-awareness", - "validate-retro-wfc-payload" + "validate-retro-wfc-payload", + "list-translation-inputs" }; /// @@ -3693,7 +3785,10 @@ static string[] KnownCommands() => new[] { "info" or "--info" or "--version" => (null, Array.Empty()), - "generate-data-init" => (null, Array.Empty()), + "generate-data-init" => (null, new CommandOption[] + { + new("--provenance-file", "path") + }), "translate-recursive" => ("", new CommandOption[] { new("--outdir", "path"), @@ -3718,7 +3813,8 @@ static string[] KnownCommands() => new[] new("--threads", "N"), new("--retro-wfc-payload", "path-or-url"), new("--skip-retro-wfc"), - new("--emit-cpp") + new("--emit-cpp"), + new("--provenance-file", "path") }), "check-base-mod-awareness" => (null, new CommandOption[] { @@ -3745,7 +3841,12 @@ static string[] KnownCommands() => new[] new("--native-index", "path"), new("--resolved-profile", "path"), new("--retro-cpp-dir", "path"), - new("--out", "generated/build_shards") + new("--out", "generated/build_shards"), + new("--provenance-file", "path") + }), + "list-translation-inputs" => (null, new CommandOption[] + { + new("--project", "path/to/recomp.yml", Required: true) }), "emit-native-index" => (null, new CommandOption[] { @@ -3917,13 +4018,13 @@ HashSet BuildKnownBaseFunctionEntryPoints( static IEnumerable DiscoverFunctionStartAddressesFromFileNames(string generatedFunctionsDir) { - if (!Directory.Exists(generatedFunctionsDir)) + if (!TrackedFs.DirectoryExists(generatedFunctionsDir)) { yield break; } var addressRegex = new Regex("([0-9A-Fa-f]{8})", RegexOptions.CultureInvariant); - foreach (var path in Directory.EnumerateFiles(generatedFunctionsDir, "*.cpp", SearchOption.AllDirectories)) + foreach (var path in TrackedFs.EnumerateFiles(generatedFunctionsDir, "*.cpp", SearchOption.AllDirectories)) { var match = addressRegex.Match(Path.GetFileNameWithoutExtension(path)); if (match.Success && @@ -3969,7 +4070,7 @@ static IReadOnlySet BuildLeafInliningBlockedTargets( { if (candidate.Enabled && !string.IsNullOrWhiteSpace(candidate.CodePul) && - File.Exists(candidate.CodePul)) + TrackedFs.FileExists(candidate.CodePul)) { profiles[candidate.Name] = candidate; } @@ -3979,7 +4080,7 @@ static IReadOnlySet BuildLeafInliningBlockedTargets( // caller selects one that is marked disabled in the project file. if (selectedProfile is not null && !string.IsNullOrWhiteSpace(selectedProfile.CodePul) && - File.Exists(selectedProfile.CodePul)) + TrackedFs.FileExists(selectedProfile.CodePul)) { profiles[selectedProfile.Name] = selectedProfile; } diff --git a/translator/src/Translator.Cli/TranslationProjectConfig.cs b/translator/src/Translator.Cli/TranslationProjectConfig.cs index bfbd71b89..613cd6dd4 100644 --- a/translator/src/Translator.Cli/TranslationProjectConfig.cs +++ b/translator/src/Translator.Cli/TranslationProjectConfig.cs @@ -1,3 +1,5 @@ +using Translator.Core; +using Translator.Core.IO; using System.Globalization; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; @@ -40,9 +42,51 @@ private TranslationProjectConfig( public IReadOnlyDictionary Profiles { get; } public static TranslationProjectConfig Load(string path) + { + var config = Parse(path); + config.ValidateInputs(); + return config; + } + + /// + /// Every existing file a translation of the project at reads, apart + /// from the pinned disc inputs (inputs.dol / inputs.rel), which are never opened here: the + /// manifest, its function map, each profile's Code.pul (the base translation blocks leaf + /// inlining at every address a profile patches), the runtime native index, every native + /// source the runtime scan reads, and the guest address map. The sibling regional metadata + /// (region_port.json, data_addresses.txt) is not read by translation; it is listed anyway + /// because it documents where the regional function map came from. Absolute, + /// de-duplicated, ordinal order. + /// + public static IReadOnlyList ListTranslationInputs(string path) + { + var config = Parse(path); + var files = new SortedSet(StringComparer.Ordinal); + void Add(string? candidate) + { + if (string.IsNullOrWhiteSpace(candidate)) return; + var full = Path.GetFullPath(candidate); + if (TrackedFs.FileExists(full)) files.Add(full); + } + + var manifestDirectory = Path.GetDirectoryName(config.SourcePath)!; + Add(config.SourcePath); + Add(config.Translation.FunctionMapPath); + Add(Path.Combine(manifestDirectory, "region_port.json")); + Add(Path.Combine(manifestDirectory, "data_addresses.txt")); + foreach (var profile in config.Profiles.Values) + Add(profile.CodePul); + Add(config.Runtime.NativeIndex); + foreach (var source in RuntimeNativeIndexBuilder.EnumerateSourceFiles(config.Runtime.NativeRegistrationRoot)) + Add(source); + Add(GuestAddressTable.DefaultPath(config.Runtime.NativeRegistrationRoot)); + return files.ToArray(); + } + + private static TranslationProjectConfig Parse(string path) { var sourcePath = Path.GetFullPath(path); - if (!File.Exists(sourcePath)) + if (!TrackedFs.FileExists(sourcePath)) { throw new FileNotFoundException("Translation project manifest not found.", sourcePath); } @@ -50,7 +94,7 @@ public static TranslationProjectConfig Load(string path) var deserializer = new DeserializerBuilder() .WithNamingConvention(UnderscoredNamingConvention.Instance) .Build(); - var dto = deserializer.Deserialize(File.ReadAllText(sourcePath)) + var dto = deserializer.Deserialize(TrackedFs.ReadAllText(sourcePath)) ?? throw new InvalidDataException($"Translation project manifest is empty: {sourcePath}"); if (dto.SchemaVersion != 1) { @@ -146,7 +190,6 @@ public static TranslationProjectConfig Load(string path) runtime, output, profiles); - config.ValidateInputs(); return config; } @@ -210,7 +253,7 @@ private void ValidateInputs() { ValidateInput(Inputs.Rel, "REL"); } - if (Translation.FunctionMapPath is { } functionMapPath && !File.Exists(functionMapPath)) + if (Translation.FunctionMapPath is { } functionMapPath && !TrackedFs.FileExists(functionMapPath)) { throw new FileNotFoundException("Configured function map was not found.", functionMapPath); } @@ -228,7 +271,7 @@ private static ProjectBinaryInput ResolveInput(string root, BinaryInputDto input private static void ValidateInput(ProjectBinaryInput input, string label) { - if (!File.Exists(input.Path)) + if (!TrackedFs.FileExists(input.Path)) { throw new FileNotFoundException($"Configured {label} input was not found.", input.Path); } @@ -256,7 +299,7 @@ private static string ResolveOutput(string outputRoot, string? value, string fal private static string ResolvePath(string root, string value) { - var expanded = Environment.ExpandEnvironmentVariables(value); + var expanded = TrackedFs.ExpandEnvironmentVariables(value); return Path.GetFullPath(Path.IsPathRooted(expanded) ? expanded : Path.Combine(root, expanded)); } diff --git a/translator/src/Translator.Core/Build/GeneratedOutputPruner.cs b/translator/src/Translator.Core/Build/GeneratedOutputPruner.cs index b37d2cab6..5148a2586 100644 --- a/translator/src/Translator.Core/Build/GeneratedOutputPruner.cs +++ b/translator/src/Translator.Core/Build/GeneratedOutputPruner.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using Translator.Core.Mods; namespace Translator.Core.Build; @@ -18,7 +19,7 @@ public static GeneratedOutputPruneResult Prune( IReadOnlySet emittedPaths, BaseTranslationOutputMetadata? previousOutputMetadata = null) { - if (!Directory.Exists(baseOutDir)) + if (!TrackedFs.OutputDirectoryExists(baseOutDir)) return GeneratedOutputPruneResult.Empty; var comparison = OperatingSystem.IsWindows() @@ -32,7 +33,7 @@ public static GeneratedOutputPruneResult Prune( { // Compatibility migration for trees produced before translator-owned // metadata: every generated body under the root is a prune candidate. - candidates = Directory.EnumerateFiles(root, "*.cpp", SearchOption.AllDirectories); + candidates = TrackedFs.EnumerateOutputFiles(root, "*.cpp", SearchOption.AllDirectories); } else { @@ -51,12 +52,12 @@ public static GeneratedOutputPruneResult Prune( warnings.Add($"refused to prune generated path outside output root: {fullPath}"); continue; } - if (emittedPaths.Contains(fullPath) || !File.Exists(fullPath)) + if (emittedPaths.Contains(fullPath) || !TrackedFs.OutputFileExists(fullPath)) continue; try { - File.Delete(fullPath); + TrackedFs.Delete(fullPath); removed++; } catch (Exception ex) diff --git a/translator/src/Translator.Core/Build/TranslatedBuildShardEmitter.cs b/translator/src/Translator.Core/Build/TranslatedBuildShardEmitter.cs index c8fcd74cc..9ca2d7717 100644 --- a/translator/src/Translator.Core/Build/TranslatedBuildShardEmitter.cs +++ b/translator/src/Translator.Core/Build/TranslatedBuildShardEmitter.cs @@ -137,7 +137,7 @@ public static TranslatedBuildShardResult Emit(TranslatedBuildShardOptions option { ValidateOptions(options); var outputRoot = Path.GetFullPath(options.OutputDirectory); - Directory.CreateDirectory(outputRoot); + TrackedFs.CreateDirectory(outputRoot); var metadata = BaseTranslationOutputMetadataFile.Read(options.BaseMetadataPath); metadata.RequireReleaseEligible(options.BaseMetadataPath); @@ -209,7 +209,7 @@ record => var retroSourceBundlePath = options.RetroCppDirectory is { } retroCppDir && !string.IsNullOrWhiteSpace(retroCppDir) ? Path.Combine(Path.GetDirectoryName(Path.GetFullPath(retroCppDir))!, "translated_sources.bin") : null; - if (retroSourceBundlePath is not null && !File.Exists(retroSourceBundlePath)) retroSourceBundlePath = null; + if (retroSourceBundlePath is not null && !TrackedFs.FileExists(retroSourceBundlePath)) retroSourceBundlePath = null; var modRecords = ReadModFunctions(options.RetroCppDirectory, retroSourceBundlePath); var shards = new List(); @@ -286,13 +286,13 @@ record => private static void ValidateOptions(TranslatedBuildShardOptions options) { - if (!File.Exists(options.BaseMetadataPath)) + if (!TrackedFs.FileExists(options.BaseMetadataPath)) { throw new FileNotFoundException("Required shard input is missing.", options.BaseMetadataPath); } - if (!Directory.Exists(options.BaseFunctionsDirectory)) + if (!TrackedFs.DirectoryExists(options.BaseFunctionsDirectory)) throw new DirectoryNotFoundException(options.BaseFunctionsDirectory); - if (options.NativeIndex is null && !Directory.Exists(options.NativeSourceDirectory)) + if (options.NativeIndex is null && !TrackedFs.DirectoryExists(options.NativeSourceDirectory)) throw new DirectoryNotFoundException(options.NativeSourceDirectory); if (options.BaseShardCount < 1 || options.ModShardCount < 1 || options.RegistrationShardCount < 1) { @@ -334,7 +334,7 @@ private static IReadOnlyList ReadBaseFunctions( } else if (item.Build is null) { - source = File.ReadAllText(path); + source = TrackedFs.ReadAllText(path); } (uint Address, string Symbol, bool Preserves, uint FprMask) registration = item.Build is null ? ParseBaseRegistration(source!, path) @@ -364,17 +364,17 @@ private static IReadOnlyList ReadBaseFunctions( private static IReadOnlyList ReadModFunctions(string? cppDirectory, string? sourceBundlePath) { if (string.IsNullOrWhiteSpace(cppDirectory) || - (!Directory.Exists(cppDirectory) && (string.IsNullOrWhiteSpace(sourceBundlePath) || !File.Exists(sourceBundlePath)))) + (!TrackedFs.DirectoryExists(cppDirectory) && (string.IsNullOrWhiteSpace(sourceBundlePath) || !TrackedFs.FileExists(sourceBundlePath)))) { return Array.Empty(); } var records = new List(); - var sources = !string.IsNullOrWhiteSpace(sourceBundlePath) && File.Exists(sourceBundlePath) + var sources = !string.IsNullOrWhiteSpace(sourceBundlePath) && TrackedFs.FileExists(sourceBundlePath) ? TranslationSourceBundle.Read(sourceBundlePath).Entries .Select(entry => (Path: Path.GetFullPath(Path.Combine(cppDirectory, entry.VirtualPath)), entry.Source)) - : Directory.EnumerateFiles(cppDirectory, "*.cpp", SearchOption.AllDirectories) + : TrackedFs.EnumerateFiles(cppDirectory, "*.cpp", SearchOption.AllDirectories) .Order(StringComparer.OrdinalIgnoreCase) - .Select(path => (Path: path, Source: File.ReadAllText(path))); + .Select(path => (Path: path, Source: TrackedFs.ReadAllText(path))); foreach (var (path, source) in sources) { var match = ModRegistrationRegex().Match(source); @@ -481,8 +481,8 @@ private static NativeOverrideSets ReadNativeOverrides( private static IReadOnlyDictionary ReadResolvedProfile(string? path) { - if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) return new Dictionary(); - using var document = JsonDocument.Parse(File.ReadAllText(path)); + if (string.IsNullOrWhiteSpace(path) || !TrackedFs.FileExists(path)) return new Dictionary(); + using var document = JsonDocument.Parse(TrackedFs.ReadAllText(path)); return document.RootElement.GetProperty("Entries").EnumerateArray() .Select(element => new ProfileEntry( element.GetProperty("Address").GetUInt32(), @@ -606,7 +606,7 @@ private static IReadOnlyList WriteFunctionShards( .ToList(); var directory = Path.Combine(outputRoot, partition); - Directory.CreateDirectory(directory); + TrackedFs.CreateDirectory(directory); // Groups own disjoint records and distinct files, so they build concurrently; results are // collected positionally to keep the emitted list byte-for-byte deterministic. Never widen // this parallelism across WriteFunctionShards calls, base and Retro Rewind share records. @@ -640,7 +640,7 @@ private static IReadOnlyList WriteFunctionShards( .OrderBy(static function => function.Address) .ThenBy(static function => function.Symbol, StringComparer.Ordinal)) { - var functionSource = function.SourceText ?? File.ReadAllText(function.SourcePath); + var functionSource = function.SourceText ?? TrackedFs.ReadAllText(function.SourcePath); functionSource = RegistrationMarkerRegex().Replace(functionSource, string.Empty); functionSource = LowerStableDirectCalls(functionSource, traits); // Diagnostics only; the named file no longer exists on disk (sources live in the @@ -817,10 +817,10 @@ private static IReadOnlyList> PartitionFrozenBoundaries( private static ShardBoundaryTable? ReadShardBoundaryTable(string path, int expectedShardCount) { - if (!File.Exists(path)) return null; + if (!TrackedFs.FileExists(path)) return null; try { - using var document = JsonDocument.Parse(File.ReadAllText(path)); + using var document = JsonDocument.Parse(TrackedFs.ReadAllText(path)); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("format", out var format) || @@ -900,7 +900,7 @@ private static IReadOnlyList WriteRegistrationShards( var count = Math.Min(requestedCount, records.Count); var groups = PartitionStableHash(records, count); var directory = Path.Combine(outputRoot, $"{profile}_registration"); - Directory.CreateDirectory(directory); + TrackedFs.CreateDirectory(directory); var paths = new List(); for (var index = 0; index < count; index++) { @@ -1028,9 +1028,9 @@ pair.Value.WinnerSymbol is not null && private static IReadOnlyList ReadRetroExtraSources(string? cppDirectory, IReadOnlyList modRecords) { - if (string.IsNullOrWhiteSpace(cppDirectory) || !Directory.Exists(cppDirectory)) return Array.Empty(); + if (string.IsNullOrWhiteSpace(cppDirectory) || !TrackedFs.DirectoryExists(cppDirectory)) return Array.Empty(); var functionPaths = modRecords.Select(static record => record.SourcePath).ToHashSet(StringComparer.OrdinalIgnoreCase); - return Directory.EnumerateFiles(cppDirectory, "*.*", SearchOption.AllDirectories) + return TrackedFs.EnumerateFiles(cppDirectory, "*.*", SearchOption.AllDirectories) .Where(path => path.EndsWith(".cpp", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".S", StringComparison.OrdinalIgnoreCase)) .Select(Path.GetFullPath) .Where(path => !functionPaths.Contains(path)) @@ -1107,13 +1107,13 @@ private static void PruneStaleShardSources( .Concat(rrRegistration) .Select(Path.GetFullPath) .ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var directory in Directory.EnumerateDirectories(outputRoot)) + foreach (var directory in TrackedFs.EnumerateOutputDirectories(outputRoot)) { - foreach (var file in Directory.EnumerateFiles(directory, "*.*", SearchOption.AllDirectories) + foreach (var file in TrackedFs.EnumerateOutputFiles(directory, "*.*", SearchOption.AllDirectories) .Where(static file => file.EndsWith(".cpp", StringComparison.OrdinalIgnoreCase) || file.EndsWith(".h", StringComparison.OrdinalIgnoreCase))) { - if (!keep.Contains(Path.GetFullPath(file))) File.Delete(file); + if (!keep.Contains(Path.GetFullPath(file))) TrackedFs.Delete(file); } } } diff --git a/translator/src/Translator.Core/Build/TranslationSourceBundle.cs b/translator/src/Translator.Core/Build/TranslationSourceBundle.cs index 6a186298f..02da013d6 100644 --- a/translator/src/Translator.Core/Build/TranslationSourceBundle.cs +++ b/translator/src/Translator.Core/Build/TranslationSourceBundle.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Security.Cryptography; using System.Text; using Translator.Core.Loading; @@ -55,9 +56,9 @@ public static void Write(string path, IEnumerable if (ordered.Select(static entry => (entry.EntryPoint, entry.VirtualPath)).Distinct().Count() != ordered.Length) throw new InvalidDataException("Translation source bundle contains duplicate address/path identities."); var fullPath = Path.GetFullPath(path); - Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!); + TrackedFs.CreateDirectory(Path.GetDirectoryName(fullPath)!); var temporary = $"{fullPath}.tmp.{Guid.NewGuid():N}"; - using (var stream = File.Create(temporary)) + using (var stream = TrackedFs.Create(temporary)) using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: false)) { writer.Write(Magic); @@ -75,14 +76,14 @@ public static void Write(string path, IEnumerable writer.Write(sourceBytes); } } - File.Move(temporary, fullPath, overwrite: true); + TrackedFs.Move(temporary, fullPath, overwrite: true); } public static TranslationSourceBundleWriter CreateWriter(string path, int entryCount) => new(path, entryCount, Magic, FormatVersion); public static TranslationSourceBundle Read(string path) { - using var stream = File.OpenRead(path); + using var stream = TrackedFs.OpenRead(path); using var reader = new BinaryReader(stream, Encoding.UTF8, leaveOpen: false); if (!reader.ReadBytes(Magic.Length).SequenceEqual(Magic) || reader.ReadInt32() != FormatVersion) throw new InvalidDataException($"Unsupported translation source bundle '{path}'."); @@ -137,11 +138,11 @@ internal TranslationSourceBundleWriter(string path, int entryCount, byte[] magic { if (entryCount < 0) throw new ArgumentOutOfRangeException(nameof(entryCount)); _path = Path.GetFullPath(path); - Directory.CreateDirectory(Path.GetDirectoryName(_path)!); + TrackedFs.CreateDirectory(Path.GetDirectoryName(_path)!); SweepAbandonedTemporaries(_path); _temporary = $"{_path}.tmp.{Guid.NewGuid():N}"; _expectedCount = entryCount; - _writer = new BinaryWriter(File.Create(_temporary), Encoding.UTF8, leaveOpen: false); + _writer = new BinaryWriter(TrackedFs.Create(_temporary), Encoding.UTF8, leaveOpen: false); _writer.Write(magic); _writer.Write(version); _writer.Write(entryCount); @@ -158,12 +159,12 @@ private static void SweepAbandonedTemporaries(string targetPath) var prefix = Path.GetFileName(targetPath) + ".tmp."; // The pattern is a Win32 wildcard, so re-check the prefix explicitly and // snapshot the listing before deleting from it. - foreach (var candidate in Directory.GetFiles(directory, prefix + "*")) + foreach (var candidate in TrackedFs.EnumerateOutputFiles(directory, prefix + "*").ToArray()) { if (!Path.GetFileName(candidate).StartsWith(prefix, StringComparison.Ordinal)) continue; try { - File.Delete(candidate); + TrackedFs.Delete(candidate); } catch (IOException) { @@ -199,13 +200,13 @@ public void Complete() if (_written != _expectedCount) throw new InvalidOperationException($"Translation source bundle expected {_expectedCount} entries but received {_written}."); _writer.Dispose(); - File.Move(_temporary, _path, overwrite: true); + TrackedFs.Move(_temporary, _path, overwrite: true); _completed = true; } public void Dispose() { _writer.Dispose(); - if (!_completed && File.Exists(_temporary)) File.Delete(_temporary); + if (!_completed && TrackedFs.FileExists(_temporary)) TrackedFs.Delete(_temporary); } } diff --git a/translator/src/Translator.Core/CodeGen/RuntimeConfigGenerator.cs b/translator/src/Translator.Core/CodeGen/RuntimeConfigGenerator.cs index 24858f2af..8ced6a501 100644 --- a/translator/src/Translator.Core/CodeGen/RuntimeConfigGenerator.cs +++ b/translator/src/Translator.Core/CodeGen/RuntimeConfigGenerator.cs @@ -52,7 +52,7 @@ public static void GenerateConfigHeader( sb.AppendLine("} // namespace RuntimeConfig"); sb.AppendLine(); - Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!); + TrackedFs.CreateDirectory(Path.GetDirectoryName(outputPath)!); FileOutput.WriteTextIfChanged(outputPath, sb.ToString()); } } diff --git a/translator/src/Translator.Core/GuestAddressTable.cs b/translator/src/Translator.Core/GuestAddressTable.cs index 871ee97ba..936a27eaf 100644 --- a/translator/src/Translator.Core/GuestAddressTable.cs +++ b/translator/src/Translator.Core/GuestAddressTable.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Text.RegularExpressions; namespace Translator.Core; @@ -53,10 +54,10 @@ public static string DefaultPath(string nativeSourceDirectory) => public static GuestAddressTable Load(string path) { - if (!File.Exists(path)) + if (!TrackedFs.FileExists(path)) throw new FileNotFoundException("The runtime's guest address map was not found.", path); var ranges = new Dictionary>(); - foreach (var line in File.ReadLines(path)) + foreach (var line in TrackedFs.ReadLines(path)) { if (!line.TrimStart().StartsWith("MKW_REGION_RANGE", StringComparison.Ordinal)) continue; var match = RangePattern().Match(line); diff --git a/translator/src/Translator.Core/IO/AssemblyBlobWriter.cs b/translator/src/Translator.Core/IO/AssemblyBlobWriter.cs index 2201e5481..b5677fe69 100644 --- a/translator/src/Translator.Core/IO/AssemblyBlobWriter.cs +++ b/translator/src/Translator.Core/IO/AssemblyBlobWriter.cs @@ -18,7 +18,7 @@ public static void Write( IReadOnlyList blobs, params string[] headerLines) { - Directory.CreateDirectory(blobDirectory); + TrackedFs.CreateDirectory(blobDirectory); var expectedFiles = new HashSet(StringComparer.OrdinalIgnoreCase); var assembly = new StringBuilder(); foreach (var header in headerLines) assembly.AppendLine(header); @@ -52,9 +52,9 @@ public static void Write( assembly.AppendLine(); } - foreach (var stalePath in Directory.EnumerateFiles(blobDirectory, "*.bin")) + foreach (var stalePath in TrackedFs.EnumerateOutputFiles(blobDirectory, "*.bin")) { - if (!expectedFiles.Contains(Path.GetFullPath(stalePath))) File.Delete(stalePath); + if (!expectedFiles.Contains(Path.GetFullPath(stalePath))) TrackedFs.Delete(stalePath); } if (!OperatingSystem.IsWindows() && !OperatingSystem.IsMacOS()) { diff --git a/translator/src/Translator.Core/IO/FileAccessRecorder.cs b/translator/src/Translator.Core/IO/FileAccessRecorder.cs new file mode 100644 index 000000000..cac55a4c8 --- /dev/null +++ b/translator/src/Translator.Core/IO/FileAccessRecorder.cs @@ -0,0 +1,275 @@ +using System.Security.Cryptography; + +namespace Translator.Core.IO; + +public enum FileScanKind +{ + Files, + Directories, +} + +/// One directory listing exactly as a command asked for it. +public sealed record FileScanQuery(string Directory, string Pattern, SearchOption Option, FileScanKind Kind) +{ + public FileScanQuery Normalized() => this with { Directory = Path.GetFullPath(Directory) }; + + /// The entries the query yields right now, relative to its directory, '/'-separated, ordinal order. + public string[] ListNow() + { + var root = Path.GetFullPath(Directory); + var entries = Kind == FileScanKind.Files + ? System.IO.Directory.EnumerateFiles(root, Pattern, Option) + : System.IO.Directory.EnumerateDirectories(root, Pattern, Option); + return Relative(root, entries); + } + + public static string[] Relative(string root, IEnumerable entries) => + entries.Select(entry => Path.GetRelativePath(root, Path.GetFullPath(entry)).Replace('\\', '/')) + .Order(StringComparer.Ordinal) + .ToArray(); +} + +/// Everything one command run touched, as reports it. +public sealed record FileAccessSnapshot( + IReadOnlyList<(string Path, string Sha256)> Inputs, + IReadOnlyList<(string Path, bool IsDirectory, bool Exists)> Probes, + IReadOnlyList<(FileScanQuery Query, string[] Entries)> Scans, + IReadOnlyList<(string Path, long Size)> Outputs, + IReadOnlyList<(string Value, string Expanded)> EnvironmentExpansions, + IReadOnlyList CurrentDirectories, + IReadOnlyList UntrackedInputs); + +/// +/// Collects what a command reads (with the content hash it saw), which paths it probed, +/// which directories it listed, and what it wrote. Paths the command itself created during +/// the run (staging trees, temporaries, its own outputs read back) are not inputs. +/// First observation wins: a file read and later rewritten keeps the hash it was read +/// with, so the record cannot match until a run reads what it leaves behind (fail closed). +/// Thread-safe; translation reads from many workers at once. +/// +public sealed class FileAccessRecorder +{ + public static readonly StringComparer PathComparer = + OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + + private readonly object _gate = new(); + private readonly Dictionary _inputs = new(PathComparer); + private readonly Dictionary _probes = new(PathComparer); + private readonly Dictionary _scans = new(new QueryComparer()); + private readonly HashSet _outputScans = new(new QueryComparer()); + private readonly HashSet _producedFiles = new(PathComparer); + private readonly HashSet _producedDirectories = new(PathComparer); + private readonly HashSet _outputTrees = new(PathComparer); + private readonly HashSet _deletedFiles = new(PathComparer); + private readonly HashSet _deletedDirectories = new(PathComparer); + private readonly Dictionary _expansions = new(StringComparer.Ordinal); + private readonly HashSet _currentDirectories = new(StringComparer.Ordinal); + private readonly List _untracked = new(); + + /// Whether a read of still needs its content hashed. + public bool WantsContent(string path) + { + var full = Path.GetFullPath(path); + lock (_gate) return !_inputs.ContainsKey(full) && !IsProducedLocked(full); + } + + public void OnRead(string path, ReadOnlySpan content) + { + if (!WantsContent(path)) return; + OnReadHash(path, SHA256.HashData(content)); + } + + public void OnReadHash(string path, byte[] sha256) + { + var full = Path.GetFullPath(path); + lock (_gate) + { + if (IsProducedLocked(full)) return; + _inputs.TryAdd(full, Convert.ToHexString(sha256).ToLowerInvariant()); + } + } + + public void OnFileProbe(string path, bool exists) => OnProbe(path, isDirectory: false, exists); + + public void OnDirectoryProbe(string path, bool exists) => OnProbe(path, isDirectory: true, exists); + + private void OnProbe(string path, bool isDirectory, bool exists) + { + var full = Path.GetFullPath(path); + lock (_gate) + { + if (IsProducedLocked(full)) return; + _probes.TryAdd(ProbeKey(full, isDirectory), (isDirectory, exists)); + } + } + + public void OnScan(FileScanQuery query, IEnumerable entries) + { + var normalized = query.Normalized(); + var listing = FileScanQuery.Relative(normalized.Directory, entries); + lock (_gate) + { + if (IsProducedLocked(normalized.Directory)) return; + _scans.TryAdd(normalized, listing); + } + } + + public void OnOutputScan(FileScanQuery query) + { + var normalized = query.Normalized(); + lock (_gate) + { + if (IsProducedLocked(normalized.Directory)) return; + _outputScans.Add(normalized); + } + } + + public void OnWrite(string path) + { + var full = Path.GetFullPath(path); + lock (_gate) _producedFiles.Add(full); + } + + public void OnDeleteFile(string path) + { + var full = Path.GetFullPath(path); + lock (_gate) + { + if (!_producedFiles.Remove(full) && !IsProducedLocked(full)) + _deletedFiles.Add(full); + } + } + + public void OnCreateDirectory(string path) + { + var full = Path.GetFullPath(path); + lock (_gate) _producedDirectories.Add(full); + } + + public void OnDeleteDirectory(string path) + { + var full = Path.GetFullPath(path); + lock (_gate) + { + if (!IsProducedLocked(full)) _deletedDirectories.Add(full); + _outputTrees.RemoveWhere(tree => IsSameOrUnder(tree, full)); + } + } + + public void OnMoveDirectory(string source, string destination) + { + var fullSource = Path.GetFullPath(source); + var fullDestination = Path.GetFullPath(destination); + lock (_gate) + { + var sourceWasProduced = IsProducedLocked(fullSource); + if (!sourceWasProduced) _deletedDirectories.Add(fullSource); + _outputTrees.RemoveWhere(tree => IsSameOrUnder(tree, fullSource)); + _producedDirectories.Add(fullDestination); + // A tree the command generated and then published is its output; a pre-existing + // tree it only moved aside (a backup) is not. + if (sourceWasProduced) _outputTrees.Add(fullDestination); + } + } + + public void OnEnvironmentExpansion(string value, string expanded) + { + if (string.Equals(value, expanded, StringComparison.Ordinal) && !value.Contains('%')) return; + lock (_gate) _expansions.TryAdd(value, expanded); + } + + public void OnCurrentDirectory(string directory) + { + lock (_gate) _currentDirectories.Add(directory); + } + + public void OnUntrackedInput(string description) + { + lock (_gate) _untracked.Add(description); + } + + /// + /// The run as a whole, judged by the file system as it stands now: outputs are the files + /// the command produced that still exist (and every file of a tree it published), output + /// listings are taken now, and a pre-existing path it deleted must stay deleted. + /// + public FileAccessSnapshot Snapshot() + { + lock (_gate) + { + var probes = new Dictionary(_probes, PathComparer); + foreach (var deleted in _deletedFiles.Where(path => !File.Exists(path) && !Directory.Exists(path))) + probes.TryAdd(ProbeKey(deleted, isDirectory: false), (false, false)); + foreach (var deleted in _deletedDirectories.Where(path => !File.Exists(path) && !Directory.Exists(path))) + probes.TryAdd(ProbeKey(deleted, isDirectory: true), (true, false)); + + var scans = new Dictionary(_scans, new QueryComparer()); + foreach (var query in _outputScans) + scans[query] = Directory.Exists(query.Directory) ? query.ListNow() : []; + + var outputs = new Dictionary(PathComparer); + foreach (var path in _producedFiles.Where(File.Exists)) + outputs[path] = new FileInfo(path).Length; + foreach (var tree in _outputTrees.Where(Directory.Exists)) + { + var query = new FileScanQuery(tree, "*", SearchOption.AllDirectories, FileScanKind.Files); + scans[query] = query.ListNow(); + foreach (var file in Directory.EnumerateFiles(tree, "*", SearchOption.AllDirectories)) + outputs[Path.GetFullPath(file)] = new FileInfo(file).Length; + } + + return new FileAccessSnapshot( + _inputs.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => (pair.Key, pair.Value)).ToArray(), + probes.Select(static pair => (Path: pair.Key[2..], pair.Value.IsDirectory, pair.Value.Exists)) + .OrderBy(static item => item.Path, StringComparer.Ordinal) + .ThenBy(static item => item.IsDirectory) + .ToArray(), + scans.OrderBy(static pair => pair.Key.Directory, StringComparer.Ordinal) + .ThenBy(static pair => pair.Key.Pattern, StringComparer.Ordinal) + .ThenBy(static pair => pair.Key.Option) + .ThenBy(static pair => pair.Key.Kind) + .Select(static pair => (pair.Key, pair.Value)).ToArray(), + outputs.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => (pair.Key, pair.Value)).ToArray(), + _expansions.OrderBy(static pair => pair.Key, StringComparer.Ordinal) + .Select(static pair => (pair.Key, pair.Value)).ToArray(), + _currentDirectories.Order(StringComparer.Ordinal).ToArray(), + _untracked.ToArray()); + } + } + + private static string ProbeKey(string fullPath, bool isDirectory) => (isDirectory ? "D:" : "F:") + fullPath; + + private bool IsProducedLocked(string fullPath) + { + if (_producedFiles.Contains(fullPath)) return true; + for (var current = fullPath; !string.IsNullOrEmpty(current); current = Path.GetDirectoryName(current)) + { + if (_producedDirectories.Contains(current)) return true; + } + return false; + } + + private static bool IsSameOrUnder(string path, string root) + { + if (PathComparer.Equals(path, root)) return true; + var prefix = Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar; + return path.StartsWith(prefix, OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal); + } + + private sealed class QueryComparer : IEqualityComparer + { + public bool Equals(FileScanQuery? x, FileScanQuery? y) => + ReferenceEquals(x, y) || + (x is not null && y is not null && + PathComparer.Equals(x.Directory, y.Directory) && + string.Equals(x.Pattern, y.Pattern, StringComparison.Ordinal) && + x.Option == y.Option && x.Kind == y.Kind); + + public int GetHashCode(FileScanQuery obj) => + HashCode.Combine(PathComparer.GetHashCode(obj.Directory), obj.Pattern, obj.Option, obj.Kind); + } +} diff --git a/translator/src/Translator.Core/IO/FileOutput.cs b/translator/src/Translator.Core/IO/FileOutput.cs index 4746d6be8..bf272c13d 100644 --- a/translator/src/Translator.Core/IO/FileOutput.cs +++ b/translator/src/Translator.Core/IO/FileOutput.cs @@ -20,15 +20,16 @@ public static bool WriteTextIfChanged(string path, string content) => public static bool WriteBytesIfChanged(string path, ReadOnlySpan content) { var fullPath = Path.GetFullPath(path); + // The target is this command's output whether or not its bytes change. + TrackedFs.KeepOutput(fullPath); if (ContentEquals(fullPath, content)) return false; - Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!); + TrackedFs.CreateDirectory(Path.GetDirectoryName(fullPath)!); var temporary = $"{fullPath}.tmp.{Guid.NewGuid():N}"; - using (var stream = new FileStream( - temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, CompareBufferSize)) + using (var stream = TrackedFs.CreateNew(temporary, CompareBufferSize)) { stream.Write(content); } - File.Move(temporary, fullPath, overwrite: true); + TrackedFs.Move(temporary, fullPath, overwrite: true); return true; } @@ -38,11 +39,9 @@ public static bool WriteBytesIfChanged(string path, ReadOnlySpan content) /// public static bool ContentEquals(string path, ReadOnlySpan content) { - var info = new FileInfo(path); - if (!info.Exists || info.Length != content.Length) return false; + if (!TrackedFs.OutputFileExists(path) || TrackedFs.OutputFileLength(path) != content.Length) return false; - using var stream = new FileStream( - path, FileMode.Open, FileAccess.Read, FileShare.Read, CompareBufferSize, FileOptions.SequentialScan); + using var stream = TrackedFs.OpenOutputForCompare(path, CompareBufferSize); var buffer = ArrayPool.Shared.Rent(CompareBufferSize); try { @@ -69,14 +68,10 @@ public static bool ContentEquals(string path, ReadOnlySpan content) /// public static bool FilesEqual(string left, string right) { - var leftInfo = new FileInfo(left); - var rightInfo = new FileInfo(right); - if (leftInfo.Length != rightInfo.Length) return false; + if (TrackedFs.OutputFileLength(left) != TrackedFs.OutputFileLength(right)) return false; - using var leftStream = new FileStream( - left, FileMode.Open, FileAccess.Read, FileShare.Read, CompareBufferSize, FileOptions.SequentialScan); - using var rightStream = new FileStream( - right, FileMode.Open, FileAccess.Read, FileShare.Read, CompareBufferSize, FileOptions.SequentialScan); + using var leftStream = TrackedFs.OpenOutputForCompare(left, CompareBufferSize); + using var rightStream = TrackedFs.OpenOutputForCompare(right, CompareBufferSize); var leftBuffer = ArrayPool.Shared.Rent(CompareBufferSize); var rightBuffer = ArrayPool.Shared.Rent(CompareBufferSize); try diff --git a/translator/src/Translator.Core/IO/StepProvenance.cs b/translator/src/Translator.Core/IO/StepProvenance.cs new file mode 100644 index 000000000..89c248fa5 --- /dev/null +++ b/translator/src/Translator.Core/IO/StepProvenance.cs @@ -0,0 +1,433 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Translator.Core.IO; + +/// What identifies one invocation of a build step apart from the files it touches. +public sealed record StepInvocation( + string Step, + string? TranslatorIdentity, + string Runtime, + string WorkingDirectory, + IReadOnlyList Arguments, + int? EffectiveThreads, + int ProcessorCount) +{ + public static StepInvocation ForCurrentProcess(string step, IReadOnlyList arguments, int? effectiveThreads) => new( + step, + StepProvenance.ComputeTranslatorIdentity(), + RuntimeInformation.FrameworkDescription, + Directory.GetCurrentDirectory(), + arguments.ToArray(), + effectiveThreads, + Environment.ProcessorCount); +} + +/// +/// On-disk record of a successful step: the invocation plus every file it read (with its +/// SHA-256), every path it probed, every directory listing it took, and every output it left +/// (with its size). A later run of the same step skips only when all of it still holds. +/// +public sealed class StepProvenanceRecord +{ + public int SchemaVersion { get; set; } + public string Step { get; set; } = string.Empty; + public string? TranslatorIdentity { get; set; } + public string Runtime { get; set; } = string.Empty; + public string WorkingDirectory { get; set; } = string.Empty; + public List Arguments { get; set; } = []; + public int? EffectiveThreads { get; set; } + public int ProcessorCount { get; set; } + public List EnvironmentExpansions { get; set; } = []; + public List Inputs { get; set; } = []; + public List Probes { get; set; } = []; + public List Scans { get; set; } = []; + public List Outputs { get; set; } = []; + + public sealed class EnvironmentExpansionEntry + { + public string Value { get; set; } = string.Empty; + public string Expanded { get; set; } = string.Empty; + } + + public sealed class InputEntry + { + public string Path { get; set; } = string.Empty; + public string Sha256 { get; set; } = string.Empty; + } + + public sealed class ProbeEntry + { + public string Path { get; set; } = string.Empty; + public bool IsDirectory { get; set; } + public bool Exists { get; set; } + } + + public sealed class ScanEntry + { + public string Directory { get; set; } = string.Empty; + public string Pattern { get; set; } = "*"; + public bool Recursive { get; set; } + public bool Directories { get; set; } + public bool DirectoryExists { get; set; } + public List Entries { get; set; } = []; + + public FileScanQuery ToQuery() => new( + Directory, + Pattern, + Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly, + Directories ? FileScanKind.Directories : FileScanKind.Files); + } + + public sealed class OutputEntry + { + public string Path { get; set; } = string.Empty; + public long Size { get; set; } + public long LastWriteTicks { get; set; } + } +} + +public static class StepProvenance +{ + /// Bump whenever the record's meaning changes; any other version is a miss. + public const int SchemaVersion = 2; + + /// Test hook: when set, a command records every access and writes it here as a provenance record. + public const string AccessLogEnvironmentVariable = "WIICOMPILED_TRANSLATOR_ACCESS_LOG"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, + }; + + /// + /// SHA-256 over the running translator's binaries: the single-file app host itself, or, + /// when the app runs from a framework-dependent layout (app host or dotnet), every + /// assembly and runtime manifest beside it. Null when it cannot be determined; a record + /// with a null identity never matches. + /// + public static string? ComputeTranslatorIdentity() + { + try + { + var files = new SortedDictionary(StringComparer.Ordinal); + var entryName = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name; + var processPath = Environment.ProcessPath; + var baseDirectory = AppContext.BaseDirectory; + if (string.IsNullOrEmpty(entryName) || string.IsNullOrEmpty(baseDirectory)) return null; + + // The entry assembly sits on disk unless it is bundled into a single-file app host. + var frameworkDependent = File.Exists(Path.Combine(baseDirectory, entryName + ".dll")); + if (!frameworkDependent) + { + // Single-file: the host is the whole translator, whatever it was renamed to + // (the AppImage ships it as translator-cli). + if (processPath is null || !File.Exists(processPath)) return null; + files["host:" + Path.GetFileName(processPath)] = Sha256OfFile(processPath); + } + else + { + // An app host next to the assemblies (not the shared dotnet muxer) is part of the translator too. + if (processPath is not null && File.Exists(processPath) && + string.Equals(Path.GetFileNameWithoutExtension(processPath), entryName, StringComparison.OrdinalIgnoreCase)) + { + files["host:" + Path.GetFileName(processPath)] = Sha256OfFile(processPath); + } + + foreach (var file in Directory.EnumerateFiles(baseDirectory, "*", SearchOption.TopDirectoryOnly) + .Where(static file => file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || + file.EndsWith(".deps.json", StringComparison.OrdinalIgnoreCase) || + file.EndsWith(".runtimeconfig.json", StringComparison.OrdinalIgnoreCase))) + { + files["lib:" + Path.GetFileName(file)] = Sha256OfFile(file); + } + } + + if (files.Count == 0) return null; + var manifest = new StringBuilder(); + foreach (var (name, hash) in files) manifest.Append(hash).Append(" ").Append(name).Append('\n'); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(manifest.ToString()))).ToLowerInvariant(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + public static StepProvenanceRecord CreateRecord(StepInvocation invocation, FileAccessSnapshot snapshot) => new() + { + SchemaVersion = SchemaVersion, + Step = invocation.Step, + TranslatorIdentity = invocation.TranslatorIdentity, + Runtime = invocation.Runtime, + WorkingDirectory = invocation.WorkingDirectory, + Arguments = invocation.Arguments.ToList(), + EffectiveThreads = invocation.EffectiveThreads, + ProcessorCount = invocation.ProcessorCount, + EnvironmentExpansions = snapshot.EnvironmentExpansions + .Select(static item => new StepProvenanceRecord.EnvironmentExpansionEntry { Value = item.Value, Expanded = item.Expanded }) + .ToList(), + Inputs = snapshot.Inputs + .Select(static item => new StepProvenanceRecord.InputEntry { Path = item.Path, Sha256 = item.Sha256 }) + .ToList(), + Probes = snapshot.Probes + .Select(static item => new StepProvenanceRecord.ProbeEntry { Path = item.Path, IsDirectory = item.IsDirectory, Exists = item.Exists }) + .ToList(), + Scans = snapshot.Scans + .Select(static item => new StepProvenanceRecord.ScanEntry + { + Directory = item.Query.Directory, + Pattern = item.Query.Pattern, + Recursive = item.Query.Option == SearchOption.AllDirectories, + Directories = item.Query.Kind == FileScanKind.Directories, + DirectoryExists = Directory.Exists(item.Query.Directory), + Entries = item.Entries.ToList(), + }) + .ToList(), + Outputs = snapshot.Outputs + .Select(static item => new StepProvenanceRecord.OutputEntry + { + Path = item.Path, + Size = item.Size, + LastWriteTicks = File.GetLastWriteTimeUtc(item.Path).Ticks, + }) + .ToList(), + }; + + /// The record at , or null with the reason when it is missing or unusable. + public static StepProvenanceRecord? TryRead(string path, out string reason) + { + try + { + if (!File.Exists(path)) + { + reason = "no provenance record"; + return null; + } + var record = JsonSerializer.Deserialize(File.ReadAllBytes(path), JsonOptions); + if (record is null) + { + reason = "empty provenance record"; + return null; + } + if (record.SchemaVersion != SchemaVersion) + { + reason = $"provenance schema {record.SchemaVersion} is not {SchemaVersion}"; + return null; + } + reason = string.Empty; + return record; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) + { + reason = $"unreadable provenance record: {ex.Message}"; + return null; + } + } + + /// Null when describes exactly this invocation, otherwise why not. + public static string? CompareInvocation(StepProvenanceRecord record, StepInvocation invocation) + { + if (invocation.TranslatorIdentity is null) return "the running translator's identity is unknown"; + if (!string.Equals(record.Step, invocation.Step, StringComparison.Ordinal)) return "the record belongs to another step"; + if (!string.Equals(record.TranslatorIdentity, invocation.TranslatorIdentity, StringComparison.Ordinal)) + return "the translator changed"; + if (!string.Equals(record.Runtime, invocation.Runtime, StringComparison.Ordinal)) return "the .NET runtime changed"; + if (!string.Equals(record.WorkingDirectory, invocation.WorkingDirectory, StringComparison.Ordinal)) + return "the working directory changed"; + if (!record.Arguments.SequenceEqual(invocation.Arguments, StringComparer.Ordinal)) return "the arguments changed"; + if (record.EffectiveThreads != invocation.EffectiveThreads) return "the thread count changed"; + if (record.ProcessorCount != invocation.ProcessorCount) return "the processor count changed"; + return null; + } + + /// Null when every recorded file-system fact still holds, otherwise the first that does not. + public static string? CheckFileSystem(StepProvenanceRecord record) + { + try + { + foreach (var expansion in record.EnvironmentExpansions) + { + if (!string.Equals(Environment.ExpandEnvironmentVariables(expansion.Value), expansion.Expanded, StringComparison.Ordinal)) + return $"environment expansion of '{expansion.Value}' changed"; + } + foreach (var probe in record.Probes) + { + var exists = probe.IsDirectory ? Directory.Exists(probe.Path) : File.Exists(probe.Path); + if (exists != probe.Exists) + return $"{(probe.IsDirectory ? "directory" : "file")} {probe.Path} {(probe.Exists ? "no longer exists" : "now exists")}"; + } + foreach (var scan in record.Scans) + { + var query = scan.ToQuery(); + var exists = Directory.Exists(query.Directory); + if (exists != scan.DirectoryExists) return $"directory {query.Directory} appeared or disappeared"; + var listing = exists ? query.ListNow() : []; + if (!listing.SequenceEqual(scan.Entries, StringComparer.Ordinal)) + return $"directory listing of {query.Directory} ({query.Pattern}) changed"; + } + foreach (var output in record.Outputs) + { + if (!File.Exists(output.Path)) return $"output {output.Path} is missing"; + var file = new FileInfo(output.Path); + if (file.Length != output.Size) return $"output {output.Path} changed size"; + if (file.LastWriteTimeUtc.Ticks != output.LastWriteTicks) return $"output {output.Path} was modified"; + } + foreach (var input in record.Inputs) + { + if (!File.Exists(input.Path)) return $"input {input.Path} is missing"; + if (!string.Equals(Sha256OfFile(input.Path), input.Sha256, StringComparison.OrdinalIgnoreCase)) + return $"input {input.Path} changed"; + } + return null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return $"could not verify the record: {ex.Message}"; + } + } + + /// Null when the record at proves this invocation is current, otherwise why not. + public static string? Evaluate(string path, StepInvocation invocation) + { + var record = TryRead(path, out var reason); + if (record is null) return reason; + return CompareInvocation(record, invocation) ?? CheckFileSystem(record); + } + + /// Temp file in the same directory, then an overwriting rename, so a reader never sees half a record. + public static void WriteAtomically(string path, StepProvenanceRecord record) + { + var fullPath = Path.GetFullPath(path); + var directory = Path.GetDirectoryName(fullPath)!; + Directory.CreateDirectory(directory); + var temporary = Path.Combine(directory, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp"); + try + { + File.WriteAllBytes(temporary, JsonSerializer.SerializeToUtf8Bytes(record, JsonOptions)); + File.Move(temporary, fullPath, overwrite: true); + } + finally + { + if (File.Exists(temporary)) File.Delete(temporary); + } + } + + public static string? AccessLogPathFromEnvironment() => + Environment.GetEnvironmentVariable(AccessLogEnvironmentVariable) is { Length: > 0 } value ? value : null; + + private static string Sha256OfFile(string path) + { + using var stream = File.OpenRead(path); + return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); + } +} + +/// +/// One command run under a provenance gate and/or the access-log hook. +/// either proves the step current (the caller skips it) or deletes the old record before +/// anything else happens and starts recording; writes the new record +/// only after the step succeeded. +/// +public sealed class StepProvenanceSession +{ + private readonly string? _recordPath; + private readonly string? _accessLogPath; + private readonly StepInvocation _invocation; + private readonly FileAccessRecorder? _recorder; + private readonly TextWriter _diagnostics; + + private StepProvenanceSession( + string? recordPath, string? accessLogPath, StepInvocation invocation, + FileAccessRecorder? recorder, TextWriter diagnostics, bool isCurrent) + { + _recordPath = recordPath; + _accessLogPath = accessLogPath; + _invocation = invocation; + _recorder = recorder; + _diagnostics = diagnostics; + IsCurrent = isCurrent; + } + + /// True when the existing record proves the step current; nothing was recorded or deleted. + public bool IsCurrent { get; } + + public static StepProvenanceSession? Start( + string? recordPath, string? accessLogPath, StepInvocation invocation, TextWriter diagnostics) + { + if (recordPath is null && accessLogPath is null) return null; + string? fullRecordPath = null; + if (recordPath is not null) + { + fullRecordPath = Path.GetFullPath(recordPath); + var miss = StepProvenance.Evaluate(fullRecordPath, invocation); + if (miss is null) + return new StepProvenanceSession(fullRecordPath, null, invocation, null, diagnostics, isCurrent: true); + diagnostics.WriteLine($"[translator] {invocation.Step} must run: {miss}."); + // From here until a successful finish there is no record, so a crash can never leave one claiming "current". + if (!TryDelete(fullRecordPath, diagnostics)) fullRecordPath = null; + } + + var recorder = new FileAccessRecorder(); + TrackedFs.Install(recorder); + return new StepProvenanceSession( + fullRecordPath, accessLogPath is null ? null : Path.GetFullPath(accessLogPath), + invocation, recorder, diagnostics, isCurrent: false); + } + + public void Finish(int exitCode) + { + if (_recorder is null) return; + TrackedFs.Install(null); + // A failed step only ever loses its record; nothing is inspected that could fail in turn. + if ((_recordPath is null || exitCode != 0) && _accessLogPath is null) return; + // Recording is an optimisation: failing to write it must never fail a step that succeeded. + try + { + Record(exitCode); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _diagnostics.WriteLine($"[translator] could not write the {_invocation.Step} provenance record: {ex.Message}"); + if (_recordPath is not null) TryDelete(_recordPath, _diagnostics); + } + } + + private static bool TryDelete(string path, TextWriter diagnostics) + { + try + { + if (File.Exists(path)) File.Delete(path); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + diagnostics.WriteLine($"[translator] could not delete {path}; no provenance record is kept: {ex.Message}"); + return false; + } + } + + private void Record(int exitCode) + { + var snapshot = _recorder!.Snapshot(); + var record = StepProvenance.CreateRecord(_invocation, snapshot); + if (_accessLogPath is not null) StepProvenance.WriteAtomically(_accessLogPath, record); + if (_recordPath is null || exitCode != 0) return; + if (snapshot.UntrackedInputs.Count != 0) + { + _diagnostics.WriteLine( + $"[translator] {_invocation.Step} read {string.Join(", ", snapshot.UntrackedInputs)}; no provenance record is kept."); + return; + } + if (_invocation.TranslatorIdentity is null) + { + _diagnostics.WriteLine($"[translator] the running translator could not be identified; no provenance record is kept."); + return; + } + StepProvenance.WriteAtomically(_recordPath, record); + } +} diff --git a/translator/src/Translator.Core/IO/TrackedFs.cs b/translator/src/Translator.Core/IO/TrackedFs.cs new file mode 100644 index 000000000..743f569e9 --- /dev/null +++ b/translator/src/Translator.Core/IO/TrackedFs.cs @@ -0,0 +1,280 @@ +using System.Security.Cryptography; +using System.Text; + +namespace Translator.Core.IO; + +/// +/// The translator's only door to the file system and the process environment. Every +/// read, probe, directory scan, write, move and delete in Translator.Core and +/// Translator.Cli goes through here (a source scan in the test suite enforces it), so a +/// sees everything a command touched. With no recorder +/// installed every member is a straight pass-through to the System.IO call it names. +/// +/// The Output* members exist for output management only: comparing a target before +/// rewriting it, carrying a timestamp over, listing an output tree to prune it. They are +/// never recorded as inputs, so their result must only decide whether or how an output is +/// written, never what it contains. Anything else uses the plain members. +/// +public static class TrackedFs +{ + private static volatile FileAccessRecorder? _recorder; + + /// The recorder every access is reported to, or null when nothing records. + public static FileAccessRecorder? Recorder => _recorder; + + /// Installs (or with null removes) the process-wide recorder. + public static void Install(FileAccessRecorder? recorder) => _recorder = recorder; + + // ---------------------------------------------------------------- inputs + + public static byte[] ReadAllBytes(string path) + { + var bytes = File.ReadAllBytes(path); + _recorder?.OnRead(path, bytes); + return bytes; + } + + /// Same decoding as : UTF-8 with byte-order-mark detection. + public static string ReadAllText(string path) + { + if (_recorder is not { } recorder) return File.ReadAllText(path); + var bytes = File.ReadAllBytes(path); + recorder.OnRead(path, bytes); + return DecodeText(bytes); + } + + /// Same decoding as . + public static IEnumerable ReadLines(string path) + { + if (_recorder is not { } recorder) return File.ReadLines(path); + var bytes = File.ReadAllBytes(path); + recorder.OnRead(path, bytes); + return DecodeLines(bytes); + } + + // File.ReadAllText/ReadLines are a StreamReader over the file with UTF-8 and BOM detection; + // decoding the hashed bytes the same way keeps a recorded run's text identical to an unrecorded one. + internal static string DecodeText(byte[] content) + { + using var reader = new StreamReader(new MemoryStream(content, writable: false), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + return reader.ReadToEnd(); + } + + internal static IEnumerable DecodeLines(byte[] content) + { + using var reader = new StreamReader(new MemoryStream(content, writable: false), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + while (reader.ReadLine() is { } line) yield return line; + } + + /// ; when recording, the content is hashed through the returned stream first. + public static FileStream OpenRead(string path) + { + var stream = File.OpenRead(path); + if (_recorder is { } recorder && recorder.WantsContent(path)) + { + try + { + var hash = SHA256.HashData(stream); + stream.Seek(0, SeekOrigin.Begin); + recorder.OnReadHash(path, hash); + } + catch + { + stream.Dispose(); + throw; + } + } + return stream; + } + + /// new FileInfo(path).Length, recorded as reading the file. + public static long FileLength(string path) + { + var length = new FileInfo(path).Length; + if (_recorder is { } recorder && recorder.WantsContent(path)) + { + using var stream = File.OpenRead(path); + recorder.OnReadHash(path, SHA256.HashData(stream)); + } + return length; + } + + public static bool FileExists(string? path) + { + var exists = File.Exists(path); + if (!string.IsNullOrEmpty(path)) _recorder?.OnFileProbe(path, exists); + return exists; + } + + public static bool DirectoryExists(string? path) + { + var exists = Directory.Exists(path); + if (!string.IsNullOrEmpty(path)) _recorder?.OnDirectoryProbe(path, exists); + return exists; + } + + public static IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) + { + if (_recorder is not { } recorder) return Directory.EnumerateFiles(path, searchPattern, searchOption); + var entries = Directory.EnumerateFiles(path, searchPattern, searchOption).ToArray(); + recorder.OnScan(new FileScanQuery(path, searchPattern, searchOption, FileScanKind.Files), entries); + return entries; + } + + public static IEnumerable EnumerateFiles(string path, string searchPattern) => + EnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly); + + public static IEnumerable EnumerateDirectories(string path) + { + if (_recorder is not { } recorder) return Directory.EnumerateDirectories(path); + var entries = Directory.EnumerateDirectories(path).ToArray(); + recorder.OnScan(new FileScanQuery(path, "*", SearchOption.TopDirectoryOnly, FileScanKind.Directories), entries); + return entries; + } + + public static string GetCurrentDirectory() + { + var directory = Directory.GetCurrentDirectory(); + _recorder?.OnCurrentDirectory(directory); + return directory; + } + + public static string ExpandEnvironmentVariables(string value) + { + var expanded = Environment.ExpandEnvironmentVariables(value); + _recorder?.OnEnvironmentExpansion(value, expanded); + return expanded; + } + + /// Marks the running command as depending on something no file record can capture (a download). + public static void NoteUntrackedInput(string description) => _recorder?.OnUntrackedInput(description); + + // ---------------------------------------------------------------- outputs + + public static void WriteAllBytes(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + _recorder?.OnWrite(path); + } + + public static void WriteAllText(string path, string? contents) + { + File.WriteAllText(path, contents); + _recorder?.OnWrite(path); + } + + /// . + public static FileStream Create(string path) + { + var stream = File.Create(path); + _recorder?.OnWrite(path); + return stream; + } + + /// new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize). + public static FileStream CreateNew(string path, int bufferSize) + { + var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize); + _recorder?.OnWrite(path); + return stream; + } + + public static void Move(string sourceFileName, string destFileName, bool overwrite) + { + File.Move(sourceFileName, destFileName, overwrite); + if (_recorder is { } recorder) + { + recorder.OnDeleteFile(sourceFileName); + recorder.OnWrite(destFileName); + } + } + + public static void Copy(string sourceFileName, string destFileName, bool overwrite) + { + if (_recorder is { } recorder && recorder.WantsContent(sourceFileName)) + { + using var stream = File.OpenRead(sourceFileName); + recorder.OnReadHash(sourceFileName, SHA256.HashData(stream)); + } + File.Copy(sourceFileName, destFileName, overwrite); + _recorder?.OnWrite(destFileName); + } + + public static void Delete(string path) + { + File.Delete(path); + _recorder?.OnDeleteFile(path); + } + + public static void CreateDirectory(string path) + { + if (_recorder is not { } recorder) + { + Directory.CreateDirectory(path); + return; + } + // The topmost directory this call brings into existence; everything below it is the command's own. + var full = Path.GetFullPath(path); + string? created = null; + for (var current = full; current is not null && !Directory.Exists(current); current = Path.GetDirectoryName(current)) + created = current; + Directory.CreateDirectory(path); + if (created is not null) recorder.OnCreateDirectory(created); + } + + public static void DeleteDirectory(string path, bool recursive) + { + Directory.Delete(path, recursive); + _recorder?.OnDeleteDirectory(path); + } + + public static void MoveDirectory(string sourceDirName, string destDirName) + { + Directory.Move(sourceDirName, destDirName); + _recorder?.OnMoveDirectory(sourceDirName, destDirName); + } + + // ---------------------------------------------------------------- output management (never inputs) + + /// Declares an existing file this command decided to keep as one of its outputs (a content-gated write that found nothing to change). + public static void KeepOutput(string path) => _recorder?.OnWrite(path); + + public static bool OutputFileExists(string? path) => File.Exists(path); + + public static bool OutputDirectoryExists(string? path) => Directory.Exists(path); + + /// new FileInfo(path).Length of an output; throws like FileInfo when it is missing. + public static long OutputFileLength(string path) => new FileInfo(path).Length; + + /// A read-only stream over an existing output, for comparing it with what is about to be written. + public static FileStream OpenOutputForCompare(string path, int bufferSize) => + new(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan); + + public static DateTime GetOutputLastWriteTimeUtc(string path) => File.GetLastWriteTimeUtc(path); + + public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc) => + File.SetLastWriteTimeUtc(path, lastWriteTimeUtc); + + /// + /// Lists an output tree for pruning. Recorded as the listing the tree must still have + /// once the command finished, so a file added there later still invalidates the command. + /// + public static IEnumerable EnumerateOutputFiles(string path, string searchPattern, SearchOption searchOption) + { + if (_recorder is not { } recorder) return Directory.EnumerateFiles(path, searchPattern, searchOption); + var entries = Directory.EnumerateFiles(path, searchPattern, searchOption).ToArray(); + recorder.OnOutputScan(new FileScanQuery(path, searchPattern, searchOption, FileScanKind.Files)); + return entries; + } + + public static IEnumerable EnumerateOutputFiles(string path, string searchPattern) => + EnumerateOutputFiles(path, searchPattern, SearchOption.TopDirectoryOnly); + + public static IEnumerable EnumerateOutputDirectories(string path) + { + if (_recorder is not { } recorder) return Directory.EnumerateDirectories(path); + var entries = Directory.EnumerateDirectories(path).ToArray(); + recorder.OnOutputScan(new FileScanQuery(path, "*", SearchOption.TopDirectoryOnly, FileScanKind.Directories)); + return entries; + } +} diff --git a/translator/src/Translator.Core/IO/TransactionalDirectoryOutput.cs b/translator/src/Translator.Core/IO/TransactionalDirectoryOutput.cs index b0d4d641b..5dd82f94d 100644 --- a/translator/src/Translator.Core/IO/TransactionalDirectoryOutput.cs +++ b/translator/src/Translator.Core/IO/TransactionalDirectoryOutput.cs @@ -34,16 +34,16 @@ public static GenerateAndPublishResult GenerateAndPublish( ArgumentNullException.ThrowIfNull(producer); var destination = Path.GetFullPath(destinationDirectory); - var parent = Directory.GetParent(destination)?.FullName + var parent = Path.GetDirectoryName(destination) ?? throw new InvalidOperationException($"Output directory has no parent: {destination}"); - Directory.CreateDirectory(parent); + TrackedFs.CreateDirectory(parent); var leaf = Path.GetFileName(destination.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); var staging = Path.Combine(parent, $".{leaf}.translate-mod-staging-{Guid.NewGuid():N}"); // The same list instance is handed to the result record, so warnings the // staging cleanup below adds still reach the caller. var warnings = new List(); - Directory.CreateDirectory(staging); + TrackedFs.CreateDirectory(staging); try { @@ -58,7 +58,7 @@ public static GenerateAndPublishResult GenerateAndPublish( } finally { - if (Directory.Exists(staging)) + if (TrackedFs.DirectoryExists(staging)) { TryDeleteDirectory(staging, "staging output", warnings); } @@ -68,7 +68,7 @@ public static GenerateAndPublishResult GenerateAndPublish( private static PublishResult Publish(string staging, string destination, List warnings) { var stagedFiles = EnumerateRelativeFiles(staging); - var liveFiles = Directory.Exists(destination) + var liveFiles = TrackedFs.OutputDirectoryExists(destination) ? EnumerateRelativeFiles(destination) : new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -92,18 +92,18 @@ private static PublishResult Publish(string staging, string destination, List !stagedFiles.ContainsKey(path)); - if (!Directory.Exists(destination)) + if (!TrackedFs.OutputDirectoryExists(destination)) { MoveDirectoryWithRetry(staging, destination); return new PublishResult(added, updated, removed, unchanged); } - var parent = Directory.GetParent(destination)!.FullName; + var parent = Path.GetDirectoryName(destination)!; var leaf = Path.GetFileName(destination.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); var backup = Path.Combine(parent, $".{leaf}.translate-mod-backup-{Guid.NewGuid():N}"); @@ -114,7 +114,7 @@ private static PublishResult Publish(string staging, string destination, List Directory.Move(source, destination), + () => TrackedFs.MoveDirectory(source, destination), $"move directory '{source}' to '{destination}'"); } @@ -150,7 +150,7 @@ private static void TryDeleteDirectory(string path, string description, List Directory.Delete(path, recursive: true), + () => TrackedFs.DeleteDirectory(path, recursive: true), $"delete {description} '{path}'"); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) @@ -186,7 +186,7 @@ private static void RetryTransientFileSystemAction(Action action, string descrip } private static Dictionary EnumerateRelativeFiles(string root) => - Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories) + TrackedFs.EnumerateOutputFiles(root, "*", SearchOption.AllDirectories) .ToDictionary( path => Path.GetRelativePath(root, path), path => path, diff --git a/translator/src/Translator.Core/Loading/ChecksumUtilities.cs b/translator/src/Translator.Core/Loading/ChecksumUtilities.cs index 586571490..c874cd9ec 100644 --- a/translator/src/Translator.Core/Loading/ChecksumUtilities.cs +++ b/translator/src/Translator.Core/Loading/ChecksumUtilities.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Security.Cryptography; namespace Translator.Core.Loading; @@ -21,7 +22,7 @@ public static string ToHex(ReadOnlySpan hash) => /// Streams the file rather than materializing it, so hashing a REL costs no copy. public static string Sha256HexOfFile(string path) { - using var stream = File.OpenRead(path); + using var stream = TrackedFs.OpenRead(path); return ToHex(SHA256.HashData(stream)); } } diff --git a/translator/src/Translator.Core/Loading/FunctionMap.cs b/translator/src/Translator.Core/Loading/FunctionMap.cs index f04413d40..543e1f132 100644 --- a/translator/src/Translator.Core/Loading/FunctionMap.cs +++ b/translator/src/Translator.Core/Loading/FunctionMap.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System; using System.Collections.Generic; using System.Globalization; @@ -69,12 +70,12 @@ public IReadOnlyDictionary NumberedFamily(string prefix) public static FunctionMap Load(string path) { - if (!File.Exists(path)) + if (!TrackedFs.FileExists(path)) { throw new FileNotFoundException("Configured function map was not found.", path); } - return Parse(File.ReadLines(path), path); + return Parse(TrackedFs.ReadLines(path), path); } public static FunctionMap Parse(IEnumerable lines, string sourcePath) diff --git a/translator/src/Translator.Core/Mods/BaseManifest.cs b/translator/src/Translator.Core/Mods/BaseManifest.cs index d0e69b4da..3e55fe8c8 100644 --- a/translator/src/Translator.Core/Mods/BaseManifest.cs +++ b/translator/src/Translator.Core/Mods/BaseManifest.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Text.Json; namespace Translator.Core.Mods; @@ -43,7 +44,7 @@ public BaseFunctionIndex(IEnumerable functions) public static BaseFunctionIndex Load(string path) { - var json = File.ReadAllText(path); + var json = TrackedFs.ReadAllText(path); var manifest = JsonSerializer.Deserialize(json) ?? throw new InvalidDataException($"Failed to parse base manifest: {path}"); return new BaseFunctionIndex(manifest.Functions); diff --git a/translator/src/Translator.Core/Mods/BaseManifestBuilder.cs b/translator/src/Translator.Core/Mods/BaseManifestBuilder.cs index c543291d6..fcf445924 100644 --- a/translator/src/Translator.Core/Mods/BaseManifestBuilder.cs +++ b/translator/src/Translator.Core/Mods/BaseManifestBuilder.cs @@ -32,7 +32,7 @@ public static BaseManifestBuildResult BuildAndWrite( string relSourceName = "module.rel", BaseTranslationOutputMetadata? translationOutput = null) { - Directory.CreateDirectory(outputDir); + TrackedFs.CreateDirectory(outputDir); var sections = new List(); var dolTextPath = Path.Combine(outputDir, $"{fileStem}_main_text.bin"); @@ -106,7 +106,7 @@ public static BaseManifestBuildResult BuildAndWrite( private static Dictionary WriteDolExecutableImage(DolFile dol, string path) { var offsets = new Dictionary(StringComparer.OrdinalIgnoreCase); - using var output = File.Create(path); + using var output = TrackedFs.Create(path); foreach (var section in dol.Sections.Where(s => s.IsExecutable && s.Size > 0).OrderBy(s => s.VirtualAddress)) { offsets[section.Name] = checked((uint)output.Position); @@ -118,7 +118,7 @@ private static Dictionary WriteDolExecutableImage(DolFile dol, str private static Dictionary WriteRelExecutableImage(RelFile rel, RelImage relImage, string path) { var offsets = new Dictionary(); - using var output = File.Create(path); + using var output = TrackedFs.Create(path); foreach (var section in rel.Sections.Where(s => s.Executable && s.Size > 0).OrderBy(s => s.FileOffset)) { if (section.FileOffset + section.Size > relImage.Data.Length) @@ -177,12 +177,12 @@ private static IReadOnlyList BuildFunctionRanges( internal static IReadOnlyList DiscoverCanonicalGeneratedFunctionStarts(string generatedFunctionsDir) { var files = new List<(uint Start, string Path)>(); - if (!Directory.Exists(generatedFunctionsDir)) + if (!TrackedFs.DirectoryExists(generatedFunctionsDir)) { return Array.Empty(); } - foreach (var path in Directory.EnumerateFiles(generatedFunctionsDir, "*.cpp", SearchOption.AllDirectories)) + foreach (var path in TrackedFs.EnumerateFiles(generatedFunctionsDir, "*.cpp", SearchOption.AllDirectories)) { var fileName = Path.GetFileNameWithoutExtension(path); var match = AddressRegex().Match(fileName); @@ -200,7 +200,7 @@ internal static IReadOnlyList DiscoverCanonicalGeneratedFunctionStarts(str var embeddedAliases = new HashSet(); foreach (var (ownerStart, path) in files) { - var source = File.ReadAllText(path); + var source = TrackedFs.ReadAllText(path); foreach (Match match in LocalLabelRegex().Matches(source)) { if (GuestTargetParser.TryParseHexAddress(match.Groups[1].Value, out var label) && diff --git a/translator/src/Translator.Core/Mods/BaseTranslationModAwareness.cs b/translator/src/Translator.Core/Mods/BaseTranslationModAwareness.cs index 3343f148b..3f74f93eb 100644 --- a/translator/src/Translator.Core/Mods/BaseTranslationModAwareness.cs +++ b/translator/src/Translator.Core/Mods/BaseTranslationModAwareness.cs @@ -185,7 +185,7 @@ public static class BaseTranslationModAwarenessFile public static BaseTranslationModAwareness Read(string path) { - var awareness = JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions) + var awareness = JsonSerializer.Deserialize(TrackedFs.ReadAllText(path), JsonOptions) ?? throw new InvalidDataException($"Base translation mod-awareness record is empty: {path}"); Validate(awareness, path); return awareness; @@ -193,7 +193,7 @@ public static BaseTranslationModAwareness Read(string path) public static BaseTranslationModAwareness? TryRead(string path) { - if (!File.Exists(path)) return null; + if (!TrackedFs.FileExists(path)) return null; try { return Read(path); } catch (Exception ex) when (ex is IOException or JsonException or InvalidDataException) { return null; } } diff --git a/translator/src/Translator.Core/Mods/BaseTranslationOutputMetadata.cs b/translator/src/Translator.Core/Mods/BaseTranslationOutputMetadata.cs index 08ce2dc24..726ce2d24 100644 --- a/translator/src/Translator.Core/Mods/BaseTranslationOutputMetadata.cs +++ b/translator/src/Translator.Core/Mods/BaseTranslationOutputMetadata.cs @@ -177,7 +177,7 @@ public static class BaseTranslationOutputMetadataFile public static BaseTranslationOutputMetadata Read(string path) { - var metadata = JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions) + var metadata = JsonSerializer.Deserialize(TrackedFs.ReadAllText(path), JsonOptions) ?? throw new InvalidDataException($"Base translation output metadata is empty: {path}"); Validate(metadata, path); return metadata; diff --git a/translator/src/Translator.Core/Mods/ModDataPatchWriter.cs b/translator/src/Translator.Core/Mods/ModDataPatchWriter.cs index 2992d1e50..e5aa1d060 100644 --- a/translator/src/Translator.Core/Mods/ModDataPatchWriter.cs +++ b/translator/src/Translator.Core/Mods/ModDataPatchWriter.cs @@ -208,7 +208,7 @@ public static void Write( sb.AppendLine(); sb.AppendLine("} // namespace"); - Directory.CreateDirectory(Path.GetDirectoryName(path)!); + TrackedFs.CreateDirectory(Path.GetDirectoryName(path)!); FileOutput.WriteTextIfChanged(path, sb.ToString()); } diff --git a/translator/src/Translator.Core/Mods/ModDvdOverlayRoots.cs b/translator/src/Translator.Core/Mods/ModDvdOverlayRoots.cs index 6a748dd7a..992f1bd2a 100644 --- a/translator/src/Translator.Core/Mods/ModDvdOverlayRoots.cs +++ b/translator/src/Translator.Core/Mods/ModDvdOverlayRoots.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; namespace Translator.Core.Mods; /// @@ -34,7 +35,7 @@ public static IReadOnlyList Discover(string? modRoot) }; return candidates - .Where(candidate => Directory.Exists(candidate.Source)) + .Where(candidate => TrackedFs.DirectoryExists(candidate.Source)) .Select(candidate => candidate.Package.Replace('\\', '/')) .Distinct(StringComparer.OrdinalIgnoreCase) .ToList(); diff --git a/translator/src/Translator.Core/Mods/OverlayFunctionBuilder.cs b/translator/src/Translator.Core/Mods/OverlayFunctionBuilder.cs index 26a775837..a4c1c6e96 100644 --- a/translator/src/Translator.Core/Mods/OverlayFunctionBuilder.cs +++ b/translator/src/Translator.Core/Mods/OverlayFunctionBuilder.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Buffers.Binary; using System.Security.Cryptography; using System.Text.Json; @@ -48,7 +49,7 @@ public static OverlayBuildResult BuildAndWrite( IReadOnlyCollection? retroWfcExecutableHooks = null) { var overlayDir = Path.Combine(outputDirectory, "overlay_images"); - Directory.CreateDirectory(overlayDir); + TrackedFs.CreateDirectory(overlayDir); var diagnostics = new List(); var moduleImage = BuildModuleImage(chunk.CodeBlob, additionalModuleImage, additionalModuleImageOffset); @@ -70,7 +71,7 @@ public static OverlayBuildResult BuildAndWrite( } var moduleImageFile = $"kamek_module_{patchPlan.ModuleGuestBase:X8}.bin"; - File.WriteAllBytes(Path.Combine(overlayDir, moduleImageFile), moduleImage); + TrackedFs.WriteAllBytes(Path.Combine(overlayDir, moduleImageFile), moduleImage); var sectionsByName = baseManifest.Sections.ToDictionary(s => s.Name, StringComparer.OrdinalIgnoreCase); var imageCache = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -201,7 +202,7 @@ public static OverlayBuildResult BuildAndWrite( } var imageFile = $"overlay_{function.Start:X8}.bin"; - File.WriteAllBytes(Path.Combine(overlayDir, imageFile), bytes); + TrackedFs.WriteAllBytes(Path.Combine(overlayDir, imageFile), bytes); overlays.Add(new OverlayFunctionImage( function.Start, @@ -274,7 +275,7 @@ private static byte[] LoadImage(string baseManifestDirectory, string imageFile, } var path = Path.Combine(baseManifestDirectory, imageFile); - bytes = File.ReadAllBytes(path); + bytes = TrackedFs.ReadAllBytes(path); cache[imageFile] = bytes; return bytes; } diff --git a/translator/src/Translator.Core/NativeSourceParsing.cs b/translator/src/Translator.Core/NativeSourceParsing.cs index 7042cc974..ba40af386 100644 --- a/translator/src/Translator.Core/NativeSourceParsing.cs +++ b/translator/src/Translator.Core/NativeSourceParsing.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System; using System.Collections.Generic; using System.Text; @@ -17,17 +18,17 @@ public static IReadOnlyList ReadDirectory(string directory) .Select(path => new NativeSourceFile( path, RelativePath(root, path), - StripCommentsAndLiterals(File.ReadAllText(path)))) + StripCommentsAndLiterals(TrackedFs.ReadAllText(path)))) .ToArray(); } /// Every file the scanner reads; the native index digest covers exactly this set. public static IEnumerable EnumerateSourcePaths(string root) { - if (!Directory.Exists(root)) + if (!TrackedFs.DirectoryExists(root)) return []; - return Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories) + return TrackedFs.EnumerateFiles(root, "*.*", SearchOption.AllDirectories) .Where(static path => path.EndsWith(".cpp", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".h", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".hpp", StringComparison.OrdinalIgnoreCase)); diff --git a/translator/src/Translator.Core/Parsing/Dol/DolFile.cs b/translator/src/Translator.Core/Parsing/Dol/DolFile.cs index ef13cb615..de8866dd3 100644 --- a/translator/src/Translator.Core/Parsing/Dol/DolFile.cs +++ b/translator/src/Translator.Core/Parsing/Dol/DolFile.cs @@ -34,7 +34,7 @@ private DolFile(IReadOnlyList sections, uint entryPoint, uint bssAdd public static DolFile Load(string path) { - using var stream = File.OpenRead(path); + using var stream = TrackedFs.OpenRead(path); return Load(stream); } diff --git a/translator/src/Translator.Core/Parsing/Kamek/KamekPulFile.cs b/translator/src/Translator.Core/Parsing/Kamek/KamekPulFile.cs index 0cd46a93a..610ec4d22 100644 --- a/translator/src/Translator.Core/Parsing/Kamek/KamekPulFile.cs +++ b/translator/src/Translator.Core/Parsing/Kamek/KamekPulFile.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Buffers.Binary; namespace Translator.Core.Parsing.Kamek; @@ -17,7 +18,7 @@ public KamekPulFile(bool isCombined, IReadOnlyList combinedChunkSizes, IRe public IReadOnlyList CombinedChunkSizes { get; } public IReadOnlyList Chunks { get; } - public static KamekPulFile Load(string path) => Parse(File.ReadAllBytes(path)); + public static KamekPulFile Load(string path) => Parse(TrackedFs.ReadAllBytes(path)); public static KamekPulFile Parse(byte[] data) { diff --git a/translator/src/Translator.Core/Parsing/Rel/RelFile.cs b/translator/src/Translator.Core/Parsing/Rel/RelFile.cs index d0f611383..60a6d96bb 100644 --- a/translator/src/Translator.Core/Parsing/Rel/RelFile.cs +++ b/translator/src/Translator.Core/Parsing/Rel/RelFile.cs @@ -32,7 +32,7 @@ private RelFile(byte[] raw, public static RelFile Load(string path) { - var raw = File.ReadAllBytes(path); + var raw = TrackedFs.ReadAllBytes(path); using var stream = new MemoryStream(raw, writable: false); using var reader = new BigEndianBinaryReader(stream, leaveOpen: true); diff --git a/translator/src/Translator.Core/RuntimeNativeIndex.cs b/translator/src/Translator.Core/RuntimeNativeIndex.cs index 66a1f4b9b..94aa4f199 100644 --- a/translator/src/Translator.Core/RuntimeNativeIndex.cs +++ b/translator/src/Translator.Core/RuntimeNativeIndex.cs @@ -1,3 +1,4 @@ +using Translator.Core.IO; using System.Text.RegularExpressions; using Translator.Core.Analysis; using Translator.Core.CodeGen; @@ -75,10 +76,14 @@ public RuntimeNativeGuestEffectSet ToGuestEffectSet() public static class RuntimeNativeIndexBuilder { + /// Every source file and the index digest read under . + public static IEnumerable EnumerateSourceFiles(string nativeSourceDirectory) => + NativeSourceParsing.EnumerateSourcePaths(Path.GetFullPath(nativeSourceDirectory)); + public static RuntimeNativeIndex Build(string nativeSourceDirectory) { var sourceRoot = Path.GetFullPath(nativeSourceDirectory); - if (!Directory.Exists(sourceRoot)) + if (!TrackedFs.DirectoryExists(sourceRoot)) return new RuntimeNativeIndex([], [], []); var sources = NativeSourceParsing.ReadDirectory(sourceRoot); @@ -107,10 +112,10 @@ public static RuntimeNativeIndex Resolve( string nativeSourceDirectory, string? indexPath, TextWriter? diagnostics = null) { var sourceRoot = Path.GetFullPath(nativeSourceDirectory); - if (string.IsNullOrWhiteSpace(indexPath) || !File.Exists(indexPath)) + if (string.IsNullOrWhiteSpace(indexPath) || !TrackedFs.FileExists(indexPath)) return Build(sourceRoot); - var expectedDigest = Directory.Exists(sourceRoot) + var expectedDigest = TrackedFs.DirectoryExists(sourceRoot) ? RuntimeNativeIndexFile.ComputeSourceDigest(sourceRoot) : null; if (RuntimeNativeIndexFile.TryLoad(indexPath, expectedDigest, out var index, out var reason)) diff --git a/translator/src/Translator.Core/RuntimeNativeIndexFile.cs b/translator/src/Translator.Core/RuntimeNativeIndexFile.cs index 0a3c27369..97c80328c 100644 --- a/translator/src/Translator.Core/RuntimeNativeIndexFile.cs +++ b/translator/src/Translator.Core/RuntimeNativeIndexFile.cs @@ -38,7 +38,7 @@ public static string ComputeSourceDigest(string nativeSourceDirectory) .Select(path => (Relative: NativeSourceParsing.RelativePath(root, path), Path: path)) .OrderBy(static item => item.Relative, StringComparer.Ordinal)) { - using var stream = File.OpenRead(path); + using var stream = TrackedFs.OpenRead(path); manifest.Append(Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant()) .Append(" ").Append(relative).Append('\n'); } @@ -112,7 +112,7 @@ public static bool TryLoad( IndexDocument? document; try { - using var parsed = JsonDocument.Parse(File.ReadAllBytes(path)); + using var parsed = JsonDocument.Parse(TrackedFs.ReadAllBytes(path)); var root = parsed.RootElement; if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("format", out var format) || format.ValueKind != JsonValueKind.String || diff --git a/translator/tests/Translator.Tests/FileAccessRecorderTests.cs b/translator/tests/Translator.Tests/FileAccessRecorderTests.cs new file mode 100644 index 000000000..9c011bb2d --- /dev/null +++ b/translator/tests/Translator.Tests/FileAccessRecorderTests.cs @@ -0,0 +1,162 @@ +using System.Text; +using Translator.Core.IO; + +namespace Translator.Tests; + +/// +/// The recorder's bookkeeping rules, exercised on a recorder instance directly (never installed +/// process-wide, so parallel tests are unaffected), and the recording-mode text decoding. +/// +public sealed class FileAccessRecorderTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"translator-recorder-{Guid.NewGuid():N}"); + + public FileAccessRecorderTests() => Directory.CreateDirectory(_root); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); + } + + [Fact] + public void FirstReadKeepsTheHashItSawAndOwnFilesAreNotInputs() + { + var input = Write("input.txt", "one"); + var recorder = new FileAccessRecorder(); + recorder.OnRead(input, File.ReadAllBytes(input)); + File.WriteAllText(input, "two"); + recorder.OnRead(input, File.ReadAllBytes(input)); + recorder.OnWrite(input); + + var produced = Write("produced.txt", "mine"); + recorder.OnWrite(produced); + recorder.OnRead(produced, File.ReadAllBytes(produced)); + recorder.OnFileProbe(produced, exists: true); + + var staging = Path.Combine(_root, "staging"); + recorder.OnCreateDirectory(staging); + Directory.CreateDirectory(staging); + var staged = Write(Path.Combine("staging", "deep", "file.txt"), "staged"); + recorder.OnRead(staged, File.ReadAllBytes(staged)); + recorder.OnScan(new FileScanQuery(staging, "*", SearchOption.AllDirectories, FileScanKind.Files), [staged]); + + var snapshot = recorder.Snapshot(); + var only = Assert.Single(snapshot.Inputs); + Assert.Equal(input, only.Path); + Assert.Equal(Translator.Core.Loading.ChecksumUtilities.Sha256Hex(Encoding.UTF8.GetBytes("one")), only.Sha256); + Assert.Empty(snapshot.Probes); + Assert.Empty(snapshot.Scans); + Assert.Contains(snapshot.Outputs, output => output.Path == produced && output.Size == 4); + // A read-then-rewritten file can never match its own record: fail closed. + Assert.Contains(snapshot.Outputs, output => output.Path == input); + } + + [Fact] + public void DeletedPreexistingPathsMustStayDeletedAndTemporariesVanish() + { + var stale = Write("stale.cpp", "old"); + var recorder = new FileAccessRecorder(); + File.Delete(stale); + recorder.OnDeleteFile(stale); + + var temporary = Write("out.tmp", "partial"); + recorder.OnWrite(temporary); + var final = Path.Combine(_root, "out.bin"); + File.Move(temporary, final); + recorder.OnDeleteFile(temporary); + recorder.OnWrite(final); + + var snapshot = recorder.Snapshot(); + Assert.Contains(snapshot.Probes, probe => probe.Path == stale && !probe.IsDirectory && !probe.Exists); + Assert.DoesNotContain(snapshot.Probes, probe => probe.Path == temporary); + Assert.Equal(new[] { (final, 7L) }, snapshot.Outputs); + } + + [Fact] + public void PublishedTreesAreOutputsAndBackupsAreNot() + { + var destination = Path.Combine(_root, "published"); + Directory.CreateDirectory(destination); + Write(Path.Combine("published", "old.txt"), "old"); + var recorder = new FileAccessRecorder(); + var staging = Path.Combine(_root, ".published.staging"); + recorder.OnCreateDirectory(staging); + Directory.CreateDirectory(staging); + Write(Path.Combine(".published.staging", "new.txt"), "new!"); + var backup = Path.Combine(_root, ".published.backup"); + Directory.Move(destination, backup); + recorder.OnMoveDirectory(destination, backup); + Directory.Move(staging, destination); + recorder.OnMoveDirectory(staging, destination); + Directory.Delete(backup, recursive: true); + recorder.OnDeleteDirectory(backup); + + var snapshot = recorder.Snapshot(); + Assert.Equal(new[] { (Path.Combine(destination, "new.txt"), 4L) }, snapshot.Outputs); + var tree = Assert.Single(snapshot.Scans); + Assert.Equal(destination, tree.Query.Directory); + Assert.Equal(new[] { "new.txt" }, tree.Entries); + Assert.DoesNotContain(snapshot.Probes, probe => probe.Path == destination); + } + + [Fact] + public void OutputListingsAreTakenWhenTheRunEnds() + { + var blobs = Path.Combine(_root, "blobs"); + Directory.CreateDirectory(blobs); + Write(Path.Combine("blobs", "stale.bin"), "x"); + var recorder = new FileAccessRecorder(); + recorder.OnOutputScan(new FileScanQuery(blobs, "*.bin", SearchOption.TopDirectoryOnly, FileScanKind.Files)); + File.Delete(Path.Combine(blobs, "stale.bin")); + Write(Path.Combine("blobs", "kept.bin"), "y"); + + var scan = Assert.Single(recorder.Snapshot().Scans); + Assert.Equal(new[] { "kept.bin" }, scan.Entries); + } + + [Fact] + public void UntrackedInputsAndEnvironmentExpansionsAreReported() + { + var recorder = new FileAccessRecorder(); + recorder.OnEnvironmentExpansion("plain/path", "plain/path"); + recorder.OnEnvironmentExpansion("%HOME%/x", "/home/user/x"); + recorder.OnUntrackedInput("a download of https://example.invalid/payload"); + var snapshot = recorder.Snapshot(); + Assert.Equal(new[] { ("%HOME%/x", "/home/user/x") }, snapshot.EnvironmentExpansions); + Assert.Single(snapshot.UntrackedInputs); + } + + [Theory] + [InlineData("utf8")] + [InlineData("utf8-bom")] + [InlineData("utf16le-bom")] + [InlineData("utf16be-bom")] + [InlineData("latin1")] + [InlineData("empty")] + public void RecordingModeDecodesTextExactlyLikeFile(string encoding) + { + const string text = "line one\r\nline two\nµ snowman ☃\rlast"; + byte[] bytes = encoding switch + { + "utf8" => Encoding.UTF8.GetBytes(text), + "utf8-bom" => [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes(text)], + "utf16le-bom" => [.. Encoding.Unicode.GetPreamble(), .. Encoding.Unicode.GetBytes(text)], + "utf16be-bom" => [.. Encoding.BigEndianUnicode.GetPreamble(), .. Encoding.BigEndianUnicode.GetBytes(text)], + "latin1" => Encoding.Latin1.GetBytes(text.Replace("☃", "?")), + _ => [], + }; + var path = Path.Combine(_root, $"{encoding}.txt"); + File.WriteAllBytes(path, bytes); + + Assert.Equal(File.ReadAllText(path), TrackedFs.DecodeText(bytes)); + Assert.Equal(File.ReadLines(path).ToArray(), TrackedFs.DecodeLines(bytes).ToArray()); + } + + private string Write(string relative, string content) + { + var path = Path.Combine(_root, relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, content); + return path; + } +} diff --git a/translator/tests/Translator.Tests/ListTranslationInputsTests.cs b/translator/tests/Translator.Tests/ListTranslationInputsTests.cs new file mode 100644 index 000000000..2112af253 --- /dev/null +++ b/translator/tests/Translator.Tests/ListTranslationInputsTests.cs @@ -0,0 +1,117 @@ +using Translator.Core.IO; + +namespace Translator.Tests; + +public sealed class ListTranslationInputsTests +{ + [Fact] + public void ListCoversEveryFileTheBaseTranslationOpensExceptTheDiscPins() + { + using var workspace = StepProvenanceWorkspace.Create(prepare: false); + // A serialized native index makes translation open it as well as the sources it digests. + workspace.RunChecked(["emit-native-index", "--project", workspace.Project, + "--native-source-dir", Path.Combine(workspace.Root, "runtime", "src"), + "--out", Path.Combine(workspace.Root, "runtime", "native-index.json")]); + var accessLog = Path.Combine(workspace.Root, "access-log.json"); + var translate = workspace.Run(workspace.TranslateBaseArguments(), + new Dictionary { [StepProvenance.AccessLogEnvironmentVariable] = accessLog }); + Assert.True(translate.ExitCode == 0, translate.Output + translate.Error); + var opened = StepProvenanceScenarios.ReadRecord(accessLog).Inputs.Select(static input => input.Path).ToArray(); + + var listed = ListInputs(workspace); + + string[] discPins = [workspace.Dol, workspace.Rel]; + Assert.All(discPins, pin => Assert.Contains(pin, opened)); + var uncovered = opened.Where(path => !discPins.Contains(path) && !listed.Contains(path)).ToArray(); + Assert.True(uncovered.Length == 0, + "translate-recursive opened files list-translation-inputs does not report:" + + Environment.NewLine + string.Join(Environment.NewLine, uncovered)); + Assert.DoesNotContain(workspace.Dol, listed); + Assert.DoesNotContain(workspace.Rel, listed); + // The project graph itself: manifest, function map, the profile's Code.pul, the runtime + // index, the native sources and the guest address map. + foreach (var expected in new[] + { + workspace.Project, + Path.Combine(workspace.Root, "MAP.txt"), + Path.Combine(workspace.Root, "Code.pul"), + Path.Combine(workspace.Root, "runtime", "native-index.json"), + Path.Combine(workspace.Root, "runtime", "src", "hle", "stub.cpp"), + Path.Combine(workspace.Root, "runtime", "include", "guest_abi", "guest_versions.inc"), + }) + { + Assert.Contains(expected, listed); + Assert.Contains(expected, opened); + } + } + + [Fact] + public void ListNeedsNoDiscPinsAndFollowsTheOutputContract() + { + using var workspace = StepProvenanceWorkspace.Create(prepare: false); + var withPins = ListInputs(workspace); + File.Delete(workspace.Dol); + File.Delete(workspace.Rel); + + var run = workspace.Run(["list-translation-inputs", "--project", workspace.Project]); + + Assert.Equal(0, run.ExitCode); + Assert.Equal(string.Empty, run.Error); + var lines = run.Output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(static line => line.TrimEnd('\r')).ToArray(); + Assert.Equal(withPins, lines); + Assert.Equal(lines.Order(StringComparer.Ordinal), lines); + Assert.Equal(lines.Length, lines.Distinct(StringComparer.Ordinal).Count()); + Assert.All(lines, line => + { + Assert.True(Path.IsPathFullyQualified(line), line); + Assert.Equal(Path.GetFullPath(line), line); + Assert.True(File.Exists(line), line); + }); + } + + [Fact] + public void RegionalProjectListsItsPortMetadataWithoutGameFiles() + { + var repository = ProjectPathsForTests.FindRepositoryRoot(); + var project = Path.Combine(repository, "projects", "mkwii-ntsc-u", "recomp.yml"); + var run = CliRun.Invoke(repository, ["list-translation-inputs", "--project", project]); + Assert.True(run.ExitCode == 0, run.Error); + var lines = run.Output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(static line => line.TrimEnd('\r')).ToArray(); + foreach (var name in new[] { "recomp.yml", "MAP.txt", "region_port.json", "data_addresses.txt" }) + Assert.Contains(Path.Combine(repository, "projects", "mkwii-ntsc-u", name), lines); + Assert.Contains(Path.Combine(repository, "runtime", "include", "guest_abi", "guest_versions.inc"), lines); + Assert.Contains(lines, line => line.StartsWith(Path.Combine(repository, "runtime", "src") + Path.DirectorySeparatorChar, StringComparison.Ordinal)); + Assert.DoesNotContain(lines, line => line.EndsWith("main.dol", StringComparison.OrdinalIgnoreCase) || + line.EndsWith("StaticR.rel", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public void ListFailsWithoutAUsableProject() + { + using var workspace = StepProvenanceWorkspace.Create(prepare: false); + var missing = workspace.Run(["list-translation-inputs", "--project", Path.Combine(workspace.Root, "absent.yml")]); + Assert.NotEqual(0, missing.ExitCode); + Assert.Equal(string.Empty, missing.Output); + + var noProject = workspace.Run(["list-translation-inputs"]); + Assert.NotEqual(0, noProject.ExitCode); + Assert.Equal(string.Empty, noProject.Output); + + File.WriteAllText(workspace.Project, "schema_version: 2\n"); + var unsupported = workspace.Run(["list-translation-inputs", "--project", workspace.Project]); + Assert.NotEqual(0, unsupported.ExitCode); + Assert.Equal(string.Empty, unsupported.Output); + + File.WriteAllText(workspace.Project, "schema_version: [1\n bad: yaml"); + var unreadable = workspace.Run(["list-translation-inputs", "--project", workspace.Project]); + Assert.NotEqual(0, unreadable.ExitCode); + Assert.Equal(string.Empty, unreadable.Output); + } + + private static string[] ListInputs(StepProvenanceWorkspace workspace) + { + var run = workspace.Run(["list-translation-inputs", "--project", workspace.Project]); + Assert.True(run.ExitCode == 0, run.Error); + return run.Output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(static line => line.TrimEnd('\r')).ToArray(); + } +} diff --git a/translator/tests/Translator.Tests/StepProvenanceFacadeCoverageTests.cs b/translator/tests/Translator.Tests/StepProvenanceFacadeCoverageTests.cs new file mode 100644 index 000000000..2c06625e4 --- /dev/null +++ b/translator/tests/Translator.Tests/StepProvenanceFacadeCoverageTests.cs @@ -0,0 +1,255 @@ +using System.Security.Cryptography; +using Translator.Core.IO; + +namespace Translator.Tests; + +/// +/// Proves the gate sees every file a step depends on, without trusting the facade's own record +/// of what was read: every file in the workspace is mutated (appended to, then deleted) one at a +/// time, and whenever the gate would still have skipped, the step is re-run for real and must +/// behave exactly as it did before. A read that bypassed the tracking facade shows up as a file +/// whose mutation changes the step while the gate stays "current". +/// +internal static class FacadeCoverage +{ + private static readonly string[] Mutations = ["append", "delete"]; + + public static void AssertGateCoversEveryDependency(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + var record = StepProvenanceScenarios.ReadRecord(workspace.RecordPath(step)); + Assert.Null(StepProvenance.CheckFileSystem(record)); + + var pristine = workspace.Root + ".pristine"; + CopyDirectory(workspace.Root, pristine); + try + { + void Restore() + { + Directory.Delete(workspace.Root, recursive: true); + CopyDirectory(pristine, workspace.Root); + } + + (int ExitCode, Dictionary Tree) Behaviour(string? excluded) + { + var run = workspace.RunStep(step, gated: false); + return (run.ExitCode, Tree(workspace, excluded)); + } + + Restore(); + var baseline = Behaviour(null); + Assert.Equal(0, baseline.ExitCode); + Restore(); + var repeat = Behaviour(null); + Assert.True(SameBehaviour(baseline, repeat, null), $"{step} is not deterministic, so this test cannot judge it"); + + var files = Directory.EnumerateFiles(pristine, "*", SearchOption.AllDirectories) + .Select(path => Path.Combine(workspace.Root, Path.GetRelativePath(pristine, path))) + .Where(path => !path.StartsWith(workspace.ProvenanceDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + .Order(StringComparer.Ordinal) + .ToArray(); + var inputs = record.Inputs.Select(static input => input.Path).ToHashSet(StringComparer.OrdinalIgnoreCase); + Assert.NotEmpty(files); + + var violations = new List(); + var behaviourChanges = 0; + var gateMisses = 0; + foreach (var file in files) + { + foreach (var mutation in Mutations) + { + Restore(); + if (mutation == "append") File.AppendAllText(file, "\n// mutated\n"); + else File.Delete(file); + + var miss = StepProvenance.CheckFileSystem(record); + if (inputs.Contains(file)) + Assert.True(miss is not null, $"{mutation} of recorded input {file} did not invalidate {step}"); + if (miss is not null) + { + gateMisses++; + continue; + } + + // The gate would have skipped: the step must therefore be unaffected. + var mutated = Behaviour(file); + if (!SameBehaviour(baseline, mutated, file)) + { + behaviourChanges++; + violations.Add($"{mutation} {Path.GetRelativePath(workspace.Root, file)} changed {step} but the gate still skipped it"); + } + } + } + + Assert.True(violations.Count == 0, string.Join(Environment.NewLine, violations)); + Assert.Equal(0, behaviourChanges); + Assert.True(gateMisses >= inputs.Count, "every recorded input invalidates the gate"); + } + finally + { + if (Directory.Exists(pristine)) Directory.Delete(pristine, recursive: true); + } + } + + /// Content hash of every file in the workspace after a run, apart from the provenance records and the mutated file. + private static Dictionary Tree(StepProvenanceWorkspace workspace, string? excluded) => + Directory.EnumerateFiles(workspace.Root, "*", SearchOption.AllDirectories) + .Where(path => !path.StartsWith(workspace.ProvenanceDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + .Where(path => excluded is null || !string.Equals(path, excluded, StringComparison.OrdinalIgnoreCase)) + .ToDictionary( + path => Path.GetRelativePath(workspace.Root, path), + static path => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))), + StringComparer.OrdinalIgnoreCase); + + private static bool SameBehaviour( + (int ExitCode, Dictionary Tree) expected, + (int ExitCode, Dictionary Tree) actual, + string? excluded) + { + if (expected.ExitCode != actual.ExitCode) return false; + var expectedTree = expected.Tree.Where(pair => excluded is null || + !excluded.EndsWith(Path.DirectorySeparatorChar + pair.Key, StringComparison.OrdinalIgnoreCase)); + return expectedTree.Count() == actual.Tree.Count && + expectedTree.All(pair => actual.Tree.TryGetValue(pair.Key, out var hash) && hash == pair.Value); + } + + private static void CopyDirectory(string source, string destination) + { + Directory.CreateDirectory(destination); + foreach (var directory in Directory.EnumerateDirectories(source, "*", SearchOption.AllDirectories)) + Directory.CreateDirectory(Path.Combine(destination, Path.GetRelativePath(source, directory))); + foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { + var target = Path.Combine(destination, Path.GetRelativePath(source, file)); + File.Copy(file, target, overwrite: true); + File.SetLastWriteTimeUtc(target, File.GetLastWriteTimeUtc(file)); + } + } +} + +public sealed class TranslateModFacadeCoverageTests +{ + [Fact] + public void GateCoversEveryFileTranslateModDependsOn() => + FacadeCoverage.AssertGateCoversEveryDependency(StepProvenanceWorkspace.TranslateMod); +} + +public sealed class GenerateDataInitFacadeCoverageTests +{ + [Fact] + public void GateCoversEveryFileGenerateDataInitDependsOn() => + FacadeCoverage.AssertGateCoversEveryDependency(StepProvenanceWorkspace.GenerateDataInit); +} + +public sealed class EmitBuildShardsFacadeCoverageTests +{ + [Fact] + public void GateCoversEveryFileEmitBuildShardsDependsOn() => + FacadeCoverage.AssertGateCoversEveryDependency(StepProvenanceWorkspace.EmitBuildShards); +} + +/// +/// The static half of the guarantee: nothing in the translator touches the file system or the +/// environment except through (and the gate's own record handling). +/// +public sealed class TrackedFileSystemSourceTests +{ + private static readonly string[] Exempt = + [ + Path.Combine("Translator.Core", "IO", "TrackedFs.cs"), + Path.Combine("Translator.Core", "IO", "FileAccessRecorder.cs"), + Path.Combine("Translator.Core", "IO", "StepProvenance.cs"), + ]; + + private static readonly (string Pattern, string Why)[] Banned = + [ + (@"(?(); + var scanned = 0; + foreach (var path in Directory.EnumerateFiles(sourceRoot, "*.cs", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(sourceRoot, path); + var top = relative.Split(Path.DirectorySeparatorChar); + if (top.Length > 1 && (top[1] is "bin" or "obj")) continue; + if (Exempt.Contains(relative, StringComparer.OrdinalIgnoreCase)) continue; + scanned++; + var lines = File.ReadAllLines(path); + for (var index = 0; index < lines.Length; index++) + { + var code = StripCommentsAndStrings(lines[index]); + foreach (var (pattern, why) in Banned) + { + if (System.Text.RegularExpressions.Regex.IsMatch(code, pattern)) + offenders.Add($"{relative}:{index + 1}: {why}: {lines[index].Trim()}"); + } + } + } + + Assert.True(scanned > 50, $"only {scanned} sources scanned under {sourceRoot}"); + Assert.True(offenders.Count == 0, + "Route these through Translator.Core.IO.TrackedFs so --provenance-file sees them:" + + Environment.NewLine + string.Join(Environment.NewLine, offenders)); + } + + [Fact] + public void TheSourceScanCatchesDirectAccess() + { + string[] samples = + [ + "var text = File.ReadAllText(path);", + "foreach (var f in System.IO.Directory.EnumerateFiles(root)) { }", + "var length = new FileInfo(path).Length;", + "using var stream = new FileStream(path, FileMode.Open);", + "var home = Environment.GetEnvironmentVariable(\"HOME\");", + ]; + foreach (var sample in samples) + { + var code = StripCommentsAndStrings(sample); + Assert.Contains(Banned, banned => System.Text.RegularExpressions.Regex.IsMatch(code, banned.Pattern)); + } + Assert.DoesNotContain(Banned, banned => System.Text.RegularExpressions.Regex.IsMatch( + StripCommentsAndStrings("TrackedFs.ReadAllText(path); // File.ReadAllText is banned"), banned.Pattern)); + Assert.DoesNotContain(Banned, banned => System.Text.RegularExpressions.Regex.IsMatch( + StripCommentsAndStrings("throw new InvalidDataException(\"File.Exists failed\"); var x = entry.File.Length;"), banned.Pattern)); + } + + /// Drops string/char literals and // comments from one line; good enough for a ban list. + private static string StripCommentsAndStrings(string line) + { + var result = new System.Text.StringBuilder(line.Length); + for (var index = 0; index < line.Length; index++) + { + var character = line[index]; + if (character == '/' && index + 1 < line.Length && line[index + 1] == '/') break; + if (character == '"' || character == '\'') + { + var verbatim = character == '"' && index > 0 && line[index - 1] == '@'; + index++; + while (index < line.Length && line[index] != character) + { + if (!verbatim && line[index] == '\\') index++; + index++; + } + result.Append(' '); + continue; + } + result.Append(character); + } + return result.ToString(); + } +} diff --git a/translator/tests/Translator.Tests/StepProvenanceGateTests.cs b/translator/tests/Translator.Tests/StepProvenanceGateTests.cs new file mode 100644 index 000000000..29f81b4a6 --- /dev/null +++ b/translator/tests/Translator.Tests/StepProvenanceGateTests.cs @@ -0,0 +1,338 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Translator.Core.IO; + +namespace Translator.Tests; + +/// +/// The opt-in --provenance-file skip gate of translate-mod, generate-data-init and +/// emit-build-shards, driven through real translator processes like the build scripts drive it. +/// Split over several classes only so xunit runs them in parallel. +/// +internal static class StepProvenanceScenarios +{ + public static TheoryData Steps => new() + { + StepProvenanceWorkspace.TranslateMod, + StepProvenanceWorkspace.GenerateDataInit, + StepProvenanceWorkspace.EmitBuildShards + }; + + /// One output each step always writes. + public static string KnownOutput(StepProvenanceWorkspace workspace, string step) => step switch + { + StepProvenanceWorkspace.TranslateMod => Path.Combine(workspace.ModOutput, "cpp", "mod_data_patches.cpp"), + StepProvenanceWorkspace.GenerateDataInit => Path.Combine(workspace.Root, "generated", "data_sections_init.cpp"), + StepProvenanceWorkspace.EmitBuildShards => Path.Combine(workspace.Root, "generated", "build_shards", "shards.cmake"), + _ => throw new ArgumentOutOfRangeException(nameof(step)) + }; + + /// Runs the gated step, which must actually execute (not skip) and leave a record. + public static StepProvenanceRecord RunAndRecord(StepProvenanceWorkspace workspace, string step) + { + var run = workspace.RunChecked(workspace.StepArguments(step)); + Assert.False(run.Skipped(step), $"{step} skipped unexpectedly:\n{run.Output}\n{run.Error}"); + AssertNoTemporaries(workspace); + return ReadRecord(workspace.RecordPath(step)); + } + + public static void AssertSkips(StepProvenanceWorkspace workspace, string step) + { + var run = workspace.RunChecked(workspace.StepArguments(step)); + Assert.True(run.Skipped(step), $"{step} did not skip:\n{run.Output}\n{run.Error}"); + } + + public static void AssertReruns(StepProvenanceWorkspace workspace, string step, string because) + { + var run = workspace.RunChecked(workspace.StepArguments(step)); + Assert.False(run.Skipped(step), $"{step} skipped although {because}:\n{run.Output}"); + Assert.Contains($"[translator] {step} must run:", run.Error, StringComparison.Ordinal); + Assert.True(File.Exists(workspace.RecordPath(step)), "a successful rerun writes a fresh record"); + AssertNoTemporaries(workspace); + // The fresh record describes the new state, so the next identical run is current again. + AssertSkips(workspace, step); + } + + public static StepProvenanceRecord ReadRecord(string path) + { + var record = StepProvenance.TryRead(path, out var reason); + Assert.True(record is not null, reason); + return record!; + } + + public static void AssertNoTemporaries(StepProvenanceWorkspace workspace) + { + if (!Directory.Exists(workspace.ProvenanceDirectory)) return; + Assert.Empty(Directory.EnumerateFiles(workspace.ProvenanceDirectory, "*.tmp")); + } +} + +public sealed class StepProvenanceGateTests +{ + public static TheoryData Steps => StepProvenanceScenarios.Steps; + + [Theory] + [MemberData(nameof(Steps))] + public void SecondIdenticalRunSkipsWithoutTouchingOutputs(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + var unrecorded = StepProvenanceWorkspace.Capture(Directory.EnumerateFiles(workspace.Root, "*", SearchOption.AllDirectories)); + var record = StepProvenanceScenarios.RunAndRecord(workspace, step); + // Recording must not change a single byte the step produces. + var recorded = StepProvenanceWorkspace.Capture(Directory.EnumerateFiles(workspace.Root, "*", SearchOption.AllDirectories) + .Where(path => !path.StartsWith(workspace.ProvenanceDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))); + Assert.Equal(unrecorded.Keys.Order(StringComparer.OrdinalIgnoreCase), recorded.Keys.Order(StringComparer.OrdinalIgnoreCase)); + foreach (var (path, (bytes, _)) in unrecorded) Assert.Equal(bytes, recorded[path].Bytes); + Assert.Equal(StepProvenance.SchemaVersion, record.SchemaVersion); + Assert.Equal(step, record.Step); + Assert.NotNull(record.TranslatorIdentity); + Assert.NotEmpty(record.Inputs); + Assert.NotEmpty(record.Outputs); + Assert.Contains(record.Inputs, input => input.Path == workspace.Project); + Assert.Contains(record.Outputs, output => output.Path == StepProvenanceScenarios.KnownOutput(workspace, step)); + Assert.Equal(workspace.StepArguments(step), record.Arguments); + var recordBytes = File.ReadAllBytes(workspace.RecordPath(step)); + var outputs = StepProvenanceWorkspace.Capture(record.Outputs.Select(static output => output.Path)); + Assert.Equal(record.Outputs.Count, outputs.Count); + + var second = workspace.RunChecked(workspace.StepArguments(step)); + + Assert.Equal($"MKWCBUILD: {step} is current; skipping", second.Output.Trim()); + Assert.Equal(recordBytes, File.ReadAllBytes(workspace.RecordPath(step))); + var after = StepProvenanceWorkspace.Capture(outputs.Keys); + foreach (var (path, (bytes, modified)) in outputs) + { + Assert.Equal(bytes, after[path].Bytes); + Assert.Equal(modified, after[path].Modified); + } + } + + [Theory] + [MemberData(nameof(Steps))] + public void MissingProvenanceReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + File.Delete(workspace.RecordPath(step)); + StepProvenanceScenarios.AssertReruns(workspace, step, "there was no record"); + } + + [Theory] + [MemberData(nameof(Steps))] + public void CorruptOrForeignProvenanceReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + var recordPath = workspace.RecordPath(step); + var valid = File.ReadAllText(recordPath); + string Edit(Action change) + { + var node = JsonNode.Parse(valid)!.AsObject(); + change(node); + return node.ToJsonString(); + } + + var corruptions = new[] + { + "{ this is not json", + "", + valid[..(valid.Length / 2)], + Edit(static node => node["SchemaVersion"] = 0), + Edit(static node => node["SchemaVersion"] = StepProvenance.SchemaVersion + 1), + Edit(static node => node.Remove("SchemaVersion")), + Edit(static node => node["UnknownField"] = true), + Edit(static node => node["Step"] = "some-other-step"), + Edit(static node => node["TranslatorIdentity"] = new string('0', 64)), + Edit(static node => node["TranslatorIdentity"] = null), + Edit(static node => node["WorkingDirectory"] = Path.GetTempPath()), + }; + foreach (var corruption in corruptions) + { + File.WriteAllText(recordPath, corruption); + StepProvenanceScenarios.AssertReruns(workspace, step, $"the record was '{corruption[..Math.Min(40, corruption.Length)]}'"); + } + } + + [Fact] + public void ChangedArgumentsRerun() + { + using var workspace = StepProvenanceWorkspace.Create(); + const string step = StepProvenanceWorkspace.TranslateMod; + StepProvenanceScenarios.RunAndRecord(workspace, step); + var run = workspace.RunChecked(workspace.StepArguments(step, threads: "2")); + Assert.False(run.Skipped(step), run.Output); + Assert.Equal(2, StepProvenanceScenarios.ReadRecord(workspace.RecordPath(step)).EffectiveThreads); + Assert.True(workspace.RunChecked(workspace.StepArguments(step, threads: "2")).Skipped(step)); + Assert.False(workspace.RunChecked(workspace.StepArguments(step, threads: "1")).Skipped(step)); + } +} + +public sealed class StepProvenanceInvalidationTests +{ + public static TheoryData Steps => StepProvenanceScenarios.Steps; + + [Theory] + [MemberData(nameof(Steps))] + public void ModifiedInputReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + var input = step switch + { + StepProvenanceWorkspace.TranslateMod => Path.Combine(workspace.Root, "base.json"), + StepProvenanceWorkspace.GenerateDataInit => Path.Combine(workspace.Root, "MAP.txt"), + _ => Path.Combine(workspace.Root, "runtime", "src", "hle", "stub.cpp"), + }; + File.AppendAllText(input, "\n"); + StepProvenanceScenarios.AssertReruns(workspace, step, $"{input} changed"); + + // The project file is an input of every step. + File.AppendAllText(workspace.Project, "# edited\n"); + StepProvenanceScenarios.AssertReruns(workspace, step, "the project file changed"); + } + + [Theory] + [MemberData(nameof(Steps))] + public void NewFileInAScannedDirectoryReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + var record = StepProvenanceScenarios.RunAndRecord(workspace, step); + var added = step == StepProvenanceWorkspace.GenerateDataInit + ? Path.Combine(workspace.Root, "generated", "data_sections_init_blobs", "added.bin") + : Path.Combine(workspace.Root, "runtime", "src", "hle", "added.cpp"); + Assert.Contains(record.Scans, scan => scan.Directory == Path.GetDirectoryName(added) || + (scan.Recursive && added.StartsWith(scan.Directory + Path.DirectorySeparatorChar))); + File.WriteAllText(added, "// added after the record\n"); + StepProvenanceScenarios.AssertReruns(workspace, step, $"{added} was added"); + if (step == StepProvenanceWorkspace.GenerateDataInit) + Assert.False(File.Exists(added), "the rerun prunes the stale blob it was invalidated by"); + } + + [Theory] + [MemberData(nameof(Steps))] + public void DeletedOutputReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + var output = StepProvenanceScenarios.KnownOutput(workspace, step); + var bytes = File.ReadAllBytes(output); + File.Delete(output); + StepProvenanceScenarios.AssertReruns(workspace, step, $"{output} was deleted"); + Assert.Equal(bytes, File.ReadAllBytes(output)); + } + + [Theory] + [MemberData(nameof(Steps))] + public void ResizedOrTruncatedOutputReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + var output = StepProvenanceScenarios.KnownOutput(workspace, step); + var bytes = File.ReadAllBytes(output); + + File.WriteAllBytes(output, bytes[..(bytes.Length / 2)]); + StepProvenanceScenarios.AssertReruns(workspace, step, $"{output} was truncated"); + Assert.Equal(bytes, File.ReadAllBytes(output)); + + File.WriteAllBytes(output, [.. bytes, (byte)'\n']); + StepProvenanceScenarios.AssertReruns(workspace, step, $"{output} grew"); + Assert.Equal(bytes, File.ReadAllBytes(output)); + } + + [Theory] + [MemberData(nameof(Steps))] + public void SameSizeEditedOutputReruns(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + var output = StepProvenanceScenarios.KnownOutput(workspace, step); + var bytes = File.ReadAllBytes(output); + + var edited = bytes.ToArray(); + edited[0] ^= 0x20; + File.WriteAllBytes(output, edited); + File.SetLastWriteTimeUtc(output, File.GetLastWriteTimeUtc(output).AddMinutes(1)); + StepProvenanceScenarios.AssertReruns(workspace, step, $"{output} was edited in place"); + Assert.Equal(bytes, File.ReadAllBytes(output)); + } +} + +public sealed class StepProvenanceSafetyTests +{ + public static TheoryData Steps => StepProvenanceScenarios.Steps; + + [Theory] + [MemberData(nameof(Steps))] + public void FailureMidStepLeavesNoProvenance(string step) + { + using var workspace = StepProvenanceWorkspace.Create(); + StepProvenanceScenarios.RunAndRecord(workspace, step); + Assert.True(File.Exists(workspace.RecordPath(step))); + + // Each break lets the step start (project load succeeds) and fail part-way through. + switch (step) + { + case StepProvenanceWorkspace.TranslateMod: + File.WriteAllText(Path.Combine(workspace.Root, "base.json"), "{ truncated"); + break; + case StepProvenanceWorkspace.GenerateDataInit: + File.WriteAllBytes(workspace.Dol, [0x00, 0x01, 0x02]); + break; + default: + File.WriteAllBytes(Path.Combine(workspace.Root, "generated", "base_translation_sources.bin"), [0x42, 0x42, 0x42, 0x42]); + break; + } + + var failed = workspace.RunStep(step); + + Assert.NotEqual(0, failed.ExitCode); + Assert.False(failed.Skipped(step)); + Assert.False(File.Exists(workspace.RecordPath(step)), "a failed step must not leave a record behind"); + StepProvenanceScenarios.AssertNoTemporaries(workspace); + // And it stays that way: the next attempt runs (and fails) again rather than skipping. + var again = workspace.RunStep(step); + Assert.NotEqual(0, again.ExitCode); + Assert.False(again.Skipped(step)); + Assert.False(File.Exists(workspace.RecordPath(step))); + } + + [Fact] + public void ARecordIsDeletedBeforeTheStepRuns() + { + using var workspace = StepProvenanceWorkspace.Create(); + const string step = StepProvenanceWorkspace.GenerateDataInit; + StepProvenanceScenarios.RunAndRecord(workspace, step); + // A stale record that no longer matches is gone even when the step dies before finishing. + File.AppendAllText(Path.Combine(workspace.Root, "MAP.txt"), "\n"); + File.WriteAllBytes(workspace.Dol, [0x00]); + var run = workspace.RunStep(step); + Assert.NotEqual(0, run.ExitCode); + Assert.Contains($"[translator] {step} must run:", run.Error, StringComparison.Ordinal); + Assert.False(File.Exists(workspace.RecordPath(step))); + } + + [Theory] + [MemberData(nameof(Steps))] + public void WithoutTheFlagNothingIsRecordedOrSkipped(string step) + { + // Create() already ran every step once without the flag. + using var workspace = StepProvenanceWorkspace.Create(); + Assert.False(Directory.Exists(workspace.ProvenanceDirectory)); + var run = workspace.RunChecked(workspace.StepArguments(step, gated: false)); + Assert.DoesNotContain("MKWCBUILD", run.Output, StringComparison.Ordinal); + Assert.DoesNotContain("must run", run.Error, StringComparison.Ordinal); + Assert.False(Directory.Exists(workspace.ProvenanceDirectory)); + } + + [Fact] + public void ProvenanceFlagIsOnlyAcceptedByTheGatedSteps() + { + using var workspace = StepProvenanceWorkspace.Create(prepare: false); + var run = workspace.Run(["emit-base-manifest", "--project", workspace.Project, "--provenance-file", workspace.RecordPath("x")]); + Assert.Equal(2, run.ExitCode); + Assert.Contains("Unrecognized option '--provenance-file'", run.Error, StringComparison.Ordinal); + var empty = workspace.Run(["generate-data-init", "--project", workspace.Project, "--provenance-file", " "]); + Assert.NotEqual(0, empty.ExitCode); + Assert.False(Directory.Exists(workspace.ProvenanceDirectory)); + } +} diff --git a/translator/tests/Translator.Tests/StepProvenanceWorkspace.cs b/translator/tests/Translator.Tests/StepProvenanceWorkspace.cs new file mode 100644 index 000000000..3cd0a0107 --- /dev/null +++ b/translator/tests/Translator.Tests/StepProvenanceWorkspace.cs @@ -0,0 +1,255 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.Text.Json; +using Translator.Cli.Configuration; +using Translator.Core.Mods; +using Translator.Core.Parsing.Kamek; + +namespace Translator.Tests; + +/// +/// A throwaway workspace laid out like the real one (project, pinned DOL/REL, function map, +/// runtime sources, a mod pack, a base translation) that runs the same translator steps the +/// local build scripts run, each in its own translator process. +/// +internal sealed class StepProvenanceWorkspace : IDisposable +{ + public const string TranslateMod = "translate-mod"; + public const string GenerateDataInit = "generate-data-init"; + public const string EmitBuildShards = "emit-build-shards"; + + private const uint Caller = 0x80004000; + private const uint Module = 0x80010000; + + private StepProvenanceWorkspace(string root) => Root = root; + + public string Root { get; } + public string Project => Path.Combine(Root, "recomp.yml"); + public string Dol => Path.Combine(Root, "main.dol"); + public string Rel => Path.Combine(Root, "empty.rel"); + public string ProvenanceDirectory => Path.Combine(Root, "generated", "step-provenance"); + public string ModOutput => Path.Combine(Root, "build", "mods", "mod_cpp"); + + public string RecordPath(string step) => Path.Combine(ProvenanceDirectory, step + ".json"); + + /// A fresh workspace; with the base is translated and every gated step has run once, ungated. + public static StepProvenanceWorkspace Create(bool prepare = true) + { + var workspace = new StepProvenanceWorkspace( + Path.Combine(Path.GetTempPath(), $"translator-provenance-{Guid.NewGuid():N}")); + try + { + workspace.WriteSources(); + if (prepare) + { + workspace.RunChecked(workspace.TranslateBaseArguments()); + foreach (var step in new[] { TranslateMod, GenerateDataInit, EmitBuildShards }) + workspace.RunChecked(workspace.StepArguments(step, gated: false)); + } + return workspace; + } + catch + { + workspace.Dispose(); + throw; + } + } + + public void Dispose() + { + if (Directory.Exists(Root)) Directory.Delete(Root, recursive: true); + } + + public string[] TranslateBaseArguments() => + [ + "translate-recursive", $"0x{Caller:X8}", "--project", Project, + "--outdir", Path.Combine(Root, "generated", "functions"), + "--output-metadata", Path.Combine(Root, "generated", "base_translation_output.json"), + "--production-source-bundle", Path.Combine(Root, "generated", "base_translation_sources.bin"), + "--no-function-files", "--prune-stale", "--threads", "1" + ]; + + /// The step exactly as Launcher/local-build.sh runs it, plus --provenance-file when gated. + public string[] StepArguments(string step, bool gated = true, string threads = "1") + { + var arguments = step switch + { + TranslateMod => new List + { + "translate-mod", "--project", Project, "--profile", "mod", + "--base-manifest", Path.Combine(Root, "base.json"), + "--base-translation-output-metadata", Path.Combine(Root, "generated", "base_translation_output.json"), + "--code-pul", Path.Combine(Root, "Code.pul"), "--mod-root", Path.Combine(Root, "mod"), + "--mod-name", "Provenance Test", "--region", "P", "--out", ModOutput, + "--prefer-cached-inputs", "--emit-cpp", "--threads", threads, "--skip-retro-wfc" + }, + GenerateDataInit => new List { "generate-data-init", "--project", Project }, + EmitBuildShards => new List + { + "emit-build-shards", "--project", Project, + "--base-metadata", Path.Combine(Root, "generated", "base_translation_output.json"), + "--base-functions-dir", Path.Combine(Root, "generated", "functions"), + "--native-source-dir", Path.Combine(Root, "runtime", "src"), + "--out", Path.Combine(Root, "generated", "build_shards"), + "--resolved-profile", Path.Combine(ModOutput, "resolved_dispatch_profile.json"), + "--retro-cpp-dir", Path.Combine(ModOutput, "cpp") + }, + _ => throw new ArgumentOutOfRangeException(nameof(step), step, null) + }; + if (gated) + { + arguments.Add("--provenance-file"); + arguments.Add(RecordPath(step)); + } + return arguments.ToArray(); + } + + public CliRun RunStep(string step, bool gated = true) => Run(StepArguments(step, gated)); + + public CliRun RunChecked(string[] arguments) + { + var run = Run(arguments); + Assert.True(run.ExitCode == 0, $"{string.Join(' ', arguments)} failed ({run.ExitCode}):\n{run.Output}\n{run.Error}"); + return run; + } + + public CliRun Run(string[] arguments, IReadOnlyDictionary? environment = null) => + CliRun.Invoke(Root, arguments, environment); + + /// Every file the step's last run left behind, by path, with its bytes and modification time. + public static Dictionary Capture(IEnumerable paths) => + paths.Where(File.Exists).ToDictionary( + static path => path, + static path => (File.ReadAllBytes(path), File.GetLastWriteTimeUtc(path)), + StringComparer.OrdinalIgnoreCase); + + private void WriteSources() + { + Directory.CreateDirectory(Root); + // Caller + 24 holds a real instruction so the hook's continuation has somewhere to resume. + uint[] caller = [0x60000000u, 0x38630001u, 0x38630001u, 0x38630001u, + 0x38630001u, 0x38630001u, 0x38630002u, 0x4E800020u]; + var baseWords = Enumerable.Repeat(0x4E800020u, 8).ToArray(); + caller.CopyTo(baseWords, 0); + var baseBytes = Words(baseWords); + File.WriteAllBytes(Dol, SyntheticDolFactory.CreateBytes( + Caller, + sections: + [ + SyntheticDolFactory.Text(0, Caller, baseWords), + SyntheticDolFactory.Data(1, 0x80006000, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88) + ])); + File.WriteAllBytes(Path.Combine(Root, "base.bin"), baseBytes); + // translate-mod needs a REL; this one has no code and no relocations. + File.WriteAllBytes(Rel, new byte[0x48]); + File.WriteAllText(Path.Combine(Root, "MAP.txt"), $"{Caller:X8} caller\n"); + + var manifest = new BaseManifest("synthetic", 1, "TEST01", "P", "", 0, + [new BaseSectionMetadata(".text", "main.dol", Caller, Caller + (uint)baseBytes.Length, true, false, "base.bin", 0)], + [new BaseFunctionRangeMetadata(Caller, Caller + 32, "caller", ".text", 0, "synthetic", ["Executable"])], + "ranges.json"); + File.WriteAllText(Path.Combine(Root, "base.json"), JsonSerializer.Serialize(manifest)); + + Directory.CreateDirectory(Path.Combine(Root, "runtime", "src", "hle")); + File.WriteAllText(Path.Combine(Root, "runtime", "src", "hle", "stub.cpp"), "// native sources the runtime scan reads\nint stub() { return 0; }\n"); + File.WriteAllText(Path.Combine(Root, "runtime", "src", "notes.txt"), "not a native source\n"); + Directory.CreateDirectory(Path.Combine(Root, "runtime", "include", "guest_abi")); + File.WriteAllText(Path.Combine(Root, "runtime", "include", "guest_abi", "guest_versions.inc"), + "// one regional range\nMKW_REGION_RANGE(NtscU, 80000000, 8001FFFF, +0x0)\n"); + Directory.CreateDirectory(Path.Combine(Root, "mod", "files")); + File.WriteAllText(Path.Combine(Root, "mod", "files", "readme.txt"), "pack contents\n"); + + // One blr-skipping hook at the caller, as KamekLrContinuationIntegrationTests builds it. + var moduleWords = Enumerable.Repeat(0x4E800020u, 0x40 / 4 + 4).ToArray(); + new uint[] { 0x7D8802A6u, 0x398C0014u, 0x7D8803A6u, 0x4E800020u }.CopyTo(moduleWords, 0x40 / 4); + var commands = new uint[] { ((uint)KamekCommandId.BranchLink << 24) | 0x00FFFFFEu, Caller, 0x40u }; + var code = Words(moduleWords); + var commandBytes = Words(commands); + var pul = new byte[KamekChunk.HeaderSize + code.Length + commandBytes.Length]; + WriteWord(pul, 0, KamekChunk.Magic0); + WriteWord(pul, 4, KamekChunk.Magic1); + WriteWord(pul, 12, (uint)code.Length); + WriteWord(pul, 24, (uint)pul.Length); + code.CopyTo(pul, KamekChunk.HeaderSize); + commandBytes.CopyTo(pul, KamekChunk.HeaderSize + code.Length); + File.WriteAllBytes(Path.Combine(Root, "Code.pul"), pul); + + File.WriteAllText(Project, $""" + schema_version: 1 + project: + id: provenance-test + memory: + base: 0x80000000 + size: 0x00020000 + sda_base: 0x80002000 + sda2_base: 0x80003000 + inputs: + dol: + path: main.dol + rel: + path: empty.rel + load_address: 0x80008000 + translation: + entry_points: + - 0x{Caller:X8} + function_map: + path: MAP.txt + runtime: + native_registration_root: runtime/src + native_abi_directories: + - runtime/src/hle + output: + root: generated + profiles: + mod: + enabled: true + code_pul: Code.pul + mod_root: mod + region: P + module_guest_base: 0x{Module:X8} + module_link_base: 0x{Module:X8} + output: build/mods/mod_cpp + """); + } + + private static byte[] Words(uint[] words) + { + var bytes = new byte[words.Length * 4]; + for (var index = 0; index < words.Length; index++) WriteWord(bytes, index * 4, words[index]); + return bytes; + } + + private static void WriteWord(byte[] bytes, int offset, uint value) => + BinaryPrimitives.WriteUInt32BigEndian(bytes.AsSpan(offset, 4), value); +} + +internal sealed record CliRun(int ExitCode, string Output, string Error) +{ + public static CliRun Invoke(string workingDirectory, string[] arguments, IReadOnlyDictionary? environment = null) + { + var startInfo = new ProcessStartInfo("dotnet") + { + WorkingDirectory = workingDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + ArgumentList = { typeof(TranslationProjectConfig).Assembly.Location } + }; + foreach (var argument in arguments) startInfo.ArgumentList.Add(argument); + startInfo.Environment.Remove(Translator.Core.IO.StepProvenance.AccessLogEnvironmentVariable); + foreach (var (name, value) in environment ?? new Dictionary()) startInfo.Environment[name] = value; + + using var process = Process.Start(startInfo)!; + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(120_000)) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(); + throw new TimeoutException($"Translator subprocess timed out: {string.Join(' ', arguments)}"); + } + return new CliRun(process.ExitCode, output.GetAwaiter().GetResult(), error.GetAwaiter().GetResult()); + } + + public bool Skipped(string step) => + Output.Contains($"MKWCBUILD: {step} is current; skipping", StringComparison.Ordinal); +} From 865785441d88e556cea559b7a88ce43e9c69fa6c Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:31:15 +0100 Subject: [PATCH 2/4] address review comments --- .../ProductCurrency.cs | 31 +++++++- Launcher/WiiCompiled.Setup.Linux/Program.cs | 3 +- .../InstallerEngine.cs | 73 +++++++++++++++---- .../PayloadInventory.cs | 11 +++ .../ToolkitFingerprint.cs | 23 ++++-- Launcher/macos/extract-disc.command | 15 +++- .../Translator.Core/IO/FileAccessRecorder.cs | 13 ++-- .../FileAccessRecorderTests.cs | 14 ++++ 8 files changed, 148 insertions(+), 35 deletions(-) diff --git a/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs b/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs index 126a70478..f46351cd8 100644 --- a/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs +++ b/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs @@ -296,8 +296,30 @@ internal static class ProductCurrencyProbe private static readonly string[] CompanionFiles = ["dsp_coef.bin", "initial_pipeline_cache.db", "cacert.pem", "local-build.json"]; + // The mbed TLS path cannot reach any server without the CA bundle beside the executable. + private const string CaBundle = "cacert.pem"; + public static IEnumerable RequiredOutputs(ProductCurrencyOptions options) => - options.Products.Select(product => Path.Combine(product.Directory, product.Executable)); + options.Products.SelectMany(product => new[] + { + Path.GetFullPath(Path.Combine(product.Directory, product.Executable)), + Path.GetFullPath(Path.Combine(product.Directory, CaBundle)), + }); + + /// True when every product executable can still be run by its owner. + public static bool ExecutablesRunnable(ProductCurrencyOptions options) + { + if (!OperatingSystem.IsLinux()) return false; + try + { + return options.Products.All(product => + (File.GetUnixFileMode(Path.Combine(product.Directory, product.Executable)) & UnixFileMode.UserExecute) != 0); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return false; + } + } /// The current inputs, or null (with a reason) when they cannot all be pinned down. public static Dictionary? TryCollectInputs(ProductCurrencyOptions options, out string reason) @@ -330,7 +352,8 @@ public static IEnumerable RequiredOutputs(ProductCurrencyOptions options var required = new List(); string? ToolkitFile(string key, string? path) { - if (string.IsNullOrEmpty(path)) return null; + // The build resolves a relative tool from the workspace, not from setup's directory. + if (string.IsNullOrEmpty(path) || !Path.IsPathRooted(path)) return null; var resolved = RealPath(path); var relative = resolved is null || !File.Exists(resolved) ? null : ProductCurrency.RelativeInside(toolkitRoot, resolved); if (relative is null) return null; @@ -435,6 +458,7 @@ public static IEnumerable RequiredOutputs(ProductCurrencyOptions options foreach (var companion in CompanionFiles) { var path = Path.Combine(directory, companion); + if (!File.Exists(path) && companion == CaBundle) return null; if (File.Exists(path) && !AddOutput(outputs, path)) return null; } var bootstrap = Path.Combine(directory, "wii_bootstrap"); @@ -467,7 +491,8 @@ public static (long Size, string Sha256)? Observe(string path) var sha = Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant(); return (stream.Length, sha); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException + or NotSupportedException) { return null; } diff --git a/Launcher/WiiCompiled.Setup.Linux/Program.cs b/Launcher/WiiCompiled.Setup.Linux/Program.cs index 6ca4eacae..968740405 100644 --- a/Launcher/WiiCompiled.Setup.Linux/Program.cs +++ b/Launcher/WiiCompiled.Setup.Linux/Program.cs @@ -209,7 +209,8 @@ downloadFailure is HttpRequestException or TimeoutException reporter.Diagnostic($"Building: the installed products cannot be checked ({notTrackedReason})."); else if (!forceCleanBuild) productsCurrent = ProductCurrency.IsCurrent(JsonState.TryRead(ProvenancePath), - currentInputs, ProductCurrencyProbe.RequiredOutputs(currency), ProductCurrencyProbe.Observe); + currentInputs, ProductCurrencyProbe.RequiredOutputs(currency), ProductCurrencyProbe.Observe) && + ProductCurrencyProbe.ExecutablesRunnable(currency); } if (productsCurrent) diff --git a/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs b/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs index 2cc82d26e..2bbee9a6b 100644 --- a/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs +++ b/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs @@ -351,22 +351,31 @@ private async Task PublishToolkitAndReconcileProductsAsync(InstallContext instal var release = install.Release; var installDirectory = existing.Root; - GraftWorkspaceCaches(existing.WorkspaceDirectory, InstalledLayout.Workspace(staging), cancellationToken); + var stagedWorkspace = InstalledLayout.Workspace(staging); + try + { + GraftWorkspaceCaches(existing.WorkspaceDirectory, stagedWorkspace, cancellationToken); - var state = BuildInstallState(install.PreviousState, installDirectory, manifest, release, - compileInputs: null, install.CanonicalRetroRoot, install.Options.RetroWfcPayloadMode); - PrepareMetadata(staging, manifest, state); + var state = BuildInstallState(install.PreviousState, installDirectory, manifest, release, + compileInputs: null, install.CanonicalRetroRoot, install.Options.RetroWfcPayloadMode); + PrepareMetadata(staging, manifest, state); - cancellationToken.ThrowIfCancellationRequested(); - var entries = new List(); + cancellationToken.ThrowIfCancellationRequested(); + var entries = new List(); - AddToolkitEntries(entries, toolkitRefresh, staging, installDirectory); - AddComponent(entries, staging, installDirectory, InstalledLayout.WorkspaceDirectoryName); - if (publishGameAssets) AddComponent(entries, staging, installDirectory, "GameAssets"); + AddToolkitEntries(entries, toolkitRefresh, staging, installDirectory); + AddComponent(entries, staging, installDirectory, InstalledLayout.WorkspaceDirectoryName); + if (publishGameAssets) AddComponent(entries, staging, installDirectory, "GameAssets"); - Publish(staging, installDirectory, install.CanonicalRetroRoot, state, - entries, cancellationToken, progressPercent: 8, completionPercent: 10, - createShortcuts: install.FirstInstall); + Publish(staging, installDirectory, install.CanonicalRetroRoot, state, + entries, cancellationToken, progressPercent: 8, completionPercent: 10, + createShortcuts: install.FirstInstall); + } + catch + { + RestoreWorkspaceCaches(existing.WorkspaceDirectory, stagedWorkspace); + throw; + } var verified = EnsurePublishedToolkitIntact(install, cancellationToken); @@ -399,6 +408,28 @@ private static void GraftWorkspaceCaches(string installedWorkspace, string stage } } + /// + /// Moves caches grafted into a staged workspace that was never published back to the installed + /// workspace, so a failed or cancelled publication does not throw the build caches away. + /// + private static void RestoreWorkspaceCaches(string installedWorkspace, string stagedWorkspace) + { + if (!Directory.Exists(installedWorkspace)) return; + foreach (var cacheDirectory in WorkspaceCacheDirectories) + { + var source = Path.Combine(stagedWorkspace, cacheDirectory); + var destination = Path.Combine(installedWorkspace, cacheDirectory); + try + { + if (Directory.Exists(source) && !Directory.Exists(destination)) Directory.Move(source, destination); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: a lost cache only costs a clean rebuild. + } + } + } + /// /// After publication, every shipped Toolkit/BuildWorkspace file must exist with its exact size /// (and, for the toolkit, its payload timestamp) and nothing foreign may sit beside them. A root @@ -456,15 +487,25 @@ private void RepublishDamagedRoots(InstallContext install, bool toolkit, bool wo ExtractWorkspace(install.Payload, WorkspaceExtraction.Full, install.Existing, stagedWorkspace, extracted, cancellationToken); VerifyExtraction(install.Inventory, ToolkitRefresh.None, WorkspaceExtraction.Full, extracted); - GraftWorkspaceCaches(install.Existing.WorkspaceDirectory, stagedWorkspace, cancellationToken); AddComponent(entries, retry, installDirectory, InstalledLayout.WorkspaceDirectoryName); } cancellationToken.ThrowIfCancellationRequested(); RunningProductGuard.EnsureProductsNotRunning(installDirectory); - using var transaction = InstallTransaction.Begin(installDirectory, _reporter, entries.ToArray()); - transaction.Publish(); - transaction.Commit(); + var retryWorkspace = InstalledLayout.Workspace(retry); + try + { + if (workspace) + GraftWorkspaceCaches(install.Existing.WorkspaceDirectory, retryWorkspace, cancellationToken); + using var transaction = InstallTransaction.Begin(installDirectory, _reporter, entries.ToArray()); + transaction.Publish(); + transaction.Commit(); + } + catch + { + if (workspace) RestoreWorkspaceCaches(install.Existing.WorkspaceDirectory, retryWorkspace); + throw; + } } /// diff --git a/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs b/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs index ac56b39e3..d71d26d1c 100644 --- a/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs +++ b/Launcher/WiiCompiled.Setup.Windows/PayloadInventory.cs @@ -77,9 +77,13 @@ public void Validate() throw new InvalidDataException($"Unsupported payload inventory schema {SchemaVersion}."); if (Files is not { Count: > 0 }) throw new InvalidDataException("The payload inventory lists no files."); + if (ToolkitFingerprint is null || ToolkitPackageFingerprint is null) + throw new InvalidDataException("The payload inventory has no toolkit identity."); var seen = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var file in Files) { + if (file is null || file.Sha256 is null) + throw new InvalidDataException("The payload inventory has an incomplete entry."); if (string.IsNullOrEmpty(file.Path) || file.Path.Contains('\\') || file.Path.StartsWith('/') || file.Path.Split('/').Any(part => part is "" or "." or "..") || !(file.Path.StartsWith(InstalledLayout.ToolkitEntryPrefix, StringComparison.Ordinal) || @@ -90,6 +94,8 @@ public void Validate() throw new InvalidDataException($"The payload inventory lists '{file.Path}' twice."); } TranslationInputs ??= new Dictionary>(StringComparer.Ordinal); + if (TranslationInputs.Any(pair => pair.Value is null || pair.Value.Any(path => path is null))) + throw new InvalidDataException("The payload inventory has an incomplete translation input list."); } /// Compact on purpose: it lists every shipped file and is read once per install. @@ -130,6 +136,11 @@ void Report(string problem) if (expected.Count > 0) Report($"{prefix} is missing"); return problems; } + if ((File.GetAttributes(directory) & FileAttributes.ReparsePoint) != 0) + { + Report($"{prefix} is a link, not shipped content"); + return problems; + } var pending = new Stack(); pending.Push(new DirectoryInfo(directory)); while (pending.Count > 0) diff --git a/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs b/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs index b602bd7b6..14e7fba43 100644 --- a/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs +++ b/Launcher/WiiCompiled.Setup.Windows/ToolkitFingerprint.cs @@ -365,18 +365,27 @@ internal static IReadOnlyList RunTranslatorLister(string translatorExecu start.ArgumentList.Add(projectFile); using var process = Process.Start(start) ?? throw new InvalidOperationException("The translator could not be started."); - var stderr = process.StandardError.ReadToEndAsync(cancellationToken); - var stdout = process.StandardOutput.ReadToEndAsync(cancellationToken); - if (!process.WaitForExit(TimeSpan.FromMinutes(2))) + var stderr = process.StandardError.ReadToEndAsync(); + var stdout = process.StandardOutput.ReadToEndAsync(); + using (var wait = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { - try { process.Kill(entireProcessTree: true); } catch { } - throw new TimeoutException("Listing the translation inputs did not finish."); + wait.CancelAfter(TimeSpan.FromMinutes(2)); + try + { + process.WaitForExitAsync(wait.Token).GetAwaiter().GetResult(); + } + catch (OperationCanceledException) + { + try { process.Kill(entireProcessTree: true); } catch { } + cancellationToken.ThrowIfCancellationRequested(); + throw new TimeoutException("Listing the translation inputs did not finish."); + } } process.WaitForExit(); if (process.ExitCode != 0) throw new InvalidDataException( - $"list-translation-inputs failed with exit code {process.ExitCode}: {stderr.Result.Trim()}"); - return stdout.Result.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + $"list-translation-inputs failed with exit code {process.ExitCode}: {stderr.GetAwaiter().GetResult().Trim()}"); + return stdout.GetAwaiter().GetResult().Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); } private static SortedDictionary SelectSubset(SortedDictionary entries, diff --git a/Launcher/macos/extract-disc.command b/Launcher/macos/extract-disc.command index b7d7409ea..ddf2e7393 100755 --- a/Launcher/macos/extract-disc.command +++ b/Launcher/macos/extract-disc.command @@ -45,15 +45,28 @@ done assets_dir=$(mkdir -p "$assets_dir" && cd "$assets_dir" && pwd) # An interrupted earlier run can leave its stage or backup behind. Remove only those whose owning -# process is gone; backups named by older versions (no process id) are left alone. +# process is gone; backups named by older versions (no process id) are left alone. A backup whose +# run stopped before publishing anything is moved back first, so it is never lost. stale_stage_pattern='^[.]extract-stage-([0-9]+)$' stale_backup_pattern='^[.]previous-extraction-([0-9]+)-[0-9]{8}-[0-9]{6}$' +extraction_items="DATA .data-manifest main.dol StaticR.rel" for stale in "$assets_dir"/.extract-stage-* "$assets_dir"/.previous-extraction-*; do [[ -e "$stale" || -L "$stale" ]] || continue stale_name=${stale##*/} if [[ "$stale_name" =~ $stale_stage_pattern || "$stale_name" =~ $stale_backup_pattern ]]; then stale_pid=${BASH_REMATCH[1]} if ! kill -0 "$stale_pid" 2>/dev/null; then + if [[ "$stale_name" =~ $stale_backup_pattern && -d "$stale" && ! -L "$stale" ]]; then + published=0 + for item in $extraction_items; do + [[ -e "$assets_dir/$item" || -L "$assets_dir/$item" ]] && published=1 + done + if (( published == 0 )); then + for item in $extraction_items; do + [[ -e "$stale/$item" ]] && mv "$stale/$item" "$assets_dir/$item" + done + fi + fi rm -rf "$stale" fi fi diff --git a/translator/src/Translator.Core/IO/FileAccessRecorder.cs b/translator/src/Translator.Core/IO/FileAccessRecorder.cs index cac55a4c8..713bb0358 100644 --- a/translator/src/Translator.Core/IO/FileAccessRecorder.cs +++ b/translator/src/Translator.Core/IO/FileAccessRecorder.cs @@ -49,8 +49,10 @@ public sealed record FileAccessSnapshot( /// public sealed class FileAccessRecorder { + // Case-sensitive everywhere but Windows: macOS volumes may be either, and keeping two spellings + // of one file apart only costs a second hash, while merging two files could hide a change. public static readonly StringComparer PathComparer = - OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; private readonly object _gate = new(); private readonly Dictionary _inputs = new(PathComparer); @@ -114,14 +116,11 @@ public void OnScan(FileScanQuery query, IEnumerable entries) } } + // Kept even for directories this run created: a file added there later must still be pruned. public void OnOutputScan(FileScanQuery query) { var normalized = query.Normalized(); - lock (_gate) - { - if (IsProducedLocked(normalized.Directory)) return; - _outputScans.Add(normalized); - } + lock (_gate) _outputScans.Add(normalized); } public void OnWrite(string path) @@ -255,7 +254,7 @@ private static bool IsSameOrUnder(string path, string root) { if (PathComparer.Equals(path, root)) return true; var prefix = Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar; - return path.StartsWith(prefix, OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() + return path.StartsWith(prefix, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } diff --git a/translator/tests/Translator.Tests/FileAccessRecorderTests.cs b/translator/tests/Translator.Tests/FileAccessRecorderTests.cs index 9c011bb2d..3d2b6e835 100644 --- a/translator/tests/Translator.Tests/FileAccessRecorderTests.cs +++ b/translator/tests/Translator.Tests/FileAccessRecorderTests.cs @@ -114,6 +114,20 @@ public void OutputListingsAreTakenWhenTheRunEnds() Assert.Equal(new[] { "kept.bin" }, scan.Entries); } + [Fact] + public void OutputListingsOfCreatedDirectoriesAreKept() + { + var blobs = Path.Combine(_root, "created"); + var recorder = new FileAccessRecorder(); + recorder.OnCreateDirectory(blobs); + Directory.CreateDirectory(blobs); + recorder.OnOutputScan(new FileScanQuery(blobs, "*.bin", SearchOption.TopDirectoryOnly, FileScanKind.Files)); + Write(Path.Combine("created", "kept.bin"), "y"); + + var scan = Assert.Single(recorder.Snapshot().Scans); + Assert.Equal(new[] { "kept.bin" }, scan.Entries); + } + [Fact] public void UntrackedInputsAndEnvironmentExpansionsAreReported() { From 541c9432aad558f23c3610d697d26abd30302811 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:32:32 +0100 Subject: [PATCH 3/4] restore product mode and ca bundle --- Launcher/local-build.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Launcher/local-build.sh b/Launcher/local-build.sh index e13db67bc..e6948dd0a 100755 --- a/Launcher/local-build.sh +++ b/Launcher/local-build.sh @@ -554,11 +554,15 @@ publish_built_product() { local exe=$build/$target assert_file "$exe" "Locally compiled game executable" cp -f "$exe" "$destination/$target" + # cp -f keeps an existing destination's mode. + chmod 755 "$destination/$target" # cacert.pem is the TLS root bundle the mbed TLS path looks up beside the executable # (runtime/src/hle/net/network_ssl.cpp); without it HTTPS fails at runtime. for name in dsp_coef.bin initial_pipeline_cache.db cacert.pem; do [[ -f "$build/$name" ]] && cp -f "$build/$name" "$destination/" done + # The build only copies the bundle when the executable relinks. + [[ -f "$destination/cacert.pem" ]] || cp -f "$workspace/runtime/assets/certs/cacert.pem" "$destination/" [[ -d "$build/wii_bootstrap" ]] && cp -rf "$build/wii_bootstrap" "$destination/" local is_retro=0 code_pul_sha=null From 56ae48ea1451b7f666ef1fe53232a10bb4e1e568 Mon Sep 17 00:00:00 2001 From: patchzyy <64382339+patchzyy@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:38:08 +0100 Subject: [PATCH 4/4] hold workspace caches outside the transaction --- .../ProductCurrency.cs | 5 ++ .../InstallerEngine.cs | 46 +++++++++++-------- .../SelfTests.Payload.cs | 36 +++++++++++++++ 3 files changed, 67 insertions(+), 20 deletions(-) diff --git a/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs b/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs index f46351cd8..6b7f78477 100644 --- a/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs +++ b/Launcher/WiiCompiled.Setup.Linux/ProductCurrency.cs @@ -385,6 +385,11 @@ public static bool ExecutablesRunnable(ProductCurrencyOptions options) inputs["tool.native-prebuilt"] = ProductCurrency.None; else { + if (!Path.IsPathRooted(options.NativePrebuiltDir)) + { + reason = "the native prebuilt package is given by a relative path"; + return null; + } var resolved = RealPath(options.NativePrebuiltDir); var relative = resolved is null || !Directory.Exists(resolved) ? null : ProductCurrency.RelativeInside(toolkitRoot, resolved); if (relative is null) { reason = "the native prebuilt package is not part of the toolkit"; return null; } diff --git a/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs b/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs index 2bbee9a6b..42f4a81f1 100644 --- a/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs +++ b/Launcher/WiiCompiled.Setup.Windows/InstallerEngine.cs @@ -351,10 +351,11 @@ private async Task PublishToolkitAndReconcileProductsAsync(InstallContext instal var release = install.Release; var installDirectory = existing.Root; - var stagedWorkspace = InstalledLayout.Workspace(staging); + var heldCaches = Path.Combine(staging, HeldCachesDirectoryName); try { - GraftWorkspaceCaches(existing.WorkspaceDirectory, stagedWorkspace, cancellationToken); + HoldWorkspaceCaches(existing.WorkspaceDirectory, InstalledLayout.Workspace(staging), heldCaches, + cancellationToken); var state = BuildInstallState(install.PreviousState, installDirectory, manifest, release, compileInputs: null, install.CanonicalRetroRoot, install.Options.RetroWfcPayloadMode); @@ -371,10 +372,9 @@ private async Task PublishToolkitAndReconcileProductsAsync(InstallContext instal entries, cancellationToken, progressPercent: 8, completionPercent: 10, createShortcuts: install.FirstInstall); } - catch + finally { - RestoreWorkspaceCaches(existing.WorkspaceDirectory, stagedWorkspace); - throw; + RestoreWorkspaceCaches(existing.WorkspaceDirectory, heldCaches); } var verified = EnsurePublishedToolkitIntact(install, cancellationToken); @@ -389,35 +389,41 @@ private async Task PublishToolkitAndReconcileProductsAsync(InstallContext instal release.DolSha256, release.RelSha256, reconciliation.CachedRetroWfcPayloadMatches); } + private const string HeldCachesDirectoryName = "workspace-caches"; + /// - /// Moves the installed workspace's build caches into a staged workspace, so a toolkit update - /// keeps the base translation, native build directory, verified inputs and payload cache. Each - /// is re-validated by the build, so stale caches degrade to a clean rebuild, never reuse. + /// Moves the installed workspace's build caches aside, outside both the installed and the staged + /// workspace, while a workspace publication runs, so a toolkit update keeps the base translation, + /// native build directory, verified inputs and payload cache whether it commits or rolls back. + /// Each is re-validated by the build, so stale caches degrade to a clean rebuild, never reuse. /// - private static void GraftWorkspaceCaches(string installedWorkspace, string stagedWorkspace, + internal static void HoldWorkspaceCaches(string installedWorkspace, string stagedWorkspace, string held, CancellationToken cancellationToken) { + Directory.CreateDirectory(held); foreach (var cacheDirectory in WorkspaceCacheDirectories) { cancellationToken.ThrowIfCancellationRequested(); + var staged = Path.Combine(stagedWorkspace, cacheDirectory); + if (Directory.Exists(staged)) Directory.Delete(staged, recursive: true); var source = Path.Combine(installedWorkspace, cacheDirectory); if (!Directory.Exists(source)) continue; - var destination = Path.Combine(stagedWorkspace, cacheDirectory); + var destination = Path.Combine(held, cacheDirectory); if (Directory.Exists(destination)) Directory.Delete(destination, recursive: true); Directory.Move(source, destination); } } /// - /// Moves caches grafted into a staged workspace that was never published back to the installed - /// workspace, so a failed or cancelled publication does not throw the build caches away. + /// Moves held caches into whichever workspace is installed once the publication finished: the + /// new one after a commit, the restored one after a rollback. /// - private static void RestoreWorkspaceCaches(string installedWorkspace, string stagedWorkspace) + internal static void RestoreWorkspaceCaches(string installedWorkspace, string held) { - if (!Directory.Exists(installedWorkspace)) return; + if (!Directory.Exists(installedWorkspace) || !Directory.Exists(held)) return; foreach (var cacheDirectory in WorkspaceCacheDirectories) { - var source = Path.Combine(stagedWorkspace, cacheDirectory); + var source = Path.Combine(held, cacheDirectory); var destination = Path.Combine(installedWorkspace, cacheDirectory); try { @@ -492,19 +498,19 @@ private void RepublishDamagedRoots(InstallContext install, bool toolkit, bool wo cancellationToken.ThrowIfCancellationRequested(); RunningProductGuard.EnsureProductsNotRunning(installDirectory); - var retryWorkspace = InstalledLayout.Workspace(retry); + var heldCaches = Path.Combine(retry, HeldCachesDirectoryName); try { if (workspace) - GraftWorkspaceCaches(install.Existing.WorkspaceDirectory, retryWorkspace, cancellationToken); + HoldWorkspaceCaches(install.Existing.WorkspaceDirectory, InstalledLayout.Workspace(retry), + heldCaches, cancellationToken); using var transaction = InstallTransaction.Begin(installDirectory, _reporter, entries.ToArray()); transaction.Publish(); transaction.Commit(); } - catch + finally { - if (workspace) RestoreWorkspaceCaches(install.Existing.WorkspaceDirectory, retryWorkspace); - throw; + if (workspace) RestoreWorkspaceCaches(install.Existing.WorkspaceDirectory, heldCaches); } } diff --git a/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs b/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs index 21d272398..c83d29de9 100644 --- a/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs +++ b/Launcher/WiiCompiled.Setup.Windows/SelfTests.Payload.cs @@ -16,6 +16,7 @@ private static void RegisterPayloadTests(List failures) Test("Payload inventory stat check", TestPayloadInventoryStatCheck, failures); Test("Asset-only and translator-only extraction", TestPartialPayloadExtraction, failures); Test("Published toolkit retry recovery", TestPublishedToolkitRecovery, failures); + Test("Workspace caches survive commit and rollback", TestWorkspaceCachesHeldAcrossPublication, failures); Test("Preverified toolkit identities", TestPreverifiedToolkitIdentities, failures); Test("Narrowed cache identities", TestNarrowedCacheIdentities, failures); Test("Progress JSON stays monotonic", TestProgressJsonMonotonic, failures); @@ -377,6 +378,41 @@ private static void TestPartialPayloadExtraction() => WithTempDirectory("partial /// must be repaired by one more publication of just the damaged roots, keeping the build caches, /// instead of leaving the user re-running setup into the same failure. /// + /// + /// Build caches are held outside both workspaces while one is published, and end up in whichever + /// workspace is installed afterwards: the new one after a commit, the old one after a rollback. + /// + private static void TestWorkspaceCachesHeldAcrossPublication() => WithTempDirectory("caches", directory => + { + foreach (var committed in new[] { true, false }) + { + var installed = Path.Combine(directory, $"installed-{committed}"); + var staged = Path.Combine(directory, $"staged-{committed}"); + var held = Path.Combine(directory, $"held-{committed}"); + var cache = Path.Combine(installed, "native-build", "CMakeCache.txt"); + Directory.CreateDirectory(Path.GetDirectoryName(cache)!); + File.WriteAllText(cache, "kept"); + Directory.CreateDirectory(Path.Combine(staged, "generated")); + File.WriteAllText(Path.Combine(installed, "shipped.txt"), "old"); + File.WriteAllText(Path.Combine(staged, "shipped.txt"), "new"); + + InstallerEngine.HoldWorkspaceCaches(installed, staged, held, CancellationToken.None); + if (Directory.Exists(Path.Combine(installed, "native-build")) || Directory.Exists(Path.Combine(staged, "generated"))) + throw new Exception("Caches were left in a workspace being replaced."); + if (committed) + { + Directory.Delete(installed, recursive: true); + Directory.Move(staged, installed); + } + InstallerEngine.RestoreWorkspaceCaches(installed, held); + + if (!File.Exists(cache) || File.ReadAllText(cache) != "kept") + throw new Exception($"The build caches were lost after a {(committed ? "commit" : "rollback")}."); + if (File.ReadAllText(Path.Combine(installed, "shipped.txt")) != (committed ? "new" : "old")) + throw new Exception("The restored caches landed in the wrong workspace."); + } + }); + private static void TestPublishedToolkitRecovery() => WithTempDirectory("recovery", directory => { var release = BuildFakeRelease(directory);