Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,19 @@ The script builds instrumented Python and Node native modules, runs the
Rust/Python/JavaScript tests and E2E suite, and writes HTML, LCOV, XML, and JSON
reports under `artifacts\coverage`. Default line gates are Rust 45%, Python
70%, and JavaScript 18%; override them with the `-Min*LineCoverage` parameters,
or re-check an existing report tree without rerunning tests via `-ValidateOnly`.
or re-check the percentage gates in an existing report tree without rerunning
tests via `-ValidateOnly`.

Report generation also requires executed Rust lines in each JavaScript native
binding module `winrt_types.rs`, `winrt_methods.rs`, `value.rs`, `winrt_array.rs`,
`winrt_struct.rs`, `js_storage.rs`, and `com_value.rs` under `bindings/js/src`,
plus `bindings/py/src/runtime.rs`. The wiring-only JavaScript `lib.rs` need not
appear in LCOV. E2E coverage additionally requires the JavaScript and Python
native WinRT implementation adapters and the core `winrt_implementation`
source family. Missing or unexecuted required sources fail independently of the
percentage gates; hits in another source or language cannot replace them.
Run `.\eng\coverage\coverage.threshold.tests.ps1` for the source-guard and
threshold boundary regression tests without building native modules.

### Code Style

Expand Down
24 changes: 24 additions & 0 deletions bindings/js/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,30 @@ test('flat Win32 pointer-bearing aggregates retain safe field owners', (t) => {
dll: 'kernel32.dll', entryPoint: 'GetLastError', parameters: [], returnType: 'u32',
})
t.throws(() => noArgs.invoke([aggregate]), { message: /detached/ })
const create = DynWin32Function.bind({
dll: 'kernel32.dll', entryPoint: 'CreateEventW',
parameters: [
{ type: 'pointer', direction: 'in', pointeeDescriptor: descriptor },
{ type: 'bool32', direction: 'in' },
{ type: 'bool32', direction: 'in' },
{ type: 'pointer', direction: 'in', nullable: true },
],
returnType: 'handle', returnCleanup: 'closeHandle', successRule: 'nonnull',
})
const args = [aggregate, DynWin32.bool32(true), DynWin32.bool32(false), DynWin32.nullPointer()]
t.throws(() => create.invoke(args), { message: /detached/ })
DynWin32.setNativeStructPointer(attributes, descriptor, 'lpSecurityDescriptor', DynWin32.nullPointer())
const result = create.invoke(args)
t.true(result.succeeded)
const event = DynWin32.toResource(result.returnValue!)!
try {
const alias = DynWin32.toResource(DynWin32.handle(event))!
alias.close()
t.true(event.closed)
t.true(alias.closed)
} finally {
event.close()
}
})

test('FORMATETC and STGMEDIUM expose a closed HGLOBAL semantic subset', (t) => {
Expand Down
169 changes: 169 additions & 0 deletions bindings/js/__test__/storage-lifetimes.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import test from 'ava'
import { execFileSync } from 'node:child_process'
import { join } from 'node:path'
import { DynWinRtMethodSig, DynWinRtType, DynWinRtValue, WinGuid, roInitialize } from '../dist/winrt.js'
import { DynCom } from '../dist/com-unsafe.js'
import { DynWin32, DynWin32Unsafe } from '../dist/win32-unsafe.js'

test('shared JS storage preserves byte-view offsets and WinRT copy isolation', (t) => {
roInitialize(1)
const bytes = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7])
const view = bytes.subarray(2, 6)
const base = DynCom.safeDataPointer(bytes)
const pointer = DynCom.safeDataPointer(view)
const counted = DynCom.buffer(view)
const win32 = DynWin32.dataPointer(view)
const winrt = DynWinRtValue.fromBuffer(view)
t.teardown(() => {
base.release()
pointer.release()
counted.release()
winrt.release()
})

const address = DynCom.asPointerBigint(base) + 2n
t.is(DynCom.asPointerBigint(pointer), address)
t.is(DynWin32Unsafe.pointerAddress(win32), address)
t.is(DynCom.bufferCount(counted), 4n)
t.deepEqual(winrt.toBuffer(), Buffer.from([2, 3, 4, 5]))
view.fill(9)
t.deepEqual(DynWin32.copyBuffer(view), Buffer.from([9, 9, 9, 9]))
t.deepEqual(winrt.toBuffer(), Buffer.from([2, 3, 4, 5]))
})

