wasm3

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2020 License: MIT Imports: 6 Imported by: 2

README

go-wasm3

GoDoc

Golang wrapper for WASM3, WIP.

This is part of a series of WASM-related experiments: go-wavm and go-wasm-benchmark.

About this fork

This is a fork of go-wasm3 by matiasinsaurralde starting from another fork.

Changes
  • Add android static libraries to allow building in gomobile
  • Add Runtime.ResizeMemory()
  • Add Module.LinkRawFunction()
  • Remove Function.CallWithArgs()
  • Allow any compatible input/output type in Function.Call()

Build example for Android:

set -ex

mkdir -p /tmp/gomobile
docker run -it \
    --mount type=bind,source=$HOME/git,target=/root/git,readonly \
    --mount type=bind,source=/tmp/gomobile,target=/tmp/gomobile \
    ed255/gomobile-android:latest \
    /bin/bash -c 'set -ex && \
        apt-get update && \
        apt-get install -y cmake && \
        rm -r /tmp/gomobile/git || true && \
        mkdir -p /tmp/gomobile/git && \
        cp -r /root/git/go-wasm3 /tmp/gomobile/git && \
        cp -r /root/git/wasm3 /tmp/gomobile/git && \
        cd /tmp/gomobile/git/wasm3 && \
        cd android && \
        rm -r build || true && \
        mkdir build && \
        cd build && \
        NDK_HOME=/opt/android-ndk/android-ndk-r20 ../make_all.sh && \
        cp -r android /tmp/gomobile/git/go-wasm3/lib/
        cd /tmp/gomobile/git/go-wasm3 && \
        go build && \
        gomobile bind -androidapi=16 --target android -o /tmp/gomobile/wasm.aar'
    # /bin/bash

Install/build

This package ships with pre-built WASM3 libraries (static builds) for Linux and Android. If you want to hack around it, check the original repository.

Check the building instructions for Android if you want to rebuild the static libraries.

If you're using one of the mentioned platforms, you may install the package using go get:

$ go get -u github.com/iden3/go-wasm3

To inspect or run the little sample use:

$ cd go-wasm3/examples/sum
$ go build # or "go run sum.go"
$ ./sum

The output will look as follows:

2020/01/15 09:51:24 Initializing WASM3
2020/01/15 09:51:24 Runtime ok
2020/01/15 09:51:24 Read WASM module (139 bytes)
2020/01/15 09:51:24 Module loaded
2020/01/15 09:51:24 Calling function
Result: 3
Result: 4

You will find additional sample projects in the next section.

Sample projects

boa

This program uses the boa engine to evaluate JS code. Boa is an embeddable JS engine written in Rust, for this sample it was compiled targeting WASM.

Link here.

libxml

