Upgrade to WasmEdge-Go v0.10.0

Due to the WasmEdge-Go API breaking changes, this document shows the guideline of programming with WasmEdge-Go API to upgrade from the v0.9.2 to the v0.10.0 version.

Due to the v0.9.1 is retracted, we use the version v0.9.2 here.

Concepts

  1. Merged the ImportObject into the Module.

    The ImportObject struct which is for the host functions is merged into Module. Developers can use the related APIs to construct host modules.

    • wasmedge.NewImportObject() is changed to wasmedge.NewModule().
    • (*wasmedge.ImportObject).Release() is changed to (*wasmedge.Module).Release().
    • (*wasmedge.ImportObject).AddFunction() is changed to (*wasmedge.Module).AddFunction().
    • (*wasmedge.ImportObject).AddTable() is changed to (*wasmedge.Module).AddTable().
    • (*wasmedge.ImportObject).AddMemory() is changed to (*wasmedge.Module).AddMemory().
    • (*wasmedge.ImportObject).AddGlobal() is changed to (*wasmedge.Module).AddGlobal().
    • (*wasmedge.ImportObject).NewWasiImportObject() is changed to (*wasmedge.Module).NewWasiModule().
    • (*wasmedge.ImportObject).NewWasmEdgeProcessImportObject() is changed to (*wasmedge.Module).NewWasmEdgeProcessModule().
    • (*wasmedge.ImportObject).InitWASI() is changed to (*wasmedge.Module).InitWASI().
    • (*wasmedge.ImportObject).InitWasmEdgeProcess() is changed to (*wasmedge.Module).InitWasmEdgeProcess().
    • (*wasmedge.ImportObject).WasiGetExitCode() is changed to (*wasmedge.Module).WasiGetExitCode.
    • (*wasmedge.VM).RegisterImport() is changed to (*wasmedge.VM).RegisterModule().
    • (*wasmedge.VM).GetImportObject() is changed to (*wasmedge.VM).GetImportModule().

    For the new host function examples, please refer to the example below.

  2. Used the pointer to Function instead of the index in the FuncRef value type.

    For the better performance and security, the FuncRef related APIs used the *wasmedge.Function for the parameters and returns.

    • wasmedge.NewFuncRef() is changed to use the *Function as it’s argument.
    • Added (wasmedge.FuncRef).GetRef() to retrieve the *Function.
  3. Supported multiple anonymous WASM module instantiation.

    In the version before v0.9.2, WasmEdge only supports 1 anonymous WASM module to be instantiated at one time. If developers instantiate a new WASM module, the old one will be replaced. After the v0.10.0 version, developers can instantiate multiple anonymous WASM module by Executor and get the Module instance. But for the source code using the VM APIs, the behavior is not changed. For the new examples of instantiating multiple anonymous WASM modules, please refer to the example below.

  4. Behavior changed of Store.

    The Function, Table, Memory, and Global instances retrievement from the Store is moved to the Module instance. The Store only manage the module linking when instantiation and the named module searching after the v0.10.0 version.

    • (*wasmedge.Store).ListFunction() and (*wasmedge.Store).ListFunctionRegistered() is replaced by (*wasmedge.Module).ListFunction().
    • (*wasmedge.Store).ListTable() and (*wasmedge.Store).ListTableRegistered() is replaced by (*wasmedge.Module).ListTable().
    • (*wasmedge.Store).ListMemory() and (*wasmedge.Store).ListMemoryRegistered() is replaced by (*wasmedge.Module).ListMemory().
    • (*wasmedge.Store).ListGlobal() and (*wasmedge.Store).ListGlobalRegistered() is replaced by (*wasmedge.Module).ListGlobal().
    • (*wasmedge.Store).FindFunction() and (*wasmedge.Store).FindFunctionRegistered() is replaced by (*wasmedge.Module).FindFunction().
    • (*wasmedge.Store).FindTable() and (*wasmedge.Store).FindTableRegistered() is replaced by (*wasmedge.Module).FindTable().
    • (*wasmedge.Store).FindMemory() and (*wasmedge.Store).FindMemoryRegistered() is replaced by (*wasmedge.Module).FindMemory().
    • (*wasmedge.Store).FindGlobal() and (*wasmedge.Store).FindGlobalRegistered() is replaced by (*wasmedge.Module).FindGlobal().

    For the new examples of retrieving instances, please refer to the example below.

  5. The Module-based resource management.

    Except the creation of Module instance for the host functons, the Executor will output a Module instance after instantiation. No matter the anonymous or named modules, developers have the responsibility to destroy them by (*wasmedge.Module).Release() API. The Store will link to the named Module instance after registering. After the destroyment of a Module instance, the Store will unlink to that automatically; after the destroyment of the Store, the all Module instances the Store linked to will unlink to that Store automatically.

