Skip to content

Instantly share code, notes, and snippets.

@samrat
Last active April 24, 2022 19:00
Show Gist options
  • Save samrat/596bcc50b19773839d514d85d99179a6 to your computer and use it in GitHub Desktop.
Save samrat/596bcc50b19773839d514d85d99179a6 to your computer and use it in GitHub Desktop.

The Debug WASM build overwrites prog with 0. This seems to be related with creating an instance of the foo struct as this behaviour does not occur when I comment out the var foo = ... line.

$ zig build-lib test2.zig -target wasm32-freestanding -dynamic
$ node test2.js

The result is 12
The result is 49
The result is 0
$ zig build-lib test2.zig -target wasm32-freestanding -dynamic -O ReleaseSafe
$ node test2.js

The result is 12
The result is 49
The result is 49
const fs = require('fs');
const source = fs.readFileSync("./test2.wasm");
const typedArray = new Uint8Array(source);
WebAssembly.instantiate(typedArray, {
env: {
print: (result) => { console.log(`The result is ${result}`); }
}}).then(result => {
const compile = result.instance.exports.compile;
const alloc = result.instance.exports.alloc;
const linearMemory = result.instance.exports.memory;
const source = "12";
const pointer = alloc();
const userWasmBuffer = new Uint8Array(linearMemory.buffer, pointer, 100);
const encoder = new TextEncoder();
// console.log("encoded " + encoder.encode("hello"));
userWasmBuffer.set(encoder.encode(source));
userWasmBuffer[source.length] = 0;
compile(pointer);
});
const std = @import("std");
const allocator = @import("std").heap.page_allocator;
extern fn print(u32) void;
const FooKind = enum {
a,
b,
};
const Foo = struct {
buffer: [:0] const u8,
kind: ?FooKind,
};
export fn compile(prog: [*:0]const u8) [*:0]const u8 {
print(12);
print(@intCast(u32, prog[0]));
var s = std.mem.span(prog);
var foo = Foo {
.buffer = s,
.kind = null,
};
// In `ReleaseSafe` mode, this seems to print what
// I expect, but in `Debug` mode, the contents of `prog`
// is also set to 0.
print(@intCast(u32, prog[0]));
const c = std.fmt.allocPrintZ(allocator,
"foo: {any}", .{foo}) catch "[allocPrintZ failed]";
return c;
}
// TODO: take size as arg
export fn alloc() *[] u8 {
var ptr = allocator.alloc(u8, 1024) catch unreachable;
return &ptr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment