package_prod2u_p4_normal_v3.ps1 36 KB

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