Skip to content

Commit 9f58293

Browse files
ktockGitHub Actions Bot
authored andcommitted
tcg/wasm32: Implement instantiation of Wasm binary
instantiate_wasm is a function that instantiates a TB's Wasm binary, importing the functions as specified by its arguments. Following the header definition in wasm32/tcg-target.c.inc, QEMU's memory is imported into the module as "env.buffer", and helper functions are imported as "helper.<id>". The instantiated Wasm module is imported to QEMU using Emscripten's "addFunction" feature[1] which returns a function pointer. This allows QEMU to call this module directly from C code via that pointer. Note Since FireFox 138, WebAssembly.Module no longer accepts a SharedArrayBuffer as input [2] as reported by Nicolas Vandeginste in my downstream fork[3]. This commit ensures that WebAssembly.Module() is passed a Uint8Array created from the binary data on a SharedArrayBuffer. [1] https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#calling-javascript-functions-as-function-pointers-from-c [2] https://bugzilla.mozilla.org/show_bug.cgi?id=1965217 [3] ktock/qemu-wasm#25 Signed-off-by: Kohei Tokunaga <ktokunaga.mail@gmail.com>
1 parent 31f588b commit 9f58293

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

tcg/wasm32.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "disas/dis-asm.h"
2626
#include "tcg-has.h"
2727
#include <ffi.h>
28+
#include <emscripten.h>
2829

2930

3031
#define ctpop_tr glue(ctpop, TCG_TARGET_REG_BITS)
@@ -44,6 +45,29 @@
4445

4546
__thread uintptr_t tci_tb_ptr;
4647

48+
EM_JS(int, instantiate_wasm, (int wasm_begin,
49+
int wasm_size,
50+
int import_vec_begin,
51+
int import_vec_size),
52+
{
53+
const memory_v = new DataView(HEAP8.buffer);
54+
const wasm = HEAP8.subarray(wasm_begin, wasm_begin + wasm_size);
55+
var helper = {};
56+
for (var i = 0; i < import_vec_size / 4; i++) {
57+
helper[i] = wasmTable.get(
58+
memory_v.getInt32(import_vec_begin + i * 4, true));
59+
}
60+
const mod = new WebAssembly.Module(new Uint8Array(wasm));
61+
const inst = new WebAssembly.Instance(mod, {
62+
"env" : {
63+
"buffer" : wasmMemory,
64+
},
65+
"helper" : helper,
66+
});
67+
68+
return addFunction(inst.exports.start, 'ii');
69+
});
70+
4771
static void tci_write_reg64(tcg_target_ulong *regs, uint32_t high_index,
4872
uint32_t low_index, uint64_t value)
4973
{

0 commit comments

Comments
 (0)