Hi all, I was trying to compile Zig to WASM with some sample code (see below), when I got hit with this error:
Uncaught RuntimeError: index out of bounds
add http://127.0.0.1:57391/zig-out/bin/main.wasm:126
<anonymous> http://127.0.0.1:57391/src/index.html:14
InterpretGeneratorResume self-hosted:1425
AsyncFunctionNext self-hosted:800
Oddly, this only happens when compiling in debug mode. Compiling in any of the release modes produces the expected output:
5
a + b = 5
Source code
build.zig:
const std = @import("std");
pub fn build(b: *std.Build) void {
const optimize = b.standardOptimizeOption(.{});
const wasm = b.addLibrary(.{
.name = "wasm",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = b.resolveTargetQuery(.{
.cpu_arch = .wasm32,
.ofmt = .wasm,
.os_tag = .freestanding,
}),
.optimize = optimize,
}),
.use_lld = false,
});
wasm.rdynamic = true;
const install_wasm = b.addInstallArtifact(wasm, .{
.dest_dir = .{ .override = .bin },
.dest_sub_path = "main.wasm",
});
b.getInstallStep().dependOn(&install_wasm.step);
}
src/main.zig
extern fn print(a: i32) void;
export fn add(a: i32, b: i32) i32 {
print(a + b);
return a + b;
}
src/index.html:
<!doctype html>
<script type="module">
const importObject = {
env: {
print: function (x) {
console.log(x);
},
},
};
const { instance } = await WebAssembly.instantiateStreaming(
fetch("../zig-out/bin/main.wasm"), // Compiled by zig
importObject,
);
console.log(`a + b = ${instance.exports.add(2, 3)}`); // Error occurs on this line
</script>
My first thought was that this was a regression in the new self-hosted x86 backend, but nope, setting .use_llvm = true
didn’t change anything. I tried setting use_lld
to true
, but still nothing. I tried out more Zig versions and surprisingly, 0.13.0 worked.
zig version | works |
---|---|
0.13.0 | ![]() |
0.14.0 | ![]() |
0.14.1 | ![]() |
master | ![]() |
Digging a bit deeper, I found out that the error goes away if I remove all arguments from the add
function (perhaps the function arguments are passed as an array?).
I didn’t manage to find an issue in the github repo documenting this. Is this a regression or am I doing something wrong (what could even go wrong with such a small piece of code)?