-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbuild.ps1
More file actions
325 lines (266 loc) · 11.4 KB
/
Copy pathbuild.ps1
File metadata and controls
325 lines (266 loc) · 11.4 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
[CmdletBinding()]
param(
[string]$Configuration = "Release",
[string]$Platform = "x64",
[string]$Timestamp = "2030-01-01 00:00:00",
[switch]$KeepIntermediates,
[switch]$CheckDependencies
)
Set-StrictMode -Version 3.0
$ErrorActionPreference = "Stop"
$ProjectRoot = $PSScriptRoot
$SourceRoot = Join-Path $ProjectRoot "src"
$BinDir = Join-Path $ProjectRoot "bin"
$SourceArtifacts = @(
(Join-Path $ProjectRoot "obj"),
(Join-Path $SourceRoot ".vs"),
(Join-Path $SourceRoot "obj"),
(Join-Path $SourceRoot "x64")
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
function Write-Info([string]$Message) { Write-Host $Message -ForegroundColor Cyan }
function Write-Step([string]$Message) { Write-Host $Message -ForegroundColor DarkGray }
function Write-Success([string]$Message) { Write-Host $Message -ForegroundColor Green }
function Write-Failure([string]$Message) { Write-Host $Message -ForegroundColor Red }
function Get-NormalizedPath([string]$Path) {
return [System.IO.Path]::GetFullPath($Path).TrimEnd('\')
}
function Test-PathInside([string]$BasePath, [string]$CandidatePath) {
$base = Get-NormalizedPath $BasePath
$candidate = Get-NormalizedPath $CandidatePath
if ($candidate.Equals($base, [System.StringComparison]::OrdinalIgnoreCase)) { return $true }
return $candidate.StartsWith($base + "\", [System.StringComparison]::OrdinalIgnoreCase)
}
function Remove-SafePath([string]$Path) {
if (-not (Test-Path -LiteralPath $Path)) { return }
$resolved = (Resolve-Path -LiteralPath $Path).Path
if (-not (Test-PathInside -BasePath $ProjectRoot -CandidatePath $resolved)) {
throw "Refusing to remove a path outside the project root: $resolved"
}
if ((Get-NormalizedPath $resolved) -eq (Get-NormalizedPath $SourceRoot)) {
throw "Refusing to remove the source root: $resolved"
}
Write-Step "Removing $resolved"
Remove-Item -LiteralPath $resolved -Recurse -Force
}
function Parse-FixedTimestamp([string]$Value) {
$styles = [System.Globalization.DateTimeStyles]::AllowWhiteSpaces -bor
[System.Globalization.DateTimeStyles]::AssumeLocal
try {
return [datetime]::Parse($Value, [System.Globalization.CultureInfo]::InvariantCulture, $styles)
}
catch {
throw "Invalid -Timestamp '$Value'. Example: 2030-01-01 00:00:00"
}
}
# ---------------------------------------------------------------------------
# Dynamic Visual Studio discovery (newest available >= 17.x)
# ---------------------------------------------------------------------------
function Find-VisualStudio {
$vswhere = Join-Path ${env:ProgramFiles(x86)} "Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path -LiteralPath $vswhere) {
$baseArgs = @(
"-products", "*",
"-requires", "Microsoft.Component.MSBuild",
"-version", "[17.0,)",
"-property", "installationPath",
"-latest"
)
foreach ($extraArg in @(@(), @("-prerelease"))) {
$path = & $vswhere @($baseArgs + $extraArg) 2>$null | Select-Object -First 1
if ($path) { $path = $path.Trim() }
if ($path -and (Test-Path -LiteralPath (Join-Path $path "Common7\Tools\VsDevCmd.bat"))) {
return $path
}
}
}
# Registry fallback
$regHive = @(
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\Setup\Instances\*",
"HKLM:\SOFTWARE\Microsoft\VisualStudio\Setup\Instances\*"
)
$hit = $regHive | ForEach-Object {
if (Test-Path $_) { Get-ItemProperty -Path $_ -ErrorAction SilentlyContinue }
} | Where-Object {
$_.InstallationPath -and
$_.InstallationVersion -and
([version]$_.InstallationVersion).Major -ge 17 -and
(Test-Path -LiteralPath (Join-Path $_.InstallationPath "Common7\Tools\VsDevCmd.bat"))
} | Sort-Object { [version]$_.InstallationVersion } -Descending | Select-Object -First 1
if ($hit) { return $hit.InstallationPath }
# Filesystem fallback -- walk %ProgramFiles%\Microsoft Visual Studio\{17,18,...}
$vsRoot = Join-Path $env:ProgramFiles "Microsoft Visual Studio"
if (Test-Path -LiteralPath $vsRoot) {
$found = Get-ChildItem -LiteralPath $vsRoot -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '^\d+$' -and [int]$_.Name -ge 17 } |
Sort-Object { [int]$_.Name } -Descending |
ForEach-Object {
Get-ChildItem -LiteralPath $_.FullName -Directory -ErrorAction SilentlyContinue
} | Where-Object {
Test-Path -LiteralPath (Join-Path $_.FullName "Common7\Tools\VsDevCmd.bat")
} | Select-Object -ExpandProperty FullName -First 1
if ($found) { return $found }
}
throw "Visual Studio 2022 or newer (17.x+) with MSBuild was not found."
}
# ---------------------------------------------------------------------------
# Dynamic project file discovery
# ---------------------------------------------------------------------------
function Find-ProjectFile {
$vcxproj = Get-ChildItem -LiteralPath $SourceRoot -Filter "*.vcxproj" -ErrorAction SilentlyContinue |
Select-Object -First 1
if (-not $vcxproj) {
throw "No .vcxproj found in: $SourceRoot"
}
return $vcxproj.FullName
}
# ---------------------------------------------------------------------------
# Build
# ---------------------------------------------------------------------------
function Invoke-MsBuild {
param(
[string]$VsDevCmdPath,
[string]$MsBuildPath,
[string]$ProjectPath,
[string]$ProjectName
)
$tempCmd = Join-Path $env:TEMP ("{0}-build-{1}.cmd" -f $ProjectName, $PID)
$cmdContent = @"
@echo off
call "$VsDevCmdPath" -no_logo -arch=amd64 -host_arch=amd64
if errorlevel 1 exit /b %errorlevel%
"$MsBuildPath" "$ProjectPath" /t:Rebuild /p:Configuration=$Configuration /p:Platform=$Platform /m /nologo /v:m
exit /b %errorlevel%
"@
Set-Content -LiteralPath $tempCmd -Value $cmdContent -Encoding ASCII
try {
& $env:ComSpec /d /c $tempCmd
if ($LASTEXITCODE -ne 0) { throw "MSBuild failed with exit code $LASTEXITCODE." }
}
finally {
Remove-Item -LiteralPath $tempCmd -Force -ErrorAction SilentlyContinue
}
}
# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------
function Get-BuildOutput([string]$ProjectName) {
$exePath = Join-Path $BinDir "$ProjectName.exe"
if (-not (Test-Path -LiteralPath $exePath)) {
throw "Expected output not found: $exePath"
}
return $exePath
}
function Set-FixedFileTimestamp {
param([string[]]$Paths, [datetime]$Value)
foreach ($path in $Paths) {
$item = Get-Item -LiteralPath $path
$item.CreationTime = $Value
$item.LastWriteTime = $Value
$item.LastAccessTime = $Value
}
}
# ---------------------------------------------------------------------------
# Optional dumpbin import check
# ---------------------------------------------------------------------------
function Test-NoDependencies {
param([string]$ExePath, [string]$VsDevCmdPath)
Write-Info "Checking imports with dumpbin."
$tempCmd = Join-Path $env:TEMP ("dumpbin-check-{0}.cmd" -f $PID)
$outFile = Join-Path $env:TEMP ("dumpbin-out-{0}.txt" -f $PID)
$cmdContent = @"
@echo off
call "$VsDevCmdPath" -no_logo -arch=amd64 -host_arch=amd64 >nul 2>&1
dumpbin /dependents "$ExePath" > "$outFile" 2>&1
exit /b %errorlevel%
"@
Set-Content -LiteralPath $tempCmd -Value $cmdContent -Encoding ASCII
try {
& $env:ComSpec /d /c $tempCmd
}
finally {
Remove-Item -LiteralPath $tempCmd -Force -ErrorAction SilentlyContinue
}
if (-not (Test-Path -LiteralPath $outFile)) {
Write-Step "dumpbin output not captured -- skipping dependency check."
return
}
$lines = Get-Content -LiteralPath $outFile
Remove-Item -LiteralPath $outFile -Force -ErrorAction SilentlyContinue
# Extract imported DLL names (lines after "Image has the following dependencies:")
$inSection = $false
$deps = [System.Collections.Generic.List[string]]::new()
foreach ($line in $lines) {
if ($line -match 'Image has the following dependencies') { $inSection = $true; continue }
if ($inSection) {
if ($line -match '^\s*$' -and $deps.Count -gt 0) { break }
$dll = $line.Trim()
if ($dll -and $dll -notmatch '^Summary') { $deps.Add($dll) }
}
}
$allowed = @("ntdll.dll")
if ($deps.Count -eq 0) {
Write-Success "dumpbin: no external DLL dependencies (fully self-contained)."
return
}
$unexpected = $deps | Where-Object { $allowed -notcontains $_.ToLower() }
foreach ($d in $deps) {
$color = if ($allowed -contains $d.ToLower()) { "Green" } else { "Yellow" }
Write-Host " $d" -ForegroundColor $color
}
if ($unexpected) {
Write-Host "WARNING: unexpected dependencies detected (see above)." -ForegroundColor Yellow
}
else {
Write-Success "dumpbin: only expected dependencies (ntdll.dll)."
}
}
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
try {
Write-Info "Preparing deterministic BootBypass build."
$ProjectPath = Find-ProjectFile
$ProjectName = [System.IO.Path]::GetFileNameWithoutExtension($ProjectPath)
Write-Step "Project: $ProjectPath"
$fixedTimestamp = Parse-FixedTimestamp -Value $Timestamp
$fixedTimestampText = $fixedTimestamp.ToString("yyyy-MM-dd HH:mm:ss", [System.Globalization.CultureInfo]::InvariantCulture)
Write-Info "Locating Visual Studio (2022 or newer)."
$vsPath = Find-VisualStudio
$vsDevCmd = Join-Path $vsPath "Common7\Tools\VsDevCmd.bat"
$msbuild = Join-Path $vsPath "MSBuild\Current\Bin\MSBuild.exe"
if (-not (Test-Path -LiteralPath $msbuild)) {
throw "MSBuild.exe not found under: $vsPath"
}
Write-Step "Visual Studio : $vsPath"
Write-Step "Timestamp : $fixedTimestampText"
$epoch = [DateTimeOffset]::new($fixedTimestamp).ToUnixTimeSeconds()
$env:SOURCE_DATE_EPOCH = [string]$epoch
Write-Step "SOURCE_DATE_EPOCH=$($env:SOURCE_DATE_EPOCH)"
# Clean previous intermediates and bin
foreach ($path in $SourceArtifacts) { Remove-SafePath -Path $path }
Remove-SafePath -Path $BinDir
New-Item -ItemType Directory -Path $BinDir | Out-Null
Write-Step "Created clean output directory: $BinDir"
Write-Info "Building."
Invoke-MsBuild -VsDevCmdPath $vsDevCmd -MsBuildPath $msbuild `
-ProjectPath $ProjectPath -ProjectName $ProjectName
Write-Success "Build completed."
$exePath = Get-BuildOutput -ProjectName "bb"
Set-FixedFileTimestamp -Paths @($exePath) -Value $fixedTimestamp
Write-Step "Applied fixed timestamp to output."
if ($CheckDependencies) {
Test-NoDependencies -ExePath $exePath -VsDevCmdPath $vsDevCmd
}
if (-not $KeepIntermediates) {
foreach ($path in $SourceArtifacts) { Remove-SafePath -Path $path }
}
Write-Success "Output:"
Write-Success " $exePath"
}
catch {
Write-Failure $_.Exception.Message
exit 1
}