Skip to content

Commit 9892568

Browse files
committed
wasi: auto close non-preopen fds after running a wasi command
1 parent 9bccc5b commit 9892568

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/wasi.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as wasi from "./wasi_defs.js";
22
import { Fd } from "./fd.js";
3+
import { PreopenDirectory } from "./fs_mem.js";
34
import { debug } from "./debug.js";
45

56
export interface Options {
@@ -27,7 +28,6 @@ export default class WASI {
2728

2829
/// Start a WASI command
2930
start(instance: {
30-
// FIXME v0.3: close opened Fds after execution
3131
exports: { memory: WebAssembly.Memory; _start: () => unknown };
3232
}) {
3333
this.inst = instance;
@@ -40,6 +40,19 @@ export default class WASI {
4040
} else {
4141
throw e;
4242
}
43+
} finally {
44+
// Close all fds except stdin/stdout/stderr and the preopen
45+
// directories. No need to call fd_close on individual fds, just
46+
// reset the fds/freeFds array, and drop all the non-preopen fds
47+
// that follow the preopen ones:
48+
// https://github.com/WebAssembly/wasi-libc/blob/wasi-sdk-27/libc-bottom-half/sources/preopens.c#L244.
49+
this.#freeFds = [];
50+
for (let fd = 3; fd < this.fds.length; ++fd) {
51+
if (!(this.fds[fd] instanceof PreopenDirectory)) {
52+
this.fds.splice(fd, this.fds.length - fd);
53+
break;
54+
}
55+
}
4356
}
4457
}
4558

0 commit comments

Comments
 (0)