Debian Codegraph @

wasm/nodejs/src/module.js

raw
1 import fs from "fs";
2 import path from "path";
3 import { createRequire } from "module";
4 import { promisify } from "util";
5 import { csoundWasiJsMessageCallback } from "./filesystem.js";
6 import { WASI } from "@wasmer/wasi";
7 import { default as wasiBindings } from "@wasmer/wasi/lib/bindings/node.js";
8 import { lowerI64Imports } from "@wasmer/wasm-transformer";
9 import { WasmFs } from "@wasmer/wasmfs";
10
11 const require = createRequire(import.meta.url);
12 const readFilePromise = promisify(fs.readFile);
13
14 const wasmDylibPath = require.resolve("@csound/wasm/lib/csound.dylib.wasm");
15 const PAGE_SIZE = 65536;
16
17 const getBinaryHeaderData = (wasmBytes) => {
18 const magicBytes = new Uint32Array(new Uint8Array(wasmBytes.subarray(0, 24)).buffer);
19 if (magicBytes[0] !== 0x6d736100) {
20 console.error("Wasm magic number is missing!");
21 }
22 if (wasmBytes[8] !== 0) {
23 log("Dylink section wasn't found in wasm binary, assuming static wasm.");
24 return "static";
25 }
26
27 let next = 9;
28 function getLEB() {
29 let returnValue = 0;
30 let mul = 1;
31 while (1) {
32 const byte = wasmBytes[next++];
33 returnValue += (byte & 0x7f) * mul;
34 mul *= 0x80;
35 if (!(byte & 0x80)) break;
36 }
37 return returnValue;
38 }
39 const sectionSize = getLEB();
40 // 6, size of "dylink" string = 7
41 next += 7;
42 const memorySize = getLEB();
43 const memoryAlign = getLEB();
44 const tableSize = getLEB();
45 const tableAlign = getLEB();
46 const neededDynlibsCount = getLEB();
47 return { sectionSize, memorySize, memoryAlign, neededDynlibsCount, tableSize, tableAlign };
48 };
49
50 export default async function ({ withPlugins = [] }) {
51 const fileBuffer = await readFilePromise(wasmDylibPath);
52 const { memorySize, memoryAlign, tableSize } = getBinaryHeaderData(fileBuffer);
53
54 const wasi = new WASI({
55 // --dir <wasm path>:<host path>
56 preopens: {
57 "/": "/",
58 },
59 env: {},
60 wasiBindings,
61 });
62 const loweredFileBuffer = await lowerI64Imports(fileBuffer);
63 const module = await WebAssembly.compile(loweredFileBuffer);
64 const options = wasi.getImports(module);
65
66 const fixedMemoryBase = 512;
67 const initialMemory = Math.ceil((memorySize + memoryAlign) / PAGE_SIZE);
68 const pluginsMemory = 0;
69 const totalInitialMemory = initialMemory + pluginsMemory + fixedMemoryBase;
70
71 const memory = new WebAssembly.Memory({
72 initial: totalInitialMemory,
73 });
74
75 const table = new WebAssembly.Table({ initial: tableSize + 1, element: "anyfunc" });
76
77 const stackPointer = new WebAssembly.Global(
78 { value: "i32", mutable: true },
79 totalInitialMemory * PAGE_SIZE,
80 );
81 const heapBase = new WebAssembly.Global(
82 { value: "i32", mutable: true },
83 totalInitialMemory * PAGE_SIZE,
84 );
85 const memoryBase = new WebAssembly.Global({ value: "i32", mutable: false }, fixedMemoryBase);
86 const tableBase = new WebAssembly.Global({ value: "i32", mutable: false }, 1);
87 const __dummy = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
88
89 options.env = options.env || {};
90 options.env.memory = memory;
91 options.env.__indirect_function_table = table;
92 options.env.__stack_pointer = stackPointer;
93 options.env.__memory_base = memoryBase;
94 options.env.__table_base = tableBase;
95 options.env.csoundLoadModules = () => {};
96
97 const streamBuffer = [];
98 const messagePort = {};
99 options.env.csoundWasiJsMessageCallback = csoundWasiJsMessageCallback({
100 memory,
101 streamBuffer,
102 messagePort,
103 });
104
105 options["GOT.mem"] = options["GOT.mem"] || {};
106 options["GOT.mem"].__heap_base = heapBase;
107 options["GOT.func"] = options["GOT.func"] || {};
108
109 const instance = await WebAssembly.instantiate(module, options);
110
111 const moduleExports = Object.assign({}, instance.exports);
112 const instance_ = {};
113 instance_.exports = Object.assign(moduleExports, {
114 memory,
115 });
116
117 wasi.start(instance_);
118 instance.exports.__wasi_js_csoundSetMessageStringCallback();
119 return instance_;
120 }