Skip to content

Commit

Permalink
feat(wasm-api): add debug() core API function
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 22, 2022
1 parent 0e27cc7 commit ca01978
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/wasm-api/include/wasmapi.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ extern "C" {
#include <stddef.h>
#include <stdint.h>

// Declares an imported symbol from named import module
// The prefix is only used for the C side, NOT for exported name
#define WASM_IMPORT(MODULE, TYPE, NAME, PREFIX) \
extern __attribute__((import_module(MODULE), import_name(#NAME))) \
TYPE PREFIX##NAME

// Same as EMSCRIPTEN_KEEP_ALIVE, ensures symbol will be exported
#define WASM_KEEP __attribute__((used))

// Generate stubs only if explicitly disabled by defining this symbol
Expand Down Expand Up @@ -53,6 +57,8 @@ WASM_IMPORT("wasmapi", void, _printF64Array, wasm)(void* addr, size_t len);
WASM_IMPORT("wasmapi", void, _printStr0, wasm)(void* addr);
WASM_IMPORT("wasmapi", void, _printStr, wasm)(void* addr, size_t len);

WASM_IMPORT("wasmapi", void, debug, wasm_)(void);

void wasm_printPtr(void* ptr) { wasm_printU32Hex((size_t)ptr); }

#ifdef __cplusplus
Expand Down
6 changes: 6 additions & 0 deletions packages/wasm-api/include/wasmapi.zig
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,16 @@ pub fn printStr(msg: []const u8) void {
_printStr(@ptrToInt(msg.ptr), msg.len);
}

/// Calls std.fmt.allocPrint to format given string, then calls `printStr()`
/// to output it via JS, then frees string's memory again
/// (Only available if the allocator used by `_wasm_allocate()` hasn't been disabled.)
pub fn printFmt(comptime fmt: []const u8, args: anytype) void {
if (allocator) |alloc| {
const res = std.fmt.allocPrint(alloc, fmt, args) catch return;
defer alloc.free(res);
printStr(res);
}
}

/// Triggers the JS/browser debugger
pub extern "wasmapi" fn debug() void;
1 change: 1 addition & 0 deletions packages/wasm-api/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ export interface CoreAPI extends WebAssembly.ModuleImports {
_printF64Array: (addr: number, len: number) => void;
_printStr0: (addr: number) => void;
_printStr: (addr: number, len: number) => void;
debug: () => void;
}

export interface WasmTypeBase {
Expand Down
4 changes: 4 additions & 0 deletions packages/wasm-api/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ export class WasmBridge<T extends WasmExports = WasmExports>

_printStr: (addr: number, len: number) =>
this.logger.debug(this.getString(addr, len)),

debug: () => {
debugger;
},
};
}

Expand Down

0 comments on commit ca01978

Please sign in to comment.