Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow browsers to specify fd preopens #64

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"author": "The Extism Authors <[email protected]>",
"license": "BSD-3-Clause",
"devDependencies": {
"@bjorn3/browser_wasi_shim": "^0.2.17",
"@bjorn3/browser_wasi_shim": "^0.2.20",
"@playwright/test": "^1.39.0",
"@types/node": "^20.8.7",
"@typescript-eslint/eslint-plugin": "^6.8.0",
Expand Down
2 changes: 1 addition & 1 deletion src/foreground-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ async function instantiateModule(
}

if (wasi === null) {
wasi = await loadWasi(opts.allowedPaths, opts.enableWasiOutput);
wasi = await loadWasi(opts.allowedPaths, opts.enableWasiOutput, opts.fileDescriptors);
wasiList.push(wasi);
imports.wasi_snapshot_preview1 = await wasi.importObject();
}
Expand Down
15 changes: 15 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,19 @@ export interface Plugin {
reset(): Promise<boolean>;
}

/**
* Options for initializing WASI.
*/
export interface WASIOptions {
/**
* A list of file descriptors; only available in browser environments.
*
* See [`@bjorn3/browser_wasi_shim`](https://github.com/bjorn3/browser_wasi_shim) for more
* details on use.
*/
fileDescriptors: (import('@bjorn3/browser_wasi_shim').Fd)[];
}

/**
* Options for initializing an Extism plugin.
*/
Expand Down Expand Up @@ -167,6 +180,7 @@ export interface ExtismPluginOptions {
functions?: { [key: string]: { [key: string]: (callContext: CallContext, ...args: any[]) => any } } | undefined;
allowedPaths?: { [key: string]: string } | undefined;
allowedHosts?: string[] | undefined;
wasiOptions?: WasiOptions;

/**
* Whether WASI stdout should be forwarded to the host.
Expand All @@ -189,6 +203,7 @@ export interface InternalConfig {
wasiEnabled: boolean;
config: PluginConfig;
sharedArrayBufferSize: number;
wasiOptions: WasiOptions | null;
}

export interface InternalWasi {
Expand Down
1 change: 1 addition & 0 deletions src/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export async function createPlugin(
config: opts.config,
enableWasiOutput: opts.enableWasiOutput,
sharedArrayBufferSize: Number(opts.sharedArrayBufferSize) || 1 << 16,
fileDescriptors: opts.fileDescriptors ?? [],
};

return (opts.runInWorker ? _createBackgroundPlugin : _createForegroundPlugin)(ic, names, moduleData);
Expand Down
39 changes: 10 additions & 29 deletions src/polyfills/browser-wasi.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,29 @@
import { WASI, Fd, File, OpenFile, wasi } from '@bjorn3/browser_wasi_shim';
import { type InternalWasi } from '../mod.ts';

class Output extends Fd {
#mode: string;

constructor(mode: string) {
super();
this.#mode = mode;
}

fd_write(view8: Uint8Array, iovs: [wasi.Iovec]): { ret: number; nwritten: number } {
let nwritten = 0;
const decoder = new TextDecoder();
const str = iovs.reduce((acc, iovec, idx, all) => {
nwritten += iovec.buf_len;
const buffer = view8.slice(iovec.buf, iovec.buf + iovec.buf_len);
return acc + decoder.decode(buffer, { stream: idx !== all.length - 1 });
}, '');

(console[this.#mode] as any)(str);

return { ret: 0, nwritten };
}
}
import { WASI, Fd, File, OpenFile, ConsoleStdout } from '@bjorn3/browser_wasi_shim';
import { type InternalWasi } from '../interfaces.ts';

export async function loadWasi(
_allowedPaths: { [from: string]: string },
enableWasiOutput: boolean,
fileDescriptors: Fd[],
): Promise<InternalWasi> {
console.log('fileDescriptors = ', fileDescriptors);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chrisdickinson - does this console.log need to be here, or just leftover from debugging?

const args: Array<string> = [];
const envVars: Array<string> = [];
const fds: Fd[] = enableWasiOutput
? [
new Output('log'), // fd 0 is dup'd to stdout
new Output('log'),
new Output('error'),
ConsoleStdout.lineBuffered((msg) => console.log(msg)), // fd 0 is dup'd to stdout
ConsoleStdout.lineBuffered((msg) => console.log(msg)),
ConsoleStdout.lineBuffered((msg) => console.warn(msg)),
...fileDescriptors,
]
: [
new OpenFile(new File([])), // stdin
new OpenFile(new File([])), // stdout
new OpenFile(new File([])), // stderr
...fileDescriptors,
];

const context = new WASI(args, envVars, fds);
const context = new WASI(args, envVars, fds, { debug: false });

return {
async importObject() {
Expand Down
8 changes: 5 additions & 3 deletions src/polyfills/deno-wasi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function createDevNullFDs() {
return {
async close() {
needsClose = false;
await Promise.all([stdin.close(), stdout.close()]).catch(() => {});
await Promise.all([stdin.close(), stdout.close()]).catch(() => { });
},
fds: [stdin.fd, stdout.fd, stdout.fd],
};
Expand All @@ -29,11 +29,13 @@ async function createDevNullFDs() {
export async function loadWasi(
allowedPaths: { [from: string]: string },
enableWasiOutput: boolean,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fileDescriptors: Fd[],
): Promise<InternalWasi> {
const {
close,
fds: [stdin, stdout, stderr],
} = enableWasiOutput ? { async close() {}, fds: [0, 1, 2] } : await createDevNullFDs();
} = enableWasiOutput ? { async close() { }, fds: [0, 1, 2] } : await createDevNullFDs();
const context = new Context({
preopens: allowedPaths,
exitOnReturn: false,
Expand Down Expand Up @@ -76,7 +78,7 @@ export async function loadWasi(
context.start({
exports: {
memory,
_start: () => {},
_start: () => { },
},
});
}
Expand Down
3 changes: 3 additions & 0 deletions src/polyfills/node-wasi.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Fd } from '@bjorn3/browser_wasi_shim';
import { WASI } from 'wasi';
import { type InternalWasi } from '../interfaces.ts';
import { devNull } from 'node:os';
Expand Down Expand Up @@ -39,6 +40,8 @@ async function createDevNullFDs() {
export async function loadWasi(
allowedPaths: { [from: string]: string },
enableWasiOutput: boolean,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fileDescriptors: Fd[],
): Promise<InternalWasi> {
const {
close,
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "Node",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"allowImportingTsExtensions": true,
"emitDeclarationOnly": true,
"declaration": true,
"strict": true,
"skipLibCheck": true,
Expand Down