From af78ada00c645a98b3e149b206cfe75daf9d1aed Mon Sep 17 00:00:00 2001 From: nsfisis Date: Wed, 23 Apr 2025 03:50:45 +0900 Subject: pass custom stdout/stderr --- README.md | 4 ++-- index.mjs | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- php-wasm.c | 2 -- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ba182c7..e14a57e 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ Article about this repo (Japanese): https://blog.nsfisis.dev/posts/2023-10-02/co ## Build ``` -$ docker build -t php-wasm . +$ docker build -t tiny-php.wasm . ``` ## Run ``` -$ echo 'echo "Hello, World!", PHP_EOL;' | docker run --rm -i php-wasm +$ echo 'echo "Hello, World!", PHP_EOL;' | docker run --rm -i tiny-php.wasm ``` ## License diff --git a/index.mjs b/index.mjs index f58aa15..055a9a8 100644 --- a/index.mjs +++ b/index.mjs @@ -1,12 +1,57 @@ import { readFile } from 'node:fs/promises'; import PHPWasm from './php-wasm.mjs' +const PRELUDE = ` +define('STDIN', fopen('php://stdin', 'r')); +define('STDOUT', fopen('php://stdout', 'r')); +define('STDERR', fopen('php://stderr', 'r')); + +`; + const code = await readFile('/dev/stdin', { encoding: 'utf-8' }); -const { ccall } = await PHPWasm(); +const BUFFER_MAX = 1024 * 1024; // 1 MiB + +let stdoutPos = 0; // bytewise +const stdoutBuf = Buffer.alloc(BUFFER_MAX); +let stderrPos = 0; // bytewise +const stderrBuf = Buffer.alloc(BUFFER_MAX); + +const { ccall } = await PHPWasm({ + stdout: (asciiCode) => { + if (asciiCode === null) { + return; // flush + } + if (BUFFER_MAX <= stdoutPos) { + return; // ignore + } + stdoutBuf.writeUInt8( + asciiCode < 0 ? asciiCode + 256 : asciiCode, + stdoutPos++, + ); + }, + stderr: (asciiCode) => { + if (asciiCode === null) { + return; // flush + } + if (BUFFER_MAX <= stderrPos) { + return; // ignore + } + stderrBuf.writeUInt8( + asciiCode < 0 ? asciiCode + 256 : asciiCode, + stderrPos++, + ); + }, +}); const result = ccall( 'php_wasm_run', 'number', ['string'], - [code], + [PRELUDE + code], ); console.log(`result: ${result}`); + +console.log("stdout:"); +console.log(stdoutBuf.subarray(0, stdoutPos).toString()); + +console.log("stderr:"); +console.log(stderrBuf.subarray(0, stderrPos).toString()); diff --git a/php-wasm.c b/php-wasm.c index cef661f..9c71ca1 100644 --- a/php-wasm.c +++ b/php-wasm.c @@ -15,9 +15,7 @@ int EMSCRIPTEN_KEEPALIVE php_wasm_run(const char* code) { PHP_EMBED_END_BLOCK(); - fprintf(stdout, "\n"); fflush(stdout); - fprintf(stderr, "\n"); fflush(stderr); return result == SUCCESS ? 0 : 1; -- cgit v1.2.3-70-g09d2