Add implementations for typed func errors to cranelift and llvm

This commit is contained in:
Lachlan Sneff
2019-04-09 15:53:01 -07:00
committed by Syrus
parent 7d09a2ee7e
commit cc656b26a9
9 changed files with 261 additions and 151 deletions

View File

@ -5,14 +5,16 @@
#include <sstream>
#include <exception>
typedef enum {
typedef enum
{
PROTECT_NONE,
PROTECT_READ,
PROTECT_READ_WRITE,
PROTECT_READ_EXECUTE,
} mem_protect_t;
typedef enum {
typedef enum
{
RESULT_OK,
RESULT_ALLOCATE_FAILURE,
RESULT_PROTECT_FAILURE,
@ -20,16 +22,17 @@ typedef enum {
RESULT_OBJECT_LOAD_FAILURE,
} result_t;
typedef result_t (*alloc_memory_t)(size_t size, mem_protect_t protect, uint8_t** ptr_out, size_t* size_out);
typedef result_t (*protect_memory_t)(uint8_t* ptr, size_t size, mem_protect_t protect);
typedef result_t (*dealloc_memory_t)(uint8_t* ptr, size_t size);
typedef uintptr_t (*lookup_vm_symbol_t)(const char* name_ptr, size_t length);
typedef result_t (*alloc_memory_t)(size_t size, mem_protect_t protect, uint8_t **ptr_out, size_t *size_out);
typedef result_t (*protect_memory_t)(uint8_t *ptr, size_t size, mem_protect_t protect);
typedef result_t (*dealloc_memory_t)(uint8_t *ptr, size_t size);
typedef uintptr_t (*lookup_vm_symbol_t)(const char *name_ptr, size_t length);
typedef void (*fde_visitor_t)(uint8_t *fde);
typedef result_t (*visit_fde_t)(uint8_t *fde, size_t size, fde_visitor_t visitor);
typedef void (*trampoline_t)(void*, void*, void*, void*);
typedef void (*trampoline_t)(void *, void *, void *, void *);
typedef struct {
typedef struct
{
/* Memory management. */
alloc_memory_t alloc_memory;
protect_memory_t protect_memory;
@ -40,32 +43,40 @@ typedef struct {
visit_fde_t visit_fde;
} callbacks_t;
struct WasmException {
public:
struct WasmException
{
public:
virtual std::string description() const noexcept = 0;
};
struct UncatchableException : WasmException {
public:
virtual std::string description() const noexcept override {
struct UncatchableException : WasmException
{
public:
virtual std::string description() const noexcept override
{
return "Uncatchable exception";
}
};
struct UserException : UncatchableException {
public:
struct UserException : UncatchableException
{
public:
UserException(std::string msg) : msg(msg) {}
virtual std::string description() const noexcept override {
virtual std::string description() const noexcept override
{
return std::string("user exception: ") + msg;
}
private:
private:
std::string msg;
};
struct WasmTrap : UncatchableException {
public:
enum Type {
struct WasmTrap : UncatchableException
{
public:
enum Type
{
Unreachable = 0,
IncorrectCallIndirectSignature = 1,
MemoryOutOfBounds = 2,
@ -76,49 +87,54 @@ public:
WasmTrap(Type type) : type(type) {}
virtual std::string description() const noexcept override {
virtual std::string description() const noexcept override
{
std::ostringstream ss;
ss
<< "WebAssembly trap:" << '\n'
<< " - type: " << type << '\n';
return ss.str();
}
Type type;
private:
friend std::ostream& operator<<(std::ostream& out, const Type& ty) {
switch (ty) {
case Type::Unreachable:
out << "unreachable";
break;
case Type::IncorrectCallIndirectSignature:
out << "incorrect call_indirect signature";
break;
case Type::MemoryOutOfBounds:
out << "memory access out-of-bounds";
break;
case Type::CallIndirectOOB:
out << "call_indirect out-of-bounds";
break;
case Type::IllegalArithmetic:
out << "illegal arithmetic operation";
break;
case Type::Unknown:
default:
out << "unknown";
break;
private:
friend std::ostream &operator<<(std::ostream &out, const Type &ty)
{
switch (ty)
{
case Type::Unreachable:
out << "unreachable";
break;
case Type::IncorrectCallIndirectSignature:
out << "incorrect call_indirect signature";
break;
case Type::MemoryOutOfBounds:
out << "memory access out-of-bounds";
break;
case Type::CallIndirectOOB:
out << "call_indirect out-of-bounds";
break;
case Type::IllegalArithmetic:
out << "illegal arithmetic operation";
break;
case Type::Unknown:
default:
out << "unknown";
break;
}
return out;
}
};
struct CatchableException : WasmException {
public:
struct CatchableException : WasmException
{
public:
CatchableException(uint32_t type_id, uint32_t value_num) : type_id(type_id), value_num(value_num) {}
virtual std::string description() const noexcept override {
virtual std::string description() const noexcept override
{
return "catchable exception";
}
@ -126,23 +142,26 @@ public:
uint64_t values[1];
};
struct WasmModule {
public:
struct WasmModule
{
public:
WasmModule(
const uint8_t *object_start,
size_t object_size,
callbacks_t callbacks
);
callbacks_t callbacks);
void *get_func(llvm::StringRef name) const;
private:
private:
std::unique_ptr<llvm::RuntimeDyld::MemoryManager> memory_manager;
std::unique_ptr<llvm::object::ObjectFile> object_file;
std::unique_ptr<llvm::RuntimeDyld> runtime_dyld;
};
extern "C" {
result_t module_load(const uint8_t* mem_ptr, size_t mem_size, callbacks_t callbacks, WasmModule** module_out) {
extern "C"
{
result_t module_load(const uint8_t *mem_ptr, size_t mem_size, callbacks_t callbacks, WasmModule **module_out)
{
*module_out = new WasmModule(mem_ptr, mem_size, callbacks);
return RESULT_OK;
@ -152,34 +171,44 @@ extern "C" {
throw WasmTrap(ty);
}
void module_delete(WasmModule* module) {
void module_delete(WasmModule *module)
{
delete module;
}
bool invoke_trampoline(
trampoline_t trampoline,
void* ctx,
void* func,
void* params,
void* results,
WasmTrap::Type* trap_out
) throw() {
try {
void *ctx,
void *func,
void *params,
void *results,
WasmTrap::Type *trap_out,
void *invoke_env) throw()
{
try
{
trampoline(ctx, func, params, results);
return true;
} catch(const WasmTrap& e) {
}
catch (const WasmTrap &e)
{
*trap_out = e.type;
return false;
} catch(const WasmException& e) {
}
catch (const WasmException &e)
{
*trap_out = WasmTrap::Type::Unknown;
return false;
} catch (...) {
}
catch (...)
{
*trap_out = WasmTrap::Type::Unknown;
return false;
}
}
void* get_func_symbol(WasmModule* module, const char* name) {
void *get_func_symbol(WasmModule *module, const char *name)
{
return module->get_func(llvm::StringRef(name));
}
}

View File

@ -11,7 +11,7 @@ use libc::{
};
use std::{
any::Any,
ffi::CString,
ffi::{c_void, CString},
mem,
ptr::{self, NonNull},
slice, str,
@ -23,6 +23,7 @@ use wasmer_runtime_core::{
export::Context,
module::{ModuleInfo, ModuleInner},
structures::TypedIndex,
typed_func::{Wasm, WasmTrapInfo},
types::{FuncIndex, FuncSig, LocalFuncIndex, LocalOrImport, SigIndex, Type, Value},
vm::{self, ImportBacking},
vmcalls,
@ -54,17 +55,6 @@ enum LLVMResult {
OBJECT_LOAD_FAILURE,
}
#[allow(dead_code)]
#[repr(C)]
enum WasmTrapType {
Unreachable = 0,
IncorrectCallIndirectSignature = 1,
MemoryOutOfBounds = 2,
CallIndirectOOB = 3,
IllegalArithmetic = 4,
Unknown,
}
#[repr(C)]
struct Callbacks {
alloc_memory: extern "C" fn(usize, MemProtect, &mut *mut u8, &mut usize) -> LLVMResult,
@ -87,13 +77,15 @@ extern "C" {
fn throw_trap(ty: i32);
#[allow(improper_ctypes)]
fn invoke_trampoline(
trampoline: unsafe extern "C" fn(*mut vm::Ctx, *const vm::Func, *const u64, *mut u64),
trampoline: unsafe extern "C" fn(*mut vm::Ctx, NonNull<vm::Func>, *const u64, *mut u64),
vmctx_ptr: *mut vm::Ctx,
func_ptr: *const vm::Func,
func_ptr: NonNull<vm::Func>,
params: *const u64,
results: *mut u64,
trap_out: *mut WasmTrapType,
trap_out: *mut WasmTrapInfo,
invoke_env: Option<NonNull<c_void>>,
) -> bool;
}
@ -360,7 +352,12 @@ impl ProtectedCaller for LLVMProtectedCaller {
let mut return_vec = vec![0; signature.returns().len()];
let trampoline: unsafe extern "C" fn(*mut vm::Ctx, *const vm::Func, *const u64, *mut u64) = unsafe {
let trampoline: unsafe extern "C" fn(
*mut vm::Ctx,
NonNull<vm::Func>,
*const u64,
*mut u64,
) = unsafe {
let name = if cfg!(target_os = "macos") {
format!("_trmp{}", sig_index.index())
} else {
@ -374,7 +371,7 @@ impl ProtectedCaller for LLVMProtectedCaller {
mem::transmute(symbol)
};
let mut trap_out = WasmTrapType::Unknown;
let mut trap_out = WasmTrapInfo::Unknown;
// Here we go.
let success = unsafe {
@ -385,6 +382,7 @@ impl ProtectedCaller for LLVMProtectedCaller {
param_vec.as_ptr(),
return_vec.as_mut_ptr(),
&mut trap_out,
None,
)
};
@ -400,29 +398,35 @@ impl ProtectedCaller for LLVMProtectedCaller {
})
.collect())
} else {
Err(match trap_out {
WasmTrapType::Unreachable => RuntimeError::Trap {
msg: "unreachable".into(),
},
WasmTrapType::IncorrectCallIndirectSignature => RuntimeError::Trap {
msg: "uncorrect call_indirect signature".into(),
},
WasmTrapType::MemoryOutOfBounds => RuntimeError::Trap {
msg: "memory out-of-bounds access".into(),
},
WasmTrapType::CallIndirectOOB => RuntimeError::Trap {
msg: "call_indirect out-of-bounds".into(),
},
WasmTrapType::IllegalArithmetic => RuntimeError::Trap {
msg: "illegal arithmetic operation".into(),
},
WasmTrapType::Unknown => RuntimeError::Trap {
msg: "unknown trap".into(),
},
Err(RuntimeError::Trap {
msg: trap_out.to_string().into(),
})
}
}
fn get_wasm_trampoline(&self, _module: &ModuleInner, sig_index: SigIndex) -> Option<Wasm> {
let trampoline: unsafe extern "C" fn(
*mut vm::Ctx,
NonNull<vm::Func>,
*const u64,
*mut u64,
) = unsafe {
let name = if cfg!(target_os = "macos") {
format!("_trmp{}", sig_index.index())
} else {
format!("trmp{}", sig_index.index())
};
let c_str = CString::new(name).unwrap();
let symbol = get_func_symbol(self.module, c_str.as_ptr());
assert!(!symbol.is_null());
mem::transmute(symbol)
};
Some(unsafe { Wasm::from_raw_parts(trampoline, invoke_trampoline, None) })
}
fn get_early_trapper(&self) -> Box<dyn UserTrapper> {
Box::new(Placeholder)
}
@ -438,7 +442,7 @@ fn get_func_from_index<'a>(
module: &'a ModuleInner,
import_backing: &ImportBacking,
func_index: FuncIndex,
) -> (*const vm::Func, Context, &'a FuncSig, SigIndex) {
) -> (NonNull<vm::Func>, Context, &'a FuncSig, SigIndex) {
let sig_index = *module
.info
.func_assoc
@ -451,14 +455,13 @@ fn get_func_from_index<'a>(
.func_resolver
.get(&module, local_func_index)
.expect("broken invariant, func resolver not synced with module.exports")
.cast()
.as_ptr() as *const _,
.cast(),
Context::Internal,
),
LocalOrImport::Import(imported_func_index) => {
let imported_func = import_backing.imported_func(imported_func_index);
(
imported_func.func as *const _,
NonNull::new(imported_func.func as *mut _).unwrap(),
Context::External(imported_func.vmctx),
)
}