Use setjmp/longjmp to handle LLVM exceptions.

This commit is contained in:
losfair
2019-08-07 00:06:35 +08:00
parent 180522095f
commit b50fd31adb
2 changed files with 47 additions and 5 deletions

View File

@ -5,6 +5,41 @@
extern "C" void __register_frame(uint8_t *);
extern "C" void __deregister_frame(uint8_t *);
struct UnwindPoint {
UnwindPoint *prev;
jmp_buf unwind_info;
std::unique_ptr<std::exception> exception;
};
static thread_local UnwindPoint *unwind_state = nullptr;
void catch_unwind(std::function<void()>&& f) {
UnwindPoint current;
current.prev = unwind_state;
unwind_state = &current;
bool rethrow = false;
if(setjmp(current.unwind_info)) {
rethrow = true;
} else {
f();
}
unwind_state = current.prev;
if(rethrow) throw *current.exception;
}
void unsafe_unwind(std::exception *exception) {
UnwindPoint *state = unwind_state;
if(state) {
state->exception.reset(exception);
longjmp(state->unwind_info, 42);
} else {
abort();
}
}
struct MemoryManager : llvm::RuntimeDyld::MemoryManager {
public:
MemoryManager(callbacks_t callbacks) : callbacks(callbacks) {}

View File

@ -3,6 +3,8 @@
#include <exception>
#include <iostream>
#include <sstream>
#include <setjmp.h>
#include <functional>
#include <llvm/ExecutionEngine/RuntimeDyld.h>
@ -48,7 +50,10 @@ typedef struct {
size_t data, vtable;
} box_any_t;
struct WasmException {
void catch_unwind(std::function<void()>&& f);
[[noreturn]] void unsafe_unwind(std::exception *exception);
struct WasmException : std::exception {
public:
virtual std::string description() const noexcept = 0;
};
@ -174,27 +179,29 @@ result_t module_load(const uint8_t *mem_ptr, size_t mem_size,
return RESULT_OK;
}
[[noreturn]] void throw_trap(WasmTrap::Type ty) { throw WasmTrap(ty); }
[[noreturn]] void throw_trap(WasmTrap::Type ty) { unsafe_unwind(new WasmTrap(ty)); }
void module_delete(WasmModule *module) { delete module; }
// Throw a fat pointer that's assumed to be `*mut dyn Any` on the rust
// side.
[[noreturn]] void throw_any(size_t data, size_t vtable) {
throw UserException(data, vtable);
unsafe_unwind(new UserException(data, vtable));
}
// Throw a pointer that's assumed to be codegen::BreakpointHandler on the
// rust side.
[[noreturn]] void throw_breakpoint(uintptr_t callback) {
throw BreakpointException(callback);
unsafe_unwind(new BreakpointException(callback));
}
bool invoke_trampoline(trampoline_t trampoline, void *ctx, void *func,
void *params, void *results, WasmTrap::Type *trap_out,
box_any_t *user_error, void *invoke_env) noexcept {
try {
trampoline(ctx, func, params, results);
catch_unwind([trampoline, ctx, func, params, results]() {
trampoline(ctx, func, params, results);
});
return true;
} catch (const WasmTrap &e) {
*trap_out = e.type;