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
5 changes: 5 additions & 0 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ helper. Apartment, message-pumping, and shutdown requirements are unchanged.
This is not a general older-Windows compatibility or addon feature-isolation
guarantee.

`npm run test:imports` checks every built addon's PE imports and measures root
and `/com` imports in separate fresh processes with a 10-second limit. Loaded-DLL
reports omit network enumeration and DNS on Node versions that support
`process.report.excludeNetwork`; failures include report/import phase timings.

## Quick start

`@microsoft/dynwinrt` is the **runtime**. You generate the typed bindings ahead of time with [`@microsoft/dynwinrt-codegen`](https://www.npmjs.com/package/@microsoft/dynwinrt-codegen), then import them at runtime:
Expand Down
40 changes: 38 additions & 2 deletions bindings/js/__test__/native-imports.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,35 @@
// Licensed under the MIT License.

import test from 'ava'
import { spawnSync } from 'node:child_process'
import { spawnSync, type SpawnSyncReturns } from 'node:child_process'
import { existsSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'

const packageDir = fileURLToPath(new URL('..', import.meta.url))
const distDir = join(packageDir, 'dist')

function importDiagnostics(
child: Pick<SpawnSyncReturns<string>, 'status' | 'signal' | 'error' | 'stdout' | 'stderr'>,
): string {
return `status=${child.status}, signal=${child.signal}\n${child.error ?? ''}\n${child.stdout}\n${child.stderr}`
}

test('fresh import timeout diagnostics retain phase output alongside the spawn error', (t) => {
const diagnostics = importDiagnostics({
status: null,
signal: 'SIGTERM',
error: Object.assign(new Error('spawnSync node ETIMEDOUT'), { code: 'ETIMEDOUT' }),
stdout: 'child stdout',
stderr: '[native-import] before-report:start 0.0ms\n[native-import] before-report:end 42.0ms\n',
})
t.true(diagnostics.includes('status=null, signal=SIGTERM'))
t.true(diagnostics.includes('ETIMEDOUT'))
t.true(diagnostics.includes('child stdout'))
t.true(diagnostics.includes('before-report:start 0.0ms'))
t.true(diagnostics.includes('before-report:end 42.0ms'))
})

function findDumpbin(): string {
const vswhere = join(
process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)',
Expand Down Expand Up @@ -60,12 +81,27 @@ for (const entrypoint of ['@microsoft/dynwinrt', '@microsoft/dynwinrt/com']) {
'--eval',
`
const assert = require('node:assert/strict');
const { writeSync } = require('node:fs');
const { basename } = require('node:path');
const { performance } = require('node:perf_hooks');
const started = performance.now();
const phase = name => writeSync(
2, '[native-import] ' + name + ' ' + (performance.now() - started).toFixed(1) + 'ms\\n'
);
// Only sharedObjects is needed; avoid network enumeration and DNS during reports.
// Feature detection preserves the check on Node versions before 20.13/22.
if ('excludeNetwork' in process.report) process.report.excludeNetwork = true;
phase('before-report:start');
const modules = () => process.report.getReport().sharedObjects.map(p => basename(p).toLowerCase());
const before = modules();
phase('before-report:end');
phase('require:start ' + ${JSON.stringify(entrypoint)});
const runtime = require(${JSON.stringify(entrypoint)});
phase('require:end');
assert.equal(typeof runtime.DynWinRtValue, 'function');
phase('after-report:start');
const after = modules();
phase('after-report:end');
assert(after.some(p => /^dynwinrt\\.win32-.*\\.node$/.test(p)), 'native addon was not loaded');
assert(
before.includes('coremessaging.dll') || !after.includes('coremessaging.dll'),
Expand All @@ -76,7 +112,7 @@ for (const entrypoint of ['@microsoft/dynwinrt', '@microsoft/dynwinrt/com']) {
],
{ cwd: packageDir, encoding: 'utf8', timeout: 10_000, windowsHide: true },
)
t.is(child.status, 0, `${child.error ?? child.stderr}`)
t.is(child.status, 0, importDiagnostics(child))
t.regex(child.stdout, /lazy-coremessaging-import-ok/)
})
}
64 changes: 48 additions & 16 deletions crates/dynwinrt/src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,14 @@ impl CollectionStorage {
pub(crate) fn is_large_value_type(self) -> bool {
self.is_value_type && self.elem_size > std::mem::size_of::<usize>()
}

fn array_stride(self) -> usize {
if self.is_value_type {
self.elem_size
} else {
std::mem::size_of::<*mut c_void>()
}
}
}

pub(crate) fn collection_storage(
Expand Down Expand Up @@ -241,6 +249,36 @@ pub(crate) unsafe fn write_item_out(
}
}

unsafe fn write_array_items(storage: CollectionStorage, items: &[usize], result: *mut *mut c_void) {
for (index, &raw) in items.iter().enumerate() {
let slot = result
.cast::<u8>()
.add(index * storage.array_stride())
.cast();
write_item_out(storage, raw, slot);
}
}

unsafe fn store_array_item(
storage: CollectionStorage,
values: *const *mut c_void,
index: usize,
) -> usize {
let slot = values.cast::<u8>().add(index * storage.array_stride());
let raw = if storage.is_value_type {
let mut word = 0usize;
std::ptr::copy_nonoverlapping(
slot,
(&mut word as *mut usize).cast::<u8>(),
storage.elem_size,
);
word as *mut c_void
} else {
slot.cast::<*mut c_void>().read()
};
store_abi_item(storage, raw)
}

unsafe fn clone_hstring_raw(raw: usize) -> usize {
if raw == 0 {
return 0;
Expand Down Expand Up @@ -685,10 +723,7 @@ impl SingleThreadedVector {
return S_OK;
}
let count = std::cmp::min(capacity as usize, items.len() - start);
for i in 0..count {
let raw = items[start + i];
write_item_out(me.storage, raw, items_out.add(i));
}
write_array_items(me.storage, &items[start..start + count], items_out);
*actual = count as u32;
S_OK
}
Expand All @@ -708,8 +743,7 @@ impl SingleThreadedVector {
}
let mut items = lock_or!(me.items, E_FAIL);
for i in 0..count as usize {
let raw = *values.add(i);
let val = store_abi_item(me.storage, raw);
let val = store_array_item(me.storage, values, i);
items.push(val);
}
drop(items);
Expand Down Expand Up @@ -779,9 +813,7 @@ impl SingleThreadedVector {
return S_OK;
}
let count = std::cmp::min(capacity as usize, items.len() - start);
for i in 0..count {
write_item_out(me.storage, items[start + i], items_out.add(i));
}
write_array_items(me.storage, &items[start..start + count], items_out);
*actual = count as u32;
S_OK
}
Expand Down Expand Up @@ -936,10 +968,7 @@ impl SingleThreadedVectorView {
return S_OK;
}
let count = std::cmp::min(capacity as usize, me.items.len() - start);
for i in 0..count {
let raw = me.items[start + i];
write_item_out(me.storage, raw, items_out.add(i));
}
write_array_items(me.storage, &me.items[start..start + count], items_out);
*actual = count as u32;
S_OK
}
Expand Down Expand Up @@ -1046,9 +1075,8 @@ impl SingleThreadedIterator {
let mut cursor = lock_or!(me.cursor, E_FAIL);
let remaining = me.items.len().saturating_sub(*cursor);
let count = std::cmp::min(capacity as usize, remaining);
for i in 0..count {
let raw = me.items[*cursor + i];
write_item_out(me.storage, raw, items_out.add(i));
if count > 0 {
write_array_items(me.storage, &me.items[*cursor..*cursor + count], items_out);
}
*cursor += count;
*actual = count as u32;
Expand Down Expand Up @@ -1258,6 +1286,10 @@ fn new_vector(items: Vec<usize>, storage: CollectionStorage, iids: VectorIids) -
// Tests
// ======================================================================

#[cfg(test)]
#[path = "vector_bulk_tests.rs"]
mod bulk_tests;

#[cfg(test)]
#[allow(unused_must_use)]
mod tests {
Expand Down
Loading
Loading