Path: blob/main/core/dylink/test/libc-archive/app.js
1393 views
const WASI = require("../../node_modules/wasi-js/dist/").default;1const bindings = require("../../node_modules/wasi-js/dist/bindings/node").default;2const importWebAssemblyDlopen = require("../../dist").default;3const { readFileSync } = require("fs");4const debug = require("debug");56function importWebAssemblySync(path, importObject) {7const binary = new Uint8Array(readFileSync(path));8const mod = new WebAssembly.Module(binary);9return new WebAssembly.Instance(mod, importObject);10}1112const table = new WebAssembly.Table({ initial: 10000, element: "anyfunc" });13exports.table = table;1415async function main() {16const memory = new WebAssembly.Memory({ initial: 1000 });17const wasi = new WASI({ bindings, env: process.env, preopens: { "/": "/" } });18const importObject = {19wasi_snapshot_preview1: wasi.wasiImport,20env: {21memory,22__indirect_function_table: table,23_Py_CheckEmscriptenSignals: () => {},24_Py_CheckEmscriptenSignalsPeriodically: () => {},25_Py_emscripten_runtime: () => 0,26getrandom: (bufPtr, bufLen, _flags) => {27// NOTE: returning 0 here (our default stub behavior)28// would result in Python hanging on startup!29bindings.randomFillSync(30// @ts-ignore31new Uint8Array(memory.buffer),32bufPtr,33bufLen34);35return bufLen;36},37},38};39initPythonTrampolineCalls(table, importObject.env);40const instance = await importWebAssemblyDlopen({41path: "app.wasm",42importWebAssemblySync,43importObject,44stub: "silent",45readFileSync,46});47wasi.start(instance, memory);48exports.instance = instance;49exports.wasi = wasi;50}5152// copied from packages/python-wasm/src/wasm/worker/trampoline.ts53// without types so we can have a nice self-contained example for dylink.5455function initPythonTrampolineCalls(table, env) {56const log = debug("trampoline");57env["_PyImport_InitFunc_TrampolineCall"] = (ptr) => {58const r = table.get(ptr)();59log("_PyImport_InitFunc_TrampolineCall - ptr=", ptr, " r=", r);60return r;61};6263env["_PyCFunctionWithKeywords_TrampolineCall"] = (ptr, self, args, kwds) => {64// log("_PyCFunctionWithKeywords_TrampolineCall - ptr=", ptr);65return table.get(ptr)(self, args, kwds);66};6768env["descr_set_trampoline_call"] = (set, obj, value, closure) => {69// log("descr_set_trampoline_call");70return table.get(set)(obj, value, closure);71};7273env["descr_get_trampoline_call"] = (get, obj, closure) => {74// log("descr_get_trampoline_call");75return table.get(get)(obj, closure);76};77}7879main();808182