package_prod2u_p4_normal_v3.ps1 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. param(
  2. [Parameter(Mandatory = $true)][string]$OutputDir,
  3. [Parameter(Mandatory = $true)][string]$NormalBitstream,
  4. [Parameter(Mandatory = $true)][string]$TdReceipt,
  5. [Parameter(Mandatory = $true)][ValidatePattern('^[0-9a-f]{32}$')][string]$VerificationRunId,
  6. [AllowEmptyString()][string]$ConfirmationTdReceipt = "",
  7. [string[]]$ValidationReceipt = @(),
  8. [string]$HostContract = "",
  9. [string]$Commit = "",
  10. [string]$WheelhouseRoot = "",
  11. [ValidateSet("python", "icarus", "verilator", "cocotb", "formal", "td_confirmation")]
  12. [string[]]$RunningValidationLayer = @(),
  13. [switch]$UrgentSingleTd
  14. )
  15. Set-StrictMode -Version Latest
  16. $ErrorActionPreference = "Stop"
  17. $repo = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
  18. $packageScriptRelative = "tools/package_prod2u_p4_normal_v3.ps1"
  19. $readmeSourceRelative = "docs/prod2u-p4-normal-v3-runbook.zh-CN.md"
  20. $hostContractSchemaRelative = "schemas/prod2u_p4_normal_host_contract_v4.schema.json"
  21. $hardwareBindingRelative = "config/prod2u_p4_normal_v3_hw_binding.json"
  22. $verificationTargetsRelative = "config/prod2u_p4_verification_targets_v1.json"
  23. $tdReceiptSchema = "prod2u-p4-normal-v3-td-build-receipt-v2"
  24. $validationLayerNames = @(
  25. "python", "icarus", "verilator", "cocotb", "formal",
  26. "td_primary", "td_confirmation", "td_primary_artifacts",
  27. "td_confirmation_artifacts", "td_confirmation_bitstream",
  28. "td_confirmation_synthesis", "td_confirmation_manifest",
  29. "resource_primary", "resource_confirmation", "package_selftest"
  30. )
  31. $verificationEvidenceLayers = @(
  32. "python", "icarus", "verilator", "cocotb", "formal",
  33. "td_primary", "td_confirmation", "td_primary_artifacts",
  34. "td_confirmation_artifacts", "td_confirmation_bitstream",
  35. "td_confirmation_synthesis", "td_confirmation_manifest",
  36. "resource_primary", "resource_confirmation"
  37. )
  38. $templateRelatives = @(
  39. "tools/package_templates/bootstrap.ps1",
  40. "tools/package_templates/selftest.ps1",
  41. "tools/package_templates/run.ps1",
  42. "tools/package_templates/SEND_HEX.ps1",
  43. "tools/package_templates/INITIALIZE_DISABLE.ps1",
  44. "tools/package_templates/PROGRAM_SRAM.ps1"
  45. )
  46. if (-not $HostContract) {
  47. $HostContract = Join-Path $repo "config\prod2u_p4_normal_host_contract_v4.json"
  48. }
  49. function Assert-File([string]$Path, [string]$Label) {
  50. if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
  51. throw "$Label is missing: $Path"
  52. }
  53. }
  54. function Assert-NonEmptyFile([string]$Path, [string]$Label) {
  55. Assert-File $Path $Label
  56. if ((Get-Item -LiteralPath $Path).Length -le 0) {
  57. throw "$Label is empty: $Path"
  58. }
  59. }
  60. function Resolve-Git {
  61. $git = Get-Command git.exe -ErrorAction SilentlyContinue
  62. if (-not $git) { $git = Get-Command git -ErrorAction SilentlyContinue }
  63. if (-not $git) { throw "Git is required to bind the package commit" }
  64. return $git.Source
  65. }
  66. function Resolve-Commit([string]$Requested) {
  67. $git = Resolve-Git
  68. $headFull = (& $git -C $repo rev-parse HEAD).Trim().ToLowerInvariant()
  69. if ($LASTEXITCODE -ne 0 -or $headFull -cnotmatch '^[0-9a-f]{40}$') {
  70. throw "Unable to resolve package commit"
  71. }
  72. $headShort = $headFull.Substring(0, 8)
  73. if ($Requested) {
  74. $requestedCommit = $Requested
  75. if ($requestedCommit -cnotmatch '^[0-9a-f]{8}$') {
  76. throw "Commit must be an 8-digit lowercase Git object id"
  77. }
  78. if ($requestedCommit -cne $headShort) {
  79. throw "Explicit Commit does not match repository HEAD"
  80. }
  81. }
  82. return [ordered]@{
  83. full = $headFull
  84. short = $headShort
  85. }
  86. }
  87. function Resolve-RepoRelativePath([string]$Path, [string]$Label) {
  88. $repoFull = [System.IO.Path]::GetFullPath($repo).TrimEnd('\') + '\'
  89. $pathFull = [System.IO.Path]::GetFullPath($Path)
  90. if (-not $pathFull.StartsWith($repoFull, [System.StringComparison]::OrdinalIgnoreCase)) {
  91. throw "$Label must be inside the repository and tracked by HEAD"
  92. }
  93. return $pathFull.Substring($repoFull.Length).Replace('\', '/')
  94. }
  95. function Assert-CleanCommittedSources(
  96. [string]$Git,
  97. [string]$ResolvedCommit,
  98. [string[]]$Relatives
  99. ) {
  100. & $Git -C $repo diff --quiet --exit-code $ResolvedCommit -- . ":(exclude).planning/**"
  101. $diffExit = $LASTEXITCODE
  102. if ($diffExit -eq 1) { throw "repository has tracked source changes outside .planning/" }
  103. if ($diffExit -ne 0) { throw "unable to verify repository tracked source state" }
  104. $statusLines = @(& $Git -C $repo status --porcelain=v1 --untracked-files=all)
  105. if ($LASTEXITCODE -ne 0) { throw "unable to verify repository untracked source state" }
  106. $unexpected = @(
  107. $statusLines | Where-Object {
  108. $relative = ([string]$_).Substring(3).Replace('\', '/')
  109. -not ($relative -eq ".planning" -or $relative.StartsWith(".planning/"))
  110. }
  111. )
  112. if ($unexpected.Count -gt 0) {
  113. throw ("repository has untracked or modified files outside .planning/: " + ($unexpected -join ", "))
  114. }
  115. foreach ($relative in $Relatives) {
  116. $saved = $ErrorActionPreference
  117. $ErrorActionPreference = "SilentlyContinue"
  118. & $Git -C $repo cat-file -e "$ResolvedCommit`:$relative" 2>$null
  119. $objectExit = $LASTEXITCODE
  120. $ErrorActionPreference = $saved
  121. if ($objectExit -ne 0) {
  122. throw "package source file is not tracked by HEAD: $relative"
  123. }
  124. }
  125. }
  126. function Assert-PrimaryPinBinding([object]$Receipt) {
  127. $gate = Get-PropertyValue $Receipt "post_route_pin_gate"
  128. if ($null -eq $gate -or [string](Get-PropertyValue $gate "status") -ne "pass") {
  129. throw "Primary TD pin gate is not pass"
  130. }
  131. if ([int](Get-PropertyValue $gate "row_count") -ne 43) {
  132. throw "Primary TD pin gate row count is not 43"
  133. }
  134. $failures = @(Get-PropertyValue $gate "failures")
  135. if ($failures.Count -ne 0) {
  136. throw "Primary TD pin gate contains failures"
  137. }
  138. $observed = Get-PropertyValue $gate "observed"
  139. $expected = [ordered]@{
  140. motor_en_n = @("A10", "OUTPUT", "LVCMOS33", "NONE")
  141. x_step = @("C11", "OUTPUT", "LVCMOS33", "NONE")
  142. x_dir = @("B12", "OUTPUT", "LVCMOS33", "NONE")
  143. y_step = @("D15", "OUTPUT", "LVCMOS33", "NONE")
  144. y_dir = @("H14", "OUTPUT", "LVCMOS33", "NONE")
  145. x_limit_raw = @("B9", "INPUT", "LVCMOS33", "PULLUP")
  146. y_limit_raw = @("A11", "INPUT", "LVCMOS33", "PULLUP")
  147. }
  148. foreach ($name in $expected.Keys) {
  149. $record = Get-PropertyValue $observed $name
  150. if ($null -eq $record -or
  151. [string](Get-PropertyValue $record "location") -ne $expected[$name][0] -or
  152. [string](Get-PropertyValue $record "direction") -ne $expected[$name][1] -or
  153. [string](Get-PropertyValue $record "io_standard") -ne $expected[$name][2] -or
  154. [string](Get-PropertyValue $record "pull_type") -ne $expected[$name][3]) {
  155. throw "Primary TD pin binding mismatch: $name"
  156. }
  157. }
  158. foreach ($property in @($observed.PSObject.Properties)) {
  159. if ([string](Get-PropertyValue $property.Value "location") -eq "A5") {
  160. throw "Primary TD pin gate assigns forbidden pin A5"
  161. }
  162. }
  163. }
  164. function Assert-PrimaryReceiptBinding(
  165. [object]$Receipt,
  166. [string]$ResolvedCommit,
  167. [string]$BitstreamSha256
  168. ) {
  169. if ([string](Get-PropertyValue $Receipt "schema") -ne $tdReceiptSchema) {
  170. throw "Primary TD receipt schema mismatch"
  171. }
  172. $sourceState = Get-PropertyValue $Receipt "source_state"
  173. if ($null -eq $sourceState -or
  174. (Get-PropertyValue $sourceState "clean") -ne $true -or
  175. [string](Get-PropertyValue $sourceState "commit") -ne $ResolvedCommit) {
  176. throw "Primary TD receipt source state is not clean and commit-bound"
  177. }
  178. $sourceBinding = Get-PropertyValue $Receipt "source_binding_gate"
  179. if ($null -eq $sourceBinding -or
  180. [string](Get-PropertyValue $sourceBinding "status") -ne "pass") {
  181. throw "Primary TD receipt source binding gate is not pass"
  182. }
  183. $bindingGate = Get-PropertyValue $Receipt "binding_gate"
  184. if ($null -eq $bindingGate -or
  185. [string](Get-PropertyValue $bindingGate "status") -ne "pass") {
  186. throw "Primary TD receipt device binding gate is not pass"
  187. }
  188. $synthesisInputHash = [string](Get-PropertyValue $Receipt "synthesis_input_hash")
  189. if ($synthesisInputHash -notmatch '^[0-9a-f]{64}$') {
  190. throw "Primary TD receipt synthesis input hash is invalid"
  191. }
  192. $manifest = Get-PropertyValue $Receipt "synthesis_input_manifest"
  193. $manifestHash = [string](Get-PropertyValue $manifest "sha256")
  194. $manifestInputs = Get-PropertyValue $manifest "inputs"
  195. if ($null -eq $manifest -or $manifestHash -ne $synthesisInputHash -or
  196. $null -eq $manifestInputs -or @($manifestInputs.PSObject.Properties).Count -eq 0) {
  197. throw "Primary TD receipt synthesis manifest is not hash-bound"
  198. }
  199. $candidates = @()
  200. $direct = Get-PropertyValue $Receipt "bitstream"
  201. if ($null -ne $direct) { $candidates += $direct }
  202. $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
  203. $measured = Get-PropertyValue $measurements "bitstream"
  204. if ($null -ne $measured) { $candidates += $measured }
  205. $artifactBound = $false
  206. foreach ($candidate in $candidates) {
  207. $path = [string](Get-PropertyValue $candidate "path")
  208. $declaredHash = [string](Get-PropertyValue $candidate "sha256")
  209. $declaredSize = Get-PropertyValue $candidate "size"
  210. if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { continue }
  211. $item = Get-Item -LiteralPath $path
  212. if ($item.Length -le 0) { continue }
  213. if ($null -ne $declaredSize -and [int64]$declaredSize -ne $item.Length) { continue }
  214. if ($declaredHash -and $declaredHash -ne $BitstreamSha256) { continue }
  215. if ((Get-Sha256 $path) -eq $BitstreamSha256) {
  216. $artifactBound = $true
  217. break
  218. }
  219. }
  220. if (-not $artifactBound) {
  221. throw "Primary TD receipt bitstream artifact is not hash-bound"
  222. }
  223. }
  224. function New-CommitSourceSnapshot(
  225. [string]$Git,
  226. [string]$ResolvedCommit,
  227. [string[]]$Relatives,
  228. [string]$Destination
  229. ) {
  230. $archive = "$Destination.zip"
  231. $arguments = @(
  232. "-C", $repo,
  233. "archive", "--format=zip", "--output=$archive",
  234. $ResolvedCommit, "--"
  235. ) + @($Relatives)
  236. & $Git @arguments
  237. if ($LASTEXITCODE -ne 0) { throw "unable to materialize package sources from HEAD" }
  238. New-Item -ItemType Directory -Force -Path $Destination | Out-Null
  239. Expand-Archive -LiteralPath $archive -DestinationPath $Destination -Force
  240. Remove-Item -LiteralPath $archive -Force
  241. }
  242. function Get-Sha256([string]$Path) {
  243. return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
  244. }
  245. function Write-Utf8NoBom([string]$Path, [string]$Text) {
  246. $parent = Split-Path -Parent $Path
  247. if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
  248. [System.IO.File]::WriteAllText($Path, $Text, [System.Text.UTF8Encoding]::new($false))
  249. }
  250. function Write-Json([string]$Path, [object]$Value) {
  251. $text = $Value | ConvertTo-Json -Depth 20
  252. Write-Utf8NoBom $Path ($text + "`n")
  253. }
  254. function Read-Json([string]$Path, [string]$Label) {
  255. Assert-File $Path $Label
  256. try {
  257. return Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
  258. } catch {
  259. throw "$Label is not valid JSON: $Path"
  260. }
  261. }
  262. function Get-PropertyValue([object]$Value, [string]$Name) {
  263. if ($null -eq $Value) { return $null }
  264. $property = $Value.PSObject.Properties[$Name]
  265. if ($null -eq $property) { return $null }
  266. return $property.Value
  267. }
  268. function Normalize-ValidationStatus([object]$Value) {
  269. $status = [string]$Value
  270. if ($status -eq "pass") { return "pass" }
  271. if ($status -eq "running") { return "running" }
  272. if ($status -eq "not_run" -or $status -eq "skipped" -or $status.StartsWith("blocked")) {
  273. return "not_run"
  274. }
  275. return "fail"
  276. }
  277. function Get-ValidationStatusRank([string]$Status) {
  278. switch ($Status) {
  279. "fail" { return 4 }
  280. "running" { return 3 }
  281. "not_run" { return 2 }
  282. "pass" { return 1 }
  283. default { return 4 }
  284. }
  285. }
  286. function New-ValidationLayer([string]$Status, [string]$Source, [object]$OriginalStatus) {
  287. return [ordered]@{
  288. status = $Status
  289. source = $Source
  290. original_status = if ($null -eq $OriginalStatus) { $null } else { [string]$OriginalStatus }
  291. }
  292. }
  293. function Set-ValidationLayer(
  294. [System.Collections.IDictionary]$Layers,
  295. [string]$Name,
  296. [object]$Status,
  297. [string]$Source
  298. ) {
  299. $newLayer = New-ValidationLayer (Normalize-ValidationStatus $Status) $Source $Status
  300. $existing = $Layers[$Name]
  301. if ($null -eq $existing -or
  302. [string]$existing.source -eq "not_provided" -or
  303. ([string]$existing.source -eq "declared_running" -and $Source -ne "declared_running")) {
  304. $Layers[$Name] = $newLayer
  305. return
  306. }
  307. if ((Get-ValidationStatusRank $newLayer.status) -gt
  308. (Get-ValidationStatusRank ([string]$existing.status))) {
  309. $Layers[$Name] = $newLayer
  310. }
  311. }
  312. function Test-VerificationComplete(
  313. [System.Collections.IDictionary]$Layers,
  314. [string]$DeliveryMode
  315. ) {
  316. if ($DeliveryMode -ne "normal_dual_td") { return $false }
  317. foreach ($name in $verificationEvidenceLayers) {
  318. if ([string]$Layers[$name].status -ne "pass") { return $false }
  319. }
  320. return $true
  321. }
  322. function Get-ValidationSummaryStatus([System.Collections.IDictionary]$Layers) {
  323. $statuses = @($Layers.Values | ForEach-Object { [string]$_.status })
  324. if ($statuses -contains "fail") { return "fail" }
  325. if ($statuses -contains "running") { return "running" }
  326. if ($statuses -contains "not_run") { return "not_run" }
  327. return "pass"
  328. }
  329. function Merge-ValidationReceipt(
  330. [System.Collections.IDictionary]$Layers,
  331. [object]$Receipt,
  332. [string]$Source
  333. ) {
  334. $schema = [string](Get-PropertyValue $Receipt "schema")
  335. if ($schema -eq "prod2u-p4-normal-v3-strict-offline-gate-v1") {
  336. $children = Get-PropertyValue $Receipt "layers"
  337. if ($null -ne $children) {
  338. $unit = Get-PropertyValue $children "unit"
  339. if ($null -ne $unit) {
  340. Set-ValidationLayer $Layers "python" (Get-PropertyValue $unit "status") $Source
  341. }
  342. $formal = Get-PropertyValue $children "formal"
  343. if ($null -ne $formal) {
  344. Set-ValidationLayer $Layers "formal" (Get-PropertyValue $formal "status") $Source
  345. }
  346. $hdl = Get-PropertyValue $children "hdl_sim"
  347. if ($null -ne $hdl) {
  348. $backendResults = Get-PropertyValue $hdl "backend_results"
  349. foreach ($backend in @("icarus", "verilator", "cocotb")) {
  350. $child = Get-PropertyValue $backendResults $backend
  351. if ($null -ne $child) {
  352. Set-ValidationLayer $Layers $backend (Get-PropertyValue $child "status") $Source
  353. }
  354. }
  355. }
  356. }
  357. return
  358. }
  359. $layer = [string](Get-PropertyValue $Receipt "verification_layer")
  360. $status = Get-PropertyValue $Receipt "status"
  361. if ($layer -eq "formal") {
  362. Set-ValidationLayer $Layers "formal" $status $Source
  363. } elseif ($layer -eq "unit") {
  364. Set-ValidationLayer $Layers "python" $status $Source
  365. } elseif ($layer -eq "hdl_sim") {
  366. $backend = [string](Get-PropertyValue $Receipt "backend")
  367. if ($backend -in @("icarus", "verilator", "cocotb")) {
  368. Set-ValidationLayer $Layers $backend $status $Source
  369. } elseif ($backend -eq "all") {
  370. $backendResults = Get-PropertyValue $Receipt "backend_results"
  371. foreach ($name in @("icarus", "verilator", "cocotb")) {
  372. $child = Get-PropertyValue $backendResults $name
  373. if ($null -ne $child) {
  374. Set-ValidationLayer $Layers $name (Get-PropertyValue $child "status") $Source
  375. }
  376. }
  377. }
  378. } elseif ($schema -eq "prod2u-p4-normal-v3-package-selftest-v1") {
  379. Set-ValidationLayer $Layers "package_selftest" $status $Source
  380. }
  381. }
  382. function Get-ResourceStatus([object]$Receipt) {
  383. $structural = Get-PropertyValue $Receipt "structural_gate"
  384. $resources = Get-PropertyValue $structural "resources"
  385. $status = Get-PropertyValue $resources "status"
  386. if ($null -ne $status) { return $status }
  387. $resourceGate = Get-PropertyValue $Receipt "resource_gate"
  388. $status = Get-PropertyValue $resourceGate "status"
  389. if ($null -ne $status) { return $status }
  390. return "not_run"
  391. }
  392. function Get-ComparisonStatus([object]$Observed, [object]$Expected) {
  393. if ($null -eq $Observed -or [string]$Observed -eq "") { return "not_run" }
  394. if ([string]$Observed -eq [string]$Expected) { return "pass" }
  395. return "fail"
  396. }
  397. function Get-TdBitstreamBindingStatus([object]$Receipt) {
  398. $digest = [string](Get-PropertyValue $Receipt "bitstream_sha256")
  399. if (-not $digest) { return "not_run" }
  400. if ($digest -notmatch '^[0-9a-f]{64}$') { return "fail" }
  401. $candidates = @()
  402. $direct = Get-PropertyValue $Receipt "bitstream"
  403. if ($null -ne $direct) { $candidates += $direct }
  404. $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
  405. $measured = Get-PropertyValue $measurements "bitstream"
  406. if ($null -ne $measured) { $candidates += $measured }
  407. foreach ($candidate in $candidates) {
  408. $path = [string](Get-PropertyValue $candidate "path")
  409. $expected = [string](Get-PropertyValue $candidate "sha256")
  410. if ($expected -ne $digest) { continue }
  411. if (Test-Path -LiteralPath $path -PathType Leaf) {
  412. if ((Get-Sha256 $path) -eq $digest) { return "pass" }
  413. }
  414. }
  415. return "fail"
  416. }
  417. function Copy-TdArtifacts(
  418. [object]$Receipt,
  419. [string]$Destination,
  420. [string]$PackageRelativeRoot
  421. ) {
  422. New-Item -ItemType Directory -Force -Path $Destination | Out-Null
  423. $records = [ordered]@{}
  424. $artifacts = Get-PropertyValue $Receipt "measurement_artifacts"
  425. if ($null -eq $artifacts) { return $records }
  426. foreach ($property in @($artifacts.PSObject.Properties)) {
  427. $name = [string]$property.Name
  428. if ($name -eq "bitstream") { continue }
  429. $metadata = $property.Value
  430. $source = [string](Get-PropertyValue $metadata "path")
  431. $expectedHash = [string](Get-PropertyValue $metadata "sha256")
  432. $record = [ordered]@{
  433. status = "fail"
  434. source_path = $source
  435. expected_sha256 = $expectedHash
  436. package_path = $null
  437. observed_sha256 = $null
  438. }
  439. if (Test-Path -LiteralPath $source -PathType Leaf) {
  440. $observed = Get-Sha256 $source
  441. $record.observed_sha256 = $observed
  442. if ($expectedHash -match '^[0-9a-f]{64}$' -and $observed -eq $expectedHash) {
  443. $safeName = ($name -replace '[^A-Za-z0-9_.-]', '_')
  444. $extension = [System.IO.Path]::GetExtension($source)
  445. if (-not $extension) { $extension = ".bin" }
  446. $fileName = "$safeName$extension"
  447. $target = Join-Path $Destination $fileName
  448. Copy-Item -LiteralPath $source -Destination $target
  449. $record.status = "pass"
  450. $record.package_path = "$PackageRelativeRoot/$fileName"
  451. }
  452. }
  453. $records[$name] = $record
  454. }
  455. return $records
  456. }
  457. function Get-ArtifactValidationStatus([System.Collections.IDictionary]$Records) {
  458. if ($Records.Count -eq 0) { return "not_run" }
  459. foreach ($record in $Records.Values) {
  460. if ([string]$record.status -ne "pass") { return "fail" }
  461. }
  462. return "pass"
  463. }
  464. function Copy-TdPinGate(
  465. [object]$Receipt,
  466. [string]$Destination,
  467. [string]$PackageRelativePath
  468. ) {
  469. $pinGate = Get-PropertyValue $Receipt "post_route_pin_gate"
  470. if ($null -eq $pinGate) {
  471. return [ordered]@{ status = "not_run"; package_path = $null; sha256 = $null }
  472. }
  473. Write-Json $Destination $pinGate
  474. return [ordered]@{
  475. status = "pass"
  476. package_path = $PackageRelativePath
  477. sha256 = Get-Sha256 $Destination
  478. }
  479. }
  480. function Get-PackageFileHashes([string]$Root) {
  481. $result = [ordered]@{}
  482. Get-ChildItem -LiteralPath $Root -Recurse -File | Sort-Object FullName | ForEach-Object {
  483. $relative = $_.FullName.Substring($Root.Length).TrimStart('\').Replace('\', '/')
  484. if ($relative -notin @("package-info.json", "evidence/package-selftest-result.json")) {
  485. $result[$relative] = Get-Sha256 $_.FullName
  486. }
  487. }
  488. return $result
  489. }
  490. function Invoke-FolderSelftest([string]$Root) {
  491. $savedErrorActionPreference = $ErrorActionPreference
  492. $ErrorActionPreference = "Continue"
  493. try {
  494. $output = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Root "selftest.ps1") 2>&1 | Out-String
  495. $returnCode = $LASTEXITCODE
  496. } catch {
  497. $output = $_ | Out-String
  498. $returnCode = if ($LASTEXITCODE) { $LASTEXITCODE } else { 1 }
  499. } finally {
  500. $ErrorActionPreference = $savedErrorActionPreference
  501. }
  502. return [ordered]@{
  503. schema = "prod2u-p4-normal-v3-package-selftest-result-v1"
  504. status = if ($returnCode -eq 0) { "pass" } else { "fail" }
  505. returncode = $returnCode
  506. output = $output.Trim()
  507. }
  508. }
  509. Assert-NonEmptyFile $NormalBitstream "Normal bitstream"
  510. Assert-File $TdReceipt "Primary TD build receipt"
  511. $deliveryMode = if ($UrgentSingleTd) { "urgent_single_td" } else { "normal_dual_td" }
  512. $confirmationTdPresent = -not [string]::IsNullOrWhiteSpace($ConfirmationTdReceipt)
  513. if ($UrgentSingleTd) {
  514. if ($confirmationTdPresent) {
  515. throw "Urgent single-TD mode must not include a Confirmation TD build receipt"
  516. }
  517. } else {
  518. if (-not $confirmationTdPresent) {
  519. throw "Confirmation TD build receipt is required in normal dual-TD mode"
  520. }
  521. Assert-File $ConfirmationTdReceipt "Confirmation TD build receipt"
  522. }
  523. Assert-File $HostContract "Normal v3 host contract"
  524. foreach ($receipt in $ValidationReceipt) {
  525. Assert-File $receipt "Validation receipt"
  526. }
  527. $hostContractRelative = Resolve-RepoRelativePath $HostContract "Normal v3 host contract"
  528. $sourceRelatives = @(
  529. $packageScriptRelative,
  530. $readmeSourceRelative,
  531. $hostContractSchemaRelative,
  532. $hostContractRelative,
  533. $hardwareBindingRelative,
  534. $verificationTargetsRelative
  535. ) + $templateRelatives | Sort-Object -Unique
  536. foreach ($relative in $sourceRelatives) {
  537. Assert-File (Join-Path $repo $relative) "Package source $relative"
  538. }
  539. $commitBinding = Resolve-Commit $Commit
  540. $resolvedFullCommit = [string]$commitBinding.full
  541. $resolvedCommit = [string]$commitBinding.short
  542. $git = Resolve-Git
  543. Assert-CleanCommittedSources $git $resolvedFullCommit $sourceRelatives
  544. $bitstreamSha256 = Get-Sha256 $NormalBitstream
  545. $tdPrimary = Read-Json $TdReceipt "Primary TD build receipt"
  546. if ([string](Get-PropertyValue $tdPrimary "commit") -ne $resolvedCommit) {
  547. throw "Primary TD receipt commit does not match package commit"
  548. }
  549. if ([string](Get-PropertyValue $tdPrimary "verification_run_id") -ne $VerificationRunId) {
  550. throw "Primary TD receipt verification_run_id mismatch"
  551. }
  552. if ([string](Get-PropertyValue $tdPrimary "bitstream_sha256") -ne $bitstreamSha256) {
  553. throw "Primary TD receipt bitstream hash does not match package bitstream"
  554. }
  555. Assert-PrimaryReceiptBinding $tdPrimary $resolvedCommit $bitstreamSha256
  556. Assert-PrimaryPinBinding $tdPrimary
  557. $synthesisInputHash = [string](Get-PropertyValue $tdPrimary "synthesis_input_hash")
  558. $primaryManifest = Get-PropertyValue $tdPrimary "synthesis_input_manifest"
  559. $primaryManifestSha256 = Get-PropertyValue $primaryManifest "sha256"
  560. $tdConfirmation = $null
  561. $confirmationBitstreamSha256 = $null
  562. $confirmationSynthesisInputHash = $null
  563. $confirmationManifestSha256 = $null
  564. if ($confirmationTdPresent) {
  565. $tdConfirmation = Read-Json $ConfirmationTdReceipt "Confirmation TD build receipt"
  566. $confirmationCommit = [string](Get-PropertyValue $tdConfirmation "commit")
  567. if ($confirmationCommit -ne $resolvedCommit) {
  568. throw "Confirmation TD receipt commit does not match package commit"
  569. }
  570. if ([string](Get-PropertyValue $tdConfirmation "verification_run_id") -ne $VerificationRunId) {
  571. throw "Confirmation TD receipt verification_run_id mismatch"
  572. }
  573. $confirmationBitstreamSha256 = Get-PropertyValue $tdConfirmation "bitstream_sha256"
  574. if ($confirmationBitstreamSha256 -and
  575. [string]$confirmationBitstreamSha256 -ne $bitstreamSha256) {
  576. throw "Confirmation TD receipt bitstream hash does not match primary"
  577. }
  578. $confirmationSynthesisInputHash = Get-PropertyValue $tdConfirmation "synthesis_input_hash"
  579. $confirmationManifest = Get-PropertyValue $tdConfirmation "synthesis_input_manifest"
  580. $confirmationManifestSha256 = Get-PropertyValue $confirmationManifest "sha256"
  581. $primaryRunId = [string](Get-PropertyValue $tdPrimary "run_id")
  582. $confirmationRunId = [string](Get-PropertyValue $tdConfirmation "run_id")
  583. if ($primaryRunId -notmatch '^[0-9a-f]{32}$' -or
  584. $confirmationRunId -notmatch '^[0-9a-f]{32}$' -or
  585. $primaryRunId -eq $confirmationRunId) {
  586. throw "Primary and confirmation TD run_id must differ"
  587. }
  588. $primaryWorkRoot = [string](Get-PropertyValue $tdPrimary "work_root")
  589. $confirmationWorkRoot = [string](Get-PropertyValue $tdConfirmation "work_root")
  590. if ([string]::IsNullOrWhiteSpace($primaryWorkRoot) -or
  591. [string]::IsNullOrWhiteSpace($confirmationWorkRoot) -or
  592. $primaryWorkRoot -cnotmatch '^[A-Za-z]:[\\/]' -or
  593. $confirmationWorkRoot -cnotmatch '^[A-Za-z]:[\\/]' -or
  594. [string]::Equals(
  595. [System.IO.Path]::GetFullPath($primaryWorkRoot).TrimEnd('\'),
  596. [System.IO.Path]::GetFullPath($confirmationWorkRoot).TrimEnd('\'),
  597. [System.StringComparison]::OrdinalIgnoreCase
  598. )) {
  599. throw "Primary and confirmation TD work_root must differ"
  600. }
  601. }
  602. $outFull = [System.IO.Path]::GetFullPath($OutputDir)
  603. $commitRoot = Join-Path $outFull $resolvedCommit
  604. New-Item -ItemType Directory -Force -Path $commitRoot | Out-Null
  605. $packageName = "prod2u-p4-normal-$resolvedCommit-$($bitstreamSha256.Substring(0, 16))"
  606. $final = Join-Path $commitRoot $packageName
  607. if (Test-Path -LiteralPath $final) { throw "Package folder already exists: $final" }
  608. $stage = Join-Path $commitRoot (".prod2u-p4-normal-stage-" + [Guid]::NewGuid().ToString("N"))
  609. New-Item -ItemType Directory -Path $stage | Out-Null
  610. try {
  611. $sourceSnapshot = Join-Path $stage ".source-snapshot"
  612. New-CommitSourceSnapshot $git $resolvedFullCommit $sourceRelatives $sourceSnapshot
  613. $configDir = Join-Path $stage "config"
  614. $evidenceDir = Join-Path $stage "evidence"
  615. $validationDir = Join-Path $evidenceDir "validation"
  616. $schemaDir = Join-Path $stage "schemas"
  617. foreach ($directory in @($configDir, $evidenceDir, $validationDir, $schemaDir)) {
  618. New-Item -ItemType Directory -Force -Path $directory | Out-Null
  619. }
  620. $packagedBitstream = Join-Path $stage "fw.bit"
  621. $packagedPrimaryReceipt = Join-Path $evidenceDir "td-primary-receipt.json"
  622. $packagedConfirmationReceipt = Join-Path $evidenceDir "td-confirmation-receipt.json"
  623. Copy-Item -LiteralPath $NormalBitstream -Destination $packagedBitstream
  624. Copy-Item -LiteralPath $TdReceipt -Destination $packagedPrimaryReceipt
  625. if ($confirmationTdPresent) {
  626. Copy-Item -LiteralPath $ConfirmationTdReceipt -Destination $packagedConfirmationReceipt
  627. }
  628. Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractRelative) -Destination (Join-Path $configDir "host-contract.json")
  629. Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hardwareBindingRelative) -Destination (Join-Path $configDir "prod2u_p4_normal_v3_hw_binding.json")
  630. Copy-Item -LiteralPath (Join-Path $sourceSnapshot $verificationTargetsRelative) -Destination (Join-Path $configDir "prod2u_p4_verification_targets_v1.json")
  631. Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractSchemaRelative) -Destination (Join-Path $schemaDir "host-contract.schema.json")
  632. $templateRoot = Join-Path $sourceSnapshot "tools\package_templates"
  633. foreach ($template in @(
  634. "bootstrap.ps1",
  635. "selftest.ps1",
  636. "run.ps1",
  637. "SEND_HEX.ps1",
  638. "INITIALIZE_DISABLE.ps1",
  639. "PROGRAM_SRAM.ps1"
  640. )) {
  641. Copy-Item -LiteralPath (Join-Path $templateRoot $template) -Destination (Join-Path $stage $template)
  642. }
  643. $readme = [System.IO.File]::ReadAllText(
  644. (Join-Path $sourceSnapshot $readmeSourceRelative),
  645. [System.Text.Encoding]::UTF8
  646. )
  647. Write-Utf8NoBom (Join-Path $stage "README.zh-CN.md") ($readme + "`r`n")
  648. Remove-Item -LiteralPath $sourceSnapshot -Recurse -Force
  649. $layers = [ordered]@{}
  650. foreach ($name in $validationLayerNames) {
  651. $layers[$name] = New-ValidationLayer "not_run" "not_provided" "not_run"
  652. }
  653. foreach ($name in $RunningValidationLayer) {
  654. Set-ValidationLayer $layers $name "running" "declared_running"
  655. }
  656. Set-ValidationLayer $layers "td_primary" (Get-PropertyValue $tdPrimary "status") "evidence/td-primary-receipt.json"
  657. Set-ValidationLayer $layers "resource_primary" (Get-ResourceStatus $tdPrimary) "evidence/td-primary-receipt.json"
  658. if ($confirmationTdPresent) {
  659. Set-ValidationLayer $layers "td_confirmation" (Get-PropertyValue $tdConfirmation "status") "evidence/td-confirmation-receipt.json"
  660. Set-ValidationLayer $layers "resource_confirmation" (Get-ResourceStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
  661. Set-ValidationLayer $layers "td_confirmation_bitstream" (Get-TdBitstreamBindingStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
  662. Set-ValidationLayer $layers "td_confirmation_synthesis" (Get-ComparisonStatus $confirmationSynthesisInputHash $synthesisInputHash) "evidence/td-confirmation-receipt.json"
  663. Set-ValidationLayer $layers "td_confirmation_manifest" (Get-ComparisonStatus $confirmationManifestSha256 $primaryManifestSha256) "evidence/td-confirmation-receipt.json"
  664. }
  665. $primaryArtifacts = Copy-TdArtifacts $tdPrimary (Join-Path $evidenceDir "td-primary") "evidence/td-primary"
  666. $primaryPinGate = Copy-TdPinGate $tdPrimary (Join-Path $evidenceDir "td-primary\pin-gate.json") "evidence/td-primary/pin-gate.json"
  667. $primaryArtifacts["pin_gate"] = $primaryPinGate
  668. $layers["td_primary"]["artifacts"] = $primaryArtifacts
  669. Set-ValidationLayer $layers "td_primary_artifacts" (Get-ArtifactValidationStatus $primaryArtifacts) "evidence/td-primary"
  670. if ($confirmationTdPresent) {
  671. $confirmationArtifacts = Copy-TdArtifacts $tdConfirmation (Join-Path $evidenceDir "td-confirmation") "evidence/td-confirmation"
  672. $confirmationPinGate = Copy-TdPinGate $tdConfirmation (Join-Path $evidenceDir "td-confirmation\pin-gate.json") "evidence/td-confirmation/pin-gate.json"
  673. $confirmationArtifacts["pin_gate"] = $confirmationPinGate
  674. $layers["td_confirmation"]["artifacts"] = $confirmationArtifacts
  675. Set-ValidationLayer $layers "td_confirmation_artifacts" (Get-ArtifactValidationStatus $confirmationArtifacts) "evidence/td-confirmation"
  676. }
  677. $validationSources = @()
  678. $validationIndex = 0
  679. foreach ($receiptPath in $ValidationReceipt) {
  680. $validationIndex += 1
  681. $receipt = Read-Json $receiptPath "Validation receipt"
  682. $receiptCommit = Get-PropertyValue $receipt "commit"
  683. if ($null -ne $receiptCommit -and [string]$receiptCommit -ne $resolvedCommit) {
  684. throw "Validation receipt commit does not match package commit"
  685. }
  686. if ([string](Get-PropertyValue $receipt "verification_run_id") -ne $VerificationRunId) {
  687. throw "Validation receipt verification_run_id mismatch"
  688. }
  689. $base = [System.IO.Path]::GetFileNameWithoutExtension($receiptPath) -replace '[^A-Za-z0-9_.-]', '_'
  690. $fileName = ("{0:D2}-{1}.json" -f $validationIndex, $base)
  691. $target = Join-Path $validationDir $fileName
  692. Copy-Item -LiteralPath $receiptPath -Destination $target
  693. $relative = "evidence/validation/$fileName"
  694. $validationSources += [ordered]@{
  695. path = $relative
  696. sha256 = Get-Sha256 $target
  697. schema = Get-PropertyValue $receipt "schema"
  698. status = Get-PropertyValue $receipt "status"
  699. verification_run_id = $VerificationRunId
  700. }
  701. Merge-ValidationReceipt $layers $receipt $relative
  702. }
  703. $verificationComplete = Test-VerificationComplete $layers $deliveryMode
  704. $validationSummaryPath = Join-Path $evidenceDir "validation-summary.json"
  705. $validationSummary = [ordered]@{
  706. schema = "prod2u-p4-normal-v3-validation-summary-v1"
  707. verification_run_id = $VerificationRunId
  708. commit = $resolvedCommit
  709. bitstream_sha256 = $bitstreamSha256
  710. delivery_mode = $deliveryMode
  711. verification_complete = $verificationComplete
  712. confirmation_td_present = $confirmationTdPresent
  713. layers = $layers
  714. sources = @($validationSources)
  715. policy = [ordered]@{
  716. image_created_when_bitstream_nonempty = $true
  717. validation_failures_block_package = $false
  718. allowed_statuses = @("pass", "fail", "running", "not_run")
  719. }
  720. }
  721. Write-Json $validationSummaryPath $validationSummary
  722. $selftestResultPath = Join-Path $evidenceDir "package-selftest-result.json"
  723. $provisionalSelftest = [ordered]@{
  724. schema = "prod2u-p4-normal-v3-package-selftest-result-v1"
  725. status = "not_run"
  726. returncode = $null
  727. output = ""
  728. }
  729. Write-Json $selftestResultPath $provisionalSelftest
  730. $packageInfoPath = Join-Path $stage "package-info.json"
  731. $packageInfo = [ordered]@{
  732. schema = "prod2u-p4-normal-v3-folder-package-info-v3"
  733. profile = "prod2u-p4-normal-actuator-binary921-v3"
  734. verification_run_id = $VerificationRunId
  735. commit = $resolvedCommit
  736. bitstream_sha256 = $bitstreamSha256
  737. delivery_mode = $deliveryMode
  738. verification_complete = $verificationComplete
  739. confirmation_td_present = $confirmationTdPresent
  740. confirmation_bitstream_sha256 = $confirmationBitstreamSha256
  741. td_receipt_sha256 = Get-Sha256 $packagedPrimaryReceipt
  742. confirmation_td_receipt_sha256 = if ($confirmationTdPresent) { Get-Sha256 $packagedConfirmationReceipt } else { $null }
  743. validation_summary_sha256 = Get-Sha256 $validationSummaryPath
  744. package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
  745. synthesis_input_hash = $synthesisInputHash
  746. confirmation_synthesis_input_hash = $confirmationSynthesisInputHash
  747. file_sha256 = Get-PackageFileHashes $stage
  748. }
  749. Write-Json $packageInfoPath $packageInfo
  750. $selftestResult = Invoke-FolderSelftest $stage
  751. Set-ValidationLayer $layers "package_selftest" $selftestResult.status "evidence/package-selftest-result.json"
  752. Write-Json $validationSummaryPath $validationSummary
  753. Write-Json $selftestResultPath $selftestResult
  754. $packageInfo.validation_summary_sha256 = Get-Sha256 $validationSummaryPath
  755. $packageInfo.package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
  756. $packageInfo.file_sha256 = Get-PackageFileHashes $stage
  757. Write-Json $packageInfoPath $packageInfo
  758. $finalSelftest = Invoke-FolderSelftest $stage
  759. if ($finalSelftest.status -ne "pass") {
  760. Set-ValidationLayer $layers "package_selftest" "fail" "evidence/package-selftest-result.json"
  761. Write-Json $validationSummaryPath $validationSummary
  762. Write-Json $selftestResultPath $finalSelftest
  763. $packageInfo.validation_summary_sha256 = Get-Sha256 $validationSummaryPath
  764. $packageInfo.package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
  765. $packageInfo.file_sha256 = Get-PackageFileHashes $stage
  766. Write-Json $packageInfoPath $packageInfo
  767. $selftestResult = $finalSelftest
  768. }
  769. Move-Item -LiteralPath $stage -Destination $final
  770. $stage = $null
  771. [ordered]@{
  772. schema = "prod2u-p4-normal-v3-folder-package-v3"
  773. status = "pass"
  774. package = $final
  775. verification_run_id = $VerificationRunId
  776. commit = $resolvedCommit
  777. bitstream_sha256 = $bitstreamSha256
  778. delivery_mode = $deliveryMode
  779. verification_complete = $verificationComplete
  780. confirmation_td_present = $confirmationTdPresent
  781. validation_status = Get-ValidationSummaryStatus $layers
  782. package_selftest_status = $selftestResult.status
  783. } | ConvertTo-Json -Compress
  784. } finally {
  785. if ($stage -and (Test-Path -LiteralPath $stage)) {
  786. Remove-Item -LiteralPath $stage -Recurse -Force
  787. }
  788. }