Files
rust-discovery/deploy/windows/Build-MsiFixture.ps1
T
2026-11-16 10:02:50 +01:00

350 lines
27 KiB
PowerShell

#requires -Version 5.1
<#
Build-only, fixed MSI1.0.0 or1.1.0 major-upgrade fixture. Writes only a NEW private child directory.
Never calls InstallProduct/OpenPackage/msiexec, modifies installed products,
services, execution policy, certificate trust or reboot state. No downloads.
1.1 removes only the exact known1.0 predecessor; no EXE/repair mode.
Primary API/format contracts:
https://learn.microsoft.com/en-us/windows/win32/msi/installer-opendatabase
https://learn.microsoft.com/en-us/windows/win32/msi/database-summaryinformation
https://learn.microsoft.com/en-us/windows/win32/msi/record-setstream
https://learn.microsoft.com/en-us/windows/win32/msi/record-readstream
https://learn.microsoft.com/en-us/windows/win32/msi/cabinet-files
https://learn.microsoft.com/en-us/windows/win32/msi/suggested-installexecutesequence
https://learn.microsoft.com/en-us/windows/win32/msi/package-codes
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$OutputParent,
[Guid]$CaseId=([Guid]::NewGuid()),
[ValidateSet('1.0.0','1.1.0')][string]$FixtureVersion='1.0.0'
)
Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
$case=$null;$created=$false;$installer=$null;$database=$null;$summary=$null;$makecabLock=$null
$product='{3F070B4B-9C08-4D65-BD41-13D81B884AEC}'
$upgrade='{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}'
$component='{4D1CA80F-9AF8-4F54-B426-450AFBAFF92E}'
$version=$FixtureVersion
$isUpgrade=$version -ceq '1.1.0'
$oldProduct=$product
if($isUpgrade){$product='{D42BD387-079B-4BBF-A134-0DA7B7A97011}'}
$upgradeCondition='Installed OR (RMM_OLD_PRODUCTS = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}" AND RMM_ALL_PRODUCTS = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}")'
# Product/family/component identities are fixed. Nonidentical MSI bytes must
# have distinct PackageCodes, so each new authoring case gets its own code.
$package='{'+([Guid]::NewGuid().ToString().ToUpperInvariant())+'}'
$artifact=[Guid]::NewGuid().ToString()
$report=[ordered]@{schema_version=1;case_id=$CaseId.ToString();completed=$false;stage='preflight';
build_only=$true;native_installation_tested=$false;product_changes=$false;services_changed=$false;
reboot_requested=$false;trust_changed=$false;downloads=$false;upgrade_authored=$isUpgrade;
product_code=$product;upgrade_code=$upgrade;component_code=$component;package_code=$package;version=$version}
function Require([bool]$Value,[string]$Code) {if (!$Value) {throw $Code}}
function Hash([string]$Path) {return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()}
function Hash-Bytes([byte[]]$Value) {
$sha=[Security.Cryptography.SHA256]::Create()
try {return ([BitConverter]::ToString($sha.ComputeHash($Value))).Replace('-','').ToLowerInvariant()}
finally {$sha.Dispose()}
}
function No-Reparse([string]$Path) {
$item=Get-Item -LiteralPath $Path -Force
while ($null -ne $item) {
Require (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0) 'MSI_BUILD_REPARSE'
if ($item -is [IO.FileInfo]) {$item=$item.Directory} else {$item=$item.Parent}
}
}
function Write-New([string]$Path,[byte[]]$Bytes) {
$stream=[IO.File]::Open($Path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
try {$stream.Write($Bytes,0,$Bytes.Length);$stream.Flush($true)} finally {$stream.Dispose()}
}
function Write-Json([string]$Path,$Value) {Write-New $Path ([Text.Encoding]::UTF8.GetBytes(($Value|ConvertTo-Json -Depth 30)))}
function Release-Com($Object) {
if ($null -ne $Object -and [Runtime.InteropServices.Marshal]::IsComObject($Object)) {
[void][Runtime.InteropServices.Marshal]::FinalReleaseComObject($Object)
}
}
function Com-Operation($Object,[string]$Kind,[string]$Name,[object[]]$Arguments) {
$report.last_com_operation=$Kind+':'+$Name
$report.last_com_target_type=if ($null -eq $Object) {'null'} else {$Object.GetType().FullName}
$report.last_com_argument_types=@($Arguments|ForEach-Object {
if ($null -eq $_) {'null'} else {$_.GetType().FullName}
})
$report.last_com_argument_count=$Arguments.Count
}
function Com-NativeArguments([object[]]$Values=@()) {
# Join-Path/COM results may carry ETS PSObject wrappers. GetType() in
# PowerShell unwraps them, but COM reflection marshals nested object[]
# values as their real CLR types. Preserve the values, remove only ETS.
$native=New-Object 'object[]' $Values.Length
for ($n=0;$n -lt $Values.Length;$n++) {
if ($null -eq $Values[$n]) {$native[$n]=$null}
else {$native[$n]=$Values[$n].PSObject.BaseObject}
}
return ,$native
}
function Com-Method($Object,[string]$Name,[object[]]$Arguments=@()) {
$target=$Object.PSObject.BaseObject;$native=Com-NativeArguments $Arguments
Com-Operation $target 'method' $Name $native
return $target.GetType().InvokeMember($Name,[Reflection.BindingFlags]::InvokeMethod,$null,$target,$native)
}
function Com-Get($Object,[string]$Name,[object[]]$Arguments=@()) {
$target=$Object.PSObject.BaseObject;$native=Com-NativeArguments $Arguments
Com-Operation $target 'get' $Name $native
return $target.GetType().InvokeMember($Name,[Reflection.BindingFlags]::GetProperty,$null,$target,$native)
}
function Com-Set($Object,[string]$Name,[object[]]$Arguments) {
$target=$Object.PSObject.BaseObject;$native=Com-NativeArguments $Arguments
Com-Operation $target 'set' $Name $native
[void]$target.GetType().InvokeMember($Name,[Reflection.BindingFlags]::SetProperty,$null,$target,$native)
}
function Sql([string]$Query) {
$report.last_sql_sha256=Hash-Bytes ([Text.Encoding]::UTF8.GetBytes($Query))
$view=Com-Method $database 'OpenView' @($Query)
try {[void](Com-Method $view 'Execute');[void](Com-Method $view 'Close')}
finally {Release-Com $view}
}
function Rows([string]$Query) {
$view=Com-Method $database 'OpenView' @($Query);$rows=New-Object 'Collections.Generic.List[object]'
try {
[void](Com-Method $view 'Execute')
while ($true) {
$row=Com-Method $view 'Fetch';if ($null -eq $row) {break}
try {
Require ($rows.Count -lt 64) 'MSI_BUILD_ROW_LIMIT'
$count=[int](Com-Get $row 'FieldCount');Require ($count -le 12) 'MSI_BUILD_FIELD_LIMIT'
$fields=New-Object 'Collections.Generic.List[string]'
for ($i=1;$i -le $count;$i++) {$text=[string](Com-Get $row 'StringData' @($i));Require ($text.Length -le 512) 'MSI_BUILD_STRING_LIMIT';$fields.Add($text)}
$rows.Add($fields.ToArray())
} finally {Release-Com $row}
}
[void](Com-Method $view 'Close')
} finally {Release-Com $view}
return ,$rows.ToArray()
}
function Run-Makecab([string]$Tool,[string]$Ddf) {
$si=New-Object Diagnostics.ProcessStartInfo;$si.FileName=$Tool;$si.Arguments='/F "'+$Ddf+'"'
$si.WorkingDirectory=$case;$si.UseShellExecute=$false;$si.CreateNoWindow=$true
$si.RedirectStandardOutput=$true;$si.RedirectStandardError=$true
$process=New-Object Diagnostics.Process;$process.StartInfo=$si
Require ($process.Start()) 'MSI_MAKECAB_START'
try {
$stdout=$process.StandardOutput.ReadToEndAsync();$stderr=$process.StandardError.ReadToEndAsync()
if (!$process.WaitForExit(30000)) {$process.Kill();throw 'MSI_MAKECAB_TIMEOUT'}
Require ($stdout.Result.Length -le 8192 -and $stderr.Result.Length -le 8192) 'MSI_MAKECAB_OUTPUT_LIMIT'
Write-New (Join-Path $case 'makecab.stdout.txt') ([Text.Encoding]::UTF8.GetBytes($stdout.Result))
Write-New (Join-Path $case 'makecab.stderr.txt') ([Text.Encoding]::UTF8.GetBytes($stderr.Result))
Require ($process.ExitCode -eq 0) 'MSI_MAKECAB_FAILED'
} finally {$process.Dispose()}
}
try {
Require ([Environment]::OSVersion.Platform -eq 'Win32NT' -and [Environment]::Is64BitProcess) 'MSI_BUILD_NATIVE_X64_REQUIRED'
Require ($CaseId -ne [Guid]::Empty -and $OutputParent -match '^[A-Za-z]:\\' -and $OutputParent -cmatch '^[\x20-\x7e]+$' -and $OutputParent -notmatch '["\x00\r\n]') 'MSI_BUILD_LOCAL_ASCII_PARENT'
$OutputParent=[IO.Path]::GetFullPath($OutputParent).TrimEnd('\');No-Reparse $OutputParent
Require ((New-Object IO.DriveInfo($OutputParent.Substring(0,3))).DriveType -eq 'Fixed') 'MSI_BUILD_LOCAL_FIXED_DRIVE'
Require ((Get-Item -LiteralPath $OutputParent).PSIsContainer) 'MSI_BUILD_EXISTING_PARENT'
$me=[Security.Principal.WindowsIdentity]::GetCurrent().User
$allowed=@($me.Value,'S-1-5-18','S-1-5-32-544')|Select-Object -Unique
$parentAcl=Get-Acl -LiteralPath $OutputParent
Require ($parentAcl.GetOwner([Security.Principal.SecurityIdentifier]).Value -in $allowed) 'MSI_BUILD_PARENT_OWNER'
$rules=@($parentAcl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));Require ($rules.Count -gt 0) 'MSI_BUILD_PARENT_DACL'
foreach ($rule in $rules) {
Require ($rule.AccessControlType -eq 'Allow') 'MSI_BUILD_PARENT_ACE'
Require ($rule.IdentityReference.Value -in $allowed -or ([long]$rule.FileSystemRights -band 0x500d0156) -eq 0) 'MSI_BUILD_PARENT_WRITABLE'
}
$case=Join-Path $OutputParent ('msi-fixture-'+$CaseId.ToString())
# New-Item without Force refuses an existing directory; no case is reused.
[void](New-Item -ItemType Directory -Path $case -ErrorAction Stop)
$created=$true
$acl=New-Object Security.AccessControl.DirectorySecurity;$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($me)
foreach ($sid in $allowed) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))}
Set-Acl -LiteralPath $case -AclObject $acl;No-Reparse $case
$report.builder_sha256=Hash $PSCommandPath;Write-Json (Join-Path $case 'started.json') $report
$report.stage='native_tools'
Require ([Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles) -ceq 'C:\Program Files') 'MSI_FIXED_PROGRAMFILES_CONTRACT'
$system=[Environment]::GetFolderPath([Environment+SpecialFolder]::System)
$makecab=Join-Path $system 'makecab.exe';$msiDll=Join-Path $system 'msi.dll'
$tools=[ordered]@{}
foreach ($tool in @($makecab,$msiDll)) {
No-Reparse $tool;$signature=Get-AuthenticodeSignature -LiteralPath $tool
Require ($signature.Status -eq 'Valid' -and $signature.SignerCertificate.Subject -match 'Microsoft Corporation') 'MSI_MICROSOFT_TOOL_SIGNATURE'
$tools[(Split-Path $tool -Leaf)]=[ordered]@{sha256=(Hash $tool);signature_status=[string]$signature.Status;file_version=(Get-Item -LiteralPath $tool).VersionInfo.FileVersion}
}
$makecabLock=[IO.File]::Open($makecab,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
$report.tools=$tools
$report.stage='payload_and_cabinet'
$payload=Join-Path $case 'msi-payload.txt'
$payloadBytes=[Text.Encoding]::ASCII.GetBytes("RustDiscovery MSI fixture $version`r`n")
Write-New $payload $payloadBytes
$ddf=Join-Path $case 'fixture.ddf'
$ddfText=@"
.OPTION EXPLICIT
.Set Cabinet=ON
.Set Compress=ON
.Set CompressionType=MSZIP
.Set CabinetNameTemplate=fixture.cab
.Set DiskDirectoryTemplate=.
.Set InfFileName=fixture.inf
.Set RptFileName=fixture.rpt
.Set MaxDiskSize=0
.Set MaxCabinetSize=262144
"$payload" PayloadFile
"@
Write-New $ddf ([Text.Encoding]::ASCII.GetBytes($ddfText))
Run-Makecab $makecab $ddf
$cab=Join-Path $case 'fixture.cab';No-Reparse $cab
Require ((Get-Item -LiteralPath $cab).Length -gt 0 -and (Get-Item -LiteralPath $cab).Length -le 65536) 'MSI_CABINET_LIMIT'
$report.stage='database_authoring:com_activation'
$msi=Join-Path $case ('RustDiscoveryFixture-'+$version+'-x64.msi');Require (!(Test-Path -LiteralPath $msi)) 'MSI_OUTPUT_EXISTS'
$installer=New-Object -ComObject WindowsInstaller.Installer
$report.stage='database_authoring:open_create'
$database=Com-Method $installer 'OpenDatabase' @($msi,[int]3)
$tables=[ordered]@{
Property='`Property` CHAR(72) NOT NULL, `Value` CHAR(0) LOCALIZABLE PRIMARY KEY `Property`'
Directory='`Directory` CHAR(72) NOT NULL, `Directory_Parent` CHAR(72), `DefaultDir` CHAR(255) NOT NULL LOCALIZABLE PRIMARY KEY `Directory`'
Component='`Component` CHAR(72) NOT NULL, `ComponentId` CHAR(38), `Directory_` CHAR(72) NOT NULL, `Attributes` SHORT NOT NULL, `Condition` CHAR(255), `KeyPath` CHAR(72) PRIMARY KEY `Component`'
Feature='`Feature` CHAR(38) NOT NULL, `Feature_Parent` CHAR(38), `Title` CHAR(64) LOCALIZABLE, `Description` CHAR(255) LOCALIZABLE, `Display` SHORT, `Level` SHORT NOT NULL, `Directory_` CHAR(72), `Attributes` SHORT NOT NULL PRIMARY KEY `Feature`'
FeatureComponents='`Feature_` CHAR(38) NOT NULL, `Component_` CHAR(72) NOT NULL PRIMARY KEY `Feature_`, `Component_`'
File='`File` CHAR(72) NOT NULL, `Component_` CHAR(72) NOT NULL, `FileName` CHAR(255) NOT NULL LOCALIZABLE, `FileSize` LONG NOT NULL, `Version` CHAR(72), `Language` CHAR(20), `Attributes` SHORT, `Sequence` SHORT NOT NULL PRIMARY KEY `File`'
Media='`DiskId` SHORT NOT NULL, `LastSequence` LONG NOT NULL, `DiskPrompt` CHAR(64) LOCALIZABLE, `Cabinet` CHAR(255), `VolumeLabel` CHAR(32), `Source` CHAR(72) PRIMARY KEY `DiskId`'
InstallExecuteSequence='`Action` CHAR(72) NOT NULL, `Condition` CHAR(255), `Sequence` SHORT PRIMARY KEY `Action`'
LaunchCondition='`Condition` CHAR(255) NOT NULL, `Description` CHAR(255) NOT NULL LOCALIZABLE PRIMARY KEY `Condition`'
}
if($isUpgrade){$tables.Upgrade='`UpgradeCode` CHAR(38) NOT NULL, `VersionMin` CHAR(20), `VersionMax` CHAR(20), `Language` CHAR(255), `Attributes` SHORT NOT NULL, `Remove` CHAR(255), `ActionProperty` CHAR(72) NOT NULL PRIMARY KEY `UpgradeCode`, `VersionMin`, `VersionMax`, `Language`, `Attributes`'}
foreach ($table in $tables.Keys) {$report.stage='database_authoring:create_table:'+$table;Sql ('CREATE TABLE `'+$table+'` ('+$tables[$table]+')')}
$report.stage='database_authoring:insert_rows'
$properties=[ordered]@{ProductCode=$product;UpgradeCode=$upgrade;ProductVersion=$version;ProductLanguage='1033';ProductName='RustDiscovery MSI Fixture';Manufacturer='Ease Technologies';ALLUSERS='1';INSTALLLEVEL='1';REBOOT='ReallySuppress'}
if($isUpgrade){$properties.SecureCustomProperties='RMM_ALL_PRODUCTS;RMM_OLD_PRODUCTS'}
foreach ($key in $properties.Keys) {Sql ("INSERT INTO ``Property`` (``Property``,``Value``) VALUES ('$key','$($properties[$key])')")}
Sql 'INSERT INTO `Directory` (`Directory`,`DefaultDir`) VALUES (''TARGETDIR'',''SourceDir'')'
Sql 'INSERT INTO `Directory` (`Directory`,`Directory_Parent`,`DefaultDir`) VALUES (''ProgramFiles64Folder'',''TARGETDIR'',''.'')'
Sql 'INSERT INTO `Directory` (`Directory`,`Directory_Parent`,`DefaultDir`) VALUES (''INSTALLDIR'',''ProgramFiles64Folder'',''RUSTDI~1|RustDiscoveryFixtures'')'
Sql ("INSERT INTO ``Component`` (``Component``,``ComponentId``,``Directory_``,``Attributes``,``KeyPath``) VALUES ('PayloadComponent','$component','INSTALLDIR',256,'PayloadFile')")
Sql 'INSERT INTO `Feature` (`Feature`,`Title`,`Display`,`Level`,`Directory_`,`Attributes`) VALUES (''Fixture'',''Fixture'',1,1,''INSTALLDIR'',0)'
Sql 'INSERT INTO `FeatureComponents` (`Feature_`,`Component_`) VALUES (''Fixture'',''PayloadComponent'')'
Sql ("INSERT INTO ``File`` (``File``,``Component_``,``FileName``,``FileSize``,``Attributes``,``Sequence``) VALUES ('PayloadFile','PayloadComponent','MSIPAY~1.TXT|msi-payload.txt',$($payloadBytes.Length),16896,1)")
Sql 'INSERT INTO `Media` (`DiskId`,`LastSequence`,`Cabinet`) VALUES (1,1,''#fixture.cab'')'
Sql 'INSERT INTO `LaunchCondition` (`Condition`,`Description`) VALUES (''VersionNT64'',''This fixture requires 64-bit Windows.'')'
if($isUpgrade){
Sql ("INSERT INTO ``Upgrade`` (``UpgradeCode``,``VersionMin``,``VersionMax``,``Attributes``,``Remove``,``ActionProperty``) VALUES ('$upgrade','1.0.0','1.0.0',768,'ALL','RMM_OLD_PRODUCTS')")
Sql ("INSERT INTO ``Upgrade`` (``UpgradeCode``,``VersionMin``,``Attributes``,``Remove``,``ActionProperty``) VALUES ('$upgrade','0.0.0',258,'ALL','RMM_ALL_PRODUCTS')")
Sql ("INSERT INTO ``LaunchCondition`` (``Condition``,``Description``) VALUES ('$upgradeCondition','Only the exact approved fixture1.0 predecessor may be upgraded.')")
}
$sequence=[ordered]@{LaunchConditions=100;CostInitialize=800;FileCost=900;CostFinalize=1000;InstallValidate=1400;InstallInitialize=1500;ProcessComponents=1600;UnpublishFeatures=1800;RemoveFiles=3500;RemoveFolders=3600;CreateFolders=3700;InstallFiles=4000;RegisterUser=6000;RegisterProduct=6100;PublishFeatures=6300;PublishProduct=6400;InstallFinalize=6600}
if($isUpgrade){$sequence.FindRelatedProducts=25;$sequence.RemoveExistingProducts=1550}
foreach ($action in $sequence.Keys) {
if($action -ceq 'RemoveExistingProducts'){Sql ("INSERT INTO ``InstallExecuteSequence`` (``Action``,``Condition``,``Sequence``) VALUES ('$action','NOT Installed',$($sequence[$action]))")}
else {Sql ("INSERT INTO ``InstallExecuteSequence`` (``Action``,``Sequence``) VALUES ('$action',$($sequence[$action]))")}
}
$view=Com-Method $database 'OpenView' @('INSERT INTO `_Streams` (`Name`,`Data`) VALUES (?,?)');$record=$null
try {$record=Com-Method $installer 'CreateRecord' @([int]2);Com-Set $record 'StringData' @([int]1,'fixture.cab');[void](Com-Method $record 'SetStream' @([int]2,$cab));[void](Com-Method $view 'Execute' @($record));[void](Com-Method $view 'Close')}
finally {Release-Com $record;Release-Com $view}
$summary=Com-Get $database 'SummaryInformation' @([int]10)
foreach ($entry in @(@(1,1252),@(2,'RustDiscovery MSI fixture'),@(3,'Isolated machine/x64 file fixture'),@(4,'Ease Technologies'),@(7,'x64;1033'),@(9,$package),@(14,500),@(15,2),@(18,'RustDiscovery Build-MsiFixture.ps1'))) {Com-Set $summary 'Property' @([int]$entry[0],$entry[1])}
[void](Com-Method $summary 'Persist');Release-Com $summary;$summary=$null
[void](Com-Method $database 'Commit');Release-Com $database;$database=$null
$report.stage='independent_readback'
No-Reparse $msi;$length=(Get-Item -LiteralPath $msi).Length;Require ($length -gt 0 -and $length -le 262144) 'MSI_ARTIFACT_LIMIT'
$database=Com-Method $installer 'OpenDatabase' @($msi,[int]0)
$readback=[ordered]@{}
foreach ($table in $tables.Keys) {$readback[$table]=Rows ('SELECT * FROM `'+$table+'`')}
Require ($readback.Property.Count -eq $properties.Count -and $readback.Directory.Count -eq 3 -and $readback.File.Count -eq 1 -and $readback.Component.Count -eq 1 -and $readback.Media.Count -eq 1 -and $readback.InstallExecuteSequence.Count -eq $sequence.Count) 'MSI_TABLE_READBACK_COUNTS'
foreach ($key in $properties.Keys) {$row=Rows ("SELECT ``Value`` FROM ``Property`` WHERE ``Property``='$key'");Require ($row.Count -eq 1 -and $row[0][0] -ceq $properties[$key]) 'MSI_PROPERTY_READBACK'}
$allTables=Rows 'SELECT `Name` FROM `_Tables`';$names=@($allTables|ForEach-Object {$_[0]})
Require ($names.Count -eq $tables.Count -and @($names|Where-Object {$_ -notin $tables.Keys}).Count -eq 0) 'MSI_UNEXPECTED_TABLE'
Require ('CustomAction' -notin $names -and 'Registry' -notin $names -and 'ServiceInstall' -notin $names -and ($isUpgrade -or 'Upgrade' -notin $names)) 'MSI_FORBIDDEN_TABLE'
# Independently read committed upgrade/sequence metadata; no install APIs.
foreach($action in $sequence.Keys){
$row=Rows ("SELECT ``Condition``,``Sequence`` FROM ``InstallExecuteSequence`` WHERE ``Action``='$action'")
$condition=if($action -ceq 'RemoveExistingProducts'){'NOT Installed'}else{''}
Require ($row.Count -eq 1 -and $row[0][0] -ceq $condition -and $row[0][1] -ceq [string]$sequence[$action]) 'MSI_SEQUENCE_READBACK'
}
if($isUpgrade){
$rows=Rows 'SELECT `UpgradeCode`,`VersionMin`,`VersionMax`,`Attributes`,`Remove`,`ActionProperty` FROM `Upgrade` WHERE `Language` IS NULL'
Require ($rows.Count -eq 2) 'MSI_UPGRADE_ROW_COUNT'
$expected=@(@($upgrade,'0.0.0','','258','ALL','RMM_ALL_PRODUCTS'),@($upgrade,'1.0.0','1.0.0','768','ALL','RMM_OLD_PRODUCTS'))
# Match the logical rows by their unique ActionProperty. The native MSI
# provider returned the committed rows in the opposite order during the
# real 1.1 build; row order is not part of this package's contract.
foreach($expectedRow in $expected){
$match=-1
for($i=0;$i -lt $rows.Count;$i++){
if($rows[$i][5] -ceq $expectedRow[5]){Require ($match -eq -1) 'MSI_UPGRADE_ROW_KEY';$match=$i}
}
Require ($match -ge 0) 'MSI_UPGRADE_ROW_KEY'
for($j=0;$j -lt 6;$j++){Require ($rows[$match][$j] -ceq $expectedRow[$j]) 'MSI_UPGRADE_ROW_READBACK'}
}
$nullMax=Rows 'SELECT `ActionProperty` FROM `Upgrade` WHERE `VersionMax` IS NULL'
Require ($nullMax.Count -eq 1 -and $nullMax[0][0] -ceq 'RMM_ALL_PRODUCTS') 'MSI_UPGRADE_NULL_MAX_READBACK'
$launch=Rows ("SELECT ``Description`` FROM ``LaunchCondition`` WHERE ``Condition``='$upgradeCondition'")
Require ($launch.Count -eq 1 -and $launch[0][0] -ceq 'Only the exact approved fixture1.0 predecessor may be upgraded.' -and $readback.LaunchCondition.Count -eq 2) 'MSI_UPGRADE_LAUNCH_READBACK'
}
$summary=Com-Get $database 'SummaryInformation' @([int]0)
Require ((Com-Get $summary 'Property' @([int]7)) -ceq 'x64;1033' -and (Com-Get $summary 'Property' @([int]9)) -ceq $package -and [int](Com-Get $summary 'Property' @([int]15)) -eq 2) 'MSI_SUMMARY_READBACK'
Release-Com $summary;$summary=$null
$view=Com-Method $database 'OpenView' @('SELECT `Data` FROM `_Streams` WHERE `Name`=''fixture.cab''');$record=$null
try {
[void](Com-Method $view 'Execute');$record=Com-Method $view 'Fetch';Require ($null -ne $record) 'MSI_EMBEDDED_CAB_MISSING'
$embedded=New-Object 'Collections.Generic.List[byte]'
while ($true) {
$chunk=[string](Com-Method $record 'ReadStream' @([int]1,[int]8192,[int]1));if (!$chunk.Length) {break}
Require ($embedded.Count+$chunk.Length -le 65536) 'MSI_EMBEDDED_CAB_LIMIT'
foreach ($char in $chunk.ToCharArray()) {Require ([int]$char -le 255) 'MSI_STREAM_BYTE_ENCODING';$embedded.Add([byte]$char)}
}
Require ((Hash-Bytes $embedded.ToArray()) -ceq (Hash $cab)) 'MSI_EMBEDDED_CAB_HASH'
$extra=Com-Method $view 'Fetch';Require ($null -eq $extra) 'MSI_DUPLICATE_CAB_STREAM';[void](Com-Method $view 'Close')
} finally {Release-Com $record;Release-Com $view}
Release-Com $database;$database=$null
$recipe=[ordered]@{schema_version=1;recipe_id=$(if($isUpgrade){'rmm-windows-msi-fixture-upgrade-1.1'}else{'rmm-windows-msi-fixture-install-1.0'});recipe_version='1';platform='windows';upgrade_code=$upgrade;architecture='x64';context='machine';command_profile='fixture_quiet_no_reboot_v1';artifact=[ordered]@{artifact_id=$artifact;sha256=(Hash $msi);bytes=$length};postcondition=[ordered]@{product_code=$product;product_version=$version;payload_path='C:\Program Files\RustDiscoveryFixtures\msi-payload.txt';payload_sha256=(Hash $payload);payload_bytes=$payloadBytes.Length};no_reboot=$true}
if($isUpgrade){
$recipe.package_code=$package
$oldBytes=[Text.Encoding]::ASCII.GetBytes("RustDiscovery MSI fixture 1.0.0`r`n")
$recipe.predecessor=[ordered]@{product_code=$oldProduct;product_version='1.0.0';payload_path=$recipe.postcondition.payload_path;payload_sha256=(Hash-Bytes $oldBytes);payload_bytes=$oldBytes.Length}
}
$recipeJson=$recipe|ConvertTo-Json -Depth 12 -Compress
Write-New (Join-Path $case 'recipe.json') ([Text.Encoding]::UTF8.GetBytes($recipeJson))
Write-Json (Join-Path $case 'tables.json') $readback
$report.artifact=[ordered]@{path=$msi;sha256=(Hash $msi);bytes=$length;artifact_id_proposal=$artifact}
$report.payload=[ordered]@{sha256=(Hash $payload);bytes=$payloadBytes.Length;content_ascii="RustDiscovery MSI fixture $version`r`n";installed_path=$recipe.postcondition.payload_path}
$report.cabinet=[ordered]@{sha256=(Hash $cab);bytes=(Get-Item -LiteralPath $cab).Length;embedded_hash_verified=$true;stream='fixture.cab'}
$report.tables_sha256=Hash (Join-Path $case 'tables.json');$report.table_names=$names
$report.resolved_recipe=[ordered]@{recipe=$recipe;recipe_sha256=(Hash (Join-Path $case 'recipe.json'))}
$report.rust_recipe_validation_executed=$false;$report.artifact_registered_on_server=$false
$report.makecab_sha256_after=Hash $makecab;Require ($report.makecab_sha256_after -ceq $tools['makecab.exe'].sha256) 'MSI_BUILD_TOOL_CHANGED'
Require ((Hash $PSCommandPath) -ceq $report.builder_sha256) 'MSI_BUILDER_CHANGED'
$report.completed=$true;$report.stage='authored_and_read_back_not_installed'
Write-Json (Join-Path $case 'result.json') $report
[ordered]@{completed=$true;build_only=$true;report_path=(Join-Path $case 'result.json');artifact=$report.artifact;native_installation_tested=$false;upgrade_authored=$isUpgrade}|ConvertTo-Json -Depth 5
} catch {
$report.completed=$false;$report.error_type=$_.Exception.GetType().FullName;$report.error_hresult=$_.Exception.HResult
$report.error_line=$_.InvocationInfo.ScriptLineNumber
$report.error_column=$_.InvocationInfo.OffsetInLine
$report.error_stack=([string]$_.ScriptStackTrace).Substring(0,[Math]::Min(2048,([string]$_.ScriptStackTrace).Length))
$chain=New-Object 'Collections.Generic.List[object]';$exception=$_.Exception
while ($null -ne $exception -and $chain.Count -lt 6) {
$chain.Add([ordered]@{type=$exception.GetType().FullName;hresult=$exception.HResult})
$exception=$exception.InnerException
}
$report.exception_chain=$chain.ToArray()
# Numeric MSI diagnostics only; never echo argument values, paths, raw SQL,
# COM error messages or formatted installer records. Preserve the original
# exception even when no LastErrorRecord is available.
$errorRecord=$null
if ($null -ne $installer) {
try {
$errorRecord=$installer.GetType().InvokeMember('LastErrorRecord',[Reflection.BindingFlags]::InvokeMethod,$null,$installer,@())
if ($null -ne $errorRecord) {
$count=[int]$errorRecord.GetType().InvokeMember('FieldCount',[Reflection.BindingFlags]::GetProperty,$null,$errorRecord,@())
$report.msi_error_record_fields=$count
if ($count -ge 1) {$report.msi_error_code=[int]$errorRecord.GetType().InvokeMember('IntegerData',[Reflection.BindingFlags]::GetProperty,$null,$errorRecord,@([int]1))}
}
} catch {$report.msi_diagnostic_hresult=$_.Exception.HResult}
finally {Release-Com $errorRecord}
}
if ($created -and (Test-Path -LiteralPath $case)) {Write-Json (Join-Path $case 'failed.json') $report}
throw 'MSI_FIXTURE_BUILD_FAILED: retain the private case; do not reuse or install an incomplete artifact.'
} finally {
Release-Com $summary;Release-Com $database;Release-Com $installer
if ($null -ne $makecabLock) {$makecabLock.Dispose()}
}