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