WasmEdge-Go VM changes

The VM APIs are basically not changed, except the ImportObject related APIs.

The following is the example of WASI initialization in WasmEdge-Go v0.9.2:

  1. conf := wasmedge.NewConfigure(wasmedge.WASI)
  2. vm := wasmedge.NewVMWithConfig(conf)
  3. // The following API can retrieve the pre-registration import objects from the VM object.
  4. // This API will return `nil` if the corresponding pre-registration is not set into the configuration.
  5. wasiobj := vm.GetImportObject(wasmedge.WASI)
  6. // Initialize the WASI.
  7. wasiobj.InitWasi(
  8. os.Args[1:], // The args
  9. os.Environ(), // The envs
  10. []string{".:."}, // The mapping preopens
  11. )
  12. // ...
  13. vm.Release()
  14. conf.Release()

Developers can change to use the WasmEdge-Go v0.10.0 as follows, with only replacing the ImportObject into Module:

  1. conf := wasmedge.NewConfigure(wasmedge.WASI)
  2. vm := wasmedge.NewVMWithConfig(conf)
  3. // The following API can retrieve the pre-registration module instances from the VM object.
  4. // This API will return `nil` if the corresponding pre-registration is not set into the configuration.
  5. wasiobj := vm.GetImportModule(wasmedge.WASI)
  6. // Initialize the WASI.
  7. wasiobj.InitWasi(
  8. os.Args[1:], // The args
  9. os.Environ(), // The envs
  10. []string{".:."}, // The mapping preopens
  11. )
  12. // ...
  13. vm.Release()
  14. conf.Release()

The VM provides a new API for getting the current instantiated anonymous Module instance. For example, if developer want to get the exported Global instance:

  1. // Assume that a WASM module is instantiated in `vm`, and exports the "global_i32".
  2. store := vm.GetStore()
  3. globinst := store.FindGlobal("global_i32")

After the WasmEdge-Go v0.10.0, developers can use the (*wasmedge.VM).GetActiveModule() to get the module instance:

  1. // Assume that a WASM module is instantiated in `vm`, and exports the "global_i32".
  2. mod := vm.GetActiveModule()
  3. // The example of retrieving the global instance.
  4. globinst := mod.FindGlobal("global_i32")

WasmEdge Executor changes

