From 5e11202e3b381f8f19b55e96ef19d79709fdf4d5 Mon Sep 17 00:00:00 2001 From: Ivan Enderlin Date: Fri, 18 Sep 2020 14:49:39 +0200 Subject: [PATCH] feat: Ability to give WAT to `NewModule`. --- wasmer/module.go | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/wasmer/module.go b/wasmer/module.go index 97eafbbe..f190f882 100644 --- a/wasmer/module.go +++ b/wasmer/module.go @@ -1,16 +1,17 @@ package wasmer // #include +// #include // // // We can't create a `wasm_byte_vec_t` directly in Go otherwise cgo // // complains with “Go pointer to Go pointer”. The hack consists at // // creating the `wasm_byte_vec_t` directly in C. -// own wasm_module_t* go_wasm_module_new(wasm_store_t *store, uint8_t *bytes, size_t bytes_length) { +// own wasm_module_t* to_wasm_module_new(wasm_store_t *store, uint8_t *bytes, size_t bytes_length) { // wasm_byte_vec_t wasm_bytes; // wasm_bytes.size = bytes_length; // wasm_bytes.data = (wasm_byte_t*) bytes; // -// return wasm_module_new(store, &wasm_bytes); +// return wasm_module_new(store, &wasm_bytes); // } import "C" import ( @@ -18,8 +19,8 @@ import ( "unsafe" ) -// A WebAssembly module contains stateless WebAssembly code that has -// already been compiled and can be instantiated multiple times. +// Module contains stateless WebAssembly code that has already been +// compiled and can be instantiated multiple times. // // Creates a new WebAssembly Module given the configuration // in the store. @@ -37,25 +38,36 @@ type Module struct { } func NewModule(store *Store, bytes []byte) (*Module, error) { - var bytesPtr *C.uint8_t + // If `bytes` contains a Wasm module with the WAT format, + // compile it to Wasm bytes. + // If it does not, it will return the same bytes. + wasmBytes, err := Wat2Wasm(string(bytes)) - if len(bytes) > 0 { - bytesPtr = (*C.uint8_t)(unsafe.Pointer(&bytes[0])) + if err != nil { + return nil, err + } + + var wasmBytesPtr *C.uint8_t + wasmBytesLength := len(wasmBytes) + + if wasmBytesLength > 0 { + wasmBytesPtr = (*C.uint8_t)(unsafe.Pointer(&wasmBytes[0])) } module := &Module{ - _inner: C.go_wasm_module_new(store.inner(), bytesPtr, C.size_t(len(bytes))), + _inner: C.to_wasm_module_new(store.inner(), wasmBytesPtr, C.size_t(wasmBytesLength)), + } + + if module._inner == nil { + return nil, newErrorFromWasmer() } runtime.KeepAlive(bytes) + runtime.KeepAlive(wasmBytes) runtime.SetFinalizer(module, func(module *Module) { C.wasm_module_delete(module.inner()) }) - if module == nil { - return nil, newError() - } - return module, nil }