Repository navigation
Expand file tree
/
Copy pathBuild.WinUI.ps1
More file actions
411 lines (335 loc) · 16.6 KB
/
Copy pathBuild.WinUI.ps1
File metadata and controls
411 lines (335 loc) · 16.6 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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
<#
.SYNOPSIS
Builds a signed NativeAOT msixbundle from Telegram.WinUI.csproj.
.DESCRIPTION
The WinUI 3 flavour, packaged by the single-project MSIX tooling that is already on in the
project - there is no wapproj, unlike the .NET Native and Modern flavours.
The bundle carries its own identity, 38833FF26BA1D.UnigramWinUIBundle, so it installs beside
the loose layout Add-AppxPackage -Register puts on during development: Windows will not move
an installed app between a registered layout and a bundle, so the two cannot share a name. The
protocol, alias and file type claims are suffixed to match, so neither steals the other's.
One architecture per run. The result is a real msixbundle either way; carrying several would
mean building the native components for each, and only x64 has ever been built here.
Takes tens of minutes - most of it the ILC link, which this flavour has never been through.
.EXAMPLE
.\Build.WinUI.ps1
.EXAMPLE
.\Build.WinUI.ps1 -SkipNative
#>
[CmdletBinding()]
param(
[ValidateSet('x64', 'ARM64')]
[string] $Platform = 'x64',
[ValidateSet('Release', 'Debug')]
[string] $Configuration = 'Release',
# Bundle installs beside the development layout; Layout builds the bundle under the identity
# the layout registers, which can then only replace it.
[ValidateSet('Bundle', 'Layout')]
[string] $Identity = 'Bundle',
# The two C++/WinRT components, which the app's ProjectReferences would otherwise build again.
[switch] $SkipNative,
# No identity: a self-contained publish folder instead of a bundle.
[switch] $Unpackaged,
# The unpackaged build's version, which has no manifest of its own to take it from. Defaults to
# the release package's.
[version] $Version
)
$ErrorActionPreference = 'Stop'
$installer = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer'
$vswhere = Join-Path $installer 'vswhere.exe'
if (-not (Test-Path $vswhere)) {
throw "vswhere.exe not found at $vswhere"
}
# On PATH, not merely found: ILC shells out to vswhere looking for link.exe, and without it the
# AOT step dies with MSB3073 naming link.exe rather than the thing that actually went missing.
$env:PATH = "$installer;$env:PATH"
$vs = & $vswhere -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath
if (-not $vs) {
throw 'No Visual Studio installation with MSBuild was found.'
}
$msbuild = Join-Path $vs 'MSBuild\Current\Bin\amd64\MSBuild.exe'
if (-not (Test-Path $msbuild)) {
throw "MSBuild.exe not found at $msbuild"
}
# Through the solution, never the project file, as Build.Modern.ps1 does: $(SolutionDir) is empty
# otherwise, and the native projects then write their .winmd somewhere other than where a solution
# build of the app looks.
$solution = Join-Path $PSScriptRoot 'Telegram.WinUI.slnx'
# The natives restore through packages.config, which -restore skips without this.
$common = @("-p:Configuration=$Configuration", '-p:RestorePackagesConfig=true', '-nologo', '-verbosity:minimal')
function Invoke-MSBuild {
param([string[]] $Arguments, [string] $Description)
Write-Host "==> $Description" -ForegroundColor Cyan
& $msbuild @Arguments
if ($LASTEXITCODE -ne 0) {
throw "$Description failed with exit code $LASTEXITCODE."
}
}
# The GUID in a binary's CodeView record and the PDB path its linker wrote; $null without one.
function Get-CodeView {
param([string] $Path)
$stream = [System.IO.File]::OpenRead($Path)
try {
$reader = New-Object System.IO.BinaryReader($stream)
$stream.Position = 0x3C
$pe = $reader.ReadInt32()
$stream.Position = $pe + 6
$sections = $reader.ReadUInt16()
$stream.Position = $pe + 20
$optionalSize = $reader.ReadUInt16()
# The debug directory is the seventh data directory, which PE32+ puts 16 bytes later.
$optional = $pe + 24
$stream.Position = $optional
$stream.Position = $optional + $(if ($reader.ReadUInt16() -eq 0x20B) { 112 } else { 96 }) + 6 * 8
$rva = $reader.ReadUInt32()
$size = $reader.ReadUInt32()
$offset = $null
for ($i = 0; $i -lt $sections -and $rva -ne 0; $i++) {
$stream.Position = $optional + $optionalSize + 40 * $i + 8
$virtualSize = $reader.ReadUInt32()
$virtualAddress = $reader.ReadUInt32()
$stream.Position += 4
$rawAddress = $reader.ReadUInt32()
if ($rva -ge $virtualAddress -and $rva -lt $virtualAddress + $virtualSize) {
$offset = $rva - $virtualAddress + $rawAddress
break
}
}
if ($null -eq $offset) {
return $null
}
for ($entry = $offset; $entry -lt $offset + $size; $entry += 28) {
$stream.Position = $entry + 12
$type = $reader.ReadUInt32()
$stream.Position = $entry + 24
$stream.Position = $reader.ReadUInt32()
if ($type -ne 2 -or [System.Text.Encoding]::ASCII.GetString($reader.ReadBytes(4)) -ne 'RSDS') {
continue
}
$guid = New-Object Guid (, $reader.ReadBytes(16))
$stream.Position += 4
$name = New-Object System.Collections.Generic.List[byte]
while (($byte = $reader.ReadByte()) -ne 0) {
$name.Add($byte)
}
return [pscustomobject]@{ Guid = $guid; Path = [System.Text.Encoding]::UTF8.GetString($name.ToArray()) }
}
return $null
}
finally {
$stream.Dispose()
}
}
# The GUID in a PDB's info stream, the second stream of its MSF container; $null if it has none.
function Get-PdbGuid {
param([string] $Path)
$stream = [System.IO.File]::OpenRead($Path)
try {
$reader = New-Object System.IO.BinaryReader($stream)
if ([System.Text.Encoding]::ASCII.GetString($reader.ReadBytes(24)) -ne 'Microsoft C/C++ MSF 7.00') {
return $null
}
$stream.Position = 32
$blockSize = $reader.ReadInt32()
$stream.Position = 44
$directorySize = $reader.ReadInt32()
$stream.Position = 52
$blockMap = $reader.ReadInt32()
# The stream directory is itself spread over blocks, which the block map lists.
$stream.Position = [long] $blockMap * $blockSize
$blocks = @(for ($i = 0; $i -lt [Math]::Ceiling($directorySize / $blockSize); $i++) { $reader.ReadInt32() })
$directory = New-Object System.IO.MemoryStream
foreach ($block in $blocks) {
$stream.Position = [long] $block * $blockSize
$directory.Write($reader.ReadBytes($blockSize), 0, $blockSize)
}
# Stream count, every stream's size, then each stream's blocks in order: stream 1's first
# block comes right after stream 0's.
$directory.Position = 0
$entries = New-Object System.IO.BinaryReader($directory)
$count = $entries.ReadInt32()
$first = $entries.ReadInt32()
$directory.Position = 4 + 4 * $count + 4 * [Math]::Ceiling([Math]::Max($first, 0) / $blockSize)
# Version, signature and age come before the GUID.
$stream.Position = [long] $entries.ReadInt32() * $blockSize + 12
return New-Object Guid (, $reader.ReadBytes(16))
}
finally {
$stream.Dispose()
}
}
if (-not $SkipNative) {
# Node reuse off: a leftover node holds pch.pch open and the next build dies with MSB6003.
Invoke-MSBuild -Description "Telegram.Native, Telegram.Native.Calls ($Configuration|$Platform)" -Arguments (
@($solution, '-target:Telegram_Native;Telegram_Native_Calls', '-restore', "-p:Platform=$Platform", '-nodeReuse:false') + $common)
}
if ($Unpackaged) {
$arch = $Platform.ToLowerInvariant()
$publish = Join-Path $PSScriptRoot "Telegram\bin\winui-unpackaged\$Platform\$Configuration\publish"
if (-not $Version) {
[xml] $release = Get-Content (Join-Path $PSScriptRoot 'Telegram.Msix\Package.appxmanifest') -Raw
$Version = $release.Package.Identity.Version
}
if ($Version.Revision -lt 0) {
throw "-Version needs four parts, got $Version."
}
# Publish only adds to the folder, and whatever an earlier one left there would ship.
if (Test-Path $publish) {
Remove-Item $publish -Recurse -Force
}
Invoke-MSBuild -Description "Telegram.Updater ($Configuration|$Platform)" -Arguments (
@($solution, '-target:Telegram_Updater', "-p:Platform=$Platform", '-nodeReuse:false') + $common)
Invoke-MSBuild -Description "Telegram.WinUI ($Configuration|$Platform, unpackaged $Version)" -Arguments (
@($solution, '-target:Telegram_WinUI:Publish', '-restore',
"-p:Platform=$Platform",
"-p:PublishProfile=Properties\PublishProfiles\winui-$arch.pubxml",
'-p:Unpackaged=true',
"-p:WinUIPackageVersion=$Version",
"-p:PublishDir=$publish\",
'-nodeReuse:false') + $common)
# The natives, the vcpkg libraries and tdjson import the desktop CRT, which the package gets from
# the UWPDesktop framework and nothing provides without one, so it goes beside the app: the
# redistributable's own folder, deployed app-local. Taken from the default toolset's version, so
# it is never older than the code that links it.
$vc = Join-Path $vs 'VC'
$redist = (Get-Content (Join-Path $vc 'Auxiliary\Build\Microsoft.VCRedistVersion.default.txt') -TotalCount 1).Trim()
$crt = Get-ChildItem (Join-Path $vc "Redist\MSVC\$redist\$arch") -Directory -Filter 'Microsoft.VC*.CRT' -ErrorAction SilentlyContinue
if (-not $crt) {
throw "No C++ runtime redistributable for $arch under $vc\Redist\MSVC\$redist."
}
Copy-Item (Join-Path $crt[0].FullName '*.dll') $publish -Force
# In app\ with everything else; the app copies it out to the root before running it.
Copy-Item (Join-Path $PSScriptRoot "$Platform\$Configuration\Updater.exe") $publish -Force
$output = Split-Path $publish -Parent
$files = Get-ChildItem $publish -Recurse -File | Where-Object Extension -ne '.pdb'
# What the app checks a downloaded update against before staging it. Paths use forward slashes,
# as zip entry names do.
$manifest = [ordered]@{
version = "$Version"
arch = $arch
files = @($files | ForEach-Object {
[ordered]@{
path = $_.FullName.Substring($publish.Length + 1).Replace('\', '/')
size = $_.Length
sha256 = (Get-FileHash $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
}
})
}
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
$package = Join-Path $output "Telegram-$Version-$arch.zip"
if (Test-Path $package) {
Remove-Item $package -Force
}
Write-Host "==> $package" -ForegroundColor Cyan
$zip = [System.IO.Compression.ZipFile]::Open($package, 'Create')
try {
$entry = $zip.CreateEntry('manifest.json')
$writer = New-Object System.IO.StreamWriter($entry.Open(), (New-Object System.Text.UTF8Encoding($false)))
try {
$writer.Write(($manifest | ConvertTo-Json -Depth 4))
}
finally {
$writer.Dispose()
}
foreach ($file in $files) {
$name = 'payload/' + $file.FullName.Substring($publish.Length + 1).Replace('\', '/')
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $file.FullName, $name, 'Optimal') | Out-Null
}
}
finally {
$zip.Dispose()
}
# Every PDB of a binary built here, beside the package rather than in it. Publish only carries
# four; the rest - the updater's, vcpkg's - are where their linker wrote them. Each is matched
# to its binary by GUID: vcpkg's bin\ copy of a PDB is not always the build that shipped.
# Microsoft's binaries name build-agent paths, and their PDBs are on its symbol server.
$vcpkg = Join-Path $PSScriptRoot "vcpkg_installed\$arch-windows\$arch-windows\bin"
$symbols = New-Object System.Collections.Generic.List[System.IO.FileInfo]
foreach ($binary in $files | Where-Object Extension -in '.dll', '.exe') {
$codeView = Get-CodeView $binary.FullName
if (-not $codeView) {
continue
}
$name = Split-Path $codeView.Path -Leaf
$pdb = @((Join-Path $publish $name), $codeView.Path, (Join-Path $vcpkg $name)) |
Where-Object { [System.IO.Path]::IsPathRooted($_) -and (Test-Path -LiteralPath $_) -and (Get-PdbGuid $_) -eq $codeView.Guid } |
Select-Object -First 1
if ($pdb) {
$symbols.Add((Get-Item -LiteralPath $pdb))
}
elseif ($codeView.Path.StartsWith($PSScriptRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "No PDB matching $($binary.Name) was found, although it was built here as $($codeView.Path)."
}
}
$symbolsPackage = Join-Path $output "Telegram-$Version-$arch-symbols.zip"
if (Test-Path $symbolsPackage) {
Remove-Item $symbolsPackage -Force
}
Write-Host "==> $symbolsPackage ($($symbols.Count) PDBs)" -ForegroundColor Cyan
$zip = [System.IO.Compression.ZipFile]::Open($symbolsPackage, 'Create')
try {
foreach ($pdb in $symbols) {
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $pdb.FullName, $pdb.Name, 'Optimal') | Out-Null
}
}
finally {
$zip.Dispose()
}
# Per-user installs of Inno Setup land under LOCALAPPDATA, machine-wide ones under Program Files.
$iscc = @(
(Get-Command 'ISCC.exe' -ErrorAction SilentlyContinue).Source
Join-Path ${env:ProgramFiles(x86)} 'Inno Setup 6\ISCC.exe'
Join-Path $env:LOCALAPPDATA 'Programs\Inno Setup 6\ISCC.exe'
) | Where-Object { $_ -and (Test-Path $_) }
if ($iscc) {
Write-Host "==> Installer ($Version, $arch)" -ForegroundColor Cyan
& @($iscc)[0] '/Q' "/DAppVersion=$Version" "/DArch=$arch" "/DPublishDir=$publish" "/DOutputDir=$output" (Join-Path $PSScriptRoot 'Telegram.Installer\Telegram.iss')
if ($LASTEXITCODE -ne 0) {
throw "ISCC failed with exit code $LASTEXITCODE."
}
}
else {
Write-Warning 'Inno Setup 6 was not found, so there is no installer: winget install JRSoftware.InnoSetup'
}
Write-Host ''
Write-Host $output -ForegroundColor Green
return
}
$packages = Join-Path $PSScriptRoot 'Telegram\AppPackages'
# Publish, not Build: the payload has to be the AOT output, and the packaging targets take it from
# the profile's PublishDir. GenerateAppxPackageOnBuild is what produces an msix at all outside
# Visual Studio, and AppxBundle=Always what makes it a bundle rather than a loose one.
Invoke-MSBuild -Description "Telegram.WinUI ($Configuration|$Platform, $Identity identity)" -Arguments (
@($solution, '-target:Telegram_WinUI:Publish', '-restore',
"-p:Platform=$Platform",
"-p:PublishProfile=Properties\PublishProfiles\winui-$($Platform.ToLowerInvariant()).pubxml",
"-p:WinUIIdentity=$Identity",
'-p:Unpackaged=false',
'-p:GenerateAppxPackageOnBuild=true',
'-p:AppxBundle=Always',
"-p:AppxBundlePlatforms=$Platform",
'-p:UapAppxPackageBuildMode=SideloadOnly',
'-p:AppxPackageSigningEnabled=true',
"-p:AppxPackageDir=$packages\",
'-nodeReuse:false') + $common)
$bundle = Get-ChildItem $packages -Recurse -Filter '*.msixbundle' -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime | Select-Object -Last 1
if (-not $bundle) {
throw "The build reported success but no .msixbundle was found under $packages."
}
# The desktop CRT framework the manifest names - see Package.Win32.Final.xslt. The packaging
# targets only lay down the Windows App Runtime here, and Add-AppDevPackage.ps1 installs whatever
# it finds, so a machine without the Visual C++ redistributable gets the framework with the app.
if ($Configuration -ne 'Debug') {
$arch = $Platform.ToLowerInvariant()
$vclibs = Join-Path ${env:ProgramFiles(x86)} "Microsoft SDKs\Windows Kits\10\ExtensionSDKs\Microsoft.VCLibs.Desktop\14.0\Appx\Retail\$arch\Microsoft.VCLibs.$arch.14.00.Desktop.appx"
if (-not (Test-Path $vclibs)) {
throw "Microsoft.VCLibs.140.00.UWPDesktop not found at $vclibs. Install the Windows SDK's Desktop C++ runtime package."
}
$dependencies = Join-Path $bundle.DirectoryName "Dependencies\$arch"
New-Item -ItemType Directory -Force $dependencies | Out-Null
Copy-Item $vclibs $dependencies -Force
}
Write-Host ''
Write-Host ("{0} ({1:N0} bytes)" -f $bundle.FullName, $bundle.Length) -ForegroundColor Green
Write-Host 'Install with Add-AppDevPackage.ps1 beside the bundle, which also trusts the test certificate.'