Executor helps to instantiate a WASM module, register a WASM module into Store with module name, register the host modules with host functions, or invoke functions.

  1. WASM module instantiation

    In WasmEdge-Go v0.9.2 version, developers can instantiate a WASM module by the Executor API:

    1. var ast *wasmedge.AST
    2. // Assume that `ast` is a loaded WASM from file or buffer and has passed the validation.
    3. // Assume that `executor` is a `*wasmedge.Executor`.
    4. // Assume that `store` is a `*wasmedge.Store`.
    5. err := executor.Instantiate(store, ast)
    6. if err != nil {
    7. fmt.Println("Instantiation FAILED:", err.Error())
    8. }

    Then the WASM module is instantiated into an anonymous module instance and handled by the Store. If a new WASM module is instantiated by this API, the old instantiated module instance will be cleaned. After the WasmEdge-Go v0.10.0 version, the instantiated anonymous module will be outputed and handled by caller, and not only 1 anonymous module instance can be instantiated. Developers have the responsibility to release the outputed module instances.

    1. var ast1 *wasmedge.AST
    2. var ast2 *wasmedge.AST
    3. // Assume that `ast1` and `ast2` are loaded WASMs from different files or buffers,
    4. // and have both passed the validation.
    5. // Assume that `executor` is a `*wasmedge.Executor`.
    6. // Assume that `store` is a `*wasmedge.Store`.
    7. mod1, err1 := executor.Instantiate(store, ast1)
    8. if err1 != nil {
    9. fmt.Println("Instantiation FAILED:", err1.Error())
    10. }
    11. mod2, err2 := executor.Instantiate(store, ast2)
    12. if err2 != nil {
    13. fmt.Println("Instantiation FAILED:", err2.Error())
    14. }
    15. mod1.Release()
    16. mod2.Release()
  2. WASM module registration with module name

    When instantiating and registering a WASM module with module name, developers can use the (*wasmedge.Executor).RegisterModule() API before WasmEdge-Go v0.9.2.

    1. var ast *wasmedge.AST
    2. // Assume that `ast` is a loaded WASM from file or buffer and has passed the validation.
    3. // Assume that `executor` is a `*wasmedge.Executor`.
    4. // Assume that `store` is a `*wasmedge.Store`.
    5. // Register the WASM module into store with the export module name "mod".
    6. err := executor.RegisterModule(store, ast, "mod")
    7. if err != nil {
    8. fmt.Println("WASM registration FAILED:", err.Error())
    9. }

    The same feature is implemented in WasmEdge-Go v0.10.0, but in different API (*wasmedge.Executor).Register():

    1. var ast *wasmedge.AST
    2. // Assume that `ast` is a loaded WASM from file or buffer and has passed the validation.
    3. // Assume that `executor` is a `*wasmedge.Executor`.
    4. // Assume that `store` is a `*wasmedge.Store`.
    5. // Register the WASM module into store with the export module name "mod".
    6. mod, err := executor.Register(store, ast, "mod")
    7. if err != nil {
    8. fmt.Println("WASM registration FAILED:", err.Error())
    9. }
    10. mod.Release()

    Developers have the responsibility to release the outputed module instances.

  3. Host module registration

    In WasmEdge-Go v0.9.2, developers can create an ImportObject and register into Store.

    1. // Create the import object with the export module name.
    2. impobj := wasmedge.NewImportObject("module")
    3. // ...
    4. // Add the host functions, tables, memories, and globals into the import object.
    5. // The import object has already contained the export module name.
    6. err := executor.RegisterImport(store, impobj)
    7. if err != nil {
    8. fmt.Println("Import object registration FAILED:", err.Error())
    9. }

    After WasmEdge-Go v0.10.0, developers should use the Module instance instead:

    1. // Create the module instance with the export module name.
    2. impmod := wasmedge.NewModule("module")
    3. // ...
    4. // Add the host functions, tables, memories, and globals into the module instance.
    5. // The module instance has already contained the export module name.
    6. err := executor.RegisterImport(store, impmod)
    7. if err != nil {
    8. fmt.Println("Module instance registration FAILED:", err.Error())
    9. }

    Developers have the responsibility to release the created module instances.

  4. WASM function invokation

    This example uses the fibonacci.wasm, and the corresponding WAT file is at fibonacci.wat. In WasmEdge-Go v0.9.2 version, developers can invoke a WASM function with the export function name:

    1. // Create the store object. The store object holds the instances.
    2. store := wasmedge.NewStore()
    3. // Error.
    4. var err error
    5. // AST object.
    6. var ast *wasmedge.AST
    7. // Return values.
    8. var res []interface{}
    9. // Create the loader object.
    10. loader := wasmedge.NewLoader()
    11. // Create the validator object.
    12. validator := wasmedge.NewValidator()
    13. // Create the executor object.
    14. executor := wasmedge.NewExecutor()
    15. // Load the WASM file or the compiled-WASM file and convert into the AST object.
    16. ast, err = loader.LoadFile("fibonacci.wasm")
    17. if err != nil {
    18. fmt.Println("Load WASM from file FAILED:", err.Error())
    19. return
    20. }
    21. // Validate the WASM module.
    22. err = validator.Validate(ast)
    23. if err != nil {
    24. fmt.Println("Validation FAILED:", err.Error())
    25. return
    26. }
    27. // Instantiate the WASM module into the Store object.
    28. err = executor.Instantiate(store, ast)
    29. if err != nil {
    30. fmt.Println("Instantiation FAILED:", err.Error())
    31. return
    32. }
    33. // Invoke the function which is exported with the function name "fib".
    34. res, err = executor.Invoke(store, "fib", int32(30))
    35. if err == nil {
    36. fmt.Println("Get fibonacci[30]:", res[0].(int32))
    37. } else {
    38. fmt.Println("Run failed:", err.Error())
    39. }
    40. ast.Release()
    41. loader.Release()
    42. validator.Release()
    43. executor.Release()
    44. store.Release()

    After the WasmEdge-Go v0.10.0, developers should retrieve the Function instance by function name first.

    1. // ...
    2. // Ignore the unchanged steps before validation. Please refer to the sample code above.
    3. var mod *wasmedge.Module
    4. // Instantiate the WASM module and get the output module instance.
    5. mod, err = executor.Instantiate(store, ast)
    6. if err != nil {
    7. fmt.Println("Instantiation FAILED:", err.Error())
    8. return
    9. }
    10. // Retrieve the function instance by name.
    11. funcinst := mod.FindFunction("fib")
    12. if funcinst == nil {
    13. fmt.Println("Run FAILED: Function name `fib` not found")
    14. return
    15. }
    16. res, err = executor.Invoke(store, funcinst, int32(30))
    17. if err == nil {
    18. fmt.Println("Get fibonacci[30]:", res[0].(int32))
    19. } else {
    20. fmt.Println("Run FAILED:", err.Error())
    21. }
    22. ast.Release()
    23. mod.Release()
    24. loader.Release()
    25. validator.Release()
    26. executor.Release()
    27. store.Release()

