Reduce Windows DLL dependencies and package release 0.2.1

This commit is contained in:
tongtong committed 2026-11-13 12:24:24 +08:00
1 parent fc0edd433f
commit efaf16de18
17 files changed
+153 -21

No files matched your search

+13 -2
View File
@@ -1,16 +1,27 @@
param(
[string]$Runtime = 'win-x64',
[ValidateSet('win-x64','win-arm64','linux-x64','linux-arm64','osx-x64','osx-arm64')][string]$Runtime = 'win-x64',
[switch]$FrameworkDependent
)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$outputDirectory = Join-Path $projectRoot "bin/desktop-$Runtime"
$selfContained = if ($FrameworkDependent) { 'false' } else { 'true' }
# Publish to a fresh staging folder so obsolete runtime DLLs cannot survive upgrades.
$stage = Join-Path $projectRoot ('bin/publish-desktop-' + [guid]::NewGuid().ToString('N'))
$publishOptions=@()
if ($Runtime.StartsWith('win-') -and -not $FrameworkDependent) {
$publishOptions=@('-p:PublishSingleFile=true','-p:IncludeNativeLibrariesForSelfExtract=false','-p:EnableCompressionInSingleFile=true','-p:DebugType=embedded')
}
Push-Location (Join-Path $projectRoot 'desktop')
try {
dotnet publish Ads.Desktop -c Release -r $Runtime --self-contained $selfContained -o $outputDirectory --nologo
dotnet publish Ads.Desktop -c Release -r $Runtime --self-contained $selfContained -o $stage --nologo @publishOptions
if ($LASTEXITCODE -ne 0) { throw 'Desktop publish failed' }
} finally { Pop-Location }
if (Test-Path -LiteralPath $outputDirectory) {
if (Get-ChildItem -LiteralPath $outputDirectory -Recurse -File -Filter '*.env') { throw 'Private env file in release directory; refusing to replace it' }
Remove-Item -LiteralPath $outputDirectory -Recurse -Force
}
Move-Item -LiteralPath $stage -Destination $outputDirectory
$suffix = if ($Runtime.StartsWith('win-')) { '.exe' } else { '' }
foreach ($toolName in @('ads-client', 'ads-usb', 'adsctl', 'ads-agent')) {
$client = Join-Path $projectRoot ('bin/' + $toolName + $suffix)
+4
View File
@@ -6,6 +6,10 @@ try {
flutter build windows --release -t lib/main.dart
if ($LASTEXITCODE -ne 0) { throw 'Flutter publish failed' }
} finally { Pop-Location }
if (Test-Path -LiteralPath $output) {
if (Get-ChildItem -LiteralPath $output -Recurse -File -Filter '*.env') { throw 'Private env file in release directory; refusing to replace it' }
Remove-Item -LiteralPath $output -Recurse -Force
}
New-Item -ItemType Directory -Force -Path $output | Out-Null
Copy-Item -Path (Join-Path $projectRoot 'flutter_manager/build/windows/x64/runner/Release/*') -Destination $output -Recurse -Force
foreach ($name in @('ads-client','ads-agent','adsctl','ads-usb')) {
+5 -7
View File
@@ -32,13 +32,11 @@ foreach ($name in @('Avalonia','Flutter')) {
if ($LASTEXITCODE) { throw "$name build failed" }
}
$source=Join-Path $root "bin/$folder"
if ($name -eq 'Flutter') {
$crt=Get-ChildItem "$env:ProgramFiles/Microsoft Visual Studio/2022/*/VC/Redist/MSVC/*/x64/Microsoft.VC143.CRT" -Directory -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
if ($crt) { Copy-Item -Path (Join-Path $crt.FullName '*.dll') -Destination $source -Force }
foreach ($runtime in @('msvcp140.dll','vcruntime140.dll','vcruntime140_1.dll')) {
if (-not (Test-Path -LiteralPath (Join-Path $source $runtime))) { throw "Missing redistributable C++ runtime: $runtime" }
}
}
$crt=Get-ChildItem "$env:ProgramFiles/Microsoft Visual Studio/2022/*/VC/Redist/MSVC/*/x64/Microsoft.VC143.CRT" -Directory -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
$crtArgs=@((Join-Path $PSScriptRoot 'check-windows-crt.py'),$source)
if ($crt) { $crtArgs+=@('--runtime-dir',$crt.FullName) }
& python @crtArgs
if ($LASTEXITCODE) { throw 'Unresolved C++ runtime dependency in release payload' }
& (Join-Path $PSScriptRoot 'copy-windows-usb-driver.ps1') -Destination $source
if (-not (Test-Path -LiteralPath (Join-Path $source 'ads-usb.exe'))) { Copy-Item -LiteralPath (Join-Path $root 'bin/ads-usb.exe') -Destination $source }
foreach ($file in @($exe,'adsctl.exe','ads-agent.exe','ads-client.exe','tools/scrcpy/adb.exe','tools/scrcpy/scrcpy.exe')) {
+82
View File
@@ -0,0 +1,82 @@
"""Resolve only required app-local MSVC runtime DLLs, or fail if missing.
Uses PE import and delay-import tables; no third-party Python modules required.
"""
import re
import struct
import sys
from pathlib import Path
def imports(path):
data = path.read_bytes()
if data[:2] != b'MZ':
raise ValueError(f'Not PE: {path}')
pe = struct.unpack_from('<I', data, 60)[0]
if data[pe:pe+4] != b'PE\0\0':
raise ValueError(f'Invalid PE: {path}')
count, optional_size = struct.unpack_from('<H12xH', data, pe+6)
optional = pe+24
plus = struct.unpack_from('<H', data, optional)[0] == 0x20b
directories = optional + (112 if plus else 96)
image_base = struct.unpack_from('<Q' if plus else '<I', data, optional+(24 if plus else 28))[0]
sections = []
for i in range(count):
size, rva, raw_size, raw = struct.unpack_from('<IIII', data, optional+optional_size+i*40+8)
sections.append((rva, max(size, raw_size), raw))
def offset(rva):
for base, size, raw in sections:
if base <= rva < base+size:
return raw+rva-base
raise ValueError(f'Unmapped RVA in {path}')
result = []
for index, stride in ((1, 20), (13, 32)):
rva, size = struct.unpack_from('<II', data, directories+index*8)
if not rva:
continue
start = offset(rva)
for at in range(start, start+size, stride):
row = data[at:at+stride]
if not any(row):
break
name = struct.unpack_from('<I', row, 12 if index == 1 else 4)[0]
if index == 13 and not (struct.unpack_from('<I', row)[0] & 1):
name -= image_base
at_name = offset(name)
result.append(data[at_name:data.index(b'\0', at_name)].decode('ascii').lower())
return result
def main():
import argparse
import shutil
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('folder', type=Path)
parser.add_argument('--runtime-dir', type=Path)
args = parser.parse_args()
folder = args.folder
pending = sorted([*folder.glob('*.exe'), *folder.glob('*.dll')])
if not pending:
raise ValueError('No Windows binaries to validate')
checked = set()
runtime = set()
while pending:
binary = pending.pop()
if binary.name.lower() in checked:
continue
checked.add(binary.name.lower())
for name in imports(binary):
if not re.match(r'(msvcp|vcruntime|vccorlib|concrt)\d', name):
continue
runtime.add(name)
target = folder / name
if not target.exists():
provider = next((p for p in args.runtime_dir.glob('*.dll') if p.name.lower() == name), None) if args.runtime_dir else None
if provider is None:
raise SystemExit(f'Missing MSVC runtime: {binary.name} requires {name}')
shutil.copyfile(provider, target)
pending.append(target)
print(f'PASS: {len(checked)} root PE files checked; required app-local CRT: {", ".join(sorted(runtime)) or "none"}')
if __name__ == '__main__':
main()
+1 -1
View File
@@ -14,7 +14,7 @@ def update(root, reuse=False):
version = f"{major}.{minor}.{patch + 1}"
changes = {cargo: content.replace(f'version = "{old}"', f'version = "{version}"', 1)}
lock = root / "Cargo.lock"
changes[lock] = re.sub(r'(name = "ads-[^"\n]+"\nversion = ")[^"]+("\n)', lambda m: m[1] + version + m[2], lock.read_text(encoding="utf-8"))
changes[lock] = re.sub(r'(name = "(?:ads-[^"\n]+|adsctl)"\nversion = ")[^"]+("\n)', lambda m: m[1] + version + m[2], lock.read_text(encoding="utf-8"))
pub = root / "flutter_manager/pubspec.yaml"
changes[pub] = re.sub(r'^version: ([^\n]+)', lambda m: f"version: {version}+{int(m[1].split('+')[1]) + 1}", pub.read_text(encoding="utf-8"), flags=re.M)
project = root / "desktop/Ads.Desktop/Ads.Desktop.csproj"