diff --git a/.github/workflows/release-windows.yml b/.github/workflows/release-windows.yml index fa7e3a351..276495d76 100644 --- a/.github/workflows/release-windows.yml +++ b/.github/workflows/release-windows.yml @@ -288,7 +288,7 @@ jobs: # (the committed .qsb carry HLSL 50 *source*; d3d11 compiles it at runtime). # Exit code is checked (pipefail); the grep is a separate, informational pass. "$QT_ROOT_DIR/bin/windeployqt.exe" --release --qmldir crates/qbz-qt/qml \ - --no-translations --no-opengl-sw "$DIST/qbz.exe" 2>&1 | tee windeploy.log + --no-translations --no-opengl-sw --no-compiler-runtime "$DIST/qbz.exe" 2>&1 | tee windeploy.log grep -iE 'error|warning' windeploy.log || true # Nothing uses Qt SQL, Qt TLS (rustls) or network-information. rm -rf "$DIST/sqldrivers" "$DIST/tls" "$DIST/networkinformation" @@ -321,43 +321,14 @@ jobs: # Hard fail, not a warning — plan A task 14 adds licenses/. if [ ! -d licenses ]; then echo "::error::licenses/ (Qt LGPL notice) is missing; refusing to package Qt without it"; exit 1; fi cp -r licenses "$DIST/licenses" - # offscreen platform plugin: smoke only; removed before packaging. - cp "$QT_ROOT_DIR/plugins/platforms/qoffscreen.dll" "$DIST/platforms/" du -sh "$DIST" - # THE gate: the deployed directory boots without the Qt install. Pass = - # >= 10 log lines, zero QML/loader complaints, core initialized (login - # screen reached; `home published` needs a session CI does not have). - # This is the step that catches the qrc-backslash bug (W1) as `Cannot open`. - # pwsh, not Git-Bash: MSYS `kill $!` cannot reliably stop a native - # Windows process (Sol R15), and a survivor locks the deploy dir. - - name: Offscreen smoke (the directory that ships) + # Both products harvest this exact app-local runtime. Audit every EXE, + # DLL and plugin (normal + delay imports) before making either artifact. + - name: Deploy official MSVC CRT app-local and audit imports shell: pwsh - run: | - $ErrorActionPreference = "Stop" - $dist = "dist\qbz" - $qtRoot = $env:QT_ROOT_DIR - $qtHidden = "$qtRoot.hidden" - # Move-Item accepts a full destination path. Rename-Item's NewName - # parameter does not, so using it here can leave the Qt install live - # and turn this deployed-tree gate into a false positive. - Move-Item -LiteralPath $qtRoot -Destination $qtHidden - foreach ($v in "QT_PLUGIN_PATH","QML_IMPORT_PATH","QML2_IMPORT_PATH","QT_ROOT_DIR") { Remove-Item "Env:$v" -ErrorAction SilentlyContinue } - $env:QT_QPA_PLATFORM = "offscreen"; $env:RUST_LOG = "info" - $p = Start-Process -FilePath "$dist\qbz.exe" -RedirectStandardOutput smoke.out -RedirectStandardError smoke.err -PassThru -NoNewWindow - Start-Sleep -Seconds 45 - if (-not $p.HasExited) { Stop-Process -Id $p.Id -Force; Start-Sleep 1 } - Move-Item -LiteralPath $qtHidden -Destination $qtRoot - Get-Content smoke.out, smoke.err | Set-Content smoke.log - $lines = (Get-Content smoke.log | Measure-Object -Line).Lines - Write-Host "smoke log: $lines lines" - if ($lines -lt 10) { Get-Content smoke.log; Write-Host "::error::the app did not start"; exit 1 } - $pat = 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed|could not be found|0xc0000135|STATUS_DLL_NOT_FOUND|This application failed to start' - $errs = Get-Content smoke.log | Where-Object { $_ -notmatch 'propertyCache' } | Select-String -Pattern $pat - if ($errs) { $errs | Select-Object -First 20; Write-Host "::error::$($errs.Count) QML/loader complaint(s) in the smoke log"; exit 1 } - if (-not (Select-String -Path smoke.log -Pattern 'QbzCore initialized' -Quiet)) { Get-Content smoke.log -Tail 20; Write-Host "::error::never reached QbzCore init"; exit 1 } - Remove-Item "$dist\platforms\qoffscreen.dll" - Write-Host "smoke OK (0 QML complaints, core initialized)" + run: ./scripts/packaging/deploy_windows_crt.ps1 -Dist dist/qbz + # D4 = unsigned, so this is a no-op until a cert exists (HAVE_CERT is # resolved at workflow level — see the env block at the top). PLACEHOLDER # for an OV cert in a PFX: cloud-issued keys (Azure Trusted Signing, @@ -402,37 +373,43 @@ jobs: -o "dist/QBZ_${VERSION}_x64.msi" ls -la dist - # The MSI is exercised, not just built: install per-user (no UAC), assert - # the layout + registry, launch the INSTALLED exe offscreen, uninstall, - # assert nothing is left. `wix msi validate` is deliberately NOT run: - # per-user harvested components fail ICE38 by WiX design (issue #8633). - - name: Install / launch / uninstall the MSI (runner smoke) + # Product smoke uses qwindows from the installed payload with an isolated + # profile/PATH. A VS runner still does not certify a clean Windows image. + - name: Install / upgrade / launch / uninstall the MSI (runner smoke) shell: pwsh env: VERSION: ${{ steps.release.outputs.version }} run: | + $ErrorActionPreference = 'Stop' $msi = (Resolve-Path "dist\QBZ_$($env:VERSION)_x64.msi").Path - $p = Start-Process msiexec -ArgumentList "/i `"$msi`" /qn /l*v install.log" -Wait -PassThru - if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; Write-Host "::error::msiexec /i exit $($p.ExitCode)"; exit 1 } $root = "$env:LOCALAPPDATA\Programs\QBZ" - foreach ($f in "qbz.exe","platforms\qwindows.dll","qml\QtQuick\Controls\Basic","imageformats\qsvg.dll","LICENSE.txt") { - if (-not (Test-Path "$root\$f")) { Write-Host "::error::installed layout is missing $f"; exit 1 } + $installed = $false + try { + foreach ($stage in @('install','upgrade')) { + $p = Start-Process msiexec -ArgumentList "/i `"$msi`" /qn /l*v $stage.log" -Wait -PassThru + if ($p.ExitCode -ne 0) { Get-Content "$stage.log" -Tail 60; throw "msiexec $stage exit $($p.ExitCode)" } + $installed = $true + } + foreach ($f in @('qbz.exe','platforms\qwindows.dll','qml\QtQuick\Controls\Basic','imageformats\qsvg.dll','LICENSE.txt')) { + if (-not (Test-Path "$root\$f")) { throw "Installed layout is missing $f" } + } + if (-not (Test-Path 'HKCU:\Software\Classes\qbz')) { throw 'qbz protocol key missing' } + if (-not (Test-Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\QBZ.lnk")) { throw 'Start-menu shortcut missing' } + $sourceHash = (Get-FileHash 'dist/qbz/licenses/msvc-runtime.json').Hash + if ((Get-FileHash "$root/licenses/msvc-runtime.json").Hash -ne $sourceHash) { throw 'MSI CRT inventory differs from shared payload' } + python scripts/packaging/windows_crt.py $root --report windows-msi-imports.json + if ($LASTEXITCODE -ne 0) { throw 'Installed MSI CRT audit failed' } + ./scripts/packaging/smoke_windows_deploy.ps1 -Directory $root -LogPrefix inst } - foreach ($protocol in "qbz") { - if (-not (Test-Path "HKCU:\Software\Classes\$protocol")) { Write-Host "::error::$protocol protocol key missing"; exit 1 } + finally { + if ($installed) { + $u = Start-Process msiexec -ArgumentList "/x `"$msi`" /qn /l*v uninstall.log" -Wait -PassThru + if ($u.ExitCode -ne 0) { Get-Content uninstall.log -Tail 60; throw "msiexec uninstall exit $($u.ExitCode)" } + } } - if (-not (Test-Path "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\QBZ.lnk")) { Write-Host "::error::Start-menu shortcut missing"; exit 1 } - $env:QT_QPA_PLATFORM = "offscreen"; $env:RUST_LOG = "info" - $app = Start-Process "$root\qbz.exe" -RedirectStandardOutput inst.out -RedirectStandardError inst.err -PassThru -NoNewWindow - Start-Sleep 25; if (-not $app.HasExited) { Stop-Process -Id $app.Id -Force; Start-Sleep 1 } - if (-not (Select-String -Path inst.out,inst.err -Pattern 'QbzCore initialized' -Quiet)) { Get-Content inst.out,inst.err -Tail 30; Write-Host "::error::installed app never reached QbzCore init"; exit 1 } - $u = Start-Process msiexec -ArgumentList "/x `"$msi`" /qn /l*v uninstall.log" -Wait -PassThru - if ($u.ExitCode -ne 0) { Get-Content uninstall.log -Tail 60; Write-Host "::error::msiexec /x exit $($u.ExitCode)"; exit 1 } - if (Test-Path "$root\qbz.exe") { Write-Host "::error::uninstall left $root\qbz.exe"; exit 1 } - foreach ($protocol in "qbz") { - if (Test-Path "HKCU:\Software\Classes\$protocol") { Write-Host "::error::uninstall left the $protocol protocol key"; exit 1 } - } - Write-Host "MSI install/launch/uninstall OK" + if (Test-Path "$root\qbz.exe") { throw 'Uninstall left qbz.exe' } + if (Test-Path 'HKCU:\Software\Classes\qbz') { throw 'Uninstall left the qbz protocol key' } + Write-Host 'MSI install/upgrade/GUI launch/uninstall OK' - name: Sign MSI if: ${{ env.HAVE_CERT == 'true' }} @@ -452,6 +429,31 @@ jobs: run: | Compress-Archive -Path dist\qbz\* -DestinationPath "dist\qbz_$($env:VERSION)_windows_x64.zip" Copy-Item "crates\target\$env:TARGET\release\qbz.pdb" "dist\qbz_$($env:VERSION)_windows_x64.pdb" + $unpacked = Join-Path $env:RUNNER_TEMP ('qbz-portable-' + [guid]::NewGuid()) + try { + Expand-Archive -LiteralPath "dist\qbz_$($env:VERSION)_windows_x64.zip" -DestinationPath $unpacked + if ((Get-FileHash "$unpacked/licenses/msvc-runtime.json").Hash -ne (Get-FileHash 'dist/qbz/licenses/msvc-runtime.json').Hash) { throw 'ZIP CRT inventory differs from shared payload' } + python scripts/packaging/windows_crt.py $unpacked --report windows-zip-imports.json + if ($LASTEXITCODE -ne 0) { throw 'Portable ZIP CRT audit failed' } + ./scripts/packaging/smoke_windows_deploy.ps1 -Directory $unpacked -LogPrefix portable + } + finally { if (Test-Path $unpacked) { Remove-Item -LiteralPath $unpacked -Recurse -Force } } + + - name: Upload deployment evidence + if: always() + uses: actions/upload-artifact@v7 + with: + name: qbz-windows-deployment-checks + retention-days: 14 + if-no-files-found: ignore + path: | + windows-*-imports.json + inst.* + portable.* + install.log + upgrade.log + uninstall.log + dist/qbz/licenses/msvc-runtime.json - name: Upload artifacts uses: actions/upload-artifact@v7 diff --git a/.github/workflows/test-crates.yml b/.github/workflows/test-crates.yml index a86a0bc16..5a7a7d6e0 100644 --- a/.github/workflows/test-crates.yml +++ b/.github/workflows/test-crates.yml @@ -39,6 +39,8 @@ on: - "scripts/qt-*.py" - "scripts/qt-*.sh" - "scripts/test_qt_build_gates.py" + - "scripts/packaging/windows_crt.py" + - "scripts/packaging/test_windows_crt.py" - "scripts/qml-audits/**" - ".github/workflows/test-crates.yml" push: @@ -50,6 +52,8 @@ on: - "scripts/qt-*.py" - "scripts/qt-*.sh" - "scripts/test_qt_build_gates.py" + - "scripts/packaging/windows_crt.py" + - "scripts/packaging/test_windows_crt.py" - "scripts/qml-audits/**" - ".github/workflows/test-crates.yml" workflow_dispatch: diff --git a/scripts/cargo-test.sh b/scripts/cargo-test.sh index 338c83eea..5bd10e8bf 100755 --- a/scripts/cargo-test.sh +++ b/scripts/cargo-test.sh @@ -48,6 +48,9 @@ say() { printf '[cargo-test] %s\n' "$*"; } say "gate: native Qt SDK cache and crash-aware smoke regressions" python3 scripts/test_qt_build_gates.py +say "gate: Windows app-local CRT import regressions" +python3 scripts/packaging/test_windows_crt.py + say "gate: all eight gettext catalogs" for locale in en es de fr pt ru ja nl; do msgfmt --check --output-file=/dev/null "crates/qbz-i18n/translations/$locale/LC_MESSAGES/qbz-ui.po" diff --git a/scripts/packaging/deploy_windows_crt.ps1 b/scripts/packaging/deploy_windows_crt.ps1 new file mode 100644 index 000000000..2b504abfd --- /dev/null +++ b/scripts/packaging/deploy_windows_crt.ps1 @@ -0,0 +1,54 @@ +# Common app-local payload for the per-user MSI and portable ZIP. No installer, +# elevation, System32 copies, debug runtime or UCRT/API-set bundling. +param([Parameter(Mandatory=$true)][string]$Dist) +$ErrorActionPreference = 'Stop' +$distRoot = (Resolve-Path -LiteralPath $Dist).Path +if (-not $env:VCToolsRedistDir -or -not $env:VCToolsVersion) { + throw 'Run from the configured MSVC build environment (VCToolsRedistDir/VCToolsVersion required)' +} +$redist = (Resolve-Path -LiteralPath $env:VCToolsRedistDir).Path +$roots = @(Get-ChildItem -LiteralPath (Join-Path $redist 'x64') -Directory | + Where-Object { $_.Name -match '^Microsoft\.VC\d+\.CRT$' }) +if ($roots.Count -ne 1) { throw "Expected one official x64 CRT directory in $redist; found $($roots.Count)" } +$source = $roots[0] +$files = @(Get-ChildItem -LiteralPath $source.FullName -Filter '*.dll' -File) +if ($files.Count -eq 0) { throw 'Official CRT directory contains no DLLs' } +$entries = @() +foreach ($file in $files) { + if ($file.Name -notmatch '^(msvc[pr]|vcruntime|vccorlib|concrt)\d.*\.dll$' -or $file.Name -match 'd\.dll$') { + throw "Unexpected DLL in release CRT directory: $($file.Name)" + } + $info = $file.VersionInfo + $fileVersion = "$($info.FileMajorPart).$($info.FileMinorPart).$($info.FileBuildPart).$($info.FilePrivatePart)" + if ([version]$fileVersion -lt [version]$env:VCToolsVersion) { throw "CRT $fileVersion predates toolset $env:VCToolsVersion" } + Copy-Item -LiteralPath $file.FullName -Destination $distRoot -Force + $entries += [ordered]@{ name=$file.Name; source=$file.FullName; file_version=$fileVersion; + sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant(); + copyright=$info.LegalCopyright } +} +$licenses = Join-Path $distRoot 'licenses' +New-Item -ItemType Directory -Path $licenses -Force | Out-Null +[ordered]@{ architecture='x64'; toolset_version=$env:VCToolsVersion; + source=$source.FullName; files=$entries } | ConvertTo-Json -Depth 5 | + Set-Content -LiteralPath (Join-Path $licenses 'msvc-runtime.json') -Encoding utf8 +@' +Microsoft Visual C++ Runtime (x64, application-local deployment) + +These runtime DLLs come from the official Visual Studio redistributable +folder. Original version and copyright resources are retained in each DLL; +msvc-runtime.json records their origin, versions, hashes and copyright. +QBZ updates these copies when updating its MSVC runtime dependency. + +Microsoft redistribution terms and list: +https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution +Deployment documentation: +https://learn.microsoft.com/en-us/cpp/windows/determining-which-dlls-to-redistribute +'@ | Set-Content -LiteralPath (Join-Path $licenses 'MSVC-RUNTIME-NOTICE.txt') -Encoding utf8 +# Retain any notices accompanying the selected official CRT directory. +foreach ($folder in @($source.FullName, $redist)) { + foreach ($notice in @(Get-ChildItem -LiteralPath $folder -File | Where-Object { $_.Name -match '(?i)(license|notice|redist).*\.txt$' })) { + Copy-Item -LiteralPath $notice.FullName -Destination (Join-Path $licenses "MSVC-$($notice.Name)") -Force + } +} +python scripts/packaging/windows_crt.py $distRoot --report windows-crt-imports.json +if ($LASTEXITCODE -ne 0) { throw 'MSVC app-local import audit failed' } diff --git a/scripts/packaging/smoke_windows_deploy.ps1 b/scripts/packaging/smoke_windows_deploy.ps1 new file mode 100644 index 000000000..c4ab6c182 --- /dev/null +++ b/scripts/packaging/smoke_windows_deploy.ps1 @@ -0,0 +1,70 @@ +# Smoke the actual deployed product. qoffscreen.dll is neither injected nor +# resolved from the SDK. A development machine still does not prove clean OS. +param( + [Parameter(Mandatory=$true)][string]$Directory, + [Parameter(Mandatory=$true)][string]$LogPrefix, + [int]$Seconds = 75 +) +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path -LiteralPath $Directory).Path +$prefix = [IO.Path]::GetFullPath($LogPrefix) +$manifest = Get-Content -LiteralPath (Join-Path $root 'licenses/msvc-runtime.json') -Raw | ConvertFrom-Json +# QML/platform/image plugins do not all have a Qt6-prefixed filename. +$qtModules = @(Get-ChildItem -LiteralPath $root -Recurse -Filter '*.dll' -File | + Where-Object { $_.DirectoryName -ne $root -or $_.Name -match '^Qt6' } | ForEach-Object { $_.Name }) +$profile = Join-Path ([IO.Path]::GetTempPath()) ('qbz-deploy-' + [guid]::NewGuid()) +New-Item -ItemType Directory -Path $profile | Out-Null +$names = @('PATH','APPDATA','LOCALAPPDATA','QT_PLUGIN_PATH','QML_IMPORT_PATH','QML2_IMPORT_PATH', + 'QT_ROOT_DIR','QTDIR','QT_QPA_PLATFORM_PLUGIN_PATH','QT_QPA_PLATFORM','QSG_RHI_BACKEND', + 'QT_QUICK_BACKEND','QBZ_RENDERER','RUST_LOG') +$saved = @{} +foreach ($name in $names) { $saved[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') } +$app = $null +try { + foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null, 'Process') } + $env:PATH = "$env:SystemRoot\System32;$env:SystemRoot" + $env:APPDATA = Join-Path $profile 'roaming' + $env:LOCALAPPDATA = Join-Path $profile 'local' + New-Item -ItemType Directory -Path $env:APPDATA,$env:LOCALAPPDATA | Out-Null + $env:QT_QPA_PLATFORM = 'windows' + $env:RUST_LOG = 'info' + $app = Start-Process -FilePath (Join-Path $root 'qbz.exe') -WorkingDirectory $root ` + -RedirectStandardOutput "$prefix.out" -RedirectStandardError "$prefix.err" -PassThru + $clock = [Diagnostics.Stopwatch]::StartNew() + while ($clock.Elapsed.TotalSeconds -lt $Seconds) { + if ($app.HasExited) { throw "Product exited before smoke deadline: $($app.ExitCode)" } + Start-Sleep -Milliseconds 250 + $app.Refresh() + } + if ($app.MainWindowHandle -eq 0) { throw 'Product did not create a visible native window' } + $modules = @($app.Modules | ForEach-Object { [ordered]@{ name=$_.ModuleName; path=$_.FileName } }) + $modules | ConvertTo-Json | Set-Content -LiteralPath "$prefix.modules.json" + foreach ($entry in $modules) { + $isCrt = @($manifest.files | Where-Object { $_.name -ieq $entry.name }).Count -gt 0 + if ($isCrt -or $entry.name -in $qtModules) { + if (-not $entry.path.StartsWith($root + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw "Product resolved $($entry.name) outside deployment: $($entry.path)" + } + } + } + foreach ($required in @('qwindows.dll','Qt6Core.dll','vcruntime140.dll')) { + if (-not ($modules | Where-Object { $_.name -ieq $required })) { throw "Expected loaded module missing: $required" } + } +} +finally { + if ($null -ne $app -and -not $app.HasExited) { + Stop-Process -Id $app.Id -Force + $app.WaitForExit(5000) | Out-Null + } + foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $saved[$name], 'Process') } + Remove-Item -LiteralPath $profile -Recurse -Force + if ((Test-Path "$prefix.out") -and (Test-Path "$prefix.err")) { + Get-Content "$prefix.out","$prefix.err" | Set-Content "$prefix.log" + } +} +$lines = @(Get-Content -LiteralPath "$prefix.log") +$pattern = 'is not a type|unavailable|ReferenceError|TypeError|Cannot read|Unable to assign|Cannot open|no such method|non-existent property|failed to load component|is not installed|could not be found|0xc0000135|STATUS_DLL_NOT_FOUND|This application failed to start' +$errors = @($lines | Where-Object { $_ -notmatch 'propertyCache' -and $_ -match $pattern }) +if ($errors.Count -gt 0) { $errors | Select-Object -First 20 | Write-Host; throw 'QML/loader complaints in deployed smoke' } +if (-not ($lines -match 'QbzCore initialized')) { throw 'Product never reached core initialization' } +Write-Host "Deployed GUI smoke OK: $root, survived ${Seconds}s, app-local Qt/CRT modules" diff --git a/scripts/packaging/test_windows_crt.py b/scripts/packaging/test_windows_crt.py new file mode 100644 index 000000000..d031655cf --- /dev/null +++ b/scripts/packaging/test_windows_crt.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""PE fixtures reproduce missing/transitive/architecture CRT packaging failures.""" +import hashlib +import json +from pathlib import Path +import struct +import tempfile +import unittest +import sys + +sys.dont_write_bytecode = True +from windows_crt import audit, pe_imports + + +def pe(path, imports=(), delayed=(), machine=0x8664): + # One PE32+ .rdata section. Imports are real descriptor/name layouts; + # fixtures are parser inputs, deliberately not runnable executables. + data = bytearray(4096) + data[:2] = b'MZ' + struct.pack_into(' len(data): + raise ValueError(f"{path}: invalid import directory") + for relative in range(0, size - stride + 1, stride): + fields = unpack('<' + 'I' * (stride // 4), offset(rva + relative)) + if not any(fields): + break + dll_rva = fields[3] if index == 1 else fields[1] + if index == 13 and not fields[0] & 1: + dll_rva -= image_base + imports.add(name(dll_rva)) + else: + raise ValueError(f"{path}: unterminated import directory") + return imports, linker + + +def version(value): + parts = tuple(int(p) for p in str(value).split('.')) + return parts + (0,) * (4 - len(parts)) + + +def audit(root): + root = Path(root) + manifest = json.loads((root / 'licenses/msvc-runtime.json').read_text(encoding='utf-8-sig')) + if manifest['architecture'] != 'x64' or not manifest['files']: + raise ValueError('missing x64 official CRT inventory') + inventory = {} + for entry in manifest['files']: + name = entry['name'].lower() + if not CRT.fullmatch(name) or DEBUG_CRT.search(name): + raise ValueError(f'non-release CRT in inventory: {name}') + if name in inventory: + raise ValueError(f'duplicate CRT entry: {name}') + inventory[name] = entry + local = {p.name.lower(): p for p in root.iterdir() if p.is_file()} + for name, entry in inventory.items(): + if name not in local: + raise ValueError(f'app-local CRT missing: {name}') + if hashlib.sha256(local[name].read_bytes()).hexdigest() != entry['sha256'].lower(): + raise ValueError(f'CRT differs from official source: {name}') + if version(entry['file_version']) < version(manifest['toolset_version']): + raise ValueError(f'CRT older than build toolset: {name}') + edges = [] + binaries = sorted(p for p in root.rglob('*') if p.suffix.lower() in ('.exe', '.dll')) + if not (root / 'qbz.exe').is_file(): + raise ValueError('qbz.exe missing') + for binary in binaries: + imports, linker = pe_imports(binary) + if binary.name.lower() in SYSTEM_DEBUG_CRT: + raise ValueError(f'debug system CRT in payload: {binary}') + if CRT.fullmatch(binary.name) and binary.parent != root: + raise ValueError(f'CRT shadows app-local copy: {binary}') + if CRT.fullmatch(binary.name) and binary.name.lower() not in inventory: + raise ValueError(f'uninventoried/debug CRT in payload: {binary}') + for name in sorted(imports): + if name in SYSTEM_DEBUG_CRT: + raise ValueError(f'{binary.relative_to(root)} imports debug system CRT {name}') + if not CRT.fullmatch(name): + continue + if DEBUG_CRT.search(name) or name not in inventory: + raise ValueError(f'{binary.relative_to(root)} imports unbundled/debug CRT {name}') + if version(inventory[name]['file_version'])[:2] < linker: + raise ValueError(f'{binary.name}: {name} older than linker {linker}') + edges.append({'binary': str(binary.relative_to(root)), 'imports': name}) + if not edges: + raise ValueError('no MSVC imports found; wrong or incomplete payload') + return {'binaries': len(binaries), 'crt_files': len(inventory), 'imports': edges} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('directory', type=Path) + parser.add_argument('--report', type=Path) + args = parser.parse_args() + report = audit(args.directory) + if args.report: + args.report.write_text(json.dumps(report, indent=2) + '\n') + print(f"CRT audit OK: {report['binaries']} AMD64 binaries, {report['crt_files']} official app-local DLLs, {len(report['imports'])} MSVC import edges") + + +if __name__ == '__main__': + main()