github.com/moontrade/wavm-go@v0.3.2-0.20220316110326-d229dd66ad65/trap.go (about) 1 package wavm 2 3 // #include <stdlib.h> 4 // #include "wavm-c.h" 5 import "C" 6 import "unsafe" 7 8 type ( 9 Trap C.wasm_trap_t 10 11 /* 12 typedef struct wasm_frame_t 13 { 14 wasm_func_t* function; 15 size_t instr_index; 16 } wasm_frame_t; 17 */ 18 Frame struct { 19 Function *Func 20 InstrIndex C.size_t 21 } 22 ) 23 24 func NewTrap(compartment *Compartment, message string) *Trap { 25 msgbytes := []byte(message) 26 return (*Trap)(C.wasm_trap_new( 27 (*C.wasm_compartment_t)(compartment), 28 (*C.char)(unsafe.Pointer(&msgbytes[0])), 29 (C.size_t)(len(msgbytes)))) 30 } 31 32 func (t *Trap) Close() error { 33 t.Delete() 34 return nil 35 } 36 37 func (t *Trap) Delete() { 38 C.wasm_trap_delete((*C.wasm_trap_t)(t)) 39 } 40 41 func (t *Trap) String() string { 42 return string(t.Message(make([]byte, 1024))) 43 } 44 45 func (t *Trap) Error() string { 46 return t.String() 47 } 48 49 func (t *Trap) Message(b []byte) []byte { 50 if b == nil { 51 b = make([]byte, 1024) 52 } 53 size := C.size_t(len(b)) 54 C.wasm_trap_message((*C.wasm_trap_t)(t), (*C.char)(unsafe.Pointer(&b[0])), &size) 55 if int(size) > len(b) { 56 b = make([]byte, int(size)) 57 C.wasm_trap_message((*C.wasm_trap_t)(t), (*C.char)(unsafe.Pointer(&b[0])), &size) 58 } 59 return b[0:int(size)] 60 } 61 62 func (t *Trap) StackNumFrames() int { 63 return int(C.wasm_trap_stack_num_frames((*C.wasm_trap_t)(t))) 64 } 65 66 func (t *Trap) StackFrame(index int, outFrame *Frame) { 67 C.wasm_trap_stack_frame((*C.wasm_trap_t)(t), (C.size_t)(index), (*C.wasm_frame_t)(unsafe.Pointer(outFrame))) 68 }