Instances retrievement

This example uses the fibonacci.wasm, and the corresponding WAT file is at fibonacci.wat.

Before the WasmEdge-Go v0.9.2 versions, developers can retrieve all exported instances of named or anonymous modules from Store:

  1. // Create the store object. The store object holds the instances.
  2. store := wasmedge.NewStore()
  3. // Error.
  4. var err error
  5. // AST object.
  6. var ast *wasmedge.AST
  7. // Create the loader object.
  8. loader := wasmedge.NewLoader()
  9. // Create the validator object.
  10. validator := wasmedge.NewValidator()
  11. // Create the executor object.
  12. executor := wasmedge.NewExecutor()
  13. // Load the WASM file or the compiled-WASM file and convert into the AST object.
  14. ast, err = loader.LoadFile("fibonacci.wasm")
  15. if err != nil {
  16. fmt.Println("Load WASM from file FAILED:", err.Error())
  17. return
  18. }
  19. // Validate the WASM module.
  20. err = validator.Validate(ast)
  21. if err != nil {
  22. fmt.Println("Validation FAILED:", err.Error())
  23. return
  24. }
  25. // Example: register and instantiate the WASM module with the module name "module_fib".
  26. err = executor.RegisterModule(store, ast, "module_fib")
  27. if err != nil {
  28. fmt.Println("Instantiation FAILED:", err.Error())
  29. return
  30. }
  31. // Example: Instantiate the WASM module into the Store object.
  32. err = executor.Instantiate(store, ast)
  33. if err != nil {
  34. fmt.Println("Instantiation FAILED:", err.Error())
  35. return
  36. }
  37. // Now, developers can retrieve the exported instances from the store.
  38. // Take the exported functions as example. This WASM exports the function "fib".
  39. // Find the function "fib" from the instantiated anonymous module.
  40. func1 := store.FindFunction("fib")
  41. // Find the function "fib" from the registered module "module_fib".
  42. func2 := store.FindFunctionRegistered("module_fib", "fib")
  43. ast.Release()
  44. store.Release()
  45. loader.Release()
  46. validator.Release()
  47. executor.Release()