This program loads libxml2 as a WASM module (it's a custom build, full instructions here). The library is used to validate a XML file against a XSD (both loaded from the Go side).

Link here.

Memory access

Take the following sample program:

#include <stdlib.h>
#include <string.h>

char* somecall() {
    // Allocate a few bytes on the heap:
    char* test = (char*) malloc(12*sizeof(char));

    // Copy a string into the previously defined address:
    strcpy(test, "testingonly");

    // Return the pointer:
    return test;
}

Build it using wasicc, this will generate a cstring.wasm file (WASM module):

wasicc cstring.c -Wl,--export-all -o cstring.wasm

The following Go code will load the WASM module and retrieve the data after calling somecall:

    // Initialize the runtime and load the module:
    env := wasm3.NewEnvironment()
	defer env.Destroy()
	runtime := wasm3.NewRuntime(env, 64*1024)
	defer runtime.Destroy()
    wasmBytes, err := ioutil.ReadFile("program.wasm")
	module, _ := env.ParseModule(wasmBytes)
	runtime.LoadModule(module)
    fn, _ := runtime.FindFunction(fnName)

    // Call somecall and get the pointer to our data:
    result := fn()
    
    // Reconstruct the string from memory:
    memoryLength = runtime.GetAllocatedMemoryLength()
    mem := runtime.GetMemory(memoryLength, 0)
    
    // Initialize a Go buffer:
	buf := new(bytes.Buffer)
	for n := 0; n < memoryLength; n++ {
		if n < result {
			continue
		}
		value := mem[n]
		if value == 0 {
			break
        }
		buf.WriteByte(value)
    }

    // Print the string: "testingonly"
    str := buf.String()
    fmt.Println(str)

For more details check this.

Limitations and future

This is a WIP. Stay tuned!

A Rust wrapper is available here.

License

MIT.

wasm3 is also under this license.

Documentation

Index

Constants

View Source
const (
	PageSize uint32 = 0x10000
)

Variables

This section is empty.

Functions

func LastErrorString

func LastErrorString() string

LastErrorString returns the last runtime error

Types

type CallbackFunction

type CallbackFunction func(runtime RuntimeT, sp unsafe.Pointer, mem unsafe.Pointer) int

CallbackFunction is the signature for callbacks

type Config

type Config struct {
	Environment *Environment
	StackSize   uint
	// EnableWASI     bool
	EnableSpecTest bool
}

Config holds the runtime and environment configuration

type Environment

type Environment struct {
	// contains filtered or unexported fields
}

Environment wraps a WASM3 environment

func NewEnvironment

func NewEnvironment() *Environment

NewEnvironment initializes a new environment

func (*Environment) Destroy

func (e *Environment) Destroy()

Destroy calls m3_FreeEnvironment

func (*Environment) ParseModule

func (e *Environment) ParseModule(wasmBytes []byte) (*Module, error)

ParseModule wraps m3_ParseModule

func (*Environment) Ptr

func (e *Environment) Ptr() C.IM3Environment

Ptr returns a pointer to IM3Environment

type EnvironmentT

type EnvironmentT C.IM3Environment

EnvironmentT is an alias for IM3Environment

type FuncTypeT

type FuncTypeT C.IM3FuncType

FuncTypeT is an alias for IM3FuncType

type Function

type Function struct {

	// fnWrapper FunctionWrapper
	Name string
	// contains filtered or unexported fields
}

Function is a function wrapper

func (*Function) Call

func (f *Function) Call(args ...interface{}) (interface{}, error)

Call implements a better call function

func (*Function) GetArgType

func (f *Function) GetArgType(index int) uint8

func (*Function) GetImportField

func (f *Function) GetImportField() *string

func (*Function) GetImportModule

func (f *Function) GetImportModule() *string

func (*Function) GetModule

func (f *Function) GetModule() *Module

GetModule retreive the function's module

func (*Function) GetNumArgs

func (f *Function) GetNumArgs() uint32

func (*Function) GetReturnType

func (f *Function) GetReturnType() uint8

func (*Function) GetSignature

func (f *Function) GetSignature() string

func (*Function) Ptr

func (f *Function) Ptr() C.IM3Function

Ptr returns a pointer to IM3Function

type FunctionT

type FunctionT C.IM3Function

FunctionT is an alias for IM3Function

type FunctionWrapper

type FunctionWrapper func(args ...interface{}) (interface{}, error)

FunctionWrapper is used to wrap WASM3 call methods and make the calls more idiomatic

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module wraps a WASM3 module.

func NewModule

func NewModule(ptr ModuleT) *Module

NewModule wraps a WASM3 moduke

func (*Module) FunctionNames

func (m *Module) FunctionNames() []string

func (*Module) GetFunction

func (m *Module) GetFunction(index uint) (*Function, error)

GetFunction provides access to IM3Function->functions

func (*Module) GetFunctionByName

func (m *Module) GetFunctionByName(lookupName string) (*Function, error)

GetFunctionByName is a helper to lookup functions by name TODO: could be optimized by caching function names and pointer on the Go side, right after the load call.

func (*Module) LinkRawFunction

func (m *Module) LinkRawFunction(moduleName, functionName, signature string, fn unsafe.Pointer) error

TODO: Store the CStrings to later free them!

func (*Module) Name

func (m *Module) Name() string

Name gets the module's name

func (*Module) NumFunctions

func (m *Module) NumFunctions() int

NumFunctions provides access to numFunctions.

func (*Module) NumImports

func (m *Module) NumImports() int

NumImports provides access to numImports

func (*Module) Ptr

func (m *Module) Ptr() C.IM3Module

Ptr returns a pointer to IM3Module

type ModuleT

type ModuleT C.IM3Module

ModuleT is an alias for IM3Module

type ResultT

type ResultT C.M3Result

ResultT is an alias for M3Result

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime wraps a WASM3 runtime

func NewRuntime

func NewRuntime(cfg *Config) *Runtime

NewRuntime initializes a new runtime TODO: nativeStackInfo is passed as NULL

func (*Runtime) AttachFunction

func (r *Runtime) AttachFunction(moduleName string, functionName string, signature string, callback CallbackFunction)

AttachFunction binds a callable function to a module+func

func (*Runtime) Destroy

func (r *Runtime) Destroy()

Destroy free calls m3_FreeRuntime

func (*Runtime) FindFunction

func (r *Runtime) FindFunction(funcName string) (FunctionWrapper, error)

FindFunction calls m3_FindFunction and returns a call function

func (*Runtime) FindFunctionByModule

func (r *Runtime) FindFunctionByModule(moduleName string, funcName string) (FunctionWrapper, error)

FindFunction does thins

func (*Runtime) GetAllocatedMemoryLength

func (r *Runtime) GetAllocatedMemoryLength() int

GetAllocatedMemoryLength returns the amount of allocated runtime memory

func (*Runtime) Load

func (r *Runtime) Load(wasmBytes []byte) (*Module, error)

Load wraps the parse and load module calls. This will be replaced by env.ParseModule and Runtime.LoadModule.

func (*Runtime) LoadModule

func (r *Runtime) LoadModule(module *Module) (*Module, error)

LoadModule wraps m3_LoadModule and returns a module object

func (*Runtime) Memory

func (r *Runtime) Memory() []byte

Memory allows access to runtime Memory. Taken from Wasmer extension: https://github.com/wasmerio/go-ext-wasm

func (*Runtime) ParseModule

func (r *Runtime) ParseModule(wasmBytes []byte) (*Module, error)

ParseModule is a helper that calls the same function in env.

func (*Runtime) PrintRuntimeInfo

func (r *Runtime) PrintRuntimeInfo()

func (*Runtime) Ptr

func (r *Runtime) Ptr() C.IM3Runtime

Ptr returns a IM3Runtime pointer

func (*Runtime) ResizeMemory

func (r *Runtime) ResizeMemory(numPages int32) error

type RuntimeT

type RuntimeT C.IM3Runtime

RuntimeT is an alias for IM3Runtime

type WasiIoVec

type WasiIoVec C.wasi_iovec_t

WasiIoVec is an alias for wasi_iovec_t

func (*WasiIoVec) GetBuf

func (w *WasiIoVec) GetBuf() uint32

GetBuf return the internal buffer index

func (*WasiIoVec) GetBufLen

func (w *WasiIoVec) GetBufLen() int

GetBufLen return the buffer len

Directories

Path Synopsis
examples
boa
sum

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL