Repository navigation
Expand file tree
/
Copy pathwasi-shim.js
More file actions
252 lines (228 loc) · 8.86 KB
/
Copy pathwasi-shim.js
File metadata and controls
252 lines (228 loc) · 8.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// wasi-shim.js
//
// A tiny, dependency-free WASI Preview 1 shim, just large enough to run a
// program compiled by rontolisp (`rontolisp prog.lisp -o prog.wasm`) in a
// browser. rontolisp's WASM output imports exactly eleven functions from the
// "wasi_snapshot_preview1" module:
//
// fd_write, fd_read, path_open, fd_close, fd_readdir,
// random_get, clock_time_get, environ_sizes_get, environ_get,
// args_sizes_get, args_get
//
// A module built with --optimize imports only the ones it actually reaches, so
// the shim provides all eleven and lets the link pick.
//
// This shim implements them over plain JavaScript:
// - stdout/stderr (fd 1/2) are captured into strings instead of a real tty
// - stdin (fd 0) is fed from a string you provide
// - files (path_open) are not supported and report "no entry"
// - directories (fd_readdir) are not supported and report "not supported"
// - randomness uses crypto.getRandomValues, the clock uses Date.now()
// - environment variables come from the `env` option
// - command-line arguments come from the `args` option (what
// uiop:command-line-arguments reads; args[0] is the program name)
//
// It is intentionally minimal and easy to read; it is NOT a complete WASI
// implementation. For a fuller one, use a package such as
// `@bjorn3/browser_wasi_shim`.
const WASI_ESUCCESS = 0;
const WASI_EBADF = 8; // bad file descriptor
const WASI_ENOENT = 44; // no such file or directory
const WASI_ENOSYS = 52; // function not supported
/**
* Create a WASI Preview 1 import object plus helpers for one run of a module.
*
* @param {Object} [opts]
* @param {string} [opts.stdin] text delivered to the program's stdin (fd 0)
* @param {Object} [opts.env] environment variables, e.g. { NAME: "Ada" }
* @param {string[]} [opts.args] command-line arguments, argv[0] first, e.g.
* ["prog.wasm", "-n", "40"]; what
* uiop:command-line-arguments hands the program
* @returns {{ imports: object, setMemory: (m: WebAssembly.Memory) => void,
* getStdout: () => string, getStderr: () => string }}
*/
export function createWasi({ stdin = "", env = {}, args = [] } = {}) {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
let memory = null; // set after instantiation via setMemory()
let stdoutText = "";
let stderrText = "";
const stdinBytes = encoder.encode(stdin);
let stdinPos = 0;
// environ entries are "KEY=VALUE\0" byte arrays (WASI layout).
const envEntries = Object.entries(env).map(([k, v]) =>
encoder.encode(`${k}=${v}\0`),
);
// argv entries are NUL-terminated byte arrays, the same layout.
const argEntries = args.map((a) => encoder.encode(`${a}\0`));
const view = () => new DataView(memory.buffer);
const bytes = () => new Uint8Array(memory.buffer);
const imports = {
// fd_write(fd, iovs, iovs_len, nwritten) -> errno
// Concatenate the iovec slices and route fd 1 -> stdout, fd 2 -> stderr.
fd_write(fd, iovs, iovsLen, nwritten) {
let written = 0;
let chunk = "";
for (let i = 0; i < iovsLen; i++) {
const base = iovs + i * 8;
const ptr = view().getUint32(base, true);
const len = view().getUint32(base + 4, true);
chunk += decoder.decode(new Uint8Array(memory.buffer, ptr, len));
written += len;
}
if (fd === 1) stdoutText += chunk;
else if (fd === 2) stderrText += chunk;
view().setUint32(nwritten, written, true);
return WASI_ESUCCESS;
},
// fd_read(fd, iovs, iovs_len, nread) -> errno
// Serve bytes from the provided stdin string; EOF reads zero bytes.
fd_read(fd, iovs, iovsLen, nread) {
if (fd !== 0) return WASI_EBADF;
let total = 0;
const mem = bytes();
for (let i = 0; i < iovsLen; i++) {
const base = iovs + i * 8;
const ptr = view().getUint32(base, true);
const len = view().getUint32(base + 4, true);
let j = 0;
for (; j < len && stdinPos < stdinBytes.length; j++) {
mem[ptr + j] = stdinBytes[stdinPos++];
}
total += j;
if (j < len) break; // ran out of input
}
view().setUint32(nread, total, true);
return WASI_ESUCCESS;
},
// Files are not backed by anything in the browser.
path_open() {
return WASI_ENOENT;
},
fd_close() {
return WASI_ESUCCESS;
},
// fd_readdir(fd, buf, buf_len, cookie, bufused_out) -> errno
// There are no directories here, so a program that lists one gets "not
// supported" rather than an empty listing it would read as "no files".
fd_readdir() {
return WASI_ENOSYS;
},
// random_get(ptr, len) -> errno
random_get(ptr, len) {
crypto.getRandomValues(new Uint8Array(memory.buffer, ptr, len));
return WASI_ESUCCESS;
},
// clock_time_get(id, precision, out) -> errno ; out is an i64 of nanoseconds
clock_time_get(_id, _precision, out) {
const nanos = BigInt(Date.now()) * 1_000_000n;
view().setBigUint64(out, nanos, true);
return WASI_ESUCCESS;
},
// environ_sizes_get(count_out, bufsize_out) -> errno
environ_sizes_get(countOut, bufsizeOut) {
const bufSize = envEntries.reduce((sum, e) => sum + e.length, 0);
view().setUint32(countOut, envEntries.length, true);
view().setUint32(bufsizeOut, bufSize, true);
return WASI_ESUCCESS;
},
// environ_get(ptrs_out, buf_out) -> errno
environ_get(ptrsOut, bufOut) {
const mem = bytes();
let bufPtr = bufOut;
for (let i = 0; i < envEntries.length; i++) {
view().setUint32(ptrsOut + i * 4, bufPtr, true);
mem.set(envEntries[i], bufPtr);
bufPtr += envEntries[i].length;
}
return WASI_ESUCCESS;
},
// args_sizes_get(count_out, bufsize_out) -> errno. Same shape as the
// environ pair: rontolisp's _argv helper asks for the sizes, then for the
// pointer table and the buffer.
args_sizes_get(countOut, bufsizeOut) {
const bufSize = argEntries.reduce((sum, a) => sum + a.length, 0);
view().setUint32(countOut, argEntries.length, true);
view().setUint32(bufsizeOut, bufSize, true);
return WASI_ESUCCESS;
},
// args_get(ptrs_out, buf_out) -> errno
args_get(ptrsOut, bufOut) {
const mem = bytes();
let bufPtr = bufOut;
for (let i = 0; i < argEntries.length; i++) {
view().setUint32(ptrsOut + i * 4, bufPtr, true);
mem.set(argEntries[i], bufPtr);
bufPtr += argEntries[i].length;
}
return WASI_ESUCCESS;
},
// Programs that exit explicitly would call this. rontolisp's output never
// imports proc_exit, but we provide it so the shim also works with modules
// that do (a thrown sentinel ends _start cleanly).
proc_exit(code) {
throw new WasiExit(code);
},
};
return {
imports: { wasi_snapshot_preview1: imports },
setMemory: (m) => {
memory = m;
},
getStdout: () => stdoutText,
getStderr: () => stderrText,
};
}
/** Thrown by proc_exit to unwind out of _start. */
export class WasiExit extends Error {
constructor(code) {
super(`WASI exit ${code}`);
this.code = code;
}
}
/**
* Instantiate and run an already-loaded rontolisp-compiled `.wasm` command
* module (a `BufferSource`: `ArrayBuffer` or typed array), returning whatever
* it wrote to stdout/stderr. Use this when the bytes are already in memory —
* e.g. compiled in the browser by the playground's `rontoCompileWasm`, with no
* `.wasm` file to fetch.
*
* @param {BufferSource} wasmBytes the module bytes
* @param {Object} [opts] same options as createWasi()
* @returns {Promise<{ stdout: string, stderr: string, exitCode: number }>}
*/
export async function runWasmModule(wasmBytes, opts = {}) {
const wasi = createWasi(opts);
const { instance } = await WebAssembly.instantiate(wasmBytes, wasi.imports);
wasi.setMemory(instance.exports.memory);
let exitCode = 0;
try {
instance.exports._start();
} catch (e) {
if (e instanceof WasiExit) exitCode = e.code;
else throw e;
}
return {
stdout: wasi.getStdout(),
stderr: wasi.getStderr(),
exitCode,
};
}
/**
* Fetch, instantiate and run a rontolisp-compiled `.wasm` command module,
* returning whatever it wrote to stdout/stderr.
*
* @param {string} url URL of the .wasm file
* @param {Object} [opts] same options as createWasi()
* @returns {Promise<{ stdout: string, stderr: string, exitCode: number }>}
*/
export async function runWasm(url, opts = {}) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`failed to fetch ${url}: ${response.status}`);
}
// instantiateStreaming needs the correct application/wasm MIME type; fall
// back to ArrayBuffer instantiation when the server doesn't send it.
const wasmBytes = await response.arrayBuffer();
return runWasmModule(wasmBytes, opts);
}