Code Monkey home page Code Monkey logo

go-ext-wasm's Introduction


A complete and mature WebAssembly runtime for Go based on Wasmer.

You are seeing the readme for the latest Wasmer Go version, if you are using an older version, please go to:

Features

  • Easy to use: The wasmer API mimics the standard WebAssembly API,
  • Fast: wasmer executes the WebAssembly modules as fast as possible, close to native speed,
  • Safe: All calls to WebAssembly will be fast, but more importantly, completely safe and sandboxed.

Install

To install the library, follow the classical:

$ go get github.com/wasmerio/wasmer-go/wasmer

Note: Wasmer doesn't work on Windows yet.

If the pre-compiled shared libraries are not compatible with your system, please wait, we are writing the documentation.

Examples

Basic example: Exported function

There is a toy program in wasmer/testdata/tests.rs, written in Rust (or any other language that compiles to WebAssembly), which contains a function like this one:

#[no_mangle]
pub extern fn sum(x: i32, y: i32) -> i32 {
    x + y
}

After compilation to WebAssembly, the wasmer/testdata/tests.wasm binary file is generated. (Download it).

Then, we can execute it in Go:

package main

import (
	"fmt"
    "io/ioutil"
	wasmer "github.com/wasmerio/wasmer-go/wasmer"
)

func main() {
    wasmBytes, _ := ioutil.ReadFile("path/to/tests.wasm")

    engine := wasmer.NewEngine()
    store := wasmer.NewStore(engine)

    // Compiles the module
    module, _ := wasmer.NewModule(store, wasmBytes)

    // Instantiates the module
    importObject := wasmer.NewImportObject()
    instance, _ := wasmer.NewInstance(module, importObject)

    // Gets the `sum` exported function from the WebAssembly instance.
    sum, _ := instance.Exports.GetFunction("sum")

    // Calls that exported function with Go standard values. The WebAssembly
    // types are inferred and values are casted automatically.
    result, _ := sum(5, 37)

    fmt.Println(result) // 42!
}

Imported function

A WebAssembly module can export functions, this is how to run a WebAssembly function, like we did in the previous example. Nonetheless, a WebAssembly module can depend on “extern functions”, then called imported functions. For instance, let's consider the basic following Rust program:

extern {
    fn sum(x: i32, y: i32) -> i32;
}

#[no_mangle]
pub extern fn add1(x: i32, y: i32) -> i32 {
    unsafe { sum(x, y) + 1 }
}

In this case, the add1 function is a WebAssembly exported function, whilst the sum function is a WebAssembly imported function (the WebAssembly instance needs to import it to complete the program). Good news: We can write the implementation of the sum function directly in Go! Let's declare the complete host function:

function := wasmer.NewFunction(
	store,
	wasmer.NewFunctionType(wasmer.NewValueTypes(I32, I32), wasmer.NewValueTypes(I32)),
	func(args []wasmer.Value) ([]wasmer.Value, error) {
		x := args[0].I32()
		y := args[1].I32()

		return []wasmer.Value{wasmer.NewI32(x + y)}, nil
	},
)

Then, we need to define an ImportObject and register the funtion inside the correct namespace:

importObject.Register(
	"math",
	map[string]IntoExtern{
		"sum": function,
	},
)

Here we are. Now let's instantiate the module with the import object, and let's call the add_one function:

instance, _ := wasmer.NewInstance(module, importObject)

addOne, _ := instance.Exports.GetFunction("add_one")

result, _ := addOne(41)
fmt.Println(result) # 42!

Read the memory

A WebAssembly instance has a linear memory. Let's see how to read it. Consider the following Rust program:

#[no_mangle]
pub extern fn return_hello() -> *const u8 {
    b"Hello, World!\0".as_ptr()
}

The return_hello function returns a pointer to a string. This string is stored in the WebAssembly memory. Let's read it.

wasmBytes, _ := wasm.ReadBytes("simple.wasm")

engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)

// Compiles the module
module, _ := wasmer.NewModule(store, wasmBytes)

// Instantiates the module
importObject := wasmer.NewImportObject()
instance, _ := wasmer.NewInstance(module, importObject)

// Calls the `return_hello` exported function.
// This function returns a pointer to a string.
result, _ := instance.GetFunction("return_hello")

// Gets the pointer value as an integer.
pointer := result.ToI32()

// Reads the memory.
memory := instance.exports.GetMemory("memory").Data()

fmt.Println(string(memory[pointer : pointer+13])) // Hello, World!

In this example, we already know the string length, and we use a slice to read a portion of the memory directly. Notice that the string terminates by a null byte, which means we could iterate over the memory starting from pointer until a null byte is met; that's a similar approach.

Documentation

The documentation can be read online on pkg.go.dev. It contains function descriptions, short examples, long examples etc. Everything one need to start using Wasmer with Go!

Testing

Once the library is build, run the following command:

$ just test

Benchmarks

We compared Wasmer to Wagon and Life. The benchmarks are in benchmarks/. The computer that ran these benchmarks is a MacBook Pro 15" from 2016, 2.9Ghz Core i7 with 16Gb of memory. Here are the results in a table (the lower the ratio is, the better):

Benchmark Runtime Time (ms) Ratio
N-Body Wasmer 42.078
Wagon 1841.950 44×
Life 1976.215 47×
Fibonacci (recursive) Wasmer 28.559
Wagon 3238.050 113×
Life 3029.209 106×
Pollard rho 128 Wasmer 37.478
Wagon 2165.563 58×
Life 2407.752 64×

While both Life and Wagon provide on average the same speed, Wasmer is on average 72 times faster.

Put on a graph, it looks like this (reminder: the lower, the better):

Benchmark results

What is WebAssembly?

Quoting the WebAssembly site:

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

About speed:

WebAssembly aims to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms.

About safety:

WebAssembly describes a memory-safe, sandboxed execution environment […].

License

The entire project is under the MIT License. Please read the LICENSE file.

go-ext-wasm's People

Contributors

adamslevy avatar antjack avatar bors[bot] avatar chai2010 avatar cvermilion avatar d0iasm avatar dependabot[bot] avatar diegobes avatar ethanfrey avatar etiennebruines avatar hywan avatar joesonw avatar jubianchi avatar koponen-styra avatar syrusakbary avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.