diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 72a873d4..ad7cc48e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -91,17 +91,15 @@ jobs: run: | npm install --prefix target/tsc --no-save --ignore-scripts --no-package-lock typescript@5.9.3 $tsc = (Resolve-Path target/tsc/node_modules/typescript/bin/tsc).Path - $windowsWinmd = Get-ChildItem 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata' ` - -Filter Windows.winmd -File -Recurse | - Sort-Object FullName -Descending | - Select-Object -First 1 - if (-not $windowsWinmd) { - throw 'Windows SDK metadata is required for declaration tests' - } "DYNWINRT_TSC=$tsc" >> $env:GITHUB_ENV - "DYNWINRT_WINDOWS_WINMD=$($windowsWinmd.FullName)" >> $env:GITHUB_ENV "DYNWINRT_REQUIRE_TSC=1" >> $env:GITHUB_ENV - uses: NuGet/setup-nuget@v2 + - name: Restore pinned Windows SDK corpus + shell: pwsh + run: | + $winmd = .\eng\ci\restore-windows-metadata.ps1 ` + -OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus') + "DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV - name: Install Win32 metadata shell: pwsh run: | diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index bbe33c65..c6ebe048 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -15,6 +15,7 @@ on: - 'crates/dynwinrt/**' - 'crates/dynwinrt-com-contracts/**' - 'eng/coverage/**' + - 'eng/ci/restore-windows-metadata.ps1' - 'tests/e2e/**' - 'tools/dynwinrt-codegen/**' push: @@ -57,6 +58,13 @@ jobs: - uses: NuGet/setup-nuget@v2 + - name: Restore pinned Windows SDK corpus + shell: pwsh + run: | + $winmd = .\eng\ci\restore-windows-metadata.ps1 ` + -OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus') + "DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV + - name: Install cargo-llvm-cov shell: pwsh run: cargo install cargo-llvm-cov --version 0.8.7 --locked diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fe460372..e9e010c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,6 +44,20 @@ cargo build -p dynwinrt-codegen ### Running Tests +The codegen's exhaustive Windows SDK corpus assertions use the immutable +`Microsoft.Windows.SDK.CPP` package pinned in +`tools/dynwinrt-codegen/tests/windows_sdk_corpus.json`, not whichever SDK servicing +update is installed on the machine. Restore and verify that metadata before +running codegen library tests or the coverage pipeline (requires `nuget` on PATH): + +```powershell +$env:DYNWINRT_WINDOWS_WINMD = .\eng\ci\restore-windows-metadata.ps1 ` + -OutputDirectory .\target\windows-sdk-corpus +``` + +CI uses the same helper and SHA-256 pin. A missing or different corpus fails with +restore instructions rather than skipping the exact member/count assertions. + ```bash # Core library tests cargo test -p dynwinrt diff --git a/Cargo.lock b/Cargo.lock index ef9eaa42..da399b7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -357,8 +357,10 @@ dependencies = [ "dynwinrt-com-contracts", "dynwinrt-win32-contracts", "fs2", + "object", "regex", "roxmltree", + "semver", "serde", "serde_json", "sha2", @@ -733,6 +735,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.3" diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index 414acb95..149554f8 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -25,6 +25,7 @@ pollster = "0.4.0" serde_json = "1" serde = { version = "1", features = ["derive"] } libffi = "5.1.0" +sha2 = "0.10" [dependencies.windows] version = ">=0.59, <=0.62" diff --git a/bindings/js/README.md b/bindings/js/README.md index c830059c..5c4fbc8a 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -19,7 +19,7 @@ dynamically at runtime. There is no native build step in the consuming Electron or Node project. The same generated bindings can work across compatible metadata revisions without rebuilding a native addon. -The runtime primarily targets **data-style WinRT APIs** (AI, storage, notifications, networking, globalization, …). It also supports WinUI `Application + Window` hosting through the generated `Application.create()` helper when the caller supplies an STA UI thread, an initialized Windows App SDK runtime, and application lifecycle. Unpackaged callers can initialize the runtime with `initWinappsdk()`; the helper resolves the framework resources from that package graph. It also enables Per-Monitor V2 DPI awareness on the UI thread. +The runtime primarily targets **data-style WinRT APIs** (AI, storage, notifications, networking, globalization, …). It also supports WinUI `Application + Window` hosting through the generated `Application.create()` helper when the caller supplies an STA UI thread, an initialized Windows App SDK runtime, and application lifecycle. Unpackaged callers initialize the runtime with explicit `initWinappsdk(major, minor)` arguments, or `initWinappsdk()` after importing a configured generated package; see [Windows App SDK initialization](#windows-app-sdk-initialization). The helper resolves the framework resources from that package graph. It also enables Per-Monitor V2 DPI awareness on the UI thread. ### System DispatcherQueue loading @@ -96,6 +96,82 @@ contains duplicate short names, each canonical module keeps its native symbol name while the root barrel uses a namespace-qualified name, such as `AIFoundationEmbeddingVector` or `SemanticSearchEmbeddingVector`. +### Windows App SDK initialization + +The existing `initWinappsdk` API returns `void`. Explicit version calls keep their +native/environment behavior; the optional third argument supplies the DLL path +without setting a process environment variable: + +```js +const { initWinappsdk } = require('@microsoft/dynwinrt'); +initWinappsdk(2, 5, bootstrapDllPath); +``` + +Generate bindings with `--winappsdk-version 2.5` and +[`--winappsdk-bootstrap-path PATH`](../../tools/dynwinrt-codegen/README.md#packaged-windows-app-sdk-initialization), +accepting a DLL file or a directory such as `.winapp\bin`; repeat the option for +multiple inputs. Directories are searched recursively for the Bootstrap DLL +without following links or searching system/global package locations. +Architecture is read from each PE, and byte-identical duplicates are deduplicated. +Unsupported directory matches are reported and ignored; explicit unsupported +files, corrupt matches and directories with no supported DLL fail. Then the normal +generated package or type import registers configuration, without initializing anything: + +```js +import { initWinappsdk, roInitialize } from '@microsoft/dynwinrt'; +import { Application } from '@winapp/bindings'; + +roInitialize(0); // The application selects the UI apartment. +initWinappsdk(); +// Create and run Application here. +``` + +CJS, ESM, proxy barrels and generated type subpaths share registration. Import the +generated module before calling the no-argument initializer; no extra setup +function, ROOT or config argument is required. Generated packages declare an +exact runtime peer dependency so the application and generated modules resolve +the same runtime installation. `npm pack` includes the DLLs, JSON configuration +and notices, and registration is marked as a side effect for bundlers. Runtime +paths are package-relative, independent of the working directory. + +Bootstrap bundling requires `--import-name` to name an npm package exposing the +`/winappsdk` support entry point (the default is `@microsoft/dynwinrt`). +File imports and package subpaths are rejected, even when a later generation pass +omits the Bootstrap options. File-based runtime imports remain supported when +generating without Bootstrap bundling in a clean output directory. + +Missing imported configuration, partial version arguments, conflicting product +versions or differing DLL payloads produce explicit errors. Identical bundles +can be registered by multiple generated packages. The codegen-support +`@microsoft/dynwinrt/winappsdk` subpath is internal to generated registration; +applications still call `initWinappsdk`, not a replacement initializer. + +Explicit DLL paths take precedence over `WINAPPSDK_BOOTSTRAP_DLL_PATH`. +No-argument calls use the environment when set, otherwise the generated resource +for `process.arch`; invalid overrides fail rather than falling back. Existing +`initWinappsdk(major, minor)` calls do not consult registered packages. + +The native process-lifetime cache remains: matching versions return after a +successful initialization; other versions fail. New explicit/generated DLL +selections additionally retain their first successful payload digest, accepting +byte-identical copies but rejecting a later different payload. A process first +initialized through the legacy two-version-argument path has no recorded DLL +digest; restart before switching it to explicit/generated DLL selection. +Initialization failures are not cached. `getWinappsdkResourcePriPath()` remains +available, and there is no automatic shutdown or Runtime installation. + +Importing generated configuration does not initialize COM or Bootstrap, and +`initWinappsdk` does not choose an apartment. The example's apartment-first order +is a conservative use of the documented Bootstrap prerequisite, not a claim that +the existing init-first examples fail on modern Windows. Package identity alone +does not make initialization a successful no-op. + +The Bootstrap DLL is not the complete Windows App Runtime and is governed by the +Microsoft Windows App SDK license, not dynwinrt's MIT license. Runtime deployment +and redistribution as part of a qualifying application remain the producer's +responsibility. Without the generation options, existing Windows SDK-only output +and calls remain unchanged. + ### Standalone WinRT interface implementations Metadata-generated standalone WinRT interfaces expose `implementation(handlers)` diff --git a/bindings/js/__test__/winappsdk-config.e2e.cjs b/bindings/js/__test__/winappsdk-config.e2e.cjs new file mode 100644 index 00000000..d903748a --- /dev/null +++ b/bindings/js/__test__/winappsdk-config.e2e.cjs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +'use strict' + +const assert = require('node:assert/strict') +const { createHash } = require('node:crypto') +const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = require('node:fs') +const { tmpdir } = require('node:os') +const { join } = require('node:path') +const { test } = require('node:test') + +const environment = 'WINAPPSDK_BOOTSTRAP_DLL_PATH' +const dllName = 'Microsoft.WindowsAppRuntime.Bootstrap.dll' + +function fixture(t, label = 'bundle') { + const root = mkdtempSync(join(tmpdir(), `dynwinrt-${label}-`)) + t.after(() => rmSync(root, { recursive: true, force: true })) + const config = { schema_version: 1, major: 2, minor: 5, dlls: {} } + for (const arch of ['x64', 'arm64']) { + const dir = join(root, '_native', 'winappsdk', arch) + mkdirSync(dir, { recursive: true }) + const content = Buffer.from(`test resource ${arch}`) + writeFileSync(join(dir, dllName), content) + config.dlls[arch] = createHash('sha256').update(content).digest('hex') + } + return { root, source: join(root, '_winappsdk.cjs'), config } +} + +function runtime(t) { + const module = require.resolve('../runtime/winappsdk.cjs') + delete require.cache[module] + const helpers = require(module) + const previous = process.env[environment] + delete process.env[environment] + t.after(() => { + if (previous === undefined) delete process.env[environment] + else process.env[environment] = previous + }) + const calls = [] + const init = helpers.createInitializer((...args) => { + calls.push(args) + }) + return { ...helpers, init, calls } +} + +test('missing configuration and partial versions fail without initializing', (t) => { + const { init, calls } = runtime(t) + assert.throws(() => init(), /No generated Windows App SDK configuration/) + assert.throws(() => init(2), /both major and minor/) + assert.throws(() => init(undefined, 5), /both major and minor/) + assert.deepEqual(calls, []) +}) + +test('explicit versions retain native/environment behavior despite registered conflicts', (t) => { + const { init, calls, registerConfig } = runtime(t) + const first = fixture(t) + const second = fixture(t) + registerConfig(first.source, first.config) + registerConfig(second.source, { ...second.config, minor: 6 }) + process.env[environment] = 'unchanged relative legacy.dll' + assert.equal(init(2, 5), undefined) + assert.deepEqual(calls, [[2, 5]]) + assert.equal(process.env[environment], 'unchanged relative legacy.dll') +}) + +test('registration is inert and consistent providers merge independently of import order', (t) => { + const { init, calls, registerConfig } = runtime(t) + const first = fixture(t) + const second = fixture(t) + registerConfig(second.source, second.config) + registerConfig(first.source, first.config) + registerConfig(first.source, first.config) + assert.equal(calls.length, 0) + init() + const selected = [first, second].sort((a, b) => a.source.localeCompare(b.source))[0] + assert.deepEqual(calls, [[2, 5, join(selected.root, '_native', 'winappsdk', process.arch, dllName)]]) + assert.equal(process.env[environment], undefined) +}) + +test('conflicting versions and payloads name both provider sources', (t) => { + const { init, calls, registerConfig } = runtime(t) + const first = fixture(t) + const second = fixture(t) + registerConfig(first.source, first.config) + registerConfig(second.source, { ...second.config, dlls: { ...second.config.dlls, x64: '0'.repeat(64) } }) + assert.throws(init, (error) => { + assert.match(error.message, /Conflicting generated/) + assert.ok(error.message.includes(first.source) && error.message.includes(second.source)) + return true + }) + assert.equal(calls.length, 0) +}) + +test('explicit path wins over environment and environment wins over generated resources', (t) => { + const { init, calls, registerConfig } = runtime(t) + const { root, source, config } = fixture(t) + registerConfig(source, config) + const fromEnv = join(root, 'env.dll') + const explicit = join(root, 'explicit.dll') + writeFileSync(fromEnv, '') + writeFileSync(explicit, '') + process.env[environment] = fromEnv + init() + init(2, 5, explicit) + assert.deepEqual(calls, [ + [2, 5, fromEnv], + [2, 5, explicit], + ]) + assert.equal(process.env[environment], fromEnv) + for (const invalid of ['', ' ', 'bad\0path', join(root, 'missing.dll')]) { + assert.throws(() => init(2, 5, invalid)) + } + process.env[environment] = '' + assert.throws(init, /nonempty path/) + assert.equal(calls.length, 2) +}) + +test('modified resources fail before initialization', (t) => { + const { init, calls, registerConfig } = runtime(t) + const { root, source, config } = fixture(t) + registerConfig(source, config) + writeFileSync(join(root, '_native', 'winappsdk', process.arch, dllName), 'changed') + assert.throws(init, /digest mismatch/) + assert.equal(calls.length, 0) +}) + +test('missing generated resources report reinstallation', (t) => { + const { init, calls, registerConfig } = runtime(t) + const { root, source, config } = fixture(t) + registerConfig(source, config) + rmSync(join(root, '_native', 'winappsdk', process.arch, dllName)) + assert.throws(init, /Reinstall the complete generated package/) + assert.equal(calls.length, 0) +}) + +test('invalid schema fields and changed registration fail closed', (t) => { + const { registerConfig } = runtime(t) + const { source, config } = fixture(t) + for (const invalid of [ + { ...config, schema_version: 2 }, + { ...config, major: -1 }, + { ...config, minor: 65536 }, + { ...config, minor: 1.5 }, + { ...config, extra: true }, + { ...config, dlls: {} }, + { ...config, dlls: { x86: '0'.repeat(64) } }, + ]) { + assert.throws(() => registerConfig(source, invalid), /Invalid Windows App SDK configuration/) + } + registerConfig(source, config) + assert.throws(() => registerConfig(source, { ...config, minor: 6 }), /configuration changed/) +}) + +test('native failures preserve the original exception and do not poison retries', (t) => { + const { createInitializer, registerConfig } = runtime(t) + const { source, config } = fixture(t) + registerConfig(source, config) + const error = new Error('native failure') + let calls = 0 + const init = createInitializer(() => { + if (++calls === 1) throw error + }) + assert.throws(init, (caught) => caught === error) + assert.equal(init(), undefined) + assert.equal(calls, 2) +}) diff --git a/bindings/js/package.json b/bindings/js/package.json index f5119798..6ab222e1 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -11,6 +11,12 @@ "require": "./dist/winrt.js", "default": "./dist/winrt.js" }, + "./winappsdk": { + "types": "./dist/winappsdk-config.d.ts", + "import": "./dist/winappsdk-config.js", + "require": "./dist/winappsdk-config.js", + "default": "./dist/winappsdk-config.js" + }, "./com": { "types": "./dist/com.d.ts", "import": "./dist/com.js", @@ -45,6 +51,9 @@ }, "typesVersions": { "*": { + "winappsdk": [ + "dist/winappsdk-config.d.ts" + ], "com": [ "dist/com.d.ts" ], @@ -108,7 +117,8 @@ "format:toml": "taplo format", "format:rs": "cargo fmt", "lint": "oxlint", - "test": "npm run test:types && ava && npm run test:native-classes && npm run test:interface-inputs", + "test": "npm run test:types && ava && npm run test:native-classes && npm run test:interface-inputs && npm run test:winappsdk", + "test:winappsdk": "node --test __test__/winappsdk-config.e2e.cjs", "test:interface-inputs": "node --test __test__/interface-inputs.e2e.mjs", "test:native-classes": "node --test __test__/native-class-boundary.e2e.mjs", "test:native-classes:hooks": "node --test __test__/native-class-boundary-hooks.e2e.mjs", diff --git a/bindings/js/runtime/winappsdk.cjs b/bindings/js/runtime/winappsdk.cjs new file mode 100644 index 00000000..467b3c5d --- /dev/null +++ b/bindings/js/runtime/winappsdk.cjs @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +'use strict' + +const { createHash } = require('node:crypto') +const { readFileSync, statSync } = require('node:fs') +const { dirname, isAbsolute, join, resolve } = require('node:path') + +const configurations = new Map() +const dllName = 'Microsoft.WindowsAppRuntime.Bootstrap.dll' + +function configuration(source, value) { + const invalid = (reason) => new TypeError(`Invalid Windows App SDK configuration from ${source}: ${reason}`) + if (typeof source !== 'string' || !isAbsolute(source)) { + throw invalid('source must be the absolute generated configuration module path') + } + if ( + !value || + typeof value !== 'object' || + Array.isArray(value) || + Object.keys(value).sort().join(',') !== 'dlls,major,minor,schema_version' + ) { + throw invalid('unexpected configuration fields') + } + if (value.schema_version !== 1) throw invalid('unsupported schema_version') + for (const name of ['major', 'minor']) { + if (!Number.isInteger(value[name]) || value[name] < 0 || value[name] > 65535) { + throw invalid(`${name} must be an integer between 0 and 65535`) + } + } + if ( + !value.dlls || + typeof value.dlls !== 'object' || + !Object.keys(value.dlls).length || + Object.keys(value.dlls).some((arch) => !['x64', 'arm64'].includes(arch)) + ) { + throw invalid('x64 and/or arm64 DLL digests are required') + } + const dlls = {} + for (const arch of Object.keys(value.dlls).sort()) { + if (typeof value.dlls[arch] !== 'string' || !/^[0-9a-f]{64}$/.test(value.dlls[arch])) { + throw invalid(`invalid ${arch} SHA-256 digest`) + } + dlls[arch] = value.dlls[arch] + } + return Object.freeze({ + source: resolve(source), + major: value.major, + minor: value.minor, + dlls: Object.freeze(dlls), + identity: JSON.stringify([value.major, value.minor, dlls]), + }) +} + +function registerConfig(source, value) { + const config = configuration(source, value) + const previous = configurations.get(config.source) + if (previous && previous.identity !== config.identity) { + throw new Error(`Windows App SDK configuration changed in ${config.source}; restart with one SDK bundle`) + } + configurations.set(config.source, config) +} + +function discover() { + const configs = [...configurations.values()].sort((a, b) => a.source.localeCompare(b.source)) + if (!configs.length) { + throw new Error( + 'No generated Windows App SDK configuration has been imported. Import the generated bindings package ' + + 'before initWinappsdk(), or pass major, minor and bootstrapDllPath explicitly.', + ) + } + const first = configs[0] + if (configs.some((item) => item.identity !== first.identity)) { + throw new Error( + 'Conflicting generated Windows App SDK configurations: ' + + configs.map((item) => `${item.source}: ${item.major}.${item.minor}`).join('; ') + + '. Use one consistent SDK bundle or pass explicit initialization arguments.', + ) + } + return first +} + +function explicitPath(value) { + if (typeof value !== 'string' || !value.trim() || value.includes('\0')) { + throw new TypeError('Windows App SDK bootstrapDllPath must be a nonempty path without NUL') + } + const path = resolve(value) + if (!statSync(path).isFile()) { + throw new Error(`Windows App SDK bootstrap DLL is not a file: ${path}`) + } + return path +} + +function resourcePath(config) { + if (process.platform !== 'win32' || !['x64', 'arm64'].includes(process.arch)) { + throw new Error(`Unsupported Node platform ${process.platform}/${process.arch}; use Windows x64 or ARM64 Node.js`) + } + if (!config.dlls[process.arch]) { + throw new Error( + `Windows App SDK configuration from ${config.source} has no ${process.arch} DLL; install matching bindings`, + ) + } + const path = join(dirname(config.source), '_native', 'winappsdk', process.arch, dllName) + let bytes + try { + bytes = readFileSync(path) + } catch (error) { + if (error.code !== 'ENOENT') throw error + throw new Error( + `Generated Windows App SDK bootstrap DLL is missing: ${path}. Reinstall the complete generated package.`, + { cause: error }, + ) + } + const digest = createHash('sha256').update(bytes).digest('hex') + if (digest !== config.dlls[process.arch]) { + throw new Error(`Windows App SDK bootstrap DLL digest mismatch: ${path}. Reinstall the complete generated package.`) + } + return path +} + +function createInitializer(initialize) { + return function initWinappsdk(major, minor, bootstrapDllPath) { + if (arguments.length !== 0) { + if (major === undefined || minor === undefined) { + throw new TypeError('initWinappsdk() requires both major and minor, or neither') + } + if (bootstrapDllPath === undefined) return initialize(major, minor) + return initialize(major, minor, explicitPath(bootstrapDllPath)) + } + const config = discover() + const override = process.env.WINAPPSDK_BOOTSTRAP_DLL_PATH + const path = override !== undefined ? explicitPath(override) : resourcePath(config) + return initialize(config.major, config.minor, path) + } +} + +module.exports.registerConfig = registerConfig +module.exports.createInitializer = createInitializer diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index c3196846..be5716aa 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -212,7 +212,11 @@ const winrtExports = nativeExports.filter( (name) => !name.startsWith('DynCom') && !name.startsWith('DynWin32') && !name.startsWith('win32') && name !== 'initializeCom', ) -writeFacade('winrt', winrtExports, [...winrtExports, 'DynWinRtImplementationMethod'], [], [ +writeFacade('winrt', winrtExports, [...winrtExports.filter((name) => name !== 'initWinappsdk'), 'DynWinRtImplementationMethod'], [], [ + '/** Initialize from the imported generated SDK configuration; does not initialize COM. */', + 'export declare function initWinappsdk(): void', + '/** Explicit versions keep the existing native/environment initialization behavior. */', + 'export declare function initWinappsdk(major: number, minor: number, bootstrapDllPath?: string): void', '/** A generated interface plan and its synchronous, metadata-ordered dispatcher. */', 'export interface DynWinRtImplementationDescriptor {', " readonly plan: import('./index.js').DynWinRtInterfacePlan", @@ -495,6 +499,22 @@ writeFileSync( join(distDir, 'com-projection.js'), readFileSync(join(packageDir, 'runtime', 'com-projection.cjs'), 'utf8'), ) +writeFileSync( + join(distDir, 'winappsdk-internal.cjs'), + readFileSync(join(packageDir, 'runtime', 'winappsdk.cjs'), 'utf8'), +) +writeFileSync(join(distDir, 'winappsdk-config.js'), [ + '// Generated by scripts/generate-entrypoints.mjs - do not edit', + "'use strict'", + "module.exports.__registerWinAppSdkConfig = require('./winappsdk-internal.cjs').registerConfig", + '', +].join('\n')) +writeFileSync(join(distDir, 'winappsdk-config.d.ts'), [ + '// Generated by scripts/generate-entrypoints.mjs - do not edit', + '/** @internal Used by generated packages. Registration does not initialize the Runtime or COM. */', + 'export declare function __registerWinAppSdkConfig(source: string, config: unknown): void', + '', +].join('\n')) function writeFacade( name, @@ -515,6 +535,7 @@ function writeFacade( "const native = require('./index.js')", ...exports.map((value) => `module.exports.${value} = native.${value}`), ...(name === 'winrt' ? [ + "module.exports.initWinappsdk = require('./winappsdk-internal.cjs').createInitializer(native.initWinappsdk)", "module.exports.DynWinRtImplementationHandle = require('./winrt-implementation.cjs').DynWinRtImplementationHandle", ] : []), ...(comProjection ? [ diff --git a/bindings/js/src/initialization.rs b/bindings/js/src/initialization.rs index a2c88ec8..a859adf1 100644 --- a/bindings/js/src/initialization.rs +++ b/bindings/js/src/initialization.rs @@ -2,11 +2,13 @@ // Licensed under the MIT License. use napi_derive::napi; -use std::{cell::Cell, sync::OnceLock}; +use sha2::{Digest, Sha256}; +use std::{cell::Cell, io::Read, path::Path, sync::OnceLock}; struct InitializedWinAppSdk { major: u32, minor: u32, + bootstrap_dll_digest: Option<[u8; 32]>, context: dynwinrt::WinAppSdkContext, } @@ -27,38 +29,93 @@ pub(crate) fn winui_dispatcher_loop_exited() -> bool { /// Add Windows App SDK to the process package graph without changing the calling thread's apartment. #[napi] -pub fn init_winappsdk(major: u32, minor: u32) -> napi::Result<()> { +pub fn init_winappsdk( + major: u32, + minor: u32, + bootstrap_dll_path: Option, +) -> napi::Result<()> { + let resolved_path = if let Some(path) = &bootstrap_dll_path { + if path.trim().is_empty() || path.contains('\0') || !std::path::Path::new(path).is_file() { + return Err(napi::Error::from_reason( + "Windows App SDK bootstrapDllPath must name an existing DLL file", + )); + } + Some(std::fs::canonicalize(path).map_err(|error| { + napi::Error::from_reason(format!("Cannot resolve Bootstrap DLL {path}: {error}")) + })?) + } else { + None + }; + let dll_digest = resolved_path + .as_deref() + .map(bootstrap_digest) + .transpose() + .map_err(|error| napi::Error::from_reason(format!("Cannot read Bootstrap DLL: {error}")))?; if let Some(initialized) = WINAPP_SDK.get() { - return ensure_winappsdk_version(initialized, major, minor); + return ensure_winappsdk_request(initialized, major, minor, dll_digest.as_ref()); } - let context = dynwinrt::initialize_winappsdk(major, minor) - .map_err(|e| napi::Error::from_reason(e.message()))?; + let context = dynwinrt::initialize_winappsdk_with_options(dynwinrt::WinAppSdkBootstrapOptions { + major_version: major, + minor_version: minor, + build_version: 0, + revision_version: 0, + bootstrap_dll_path: resolved_path + .as_ref() + .map(|path| path.to_string_lossy().into_owned()), + }) + .map_err(|e| napi::Error::from_reason(e.message()))?; let initialized = InitializedWinAppSdk { major, minor, + bootstrap_dll_digest: dll_digest, context, }; match WINAPP_SDK.set(initialized) { Ok(()) => Ok(()), - Err(_) => ensure_winappsdk_version(WINAPP_SDK.get().unwrap(), major, minor), + Err(_) => { + ensure_winappsdk_request(WINAPP_SDK.get().unwrap(), major, minor, dll_digest.as_ref()) + } + } +} + +fn bootstrap_digest(path: &Path) -> std::io::Result<[u8; 32]> { + let mut file = std::fs::File::open(path)?; + let mut digest = Sha256::new(); + let mut buffer = [0; 16384]; + loop { + let length = file.read(&mut buffer)?; + if length == 0 { + break; + } + digest.update(&buffer[..length]); } + Ok(digest.finalize().into()) } -fn ensure_winappsdk_version( +fn ensure_winappsdk_request( initialized: &InitializedWinAppSdk, major: u32, minor: u32, + bootstrap_dll_digest: Option<&[u8; 32]>, ) -> napi::Result<()> { - if initialized.major == major && initialized.minor == minor { - Ok(()) - } else { - Err(napi::Error::from_reason(format!( + if initialized.major != major || initialized.minor != minor { + return Err(napi::Error::from_reason(format!( "Windows App SDK is already initialized for {}.{}; cannot reinitialize for {major}.{minor}", initialized.major, initialized.minor - ))) + ))); + } + if let Some(digest) = bootstrap_dll_digest { + if initialized.bootstrap_dll_digest.as_ref() != Some(digest) { + return Err(napi::Error::from_reason( + "Windows App SDK is already initialized with another Bootstrap DLL selection; \ + restart the process to select an explicit/generated DLL path. \ + Existing two-version-argument calls keep the original initialization.", + )); + } } + Ok(()) } /// Return the framework resources.pri path selected by initWinappsdk. @@ -96,3 +153,35 @@ pub(crate) fn set_winui_dispatcher_loop_active(active: bool) { } WINUI_DISPATCHER_LOOP_ACTIVE.with(|state| state.set(active)); } + +#[cfg(test)] +mod bootstrap_tests { + use super::*; + + #[test] + fn explicit_dll_identity_cannot_bypass_the_native_success_cache() { + let initialized = InitializedWinAppSdk { + major: 2, + minor: 5, + bootstrap_dll_digest: Some([1; 32]), + context: dynwinrt::WinAppSdkContext {}, + }; + assert!(ensure_winappsdk_request(&initialized, 2, 5, Some(&[1; 32])).is_ok()); + assert!(ensure_winappsdk_request(&initialized, 2, 5, Some(&[2; 32])).is_err()); + assert!(ensure_winappsdk_request(&initialized, 2, 6, Some(&[1; 32])).is_err()); + assert!(ensure_winappsdk_request(&initialized, 2, 5, None).is_ok()); + } + + #[test] + fn legacy_calls_keep_version_only_cache_semantics() { + let initialized = InitializedWinAppSdk { + major: 2, + minor: 5, + bootstrap_dll_digest: None, + context: dynwinrt::WinAppSdkContext {}, + }; + assert!(ensure_winappsdk_request(&initialized, 2, 5, None).is_ok()); + assert!(ensure_winappsdk_request(&initialized, 2, 6, None).is_err()); + assert!(ensure_winappsdk_request(&initialized, 2, 5, Some(&[1; 32])).is_err()); + } +} diff --git a/bindings/py/README.md b/bindings/py/README.md index f7fa3915..4a977337 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -785,6 +785,64 @@ mismatches also fail rather than returning fabricated values. `take_error()` returns and clears the latest native callback diagnostic; `is_closed` is a read-only property. +## Windows App SDK initialization + +The existing initializer supports explicit versions, and optionally a DLL path: + +```python +from dynwinrt import init_winappsdk + +bootstrap = init_winappsdk(2, 5, bootstrap_dll_path=bootstrap_dll) +``` + +`init_winappsdk(2, 5)` retains its existing behavior and uses +`WINAPPSDK_BOOTSTRAP_DLL_PATH`. Installed generated packages never alter that +explicit two-version-argument path. + +When bindings were generated with the paired +[`--winappsdk-version` / `--winappsdk-bootstrap-path` options](../../tools/dynwinrt-codegen/python/README.md#windows-app-sdk-configuration), +install their package normally or editable. The same initializer can then discover +the installed configuration without application-maintained constants or paths: + +```python +from dynwinrt import RoApartment, init_winappsdk, projected_lifetime_scope + +with RoApartment(0): # The application selects the apartment, not the initializer. + bootstrap = init_winappsdk() + with projected_lifetime_scope(): + # Create and run the application here. + ... +``` + +Discovery uses the generated package's `dynwinrt.winappsdk` entry point; no +generated-package import is required first. It does not scan application source +or infer a version from WinMD names. Missing configuration and conflicting +versions/payloads are errors naming the provider packages; identical bundles can +coexist. Supplying just one version component is an error. + +An explicit `bootstrap_dll_path` overrides the environment, which overrides the +generated resource path. Invalid overrides fail rather than silently falling +back. A path override alone still needs a generated version configuration. +The runtime selects resources for the running Python interpreter, not the OS's +native architecture, and verifies their generated SHA-256 digests. + +Importing a provider does not initialize Bootstrap or COM. The initializer also +does not select STA/MTA; the explicit apartment-first example follows Bootstrap's +documented prerequisite for compatibility across its native implementation paths. +This does not imply that the existing init-first examples fail on modern Windows. + +The result remains `WinAppSDKContext`, including `resource_pri_path()`. It is +**not** a shutdown/RAII context: dropping it does not remove the native package +graph or unload Bootstrap. Repeated calls retain the existing native behavior, +and failed calls can be retried. Changing SDK deployment or replacing loaded +binaries requires a new process. + +The bundled Bootstrap DLL is not the complete Windows App Runtime. Deployment +of a matching Runtime and the SDK's redistribution terms remain the application +producer's responsibility. This API does not install the Runtime or silently +skip initialization merely because the process has package identity. +Ordinary Windows SDK-only generated bindings require none of this configuration. + ## Experimental WinUI support When the required WinUI metadata is generated, `Application.create()` installs diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 7f26c269..c6627b6d 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,5 +1,6 @@ from collections.abc import Coroutine from datetime import datetime, timedelta +from os import PathLike from typing import Any, Awaitable, Callable, Final, Generic, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload from uuid import UUID @@ -703,7 +704,15 @@ class DynWinRtElementFactory: def __repr__(self) -> str: ... -def init_winappsdk(major: int, minor: int) -> WinAppSDKContext: ... +@overload +def init_winappsdk(*, bootstrap_dll_path: str | PathLike[str] | None = ...) -> WinAppSDKContext: ... +@overload +def init_winappsdk( + major: int, + minor: int, + *, + bootstrap_dll_path: str | PathLike[str] | None = ..., +) -> WinAppSDKContext: ... def ro_initialize(apartment_type: Optional[int]) -> None: ... def ro_uninitialize() -> None: ... def retry_pending_apartment_close() -> None: ... diff --git a/bindings/py/python/dynwinrt/__init__.py b/bindings/py/python/dynwinrt/__init__.py index e32dcc55..4330b92f 100644 --- a/bindings/py/python/dynwinrt/__init__.py +++ b/bindings/py/python/dynwinrt/__init__.py @@ -4,6 +4,7 @@ from . import dynwinrt as dynwinrt from .dynwinrt import * from . import values as values +from ._winappsdk import init_winappsdk as init_winappsdk __doc__ = dynwinrt.__doc__ __all__ = dynwinrt.__all__ diff --git a/bindings/py/python/dynwinrt/_winappsdk.py b/bindings/py/python/dynwinrt/_winappsdk.py new file mode 100644 index 00000000..4462011b --- /dev/null +++ b/bindings/py/python/dynwinrt/_winappsdk.py @@ -0,0 +1,168 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Configuration discovery for the explicit Windows App SDK initializer.""" + +from dataclasses import dataclass +import hashlib +from importlib import import_module as _import_module +from importlib.metadata import entry_points +import os +from pathlib import Path +import re +import sysconfig + +from dynwinrt import WinAppSDKContext + +_native = _import_module("dynwinrt.dynwinrt") + +_ENVIRONMENT = "WINAPPSDK_BOOTSTRAP_DLL_PATH" +_GROUP = "dynwinrt.winappsdk" +_DLL = "Microsoft.WindowsAppRuntime.Bootstrap.dll" +_MISSING = object() + + +@dataclass(frozen=True) +class _Configuration: + source: str + root: Path + major: int + minor: int + digests: tuple[tuple[str, str], ...] + + @property + def identity(self) -> tuple[int, int, tuple[tuple[str, str], ...]]: + return self.major, self.minor, self.digests + + +def _configuration(source: str, value: object) -> _Configuration: + def invalid(reason: str) -> ValueError: + return ValueError(f"Invalid Windows App SDK configuration from {source}: {reason}") + + if not isinstance(value, tuple) or len(value) != 2: + raise invalid("provider must return (package_directory, configuration)") + root, config = value + if not isinstance(root, str) or not Path(root).is_absolute(): + raise invalid("package_directory must be an absolute path") + if not isinstance(config, dict) or set(config) != {"schema_version", "major", "minor", "dlls"}: + raise invalid("unexpected configuration fields") + if type(config["schema_version"]) is not int or config["schema_version"] != 1: + raise invalid("unsupported schema_version") + for name in ("major", "minor"): + number = config[name] + if type(number) is not int or not 0 <= number <= 65535: + raise invalid(f"{name} must be an integer between 0 and 65535") + dlls = config["dlls"] + if not isinstance(dlls, dict) or not dlls or not set(dlls) <= {"x64", "arm64"}: + raise invalid("x64 and/or arm64 DLL digests are required") + digests = [] + for architecture in sorted(dlls): + digest = dlls[architecture] + if not isinstance(digest, str) or not re.fullmatch("[0-9a-f]{64}", digest): + raise invalid(f"invalid {architecture} SHA-256 digest") + digests.append((architecture, digest)) + return _Configuration( + source, Path(root), config["major"], config["minor"], tuple(digests) + ) + + +def _discover() -> _Configuration: + configurations = [] + for provider in sorted(entry_points(group=_GROUP), key=lambda item: (item.name, item.value)): + distribution = provider.dist + source = ( + f"{distribution.metadata['Name']}=={distribution.version} ({provider.value})" + if distribution is not None + else f"{provider.name} ({provider.value})" + ) + get_config = provider.load() + if not callable(get_config): + raise TypeError(f"Windows App SDK configuration provider {source} is not callable") + configurations.append(_configuration(source, get_config())) + if not configurations: + raise RuntimeError( + "No generated Windows App SDK configuration is installed. Install the generated " + "bindings package (ordinary or editable), or pass major, minor and " + "bootstrap_dll_path explicitly to init_winappsdk()." + ) + first = configurations[0] + if any(item.identity != first.identity for item in configurations[1:]): + sources = "; ".join( + f"{item.source}: {item.major}.{item.minor}" for item in configurations + ) + raise RuntimeError( + f"Conflicting generated Windows App SDK configurations: {sources}. " + "Use one consistent SDK bundle or pass explicit initialization arguments." + ) + return first + + +def _explicit_path(value: str | os.PathLike[str]) -> str: + path = os.fspath(value) + if not isinstance(path, str) or not path.strip() or "\0" in path: + raise ValueError("Windows App SDK bootstrap_dll_path must be a nonempty path without NUL") + resolved = Path(path).resolve() + if not resolved.is_file(): + raise FileNotFoundError(f"Windows App SDK bootstrap DLL not found: {resolved}") + return str(resolved) + + +def _resource_path(config: _Configuration) -> str: + platform = sysconfig.get_platform().lower().replace("_", "-") + architecture = {"win-amd64": "x64", "win-arm64": "arm64"}.get(platform) + if architecture is None: + raise RuntimeError( + f"Unsupported Python platform {platform!r} for Windows App SDK; " + "use Windows x64 or ARM64 Python." + ) + expected = dict(config.digests).get(architecture) + if expected is None: + raise RuntimeError( + f"Windows App SDK configuration from {config.source} has no {architecture} DLL. " + "Install or generate bindings for the running interpreter architecture." + ) + path = config.root / "_native" / "winappsdk" / architecture / _DLL + try: + data = path.read_bytes() + except FileNotFoundError as error: + raise FileNotFoundError( + f"Generated Windows App SDK bootstrap DLL is missing: {path} ({config.source}). " + "Reinstall the complete generated bindings package." + ) from error + digest = hashlib.sha256(data).hexdigest() + if digest != expected: + raise ValueError( + f"Windows App SDK bootstrap DLL digest mismatch: {path} ({config.source}). " + "Reinstall the complete generated bindings package." + ) + return str(path.resolve()) + + +def init_winappsdk( + major=_MISSING, + minor=_MISSING, + *, + bootstrap_dll_path: str | os.PathLike[str] | None = None, +) -> WinAppSDKContext: + """Initialize explicitly, or discover a consistent installed generated SDK bundle. + + This does not initialize COM, install the Runtime, or unload it on return. + Existing two-version-argument calls keep their native environment semantics. + """ + if major is not _MISSING or minor is not _MISSING: + if major is _MISSING or minor is _MISSING: + raise TypeError("init_winappsdk() requires both major and minor, or neither") + if bootstrap_dll_path is None: + return _native.init_winappsdk(major, minor) + return _native.init_winappsdk( + major, minor, bootstrap_dll_path=_explicit_path(bootstrap_dll_path) + ) + + config = _discover() + override = ( + bootstrap_dll_path + if bootstrap_dll_path is not None + else os.environ.get(_ENVIRONMENT) + ) + path = _explicit_path(override) if override is not None else _resource_path(config) + return _native.init_winappsdk(config.major, config.minor, bootstrap_dll_path=path) diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 55e9a88c..da94c2e8 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -869,10 +869,21 @@ impl RoApartment { } #[pyfunction] -pub fn init_winappsdk(major: u32, minor: u32) -> PyResult { - dynwinrt::initialize_winappsdk(major, minor) - .map(WinAppSDKContext) - .map_err(map_dynwinrt_error) +#[pyo3(signature = (major, minor, *, bootstrap_dll_path=None))] +pub fn init_winappsdk( + major: u32, + minor: u32, + bootstrap_dll_path: Option, +) -> PyResult { + dynwinrt::initialize_winappsdk_with_options(dynwinrt::WinAppSdkBootstrapOptions { + major_version: major, + minor_version: minor, + build_version: 0, + revision_version: 0, + bootstrap_dll_path, + }) + .map(WinAppSDKContext) + .map_err(map_windows_error) } #[pyfunction] diff --git a/bindings/py/tests/test_winappsdk.py b/bindings/py/tests/test_winappsdk.py new file mode 100644 index 00000000..c5285fc6 --- /dev/null +++ b/bindings/py/tests/test_winappsdk.py @@ -0,0 +1,256 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import copy +import hashlib +from pathlib import Path +from types import SimpleNamespace + +import pytest + +import dynwinrt +from dynwinrt import _winappsdk + +ENVIRONMENT = "WINAPPSDK_BOOTSTRAP_DLL_PATH" +DLL = "Microsoft.WindowsAppRuntime.Bootstrap.dll" + + +def bundle(root, major=2, minor=5, architectures=("x64", "arm64")): + config = {"schema_version": 1, "major": major, "minor": minor, "dlls": {}} + for architecture in architectures: + path = root / "_native" / "winappsdk" / architecture / DLL + path.parent.mkdir(parents=True, exist_ok=True) + data = f"test resource {architecture}".encode() + path.write_bytes(data) + config["dlls"][architecture] = hashlib.sha256(data).hexdigest() + return str(root), config + + +def providers(monkeypatch, *values): + entries = [ + SimpleNamespace( + name=f"package_{index}", + value=f"package_{index}._winappsdk:get_config", + dist=SimpleNamespace( + metadata={"Name": f"package-{index}"}, version="0.1.0" + ), + load=lambda value=value: lambda: value, + ) + for index, value in enumerate(values) + ] + + def discover(*, group): + assert group == "dynwinrt.winappsdk" + return entries + + monkeypatch.setattr(_winappsdk, "entry_points", discover) + + +@pytest.fixture +def native_calls(monkeypatch): + calls = [] + result = object() + + def initialize(*args, **kwargs): + calls.append((args, kwargs)) + return result + + monkeypatch.setattr(_winappsdk._native, "init_winappsdk", initialize) + monkeypatch.setattr(_winappsdk.sysconfig, "get_platform", lambda: "win-amd64") + monkeypatch.delenv(ENVIRONMENT, raising=False) + return calls, result + + +def test_missing_provider_is_actionable(monkeypatch, native_calls): + providers(monkeypatch) + with pytest.raises(RuntimeError, match="No generated Windows App SDK configuration"): + dynwinrt.init_winappsdk() + assert native_calls[0] == [] + + +@pytest.mark.parametrize("args,kwargs", [((2,), {}), ((), {"minor": 5})]) +def test_partial_version_never_falls_back_to_discovery(monkeypatch, native_calls, args, kwargs): + monkeypatch.setattr(_winappsdk, "entry_points", lambda **_: pytest.fail("must not discover")) + with pytest.raises(TypeError, match="both major and minor"): + dynwinrt.init_winappsdk(*args, **kwargs) + assert native_calls[0] == [] + + +def test_legacy_explicit_versions_bypass_configuration_and_preserve_env(monkeypatch, native_calls): + monkeypatch.setenv(ENVIRONMENT, "old-relative-dll-path.dll") + monkeypatch.setattr(_winappsdk, "entry_points", lambda **_: pytest.fail("must not discover")) + calls, result = native_calls + assert dynwinrt.init_winappsdk(2, 5) is result + assert dynwinrt.init_winappsdk(major=2, minor=5) is result + assert calls == [((2, 5), {}), ((2, 5), {})] + assert _winappsdk.os.environ[ENVIRONMENT] == "old-relative-dll-path.dll" + + +@pytest.mark.parametrize("platform,architecture", [("win-amd64", "x64"), ("win-arm64", "arm64")]) +def test_generated_resources_use_interpreter_architecture_and_not_cwd( + monkeypatch, tmp_path, native_calls, platform, architecture +): + root = tmp_path / "installed" + providers(monkeypatch, bundle(root)) + monkeypatch.setattr(_winappsdk.sysconfig, "get_platform", lambda: platform) + elsewhere = tmp_path / "different_cwd" + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + calls, result = native_calls + assert dynwinrt.init_winappsdk() is result + assert calls == [ + ((2, 5), {"bootstrap_dll_path": str(root / "_native" / "winappsdk" / architecture / DLL)}) + ] + assert ENVIRONMENT not in _winappsdk.os.environ + + +def test_consistent_providers_merge_and_conflicting_providers_list_sources( + monkeypatch, tmp_path, native_calls +): + first = bundle(tmp_path / "first") + second = bundle(tmp_path / "second") + providers(monkeypatch, first, second) + dynwinrt.init_winappsdk() + assert len(native_calls[0]) == 1 + for changed in [ + {**second[1], "minor": 6}, + {**second[1], "dlls": {**second[1]["dlls"], "x64": "0" * 64}}, + ]: + providers(monkeypatch, first, (second[0], changed)) + with pytest.raises(RuntimeError, match="Conflicting") as error: + dynwinrt.init_winappsdk() + assert "package-0" in str(error.value) and "package-1" in str(error.value) + assert len(native_calls[0]) == 1 + + +def test_explicit_path_and_environment_override_generated_resource( + monkeypatch, tmp_path, native_calls +): + root, config = bundle(tmp_path / "package") + providers(monkeypatch, (root, config)) + override = tmp_path / "override.dll" + override.touch() + explicit = tmp_path / "explicit.dll" + explicit.touch() + monkeypatch.setenv(ENVIRONMENT, str(override)) + for path in Path(root).rglob("*.dll"): + path.unlink() + dynwinrt.init_winappsdk() + dynwinrt.init_winappsdk(bootstrap_dll_path=explicit) + dynwinrt.init_winappsdk(2, 5, bootstrap_dll_path=explicit) + assert [call[1]["bootstrap_dll_path"] for call in native_calls[0]] == [ + str(override), str(explicit), str(explicit) + ] + assert _winappsdk.os.environ[ENVIRONMENT] == str(override) + + +@pytest.mark.parametrize("override", ["", " ", "bad\0path", "missing.dll"]) +def test_bad_overrides_do_not_silently_use_bundle( + monkeypatch, tmp_path, native_calls, override +): + providers(monkeypatch, bundle(tmp_path / "package")) + with pytest.raises((ValueError, FileNotFoundError)): + dynwinrt.init_winappsdk(bootstrap_dll_path=override) + monkeypatch.setenv(ENVIRONMENT, override.replace("\0", "")) + with pytest.raises((ValueError, FileNotFoundError)): + dynwinrt.init_winappsdk() + assert not native_calls[0] + + +def test_modified_resource_rejected_before_native_call(monkeypatch, tmp_path, native_calls): + root = tmp_path / "package" + providers(monkeypatch, bundle(root)) + (root / "_native" / "winappsdk" / "x64" / DLL).write_bytes(b"changed") + with pytest.raises(ValueError, match="digest mismatch"): + dynwinrt.init_winappsdk() + assert not native_calls[0] + + +def test_missing_generated_resource_reports_reinstallation(monkeypatch, tmp_path, native_calls): + root = tmp_path / "package" + providers(monkeypatch, bundle(root)) + (root / "_native" / "winappsdk" / "x64" / DLL).unlink() + with pytest.raises(FileNotFoundError, match="Reinstall the complete generated"): + dynwinrt.init_winappsdk() + assert not native_calls[0] + + +def test_unsupported_architecture_is_clear(monkeypatch, tmp_path, native_calls): + providers(monkeypatch, bundle(tmp_path / "package", architectures=("arm64",))) + with pytest.raises(RuntimeError, match="has no x64 DLL"): + dynwinrt.init_winappsdk() + monkeypatch.setattr(_winappsdk.sysconfig, "get_platform", lambda: "win32") + with pytest.raises(RuntimeError, match="Unsupported Python platform"): + dynwinrt.init_winappsdk() + + +@pytest.mark.parametrize( + "change", + [ + lambda c: c.update(schema_version=2), + lambda c: c.update(schema_version=True), + lambda c: c.update(major=-1), + lambda c: c.update(minor=65536), + lambda c: c.update(major=True), + lambda c: c.update(dlls={}), + lambda c: c.update(dlls={"x86": "0" * 64}), + lambda c: c.update(dlls={"x64": "bad"}), + lambda c: c.update(extra="ignored?"), + ], +) +def test_invalid_provider_fails_closed(monkeypatch, tmp_path, native_calls, change): + root, original = bundle(tmp_path / "package") + config = copy.deepcopy(original) + change(config) + providers(monkeypatch, (root, config)) + with pytest.raises(ValueError, match="configuration from package-0"): + dynwinrt.init_winappsdk() + assert not native_calls[0] + + +def test_native_failure_propagates_and_can_retry(monkeypatch, tmp_path): + providers(monkeypatch, bundle(tmp_path / "package")) + monkeypatch.delenv(ENVIRONMENT, raising=False) + failure = OSError("bootstrap failed") + count = 0 + returned = object() + + def initialize(*args, **kwargs): + nonlocal count + count += 1 + if count == 1: + raise failure + return returned + + monkeypatch.setattr(_winappsdk._native, "init_winappsdk", initialize) + with pytest.raises(OSError) as error: + dynwinrt.init_winappsdk() + assert error.value is failure + assert dynwinrt.init_winappsdk() is returned + assert count == 2 + + +def test_real_native_missing_input_errors_and_return_type_contract(monkeypatch, tmp_path): + import ctypes + + monkeypatch.delenv(ENVIRONMENT, raising=False) + with pytest.raises(OSError, match="bootstrap DLL path is required"): + dynwinrt.init_winappsdk(2, 5) + with pytest.raises(OSError, match="major version component"): + dynwinrt.init_winappsdk(65536, 0) + not_a_dll = tmp_path / "invalid.dll" + not_a_dll.write_bytes(b"not a native library") + kernel = ctypes.WinDLL("kernel32") + kernel.SetErrorMode.argtypes = [ctypes.c_uint] + kernel.SetErrorMode.restype = ctypes.c_uint + previous = kernel.SetErrorMode(0x0001 | 0x8000) + try: + with pytest.raises(OSError): + dynwinrt.init_winappsdk(2, 5, bootstrap_dll_path=not_a_dll) + finally: + kernel.SetErrorMode(previous) + assert hasattr(dynwinrt.WinAppSDKContext, "resource_pri_path") + assert not hasattr(dynwinrt.WinAppSDKContext, "__exit__") + stub = (Path(dynwinrt.__file__).parent / "__init__.pyi").read_text(encoding="utf-8") + assert "def init_winappsdk(*, bootstrap_dll_path:" in stub + assert ") -> WinAppSDKContext:" in stub diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index 82e4cd77..59d03ca8 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -67,7 +67,10 @@ pub use crate::result::{Error, Result}; pub use crate::roapi::ro_get_activation_factory_2; pub use crate::signature::{InterfaceSignature, MethodSignature}; pub use crate::value::{ArrayOfIUnknownData, AsyncInfo, WinRTValue}; -pub use crate::winapp::{WinAppSdkContext, initialize_winappsdk}; +pub use crate::winapp::{ + WinAppSdkBootstrapOptions, WinAppSdkContext, initialize as initialize_winappsdk_with_options, + initialize_winappsdk, +}; pub use crate::winrt_implementation::{ WinRtImplementation, WinRtImplementationCallback, WinRtImplementationPlan, WinRtInterfaceDefinition, WinRtMethodDefinition, WinRtThreadingPolicy, diff --git a/eng/ci/restore-windows-metadata.ps1 b/eng/ci/restore-windows-metadata.ps1 new file mode 100644 index 00000000..e3565846 --- /dev/null +++ b/eng/ci/restore-windows-metadata.ps1 @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory = $true)][string]$OutputDirectory, + [string]$NuGet = "nuget" +) + +$ErrorActionPreference = "Stop" +$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +$pin = Get-Content -LiteralPath (Join-Path $root "tools\dynwinrt-codegen\tests\windows_sdk_corpus.json") -Raw | + ConvertFrom-Json +$destination = [IO.Path]::GetFullPath($OutputDirectory) +$packageRoot = Join-Path $destination "$($pin.package).$($pin.version)" +$winmd = Join-Path $packageRoot $pin.relative_path +if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) { + & $NuGet install $pin.package -Version $pin.version ` + -OutputDirectory $destination -DirectDownload -NonInteractive | Out-Host + if ($LASTEXITCODE -ne 0) { + throw "Failed to restore $($pin.package) $($pin.version)" + } +} +if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) { + throw "Pinned Windows SDK package is missing $($pin.relative_path)" +} +$actual = (Get-FileHash -LiteralPath $winmd -Algorithm SHA256).Hash +if ($actual -ne $pin.sha256) { + throw "Pinned Windows SDK metadata hash mismatch: expected $($pin.sha256), got $actual at $winmd" +} +Write-Host "Verified Windows SDK corpus: $($pin.package) $($pin.version), SHA256 $actual" +(Resolve-Path -LiteralPath $winmd).Path diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py index df818269..c01e2495 100644 --- a/eng/ci/test_ci.py +++ b/eng/ci/test_ci.py @@ -2,6 +2,7 @@ # Licensed under the MIT License. import copy +import hashlib import json import os from pathlib import Path @@ -191,6 +192,87 @@ def test_missing_empty_and_invalid_readmes_fail_in_github_wrapper(self): readme.write_bytes(original) +class WindowsCorpusTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-corpus-") + self.addCleanup(self.temporary.cleanup) + self.repo = Path(self.temporary.name) + self.relative_pin = Path("tools/dynwinrt-codegen/tests/windows_sdk_corpus.json") + self.pin = json.loads((ROOT / self.relative_pin).read_text(encoding="utf-8")) + self.payload = b"test metadata bytes" + self.pin["sha256"] = hashlib.sha256(self.payload).hexdigest() + destination = self.repo / self.relative_pin + destination.parent.mkdir(parents=True) + destination.write_text(json.dumps(self.pin), encoding="utf-8") + self.script = self.repo / "eng/ci/restore-windows-metadata.ps1" + self.script.parent.mkdir(parents=True) + shutil.copyfile(CI / "restore-windows-metadata.ps1", self.script) + self.output = self.repo / "packages" + self.winmd = ( + self.output / f"{self.pin['package']}.{self.pin['version']}" + / self.pin["relative_path"] + ) + self.nuget = self.repo / "nuget.ps1" + self.nuget.write_text( + "param([string]$Command, [string]$Id, [string]$Version, " + "[string]$OutputDirectory, [switch]$DirectDownload, [switch]$NonInteractive)\n" + "if ($Command -ne 'install' -or -not $DirectDownload -or -not $NonInteractive) { exit 2 }\n" + f"if ($Id -ne '{self.pin['package']}' -or $Version -ne '{self.pin['version']}') {{ exit 3 }}\n" + "$package = Join-Path $OutputDirectory \"$Id.$Version\"\n" + f"$path = Join-Path $package '{self.pin['relative_path']}'\n" + "New-Item -ItemType Directory -Path (Split-Path -Parent $path) -Force | Out-Null\n" + "[IO.File]::WriteAllBytes($path, [Text.Encoding]::UTF8.GetBytes('test metadata bytes'))\n" + "exit 0\n", + encoding="utf-8", + ) + + def restore(self): + return powershell( + self.script, "-OutputDirectory", self.output, "-NuGet", self.nuget, + ) + + def test_restore_verifies_content_and_reuses_only_verified_existing_input(self): + result = self.restore() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + returned = Path(result.stdout.strip().splitlines()[-1]) + self.assertTrue(returned.is_absolute()) + self.assertTrue(returned.samefile(self.winmd), f"{returned} != {self.winmd}") + self.assertEqual(self.winmd.read_bytes(), self.payload) + self.nuget.unlink() + result = self.restore() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_modified_input_and_failed_restore_are_errors(self): + self.winmd.parent.mkdir(parents=True) + self.winmd.write_bytes(b"rolling SDK changed in-place") + result = self.restore() + self.assertNotEqual(result.returncode, 0) + self.assertIn("metadata hash mismatch", result.stdout + result.stderr) + self.assertEqual(self.winmd.read_bytes(), b"rolling SDK changed in-place") + self.winmd.unlink() + self.nuget.write_text("exit 7\n", encoding="utf-8") + result = self.restore() + self.assertNotEqual(result.returncode, 0) + self.assertIn("Failed to restore", result.stdout + result.stderr) + + def test_build_and_coverage_share_the_pinned_corpus_input(self): + coverage = yaml.safe_load( + (ROOT / ".github/workflows/coverage.yml").read_text(encoding="utf-8") + ) + triggers = coverage.get("on", coverage.get(True)) + self.assertIn( + "eng/ci/restore-windows-metadata.ps1", triggers["pull_request"]["paths"] + ) + for job in (JOBS["test-rust"], coverage["jobs"]["coverage"]): + step, = [ + step for step in job["steps"] + if step.get("name") == "Restore pinned Windows SDK corpus" + ] + self.assertIn(r".\eng\ci\restore-windows-metadata.ps1", step["run"]) + self.assertIn("DYNWINRT_WINDOWS_WINMD=$winmd", step["run"]) + self.assertNotIn("Sort-Object", step["run"]) + + class WorkflowTests(unittest.TestCase): def ancestors(self, job): needs = JOBS[job].get("needs", []) diff --git a/eng/release/python/verify_generated_python_install.py b/eng/release/python/verify_generated_python_install.py index 75e0205a..c685401f 100644 --- a/eng/release/python/verify_generated_python_install.py +++ b/eng/release/python/verify_generated_python_install.py @@ -2,7 +2,9 @@ # Licensed under the MIT License. import argparse +import hashlib import importlib +import json import os import subprocess import sys @@ -24,7 +26,7 @@ def generated_source_files(root: Path) -> set[Path]: files = { Path(line) for line in inventory.read_text(encoding="utf-8").splitlines() - if Path(line).suffix in {".py", ".pyi"} + if Path(line).suffix in {".py", ".pyi"} and Path(line).parts[0] != "_dynwinrt_build" } invalid = [path for path in files if path.is_absolute() or ".." in path.parts] if invalid: @@ -128,6 +130,20 @@ def main() -> None: f"Installed package has {len(unexpected)} unexpected generated files: " f"{unexpected[:10]}" ) + bundle_manifest = source / ".dynwinrt-winappsdk.json" + if bundle_manifest.is_file(): + bundle = json.loads(bundle_manifest.read_text(encoding="utf-8")) + for name, expected_digest in bundle["files"].items(): + relative = Path(name) + if relative.is_absolute() or ".." in relative.parts or not relative.parts: + raise RuntimeError(f"Invalid Bootstrap inventory path: {name}") + if relative.parts[0] == "_dynwinrt_build" or name == "MANIFEST.in": + if (installed / relative).exists(): + raise RuntimeError(f"Build-only file was installed: {name}") + continue + actual_digest = hashlib.sha256((installed / relative).read_bytes()).hexdigest() + if actual_digest != expected_digest: + raise RuntimeError(f"Installed Bootstrap resource differs from generation: {name}") sys.path.insert(0, str(args.install.resolve())) modules = { diff --git a/tools/dynwinrt-codegen/Cargo.toml b/tools/dynwinrt-codegen/Cargo.toml index dca7ea07..50f8f3a9 100644 --- a/tools/dynwinrt-codegen/Cargo.toml +++ b/tools/dynwinrt-codegen/Cargo.toml @@ -14,8 +14,10 @@ windows-metadata = "0.59.0" clap = { version = "4", features = ["derive"] } csv = "1" fs2 = "0.4" +object = { version = "0.37", default-features = false, features = ["read", "pe", "std"] } roxmltree = "0.20" regex = "1" +semver = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index 204d5dc5..b5f0f848 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -57,10 +57,12 @@ package. | `--ref-list FILE` | Newline-separated reference metadata paths; blank lines and `#` comments are ignored. | | `--lang js\|py` | `js` emits CommonJS `.js`, an ESM facade, and `.d.ts` files (default); `py` emits `.py`, `.pyi`, and `py.typed`. | | `--output DIR` | Dedicated codegen-owned output directory (default `./generated`). Existing contents may be replaced or removed. | -| `--import-name NAME` | Runtime package imported by generated JavaScript (default `@microsoft/dynwinrt`). | +| `--import-name NAME` | Runtime imported by generated JavaScript (default `@microsoft/dynwinrt`). Bootstrap bundling requires an npm package name, not a file path or package subpath. | | `--dry-run` | Validate metadata, dependencies, ABI contracts, and layout without writing files. | | `--pyi` | With `--lang py`, explicitly request the default type stubs; retained for compatibility. | | `--no-pyi` | With `--lang py`, omit `.pyi` files and `py.typed`. | +| `--winappsdk-version MAJOR.MINOR` | Stable Windows App SDK product version, such as `2.5`, not a NuGet servicing version. Requires `--winappsdk-bootstrap-path`. | +| `--winappsdk-bootstrap-path PATH` | Bootstrap DLL file or recursively searched directory; repeat for multiple inputs. Requires `--winappsdk-version`. | ### Examples @@ -146,6 +148,100 @@ machine-readable value per line. `dynwinrt-codegen com-census --winmd [--json]` measures how many eligible interfaces in `Windows.Win32.winmd` have complete safe Classic COM generation. +### Packaged Windows App SDK initialization + +For framework-dependent applications with already-restored SDK inputs: + +```powershell +dynwinrt-codegen generate ` + --winmd-list .\winmd-inputs.txt --ref-list .\winmd-references.txt ` + --lang py --output .\app_bindings ` + --winappsdk-version 2.5 ` + --winappsdk-bootstrap-path '.winapp\bin' +``` + +The same options work with `--lang js`. Each path is a **generation-time input**. +A directory is searched recursively only for `Microsoft.WindowsAppRuntime.Bootstrap.dll` +(case-insensitively on Windows), within that directory and its descendants. +No system directories or global package caches are searched. Directory links and +reparse points are rejected rather than followed, including links back into the +tree. An unreadable directory or damaged/unreadable matching DLL fails generation. + +The generator validates PE/DLL architecture, bounds and the bootstrap export +without executing any input, then copies the original bytes into +`_native/winappsdk//Microsoft.WindowsAppRuntime.Bootstrap.dll`. +Directory matches for unsupported architectures such as x86 are ignored with a +warning; each directory must contain at least one supported x64/ARM64 DLL. +Explicit file inputs still reject unsupported architectures. Repeat the option +to combine directories or concrete files, including renamed files. Only the +architectures identified by PE headers are packaged; directory names and the +generator's architecture do not select or supply DLLs. +Repeated paths and byte-identical DLLs for the same architecture are deduplicated. +Different DLL contents for the same architecture are rejected with both sources +identified, never overwritten. Licenses are checked for every supported source, +including deduplicated DLLs. Input order and overlapping directory/file inputs do +not affect the configuration, payloads or build-cache digest. The SDK's +`win-arm64ec` directory may contain a byte-identical x64 Bootstrap DLL; this is +deduplicated as x64, not treated as native ARM64EC support. + +Concrete files can still be supplied individually: + +```powershell +--winappsdk-bootstrap-path '.winapp\bin\x64\Microsoft.WindowsAppRuntime.Bootstrap.dll' ` +--winappsdk-bootstrap-path '.winapp\bin\arm64\Microsoft.WindowsAppRuntime.Bootstrap.dll' +``` + +`MAJOR.MINOR` is the stable SDK **product** version used by Bootstrap, not the +NuGet servicing version, the DLL's FileVersion, or a minimum Runtime package +version. Preview/experimental channels and three-component versions are rejected. +The caller supplies matching restored inputs; WinMD paths and DLL file versions +do not establish NuGet provenance. + +Python packages register a `dynwinrt.winappsdk` entry point for explicit, +no-argument `dynwinrt.init_winappsdk()`. JavaScript packages register configuration +when imported, enabling the existing `initWinappsdk()` after the normal generated +package/type import. Neither registration nor discovery initializes Bootstrap or +COM automatically. See the [Python runtime](../../bindings/py/README.md#windows-app-sdk-initialization) +and [Node runtime](../../bindings/js/README.md#windows-app-sdk-initialization) for +the calling and override contracts. + +With JavaScript Bootstrap bundling, `--import-name` must be a scoped or unscoped +npm package name exposing the runtime's `/winappsdk` support entry point, such as +the default `@microsoft/dynwinrt`. File paths and package subpaths are rejected +before generation, including later passes that omit the Bootstrap options. +To use a file import such as `../../bindings/js/dist/winrt.js`, generate without +Bootstrap bundling in a clean output directory; that existing mode is unchanged. + +Generated Python wheels use `py3-none-win_amd64`, `py3-none-win_arm64`, or the +compressed `py3-none-win_amd64.win_arm64` tag. The generated setuptools wheel hook +is build-only; both ordinary and editable installations locate DLLs inside the +package. JavaScript `files`/`exports`, an exact runtime peer dependency and +side-effect metadata preserve registration and resources through `npm pack`. +The generated package never embeds the original machine's absolute input path. + +Repeated passes may repeat identical inputs or omit both options to retain the +bundle. `--no-pyi` does not remove its DLLs. A different product version, DLL +payload or source license requires cleaning the dedicated output and regenerating +the complete package; failures leave the original output unchanged. Bundle +digests participate in Python build-cache identity. A new package generated +without these options keeps the existing output and has no App SDK requirement. + +The copied DLLs remain subject to the **Microsoft Windows App SDK license**, not +dynwinrt's MIT license. `NOTICE.txt` records the distribution requirements. +An adjacent/common-directory `license.txt`, or the license in a standard source +NuGet package, is copied unchanged when present; otherwise generation warns the +application producer to supply the matching terms before redistribution. +This is for distributing applications that satisfy the SDK's terms, not for +redistributing the SDK as a standalone offering. The Bootstrap DLL is **not** +the complete Windows App Runtime; matching Runtime deployment is still required. +This feature does not implement MSIX/sparse-identity or self-contained deployment. + +Integrators must check `dynwinrt-codegen capabilities` for +`python.winappsdk-bootstrap-config` or `javascript.winappsdk-bootstrap-config` +before passing these options. Older published generators, including rc23, do not +support them. Use the matching runtime version; local source builds are not a +published upgrade. + ## Generated output The generator resolves transitive dependencies and emits namespace index files. diff --git a/tools/dynwinrt-codegen/npm/cli.js b/tools/dynwinrt-codegen/npm/cli.js index f31c7a1b..6f7597e1 100644 --- a/tools/dynwinrt-codegen/npm/cli.js +++ b/tools/dynwinrt-codegen/npm/cli.js @@ -53,7 +53,10 @@ for (let i = 0; i < args.length; i++) { } try { - execFileSync(exe, exeArgs, { stdio: "inherit" }); + execFileSync(exe, exeArgs, { + stdio: "inherit", + env: { ...process.env, DYNWINRT_CODEGEN_NPM_VERSION: pkg.version }, + }); } catch (e) { process.exit(e.status ?? 1); } diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md index 71140c34..2d72b968 100644 --- a/tools/dynwinrt-codegen/python/README.md +++ b/tools/dynwinrt-codegen/python/README.md @@ -74,10 +74,66 @@ explicitly inside its apartment. | `--dry-run` | Validate metadata and dependencies without writing files. | | `--pyi` | Explicitly request the default Python type stubs; retained for compatibility. | | `--no-pyi` | Omit `.pyi` files and the `py.typed` marker. | +| `--winappsdk-version MAJOR.MINOR` | Stable SDK product version, such as `2.5`, not a NuGet servicing version. Requires `--winappsdk-bootstrap-path`. | +| `--winappsdk-bootstrap-path PATH` | Bootstrap DLL file or recursively searched directory; repeat for multiple inputs. Requires `--winappsdk-version`. | Use `--lang py` for every Python generation command. Run `dynwinrt-codegen generate --help` for the complete command reference. +### Windows App SDK configuration + +Pass the paired options when generating bindings for an application with restored +Windows App SDK inputs: + +```powershell +dynwinrt-codegen generate ` + --winmd-list .\winmd-inputs.txt --ref-list .\winmd-references.txt ` + --lang py --output .\app_bindings ` + --winappsdk-version 2.5 ` + --winappsdk-bootstrap-path '.winapp\bin' +python -m pip install .\app_bindings +``` + +Supply a directory to search for `Microsoft.WindowsAppRuntime.Bootstrap.dll` +within it and its descendants, or concrete DLL files; repeat the option to mix +inputs. Discovery does not search outside the supplied directories or follow +directory links/reparse points. Architecture is read from each DLL, not inferred +from its name or directory. Unsupported directory matches such as x86 are +reported and ignored; explicit unsupported files still fail. A directory with +no supported DLL, an unreadable directory, or a corrupt/unreadable matching file +fails rather than producing a partial bundle. +Byte-identical duplicates are deduplicated without losing their source licenses; +different DLL bytes for the same architecture are an error. Reordering paths +or combining overlapping files/directories does not change the generated +configuration or build-cache digest. + +The generated package contains `_winappsdk.py`, `_winappsdk.json`, the unchanged +DLLs under `_native/winappsdk/x64` and/or `arm64`, and redistribution notices. +It declares an installed `dynwinrt.winappsdk` entry point. The application can +call **`dynwinrt.init_winappsdk()`** without passing a project root, version, path, +or environment variable, even before importing the generated projection. +Initialization remains an explicit application action. + +Normal wheel installs and `pip install -e` work independently of the runtime +working directory. A generated source folder added only to `sys.path`, without +installing its distribution metadata, is not automatically discovered; the +runtime's explicit version/path API remains available. Moving an editable source +tree requires reinstalling it. Zip imports and frozen-app resource extraction +are not supported by this configuration provider. + +The generated wheel is Windows/platform-specific, with a compressed +`py3-none-win_amd64.win_arm64` tag when both DLLs are present. A small build-only +setuptools hook supplies the tag and is retained in sdists, not installed as +runtime code. Matching `dynwinrt` CPython 3.11-3.14 wheels are still required. + +`MAJOR.MINOR` identifies the stable product, not a NuGet patch version or the +DLL's FileVersion. Metadata/configuration presence does not prove that an +application has used an App SDK API or that Runtime deployment is ready. +Repeated generation preserves an omitted configuration, including `--no-pyi`; +changing its version or bytes requires clean, complete regeneration. +See [bundle validation, capabilities and licensing](../README.md#packaged-windows-app-sdk-initialization) +and the [runtime initialization contract](../../../bindings/py/README.md#windows-app-sdk-initialization). + ### More examples Generate two classes from the Windows SDK: diff --git a/tools/dynwinrt-codegen/src/codegen/package.rs b/tools/dynwinrt-codegen/src/codegen/package.rs index 85a00ba5..37d5ad22 100644 --- a/tools/dynwinrt-codegen/src/codegen/package.rs +++ b/tools/dynwinrt-codegen/src/codegen/package.rs @@ -49,6 +49,13 @@ pub fn render_bindings_package_json_with_win32( } pub fn render_python_pyproject(input: &PythonPackageManifestInput<'_>) -> String { + render_python_pyproject_with_winappsdk(input, false) +} + +pub fn render_python_pyproject_with_winappsdk( + input: &PythonPackageManifestInput<'_>, + winappsdk: bool, +) -> String { let mut packages = vec![format!("\"{}\"", input.import_name)]; packages.extend( input @@ -56,8 +63,13 @@ pub fn render_python_pyproject(input: &PythonPackageManifestInput<'_>) -> String .iter() .map(|namespace| format!("\"{}.{}\"", input.import_name, namespace)), ); + let resources = if winappsdk { + ", \"_winappsdk.json\", \"_native/winappsdk/*/*.dll\", \"_native/winappsdk/*.txt\"" + } else { + "" + }; let mut package_data = vec![format!( - "\"{}\" = [\"py.typed\", \"*.pyi\"]", + "\"{}\" = [\"py.typed\", \"*.pyi\"{resources}]", input.import_name )]; package_data.extend( @@ -66,9 +78,34 @@ pub fn render_python_pyproject(input: &PythonPackageManifestInput<'_>) -> String .iter() .map(|namespace| format!("\"{}.{}\" = [\"*.pyi\"]", input.import_name, namespace)), ); + let build_requirements = if winappsdk { + "\"setuptools>=68\", \"wheel>=0.43\"" + } else { + "\"setuptools>=68\"" + }; + let entry_points = if winappsdk { + format!( + "[project.entry-points.\"dynwinrt.winappsdk\"]\n\ + configuration = \"{}._winappsdk:get_config\"\n\n", + input.import_name + ) + } else { + String::new() + }; + let build_commands = if winappsdk { + "[tool.setuptools.cmdclass]\n\ + bdist_wheel = \"_dynwinrt_build.wheel.BootstrapWheel\"\n\n" + } else { + "" + }; + let explicit_package_data = if winappsdk { + "include-package-data = false\n" + } else { + "" + }; format!( "[build-system]\n\ - requires = [\"setuptools>=68\"]\n\ + requires = [{build_requirements}]\n\ build-backend = \"setuptools.build_meta\"\n\ \n\ [project]\n\ @@ -77,10 +114,13 @@ pub fn render_python_pyproject(input: &PythonPackageManifestInput<'_>) -> String requires-python = \">=3.11,<3.15\"\n\ dependencies = [\"dynwinrt=={runtime_version}\"]\n\ \n\ + {entry_points}\ [tool.setuptools]\n\ + {explicit_package_data}\ packages = [{packages}]\n\ package-dir = {{ \"{import_name}\" = \".\" }}\n\ \n\ + {build_commands}\ [tool.setuptools.package-data]\n\ {package_data}\n", distribution_name = input.distribution_name, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs index 1704d599..1c59d1e8 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs @@ -2597,14 +2597,8 @@ mod tests { fn windows_corpus_marks_every_new_dispatcher_with_its_old_standalone_method() { use crate::codegen::winrt::python::naming::PythonProjectionContext; use crate::meta; - use std::path::Path; - - const WINMD: &str = - r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; - if !Path::new(WINMD).is_file() { - eprintln!("Skipping: Windows.winmd not found"); - return; - } + let winmd = crate::test_metadata::windows_winmd(); + let winmd = winmd.as_str(); fn assert_scope(interfaces: &[&InterfaceMeta], plan: &ScopePlan<'_>) -> (usize, usize) { let methods = interfaces @@ -2653,21 +2647,21 @@ mod tests { (count, bool_shadows) } - let namespaces = meta::list_namespaces(WINMD); + let namespaces = meta::list_namespaces(winmd); let mut identities = BTreeSet::new(); for namespace in &namespaces { identities.extend( - meta::parse_enums(WINMD, namespace) + meta::parse_enums(winmd, namespace) .into_iter() .map(|typ| typ.type_identity()), ); identities.extend( - meta::parse_interfaces(WINMD, namespace) + meta::parse_interfaces(winmd, namespace) .into_iter() .map(|interface| interface.type_identity()), ); identities.extend( - meta::parse_namespace(WINMD, namespace) + meta::parse_namespace(winmd, namespace) .into_iter() .map(|class| { crate::types::TypeIdentity::named( @@ -2685,7 +2679,7 @@ mod tests { let mut compatibility_fallbacks = BTreeSet::new(); let mut interface_fallbacks = BTreeSet::new(); for namespace in namespaces { - for class in meta::parse_namespace(WINMD, &namespace) { + for class in meta::parse_namespace(winmd, &namespace) { let statics = class .factory_interfaces .iter() @@ -2720,7 +2714,7 @@ mod tests { bool_shadows += count.1; } } - for interface in meta::parse_interfaces(WINMD, &namespace) { + for interface in meta::parse_interfaces(winmd, &namespace) { if !interface.is_delegate() { let interface_plan = interface_member_plan(&interface, &context); interface_fallbacks.extend( diff --git a/tools/dynwinrt-codegen/src/documented_nulls.rs b/tools/dynwinrt-codegen/src/documented_nulls.rs index 45b04d3d..9193ad66 100644 --- a/tools/dynwinrt-codegen/src/documented_nulls.rs +++ b/tools/dynwinrt-codegen/src/documented_nulls.rs @@ -401,18 +401,15 @@ mod tests { /// typos and drift, and the key derivation against metadata changes. #[test] fn every_entry_resolves_to_a_flagged_windows_sdk_member() { - // Documented, but absent from the 10.0.26100 SDK metadata: newer APIs, + // Documented, but absent from the pinned 10.0.26100.8249 metadata: newer APIs, // and AllJoyn, which the SDK dropped. const ABSENT_FROM_TEST_SDK: [&str; 3] = [ "M:Windows.Devices.AllJoyn.AllJoynServiceInfo.FromIdAsync(System.String)", "M:Windows.Gaming.UI.GameMonitor.GetDefault()", "M:Windows.System.User.GetUserAgeRangeAsync()", ]; - if !Path::new(WINDOWS_WINMD).is_file() { - eprintln!("Skipping: Windows.winmd not found"); - return; - } - let index = crate::meta::load_index(WINDOWS_WINMD).expect("Windows.winmd index"); + let winmd = crate::test_metadata::windows_winmd(); + let index = crate::meta::load_index(&winmd).expect("Windows.winmd index"); let mut by_owner = BTreeMap::>::new(); for entry in entries() { let id = normalize_api_id(entry); diff --git a/tools/dynwinrt-codegen/src/lib.rs b/tools/dynwinrt-codegen/src/lib.rs index 09db795e..fe8f9d2e 100644 --- a/tools/dynwinrt-codegen/src/lib.rs +++ b/tools/dynwinrt-codegen/src/lib.rs @@ -7,6 +7,8 @@ pub mod com_metadata; mod contract_registry; mod documented_nulls; pub mod meta; +#[cfg(test)] +mod test_metadata; pub mod types; mod win32_contracts; pub mod win32_metadata; diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 318c2572..b8f312ab 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -4,6 +4,7 @@ mod python_output_paths; mod win32_census; mod win32_output; +mod winappsdk_output; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fs; @@ -174,6 +175,7 @@ enum Commands { /// Custom import name for the dynwinrt runtime package in generated JS/TS files. /// Defaults to "@microsoft/dynwinrt". + /// Bootstrap bundling requires an npm package name, not a file path or package subpath. #[arg(long, default_value = "@microsoft/dynwinrt", value_name = "NAME")] import_name: String, @@ -188,6 +190,25 @@ enum Commands { /// Skip .pyi type stubs and the py.typed marker (requires --lang py). #[arg(long, conflicts_with = "pyi")] no_pyi: bool, + + /// Stable Windows App SDK product MAJOR.MINOR for an explicit initializer configuration. + /// For example, 2.5, not a full NuGet servicing version. + #[arg( + long, + value_name = "MAJOR.MINOR", + requires = "winappsdk_bootstrap_path" + )] + winappsdk_version: Option, + + /// Bootstrap DLL file or directory to search recursively; repeat for multiple inputs. + /// Directories match Microsoft.WindowsAppRuntime.Bootstrap.dll; architecture comes from PE. + #[arg( + long, + value_name = "PATH", + num_args = 1, + requires = "winappsdk_version" + )] + winappsdk_bootstrap_path: Vec, }, } @@ -389,11 +410,17 @@ fn run() -> Result<(), String> { dry_run, pyi, no_pyi, + winappsdk_version, + winappsdk_bootstrap_path, } => { if lang != "py" && (pyi || no_pyi) { return Err("--pyi and --no-pyi require --lang py".into()); } let pyi = lang == "py" && !no_pyi; + let bootstrap_inputs = winappsdk_output::parse_inputs( + winappsdk_version.as_deref(), + &winappsdk_bootstrap_path, + )?; // Collect winmd paths from --folder and/or --winmd let mut winmd_parts: Vec = Vec::new(); @@ -535,6 +562,16 @@ fn run() -> Result<(), String> { .map(|transaction| transaction.stage_dir().to_path_buf()) .unwrap_or_else(|| final_output_dir.to_path_buf()); let output_dir = effective_output_dir.as_path(); + let bootstrap = winappsdk_output::prepare( + output_dir, + &lang, + if lang == "py" { + "dynwinrt" + } else { + &import_name + }, + bootstrap_inputs, + )?; if lang == "js" { project::set_import_name(&import_name); } @@ -542,6 +579,10 @@ fn run() -> Result<(), String> { fs::create_dir_all(output_dir).map_err(|e| { format!("Failed to create output directory '{}': {}", output, e) })?; + if bootstrap.is_some() && lang == "js" { + win32_output::wire_winappsdk_registration(output_dir)?; + winappsdk_output::wire_existing_com_files(output_dir)?; + } } if lang == "py" && !dry_run && !pyi && class_name.is_some() { remove_all_generated_python_stubs(output_dir)?; @@ -638,6 +679,7 @@ fn run() -> Result<(), String> { &win32_namespaces, &import_name, dry_run, + bootstrap.is_some(), )?; if classes.is_empty() && requested_winrt_interfaces.is_empty() @@ -645,6 +687,9 @@ fn run() -> Result<(), String> { && com_coclasses.is_empty() && !native_audio_completion { + if !dry_run && let Some(bootstrap) = bootstrap { + bootstrap.write(output_dir, pyi)?; + } if let Some(transaction) = output_transaction.take() { transaction.commit()?; } @@ -869,6 +914,14 @@ fn run() -> Result<(), String> { files.insert("unsafe/runtime.js".into()); files.insert("unsafe/runtime.d.ts".into()); } + if bootstrap.is_some() { + for (file, content) in &mut planned_files { + *content = winappsdk_output::javascript_registration( + &Path::new("com").join(file), + content, + ); + } + } let manifest_update = prepare_com_generation_manifest( &com_output_dir, &root_files, @@ -939,6 +992,9 @@ fn run() -> Result<(), String> { .iter() .filter_map(|output| output.no_callable_error.clone()) .collect::>(); + if bootstrap.is_some() && !no_callable_errors.is_empty() { + return Err(no_callable_errors.join("\n")); + } if classes.is_empty() && requested_winrt_interfaces.is_empty() { if !dry_run { finalize_com_generation(output_dir)?; @@ -949,6 +1005,9 @@ fn run() -> Result<(), String> { } return Err(no_callable_errors.join("\n")); } + if !dry_run && let Some(bootstrap) = bootstrap { + bootstrap.write(output_dir, pyi)?; + } if let Some(transaction) = output_transaction.take() { transaction.commit()?; } @@ -1076,7 +1135,11 @@ fn run() -> Result<(), String> { &BTreeSet::from([ns.to_string()]), &import_name, dry_run, + bootstrap.is_some(), )?; + if !dry_run && let Some(bootstrap) = bootstrap { + bootstrap.write(output_dir, pyi)?; + } if let Some(transaction) = output_transaction.take() { transaction.commit()?; } @@ -1244,6 +1307,9 @@ fn run() -> Result<(), String> { } } + if !dry_run && let Some(bootstrap) = bootstrap { + bootstrap.write(output_dir, pyi)?; + } if lang == "py" && !dry_run { write_python_package_manifest(output_dir, final_output_dir)?; write_python_generator_metadata(output_dir)?; @@ -6772,13 +6838,16 @@ fn write_python_package_manifest(output_dir: &Path, final_output_dir: &Path) -> let distribution_name = import_name.replace('_', "-"); let version = env!("CARGO_PKG_VERSION"); let namespace_packages = collect_python_namespace_packages(output_dir)?; - let manifest = package::render_python_pyproject(&package::PythonPackageManifestInput { - distribution_name: &distribution_name, - import_name: &import_name, - package_version: version, - runtime_version: version, - namespace_packages: &namespace_packages, - }); + let manifest = package::render_python_pyproject_with_winappsdk( + &package::PythonPackageManifestInput { + distribution_name: &distribution_name, + import_name: &import_name, + package_version: version, + runtime_version: version, + namespace_packages: &namespace_packages, + }, + output_dir.join(winappsdk_output::MANIFEST).is_file(), + ); let build_cache_key = python_build_cache_key(output_dir, &import_name)?; let setup = package::render_python_setup_cfg(&build_cache_key); write_file(&manifest_path, &manifest)?; @@ -6807,6 +6876,15 @@ fn python_build_cache_key(output_dir: &Path, import_name: &str) -> Result String { + let corpus: Corpus = serde_json::from_str(include_str!("../tests/windows_sdk_corpus.json")) + .expect("valid Windows SDK corpus descriptor"); + let path = std::env::var_os("DYNWINRT_WINDOWS_WINMD") + .map(PathBuf::from) + .unwrap_or_else(|| { + PathBuf::from( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ) + }); + let instructions = format!( + "Windows corpus tests require {} {} ({}). \ + Run eng\\ci\\restore-windows-metadata.ps1 -OutputDirectory \ + and set DYNWINRT_WINDOWS_WINMD to its returned path; \ + a rolling SDK installation is not a pinned corpus.", + corpus.package, corpus.version, corpus.relative_path, + ); + let bytes = std::fs::read(&path) + .unwrap_or_else(|error| panic!("Cannot read {}: {error}. {instructions}", path.display())); + assert_eq!( + format!("{:x}", Sha256::digest(&bytes)), + corpus.sha256, + "Unexpected Windows metadata content at {}. {instructions}", + path.display() + ); + path.to_str() + .expect("Windows metadata path must be Unicode") + .into() +} diff --git a/tools/dynwinrt-codegen/src/win32_output.rs b/tools/dynwinrt-codegen/src/win32_output.rs index 3da7f05f..b6d2ca02 100644 --- a/tools/dynwinrt-codegen/src/win32_output.rs +++ b/tools/dynwinrt-codegen/src/win32_output.rs @@ -226,12 +226,43 @@ fn write_javascript(output: &Path, relative: &Path, content: &str) -> Result<(), super::write_generated_javascript_file(output, &output.join(relative), content) } +pub(super) fn wire_winappsdk_registration(output: &Path) -> Result<(), String> { + let Some(mut manifest) = read_manifest(output)? else { + return Ok(()); + }; + for (namespace, record) in &mut manifest.namespaces { + let directory = Path::new("win32").join(namespace_directory(namespace)?); + for (file, hash) in std::iter::once(("Apis.js", &mut record.javascript_sha256)).chain( + record + .extra_files + .iter_mut() + .filter(|(file, _)| file.ends_with(".js")) + .map(|(file, extra)| (file.as_str(), &mut extra.sha256)), + ) { + let relative = directory.join(file); + let bytes = read_file(output, &relative)?.ok_or_else(|| { + format!("Win32 manifest references missing {}", relative.display()) + })?; + let text = String::from_utf8(bytes).map_err(|error| { + format!("Invalid Win32 JavaScript {}: {error}", relative.display()) + })?; + let registered = super::winappsdk_output::javascript_registration(&relative, &text); + if registered != text { + write_javascript(output, &relative, ®istered)?; + *hash = digest(registered.as_bytes()); + } + } + } + write_manifest(output, &manifest) +} + pub(super) fn generate( output: &Path, winmd: &str, namespaces: &BTreeSet, import_name: &str, dry_run: bool, + winappsdk: bool, ) -> Result<(), String> { let existing = read_manifest(output)?; let root = output.join("win32"); @@ -257,8 +288,19 @@ pub(super) fn generate( let mut stale_files = Vec::new(); for namespace in namespaces { let directory = namespace_directory(namespace)?; - let generated_namespace = + let mut generated_namespace = win32::generate_namespace(winmd, namespace, &runtime_import(import_name, &directory))?; + if winappsdk { + let relative = Path::new("win32").join(&directory); + generated_namespace.js = super::winappsdk_output::javascript_registration( + &relative.join("Apis.js"), + &generated_namespace.js, + ); + for (file, content) in &mut generated_namespace.extra_files { + *content = + super::winappsdk_output::javascript_registration(&relative.join(file), content); + } + } if generated_namespace.namespace != *namespace { return Err(format!("Win32 projection changed namespace `{namespace}`")); } @@ -358,13 +400,17 @@ pub(super) fn generate( })?; } write_indexes(output, &manifest)?; - let path = root.join(MANIFEST); + write_manifest(output, &manifest)?; + super::write_bindings_manifest(output) +} + +fn write_manifest(output: &Path, manifest: &Manifest) -> Result<(), String> { + let path = output.join("win32").join(MANIFEST); super::ensure_safe_generated_destination(output, &path)?; - let content = serde_json::to_string_pretty(&manifest) + let content = serde_json::to_string_pretty(manifest) .map_err(|error| format!("Failed to serialize Win32 generation manifest: {error}"))?; fs::write(&path, format!("{content}\n")) - .map_err(|error| format!("Failed to write {}: {error}", path.display()))?; - super::write_bindings_manifest(output) + .map_err(|error| format!("Failed to write {}: {error}", path.display())) } fn write_indexes(output: &Path, manifest: &Manifest) -> Result<(), String> { diff --git a/tools/dynwinrt-codegen/src/winappsdk_output.rs b/tools/dynwinrt-codegen/src/winappsdk_output.rs new file mode 100644 index 00000000..8fa0a8ce --- /dev/null +++ b/tools/dynwinrt-codegen/src/winappsdk_output.rs @@ -0,0 +1,1027 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Optional, transaction-owned Bootstrap resources. No native input is executed. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use object::{Object, ObjectSection}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub(crate) const MANIFEST: &str = ".dynwinrt-winappsdk.json"; +const CONFIG: &str = "_winappsdk.json"; +const WHEEL_HOOK: &str = "_dynwinrt_build/wheel.py"; +const DLL_NAME: &str = "Microsoft.WindowsAppRuntime.Bootstrap.dll"; +const NOTICE: &str = "_native/winappsdk/NOTICE.txt"; +const LICENSE: &str = "_native/winappsdk/LICENSE.txt"; +const JS_MARKER: &str = " // dynwinrt: Windows App SDK configuration"; +const MAX_DLL_SIZE: u64 = 64 * 1024 * 1024; +const NPM_VERSION_ENV: &str = "DYNWINRT_CODEGEN_NPM_VERSION"; + +const NOTICE_TEXT: &str = "\ +Microsoft Windows App SDK Bootstrap redistributable + +The DLLs in this directory were copied unchanged from inputs selected by this +application package's producer. They are NOT licensed under dynwinrt's MIT +license. The Microsoft Software License Terms supplied with the original +Windows App SDK NuGet package govern them. + +Redistribution is permitted only in applications satisfying those terms, +including significant primary application functionality and protective +distributor/end-user terms. This bundle does not grant standalone SDK +distribution rights. The application producer must preserve and provide the +applicable SDK license and notices when redistributing their application. +If LICENSE.txt is present, it is an unmodified copy found beside the supplied +inputs or in their standard NuGet package. Otherwise obtain the terms from +the same SDK package used to restore the inputs before distribution. + +The Bootstrap DLL is not the complete Windows App Runtime. Deploy the matching +Windows App Runtime separately for framework-dependent applications. +https://learn.microsoft.com/windows/apps/windows-app-sdk/deploy-unpackaged-apps +"; + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct Configuration { + schema_version: u32, + major: u16, + minor: u16, + dlls: BTreeMap, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + schema_version: u32, + generator_version: String, + language: String, + runtime_import: String, + configuration: Configuration, + files: BTreeMap, +} + +pub(crate) struct Bundle { + manifest: Manifest, + contents: BTreeMap>, +} + +pub(crate) struct Inputs { + major: u16, + minor: u16, + dll_paths: Vec, +} + +fn regeneration_error(reason: impl std::fmt::Display) -> String { + format!( + "{reason}. Clean the dedicated output directory and regenerate the complete bindings \ + package with matching Windows App SDK inputs. Existing output has not been changed." + ) +} + +fn digest(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +fn producer_version(language: &str) -> Result { + if language != "js" { + return Ok(env!("CARGO_PKG_VERSION").into()); + } + // npm releases stamp their package.json after compiling the native executable. + let version = match std::env::var(NPM_VERSION_ENV) { + Ok(version) => version, + Err(std::env::VarError::NotPresent) => return Ok(env!("CARGO_PKG_VERSION").into()), + Err(error) => return Err(format!("Invalid npm codegen version: {error}")), + }; + semver::Version::parse(&version) + .map_err(|error| format!("Invalid {NPM_VERSION_ENV} {version:?}: {error}"))?; + Ok(version) +} + +fn dll_path(architecture: &str) -> String { + format!("_native/winappsdk/{architecture}/{DLL_NAME}") +} + +pub(crate) fn parse_inputs( + version: Option<&str>, + paths: &[String], +) -> Result, String> { + let version = match (version, paths.is_empty()) { + (None, true) => return Ok(None), + (Some(version), false) => version, + _ => { + return Err( + "--winappsdk-version and --winappsdk-bootstrap-path must be supplied together" + .into(), + ); + } + }; + let components = version.split('.').collect::>(); + if components.len() != 2 + || components.iter().any(|part| { + part.is_empty() + || !part.bytes().all(|byte| byte.is_ascii_digit()) + || (part.len() > 1 && part.starts_with('0')) + || part.parse::().is_err() + }) + { + return Err( + "--winappsdk-version requires a stable product MAJOR.MINOR (each 0..65535), \ + not a NuGet servicing version or a preview/experimental channel" + .into(), + ); + } + if paths + .iter() + .any(|path| path.trim().is_empty() || path.contains('\0')) + { + return Err( + "Each --winappsdk-bootstrap-path must be a nonempty file or directory path without NUL" + .into(), + ); + } + Ok(Some(Inputs { + major: components[0].parse().unwrap(), + minor: components[1].parse().unwrap(), + dll_paths: paths.iter().map(PathBuf::from).collect(), + })) +} + +fn read_input(path: &Path, limit: u64) -> Result, String> { + let metadata = fs::metadata(path) + .map_err(|error| format!("Cannot inspect Bootstrap input {}: {error}", path.display()))?; + if !metadata.is_file() || metadata.len() == 0 || metadata.len() > limit { + return Err(format!( + "Bootstrap input {} must be a nonempty file no larger than {limit} bytes", + path.display() + )); + } + let bytes = fs::read(path) + .map_err(|error| format!("Cannot read Bootstrap input {}: {error}", path.display()))?; + if bytes.is_empty() || bytes.len() as u64 > limit { + return Err(format!("Bootstrap input changed size: {}", path.display())); + } + Ok(bytes) +} + +enum BootstrapArchitecture { + Supported(&'static str), + Unsupported(u16), +} + +fn validate_pe(bytes: &[u8]) -> Result { + let file = + object::File::parse(bytes).map_err(|error| format!("Invalid Bootstrap PE: {error}"))?; + if file.format() != object::BinaryFormat::Pe { + return Err("Bootstrap input must be a PE DLL, not an object file or executable".into()); + } + let characteristics = match file.flags() { + object::FileFlags::Coff { characteristics } => characteristics, + _ => return Err("Bootstrap input has no PE characteristics".into()), + }; + if characteristics & object::pe::IMAGE_FILE_DLL == 0 { + return Err("Bootstrap PE input is not marked as a DLL".into()); + } + let offset = bytes + .get(0x3c..0x40) + .map(|value| u32::from_le_bytes(value.try_into().unwrap()) as usize) + .ok_or("Truncated Bootstrap DOS header")?; + let machine_start = offset.checked_add(4).ok_or("Invalid Bootstrap PE offset")?; + let machine_end = offset.checked_add(6).ok_or("Invalid Bootstrap PE offset")?; + let machine = bytes + .get(machine_start..machine_end) + .map(|value| u16::from_le_bytes(value.try_into().unwrap())) + .ok_or("Truncated Bootstrap PE header")?; + for section in file.sections() { + section + .data() + .map_err(|error| format!("Invalid Bootstrap PE section bounds: {error}"))?; + } + let exports = file + .exports() + .map_err(|error| format!("Invalid Bootstrap PE export table: {error}"))?; + if !exports + .iter() + .any(|export| export.name() == b"MddBootstrapInitialize2") + { + return Err("Bootstrap DLL does not export MddBootstrapInitialize2".into()); + } + // Validate unsupported DLLs too: a damaged matching file is not an ignorable architecture. + Ok(match (machine, file.architecture()) { + (0x8664, object::Architecture::X86_64) => BootstrapArchitecture::Supported("x64"), + (0xaa64, object::Architecture::Aarch64) => BootstrapArchitecture::Supported("arm64"), + _ => BootstrapArchitecture::Unsupported(machine), + }) +} + +fn inspect_directory_entry(root: &Path, path: &Path) -> Result<(fs::Metadata, PathBuf), String> { + let metadata = fs::symlink_metadata(path).map_err(|error| { + format!( + "Cannot inspect Bootstrap directory entry {}: {error}", + path.display() + ) + })?; + if super::is_link_or_reparse_point(&metadata) { + return Err(format!( + "Refusing linked Bootstrap directory entry {}; directory searches do not follow links or reparse points", + path.display() + )); + } + let resolved = fs::canonicalize(path).map_err(|error| { + format!( + "Cannot resolve Bootstrap directory entry {}: {error}", + path.display() + ) + })?; + if !resolved.starts_with(root) { + return Err(format!( + "Bootstrap directory entry {} resolves outside {}", + path.display(), + root.display() + )); + } + Ok((metadata, resolved)) +} + +fn directory_dlls(input: &Path) -> Result, String> { + let metadata = fs::symlink_metadata(input).map_err(|error| { + format!( + "Cannot inspect Bootstrap directory {}: {error}", + input.display() + ) + })?; + if super::is_link_or_reparse_point(&metadata) { + return Err(format!( + "Refusing linked Bootstrap directory {}", + input.display() + )); + } + let root = fs::canonicalize(input).map_err(|error| { + format!( + "Cannot resolve Bootstrap directory {}: {error}", + input.display() + ) + })?; + let mut pending = vec![root.clone()]; + let mut visited = BTreeSet::new(); + let mut files = BTreeSet::new(); + while let Some(directory) = pending.pop() { + let (metadata, resolved) = inspect_directory_entry(&root, &directory)?; + if !metadata.is_dir() { + return Err(format!( + "Bootstrap search directory is no longer a directory: {}", + directory.display() + )); + } + if !visited.insert(resolved) { + continue; + } + let mut entries = fs::read_dir(&directory) + .map_err(|error| { + format!( + "Cannot read Bootstrap directory {}: {error}", + directory.display() + ) + })? + .collect::, _>>() + .map_err(|error| { + format!( + "Cannot read Bootstrap directory {}: {error}", + directory.display() + ) + })?; + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + let path = entry.path(); + let metadata = fs::symlink_metadata(&path).map_err(|error| { + format!( + "Cannot inspect Bootstrap directory entry {}: {error}", + path.display() + ) + })?; + if super::is_link_or_reparse_point(&metadata) { + return Err(format!( + "Refusing linked Bootstrap directory entry {}; directory searches do not follow links or reparse points", + path.display() + )); + } + if metadata.is_dir() { + pending.push(path); + } else if entry + .file_name() + .to_string_lossy() + .eq_ignore_ascii_case(DLL_NAME) + { + let (metadata, resolved) = inspect_directory_entry(&root, &path)?; + if !metadata.is_file() { + return Err(format!( + "Bootstrap directory match is not a file: {}", + path.display() + )); + } + files.insert(resolved); + } + } + } + Ok(files.into_iter().collect()) +} + +fn source_license(paths: &[PathBuf]) -> Result>, String> { + let mut candidates = BTreeSet::new(); + for path in paths { + let parent = path + .parent() + .ok_or("Bootstrap input has no parent directory")?; + candidates.insert(parent.join("license.txt")); + if let Some(common) = parent.parent() { + candidates.insert(common.join("license.txt")); + } + // A restored NuGet payload has //runtimes/win-*/native/. + if parent.file_name().is_some_and(|name| name == "native") + && let Some(runtimes) = parent.parent().and_then(Path::parent) + && runtimes.file_name().is_some_and(|name| name == "runtimes") + && let Some(package) = runtimes.parent() + { + candidates.insert(package.join("license.txt")); + } + } + let mut license: Option<(PathBuf, Vec)> = None; + for candidate in candidates { + match fs::metadata(&candidate) { + Ok(_) => { + let bytes = read_input(&candidate, 1024 * 1024)?; + if let Some((source, existing)) = &license + && existing != &bytes + { + return Err(format!( + "Bootstrap inputs have conflicting license.txt files: {} and {}", + source.display(), + candidate.display() + )); + } + license = Some((candidate, bytes)); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(format!("Cannot inspect {}: {error}", candidate.display())); + } + } + } + Ok(license.map(|(_, bytes)| bytes)) +} + +fn from_inputs(inputs: Inputs, language: &str, runtime_import: &str) -> Result { + let mut contents = BTreeMap::new(); + let mut dlls = BTreeMap::new(); + let mut sources = BTreeMap::<&str, PathBuf>::new(); + let mut supported_sources = BTreeSet::new(); + let mut ignored = BTreeSet::new(); + for input in inputs.dll_paths.iter().collect::>() { + let metadata = fs::metadata(input).map_err(|error| { + format!( + "Cannot inspect Bootstrap input {}: {error}", + input.display() + ) + })?; + let directory = metadata.is_dir(); + let paths = if directory { + directory_dlls(input)? + } else { + vec![input.clone()] + }; + let mut supported = false; + for path in paths { + let bytes = read_input(&path, MAX_DLL_SIZE)?; + let architecture = match validate_pe(&bytes) + .map_err(|error| format!("{}: {error}", path.display()))? + { + BootstrapArchitecture::Supported(architecture) => architecture, + BootstrapArchitecture::Unsupported(machine) if directory => { + if ignored.insert(path.clone()) { + eprintln!( + "warning: ignoring unsupported Bootstrap PE machine 0x{machine:04x} discovered in {}", + path.display() + ); + } + continue; + } + BootstrapArchitecture::Unsupported(machine) => { + return Err(format!( + "Unsupported Bootstrap PE machine 0x{machine:04x} in explicit file {}", + path.display() + )); + } + }; + supported = true; + let relative = dll_path(architecture); + if let Some(existing) = contents.get(&relative) { + if existing != &bytes { + return Err(format!( + "Conflicting Bootstrap DLL inputs for {architecture}: {} and {} have different contents", + sources[architecture].display(), + path.display() + )); + } + } else { + sources.insert(architecture, path.clone()); + dlls.insert(architecture.into(), digest(&bytes)); + contents.insert(relative, bytes); + } + supported_sources.insert(path); + } + if !supported { + return Err(format!( + "No supported Bootstrap DLLs found in directory {}; searched recursively for {DLL_NAME} (x64 or ARM64)", + input.display() + )); + } + } + // Duplicate payloads may still supply a missing or conflicting source license. + if let Some(license) = source_license(&supported_sources.into_iter().collect::>())? { + contents.insert(LICENSE.into(), license); + } else { + eprintln!( + "warning: Bootstrap DLLs retain the Microsoft Windows App SDK license, not dynwinrt's \ + MIT license. No source license.txt was found beside the inputs; include the matching \ + SDK terms with your application before redistribution. See {NOTICE} in the output." + ); + } + let configuration = Configuration { + schema_version: 1, + major: inputs.major, + minor: inputs.minor, + dlls, + }; + Ok(Bundle { + manifest: Manifest { + schema_version: 1, + generator_version: producer_version(language)?, + language: language.into(), + runtime_import: runtime_import.into(), + configuration, + files: BTreeMap::new(), + }, + contents, + }) +} + +fn read_manifest(output: &Path) -> Result, String> { + let path = output.join(MANIFEST); + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(format!("Cannot inspect {}: {error}", path.display())), + }; + if super::is_link_or_reparse_point(&metadata) || !metadata.is_file() || metadata.len() > 65536 { + return Err(regeneration_error( + "Invalid Windows App SDK bundle manifest", + )); + } + let content = + fs::read(&path).map_err(|error| format!("Cannot read {}: {error}", path.display()))?; + let manifest: Manifest = serde_json::from_slice(&content).map_err(|error| { + regeneration_error(format!("Invalid Windows App SDK manifest: {error}")) + })?; + let config = &manifest.configuration; + if manifest.schema_version != 1 + || config.schema_version != 1 + || manifest.generator_version != producer_version(&manifest.language)? + || !matches!(manifest.language.as_str(), "py" | "js") + || config.dlls.is_empty() + || config + .dlls + .iter() + .any(|(arch, hash)| !matches!(arch.as_str(), "x64" | "arm64") || !valid_hash(hash)) + { + return Err(regeneration_error( + "Unsupported Windows App SDK bundle manifest", + )); + } + let allowed = allowed_files(&manifest.language, config); + if manifest + .files + .iter() + .any(|(path, hash)| !allowed.contains(path) || !valid_hash(hash)) + || ![CONFIG, NOTICE] + .iter() + .all(|path| manifest.files.contains_key(*path)) + || config + .dlls + .iter() + .any(|(arch, hash)| manifest.files.get(&dll_path(arch)) != Some(hash)) + || (manifest.language == "py" + && !["_winappsdk.py", WHEEL_HOOK, "MANIFEST.in"] + .iter() + .all(|path| manifest.files.contains_key(*path))) + || (manifest.language == "js" && !manifest.files.contains_key("_winappsdk.cjs")) + { + return Err(regeneration_error( + "Invalid Windows App SDK bundle file inventory", + )); + } + Ok(Some(manifest)) +} + +fn valid_hash(hash: &str) -> bool { + hash.len() == 64 + && hash + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) +} + +fn allowed_files(language: &str, config: &Configuration) -> BTreeSet { + [CONFIG, NOTICE, LICENSE] + .into_iter() + .map(String::from) + .chain(config.dlls.keys().map(|arch| dll_path(arch))) + .chain( + if language == "py" { + vec!["_winappsdk.py", "_winappsdk.pyi", WHEEL_HOOK, "MANIFEST.in"] + } else { + vec!["_winappsdk.cjs"] + } + .into_iter() + .map(String::from), + ) + .collect() +} + +fn inspect_owned_path(output: &Path, relative: &str) -> Result<(), String> { + let mut current = output.to_path_buf(); + for component in Path::new(relative).components() { + if !matches!(component, std::path::Component::Normal(_)) { + return Err(regeneration_error("Invalid Bootstrap resource path")); + } + current.push(component); + match fs::symlink_metadata(¤t) { + Ok(metadata) if super::is_link_or_reparse_point(&metadata) => { + return Err(regeneration_error(format!( + "Windows App SDK resource is linked: {}", + current.display() + ))); + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("Cannot inspect {}: {error}", current.display())), + } + } + Ok(()) +} + +fn is_npm_package_name(name: &str) -> bool { + fn component(name: &str) -> bool { + !name.is_empty() + && !name.starts_with(['.', '_']) + && name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') + }) + } + + if name.len() > 214 + || name.eq_ignore_ascii_case("node_modules") + || name.eq_ignore_ascii_case("favicon.ico") + { + return false; + } + if let Some(scoped) = name.strip_prefix('@') { + scoped + .split_once('/') + .is_some_and(|(scope, package)| component(scope) && component(package)) + } else { + component(name) + } +} + +pub(crate) fn prepare( + output: &Path, + language: &str, + runtime_import: &str, + inputs: Option, +) -> Result, String> { + let existing = read_manifest(output)?; + if language == "js" + && (inputs.is_some() || existing.is_some()) + && !is_npm_package_name(runtime_import) + { + return Err(format!( + "Windows App SDK Bootstrap bundling requires --import-name to be an npm package name \ + (for example @microsoft/dynwinrt), not a file path or package subpath: \ + {runtime_import:?}. Install the runtime package and use its package name, or keep \ + file imports by generating without Bootstrap bundling in a clean output directory. \ + Existing output has not been changed." + )); + } + if existing.is_none() + && inputs.is_none() + && [ + CONFIG, + "_winappsdk.py", + "_winappsdk.cjs", + "_native/winappsdk", + ] + .iter() + .any(|name| super::path_entry_exists(&output.join(name))) + { + return Err(regeneration_error( + "Windows App SDK bundle artifacts have no ownership manifest", + )); + } + let mut retained = BTreeMap::new(); + if let Some(manifest) = &existing { + if manifest.language != language || manifest.runtime_import != runtime_import { + return Err(regeneration_error( + "Conflicting Windows App SDK language/runtime import", + )); + } + for (relative, hash) in &manifest.files { + inspect_owned_path(output, relative)?; + let path = output.join(relative); + let bytes = read_input(&path, MAX_DLL_SIZE)?; + if digest(&bytes) != *hash { + return Err(regeneration_error(format!( + "Windows App SDK generated resource was modified: {}", + path.display() + ))); + } + if relative == LICENSE || relative.ends_with(".dll") { + retained.insert(relative.clone(), bytes); + } + } + } + let mut bundle = if let Some(inputs) = inputs { + let requested = from_inputs(inputs, language, runtime_import)?; + if let Some(existing) = &existing + && (existing.configuration != requested.manifest.configuration + || retained.get(LICENSE) != requested.contents.get(LICENSE)) + { + return Err(regeneration_error( + "Conflicting Windows App SDK version or payload", + )); + } + requested + } else if let Some(manifest) = existing { + Bundle { + manifest, + contents: retained, + } + } else { + return Ok(None); + }; + // Keep every currently-owned helper in the reservation set, including optional stubs. + let reservations = allowed_files(language, &bundle.manifest.configuration); + let prior = read_manifest(output)?; + for relative in reservations { + inspect_owned_path(output, &relative)?; + if super::path_entry_exists(&output.join(&relative)) + && !prior + .as_ref() + .is_some_and(|manifest| manifest.files.contains_key(&relative)) + { + return Err(format!( + "Refusing to overwrite non-generated Windows App SDK resource `{relative}`" + )); + } + } + bundle.manifest.files = prior.map(|manifest| manifest.files).unwrap_or_default(); + bundle + .contents + .insert(NOTICE.into(), NOTICE_TEXT.as_bytes().to_vec()); + Ok(Some(bundle)) +} + +pub(crate) fn owned_files(output: &Path) -> Result, String> { + Ok(read_manifest(output)? + .map(|manifest| { + manifest + .files + .keys() + .map(PathBuf::from) + .chain(std::iter::once(PathBuf::from(MANIFEST))) + .collect() + }) + .unwrap_or_default()) +} + +pub(crate) fn owns(output: &Path, relative: &Path) -> Result { + Ok(owned_files(output)?.iter().any(|path| path == relative)) +} + +impl Bundle { + pub(crate) fn write(mut self, output: &Path, pyi: bool) -> Result<(), String> { + self.contents.insert( + CONFIG.into(), + format!( + "{}\n", + serde_json::to_string_pretty(&self.manifest.configuration).map_err( + |error| format!("Cannot serialize Bootstrap configuration: {error}") + )? + ) + .into_bytes(), + ); + if self.manifest.language == "py" { + self.contents + .insert("_winappsdk.py".into(), python_provider().into_bytes()); + self.contents + .insert(WHEEL_HOOK.into(), self.python_wheel_hook().into_bytes()); + self.contents.insert( + "MANIFEST.in".into(), + format!("{}include {WHEEL_HOOK}\n", super::GENERATED_PYTHON_HEADER).into_bytes(), + ); + if pyi { + self.contents.insert( + "_winappsdk.pyi".into(), + format!( + "{}def get_config() -> tuple[str, dict[str, object]]: ...\n", + super::GENERATED_PYTHON_HEADER + ) + .into_bytes(), + ); + } + } else { + let import = + serde_json::to_string(&format!("{}/winappsdk", self.manifest.runtime_import)) + .map_err(|error| format!("Invalid runtime import: {error}"))?; + self.contents.insert( + "_winappsdk.cjs".into(), + format!( + "// Generated by dynwinrt-codegen - do not edit\n\ + 'use strict';\n\ + require({import}).__registerWinAppSdkConfig(__filename, require('./{CONFIG}'));\n" + ) + .into_bytes(), + ); + } + for relative in allowed_files(&self.manifest.language, &self.manifest.configuration) { + inspect_owned_path(output, &relative)?; + let path = output.join(&relative); + match fs::symlink_metadata(&path) { + Ok(_) => { + let bytes = read_input(&path, MAX_DLL_SIZE)?; + if self.manifest.files.get(&relative) != Some(&digest(&bytes)) { + return Err(format!( + "Refusing to overwrite Windows App SDK destination `{relative}` \ + created or modified by another generator" + )); + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("Cannot inspect {}: {error}", path.display())), + } + } + for relative in self.manifest.files.keys() { + if !self.contents.contains_key(relative) { + let path = output.join(relative); + match fs::remove_file(&path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("Cannot remove {}: {error}", path.display())), + } + } + } + for (relative, bytes) in &self.contents { + let path = output.join(relative); + super::ensure_safe_generated_destination(output, &path)?; + fs::write(&path, bytes) + .map_err(|error| format!("Cannot write {}: {error}", path.display()))?; + } + self.manifest.files = self + .contents + .iter() + .map(|(path, bytes)| (path.clone(), digest(bytes))) + .collect(); + let path = output.join(MANIFEST); + super::ensure_safe_generated_destination(output, &path)?; + super::write_file( + &path, + &format!( + "{}\n", + serde_json::to_string_pretty(&self.manifest) + .map_err(|error| format!("Cannot serialize Bootstrap manifest: {error}"))? + ), + )?; + if self.manifest.language == "js" { + wire_javascript(output, output)?; + decorate_javascript_package(output, &self.manifest)?; + } + Ok(()) + } + + fn python_wheel_hook(&self) -> String { + let platforms = self + .manifest + .configuration + .dlls + .keys() + .map(|arch| { + if arch == "x64" { + "win_amd64" + } else { + "win_arm64" + } + }) + .collect::>() + .into_iter() + .collect::>() + .join("."); + format!( + "{}\ + from wheel.bdist_wheel import bdist_wheel\n\n\ + class BootstrapWheel(bdist_wheel):\n\ + \x20 def finalize_options(self):\n\ + \x20 super().finalize_options()\n\ + \x20 self.root_is_pure = False\n\n\ + \x20 def get_tag(self):\n\ + \x20 return ('py3', 'none', '{platforms}')\n", + super::GENERATED_PYTHON_HEADER + ) + } +} + +fn python_provider() -> String { + format!( + "{}\ + \"\"\"Generated SDK configuration; importing this module does not initialize anything.\"\"\"\n\ + import json\n\ + from pathlib import Path\n\n\ + def get_config() -> tuple[str, dict[str, object]]:\n\ + \x20 root = Path(__file__).resolve().parent\n\ + \x20 return str(root), json.loads((root / '{CONFIG}').read_text(encoding='utf-8'))\n", + super::GENERATED_PYTHON_HEADER + ) +} + +pub(crate) fn javascript_registration(relative: &Path, text: &str) -> String { + let extension = relative + .extension() + .and_then(|extension| extension.to_str()); + if !matches!(extension, Some("js" | "mjs")) + || !text.starts_with("// Generated by dynwinrt-codegen") + { + return text.into(); + } + let depth = relative + .parent() + .map_or(0, |parent| parent.components().count()); + let import = if depth == 0 { + "./".into() + } else { + "../".repeat(depth) + }; + let hook = if extension == Some("mjs") { + format!("import '{import}_winappsdk.cjs';{JS_MARKER}") + } else { + format!("require('{import}_winappsdk.cjs');{JS_MARKER}") + }; + let mut lines = text + .lines() + .filter(|line| !line.ends_with(JS_MARKER)) + .map(str::to_string) + .collect::>(); + let offset = if lines.get(1).is_some_and(|line| { + matches!( + line.trim(), + "'use strict';" | "\"use strict\";" | "'use strict'" + ) + }) { + 2 + } else { + 1 + }; + lines.insert(offset, hook); + format!("{}\n", lines.join("\n")) +} + +pub(crate) fn wire_existing_com_files(output: &Path) -> Result<(), String> { + let com_root = output.join("com"); + let Some(manifest) = super::read_com_generation_manifest(&com_root)? else { + return Ok(()); + }; + let files = manifest.roots.values().flatten().collect::>(); + for file in files { + com_path_is_safe(file)?; + let relative = Path::new("com").join(file); + if relative + .extension() + .is_none_or(|extension| extension != "js") + { + continue; + } + let path = output.join(&relative); + super::ensure_safe_generated_destination(output, &path)?; + let text = fs::read_to_string(&path) + .map_err(|error| format!("Cannot read {}: {error}", path.display()))?; + let registered = javascript_registration(&relative, &text); + if registered != text { + super::write_generated_javascript_file(output, &path, ®istered)?; + } + } + Ok(()) +} + +fn com_path_is_safe(relative: &str) -> Result<(), String> { + dynwinrt_codegen::codegen::com::windows_relative_path_key(relative)?; + if !super::is_safe_relative_path(Path::new(relative)) { + return Err(format!("Invalid retained COM path `{relative}`")); + } + Ok(()) +} + +fn wire_javascript(root: &Path, current: &Path) -> Result<(), String> { + for entry in fs::read_dir(current) + .map_err(|error| format!("Cannot inspect {}: {error}", current.display()))? + { + let entry = entry.map_err(|error| format!("Cannot inspect generated module: {error}"))?; + let path = entry.path(); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| format!("Cannot inspect {}: {error}", path.display()))?; + if super::is_link_or_reparse_point(&metadata) { + continue; + } + if metadata.is_dir() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if !name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "_native") { + wire_javascript(root, &path)?; + } + continue; + } + let extension = path.extension().and_then(|extension| extension.to_str()); + if !matches!(extension, Some("js" | "mjs")) { + continue; + } + let text = fs::read_to_string(&path) + .map_err(|error| format!("Cannot read {}: {error}", path.display()))?; + if !text.starts_with("// Generated by dynwinrt-codegen") { + continue; + } + let registered = javascript_registration(path.strip_prefix(root).unwrap(), &text); + if registered != text { + super::write_file(&path, ®istered)?; + } + } + Ok(()) +} + +fn decorate_javascript_package(output: &Path, manifest: &Manifest) -> Result<(), String> { + let path = output.join("package.json"); + let bytes = + fs::read(&path).map_err(|error| format!("Cannot read {}: {error}", path.display()))?; + let mut package: serde_json::Value = serde_json::from_slice(&bytes) + .map_err(|error| format!("Invalid generated package.json: {error}"))?; + package["version"] = manifest.generator_version.clone().into(); + package["sideEffects"] = true.into(); + package["os"] = serde_json::json!(["win32"]); + package["cpu"] = serde_json::json!(manifest.configuration.dlls.keys().collect::>()); + package["peerDependencies"][&manifest.runtime_import] = + manifest.generator_version.clone().into(); + // Explicitly include support and binary data; exclude dependencies/build caches by construction. + package["files"] = serde_json::json!([ + "**/*.js", + "**/*.mjs", + "**/*.cjs", + "**/*.d.ts", + CONFIG, + "_native/winappsdk" + ]); + super::write_file( + &path, + &format!( + "{}\n", + serde_json::to_string_pretty(&TypesFirst(&package)) + .map_err(|error| format!("Cannot serialize package.json: {error}"))? + ), + ) +} + +// TypeScript conditional exports must test "types" before runtime conditions. +struct TypesFirst<'a>(&'a serde_json::Value); + +impl Serialize for TypesFirst<'_> { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::{SerializeMap, SerializeSeq}; + match self.0 { + serde_json::Value::Object(object) => { + let mut map = serializer.serialize_map(Some(object.len()))?; + if let Some(types) = object.get("types") { + map.serialize_entry("types", &TypesFirst(types))?; + } + for (key, value) in object { + if key != "types" { + map.serialize_entry(key, &TypesFirst(value))?; + } + } + map.end() + } + serde_json::Value::Array(array) => { + let mut sequence = serializer.serialize_seq(Some(array.len()))?; + for value in array { + sequence.serialize_element(&TypesFirst(value))?; + } + sequence.end() + } + value => value.serialize(serializer), + } + } +} diff --git a/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs b/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs new file mode 100644 index 00000000..45a76998 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/winappsdk_bundle_test.rs @@ -0,0 +1,1401 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use sha2::{Digest, Sha256}; +use windows_metadata::{FieldAttributes, Type, TypeAttributes, Value, writer}; + +static NEXT: AtomicU64 = AtomicU64::new(0); +const DLL: &str = "Microsoft.WindowsAppRuntime.Bootstrap.dll"; +const MANIFEST: &str = ".dynwinrt-winappsdk.json"; + +struct Fixture { + root: PathBuf, + metadata: PathBuf, + output: PathBuf, +} + +impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "dwb{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + let metadata = root.join("BootstrapTest.winmd"); + let mut file = writer::File::new("BootstrapTest"); + let base = file.TypeRef("System", "Enum"); + file.TypeDef( + "Windows.BootstrapTest", + "Options", + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + file.Field( + "value__", + &Type::I32, + FieldAttributes::Public | FieldAttributes::SpecialName | FieldAttributes::RTSpecialName, + ); + let member = file.Field( + "One", + &Type::named("Windows.BootstrapTest", "Options"), + FieldAttributes::Public + | FieldAttributes::Static + | FieldAttributes::Literal + | FieldAttributes::HasDefault, + ); + file.Constant(writer::HasConstant::Field(member), &Value::I32(1)); + let object = file.TypeRef("System", "Object"); + file.TypeDef( + "Windows.BootstrapTest", + "Widget", + writer::TypeDefOrRef::TypeRef(object), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + file.TypeDef( + "_dynwinrt_build", + "Wheel", + writer::TypeDefOrRef::TypeRef(object), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + fs::write(&metadata, file.into_stream()).unwrap(); + for (architecture, machine) in [("x64", 0x8664), ("arm64", 0xaa64)] { + let directory = root.join("inputs").join(architecture); + fs::create_dir_all(&directory).unwrap(); + fs::write(directory.join(DLL), pe(machine)).unwrap(); + } + fs::write( + root.join("inputs").join("license.txt"), + "SDK test license\n", + ) + .unwrap(); + let output = root.join("bindings"); + Self { + root, + metadata, + output, + } + } + + fn command(&self, language: &str, configured: bool) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(&self.metadata) + .args([ + "--namespace", + "Windows.BootstrapTest", + "--lang", + language, + "--output", + ]) + .arg(&self.output) + .env_remove("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT"); + if configured { + command + .args(["--winappsdk-version", "2.5", "--winappsdk-bootstrap-path"]) + .arg(self.input("x64")) + .arg("--winappsdk-bootstrap-path") + .arg(self.input("arm64")); + } + command + } + + fn input(&self, architecture: &str) -> PathBuf { + self.root.join("inputs").join(architecture).join(DLL) + } + + fn command_with_paths(&self, language: &str, paths: &[PathBuf]) -> Command { + let mut command = self.command(language, false); + command.args(["--winappsdk-version", "2.5"]); + for path in paths { + command.arg("--winappsdk-bootstrap-path").arg(path); + } + command + } + + fn generate(&self, language: &str, configured: bool) { + succeeded(self.command(language, configured).output().unwrap()); + } + + fn refused_unchanged(&self, command: &mut Command, message: &str) -> String { + let before = files(&self.output); + let output = command.output().unwrap(); + assert!(!output.status.success(), "unexpected success"); + assert!( + String::from_utf8_lossy(&output.stderr).contains(message), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(files(&self.output), before); + assert!(fs::read_dir(&self.root).unwrap().all(|entry| { + let name = entry.unwrap().file_name().to_string_lossy().into_owned(); + !name.contains(".dynwinrt-stage-") && !name.contains(".dynwinrt-backup-") + })); + String::from_utf8_lossy(&output.stderr).into_owned() + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.root).unwrap(); + } +} + +fn succeeded(output: Output) { + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn files(root: &Path) -> BTreeMap> { + fn visit(root: &Path, current: &Path, result: &mut BTreeMap>) { + for entry in fs::read_dir(current).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + visit(root, &path, result); + } else { + result.insert( + path.strip_prefix(root).unwrap().into(), + fs::read(path).unwrap(), + ); + } + } + } + let mut result = BTreeMap::new(); + if root.is_dir() { + visit(root, root, &mut result); + } + result +} + +// A bounded PE fixture with one exported function; never loaded or executed. +fn pe(machine: u16) -> Vec { + fn u16_at(bytes: &mut [u8], offset: usize, value: u16) { + bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); + } + fn u32_at(bytes: &mut [u8], offset: usize, value: u32) { + bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + } + let mut bytes = vec![0; 0x600]; + bytes[0..2].copy_from_slice(b"MZ"); + u32_at(&mut bytes, 0x3c, 0x80); + bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); + u16_at(&mut bytes, 0x84, machine); + u16_at(&mut bytes, 0x86, 1); + let pe32 = machine == 0x014c; + let optional_size = if pe32 { 0xe0 } else { 0xf0 }; + u16_at(&mut bytes, 0x94, optional_size); + u16_at(&mut bytes, 0x96, 0x2022); + let optional = 0x98; + u16_at(&mut bytes, optional, if pe32 { 0x10b } else { 0x20b }); + u32_at(&mut bytes, optional + 16, 0x1100); + u32_at(&mut bytes, optional + 20, 0x1000); + u32_at(&mut bytes, optional + 32, 0x1000); + u32_at(&mut bytes, optional + 36, 0x200); + u32_at(&mut bytes, optional + 56, 0x2000); + u32_at(&mut bytes, optional + 60, 0x200); + u16_at(&mut bytes, optional + 68, 3); + let directories = optional + if pe32 { 96 } else { 112 }; + u32_at(&mut bytes, directories - 4, 16); + u32_at(&mut bytes, directories, 0x1000); + u32_at(&mut bytes, directories + 4, 0xa0); + let section = optional + usize::from(optional_size); + bytes[section..section + 5].copy_from_slice(b".text"); + u32_at(&mut bytes, section + 8, 0x400); + u32_at(&mut bytes, section + 12, 0x1000); + u32_at(&mut bytes, section + 16, 0x400); + u32_at(&mut bytes, section + 20, 0x200); + u32_at(&mut bytes, section + 36, 0x60000020); + u32_at(&mut bytes, 0x20c, 0x1060); + u32_at(&mut bytes, 0x210, 1); + u32_at(&mut bytes, 0x214, 1); + u32_at(&mut bytes, 0x218, 1); + u32_at(&mut bytes, 0x21c, 0x1030); + u32_at(&mut bytes, 0x220, 0x1034); + u32_at(&mut bytes, 0x224, 0x1038); + u32_at(&mut bytes, 0x230, 0x1100); + u32_at(&mut bytes, 0x234, 0x1080); + bytes[0x260..0x26c].copy_from_slice(b"fixture.dll\0"); + let export = b"MddBootstrapInitialize2\0"; + bytes[0x280..0x280 + export.len()].copy_from_slice(export); + bytes[0x300] = 0xc3; + bytes +} + +#[test] +fn bundle_generation_is_opt_in_and_exposes_precise_capabilities() { + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .arg("capabilities") + .output() + .unwrap(); + let capabilities = String::from_utf8_lossy(&output.stdout); + for name in [ + "python.winappsdk-bootstrap-config", + "javascript.winappsdk-bootstrap-config", + "input.ref-list", + ] { + assert!(capabilities.lines().any(|line| line == name)); + } + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, false); + assert!(!fixture.output.join(MANIFEST).exists()); + assert!(!fixture.output.join("_winappsdk.json").exists()); + assert!(!fixture.output.join("_dynwinrt_build").exists()); + let before = files(&fixture.output); + succeeded( + fixture + .command(language, true) + .arg("--dry-run") + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } +} + +#[test] +fn original_dll_bytes_licenses_and_runtime_configuration_are_packaged() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + for arch in ["x64", "arm64"] { + assert_eq!( + fs::read( + fixture + .output + .join("_native") + .join("winappsdk") + .join(arch) + .join(DLL) + ) + .unwrap(), + fs::read(fixture.root.join("inputs").join(arch).join(DLL)).unwrap() + ); + } + assert_eq!( + fs::read_to_string(fixture.output.join("_native/winappsdk/LICENSE.txt")).unwrap(), + "SDK test license\n" + ); + assert!( + fs::read_to_string(fixture.output.join("_native/winappsdk/NOTICE.txt")) + .unwrap() + .contains("NOT licensed under dynwinrt's MIT") + ); + let config = fs::read_to_string(fixture.output.join("_winappsdk.json")).unwrap(); + assert!(!config.contains(&fixture.root.to_string_lossy().to_string())); + if language == "py" { + let project = fs::read_to_string(fixture.output.join("pyproject.toml")).unwrap(); + assert!(project.contains("[project.entry-points.\"dynwinrt.winappsdk\"]")); + assert!(project.contains("bindings._winappsdk:get_config")); + assert!(project.contains("_native/winappsdk/*/*.dll")); + assert!( + fs::read_to_string(fixture.output.join("_dynwinrt_build/wheel.py")) + .unwrap() + .contains("win_amd64.win_arm64") + ); + } else { + let project: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("package.json")).unwrap()) + .unwrap(); + assert_eq!(project["sideEffects"], true); + assert_eq!(project["cpu"], serde_json::json!(["arm64", "x64"])); + assert_eq!( + project["peerDependencies"]["@microsoft/dynwinrt"], + env!("CARGO_PKG_VERSION") + ); + assert!( + project["files"] + .as_array() + .unwrap() + .iter() + .any(|entry| entry == "_native/winappsdk") + ); + let manifest = fs::read_to_string(fixture.output.join("package.json")).unwrap(); + let root_export = manifest.split("\".\": {").nth(1).unwrap(); + assert!( + root_export.find("\"types\"").unwrap() < root_export.find("\"import\"").unwrap() + ); + for name in [ + "index.js", + "index.mjs", + "index.proxy.js", + "windows/bootstrap-test/Options.js", + ] { + let path = fixture.output.join(name); + assert!(path.is_file(), "missing generated path {}", path.display()); + assert!(fs::read_to_string(path).unwrap().contains("_winappsdk.cjs")); + } + } + } +} + +#[test] +fn javascript_bootstrap_accepts_scoped_and_unscoped_package_names() { + for runtime in [ + "@microsoft/dynwinrt", + "dynwinrt-local", + "@custom-scope/dynwinrt.runtime", + "dynwinrt.runtime", + ] { + let fixture = Fixture::new(); + succeeded( + fixture + .command("js", true) + .args(["--import-name", runtime]) + .output() + .unwrap(), + ); + let package: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("package.json")).unwrap()) + .unwrap(); + assert_eq!( + package["peerDependencies"], + serde_json::json!({ runtime: env!("CARGO_PKG_VERSION") }) + ); + let registration = fs::read_to_string(fixture.output.join("_winappsdk.cjs")).unwrap(); + assert!(registration.contains(&format!("require(\"{runtime}/winappsdk\")"))); + let before = files(&fixture.output); + succeeded( + fixture + .command("js", false) + .args(["--import-name", runtime]) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } +} + +#[test] +fn javascript_bootstrap_rejects_non_package_imports_before_writing() { + let fixture = Fixture::new(); + for existing in [false, true] { + if existing { + fixture.generate("js", false); + } + for runtime in [ + "../../bindings/js/dist/winrt.js", + "./runtime.js", + r"..\..\bindings\js\dist\winrt.js", + r"C:\runtime\winrt.js", + "C:/runtime/winrt.js", + "/runtime/winrt.js", + r"\\server\share\runtime.js", + "file:///C:/runtime/winrt.js", + "@microsoft/dynwinrt/dist/winrt.js", + "dynwinrt/dist/winrt.js", + "@scope", + "@scope/", + "@scope//runtime", + "dynwinrt@0.1.0", + "runtime name", + "node_modules", + ".runtime", + "_runtime", + "", + ] { + for dry_run in [false, true] { + let mut command = fixture.command("js", true); + command.args(["--import-name", runtime]); + if dry_run { + command.arg("--dry-run"); + } + let error = fixture.refused_unchanged( + &mut command, + "Bootstrap bundling requires --import-name to be an npm package name", + ); + assert!(error.contains("clean output directory")); + assert_eq!(fixture.output.exists(), existing); + } + } + } +} + +#[test] +fn javascript_file_imports_remain_supported_without_bootstrap() { + for runtime in [ + "../../bindings/js/dist/winrt.js", + "./runtime.js", + "C:/runtime/winrt.js", + "@microsoft/dynwinrt/dist/winrt.js", + ] { + let fixture = Fixture::new(); + succeeded( + fixture + .command("js", false) + .args(["--import-name", runtime]) + .output() + .unwrap(), + ); + assert!(!fixture.output.join(MANIFEST).exists()); + assert!(!fixture.output.join("_winappsdk.cjs").exists()); + let package: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("package.json")).unwrap()) + .unwrap(); + assert!(package.get("peerDependencies").is_none()); + } +} + +#[test] +fn retained_javascript_bootstrap_validates_imports_when_options_are_omitted() { + let fixture = Fixture::new(); + fixture.generate("js", true); + let runtime = "../../bindings/js/dist/winrt.js"; + fixture.refused_unchanged( + fixture + .command("js", false) + .args(["--import-name", runtime]), + "Bootstrap bundling requires --import-name to be an npm package name", + ); + + // Reproduce a bundle created by the old generator with a file-path runtime import. + let manifest_path = fixture.output.join(MANIFEST); + let mut manifest: serde_json::Value = + serde_json::from_slice(&fs::read(&manifest_path).unwrap()).unwrap(); + manifest["runtime_import"] = runtime.into(); + let registration = fs::read_to_string(fixture.output.join("_winappsdk.cjs")) + .unwrap() + .replace("@microsoft/dynwinrt", runtime); + manifest["files"]["_winappsdk.cjs"] = + format!("{:x}", Sha256::digest(registration.as_bytes())).into(); + fs::write(fixture.output.join("_winappsdk.cjs"), registration).unwrap(); + fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + for incremental in [false, true] { + let mut command = fixture.command("js", false); + command.args(["--import-name", runtime]); + if incremental { + command.args(["--class-name", "Widget"]); + } + fixture.refused_unchanged( + &mut command, + "Bootstrap bundling requires --import-name to be an npm package name", + ); + } +} + +#[test] +fn same_bundle_survives_full_and_incremental_passes_with_omitted_options() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + for explicit in [true, false] { + let before = files(&fixture.output); + fixture.generate(language, explicit); + assert_eq!(files(&fixture.output), before); + } + succeeded( + fixture + .command(language, false) + .args(["--class-name", "Widget"]) + .output() + .unwrap(), + ); + assert!( + fixture + .output + .join("_native/winappsdk/x64") + .join(DLL) + .is_file() + ); + if language == "py" { + for incremental in [true, false] { + let mut command = fixture.command(language, false); + command.arg("--no-pyi"); + if incremental { + command.args(["--class-name", "Widget"]); + } + succeeded(command.output().unwrap()); + assert!(!fixture.output.join("_winappsdk.pyi").exists()); + let inventory = + fs::read_to_string(fixture.output.join(".dynwinrt-generated-files")).unwrap(); + assert!(inventory.contains(DLL)); + assert!(fixture.output.join(MANIFEST).is_file()); + } + fixture.generate(language, false); + assert!(fixture.output.join("_winappsdk.pyi").is_file()); + } + } +} + +#[test] +fn conflicting_version_or_payload_requires_complete_regeneration_without_writes() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let mut version = fixture.command(language, false); + version + .args(["--winappsdk-version", "2.6", "--winappsdk-bootstrap-path"]) + .arg(fixture.input("x64")) + .arg("--winappsdk-bootstrap-path") + .arg(fixture.input("arm64")); + fixture.refused_unchanged( + &mut version, + "Conflicting Windows App SDK version or payload", + ); + let mut bytes = pe(0x8664); + bytes[0x500] = 1; + fs::write(fixture.root.join("inputs/x64").join(DLL), bytes).unwrap(); + fixture.refused_unchanged( + &mut fixture.command(language, true), + "Conflicting Windows App SDK version or payload", + ); + if language == "py" { + let old_cache = fs::read_to_string(fixture.output.join("setup.cfg")).unwrap(); + let fresh = fixture.root.join("fresh").join("bindings"); + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(&fixture.metadata) + .args([ + "--namespace", + "Windows.BootstrapTest", + "--lang", + "py", + "--output", + ]) + .arg(&fresh) + .args(["--winappsdk-version", "2.5", "--winappsdk-bootstrap-path"]) + .arg(fixture.input("x64")) + .arg("--winappsdk-bootstrap-path") + .arg(fixture.input("arm64")); + succeeded(command.output().unwrap()); + let new_cache = fs::read_to_string(fresh.join("setup.cfg")).unwrap(); + assert_ne!( + old_cache, new_cache, + "payload changes must isolate setuptools build caches" + ); + } + } +} + +#[test] +fn concrete_input_selects_its_pe_architecture_without_using_codegen_host_architecture() { + for language in ["py", "js"] { + for architecture in ["x64", "arm64"] { + let fixture = Fixture::new(); + let other = if architecture == "x64" { + "arm64" + } else { + "x64" + }; + let renamed = fixture.input(other).with_file_name("renamed.bin"); + fs::copy(fixture.input(architecture), &renamed).unwrap(); + succeeded( + fixture + .command_with_paths(language, std::slice::from_ref(&renamed)) + .output() + .unwrap(), + ); + let config: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("_winappsdk.json")).unwrap()) + .unwrap(); + assert_eq!(config["dlls"].as_object().unwrap().len(), 1); + assert!(config["dlls"].get(architecture).is_some()); + assert!( + !fixture + .output + .join("_native/winappsdk") + .join(other) + .exists() + ); + if language == "py" { + let setup = + fs::read_to_string(fixture.output.join("_dynwinrt_build/wheel.py")).unwrap(); + let expected = if architecture == "x64" { + "win_amd64" + } else { + "win_arm64" + }; + assert!(setup.contains(&format!("'py3', 'none', '{expected}'"))); + } else { + let package: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("package.json")).unwrap()) + .unwrap(); + assert_eq!(package["cpu"], serde_json::json!([architecture])); + } + let before = files(&fixture.output); + succeeded( + fixture + .command_with_paths( + language, + &[renamed.clone(), fixture.input(architecture), renamed], + ) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } + } +} + +#[test] +fn malformed_pe_and_missing_exports_fail_before_output_changes() { + for language in ["py", "js"] { + for mutation in [ + "truncated", + "not-dll", + "missing-export", + "x86", + "unknown-machine", + "section-bounds", + ] { + let fixture = Fixture::new(); + fixture.generate(language, false); + let mut bytes = pe(0x8664); + match mutation { + "truncated" => bytes.truncate(80), + "not-dll" => bytes[0x97] &= !0x20, + "missing-export" => bytes[0x280] = b'X', + "x86" => bytes[0x84..0x86].copy_from_slice(&0x014c_u16.to_le_bytes()), + "unknown-machine" => bytes[0x84..0x86].copy_from_slice(&0xffff_u16.to_le_bytes()), + "section-bounds" => { + bytes[0x19c..0x1a0].copy_from_slice(&0xfffffff0_u32.to_le_bytes()) + } + _ => unreachable!(), + } + fs::write(fixture.input("x64"), bytes).unwrap(); + fixture.refused_unchanged(&mut fixture.command(language, true), "Bootstrap"); + } + } +} + +#[test] +fn invalid_flags_manual_collisions_and_publication_failures_are_atomic() { + let fixture = Fixture::new(); + fixture.generate("py", false); + for version in ["2", "2.5.1", "2.5-preview", "-1.2", "65536.1", "02.5"] { + let mut command = fixture.command("py", false); + command + .arg(format!("--winappsdk-version={version}")) + .arg("--winappsdk-bootstrap-path") + .arg(fixture.input("x64")); + fixture.refused_unchanged(&mut command, "--winappsdk-version"); + } + for field in [ + "--winappsdk-version=2.5", + "--winappsdk-bootstrap-path=missing.dll", + ] { + fixture.refused_unchanged(fixture.command("py", false).arg(field), "required"); + } + fs::write(fixture.output.join("_winappsdk.json"), "user-owned").unwrap(); + fixture.refused_unchanged( + &mut fixture.command("py", true), + "Refusing to overwrite non-generated", + ); + fs::remove_file(fixture.output.join("_winappsdk.json")).unwrap(); + fixture.refused_unchanged( + fixture + .command("py", true) + .env("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT", "before_publish"), + "Injected output transaction failure", + ); + fixture.generate("py", true); + fs::write( + fixture.output.join("_native/winappsdk/x64").join(DLL), + "modified", + ) + .unwrap(); + fixture.refused_unchanged( + &mut fixture.command("py", false), + "generated resource was modified", + ); +} + +#[test] +fn lost_bundle_manifest_cannot_silently_drop_configuration_or_orphan_dlls() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + fs::remove_file(fixture.output.join(MANIFEST)).unwrap(); + fixture.refused_unchanged( + &mut fixture.command(language, false), + "bundle artifacts have no ownership manifest", + ); + } +} + +#[test] +fn projected_namespace_and_private_build_hook_remain_distinct() { + let fixture = Fixture::new(); + succeeded( + fixture + .command("py", true) + .args(["--class-name", "_dynwinrt_build.Wheel"]) + .output() + .unwrap(), + ); + let projected = fs::read_to_string(fixture.output.join("dynwinrt_build/wheel.py")).unwrap(); + let build_hook = fs::read_to_string(fixture.output.join("_dynwinrt_build/wheel.py")).unwrap(); + assert!(projected.contains(" import Wheel")); + assert!(!projected.contains("class BootstrapWheel")); + assert!(build_hook.contains("class BootstrapWheel")); +} + +#[test] +fn input_order_and_identical_duplicates_preserve_payloads_licenses_and_cache() { + for language in ["py", "js"] { + let mut fixture = Fixture::new(); + fs::remove_file(fixture.root.join("inputs/license.txt")).unwrap(); + let duplicate = fixture.root.join("licensed-copy/renamed.bin"); + fs::create_dir(duplicate.parent().unwrap()).unwrap(); + fs::copy(fixture.input("x64"), &duplicate).unwrap(); + fs::write( + duplicate.parent().unwrap().join("license.txt"), + "License from a duplicate payload's source\n", + ) + .unwrap(); + let mut paths = vec![ + fixture.input("x64"), + fixture.input("arm64"), + fixture.input("x64"), + duplicate.clone(), + ]; + succeeded( + fixture + .command_with_paths(language, &paths) + .output() + .unwrap(), + ); + assert_eq!( + fs::read_to_string(fixture.output.join("_native/winappsdk/LICENSE.txt")).unwrap(), + "License from a duplicate payload's source\n" + ); + let before = files(&fixture.output); + assert_eq!( + before + .keys() + .filter(|path| path.extension().is_some_and(|extension| extension == "dll")) + .count(), + 2 + ); + paths.reverse(); + succeeded( + fixture + .command_with_paths(language, &paths) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + fixture.output = fixture.root.join("reverse/bindings"); + succeeded( + fixture + .command_with_paths(language, &paths) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + fixture.output = fixture.root.join("deduplicated/bindings"); + succeeded( + fixture + .command_with_paths(language, &[duplicate, fixture.input("arm64")]) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } +} + +#[test] +fn different_valid_payloads_for_one_architecture_report_both_sources_and_preserve_output() { + for language in ["py", "js"] { + let mut fixture = Fixture::new(); + let original = fixture.input("x64"); + let serviced = original.with_file_name("serviced.dll"); + let mut bytes = pe(0x8664); + bytes[0x500] = 1; + fs::write(&serviced, bytes).unwrap(); + + fixture.output = fixture.root.join("serviced/bindings"); + succeeded( + fixture + .command_with_paths(language, std::slice::from_ref(&serviced)) + .output() + .unwrap(), + ); + fixture.output = fixture.root.join("bindings"); + fixture.generate(language, true); + for paths in [ + [original.clone(), serviced.clone()], + [serviced.clone(), original.clone()], + ] { + let error = fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &paths), + "Conflicting Bootstrap DLL inputs for x64", + ); + assert!(error.contains(&original.display().to_string()), "{error}"); + assert!(error.contains(&serviced.display().to_string()), "{error}"); + } + } +} + +#[test] +fn identical_dlls_do_not_hide_conflicting_source_licenses() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let duplicate = fixture.root.join("alternate/renamed.dll"); + fs::create_dir(duplicate.parent().unwrap()).unwrap(); + fs::copy(fixture.input("x64"), &duplicate).unwrap(); + let duplicate_license = duplicate.parent().unwrap().join("license.txt"); + fs::write(&duplicate_license, "Different SDK license\n").unwrap(); + let original_license = fixture.root.join("inputs").join("license.txt"); + for paths in [ + [fixture.input("x64"), duplicate.clone()], + [duplicate.clone(), fixture.input("x64")], + ] { + let error = fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &paths), + "conflicting license.txt files", + ); + assert!( + error.contains(&original_license.display().to_string()), + "{error}" + ); + assert!( + error.contains(&duplicate_license.display().to_string()), + "{error}" + ); + } + } +} + +#[test] +fn missing_and_empty_paths_never_skip_an_input_or_change_existing_output() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + fixture.refused_unchanged(&mut fixture.command_with_paths(language, &[]), "required"); + fixture.refused_unchanged( + fixture + .command(language, false) + .arg("--winappsdk-bootstrap-path") + .arg(fixture.input("x64")), + "required", + ); + fixture.refused_unchanged( + fixture.command(language, false).args([ + "--winappsdk-version", + "2.5", + "--winappsdk-bootstrap-path", + ]), + "required", + ); + for path in ["", " "] { + fixture.refused_unchanged( + &mut fixture + .command_with_paths(language, &[fixture.input("x64"), PathBuf::from(path)]), + "--winappsdk-bootstrap-path", + ); + } + let empty = fixture.root.join("empty.dll"); + fs::write(&empty, []).unwrap(); + for path in [fixture.root.join("missing.dll"), empty] { + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &[fixture.input("x64"), path]), + "Bootstrap input", + ); + } + fixture.refused_unchanged( + fixture + .command_with_paths(language, &[fixture.input("x64")]) + .arg(fixture.input("arm64")), + "unexpected argument", + ); + } +} + +#[test] +fn directory_inputs_match_files_recursively_without_changing_the_bundle() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let before = files(&fixture.output); + let nested = fixture.root.join("inputs/deep/nested"); + fs::create_dir_all(&nested).unwrap(); + fs::copy(fixture.input("x64"), nested.join(DLL.to_ascii_lowercase())).unwrap(); + fs::write(nested.join("unrelated.dll"), "not a PE").unwrap(); + fs::write(fixture.root.join(DLL), "outside the search root").unwrap(); + let inputs = fixture.root.join("inputs"); + for paths in [ + vec![inputs.clone()], + vec![ + fixture.input("arm64"), + inputs.clone(), + nested.clone(), + inputs.clone(), + ], + vec![nested, inputs, fixture.input("x64")], + ] { + succeeded( + fixture + .command_with_paths(language, &paths) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } + fixture.generate(language, false); + assert_eq!(files(&fixture.output), before); + } +} + +#[test] +fn directory_scans_ignore_unsupported_pe_architectures_but_explicit_files_remain_strict() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let before = files(&fixture.output); + let inputs = fixture.root.join("inputs"); + for (folder, machine) in [("x86", 0x014c), ("unknown", 0xffff), ("arm64ec", 0x8664)] { + let dir = inputs.join(folder); + fs::create_dir(&dir).unwrap(); + fs::write(dir.join(DLL), pe(machine)).unwrap(); + } + let result = fixture + .command_with_paths(language, std::slice::from_ref(&inputs)) + .output() + .unwrap(); + let diagnostics = String::from_utf8_lossy(&result.stderr); + assert!( + diagnostics.contains("ignoring unsupported Bootstrap PE machine 0x014c"), + "{diagnostics}" + ); + assert!( + diagnostics.contains("ignoring unsupported Bootstrap PE machine 0xffff"), + "{diagnostics}" + ); + succeeded(result); + assert_eq!(files(&fixture.output), before); + for folder in ["x86", "unknown"] { + let file = inputs.join(folder).join(DLL); + for paths in [ + vec![inputs.clone(), file.clone()], + vec![file, inputs.clone()], + ] { + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &paths), + "in explicit file", + ); + } + } + } +} + +#[test] +fn empty_and_unsupported_only_directories_fail_even_with_other_valid_inputs() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let empty = fixture.root.join("empty"); + let unsupported = fixture.root.join("unsupported"); + fs::create_dir(&empty).unwrap(); + fs::create_dir(&unsupported).unwrap(); + fs::write(empty.join("another-name.dll"), pe(0x8664)).unwrap(); + fs::write(unsupported.join(DLL), pe(0x014c)).unwrap(); + for directory in [empty, unsupported] { + for paths in [ + vec![directory.clone()], + vec![fixture.input("x64"), directory.clone()], + ] { + let error = fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &paths), + "No supported Bootstrap DLLs found in directory", + ); + assert!(error.contains(&directory.display().to_string()), "{error}"); + } + } + } +} + +#[test] +fn damaged_directory_matches_cannot_be_ignored_as_unsupported() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let directory = fixture.root.join("inputs/bad"); + fs::create_dir(&directory).unwrap(); + for machine in [0x8664, 0x014c, 0xffff] { + let mut bytes = pe(machine); + bytes[0x280] = b'X'; + fs::write(directory.join(DLL), bytes).unwrap(); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &[fixture.root.join("inputs")]), + "does not export MddBootstrapInitialize2", + ); + } + fs::write(directory.join(DLL), b"MZ").unwrap(); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &[fixture.root.join("inputs")]), + "Invalid Bootstrap PE", + ); + } +} + +#[test] +fn directory_payload_and_license_conflicts_preserve_existing_output() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let inputs = fixture.root.join("inputs"); + let directory = inputs.join("conflicting"); + fs::create_dir(&directory).unwrap(); + let mut changed = pe(0x8664); + changed[0x500] = 1; + fs::write(directory.join(DLL), changed).unwrap(); + let error = fixture.refused_unchanged( + &mut fixture.command_with_paths(language, std::slice::from_ref(&inputs)), + "Conflicting Bootstrap DLL inputs for x64", + ); + assert!( + error.contains("conflicting") && error.contains("x64"), + "{error}" + ); + fs::copy(fixture.input("x64"), directory.join(DLL)).unwrap(); + fs::write(directory.join("license.txt"), "Different source license").unwrap(); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &[inputs]), + "conflicting license.txt files", + ); + } +} + +#[cfg(windows)] +#[test] +fn directory_scans_reject_junction_escapes_cycles_and_linked_roots() { + let node = std::env::var_os("DYNWINRT_TEST_NODE").unwrap_or_else(|| "node".into()); + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let inputs = fixture.root.join("inputs"); + let outside = fixture.root.join("outside"); + fs::create_dir(&outside).unwrap(); + fs::write(outside.join(DLL), "outside DLL must never be read").unwrap(); + let junction = inputs.join("linked"); + for target in [&outside, &inputs] { + succeeded(Command::new(&node).args([ + "-e", + "require('node:fs').symlinkSync(process.argv[1], process.argv[2], 'junction')", + ]).arg(target).arg(&junction).output().unwrap()); + let error = fixture.refused_unchanged( + &mut fixture.command_with_paths(language, std::slice::from_ref(&inputs)), + "Refusing linked Bootstrap directory entry", + ); + assert!(error.contains("linked"), "{error}"); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, std::slice::from_ref(&junction)), + "Refusing linked Bootstrap directory", + ); + fs::remove_dir(&junction).unwrap(); + } + } +} + +#[cfg(windows)] +#[test] +fn unreadable_directory_matches_and_subdirectories_fail_before_publication() { + use std::os::windows::fs::OpenOptionsExt; + + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, true); + let inputs = fixture.root.join("inputs"); + let file = fixture.input("x64"); + let lock = fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&file) + .unwrap(); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, std::slice::from_ref(&inputs)), + "Bootstrap", + ); + drop(lock); + let directory = inputs.join("unreadable"); + fs::create_dir(&directory).unwrap(); + let lock = fs::OpenOptions::new() + .read(true) + .share_mode(0) + .custom_flags(0x02000000) // FILE_FLAG_BACKUP_SEMANTICS opens the directory handle. + .open(&directory) + .unwrap(); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, &[inputs]), + "Bootstrap", + ); + drop(lock); + } +} + +#[test] +fn bootstrap_cli_help_uses_the_final_sdk_scoped_name_without_a_legacy_alias() { + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--help"]) + .output() + .unwrap(); + let help = String::from_utf8_lossy(&output.stdout); + assert!(help.contains("--winappsdk-version ")); + assert!(help.contains("--winappsdk-bootstrap-path ")); + assert!(help.contains("directory to search recursively")); + assert!(!help.contains("--bootstrap-dll-path")); + succeeded(output); + let fixture = Fixture::new(); + fixture.refused_unchanged( + fixture + .command("py", false) + .args(["--winappsdk-version", "2.5", "--bootstrap-dll-path"]) + .arg(fixture.input("x64")), + "unexpected argument", + ); +} + +#[test] +fn input_paths_are_literal_without_architecture_placeholder_expansion() { + for language in ["py", "js"] { + let fixture = Fixture::new(); + fixture.generate(language, false); + let literal = fixture.input("{arch}"); + fixture.refused_unchanged( + &mut fixture.command_with_paths(language, std::slice::from_ref(&literal)), + "Cannot inspect Bootstrap input", + ); + fs::create_dir(literal.parent().unwrap()).unwrap(); + fs::copy(fixture.input("x64"), &literal).unwrap(); + succeeded( + fixture + .command_with_paths(language, &[literal]) + .output() + .unwrap(), + ); + let config: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("_winappsdk.json")).unwrap()) + .unwrap(); + assert_eq!(config["dlls"].as_object().unwrap().len(), 1); + assert!(config["dlls"].get("x64").is_some()); + assert!(!fixture.output.join("_native/winappsdk/arm64").exists()); + } +} + +fn native_metadata() -> Option { + let path = std::env::var_os("DYNWINRT_WIN32_WINMD") + .map(PathBuf::from) + .filter(|path| path.is_file()); + if path.is_none() { + assert_ne!( + std::env::var("DYNWINRT_REQUIRE_WIN32_METADATA").as_deref(), + Ok("1"), + "Bootstrap/native generation tests require DYNWINRT_WIN32_WINMD" + ); + eprintln!("Skipping: DYNWINRT_WIN32_WINMD is not configured"); + } + path +} + +fn native_command(fixture: &Fixture, winmd: &Path, classes: &str, configured: bool) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(format!( + "{};{}", + winmd.display(), + fixture.metadata.display() + )) + .args(["--lang", "js", "--class-name", classes, "--output"]) + .arg(&fixture.output) + .env_remove("DYNWINRT_CODEGEN_TEST_FAIL_OUTPUT_COMMIT"); + if configured { + command + .args(["--winappsdk-version", "2.5", "--winappsdk-bootstrap-path"]) + .arg(fixture.input("x64")); + } + command +} + +#[test] +fn win32_hashes_include_registration_before_repeated_generation_and_verify_tampering() { + let Some(winmd) = native_metadata() else { + return; + }; + let namespace = "Windows.Win32.System.SystemInformation"; + let class = format!("{namespace}.Apis"); + for existing_unconfigured in [false, true] { + let fixture = Fixture::new(); + succeeded( + native_command(&fixture, &winmd, &class, !existing_unconfigured) + .output() + .unwrap(), + ); + if existing_unconfigured { + succeeded( + fixture + .command_with_paths("js", &[fixture.input("x64")]) + .output() + .unwrap(), + ); + } + let before = files(&fixture.output); + for configured in [true, false] { + succeeded( + native_command(&fixture, &winmd, &class, configured) + .output() + .unwrap(), + ); + assert_eq!(files(&fixture.output), before); + } + let path = fixture + .output + .join("win32/windows/win32/system/system-information/Apis.js"); + let bytes = fs::read(&path).unwrap(); + let manifest: serde_json::Value = serde_json::from_slice( + &fs::read(fixture.output.join("win32/.dynwinrt-win32-manifest.json")).unwrap(), + ) + .unwrap(); + assert_eq!( + manifest["namespaces"][namespace]["javascript_sha256"], + format!("{:x}", Sha256::digest(&bytes)) + ); + fs::write(&path, [bytes.as_slice(), b"\n// changed\n"].concat()).unwrap(); + fixture.refused_unchanged( + &mut native_command(&fixture, &winmd, &class, false), + "does not match its manifest", + ); + } +} + +#[test] +fn shared_com_helpers_remain_identical_when_configuration_is_retained_or_added() { + let Some(winmd) = native_metadata() else { + return; + }; + let first = "Windows.Win32.Graphics.Dxgi.IDXGIObject"; + let second = "Windows.Win32.System.ClrHosting.IHostMalloc"; + for existing_unconfigured in [false, true] { + let fixture = Fixture::new(); + succeeded( + native_command(&fixture, &winmd, first, !existing_unconfigured) + .output() + .unwrap(), + ); + if existing_unconfigured { + succeeded( + fixture + .command_with_paths("js", &[fixture.input("x64")]) + .output() + .unwrap(), + ); + } + let shared = fixture.output.join("com/unsafe/runtime.js"); + let before = fs::read(&shared).unwrap(); + succeeded( + native_command(&fixture, &winmd, second, false) + .output() + .unwrap(), + ); + assert_eq!(fs::read(&shared).unwrap(), before); + succeeded( + native_command(&fixture, &winmd, first, true) + .output() + .unwrap(), + ); + assert_eq!(fs::read(&shared).unwrap(), before); + } +} + +#[test] +fn configured_report_only_com_errors_roll_back_instead_of_stripping_package_metadata() { + let Some(winmd) = native_metadata() else { + return; + }; + for classes in [ + "Windows.Win32.Media.MediaFoundation.MFASYNCRESULT", + "Windows.Win32.Media.MediaFoundation.MFASYNCRESULT,Windows.BootstrapTest.Widget", + ] { + let fixture = Fixture::new(); + fixture.generate("js", true); + fixture.refused_unchanged( + &mut native_command(&fixture, &winmd, classes, false), + "emitted a support report but no callable class", + ); + } +} + +#[test] +fn npm_wrapper_pins_its_published_version_not_the_precompiled_cargo_version() { + let node = std::env::var_os("DYNWINRT_TEST_NODE").unwrap_or_else(|| "node".into()); + let probe = Command::new(&node).args(["-p", "process.arch"]).output(); + let Ok(probe) = probe else { + eprintln!("Skipping npm wrapper check: Node.js is unavailable"); + return; + }; + assert!(probe.status.success()); + let architecture = String::from_utf8(probe.stdout).unwrap(); + let fixture = Fixture::new(); + let wrapper = fixture.root.join("npm"); + let binary = wrapper.join("bin").join(architecture.trim()); + fs::create_dir_all(&binary).unwrap(); + fs::copy( + env!("CARGO_BIN_EXE_dynwinrt-codegen"), + binary.join("dynwinrt-codegen.exe"), + ) + .unwrap(); + fs::copy( + Path::new(env!("CARGO_MANIFEST_DIR")).join("npm/cli.js"), + wrapper.join("cli.js"), + ) + .unwrap(); + let version = "0.1.0-preview.999"; + fs::write( + wrapper.join("package.json"), + format!(r#"{{"version":"{version}"}}"#), + ) + .unwrap(); + for configured in [true, false] { + let args = fixture.command("js", configured); + succeeded( + Command::new(&node) + .arg(wrapper.join("cli.js")) + .args(args.get_args()) + .env("DYNWINRT_CODEGEN_NPM_VERSION", "9.9.9") + .output() + .unwrap(), + ); + let package: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join("package.json")).unwrap()) + .unwrap(); + assert_eq!(package["version"], version); + assert_eq!(package["peerDependencies"]["@microsoft/dynwinrt"], version); + let manifest: serde_json::Value = + serde_json::from_slice(&fs::read(fixture.output.join(MANIFEST)).unwrap()).unwrap(); + assert_eq!(manifest["generator_version"], version); + } + fixture.refused_unchanged( + &mut fixture.command("js", false), + "Unsupported Windows App SDK bundle manifest", + ); + let python = Fixture::new(); + let args = python.command("py", true); + succeeded( + Command::new(node) + .arg(wrapper.join("cli.js")) + .args(args.get_args()) + .output() + .unwrap(), + ); + let manifest: serde_json::Value = + serde_json::from_slice(&fs::read(python.output.join(MANIFEST)).unwrap()).unwrap(); + assert_eq!(manifest["generator_version"], env!("CARGO_PKG_VERSION")); +} diff --git a/tools/dynwinrt-codegen/tests/windows_sdk_corpus.json b/tools/dynwinrt-codegen/tests/windows_sdk_corpus.json new file mode 100644 index 00000000..b03e287c --- /dev/null +++ b/tools/dynwinrt-codegen/tests/windows_sdk_corpus.json @@ -0,0 +1,6 @@ +{ + "package": "Microsoft.Windows.SDK.CPP", + "version": "10.0.26100.8249", + "relative_path": "c/UnionMetadata/10.0.26100.0/Windows.winmd", + "sha256": "11191cbcc796e520d47547b3f986be94a48556fe336d4e63334596d9f31a7806" +}