Host Functions

Host functions are functions outside WebAssembly and passed to WASM modules as imports. The following steps give an example of registering a host module into WasmEdge runtime.

This example is for the sources compile with the WasmEdge project in C++. If developers want to implement the host functions in C/C++ with WasmEdge C API and without compiling with the WasmEdge project, please refer to the C API Documentation.

Definitions of Host Instances

WasmEdge supports registering host function, memory, table, and global instances as imports. For more details, samples can be found in include/host/wasi/ and test/core/spectest.h.

Functions

A simple host function class can be declared as follows:

  1. #include "common/errcode.h"
  2. #include "runtime/hostfunc.h"
  3. #include "runtime/instance/memory.h"
  4. namespace WasmEdge {
  5. namespace Host {
  6. class TestHost : public Runtime::HostFunction<TestHost> {
  7. public:
  8. Expect<uint32_t> body(Runtime::Instance::MemoryInstance *MemInst, uint32_t Param1, float Param2);
  9. };
  10. } // namespace Host
  11. } // namespace WasmEdge

According to example, return type Expect<T> presents the expected return number type T of this host function. Types of Param1 and Param2 presents argument types of this host function. Only WASM built-in types (aka. uint32_t, uint64_t, float, and double) are supported in host functions. When instantiating, the function signature of vec(valtype) -> resulttype is generated and can be imported by WASM modules.

Note: In the current state, only a single value returning is supported.

Another situation is passing environments or information which need to be accessed by host function body. The following sample shows how to implement host function clusters:

  1. #include "common/errcode.h"
  2. #include "runtime/hostfunc.h"
  3. #include "runtime/instance/memory.h"
  4. #include <vector>
  5. namespace WasmEdge {
  6. namespace Host {
  7. template <typename T> class TestCluster : public Runtime::HostFunction<T> {
  8. public:
  9. TestCluster(std::vector<uint8_t> &Vec) : Data(Vec) {}
  10. protected:
  11. std::vector<uint8_t> &Data;
  12. };
  13. class TestHost1 : public TestCluster<TestHost1> {
  14. public:
  15. TestHost1(std::vector<uint8_t> &Vec) : TestCluster(Vec) {}
  16. Expect<uint32_t> body(Runtime::Instance::MemoryInstance *MemInst, uint32_t Param1, float Param2) {
  17. // Operations to `Data` ...
  18. return {};
  19. }
  20. };
  21. class TestHost2 : public TestCluster<TestHost2> {
  22. public:
  23. TestHost2(std::vector<uint8_t> &Vec) : TestCluster(Vec) {}
  24. Expect<uint64_t> body(Runtime::Instance::MemoryInstance *MemInst, uint64_t Param1, double Param2) {
  25. // Operations to `Data` ...
  26. return {};
  27. }
  28. };
  29. } // namespace Host
  30. } // namespace WasmEdge

Tables, Memories, and Globals

To create a host table, memory, and global instance, the only way is to create them with their constructor in the host module. The following chapter about the host module will provide examples.

Host Modules

The host module is a module instance which can be registered into WasmEdge runtime. A module instance contains host functions, tables, memories, globals, and other user-customized data. WasmEdge provides API to register a module instance into a VM or Store. After registering, these host instances in the module instance can be imported by WASM modules.

Declaration

Module instance supplies exported module name and can contain customized data. A module name is needed when constructing module instances.

  1. #include "common/errcode.h"
  2. #include "runtime/instance/module.h"
  3. namespace WasmEdge {
  4. namespace Host {
  5. class TestModule : public Runtime::Instance::ModuleInstance {
  6. public:
  7. TestModule() : ModuleInstance("test");
  8. virtual ~TestModule() = default;
  9. };
  10. } // namespace Host
  11. } // namespace WasmEdge

Add Instances

