diff --git a/examples/demo/build.js b/examples/demo/build.js new file mode 100644 index 0000000..fbc497f --- /dev/null +++ b/examples/demo/build.js @@ -0,0 +1,41 @@ +export function buildWasm({ types, funcs, exports }) { + const str = s => [s.length, ...Buffer.from(s)]; + const section = (id, data) => [id, data.length, ...data]; + + return new Uint8Array([ + 0x00, + 0x61, + 0x73, + 0x6d, // magic + 0x01, + 0x00, + 0x00, + 0x00, // version + + ...section(0x01, [ + // types + types.length, + ...types.flatMap(([params, results]) => [0x60, params.length, ...params, results.length, ...results]) + ]), + + ...section(0x03, [ + // funcs -> type index + funcs.length, + ...funcs.map((_, i) => i) + ]), + + ...section(0x07, [ + // exports + exports.length, + ...exports.flatMap(([name, kind, idx]) => [...str(name), kind, idx]) + ]), + + ...section(0x0a, [ + funcs.length, + ...funcs.flatMap(({ locals = [], body }) => { + const code = [locals.length, ...body, 0x0b]; + return [code.length, ...code]; + }) + ]) + ]); +} diff --git a/examples/demo/wasm.js b/examples/demo/wasm.js new file mode 100644 index 0000000..b7db652 --- /dev/null +++ b/examples/demo/wasm.js @@ -0,0 +1,17 @@ +import { buildWasm } from './build'; + +const i32 = 0x7f; +const local_get = i => [0x20, i]; +const i32_add = [0x6a]; + +const wasmBytes = buildWasm({ + types: [[[i32, i32], [i32]]], + funcs: [{ body: [...local_get(0), ...local_get(1), ...i32_add] }], + exports: [['add', 0x00, 0]] +}); + +console.log(`compiled to ${wasmBytes.length} bytes\n`); +const { instance } = await WebAssembly.instantiate(wasmBytes); + +console.log('add(2, 3) =', instance.exports.add(2, 3)); +console.log('add(100, 200) =', instance.exports.add(100, 200)); diff --git a/src/modules/napi.c b/src/modules/napi.c index cb243d6..9ced3bf 100644 --- a/src/modules/napi.c +++ b/src/modules/napi.c @@ -1344,6 +1344,7 @@ NAPI_EXTERN napi_status NAPI_CDECL napi_get_cb_info( if (argv) { size_t ncopy = requested < info->argc ? requested : info->argc; if (ncopy > 0) memcpy(argv, info->argv, ncopy * sizeof(napi_value)); + for (size_t i = ncopy; i < requested; i++) argv[i] = (napi_value)js_mkundef(); } *argc = info->argc; }