Giter Site home page Giter Site logo

wasmedge-core's Introduction

WasmEdge for Node.js Addon

The WasmEdge (previously known as Second State VM, SSVM) is a high-performance WebAssembly runtime optimized for server-side applications. This project provides support for accessing WasmEdge as a Node.js addon. It allows Node.js applications to call WebAssembly functions written in Rust or other high-performance languages. Why do you want to run WebAssembly on the server-side? The WasmEdge addon could interact with the wasm files generated by the rustwasmc compiler tool.

NOTICE

In the current stage, our prebuilt version only supports x86_64 and aarch64 Linux. Or you could use --build-from-source flag to build from the source during addon installation.

WasmEdge versions

There are mappings of wasmedge-core versoins and corresponding WasmEdge versions:

wasmedge-core WasmEdge
0.8.1 0.8.1
0.8.2-rc.1 0.8.1
0.8.2 0.8.2
0.8.3 0.8.2
0.9.0-rc.1 0.9.0-rc.1
0.9.0 0.9.0

Development Requirements

Users should install the dependencies by the following requirments:

  • boost >= 1.65.0
  • llvm >= 10
  • liblld-10-dev >= 10
  • libstdc++6 >= 6.0.28 (GLIBCXX >= 3.4.28)
  • g++ version >= 9.0 (Optional, if you have to build from source)

Prepare the environment

docker pull wasmedge/wasmedge

For ubuntu 20.04

# Tools and libraries
sudo apt install -y \
	software-properties-common \
	cmake \
	libboost-all-dev

# And you will need to install llvm for wasmedge-aot tools
sudo apt install -y \
	llvm-dev \
	liblld-10-dev

# WasmEdge supports both clang++ and g++ compilers
# You can choose one of them for building this project
sudo apt install -y gcc g++
sudo apt install -y clang

Verify the version of llvm

sudo apt list | grep llvm

# Expected output
...omitted...
llvm-dev/focal,now 1:10.0-50~exp1 amd64 [installed]
llvm-runtime/focal,now 1:10.0-50~exp1 amd64 [installed,automatic]
llvm/focal,now 1:10.0-50~exp1 amd64 [installed,automatic]
...omitted...

# If the version is 1:10.x, then your llvm version is correct.

Verify the version of libstdc++6

strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIBCXX

# Expected output
...omitted...
GLIBCXX_3.4.24
GLIBCXX_3.4.25
GLIBCXX_3.4.26
GLIBCXX_3.4.27
GLIBCXX_3.4.28
GLIBCXX_DEBUG_MESSAGE_LENGTH

# If you can find GLIBCXX_3.4.28 in the output, then your libstdc++6 version is correct.

Running on MacOS Darwin

To run on MacOS you will need to build from source by following the steps mentioned below,

  • Install WasmEdge library using the installation script
  • Install all the necessary packages
  • Clone the wasmedge-core project to your local environment
  • Run npm install

Works with Rust library using Wasm-Bindgen

Please refer to Tutorial: A Wasm-Bindgen application.

Works with Rust application using standalone wasm32-wasi backend

Please refer to Tutorial: A standalone wasm32-wasi application.

APIs

Constructor: wasmedge.VM(wasm, wasmedge_options) -> vm_instance

  • Create a WasmEdge instance by given wasm file and options.
  • Arguments:
    • wasm: Input wasm file, can be the following three formats:
      1. Wasm file path (String, e.g. /tmp/hello.wasm)
      2. Wasm bytecode format which is the content of a wasm binary file (Uint8Array)
    • options: An options object for setup the WasmEdge execution environment.
      • options
        • args : An array of strings that the Wasm application will get as function arguments. Default: [].
        • env : An object like process.env that Wasm application will get as its environment variables. Default: {}.
        • preopens : An object which maps '<guest_path>:<host_path>'. E.g. {'/sandbox': '/some/real/path/that/wasm/can/access'} Default: {}.
        • EnableWasiStartFunction : This option will disable wasm-bindgen mode and prepare the working environment for the standalone wasm program. If you want to run an application with main(), you should set this to true. Default: false.
        • EnableAOT : This option will enable WasmEdge AoT mode. Default: false.
        • EnableMeasurement : This option will enable measurement but decrease its performance. Default: false.
        • AllowCommands : An array of strings that indicate what commands are allowed to execute in the WasmEdge Process Module. Default [].
        • AllowAllCommands : Allow users to call any command in the WasmEdge Process Module. This option will overwrite the AllowCommands. Default: false.
  • Return value:
    • vm_instance: A WasmEdge instance.

