aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/.ci/verify_arch.ps1
blob: 183a8c5922d4b2e2557803072655ef3ab7179665 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
param(
    [Parameter(Mandatory=$true)]
    [string] $Path,
    [Parameter(Mandatory=$true)]
    [ValidateSet('x64', 'x86')]
    [string] $Arch
)

$ErrorActionPreference = "Stop";
Set-PSDebug -Strict

function Get-MachineType {
    param(
        [Parameter(Mandatory=$true)]
        [string] $Arch
    )

    $machine_type = switch ($Arch) {
        'x64' { 0x8664 }
        'x86' { 0x14c }
        default { throw "Unsupported architecture: $Arch" }
    }
    return $machine_type
}

function Parse-MachineType {
    param(
        [Parameter(Mandatory=$true)]
        [string] $Path
    )

    $header_offset_offset = 0x3c
    $machine_type_offset = 4 # Two words

    $bytes = [System.IO.File]::ReadAllBytes($Path)
    $header_offset = [System.BitConverter]::ToUInt32($bytes, $header_offset_offset)
    $machine_type = [System.BitConverter]::ToUInt16($bytes, $header_offset + $machine_type_offset)

    return $machine_type
}

function Verify-Architecture {
    param(
        [Parameter(Mandatory=$true)]
        [string] $Path,
        [Parameter(Mandatory=$true)]
        [string] $Arch
    )

    $actual = Parse-MachineType -Path $Path
    $actual_hex = "0x{0:x}" -f $actual
    $expected = Get-MachineType -Arch $Arch
    $expected_hex = "0x{0:x}" -f $expected

    if ($actual -eq $expected) {
        Write-Host "File '$Path' matches architecture '$Arch'."
    } else {
        Write-Host "File '$Path' DOES NOT match architecture '$Arch'."
        Write-Error "Expected machine type '$expected_hex', actual machine type is '$actual_hex'."
    }
}

function Test-AppVeyor {
    return Test-Path env:APPVEYOR
}

function Verify-ArchitectureAppVeyor {
    if (Test-AppVeyor) {
        $appveyor_cwd = pwd
    }

    try {
        Verify-Architecture -Path $script:Path -Arch $script:Arch
    } finally {
        if (Test-AppVeyor) {
            cd $appveyor_cwd
            Set-PSDebug -Off
        }
    }
}

Verify-ArchitectureAppVeyor