Module instance provides addHostFunc(), addHostTable(), addHostMemory(), and addHostGlobal() to insert instances with their unique names. Insertion can be done in constructor. The following example also shows how to create host memories, tables, and globals.

  1. #include "common/errcode.h"
  2. #include "runtime/hostfunc.h"
  3. #include "runtime/instance/module.h"
  4. #include <memory>
  5. #include <vector>
  6. namespace WasmEdge {
  7. namespace Host {
  8. template <typename T> class TestCluster : public Runtime::HostFunction<T> {
  9. public:
  10. TestCluster(std::vector<uint8_t> &Vec) : Data(Vec) {}
  11. protected:
  12. std::vector<uint8_t> &Data;
  13. };
  14. class TestHost1 : public TestCluster<TestHost1> {
  15. public:
  16. TestHost1(std::vector<uint8_t> &Vec) : TestCluster(Vec) {}
  17. Expect<uint32_t> body(Runtime::Instance::MemoryInstance *MemInst, uint32_t Param1, float Param2) {
  18. // Operations to `Data` ...
  19. return {};
  20. }
  21. };
  22. class TestHost2 : public TestCluster<TestHost2> {
  23. public:
  24. TestHost2(std::vector<uint8_t> &Vec) : TestCluster(Vec) {}
  25. Expect<uint64_t> body(Runtime::Instance::MemoryInstance *MemInst, uint64_t Param1, double Param2) {
  26. // Operations to `Data` ...
  27. return {};
  28. }
  29. };
  30. class TestModule : public Runtime::Instance::ModuleInstance {
  31. public:
  32. TestModule(std::vector<uint8_t> &Vec) : ModuleInstance("test"), Data(Vec) {
  33. // Add function instances with exporting name
  34. addHostFunc("test_func1", std::make_unique<TestHost1>(Data));
  35. addHostFunc("test_func2", std::make_unique<TestHost2>(Data));
  36. // Add table instance with exporting name
  37. addHostTable("table", std::make_unique<Runtime::Instance::TableInstance>(
  38. TableType(RefType::FuncRef, 10, 20)));
  39. // Add memory instance with exporting name
  40. addHostMemory("memory", std::make_unique<Runtime::Instance::MemoryInstance>(
  41. MemoryType(1, 2)));
  42. // Add global instance with exporting name
  43. addHostGlobal("global_i32",
  44. std::make_unique<Runtime::Instance::GlobalInstance>(
  45. GlobalType(ValType::I32, ValMut::Const), uint32_t(666)));
  46. addHostGlobal("global_i64",
  47. std::make_unique<Runtime::Instance::GlobalInstance>(
  48. GlobalType(ValType::I64, ValMut::Const), uint64_t(666)));
  49. addHostGlobal("global_f32",
  50. std::make_unique<Runtime::Instance::GlobalInstance>(
  51. GlobalType(ValType::F32, ValMut::Const), float(666)));
  52. addHostGlobal("global_f64",
  53. std::make_unique<Runtime::Instance::GlobalInstance>(
  54. GlobalType(ValType::F64, ValMut::Const), double(666)));
  55. }
  56. virtual ~TestModule() = default;
  57. private:
  58. std::vector<uint8_t> &Data;
  59. };
  60. } // namespace Host
  61. } // namespace WasmEdge

Module instance supplies getFuncs(), getTables(), getMems(), and getGlobals() to search registered instances by unique exporting name. For more details, APIs can be found in include/runtime/importobj.h.

Register Host Modules to WasmEdge

Users can register host modules via WasmEdge::VM::registerModule() API.

  1. #include "common/configure.h"
  2. #include "vm/vm.h"
  3. #include <vector>
  4. WasmEdge::Configure Conf;
  5. WasmEdge::VM::VM VM(Conf);
  6. std::vector<uint8_t> Data;
  7. WasmEdge::Host::TestModule TestMod(Data);
  8. VM.registerModule(TestMod);

For finding headers from WasmEdge include directories and linking static libraries, some settings are necessary for CMakeFile:

  1. add_library(wasmedgeHostModuleTest # Static library name of host modules
  2. test.cpp # Path to host modules cpp files
  3. )
  4. target_include_directories(wasmedgeHostModuleTest
  5. PUBLIC
  6. ${Boost_INCLUDE_DIRS}
  7. ${PROJECT_SOURCE_DIR}/include
  8. )

Implementation of Host Function Body

There are some tips about implementing host function bodies.

Checking Memory Instance When Using

Host function can access WASM memory, which passed as MemoryInstance * argument. When a function call occurs, a frame with module which the called function belonging to will be pushed onto the stack. In the host function case, the memory instance of the module of the top frame on the stack will be passed as the host function body’s argument. But there can be no memory instance in a WASM module. Therefore, users should check if the memory instance pointer is a nullptr or not when accessing.

Returning Expectation

From our mechanism, Expect<T> declared in include/common/errcode.h is used as the result type of function body. In Expect<void> case, return {}; is needed for an expected situation. In other cases, return Value; is needed, where Value is a variable of type T. If an unexpected situation occurs, users can call return Unexpect(Code); to return an error, which Code is an element of enumeration ErrCode.

Forcing Termination

WasmEdge provides a method for terminating WASM execution in host functions. Developers can return ErrCode::Terminated to trigger the forcing termination of the current execution and pass the ErrCode::Terminated to the caller of the host functions.