Files
Reims-Go/scripts/pack-runtime.ps1
T

349 lines
19 KiB
PowerShell

<#
.SYNOPSIS
Pack a portable reims-vgpu runtime for Windows x64, its matching source
package, and SHA256SUMS.txt, ready to publish as a GitHub Release.
.DESCRIPTION
Outputs, in -OutDir (all four are assets of one GitHub Release):
reims-runtime-win-x64-<commit>.tar.zst runtime (bin/, qemu/, manifest.json,
NOTICE.md, licenses/, patches/,
MSYS2-PACKAGES.txt)
reims-runtime-src-<commit>.tar.zst corresponding source: pristine upstream
trees at the built commits + patches/
reims-runtime-msys2-src-<commit>.tar.zst sources of the copyleft MSYS2 packages
whose DLLs are bundled (pack-msys2-sources.ps1)
SHA256SUMS.txt all three archives
manifest.json (schema 2) states what the package was really built from:
upstream commit, vendor/qemu commit, reims-util and metal2vulkan commits,
every local patch with its SHA256, and the channel. A package built with
patches is never described as pure upstream (AGENTS.md rule 5).
Before packing, each patch in -Patches is checked against the build tree:
the tree's diff must equal the patch, so the source package matches the
binaries. A mismatch stops the script.
.EXAMPLE
pwsh -File scripts/pack-runtime.ps1 -Channel candidate
#>
[CmdletBinding()]
param(
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$CargoHome = 'D:\DevTools\cargo',
[string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current',
[string]$Msys2 = 'D:\DevTools\msys64',
[string]$OutDir = 'D:\Data\reims-go\releases',
[string]$TempRoot = 'D:\Build\Temp',
[ValidateSet('candidate', 'stable')]
[string]$Channel = 'candidate',
[int]$ZstdLevel = 15,
[switch]$IncludeNestedVirtPatch,
[switch]$IncludeWin32FiberPatch
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$CargoBin = Join-Path $CargoHome 'bin'
function Invoke-Native([string]$exe, [string[]]$argv) {
& $exe @argv
if ($LASTEXITCODE -ne 0) { throw "$exe $($argv -join ' ') failed ($LASTEXITCODE)" }
}
function Get-Sha256([string]$path) {
(Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant()
}
function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Resolve-Zstd {
@(
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
(Join-Path $Msys2 'usr\bin\zstd.exe'),
(Join-Path $Msys2 'clang64\bin\zstd.exe')
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
}
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
$zstd = Resolve-Zstd
if (-not $zstd) { throw 'zstd not found (install MSYS2 zstd or put zstd.exe on PATH)' }
$tar = Join-Path $TempRoot "$name.tar"
Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name)
Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
Remove-Item -LiteralPath $tar -Force
}
# ── 1. Inputs and provenance ─────────────────────────────────
$ctlExe = Join-Path $CargoBin 'reims-ctl.exe'
$utilExe = Join-Path $CargoBin 'reims-util.exe'
$qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe'
foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
if (-not (Test-Path -LiteralPath $p)) { throw "Required runtime binary not found: $p" }
}
$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim()
$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim()
$qemuRepo = Join-Path $ReimsRepo 'vendor\qemu'
$qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim()
# reims-util's pinned commit is a constant in reims-ctl (crates/reims-ctl/src/reims_util.rs, REV).
$utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs')
if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' }
$utilCommit = $Matches[1]
# metal2vulkan's git rev as built (Cargo.lock in the build tree).
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.lock' }
$m2vCommit = $Matches[1]
$qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim()
$utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim()
# ── 2. Patches must equal the build tree's diffs ─────────────
$patchSpecs = @(
@{ Name = 'reims-vgpu-cargo-lock.patch'; Target = 'reims-vgpu'; Repo = $ReimsRepo; Paths = @('Cargo.lock') },
@{ Name = 'qemu-whpx-win10-compat.patch'; Target = 'vendor/qemu'; Repo = $qemuRepo; Paths = @() },
@{ Name = 'qemu-whpx-win10-startup-ipis.patch'; Target = 'vendor/qemu'; Repo = $qemuRepo; Paths = @() }
)
if ($IncludeNestedVirtPatch) {
$patchSpecs += @{ Name = 'qemu-whpx-nested-virt-nonfatal.patch'; Target = 'vendor/qemu'; Repo = $qemuRepo; Paths = @() }
}
if ($IncludeWin32FiberPatch) {
$patchSpecs += @{ Name = 'qemu-win32-coroutine-fiber-commit.patch'; Target = 'vendor/qemu'; Repo = $qemuRepo; Paths = @() }
}
$patches = @()
# Group patches by repo so multi-patch stacks (e.g. 2-3 QEMU WHPX patches) are
# verified together against a clean HEAD export with zero undeclared diff.
$byTarget = [ordered]@{}
foreach ($ps in $patchSpecs) {
$file = Join-Path $patchesDir $ps.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
if (-not $byTarget.Contains($ps.Target)) {
$byTarget[$ps.Target] = [Collections.Generic.List[hashtable]]::new()
}
$byTarget[$ps.Target].Add($ps)
$patches += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) }
}
foreach ($targetName in $byTarget.Keys) {
$group = $byTarget[$targetName]
$repo = $group[0].Repo
$paths = @($group | ForEach-Object { $_.Paths } | Where-Object { $_ } | Select-Object -Unique)
$diffArgs = @('-C', $repo, '-c', 'core.autocrlf=false', 'diff')
if ($paths.Count) { $diffArgs += $paths }
$treeDiff = (& git @diffArgs | Out-String).Replace("`r`n", "`n").TrimEnd()
if ($group.Count -eq 1) {
$patchText = [IO.File]::ReadAllText((Join-Path $patchesDir $group[0].Name)).Replace("`r`n", "`n").TrimEnd()
if ($treeDiff -ne $patchText) {
throw "$($group[0].Name) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
} else {
# Apply the declared patch stack to a clean temporary clone of HEAD and compare diffs byte-for-byte.
$verifyDir = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid())
try {
New-Item -ItemType Directory -Force -Path $verifyDir | Out-Null
$headRev = (git -C $repo rev-parse HEAD).Trim()
Invoke-Native 'git' @('init', '-q', $verifyDir)
$tar = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $headRev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $verifyDir)
Remove-Item -LiteralPath $tar -Force
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'add', '-A')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '-m', 'base')
foreach ($ps in $group) {
$pf = Join-Path $patchesDir $ps.Name
Invoke-Native 'git' @('-C', $verifyDir, 'apply', '--check', $pf)
Invoke-Native 'git' @('-C', $verifyDir, 'apply', $pf)
}
$expectedDiff = (& git -C $verifyDir -c core.autocrlf=false diff | Out-String).Replace("`r`n", "`n").TrimEnd()
if ($treeDiff -ne $expectedDiff) {
throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
} finally {
if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir }
}
}
}
# Anything else changed in the build trees is undeclared: refuse.
$otherCtl = @(git -C $ReimsRepo status --porcelain --ignore-submodules=all | Where-Object { $_ -notmatch 'Cargo\.lock$' })
$otherQemu = @(git -C $qemuRepo status --porcelain --untracked-files=no | Where-Object { $_ -notmatch 'target/i386/whpx/whpx-all\.c$' })
if ($otherCtl.Count -or $otherQemu.Count) {
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu -join "`n")"
}
$bundleName = "reims-runtime-win-x64-$commit"
$srcName = "reims-runtime-src-$commit"
$stageRoot = Join-Path $TempRoot "pack-$commit"
$bundleDir = Join-Path $stageRoot $bundleName
$srcDir = Join-Path $stageRoot $srcName
if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot }
New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", "$bundleDir\patches", $srcDir, $OutDir | Out-Null
# ── 3. Runtime bundle ────────────────────────────────────────
Write-Host "==> Staging $bundleName ($Channel)"
Copy-Item -LiteralPath $ctlExe -Destination "$bundleDir\bin\reims-ctl.exe"
Copy-Item -LiteralPath $utilExe -Destination "$bundleDir\bin\reims-util.exe"
$resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target
if (-not $resolvedQemu) { $resolvedQemu = $QemuDir }
Copy-Item -Path "$resolvedQemu\*" -Destination "$bundleDir\qemu" -Recurse -Force
Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md"
foreach ($ps in $patchSpecs) { Copy-Item -LiteralPath (Join-Path $patchesDir $ps.Name) -Destination "$bundleDir\patches\" }
Copy-Item -LiteralPath (Join-Path $patchesDir 'README.md') -Destination "$bundleDir\patches\README.md"
$licenses = @{
'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE')
'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING')
'qemu-COPYING.LIB.txt' = (Join-Path $qemuRepo 'COPYING.LIB')
}
foreach ($k in $licenses.Keys) {
if (Test-Path -LiteralPath $licenses[$k]) { Copy-Item -LiteralPath $licenses[$k] -Destination (Join-Path "$bundleDir\licenses" $k) }
}
if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) {
Copy-Item -Path (Join-Path $ReimsRepo 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force
}
# MSYS2 CLANG64 DLLs: owning package and version, and where its source is.
Write-Host '==> Listing MSYS2 packages of bundled DLLs'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$dlls = @(Get-ChildItem -LiteralPath "$bundleDir\qemu\bin" -Filter '*.dll' -File | Sort-Object Name)
$pkgLines = [Collections.Generic.List[string]]::new()
$pkgSet = [ordered]@{}
foreach ($d in $dlls) {
$owner = (& $bash -lc "LC_ALL=C pacman -Qqo /clang64/bin/$($d.Name) 2>/dev/null" | Select-Object -First 1)
if ($owner) {
$ver = (& $bash -lc "LC_ALL=C pacman -Q $owner" | Select-Object -First 1).Split(' ')[1]
$pkgLines.Add("$($d.Name)`t$owner`t$ver")
$pkgSet["$owner $ver"] = $true
} else {
$pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-")
}
}
$msysText = @"
# DLLs bundled in qemu/bin and the MSYS2 CLANG64 packages they come from
# (pacman -Qo on the build machine, $(Get-Date -Format 'yyyy-MM-dd')).
#
# Sources: every package whose licence requires source (GPL / LGPL / MPL) is in
# reims-runtime-msys2-src-$commit.tar.zst, published beside this runtime.
# The same files are also at:
# https://repo.msys2.org/mingw/sources/ (<package>-<version>.src.tar.zst, by pkgbase)
# https://github.com/msys2/MINGW-packages (build recipes)
# Licenses: see each package's /clang64/share/licenses/<package>/ in MSYS2.
DLL`tPACKAGE`tVERSION
$($pkgLines -join "`n")
# Packages ($($pkgSet.Count))
$($pkgSet.Keys -join "`n")
"@
Write-Utf8 "$bundleDir\MSYS2-PACKAGES.txt" $msysText
# ── 4. Source bundle ─────────────────────────────────────────
Write-Host "==> Staging $srcName"
function Export-GitTree([string]$repo, [string]$rev, [string]$dest) {
New-Item -ItemType Directory -Force -Path $dest | Out-Null
$tar = Join-Path $TempRoot ("git-export-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $rev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $dest)
Remove-Item -LiteralPath $tar -Force
}
Export-GitTree $ReimsRepo $fullCommit (Join-Path $srcDir "reims-vgpu-$commit")
Export-GitTree $qemuRepo $qemuCommit (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu")
# QEMU's meson wraps downloaded for this build (dtc, keycodemapdb, ...): part of what was built.
Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory |
Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } |
ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force }
$checkouts = Join-Path $CargoHome 'git\checkouts'
$utilTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
$m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
if (-not $utilTree) { throw "reims-util source at $utilCommit not found under $checkouts" }
if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" }
Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))")
Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))")
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\"
Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt"
Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md"
Write-Utf8 "$srcDir\README.md" @"
# Source for $bundleName
Corresponding source for the binaries in ``$bundleName.tar.zst``.
| Directory | Upstream | Commit |
| :-- | :-- | :-- |
| ``reims-vgpu-$commit/`` | https://github.com/steelbrain/reims-vgpu | ``$fullCommit`` |
| ``reims-vgpu-$commit/vendor/qemu/`` | https://github.com/steelbrain/qemu-reims-vgpu | ``$qemuCommit`` |
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | https://github.com/steelbrain/reims-util | ``$utilCommit`` |
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | https://github.com/steelbrain/metal2vulkan | ``$m2vCommit`` |
The trees are pristine upstream. The binaries were built after applying the
patches in ``patches/``:
cd reims-vgpu-$commit && git apply ../patches/reims-vgpu-cargo-lock.patch
cd vendor/qemu
$((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object { " git apply ../../../patches/$($_.Name)" }) -join "`n"))
(``patch -p1`` works too.) Then build as upstream documents (``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
"@
# ── 5. Manifest (schema 2) ───────────────────────────────────
$allFiles = Get-ChildItem -LiteralPath $bundleDir -Recurse -File
$keyFiles = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe', 'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
$hashes = [ordered]@{}
foreach ($rel in $keyFiles) {
$fp = Join-Path $bundleDir ($rel -replace '/', '\')
if (Test-Path -LiteralPath $fp) { $hashes[$rel] = Get-Sha256 $fp }
}
$manifest = [ordered]@{
schema_version = 2
name = $bundleName
platform = 'windows-x86_64'
upstream_repo = 'https://github.com/steelbrain/reims-vgpu'
commit = $commit
full_commit = $fullCommit
vendor_qemu_commit = $qemuCommit
util_commit = $utilCommit
metal2vulkan_commit = $m2vCommit
patches = $patches
channel = $Channel
source_package = "$srcName.tar.zst"
qemu_version = $qemuVersionLine
util_version = $utilVersionLine
built_at = (Get-Date).ToString('o')
file_count = $allFiles.Count + 1
dll_count = $dlls.Count
raw_bytes = [int64](($allFiles | Measure-Object Length -Sum).Sum) # PowerShell 7 sums to a double; JSON must stay an integer
sha256 = $hashes
}
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
# ── 6. Archives and sums ─────────────────────────────────────
Write-Host '==> Compressing runtime'
$runtimeArchive = Join-Path $OutDir "$bundleName.tar.zst"
New-TarZst $stageRoot $bundleName $runtimeArchive
Write-Host '==> Compressing sources'
$srcArchive = Join-Path $OutDir "$srcName.tar.zst"
New-TarZst $stageRoot $srcName $srcArchive
$rtHash = Get-Sha256 $runtimeArchive
$srcHash = Get-Sha256 $srcArchive
Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n"
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $commit -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
Remove-Item -Recurse -Force -LiteralPath $stageRoot
Write-Host ''
Write-Host '==> Done' -ForegroundColor Green
'{0,-10} {1} {2:N1} MB' -f 'runtime', $runtimeArchive, ((Get-Item $runtimeArchive).Length / 1MB)
'{0,-10} {1} {2:N1} MB' -f 'source', $srcArchive, ((Get-Item $srcArchive).Length / 1MB)
"channel $Channel; patches: $(($patches | ForEach-Object { $_.name }) -join ', '); DLLs: $($dlls.Count)"