After the WasmEdge-Go v0.10.0, developers can instantiate several anonymous Module instances, and should retrieve the exported instances from named or anonymous Module instances:

  1. // Create the store object. The store is the object to link the modules for imports and exports.
  2. store := wasmedge.NewStore()
  3. // Error.
  4. var err error
  5. // AST object.
  6. var ast *wasmedge.AST
  7. // Module instances.
  8. var namedmod *wasmedge.Module
  9. var anonymousmod *wasmedge.Module
  10. // Create the loader object.
  11. loader := wasmedge.NewLoader()
  12. // Create the validator object.
  13. validator := wasmedge.NewValidator()
  14. // Create the executor object.
  15. executor := wasmedge.NewExecutor()
  16. // Load the WASM file or the compiled-WASM file and convert into the AST object.
  17. ast, err = loader.LoadFile("fibonacci.wasm")
  18. if err != nil {
  19. fmt.Println("Load WASM from file FAILED:", err.Error())
  20. return
  21. }
  22. // Validate the WASM module.
  23. err = validator.Validate(ast)
  24. if err != nil {
  25. fmt.Println("Validation FAILED:", err.Error())
  26. return
  27. }
  28. // Example: register and instantiate the WASM module with the module name "module_fib".
  29. namedmod, err = executor.Register(store, ast, "module_fib")
  30. if err != nil {
  31. fmt.Println("Instantiation FAILED:", err.Error())
  32. return
  33. }
  34. // Example: Instantiate the WASM module and get the output module instance.
  35. anonymousmod, err = executor.Instantiate(store, ast)
  36. if err != nil {
  37. fmt.Println("Instantiation FAILED:", err.Error())
  38. return
  39. }
  40. // Now, developers can retrieve the exported instances from the module instaces.
  41. // Take the exported functions as example. This WASM exports the function "fib".
  42. // Find the function "fib" from the instantiated anonymous module.
  43. func1 := anonymousmod.FindFunction("fib")
  44. // Find the function "fib" from the registered module "module_fib".
  45. func2 := namedmod.FindFunction("fib")
  46. // Or developers can get the named module instance from the store:
  47. gotmod := store.FindModule("module_fib")
  48. func3 := gotmod.FindFunction("fib")
  49. namedmod.Release()
  50. anonymousmod.Release()
  51. ast.Release()
  52. store.Release()
  53. loader.Release()
  54. validator.Release()
  55. executor.Release()

Host functions

The difference of host functions are the replacement of ImportObject struct.

  1. // Host function body definition.
  2. func host_add(data interface{}, mem *wasmedge.Memory, params []interface{}) ([]interface{}, wasmedge.Result) {
  3. // add: i32, i32 -> i32
  4. res := params[0].(int32) + params[1].(int32)
  5. // Set the returns
  6. returns := make([]interface{}, 1)
  7. returns[0] = res
  8. // Return
  9. return returns, wasmedge.Result_Success
  10. }
  11. // ...
  12. // Create an import object with the module name "module".
  13. impobj := wasmedge.NewImportObject("module")
  14. // Create and add a function instance into the import object with export name "add".
  15. functype := wasmedge.NewFunctionType(
  16. []wasmedge.ValType{wasmedge.ValType_I32, wasmedge.ValType_I32},
  17. []wasmedge.ValType{wasmedge.ValType_I32},
  18. )
  19. hostfunc := wasmedge.NewFunction(functype, host_add, nil, 0)
  20. // The third parameter is the pointer to the additional data object.
  21. // Developers should guarantee the life cycle of the data, and it can be `nil`
  22. // if the external data is not needed.
  23. functype.Release()
  24. impobj.AddFunction("add", hostfunc)
  25. // The import object should be released.
  26. // Developers should __NOT__ release the instances added into the import objects.
  27. impobj.Release()

Developers can use the Module struct to upgrade to WasmEdge v0.10.0 easily.

  1. // Host function body definition.
  2. func host_add(data interface{}, mem *wasmedge.Memory, params []interface{}) ([]interface{}, wasmedge.Result) {
  3. // add: i32, i32 -> i32
  4. res := params[0].(int32) + params[1].(int32)
  5. // Set the returns
  6. returns := make([]interface{}, 1)
  7. returns[0] = res
  8. // Return
  9. return returns, wasmedge.Result_Success
  10. }
  11. // ...
  12. // Create a module instance with the module name "module".
  13. mod := wasmedge.NewModule("module")
  14. // Create and add a function instance into the module instance with export name "add".
  15. functype := wasmedge.NewFunctionType(
  16. []wasmedge.ValType{wasmedge.ValType_I32, wasmedge.ValType_I32},
  17. []wasmedge.ValType{wasmedge.ValType_I32},
  18. )
  19. hostfunc := wasmedge.NewFunction(functype, host_add, nil, 0)
  20. // The third parameter is the pointer to the additional data object.
  21. // Developers should guarantee the life cycle of the data, and it can be `nil`
  22. // if the external data is not needed.
  23. functype.Release()
  24. mod.AddFunction("add", hostfunc)
  25. // The module instances should be released.
  26. // Developers should __NOT__ release the instances added into the module instance objects.
  27. mod.Release()