test('shared JS storage preserves domain-specific detachment errors and validation order', (t) => {
roInitialize(1)
const view = new Uint8Array(16)
const pointer = DynCom.safeDataPointer(view)
const counted = DynCom.buffer(view)
const win32 = DynWin32.dataPointer(view)
const copied = DynWinRtValue.fromBuffer(view)
const factoryIid = WinGuid.parse('44a9796f-723e-4fdf-a218-033e75b0c084')
const factoryType = DynWinRtType.registerInterface('StorageTest.IUriRuntimeClassFactory', factoryIid).addMethod(
'CreateUri',
new DynWinRtMethodSig().addIn(DynWinRtType.hstring()).addOut(DynWinRtType.object()),
)
const activation = DynWinRtValue.activationFactory('Windows.Foundation.Uri')
const factory = activation.cast(factoryIid)
t.teardown(() => {
pointer.release()
counted.release()
copied.release()
factory.release()
activation.release()
})
structuredClone(view.buffer, { transfer: [view.buffer] })

const pointerError = 'Cannot use a pointer whose TypedArray backing ArrayBuffer is detached'
t.throws(() => DynCom.asPointerBigint(pointer), { message: pointerError })
t.throws(() => DynWin32Unsafe.pointerAddress(win32), { message: pointerError })
t.throws(() => DynCom.asPointerBigint(counted), {
message: 'Cannot use a COM buffer whose backing ArrayBuffer is detached',
})
t.throws(() => DynWin32.bufferLength(view), { message: 'Cannot use a detached Win32 Buffer/Uint8Array' })
// Storage admission precedes WinRT signature validation; this must never dispatch.
for (const invoke of ['invoke', 'invokeAll'] as const) {
t.throws(() => factoryType.method(6)[invoke](factory, [pointer]), { message: pointerError })
}
t.deepEqual(copied.toBuffer(), Buffer.alloc(16))
})

test('shared JS storage rejects resized views without rejecting unchanged fixed views', (t) => {
const backing = new ArrayBuffer(16, { maxByteLength: 64 })
const tracking = new Uint8Array(backing)
const fixed = new Uint8Array(backing, 4, 8)
const pointer = DynCom.safeDataPointer(tracking)
const counted = DynCom.buffer(tracking)
const win32 = DynWin32.dataPointer(tracking)
const fixedPointer = DynCom.safeDataPointer(fixed)
const fixedCounted = DynCom.buffer(fixed)
const originalAddress = DynCom.asPointerBigint(fixedPointer)
t.teardown(() => {
for (const value of [pointer, counted, fixedPointer, fixedCounted]) value.release()
})

backing.resize(32)
t.throws(() => DynCom.asPointerBigint(pointer), { message: /backing storage changed/ })
t.throws(() => DynCom.asPointerBigint(counted), { message: /backing storage changed/ })
t.throws(() => DynWin32Unsafe.pointerAddress(win32), { message: /backing storage changed/ })
const current = DynCom.safeDataPointer(fixed)
t.teardown(() => current.release())
if (DynCom.asPointerBigint(current) === originalAddress) {
t.is(DynCom.asPointerBigint(fixedPointer), originalAddress)
t.is(DynCom.asPointerBigint(fixedCounted), 0n)
} else {
t.throws(() => DynCom.asPointerBigint(fixedPointer), { message: /backing storage changed/ })
t.throws(() => DynCom.asPointerBigint(fixedCounted), { message: /backing storage changed/ })
}
backing.resize(4)
t.throws(() => DynCom.asPointerBigint(fixedPointer), { message: /backing storage changed/ })
t.throws(() => DynCom.asPointerBigint(fixedCounted), { message: /backing storage changed/ })
})

test('shared JS storage keeps the existing view-kind and shared-backing boundaries', (t) => {
const wide = new Uint16Array(4)
const counted = DynCom.buffer(wide)
t.teardown(() => counted.release())
t.is(DynCom.bufferCount(counted), 4n)
for (const invalid of [wide, new DataView(new ArrayBuffer(8))]) {
t.throws(() => Reflect.apply(DynWin32.dataPointer, DynWin32, [invalid]))
t.throws(() => Reflect.apply(DynCom.safeDataPointer, DynCom, [invalid]))
}
const shared = new Uint8Array(new SharedArrayBuffer(8))
t.throws(() => DynCom.buffer(shared), {
message: 'SharedArrayBuffer-backed views cannot be passed to native COM calls',
})
t.throws(() => DynWin32.dataPointer(shared), { message: 'SharedArrayBuffer storage is unsupported for Win32' })
const sharedWide = new Uint16Array(new SharedArrayBuffer(8))
t.throws(() => Reflect.apply(DynCom.safeDataPointer, DynCom, [sharedWide]), {
message: 'SharedArrayBuffer-backed views cannot be passed to native COM calls',
})
t.throws(() => Reflect.apply(DynWin32.dataPointer, DynWin32, [sharedWide]), {
message: 'Expected unsigned byte Buffer or Uint8Array storage',
})
})