Methods

Start() -> Integer

  • Emit _start() and expect the return value type is Integer which represents the error code from main().
  • Arguments:
    • If you want to append arguments for the standalone wasm program, please set the args in wasi options.
  • Example:
let error_code = Start();

Run(function_name, args...) -> void

  • Emit function_name with args and expect the return value type is void.
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
Run("Print", 1234);

RunInt(function_name, args...) -> Integer

  • Emit function_name with args and expect the return value type is Integer (Int32).
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
let result = RunInt("Add", 1, 2);
// result should be 3

RunUInt(function_name, args...) -> Integer

  • Emit function_name with args and expect the return value type is Integer (UInt32).
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
let result = RunInt("Add", 1, 2);
// result should be 3

RunInt64(function_name, args...) -> BigInt

  • Emit function_name with args and expect the return value type is BigInt (Int64).
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
let result = RunInt("Add", 1, 2);
// result should be 3

RunUInt64(function_name, args...) -> BigInt

  • Emit function_name with args and expect the return value type is BigInt (UInt64).
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
let result = RunInt("Add", 1, 2);
// result should be 3

RunString(function_name, args...) -> String

  • Emit function_name with args and expect the return value type is String.
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
let result = RunString("PrintMathScore", "Amy", 98);
// result: "Amy’s math score is 98".

RunUint8Array(function_name, args...) -> Uint8Array

  • Emit function_name with args and expect the return value type is Uint8Array.
  • Arguments:
    • function_name : The function name which users want to emit.
    • args <Integer/String/Uint8Array>*: The function arguments. The delimiter is ,
  • Example:
let result = RunUint8Array("Hash", "Hello, world!");
// result: "[12, 22, 33, 42, 51]".

Compile(output_filename) -> boolean

  • Compile a given wasm file (can be a file path or a byte array) into a native binary whose name is the given output_filename.
  • This function uses WasmEdge AoT compiler.
  • Return false when the compilation failed.
// Compile only
let vm = wasmedge.VM("/path/to/wasm/file", options);
vm.Compile("/path/to/aot/file");

// When you want to run the compiled file
let vm = wasmedge.VM("/path/to/aot/file", options);
vm.RunXXX("Func", args);

GetStatistics() -> Object

  • If you want to enable measurement, set the option EnableMeasurement to true. But please notice that enabling measurement will significantly affect performance.
  • Get the statistics of execution runtime.
  • Return Value Statistics
    • Measure -> : To show if the measurement is enabled or not.
    • TotalExecutionTime -> : Total execution time (Wasm exeuction time + Host function execution time) in `` unit.
    • WasmExecutionTime -> : Wasm instructions execution time in ns unit.
    • HostFunctionExecutionTime -> : Host functions (e.g. eei or wasi functions) execution time in ns unit.
    • InstructionCount -> : The number of executed instructions in this execution.
    • TotalGasCost -> : The cost of this execution.
    • InstructionPerSecond -> : The instructions per second of this execution.
    let result = RunInt("Add", 1, 2);
    // result should be 3
    let stat = GetStatistics();
    /*
    If the `EnableMeasurement: true`:
    
    stat = Statistics:  {
      Measure: true,
      TotalExecutionTime: 1512,
      WasmExecutionTime: 1481,
      HostFunctionExecutionTime: 31,
      InstructionCount: 27972,
      TotalGasCost: 27972,
      InstructionPerSecond: 18887238.35246455
    }
    
    Else:
    
    stat = Statistics:  {
      Measure: false
    }
    */

wasmedge-core's People

Contributors

0yi0 avatar alabulei1 avatar dm4 avatar hydai avatar juntao avatar q82419 avatar tpmccallum avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

