| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835 |
- param(
- [Parameter(Mandatory = $true)][string]$OutputDir,
- [Parameter(Mandatory = $true)][string]$NormalBitstream,
- [Parameter(Mandatory = $true)][string]$TdReceipt,
- [Parameter(Mandatory = $true)][ValidatePattern('^[0-9a-f]{32}$')][string]$VerificationRunId,
- [AllowEmptyString()][string]$ConfirmationTdReceipt = "",
- [string[]]$ValidationReceipt = @(),
- [string]$HostContract = "",
- [string]$Commit = "",
- [string]$WheelhouseRoot = "",
- [ValidateSet("python", "icarus", "verilator", "cocotb", "formal", "td_confirmation")]
- [string[]]$RunningValidationLayer = @(),
- [switch]$UrgentSingleTd
- )
- Set-StrictMode -Version Latest
- $ErrorActionPreference = "Stop"
- $repo = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
- $packageScriptRelative = "tools/package_prod2u_p4_normal_v3.ps1"
- $readmeSourceRelative = "docs/prod2u-p4-normal-v3-runbook.zh-CN.md"
- $hostContractSchemaRelative = "schemas/prod2u_p4_normal_host_contract_v4.schema.json"
- $hardwareBindingRelative = "config/prod2u_p4_normal_v3_hw_binding.json"
- $verificationTargetsRelative = "config/prod2u_p4_verification_targets_v1.json"
- $tdReceiptSchema = "prod2u-p4-normal-v3-td-build-receipt-v2"
- $validationLayerNames = @(
- "python", "icarus", "verilator", "cocotb", "formal",
- "td_primary", "td_confirmation", "td_primary_artifacts",
- "td_confirmation_artifacts", "td_confirmation_bitstream",
- "td_confirmation_synthesis", "td_confirmation_manifest",
- "resource_primary", "resource_confirmation", "package_selftest"
- )
- $verificationEvidenceLayers = @(
- "python", "icarus", "verilator", "cocotb", "formal",
- "td_primary", "td_confirmation", "td_primary_artifacts",
- "td_confirmation_artifacts", "td_confirmation_bitstream",
- "td_confirmation_synthesis", "td_confirmation_manifest",
- "resource_primary", "resource_confirmation"
- )
- $templateRelatives = @(
- "tools/package_templates/bootstrap.ps1",
- "tools/package_templates/selftest.ps1",
- "tools/package_templates/run.ps1",
- "tools/package_templates/SEND_HEX.ps1",
- "tools/package_templates/INITIALIZE_DISABLE.ps1",
- "tools/package_templates/PROGRAM_SRAM.ps1"
- )
- if (-not $HostContract) {
- $HostContract = Join-Path $repo "config\prod2u_p4_normal_host_contract_v4.json"
- }
- function Assert-File([string]$Path, [string]$Label) {
- if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
- throw "$Label is missing: $Path"
- }
- }
- function Assert-NonEmptyFile([string]$Path, [string]$Label) {
- Assert-File $Path $Label
- if ((Get-Item -LiteralPath $Path).Length -le 0) {
- throw "$Label is empty: $Path"
- }
- }
- function Resolve-Git {
- $git = Get-Command git.exe -ErrorAction SilentlyContinue
- if (-not $git) { $git = Get-Command git -ErrorAction SilentlyContinue }
- if (-not $git) { throw "Git is required to bind the package commit" }
- return $git.Source
- }
- function Resolve-Commit([string]$Requested) {
- $git = Resolve-Git
- $head = (& $git -C $repo rev-parse HEAD).Trim().ToLowerInvariant()
- if ($LASTEXITCODE -ne 0 -or $head -notmatch '^[0-9a-f]{40}$') {
- throw "Unable to resolve package commit"
- }
- if ($Requested) {
- $requestedCommit = $Requested.Trim().ToLowerInvariant()
- if ($requestedCommit -notmatch '^[0-9a-f]{40}$') {
- throw "Commit must be a 40-digit lowercase Git object id"
- }
- if ($requestedCommit -ne $head) {
- throw "Explicit Commit does not match repository HEAD"
- }
- }
- return $head
- }
- function Resolve-RepoRelativePath([string]$Path, [string]$Label) {
- $repoFull = [System.IO.Path]::GetFullPath($repo).TrimEnd('\') + '\'
- $pathFull = [System.IO.Path]::GetFullPath($Path)
- if (-not $pathFull.StartsWith($repoFull, [System.StringComparison]::OrdinalIgnoreCase)) {
- throw "$Label must be inside the repository and tracked by HEAD"
- }
- return $pathFull.Substring($repoFull.Length).Replace('\', '/')
- }
- function Assert-CleanCommittedSources(
- [string]$Git,
- [string]$ResolvedCommit,
- [string[]]$Relatives
- ) {
- & $Git -C $repo diff --quiet --exit-code $ResolvedCommit -- . ":(exclude).planning/**"
- $diffExit = $LASTEXITCODE
- if ($diffExit -eq 1) { throw "repository has tracked source changes outside .planning/" }
- if ($diffExit -ne 0) { throw "unable to verify repository tracked source state" }
- $statusLines = @(& $Git -C $repo status --porcelain=v1 --untracked-files=all)
- if ($LASTEXITCODE -ne 0) { throw "unable to verify repository untracked source state" }
- $unexpected = @(
- $statusLines | Where-Object {
- $relative = ([string]$_).Substring(3).Replace('\', '/')
- -not ($relative -eq ".planning" -or $relative.StartsWith(".planning/"))
- }
- )
- if ($unexpected.Count -gt 0) {
- throw ("repository has untracked or modified files outside .planning/: " + ($unexpected -join ", "))
- }
- foreach ($relative in $Relatives) {
- $saved = $ErrorActionPreference
- $ErrorActionPreference = "SilentlyContinue"
- & $Git -C $repo cat-file -e "$ResolvedCommit`:$relative" 2>$null
- $objectExit = $LASTEXITCODE
- $ErrorActionPreference = $saved
- if ($objectExit -ne 0) {
- throw "package source file is not tracked by HEAD: $relative"
- }
- }
- }
- function Assert-PrimaryPinBinding([object]$Receipt) {
- $gate = Get-PropertyValue $Receipt "post_route_pin_gate"
- if ($null -eq $gate -or [string](Get-PropertyValue $gate "status") -ne "pass") {
- throw "Primary TD pin gate is not pass"
- }
- if ([int](Get-PropertyValue $gate "row_count") -ne 41) {
- throw "Primary TD pin gate row count is not 41"
- }
- $failures = @(Get-PropertyValue $gate "failures")
- if ($failures.Count -ne 0) {
- throw "Primary TD pin gate contains failures"
- }
- $observed = Get-PropertyValue $gate "observed"
- $expected = [ordered]@{
- motor_en_n = @("A10", "OUTPUT", "LVCMOS33", "NONE")
- x_step = @("C11", "OUTPUT", "LVCMOS33", "NONE")
- x_dir = @("B12", "OUTPUT", "LVCMOS33", "NONE")
- y_step = @("D15", "OUTPUT", "LVCMOS33", "NONE")
- y_dir = @("H14", "OUTPUT", "LVCMOS33", "NONE")
- x_limit_raw = @("B9", "INPUT", "LVCMOS33", "PULLUP")
- y_limit_raw = @("A11", "INPUT", "LVCMOS33", "PULLUP")
- }
- foreach ($name in $expected.Keys) {
- $record = Get-PropertyValue $observed $name
- if ($null -eq $record -or
- [string](Get-PropertyValue $record "location") -ne $expected[$name][0] -or
- [string](Get-PropertyValue $record "direction") -ne $expected[$name][1] -or
- [string](Get-PropertyValue $record "io_standard") -ne $expected[$name][2] -or
- [string](Get-PropertyValue $record "pull_type") -ne $expected[$name][3]) {
- throw "Primary TD pin binding mismatch: $name"
- }
- }
- foreach ($property in @($observed.PSObject.Properties)) {
- if ([string](Get-PropertyValue $property.Value "location") -eq "A5") {
- throw "Primary TD pin gate assigns forbidden pin A5"
- }
- }
- }
- function Assert-PrimaryReceiptBinding(
- [object]$Receipt,
- [string]$ResolvedCommit,
- [string]$BitstreamSha256
- ) {
- if ([string](Get-PropertyValue $Receipt "schema") -ne $tdReceiptSchema) {
- throw "Primary TD receipt schema mismatch"
- }
- $sourceState = Get-PropertyValue $Receipt "source_state"
- if ($null -eq $sourceState -or
- (Get-PropertyValue $sourceState "clean") -ne $true -or
- [string](Get-PropertyValue $sourceState "commit") -ne $ResolvedCommit) {
- throw "Primary TD receipt source state is not clean and commit-bound"
- }
- $sourceBinding = Get-PropertyValue $Receipt "source_binding_gate"
- if ($null -eq $sourceBinding -or
- [string](Get-PropertyValue $sourceBinding "status") -ne "pass") {
- throw "Primary TD receipt source binding gate is not pass"
- }
- $bindingGate = Get-PropertyValue $Receipt "binding_gate"
- if ($null -eq $bindingGate -or
- [string](Get-PropertyValue $bindingGate "status") -ne "pass") {
- throw "Primary TD receipt device binding gate is not pass"
- }
- $synthesisInputHash = [string](Get-PropertyValue $Receipt "synthesis_input_hash")
- if ($synthesisInputHash -notmatch '^[0-9a-f]{64}$') {
- throw "Primary TD receipt synthesis input hash is invalid"
- }
- $manifest = Get-PropertyValue $Receipt "synthesis_input_manifest"
- $manifestHash = [string](Get-PropertyValue $manifest "sha256")
- $manifestInputs = Get-PropertyValue $manifest "inputs"
- if ($null -eq $manifest -or $manifestHash -ne $synthesisInputHash -or
- $null -eq $manifestInputs -or @($manifestInputs.PSObject.Properties).Count -eq 0) {
- throw "Primary TD receipt synthesis manifest is not hash-bound"
- }
- $candidates = @()
- $direct = Get-PropertyValue $Receipt "bitstream"
- if ($null -ne $direct) { $candidates += $direct }
- $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
- $measured = Get-PropertyValue $measurements "bitstream"
- if ($null -ne $measured) { $candidates += $measured }
- $artifactBound = $false
- foreach ($candidate in $candidates) {
- $path = [string](Get-PropertyValue $candidate "path")
- $declaredHash = [string](Get-PropertyValue $candidate "sha256")
- $declaredSize = Get-PropertyValue $candidate "size"
- if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { continue }
- $item = Get-Item -LiteralPath $path
- if ($item.Length -le 0) { continue }
- if ($null -ne $declaredSize -and [int64]$declaredSize -ne $item.Length) { continue }
- if ($declaredHash -and $declaredHash -ne $BitstreamSha256) { continue }
- if ((Get-Sha256 $path) -eq $BitstreamSha256) {
- $artifactBound = $true
- break
- }
- }
- if (-not $artifactBound) {
- throw "Primary TD receipt bitstream artifact is not hash-bound"
- }
- }
- function New-CommitSourceSnapshot(
- [string]$Git,
- [string]$ResolvedCommit,
- [string[]]$Relatives,
- [string]$Destination
- ) {
- $archive = "$Destination.zip"
- $arguments = @(
- "-C", $repo,
- "archive", "--format=zip", "--output=$archive",
- $ResolvedCommit, "--"
- ) + @($Relatives)
- & $Git @arguments
- if ($LASTEXITCODE -ne 0) { throw "unable to materialize package sources from HEAD" }
- New-Item -ItemType Directory -Force -Path $Destination | Out-Null
- Expand-Archive -LiteralPath $archive -DestinationPath $Destination -Force
- Remove-Item -LiteralPath $archive -Force
- }
- function Get-Sha256([string]$Path) {
- return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
- }
- function Write-Utf8NoBom([string]$Path, [string]$Text) {
- $parent = Split-Path -Parent $Path
- if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
- [System.IO.File]::WriteAllText($Path, $Text, [System.Text.UTF8Encoding]::new($false))
- }
- function Write-Json([string]$Path, [object]$Value) {
- $text = $Value | ConvertTo-Json -Depth 20
- Write-Utf8NoBom $Path ($text + "`n")
- }
- function Read-Json([string]$Path, [string]$Label) {
- Assert-File $Path $Label
- try {
- return Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
- } catch {
- throw "$Label is not valid JSON: $Path"
- }
- }
- function Get-PropertyValue([object]$Value, [string]$Name) {
- if ($null -eq $Value) { return $null }
- $property = $Value.PSObject.Properties[$Name]
- if ($null -eq $property) { return $null }
- return $property.Value
- }
- function Normalize-ValidationStatus([object]$Value) {
- $status = [string]$Value
- if ($status -eq "pass") { return "pass" }
- if ($status -eq "running") { return "running" }
- if ($status -eq "not_run" -or $status -eq "skipped" -or $status.StartsWith("blocked")) {
- return "not_run"
- }
- return "fail"
- }
- function Get-ValidationStatusRank([string]$Status) {
- switch ($Status) {
- "fail" { return 4 }
- "running" { return 3 }
- "not_run" { return 2 }
- "pass" { return 1 }
- default { return 4 }
- }
- }
- function New-ValidationLayer([string]$Status, [string]$Source, [object]$OriginalStatus) {
- return [ordered]@{
- status = $Status
- source = $Source
- original_status = if ($null -eq $OriginalStatus) { $null } else { [string]$OriginalStatus }
- }
- }
- function Set-ValidationLayer(
- [System.Collections.IDictionary]$Layers,
- [string]$Name,
- [object]$Status,
- [string]$Source
- ) {
- $newLayer = New-ValidationLayer (Normalize-ValidationStatus $Status) $Source $Status
- $existing = $Layers[$Name]
- if ($null -eq $existing -or
- [string]$existing.source -eq "not_provided" -or
- ([string]$existing.source -eq "declared_running" -and $Source -ne "declared_running")) {
- $Layers[$Name] = $newLayer
- return
- }
- if ((Get-ValidationStatusRank $newLayer.status) -gt
- (Get-ValidationStatusRank ([string]$existing.status))) {
- $Layers[$Name] = $newLayer
- }
- }
- function Test-VerificationComplete(
- [System.Collections.IDictionary]$Layers,
- [string]$DeliveryMode
- ) {
- if ($DeliveryMode -ne "normal_dual_td") { return $false }
- foreach ($name in $verificationEvidenceLayers) {
- if ([string]$Layers[$name].status -ne "pass") { return $false }
- }
- return $true
- }
- function Get-ValidationSummaryStatus([System.Collections.IDictionary]$Layers) {
- $statuses = @($Layers.Values | ForEach-Object { [string]$_.status })
- if ($statuses -contains "fail") { return "fail" }
- if ($statuses -contains "running") { return "running" }
- if ($statuses -contains "not_run") { return "not_run" }
- return "pass"
- }
- function Merge-ValidationReceipt(
- [System.Collections.IDictionary]$Layers,
- [object]$Receipt,
- [string]$Source
- ) {
- $schema = [string](Get-PropertyValue $Receipt "schema")
- if ($schema -eq "prod2u-p4-normal-v3-strict-offline-gate-v1") {
- $children = Get-PropertyValue $Receipt "layers"
- if ($null -ne $children) {
- $unit = Get-PropertyValue $children "unit"
- if ($null -ne $unit) {
- Set-ValidationLayer $Layers "python" (Get-PropertyValue $unit "status") $Source
- }
- $formal = Get-PropertyValue $children "formal"
- if ($null -ne $formal) {
- Set-ValidationLayer $Layers "formal" (Get-PropertyValue $formal "status") $Source
- }
- $hdl = Get-PropertyValue $children "hdl_sim"
- if ($null -ne $hdl) {
- $backendResults = Get-PropertyValue $hdl "backend_results"
- foreach ($backend in @("icarus", "verilator", "cocotb")) {
- $child = Get-PropertyValue $backendResults $backend
- if ($null -ne $child) {
- Set-ValidationLayer $Layers $backend (Get-PropertyValue $child "status") $Source
- }
- }
- }
- }
- return
- }
- $layer = [string](Get-PropertyValue $Receipt "verification_layer")
- $status = Get-PropertyValue $Receipt "status"
- if ($layer -eq "formal") {
- Set-ValidationLayer $Layers "formal" $status $Source
- } elseif ($layer -eq "unit") {
- Set-ValidationLayer $Layers "python" $status $Source
- } elseif ($layer -eq "hdl_sim") {
- $backend = [string](Get-PropertyValue $Receipt "backend")
- if ($backend -in @("icarus", "verilator", "cocotb")) {
- Set-ValidationLayer $Layers $backend $status $Source
- } elseif ($backend -eq "all") {
- $backendResults = Get-PropertyValue $Receipt "backend_results"
- foreach ($name in @("icarus", "verilator", "cocotb")) {
- $child = Get-PropertyValue $backendResults $name
- if ($null -ne $child) {
- Set-ValidationLayer $Layers $name (Get-PropertyValue $child "status") $Source
- }
- }
- }
- } elseif ($schema -eq "prod2u-p4-normal-v3-package-selftest-v1") {
- Set-ValidationLayer $Layers "package_selftest" $status $Source
- }
- }
- function Get-ResourceStatus([object]$Receipt) {
- $structural = Get-PropertyValue $Receipt "structural_gate"
- $resources = Get-PropertyValue $structural "resources"
- $status = Get-PropertyValue $resources "status"
- if ($null -ne $status) { return $status }
- $resourceGate = Get-PropertyValue $Receipt "resource_gate"
- $status = Get-PropertyValue $resourceGate "status"
- if ($null -ne $status) { return $status }
- return "not_run"
- }
- function Get-ComparisonStatus([object]$Observed, [object]$Expected) {
- if ($null -eq $Observed -or [string]$Observed -eq "") { return "not_run" }
- if ([string]$Observed -eq [string]$Expected) { return "pass" }
- return "fail"
- }
- function Get-TdBitstreamBindingStatus([object]$Receipt) {
- $digest = [string](Get-PropertyValue $Receipt "bitstream_sha256")
- if (-not $digest) { return "not_run" }
- if ($digest -notmatch '^[0-9a-f]{64}$') { return "fail" }
- $candidates = @()
- $direct = Get-PropertyValue $Receipt "bitstream"
- if ($null -ne $direct) { $candidates += $direct }
- $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
- $measured = Get-PropertyValue $measurements "bitstream"
- if ($null -ne $measured) { $candidates += $measured }
- foreach ($candidate in $candidates) {
- $path = [string](Get-PropertyValue $candidate "path")
- $expected = [string](Get-PropertyValue $candidate "sha256")
- if ($expected -ne $digest) { continue }
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ((Get-Sha256 $path) -eq $digest) { return "pass" }
- }
- }
- return "fail"
- }
- function Copy-TdArtifacts(
- [object]$Receipt,
- [string]$Destination,
- [string]$PackageRelativeRoot
- ) {
- New-Item -ItemType Directory -Force -Path $Destination | Out-Null
- $records = [ordered]@{}
- $artifacts = Get-PropertyValue $Receipt "measurement_artifacts"
- if ($null -eq $artifacts) { return $records }
- foreach ($property in @($artifacts.PSObject.Properties)) {
- $name = [string]$property.Name
- if ($name -eq "bitstream") { continue }
- $metadata = $property.Value
- $source = [string](Get-PropertyValue $metadata "path")
- $expectedHash = [string](Get-PropertyValue $metadata "sha256")
- $record = [ordered]@{
- status = "fail"
- source_path = $source
- expected_sha256 = $expectedHash
- package_path = $null
- observed_sha256 = $null
- }
- if (Test-Path -LiteralPath $source -PathType Leaf) {
- $observed = Get-Sha256 $source
- $record.observed_sha256 = $observed
- if ($expectedHash -match '^[0-9a-f]{64}$' -and $observed -eq $expectedHash) {
- $safeName = ($name -replace '[^A-Za-z0-9_.-]', '_')
- $extension = [System.IO.Path]::GetExtension($source)
- if (-not $extension) { $extension = ".bin" }
- $fileName = "$safeName$extension"
- $target = Join-Path $Destination $fileName
- Copy-Item -LiteralPath $source -Destination $target
- $record.status = "pass"
- $record.package_path = "$PackageRelativeRoot/$fileName"
- }
- }
- $records[$name] = $record
- }
- return $records
- }
- function Get-ArtifactValidationStatus([System.Collections.IDictionary]$Records) {
- if ($Records.Count -eq 0) { return "not_run" }
- foreach ($record in $Records.Values) {
- if ([string]$record.status -ne "pass") { return "fail" }
- }
- return "pass"
- }
- function Copy-TdPinGate(
- [object]$Receipt,
- [string]$Destination,
- [string]$PackageRelativePath
- ) {
- $pinGate = Get-PropertyValue $Receipt "post_route_pin_gate"
- if ($null -eq $pinGate) {
- return [ordered]@{ status = "not_run"; package_path = $null; sha256 = $null }
- }
- Write-Json $Destination $pinGate
- return [ordered]@{
- status = "pass"
- package_path = $PackageRelativePath
- sha256 = Get-Sha256 $Destination
- }
- }
- function Get-PackageFileHashes([string]$Root) {
- $result = [ordered]@{}
- Get-ChildItem -LiteralPath $Root -Recurse -File | Sort-Object FullName | ForEach-Object {
- $relative = $_.FullName.Substring($Root.Length).TrimStart('\').Replace('\', '/')
- if ($relative -notin @("package-info.json", "evidence/package-selftest-result.json")) {
- $result[$relative] = Get-Sha256 $_.FullName
- }
- }
- return $result
- }
- function Invoke-FolderSelftest([string]$Root) {
- $savedErrorActionPreference = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- $output = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Root "selftest.ps1") 2>&1 | Out-String
- $returnCode = $LASTEXITCODE
- } catch {
- $output = $_ | Out-String
- $returnCode = if ($LASTEXITCODE) { $LASTEXITCODE } else { 1 }
- } finally {
- $ErrorActionPreference = $savedErrorActionPreference
- }
- return [ordered]@{
- schema = "prod2u-p4-normal-v3-package-selftest-result-v1"
- status = if ($returnCode -eq 0) { "pass" } else { "fail" }
- returncode = $returnCode
- output = $output.Trim()
- }
- }
- Assert-NonEmptyFile $NormalBitstream "Normal bitstream"
- Assert-File $TdReceipt "Primary TD build receipt"
- $deliveryMode = if ($UrgentSingleTd) { "urgent_single_td" } else { "normal_dual_td" }
- $confirmationTdPresent = -not [string]::IsNullOrWhiteSpace($ConfirmationTdReceipt)
- if ($UrgentSingleTd) {
- if ($confirmationTdPresent) {
- throw "Urgent single-TD mode must not include a Confirmation TD build receipt"
- }
- } else {
- if (-not $confirmationTdPresent) {
- throw "Confirmation TD build receipt is required in normal dual-TD mode"
- }
- Assert-File $ConfirmationTdReceipt "Confirmation TD build receipt"
- }
- Assert-File $HostContract "Normal v3 host contract"
- foreach ($receipt in $ValidationReceipt) {
- Assert-File $receipt "Validation receipt"
- }
- $hostContractRelative = Resolve-RepoRelativePath $HostContract "Normal v3 host contract"
- $sourceRelatives = @(
- $packageScriptRelative,
- $readmeSourceRelative,
- $hostContractSchemaRelative,
- $hostContractRelative,
- $hardwareBindingRelative,
- $verificationTargetsRelative
- ) + $templateRelatives | Sort-Object -Unique
- foreach ($relative in $sourceRelatives) {
- Assert-File (Join-Path $repo $relative) "Package source $relative"
- }
- $resolvedCommit = Resolve-Commit $Commit
- $git = Resolve-Git
- Assert-CleanCommittedSources $git $resolvedCommit $sourceRelatives
- $bitstreamSha256 = Get-Sha256 $NormalBitstream
- $tdPrimary = Read-Json $TdReceipt "Primary TD build receipt"
- if ([string](Get-PropertyValue $tdPrimary "commit") -ne $resolvedCommit) {
- throw "Primary TD receipt commit does not match package commit"
- }
- if ([string](Get-PropertyValue $tdPrimary "verification_run_id") -ne $VerificationRunId) {
- throw "Primary TD receipt verification_run_id mismatch"
- }
- if ([string](Get-PropertyValue $tdPrimary "bitstream_sha256") -ne $bitstreamSha256) {
- throw "Primary TD receipt bitstream hash does not match package bitstream"
- }
- Assert-PrimaryReceiptBinding $tdPrimary $resolvedCommit $bitstreamSha256
- Assert-PrimaryPinBinding $tdPrimary
- $synthesisInputHash = [string](Get-PropertyValue $tdPrimary "synthesis_input_hash")
- $primaryManifest = Get-PropertyValue $tdPrimary "synthesis_input_manifest"
- $primaryManifestSha256 = Get-PropertyValue $primaryManifest "sha256"
- $tdConfirmation = $null
- $confirmationBitstreamSha256 = $null
- $confirmationSynthesisInputHash = $null
- $confirmationManifestSha256 = $null
- if ($confirmationTdPresent) {
- $tdConfirmation = Read-Json $ConfirmationTdReceipt "Confirmation TD build receipt"
- $confirmationCommit = [string](Get-PropertyValue $tdConfirmation "commit")
- if ($confirmationCommit -ne $resolvedCommit) {
- throw "Confirmation TD receipt commit does not match package commit"
- }
- if ([string](Get-PropertyValue $tdConfirmation "verification_run_id") -ne $VerificationRunId) {
- throw "Confirmation TD receipt verification_run_id mismatch"
- }
- $confirmationBitstreamSha256 = Get-PropertyValue $tdConfirmation "bitstream_sha256"
- if ($confirmationBitstreamSha256 -and
- [string]$confirmationBitstreamSha256 -ne $bitstreamSha256) {
- throw "Confirmation TD receipt bitstream hash does not match primary"
- }
- $confirmationSynthesisInputHash = Get-PropertyValue $tdConfirmation "synthesis_input_hash"
- $confirmationManifest = Get-PropertyValue $tdConfirmation "synthesis_input_manifest"
- $confirmationManifestSha256 = Get-PropertyValue $confirmationManifest "sha256"
- $primaryRunId = [string](Get-PropertyValue $tdPrimary "run_id")
- $confirmationRunId = [string](Get-PropertyValue $tdConfirmation "run_id")
- if ($primaryRunId -notmatch '^[0-9a-f]{32}$' -or
- $confirmationRunId -notmatch '^[0-9a-f]{32}$' -or
- $primaryRunId -eq $confirmationRunId) {
- throw "Primary and confirmation TD run_id must differ"
- }
- $primaryWorkRoot = [string](Get-PropertyValue $tdPrimary "work_root")
- $confirmationWorkRoot = [string](Get-PropertyValue $tdConfirmation "work_root")
- if ([string]::IsNullOrWhiteSpace($primaryWorkRoot) -or
- [string]::IsNullOrWhiteSpace($confirmationWorkRoot) -or
- $primaryWorkRoot -cnotmatch '^[A-Za-z]:[\\/]' -or
- $confirmationWorkRoot -cnotmatch '^[A-Za-z]:[\\/]' -or
- [string]::Equals(
- [System.IO.Path]::GetFullPath($primaryWorkRoot).TrimEnd('\'),
- [System.IO.Path]::GetFullPath($confirmationWorkRoot).TrimEnd('\'),
- [System.StringComparison]::OrdinalIgnoreCase
- )) {
- throw "Primary and confirmation TD work_root must differ"
- }
- }
- $outFull = [System.IO.Path]::GetFullPath($OutputDir)
- $commitRoot = Join-Path $outFull $resolvedCommit
- New-Item -ItemType Directory -Force -Path $commitRoot | Out-Null
- $packageName = "prod2u-p4-normal-$resolvedCommit-$($bitstreamSha256.Substring(0, 16))"
- $final = Join-Path $commitRoot $packageName
- if (Test-Path -LiteralPath $final) { throw "Package folder already exists: $final" }
- $stage = Join-Path $commitRoot (".prod2u-p4-normal-stage-" + [Guid]::NewGuid().ToString("N"))
- New-Item -ItemType Directory -Path $stage | Out-Null
- try {
- $sourceSnapshot = Join-Path $stage ".source-snapshot"
- New-CommitSourceSnapshot $git $resolvedCommit $sourceRelatives $sourceSnapshot
- $configDir = Join-Path $stage "config"
- $evidenceDir = Join-Path $stage "evidence"
- $validationDir = Join-Path $evidenceDir "validation"
- $schemaDir = Join-Path $stage "schemas"
- foreach ($directory in @($configDir, $evidenceDir, $validationDir, $schemaDir)) {
- New-Item -ItemType Directory -Force -Path $directory | Out-Null
- }
- $packagedBitstream = Join-Path $stage "fw.bit"
- $packagedPrimaryReceipt = Join-Path $evidenceDir "td-primary-receipt.json"
- $packagedConfirmationReceipt = Join-Path $evidenceDir "td-confirmation-receipt.json"
- Copy-Item -LiteralPath $NormalBitstream -Destination $packagedBitstream
- Copy-Item -LiteralPath $TdReceipt -Destination $packagedPrimaryReceipt
- if ($confirmationTdPresent) {
- Copy-Item -LiteralPath $ConfirmationTdReceipt -Destination $packagedConfirmationReceipt
- }
- Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractRelative) -Destination (Join-Path $configDir "host-contract.json")
- Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hardwareBindingRelative) -Destination (Join-Path $configDir "prod2u_p4_normal_v3_hw_binding.json")
- Copy-Item -LiteralPath (Join-Path $sourceSnapshot $verificationTargetsRelative) -Destination (Join-Path $configDir "prod2u_p4_verification_targets_v1.json")
- Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractSchemaRelative) -Destination (Join-Path $schemaDir "host-contract.schema.json")
- $templateRoot = Join-Path $sourceSnapshot "tools\package_templates"
- foreach ($template in @(
- "bootstrap.ps1",
- "selftest.ps1",
- "run.ps1",
- "SEND_HEX.ps1",
- "INITIALIZE_DISABLE.ps1",
- "PROGRAM_SRAM.ps1"
- )) {
- Copy-Item -LiteralPath (Join-Path $templateRoot $template) -Destination (Join-Path $stage $template)
- }
- $readme = [System.IO.File]::ReadAllText(
- (Join-Path $sourceSnapshot $readmeSourceRelative),
- [System.Text.Encoding]::UTF8
- )
- Write-Utf8NoBom (Join-Path $stage "README.zh-CN.md") ($readme + "`r`n")
- Remove-Item -LiteralPath $sourceSnapshot -Recurse -Force
- $layers = [ordered]@{}
- foreach ($name in $validationLayerNames) {
- $layers[$name] = New-ValidationLayer "not_run" "not_provided" "not_run"
- }
- foreach ($name in $RunningValidationLayer) {
- Set-ValidationLayer $layers $name "running" "declared_running"
- }
- Set-ValidationLayer $layers "td_primary" (Get-PropertyValue $tdPrimary "status") "evidence/td-primary-receipt.json"
- Set-ValidationLayer $layers "resource_primary" (Get-ResourceStatus $tdPrimary) "evidence/td-primary-receipt.json"
- if ($confirmationTdPresent) {
- Set-ValidationLayer $layers "td_confirmation" (Get-PropertyValue $tdConfirmation "status") "evidence/td-confirmation-receipt.json"
- Set-ValidationLayer $layers "resource_confirmation" (Get-ResourceStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
- Set-ValidationLayer $layers "td_confirmation_bitstream" (Get-TdBitstreamBindingStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
- Set-ValidationLayer $layers "td_confirmation_synthesis" (Get-ComparisonStatus $confirmationSynthesisInputHash $synthesisInputHash) "evidence/td-confirmation-receipt.json"
- Set-ValidationLayer $layers "td_confirmation_manifest" (Get-ComparisonStatus $confirmationManifestSha256 $primaryManifestSha256) "evidence/td-confirmation-receipt.json"
- }
- $primaryArtifacts = Copy-TdArtifacts $tdPrimary (Join-Path $evidenceDir "td-primary") "evidence/td-primary"
- $primaryPinGate = Copy-TdPinGate $tdPrimary (Join-Path $evidenceDir "td-primary\pin-gate.json") "evidence/td-primary/pin-gate.json"
- $primaryArtifacts["pin_gate"] = $primaryPinGate
- $layers["td_primary"]["artifacts"] = $primaryArtifacts
- Set-ValidationLayer $layers "td_primary_artifacts" (Get-ArtifactValidationStatus $primaryArtifacts) "evidence/td-primary"
- if ($confirmationTdPresent) {
- $confirmationArtifacts = Copy-TdArtifacts $tdConfirmation (Join-Path $evidenceDir "td-confirmation") "evidence/td-confirmation"
- $confirmationPinGate = Copy-TdPinGate $tdConfirmation (Join-Path $evidenceDir "td-confirmation\pin-gate.json") "evidence/td-confirmation/pin-gate.json"
- $confirmationArtifacts["pin_gate"] = $confirmationPinGate
- $layers["td_confirmation"]["artifacts"] = $confirmationArtifacts
- Set-ValidationLayer $layers "td_confirmation_artifacts" (Get-ArtifactValidationStatus $confirmationArtifacts) "evidence/td-confirmation"
- }
- $validationSources = @()
- $validationIndex = 0
- foreach ($receiptPath in $ValidationReceipt) {
- $validationIndex += 1
- $receipt = Read-Json $receiptPath "Validation receipt"
- $receiptCommit = Get-PropertyValue $receipt "commit"
- if ($null -ne $receiptCommit -and [string]$receiptCommit -ne $resolvedCommit) {
- throw "Validation receipt commit does not match package commit"
- }
- if ([string](Get-PropertyValue $receipt "verification_run_id") -ne $VerificationRunId) {
- throw "Validation receipt verification_run_id mismatch"
- }
- $base = [System.IO.Path]::GetFileNameWithoutExtension($receiptPath) -replace '[^A-Za-z0-9_.-]', '_'
- $fileName = ("{0:D2}-{1}.json" -f $validationIndex, $base)
- $target = Join-Path $validationDir $fileName
- Copy-Item -LiteralPath $receiptPath -Destination $target
- $relative = "evidence/validation/$fileName"
- $validationSources += [ordered]@{
- path = $relative
- sha256 = Get-Sha256 $target
- schema = Get-PropertyValue $receipt "schema"
- status = Get-PropertyValue $receipt "status"
- verification_run_id = $VerificationRunId
- }
- Merge-ValidationReceipt $layers $receipt $relative
- }
- $verificationComplete = Test-VerificationComplete $layers $deliveryMode
- $validationSummaryPath = Join-Path $evidenceDir "validation-summary.json"
- $validationSummary = [ordered]@{
- schema = "prod2u-p4-normal-v3-validation-summary-v1"
- verification_run_id = $VerificationRunId
- commit = $resolvedCommit
- bitstream_sha256 = $bitstreamSha256
- delivery_mode = $deliveryMode
- verification_complete = $verificationComplete
- confirmation_td_present = $confirmationTdPresent
- layers = $layers
- sources = @($validationSources)
- policy = [ordered]@{
- image_created_when_bitstream_nonempty = $true
- validation_failures_block_package = $false
- allowed_statuses = @("pass", "fail", "running", "not_run")
- }
- }
- Write-Json $validationSummaryPath $validationSummary
- $selftestResultPath = Join-Path $evidenceDir "package-selftest-result.json"
- $provisionalSelftest = [ordered]@{
- schema = "prod2u-p4-normal-v3-package-selftest-result-v1"
- status = "not_run"
- returncode = $null
- output = ""
- }
- Write-Json $selftestResultPath $provisionalSelftest
- $packageInfoPath = Join-Path $stage "package-info.json"
- $packageInfo = [ordered]@{
- schema = "prod2u-p4-normal-v3-folder-package-info-v3"
- profile = "prod2u-p4-normal-actuator-binary921-v3"
- verification_run_id = $VerificationRunId
- commit = $resolvedCommit
- bitstream_sha256 = $bitstreamSha256
- delivery_mode = $deliveryMode
- verification_complete = $verificationComplete
- confirmation_td_present = $confirmationTdPresent
- confirmation_bitstream_sha256 = $confirmationBitstreamSha256
- td_receipt_sha256 = Get-Sha256 $packagedPrimaryReceipt
- confirmation_td_receipt_sha256 = if ($confirmationTdPresent) { Get-Sha256 $packagedConfirmationReceipt } else { $null }
- validation_summary_sha256 = Get-Sha256 $validationSummaryPath
- package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
- synthesis_input_hash = $synthesisInputHash
- confirmation_synthesis_input_hash = $confirmationSynthesisInputHash
- file_sha256 = Get-PackageFileHashes $stage
- }
- Write-Json $packageInfoPath $packageInfo
- $selftestResult = Invoke-FolderSelftest $stage
- Set-ValidationLayer $layers "package_selftest" $selftestResult.status "evidence/package-selftest-result.json"
- Write-Json $validationSummaryPath $validationSummary
- Write-Json $selftestResultPath $selftestResult
- $packageInfo.validation_summary_sha256 = Get-Sha256 $validationSummaryPath
- $packageInfo.package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
- $packageInfo.file_sha256 = Get-PackageFileHashes $stage
- Write-Json $packageInfoPath $packageInfo
- $finalSelftest = Invoke-FolderSelftest $stage
- if ($finalSelftest.status -ne "pass") {
- Set-ValidationLayer $layers "package_selftest" "fail" "evidence/package-selftest-result.json"
- Write-Json $validationSummaryPath $validationSummary
- Write-Json $selftestResultPath $finalSelftest
- $packageInfo.validation_summary_sha256 = Get-Sha256 $validationSummaryPath
- $packageInfo.package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
- $packageInfo.file_sha256 = Get-PackageFileHashes $stage
- Write-Json $packageInfoPath $packageInfo
- $selftestResult = $finalSelftest
- }
- Move-Item -LiteralPath $stage -Destination $final
- $stage = $null
- [ordered]@{
- schema = "prod2u-p4-normal-v3-folder-package-v3"
- status = "pass"
- package = $final
- verification_run_id = $VerificationRunId
- commit = $resolvedCommit
- bitstream_sha256 = $bitstreamSha256
- delivery_mode = $deliveryMode
- verification_complete = $verificationComplete
- confirmation_td_present = $confirmationTdPresent
- validation_status = Get-ValidationSummaryStatus $layers
- package_selftest_status = $selftestResult.status
- } | ConvertTo-Json -Compress
- } finally {
- if ($stage -and (Test-Path -LiteralPath $stage)) {
- Remove-Item -LiteralPath $stage -Recurse -Force
- }
- }
|