test('shared JS storage retains both JS owner strategies across collection', (t) => {
const output = execFileSync(
process.execPath,
[
'--expose-gc',
'-e',
`
const assert = require('node:assert/strict');
const { DynCom } = require(${JSON.stringify(join(process.cwd(), 'dist', 'com-unsafe.js'))});
const { DynWin32, DynWin32Unsafe } = require(${JSON.stringify(join(process.cwd(), 'dist', 'win32-unsafe.js'))});
function retain() {
const bytes = new Uint8Array([1, 2, 3, 4]);
const wide = new Uint16Array([5, 6]);
const win32 = new Uint8Array([7, 8]);
const pointer = DynCom.safeDataPointer(bytes);
return {
pointer, address: DynCom.asPointerBigint(pointer), counted: DynCom.buffer(wide),
win32: DynWin32.dataPointer(win32),
weak: [new WeakRef(bytes), new WeakRef(wide), new WeakRef(win32)],
};
}
(async () => {
const retained = retain();
for (let index = 0; index < 4; index++) {
await new Promise(setImmediate);
global.gc();
}
assert(retained.weak.every(value => value.deref() !== undefined));
assert.equal(DynCom.asPointerBigint(retained.pointer), retained.address);
assert.equal(DynCom.asPointerBigint(retained.counted), 0n);
assert.notEqual(DynWin32Unsafe.pointerAddress(retained.win32), 0n);
retained.pointer.release();
retained.counted.release();
process.stdout.write('retained');
})().catch(error => { console.error(error); process.exitCode = 1; });
`,
],
{ encoding: 'utf8', timeout: 30_000 },
)
t.is(output, 'retained')
})
40 changes: 33 additions & 7 deletions bindings/js/__test__/win32-contracts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import * as safe from '../dist/win32.js'

const require = createRequire(import.meta.url)
const machine = () => DynWin32.handle(0x80000002n)
const openKey = () => {
const openKey = (path = DynWin32.wideString('SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion')) => {
const open = DynWin32Function.bind({
dll: 'advapi32.dll',
entryPoint: 'RegOpenKeyExW',
Expand All @@ -43,12 +43,7 @@ const openKey = () => {
returnType: 'i32',
successRule: 'zero',
})
const result = open.invoke([
machine(),
DynWin32.wideString('SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'),
DynWin32.u32(0),
DynWin32.u32(1),
])
const result = open.invoke([machine(), path, DynWin32.u32(0), DynWin32.u32(1)])
if (!result.succeeded) throw new Error(`RegOpenKeyExW: ${DynWin32.toNumber(result.returnValue!)}`)
return DynWin32.toResource(result.outputs[0])!
}
Expand Down Expand Up @@ -355,6 +350,30 @@ test('Win32 native alias contracts share HKEY ownership and preserve borrowed in
}
})

test('Win32 owned outputs preserve retained byte and string input validation', (t) => {
for (const construct of [DynWin32.dataPointer, DynWin32.wideString]) {
const bytes = new Uint8Array(Buffer.from('SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\0', 'utf16le'))
const pointer = construct(bytes)
const resource = openKey(pointer)
try {
const alias = DynWin32.toResource(DynWin32.handle(resource))!
alias.close()
t.true(resource.closed)
t.true(alias.closed)
} finally {
resource.close()
}
if (construct === DynWin32.wideString) {
bytes[bytes.length - 2] = 65
t.throws(() => openKey(pointer), { message: /NUL-terminated/ })
}
structuredClone(bytes.buffer, { transfer: [bytes.buffer] })
const error = t.throws(() => openKey(pointer), { message: /detached/ })!
t.false(error instanceof DynWin32CallError)
t.false('cleanupFailures' in error)
}
})

test('Win32 predefined HKEY aliases use native pointer-width values, not truncated bits', (t) => {
for (const suffix of ['A', 'W']) {
const open = DynWin32Function.bind({
Expand Down Expand Up @@ -784,6 +803,13 @@ test('Win32 COM inputs borrow an exact IID and retain the independent reference'
}
object.release()
t.true(DynWin32Unsafe.pointerAddress(borrowed) > 0n)
const connected = DynWin32Function.bind({
dll: 'ole32.dll',
entryPoint: 'CoIsHandlerConnected',
parameters: [{ type: 'pointer', direction: 'in' }],
returnType: 'bool32',
})
t.true(DynWin32.toBoolean(connected.invoke([borrowed]).returnValue!))
} finally {
object.release()
}
Expand Down
Loading
Loading