wasmedge-core's Issues

VM report error randomly

If I create a new VM and call its run function periodically, it would throw errors randomly.

var wasmedge = require('wasmedge-core');

setInterval(() => {
  try {
    var vm = new wasmedge.VM("/home/ubuntu/calculator_bg.wasm");
    var ret = vm.RunString("run", "3*3");
    console.log(ret);
  } catch {}
}, 1500)

or using for loop

var wasmedge = require('wasmedge-core');

for (let i = 0; i < 5; i++) {
  try {
    var vm = new wasmedge.VM("/home/ubuntu/calculator_bg.wasm");
    var ret = vm.RunString("run", "3*3");
    console.log(ret);
  } catch {}
}

The error is:

[2021-10-15 08:15:55.931] [error] wasmedge runtime failed: wasm function not found, Code: 0x05
[2021-10-15 08:15:55.931] [error]     When executing function name: "__wbindgen_malloc"
[2021-10-15 08:15:55.931] [error] wasmedge runtime failed: wasm function not found, Code: 0x05
[2021-10-15 08:15:55.931] [error]     When executing function name: "run"

Unable to run in Node

I am running in an Ubuntu container after following the instructions listed on the repo here (and the wasmedge-quickjs repo).

I am instantiating the VM like so:


const path = require("path");
const wasmedge = require("wasmedge-core");

const vm = new wasmedge.VM(
  path.resolve(process.cwd(), "target/wasm32-wasi/release/main.wasm"),
  {
    EnableWasiStartFunction: true,
    args: [],
    preopens: {},
  }
);

console.log(vm);

vm.Start();

However, whenever i try to start the app, I am receiving the following error:

root@944558b7af10:/app# node server
/app/node_modules/wasmedge-core/index.js:7
process.dlopen(module, binding_path,
        ^
Error: /app/node_modules/wasmedge-core/lib/binding/linux-x64/wasmedge.node: cannot open shared object file: No such file or directory
    at Object.<anonymous> (/app/node_modules/wasmedge-core/index.js:7:9)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:827:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/app/server.js:4:18)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10) {
  code: 'ERR_DLOPEN_FAILED'
}

Any ideas on what this could be? Thanks

Embed the lifecycle scripts in the releases or checksum to prevent tampering

Hey,

My name is Maciej Mensfeld and I run a research security project called WhiteSource Diffend.io.

I've noticed, that this wasmedge-core downloads lifecycle scripts uses them (ref b82ebf3). While it's a totally common pattern, what is lacking here is integrity verification and version pinning.

You could verify the integrity of the downloaded files before using it by comparing the file hash to a hardcoded, expected file hash.

This is essentially what package managers do to verify the integrity of downloaded packages.

Doing this would prevent attack scenarios in which WasmEdge/WasmEdge Github scripts are compromised or manipulated in a malicious way.

Have a great day :)

npm i -g wasmedge-core didn't work on MacOS

$ npm i -g wasmedge-core
npm ERR! code 127
npm ERR! path /Users/katopz/.nvm/versions/node/v16.13.0/lib/node_modules/wasmedge-core
npm ERR! command failed
npm ERR! command sh -c ./scripts/preinstall.sh
npm ERR! ./scripts/preinstall.sh: line 16: wget: command not found

Any workaround?

Support latest WasmEdge version (0.10.0 and onwards to 0.11.x)

Hi,

thanks for your works on establishing WebAssembly. As discussed in #17 and #18, I would like to ask if it was possible to update wasmedge-core to support the latest WasmEdge versions.

I am currently writing a framework on top of WasmEdge as part of my master's thesis (see WasmEdge/WasmEdge#2233) and one consideration are supported programming languages to embed WasmWedge compatible WebAssembly binaries into. As node is a popular target, it is also in my interest to support JS as a target. I require wasmedge-core as an SDK for JavaScript / node, because the goal is a WebAssembly binary compiled to WASI + WasmEdge specs and this requires WasmEdge compatible bindings for node.

I'm in my pre evaluations currently and would be very happy if you could support node bindings for the latest WasmEdge versions.

Thanks in advance!

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.