Skip to content

Commit

Permalink
wasm2c: add hook to allow a custom trap handler
Browse files Browse the repository at this point in the history
In production use cases, unwinding the stack before reporting an error throws away valuable information such as the stack trace. This hook allows the host to implement an alternate error recovery/reporting mechanism
  • Loading branch information
shravanrn committed Nov 7, 2022
1 parent 44370eb commit d149463
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
13 changes: 10 additions & 3 deletions wasm2c/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,16 @@ initialize the runtime. `wasm_rt_free` frees any global
state. `wasm_rt_is_initialized` can be used to confirm that the
runtime has been initialized.
`wasm_rt_trap` is a function that is called when the module traps. Some
possible implementations are to throw a C++ exception, or to just abort the
program execution.
`wasm_rt_trap` is a function that is called when the module traps. Some possible
implementations are to throw a C++ exception, or to just abort the program
execution. The default runtime included in wasm2c unwinds the stack using
`longjmp`. You can overide this call to `longjmp` from the embeder by defining a
custom trap handler with the signature `void
wasm2c_custom_trap_handler(wasm_rt_trap_t code)` and compiling the runtime with
the with macro definition `#define WASM_RT_MEMCHECK_SIGNAL_HANDLER
wasm2c_custom_trap_handler`. It is recommended that you add this macro
definition via a compiler flag
(`-DWASM_RT_MEMCHECK_SIGNAL_HANDLER=wasm2c_custom_trap_handler` on clang/gcc).
`wasm_rt_register_func_type` is a function that registers a function type. It
is a variadic function where the first two arguments give the number of
Expand Down
6 changes: 6 additions & 0 deletions wasm2c/wasm-rt-impl.c
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,13 @@ void wasm_rt_trap(wasm_rt_trap_t code) {
#if WASM_RT_USE_STACK_DEPTH_COUNT
wasm_rt_call_stack_depth = wasm_rt_saved_call_stack_depth;
#endif

#ifdef WASM_RT_TRAP_HANDLER
WASM_RT_TRAP_HANDLER(code);
wasm_rt_unreachable();
#else
WASM_RT_LONGJMP(wasm_rt_jmp_buf, code);
#endif
}

static bool func_types_are_equal(FuncType* a, FuncType* b) {
Expand Down
7 changes: 7 additions & 0 deletions wasm2c/wasm-rt.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <setjmp.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#ifdef __cplusplus
Expand All @@ -44,6 +45,12 @@ extern "C" {
#define wasm_rt_memcpy memcpy
#endif

#if __has_builtin(__builtin_unreachable)
#define wasm_rt_unreachable __builtin_unreachable
#else
#define wasm_rt_unreachable abort
#endif

/**
* Enable memory checking via a signal handler via the following definition:
*
Expand Down

0 comments on commit d149463

Please sign in to comment.