WasmEdge 0.9.1 C API Documentation

WasmEdge C API denotes an interface to access the WasmEdge runtime at version 0.9.1. The followings are the guides to working with the C APIs of WasmEdge.

Developers can refer here to upgrade to 0.10.0.

Table of Contents

WasmEdge Installation

Download And Install

The easiest way to install WasmEdge is to run the following command. Your system should have git and wget as prerequisites.

  1. curl -sSf https://raw.githubusercontent.com/WasmEdge/WasmEdge/master/utils/install.sh | bash -s -- -v 0.9.1

For more details, please refer to the Installation Guide for the WasmEdge installation.

Compile Sources

After the installation of WasmEdge, the following guide can help you to test for the availability of the WasmEdge C API.

  1. Prepare the test C file (and assumed saved as test.c):

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. printf("WasmEdge version: %s\n", WasmEdge_VersionGet());
    5. return 0;
    6. }
  2. Compile the file with gcc or clang.

    1. gcc test.c -lwasmedge_c
  3. Run and get the expected output.

    1. $ ./a.out
    2. WasmEdge version: 0.9.1

WasmEdge Basics

In this part, we will introduce the utilities and concepts of WasmEdge shared library.

Version

The Version related APIs provide developers to check for the WasmEdge shared library version.

  1. #include <wasmedge/wasmedge.h>
  2. printf("WasmEdge version: %s\n", WasmEdge_VersionGet());
  3. printf("WasmEdge version major: %u\n", WasmEdge_VersionGetMajor());
  4. printf("WasmEdge version minor: %u\n", WasmEdge_VersionGetMinor());
  5. printf("WasmEdge version patch: %u\n", WasmEdge_VersionGetPatch());

Logging Settings

The WasmEdge_LogSetErrorLevel() and WasmEdge_LogSetDebugLevel() APIs can set the logging system to debug level or error level. By default, the error level is set, and the debug info is hidden.

Value Types

In WasmEdge, developers should convert the values to WasmEdge_Value objects through APIs for matching to the WASM value types.

  1. Number types: i32, i64, f32, f64, and v128 for the SIMD proposal

    1. WasmEdge_Value Val;
    2. Val = WasmEdge_ValueGenI32(123456);
    3. printf("%d\n", WasmEdge_ValueGetI32(Val));
    4. /* Will print "123456" */
    5. Val = WasmEdge_ValueGenI64(1234567890123LL);
    6. printf("%ld\n", WasmEdge_ValueGetI64(Val));
    7. /* Will print "1234567890123" */
    8. Val = WasmEdge_ValueGenF32(123.456f);
    9. printf("%f\n", WasmEdge_ValueGetF32(Val));
    10. /* Will print "123.456001" */
    11. Val = WasmEdge_ValueGenF64(123456.123456789);
    12. printf("%.10f\n", WasmEdge_ValueGetF64(Val));
    13. /* Will print "123456.1234567890" */
  2. Reference types: funcref and externref for the Reference-Types proposal

    1. WasmEdge_Value Val;
    2. void *Ptr;
    3. bool IsNull;
    4. uint32_t Num = 10;
    5. /* Genreate a externref to NULL. */
    6. Val = WasmEdge_ValueGenNullRef(WasmEdge_RefType_ExternRef);
    7. IsNull = WasmEdge_ValueIsNullRef(Val);
    8. /* The `IsNull` will be `TRUE`. */
    9. Ptr = WasmEdge_ValueGetExternRef(Val);
    10. /* The `Ptr` will be `NULL`. */
    11. /* Genreate a funcref with function index 20. */
    12. Val = WasmEdge_ValueGenFuncRef(20);
    13. uint32_t FuncIdx = WasmEdge_ValueGetFuncIdx(Val);
    14. /* The `FuncIdx` will be 20. */
    15. /* Genreate a externref to `Num`. */
    16. Val = WasmEdge_ValueGenExternRef(&Num);
    17. Ptr = WasmEdge_ValueGetExternRef(Val);
    18. /* The `Ptr` will be `&Num`. */
    19. printf("%u\n", *(uint32_t *)Ptr);
    20. /* Will print "10" */
    21. Num += 55;
    22. printf("%u\n", *(uint32_t *)Ptr);
    23. /* Will print "65" */

Strings

The WasmEdge_String object is for the instance names when invoking a WASM function or finding the contexts of instances.

  1. Create a WasmEdge_String from a C string (const char * with NULL termination) or a buffer with length.

    The content of the C string or buffer will be copied into the WasmEdge_String object.

    1. char Buf[4] = {50, 55, 60, 65};
    2. WasmEdge_String Str1 = WasmEdge_StringCreateByCString("test");
    3. WasmEdge_String Str2 = WasmEdge_StringCreateByBuffer(Buf, 4);
    4. /* The objects should be deleted by `WasmEdge_StringDelete()`. */
    5. WasmEdge_StringDelete(Str1);
    6. WasmEdge_StringDelete(Str2);
  2. Wrap a WasmEdge_String to a buffer with length.

    The content will not be copied, and the caller should guarantee the life cycle of the input buffer.

    1. const char CStr[] = "test";
    2. WasmEdge_String Str = WasmEdge_StringWrap(CStr, 4);
    3. /* The object should __NOT__ be deleted by `WasmEdge_StringDelete()`. */
  3. String comparison

    1. const char CStr[] = "abcd";
    2. char Buf[4] = {0x61, 0x62, 0x63, 0x64};
    3. WasmEdge_String Str1 = WasmEdge_StringWrap(CStr, 4);
    4. WasmEdge_String Str2 = WasmEdge_StringCreateByBuffer(Buf, 4);
    5. bool IsEq = WasmEdge_StringIsEqual(Str1, Str2);
    6. /* The `IsEq` will be `TRUE`. */
    7. WasmEdge_StringDelete(Str2);
  4. Convert to C string

    1. char Buf[256];
    2. WasmEdge_String Str = WasmEdge_StringCreateByCString("test_wasmedge_string");
    3. uint32_t StrLength = WasmEdge_StringCopy(Str, Buf, sizeof(Buf));
    4. /* StrLength will be 20 */
    5. printf("String: %s\n", Buf);
    6. /* Will print "test_wasmedge_string". */

Results

The WasmEdge_Result object specifies the execution status. APIs about WASM execution will return the WasmEdge_Result to denote the status.

  1. WasmEdge_Result Res = WasmEdge_Result_Success;
  2. bool IsSucceeded = WasmEdge_ResultOK(Res);
  3. /* The `IsSucceeded` will be `TRUE`. */
  4. uint32_t Code = WasmEdge_ResultGetCode(Res);
  5. /* The `Code` will be 0. */
  6. const char *Msg = WasmEdge_ResultGetMessage(Res);
  7. /* The `Msg` will be "success". */

Contexts

The objects, such as VM, Store, and Function, are composed of Contexts. All of the contexts can be created by calling the corresponding creation APIs and should be destroyed by calling the corresponding deletion APIs. Developers have responsibilities to manage the contexts for memory management.

  1. /* Create the configure context. */
  2. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
  3. /* Delete the configure context. */
  4. WasmEdge_ConfigureDelete(ConfCxt);

The details of other contexts will be introduced later.

WASM Data Structures

The WASM data structures are used for creating instances or can be queried from instance contexts. The details of instances creation will be introduced in the Instances.

  1. Limit

    The WasmEdge_Limit struct is defined in the header:

    1. /// Struct of WASM limit.
    2. typedef struct WasmEdge_Limit {
    3. /// Boolean to describe has max value or not.
    4. bool HasMax;
    5. /// Minimum value.
    6. uint32_t Min;
    7. /// Maximum value. Will be ignored if the `HasMax` is false.
    8. uint32_t Max;
    9. } WasmEdge_Limit;

    Developers can initialize the struct by assigning it’s value, and the Max value is needed to be larger or equal to the Min value. The API WasmEdge_LimitIsEqual() is provided to compare with 2 WasmEdge_Limit structs.

  2. Function type context

    The Function Type context is used for the Function creation, checking the value types of a Function instance, or getting the function type with function name from VM. Developers can use the Function Type context APIs to get the parameter or return value types information.

    1. enum WasmEdge_ValType ParamList[2] = { WasmEdge_ValType_I32, WasmEdge_ValType_I64 };
    2. enum WasmEdge_ValType ReturnList[1] = { WasmEdge_ValType_FuncRef };
    3. WasmEdge_FunctionTypeContext *FuncTypeCxt = WasmEdge_FunctionTypeCreate(ParamList, 2, ReturnList, 1);
    4. enum WasmEdge_ValType Buf[16];
    5. uint32_t ParamLen = WasmEdge_FunctionTypeGetParametersLength(FuncTypeCxt);
    6. /* `ParamLen` will be 2. */
    7. uint32_t GotParamLen = WasmEdge_FunctionTypeGetParameters(FuncTypeCxt, Buf, 16);
    8. /* `GotParamLen` will be 2, and `Buf[0]` and `Buf[1]` will be the same as `ParamList`. */
    9. uint32_t ReturnLen = WasmEdge_FunctionTypeGetReturnsLength(FuncTypeCxt);
    10. /* `ReturnLen` will be 1. */
    11. uint32_t GotReturnLen = WasmEdge_FunctionTypeGetReturns(FuncTypeCxt, Buf, 16);
    12. /* `GotReturnLen` will be 1, and `Buf[0]` will be the same as `ReturnList`. */
    13. WasmEdge_FunctionTypeDelete(FuncTypeCxt);
  3. Table type context

    The Table Type context is used for Table instance creation or getting information from Table instances.

    1. WasmEdge_Limit TabLim = {.HasMax = true, .Min = 10, .Max = 20};
    2. WasmEdge_TableTypeContext *TabTypeCxt = WasmEdge_TableTypeCreate(WasmEdge_RefType_ExternRef, TabLim);
    3. enum WasmEdge_RefType GotRefType = WasmEdge_TableTypeGetRefType(TabTypeCxt);
    4. /* `GotRefType` will be WasmEdge_RefType_ExternRef. */
    5. WasmEdge_Limit GotTabLim = WasmEdge_TableTypeGetLimit(TabTypeCxt);
    6. /* `GotTabLim` will be the same value as `TabLim`. */
    7. WasmEdge_TableTypeDelete(TabTypeCxt);
  4. Memory type context

    The Memory Type context is used for Memory instance creation or getting information from Memory instances.

    1. WasmEdge_Limit MemLim = {.HasMax = true, .Min = 10, .Max = 20};
    2. WasmEdge_MemoryTypeContext *MemTypeCxt = WasmEdge_MemoryTypeCreate(MemLim);
    3. WasmEdge_Limit GotMemLim = WasmEdge_MemoryTypeGetLimit(MemTypeCxt);
    4. /* `GotMemLim` will be the same value as `MemLim`. */
    5. WasmEdge_MemoryTypeDelete(MemTypeCxt)
  5. Global type context

    The Global Type context is used for Global instance creation or getting information from Global instances.

    1. WasmEdge_GlobalTypeContext *GlobTypeCxt = WasmEdge_GlobalTypeCreate(WasmEdge_ValType_F64, WasmEdge_Mutability_Var);
    2. WasmEdge_ValType GotValType = WasmEdge_GlobalTypeGetValType(GlobTypeCxt);
    3. /* `GotValType` will be WasmEdge_ValType_F64. */
    4. WasmEdge_Mutability GotValMut = WasmEdge_GlobalTypeGetMutability(GlobTypeCxt);
    5. /* `GotValMut` will be WasmEdge_Mutability_Var. */
    6. WasmEdge_GlobalTypeDelete(GlobTypeCxt);
  6. Import type context

    The Import Type context is used for getting the imports information from a AST Module. Developers can get the external type (function, table, memory, or global), import module name, and external name from an Import Type context. The details about querying Import Type contexts will be introduced in the AST Module.

    1. WasmEdge_ASTModuleContext *ASTCxt = ...;
    2. /* Assume that `ASTCxt` is returned by the `WasmEdge_LoaderContext` for the result of loading a WASM file. */
    3. const WasmEdge_ImportTypeContext *ImpType = ...;
    4. /* Assume that `ImpType` is queried from the `ASTCxt` for the import. */
    5. enum WasmEdge_ExternalType ExtType = WasmEdge_ImportTypeGetExternalType(ImpType);
    6. /*
    7. * The `ExtType` can be one of `WasmEdge_ExternalType_Function`, `WasmEdge_ExternalType_Table`,
    8. * `WasmEdge_ExternalType_Memory`, or `WasmEdge_ExternalType_Global`.
    9. */
    10. WasmEdge_String ModName = WasmEdge_ImportTypeGetModuleName(ImpType);
    11. WasmEdge_String ExtName = WasmEdge_ImportTypeGetExternalName(ImpType);
    12. /* The `ModName` and `ExtName` should not be destroyed and the string buffers are binded into the `ASTCxt`. */
    13. const WasmEdge_FunctionTypeContext *FuncTypeCxt = WasmEdge_ImportTypeGetFunctionType(ASTCxt, ImpType);
    14. /* If the `ExtType` is not `WasmEdge_ExternalType_Function`, the `FuncTypeCxt` will be NULL. */
    15. const WasmEdge_TableTypeContext *TabTypeCxt = WasmEdge_ImportTypeGetTableType(ASTCxt, ImpType);
    16. /* If the `ExtType` is not `WasmEdge_ExternalType_Table`, the `TabTypeCxt` will be NULL. */
    17. const WasmEdge_MemoryTypeContext *MemTypeCxt = WasmEdge_ImportTypeGetMemoryType(ASTCxt, ImpType);
    18. /* If the `ExtType` is not `WasmEdge_ExternalType_Memory`, the `MemTypeCxt` will be NULL. */
    19. const WasmEdge_GlobalTypeContext *GlobTypeCxt = WasmEdge_ImportTypeGetGlobalType(ASTCxt, ImpType);
    20. /* If the `ExtType` is not `WasmEdge_ExternalType_Global`, the `GlobTypeCxt` will be NULL. */
  7. Export type context

    The Export Type context is used for getting the exports information from a AST Module. Developers can get the external type (function, table, memory, or global) and external name from an Export Type context. The details about querying Export Type contexts will be introduced in the AST Module.

    1. WasmEdge_ASTModuleContext *ASTCxt = ...;
    2. /* Assume that `ASTCxt` is returned by the `WasmEdge_LoaderContext` for the result of loading a WASM file. */
    3. const WasmEdge_ExportTypeContext *ExpType = ...;
    4. /* Assume that `ExpType` is queried from the `ASTCxt` for the export. */
    5. enum WasmEdge_ExternalType ExtType = WasmEdge_ExportTypeGetExternalType(ExpType);
    6. /*
    7. * The `ExtType` can be one of `WasmEdge_ExternalType_Function`, `WasmEdge_ExternalType_Table`,
    8. * `WasmEdge_ExternalType_Memory`, or `WasmEdge_ExternalType_Global`.
    9. */
    10. WasmEdge_String ExtName = WasmEdge_ExportTypeGetExternalName(ExpType);
    11. /* The `ExtName` should not be destroyed and the string buffer is binded into the `ASTCxt`. */
    12. const WasmEdge_FunctionTypeContext *FuncTypeCxt = WasmEdge_ExportTypeGetFunctionType(ASTCxt, ExpType);
    13. /* If the `ExtType` is not `WasmEdge_ExternalType_Function`, the `FuncTypeCxt` will be NULL. */
    14. const WasmEdge_TableTypeContext *TabTypeCxt = WasmEdge_ExportTypeGetTableType(ASTCxt, ExpType);
    15. /* If the `ExtType` is not `WasmEdge_ExternalType_Table`, the `TabTypeCxt` will be NULL. */
    16. const WasmEdge_MemoryTypeContext *MemTypeCxt = WasmEdge_ExportTypeGetMemoryType(ASTCxt, ExpType);
    17. /* If the `ExtType` is not `WasmEdge_ExternalType_Memory`, the `MemTypeCxt` will be NULL. */
    18. const WasmEdge_GlobalTypeContext *GlobTypeCxt = WasmEdge_ExportTypeGetGlobalType(ASTCxt, ExpType);
    19. /* If the `ExtType` is not `WasmEdge_ExternalType_Global`, the `GlobTypeCxt` will be NULL. */

Async

After calling the asynchronous execution APIs, developers will get the WasmEdge_Async object. Developers own the object and should call the WasmEdge_AsyncDelete() API to destroy it.

  1. Wait for the asynchronous execution

    Developers can wait the execution until finished:

    1. WasmEdge_Async *Async = ...; /* Ignored. Asynchronous execute a function. */
    2. /* Blocking and waiting for the execution. */
    3. WasmEdge_AsyncWait(Async);
    4. WasmEdge_AsyncDelete(Async);

    Or developers can wait for a time limit. If the time limit exceeded, developers can choose to cancel the execution. For the interruptible execution in AOT mode, developers should set TRUE thourgh the WasmEdge_ConfigureCompilerSetInterruptible() API into the configure context for the AOT compiler.

    1. WasmEdge_Async *Async = ...; /* Ignored. Asynchronous execute a function. */
    2. /* Blocking and waiting for the execution for 1 second. */
    3. bool IsEnd = WasmEdge_AsyncWaitFor(Async, 1000);
    4. if (IsEnd) {
    5. /* The execution finished. Developers can get the result. */
    6. WasmEdge_Result Res = WasmEdge_AsyncGet(/* ... Ignored */);
    7. } else {
    8. /* The time limit exceeded. Developers can keep waiting or cancel the execution. */
    9. WasmEdge_AsyncCancel(Async);
    10. WasmEdge_Result Res = WasmEdge_AsyncGet(Async, 0, NULL);
    11. /* The result error code will be `WasmEdge_ErrCode_Interrupted`. */
    12. }
    13. WasmEdge_AsyncDelete(Async);
  2. Get the execution result of the asynchronous execution

    Developers can use the WasmEdge_AsyncGetReturnsLength() API to get the return value list length. This function will block and wait for the execution. If the execution has finished, this function will return the length immediately. If the execution failed, this function will return 0. This function can help the developers to create the buffer to get the return values. If developers have already known the buffer length, they can skip this function and use the WasmEdge_AsyncGet() API to get the result.

    1. WasmEdge_Async *Async = ...; /* Ignored. Asynchronous execute a function. */
    2. /* Blocking and waiting for the execution and get the return value list length. */
    3. uint32_t Arity = WasmEdge_AsyncGetReturnsLength(Async);
    4. WasmEdge_AsyncDelete(Async);

    The WasmEdge_AsyncGet() API will block and wait for the execution. If the execution has finished, this function will fill the return values into the buffer and return the execution result immediately.

    1. WasmEdge_Async *Async = ...; /* Ignored. Asynchronous execute a function. */
    2. /* Blocking and waiting for the execution and get the return values. */
    3. const uint32_t BUF_LEN = 256;
    4. WasmEdge_Value Buf[BUF_LEN];
    5. WasmEdge_Result Res = WasmEdge_AsyncGet(Async, Buf, BUF_LEN);
    6. WasmEdge_AsyncDelete(Async);

Configurations

The configuration context, WasmEdge_ConfigureContext, manages the configurations for Loader, Validator, Executor, VM, and Compiler. Developers can adjust the settings about the proposals, VM host pre-registrations (such as WASI), and AOT compiler options, and then apply the Configure context to create other runtime contexts.

  1. Proposals

    WasmEdge supports turning on or off the WebAssembly proposals. This configuration is effective in any contexts created with the Configure context.

    1. enum WasmEdge_Proposal {
    2. WasmEdge_Proposal_ImportExportMutGlobals = 0,
    3. WasmEdge_Proposal_NonTrapFloatToIntConversions,
    4. WasmEdge_Proposal_SignExtensionOperators,
    5. WasmEdge_Proposal_MultiValue,
    6. WasmEdge_Proposal_BulkMemoryOperations,
    7. WasmEdge_Proposal_ReferenceTypes,
    8. WasmEdge_Proposal_SIMD,
    9. WasmEdge_Proposal_TailCall,
    10. WasmEdge_Proposal_MultiMemories,
    11. WasmEdge_Proposal_Annotations,
    12. WasmEdge_Proposal_Memory64,
    13. WasmEdge_Proposal_ExceptionHandling,
    14. WasmEdge_Proposal_Threads,
    15. WasmEdge_Proposal_FunctionReferences
    16. };

    Developers can add or remove the proposals into the Configure context.

    1. /*
    2. * By default, the following proposals have turned on initially:
    3. * * Import/Export of mutable globals
    4. * * Non-trapping float-to-int conversions
    5. * * Sign-extension operators
    6. * * Multi-value returns
    7. * * Bulk memory operations
    8. * * Reference types
    9. * * Fixed-width SIMD
    10. */
    11. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    12. WasmEdge_ConfigureAddProposal(ConfCxt, WasmEdge_Proposal_MultiMemories);
    13. WasmEdge_ConfigureRemoveProposal(ConfCxt, WasmEdge_Proposal_ReferenceTypes);
    14. bool IsBulkMem = WasmEdge_ConfigureHasProposal(ConfCxt, WasmEdge_Proposal_BulkMemoryOperations);
    15. /* The `IsBulkMem` will be `TRUE`. */
    16. WasmEdge_ConfigureDelete(ConfCxt);
  2. Host registrations

    This configuration is used for the VM context to turn on the WASI or wasmedge_process supports and only effective in VM contexts.

    1. enum WasmEdge_HostRegistration {
    2. WasmEdge_HostRegistration_Wasi = 0,
    3. WasmEdge_HostRegistration_WasmEdge_Process
    4. };

    The details will be introduced in the preregistrations of VM context.

    1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    2. bool IsHostWasi = WasmEdge_ConfigureHasHostRegistration(ConfCxt, WasmEdge_HostRegistration_Wasi);
    3. /* The `IsHostWasi` will be `FALSE`. */
    4. WasmEdge_ConfigureAddHostRegistration(ConfCxt, WasmEdge_HostRegistration_Wasi);
    5. IsHostWasi = WasmEdge_ConfigureHasHostRegistration(ConfCxt, WasmEdge_HostRegistration_Wasi);
    6. /* The `IsHostWasi` will be `TRUE`. */
    7. WasmEdge_ConfigureDelete(ConfCxt);
  3. Maximum memory pages

    Developers can limit the page size of memory instances by this configuration. When growing the page size of memory instances in WASM execution and exceeding the limited size, the page growing will fail. This configuration is only effective in the Executor and VM contexts.

    1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    2. uint32_t PageSize = WasmEdge_ConfigureGetMaxMemoryPage(ConfCxt);
    3. /* By default, the maximum memory page size is 65536. */
    4. WasmEdge_ConfigureSetMaxMemoryPage(ConfCxt, 1024);
    5. /* Limit the memory size of each memory instance with not larger than 1024 pages (64 MiB). */
    6. PageSize = WasmEdge_ConfigureGetMaxMemoryPage(ConfCxt);
    7. /* The `PageSize` will be 1024. */
    8. WasmEdge_ConfigureDelete(ConfCxt);
  4. AOT compiler options

    The AOT compiler options configure the behavior about optimization level, output format, dump IR, and generic binary.

    1. enum WasmEdge_CompilerOptimizationLevel {
    2. /// Disable as many optimizations as possible.
    3. WasmEdge_CompilerOptimizationLevel_O0 = 0,
    4. /// Optimize quickly without destroying debuggability.
    5. WasmEdge_CompilerOptimizationLevel_O1,
    6. /// Optimize for fast execution as much as possible without triggering
    7. /// significant incremental compile time or code size growth.
    8. WasmEdge_CompilerOptimizationLevel_O2,
    9. /// Optimize for fast execution as much as possible.
    10. WasmEdge_CompilerOptimizationLevel_O3,
    11. /// Optimize for small code size as much as possible without triggering
    12. /// significant incremental compile time or execution time slowdowns.
    13. WasmEdge_CompilerOptimizationLevel_Os,
    14. /// Optimize for small code size as much as possible.
    15. WasmEdge_CompilerOptimizationLevel_Oz
    16. };
    17. enum WasmEdge_CompilerOutputFormat {
    18. /// Native dynamic library format.
    19. WasmEdge_CompilerOutputFormat_Native = 0,
    20. /// WebAssembly with AOT compiled codes in custom section.
    21. WasmEdge_CompilerOutputFormat_Wasm
    22. };

    These configurations are only effective in Compiler contexts.

    1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    2. /* By default, the optimization level is O3. */
    3. WasmEdge_ConfigureCompilerSetOptimizationLevel(ConfCxt, WasmEdge_CompilerOptimizationLevel_O2);
    4. /* By default, the output format is universal WASM. */
    5. WasmEdge_ConfigureCompilerSetOutputFormat(ConfCxt, WasmEdge_CompilerOutputFormat_Native);
    6. /* By default, the dump IR is `FALSE`. */
    7. WasmEdge_ConfigureCompilerSetDumpIR(ConfCxt, TRUE);
    8. /* By default, the generic binary is `FALSE`. */
    9. WasmEdge_ConfigureCompilerSetGenericBinary(ConfCxt, TRUE);
    10. /* By default, the interruptible is `FALSE`.
    11. /* Set this option to `TRUE` to support the interruptible execution in AOT mode. */
    12. WasmEdge_ConfigureCompilerSetInterruptible(ConfCxt, TRUE);
    13. WasmEdge_ConfigureDelete(ConfCxt);
  5. Statistics options

    The statistics options configure the behavior about instruction counting, cost measuring, and time measuring in both runtime and AOT compiler. These configurations are effective in Compiler, VM, and Executor contexts.

    1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    2. /* By default, the intruction counting is `FALSE` when running a compiled-WASM or a pure-WASM. */
    3. WasmEdge_ConfigureStatisticsSetInstructionCounting(ConfCxt, TRUE);
    4. /* By default, the cost measurement is `FALSE` when running a compiled-WASM or a pure-WASM. */
    5. WasmEdge_ConfigureStatisticsSetCostMeasuring(ConfCxt, TRUE);
    6. /* By default, the time measurement is `FALSE` when running a compiled-WASM or a pure-WASM. */
    7. WasmEdge_ConfigureStatisticsSetTimeMeasuring(ConfCxt, TRUE);
    8. WasmEdge_ConfigureDelete(ConfCxt);

Statistics

The statistics context, WasmEdge_StatisticsContext, provides the instruction counter, cost summation, and cost limitation at runtime.

Before using statistics, the statistics configuration must be set. Otherwise, the return values of calling statistics are undefined behaviour.

  1. Instruction counter

    The instruction counter can help developers to profile the performance of WASM running. Developers can retrieve the Statistics context from the VM context, or create a new one for the Executor creation. The details will be introduced in the next partitions.

    1. WasmEdge_StatisticsContext *StatCxt = WasmEdge_StatisticsCreate();
    2. /* ....
    3. * After running the WASM functions with the `Statistics` context
    4. */
    5. uint32_t Count = WasmEdge_StatisticsGetInstrCount(StatCxt);
    6. double IPS = WasmEdge_StatisticsGetInstrPerSecond(StatCxt);
    7. WasmEdge_StatisticsDelete(StatCxt);
  2. Cost table

    The cost table is to accumulate the cost of instructions with their weights. Developers can set the cost table array (the indices are the byte code value of instructions, and the values are the cost of instructions) into the Statistics context. If the cost limit value is set, the execution will return the cost limit exceeded error immediately when exceeds the cost limit in runtime.

    1. WasmEdge_StatisticsContext *StatCxt = WasmEdge_StatisticsCreate();
    2. uint64_t CostTable[16] = {
    3. 0, 0,
    4. 10, /* 0x02: Block */
    5. 11, /* 0x03: Loop */
    6. 12, /* 0x04: If */
    7. 12, /* 0x05: Else */
    8. 0, 0, 0, 0, 0, 0,
    9. 20, /* 0x0C: Br */
    10. 21, /* 0x0D: Br_if */
    11. 22, /* 0x0E: Br_table */
    12. 0
    13. };
    14. /* Developers can set the costs of each instruction. The value not covered will be 0. */
    15. WasmEdge_StatisticsSetCostTable(StatCxt, CostTable, 16);
    16. WasmEdge_StatisticsSetCostLimit(StatCxt, 5000000);
    17. /* ....
    18. * After running the WASM functions with the `Statistics` context
    19. */
    20. uint64_t Cost = WasmEdge_StatisticsGetTotalCost(StatCxt);
    21. WasmEdge_StatisticsDelete(StatCxt);

WasmEdge VM

In this partition, we will introduce the functions of WasmEdge_VMContext object and show examples of executing WASM functions.

WASM Execution Example With VM Context

The following shows the example of running the WASM for getting the Fibonacci. This example uses the fibonacci.wasm, and the corresponding WAT file is at fibonacci.wat.

  1. (module
  2. (export "fib" (func $fib))
  3. (func $fib (param $n i32) (result i32)
  4. (if
  5. (i32.lt_s (get_local $n)(i32.const 2))
  6. (return (i32.const 1))
  7. )
  8. (return
  9. (i32.add
  10. (call $fib (i32.sub (get_local $n)(i32.const 2)))
  11. (call $fib (i32.sub (get_local $n)(i32.const 1)))
  12. )
  13. )
  14. )
  15. )
  1. Run WASM functions rapidly

    Assume that the WASM file fibonacci.wasm is copied into the current directory, and the C file test.c is as following:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. /* Create the configure context and add the WASI support. */
    5. /* This step is not necessary unless you need WASI support. */
    6. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    7. WasmEdge_ConfigureAddHostRegistration(ConfCxt, WasmEdge_HostRegistration_Wasi);
    8. /* The configure and store context to the VM creation can be NULL. */
    9. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(ConfCxt, NULL);
    10. /* The parameters and returns arrays. */
    11. WasmEdge_Value Params[1] = { WasmEdge_ValueGenI32(5) };
    12. WasmEdge_Value Returns[1];
    13. /* Function name. */
    14. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    15. /* Run the WASM function from file. */
    16. WasmEdge_Result Res = WasmEdge_VMRunWasmFromFile(VMCxt, "fibonacci.wasm", FuncName, Params, 1, Returns, 1);
    17. /*
    18. * Developers can run the WASM binary from buffer with the `WasmEdge_VMRunWasmFromBuffer()` API,
    19. * or from `WasmEdge_ASTModuleContext` object with the `WasmEdge_VMRunWasmFromASTModule()` API.
    20. */
    21. if (WasmEdge_ResultOK(Res)) {
    22. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    23. } else {
    24. printf("Error message: %s\n", WasmEdge_ResultGetMessage(Res));
    25. }
    26. /* Resources deallocations. */
    27. WasmEdge_VMDelete(VMCxt);
    28. WasmEdge_ConfigureDelete(ConfCxt);
    29. WasmEdge_StringDelete(FuncName);
    30. return 0;
    31. }

    Then you can compile and run: (the 5th Fibonacci number is 8 in 0-based index)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Get the result: 8
  2. Instantiate and run WASM functions manually

    Besides the above example, developers can run the WASM functions step-by-step with VM context APIs:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. /* Create the configure context and add the WASI support. */
    5. /* This step is not necessary unless you need the WASI support. */
    6. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    7. WasmEdge_ConfigureAddHostRegistration(ConfCxt, WasmEdge_HostRegistration_Wasi);
    8. /* The configure and store context to the VM creation can be NULL. */
    9. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(ConfCxt, NULL);
    10. /* The parameters and returns arrays. */
    11. WasmEdge_Value Params[1] = { WasmEdge_ValueGenI32(10) };
    12. WasmEdge_Value Returns[1];
    13. /* Function name. */
    14. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    15. /* Result. */
    16. WasmEdge_Result Res;
    17. /* Step 1: Load WASM file. */
    18. Res = WasmEdge_VMLoadWasmFromFile(VMCxt, "fibonacci.wasm");
    19. /*
    20. * Developers can load the WASM binary from buffer with the `WasmEdge_VMLoadWasmFromBuffer()` API,
    21. * or from `WasmEdge_ASTModuleContext` object with the `WasmEdge_VMLoadWasmFromASTModule()` API.
    22. */
    23. if (!WasmEdge_ResultOK(Res)) {
    24. printf("Loading phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    25. return 1;
    26. }
    27. /* Step 2: Validate the WASM module. */
    28. Res = WasmEdge_VMValidate(VMCxt);
    29. if (!WasmEdge_ResultOK(Res)) {
    30. printf("Validation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    31. return 1;
    32. }
    33. /* Step 3: Instantiate the WASM module. */
    34. Res = WasmEdge_VMInstantiate(VMCxt);
    35. /*
    36. * Developers can load, validate, and instantiate another WASM module to replace the
    37. * instantiated one. In this case, the old module will be cleared, but the registered
    38. * modules are still kept.
    39. */
    40. if (!WasmEdge_ResultOK(Res)) {
    41. printf("Instantiation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    42. return 1;
    43. }
    44. /* Step 4: Execute WASM functions. You can execute functions repeatedly after instantiation. */
    45. Res = WasmEdge_VMExecute(VMCxt, FuncName, Params, 1, Returns, 1);
    46. if (WasmEdge_ResultOK(Res)) {
    47. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    48. } else {
    49. printf("Execution phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    50. }
    51. /* Resources deallocations. */
    52. WasmEdge_VMDelete(VMCxt);
    53. WasmEdge_ConfigureDelete(ConfCxt);
    54. WasmEdge_StringDelete(FuncName);
    55. return 0;
    56. }

    Then you can compile and run: (the 10th Fibonacci number is 89 in 0-based index)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Get the result: 89

    The following graph explains the status of the VM context.

    1. |========================|
    2. |------->| VM: Initiated |
    3. | |========================|
    4. | |
    5. | LoadWasm
    6. | |
    7. | v
    8. | |========================|
    9. |--------| VM: Loaded |<-------|
    10. | |========================| |
    11. | | ^ |
    12. | Validate | |
    13. Cleanup | LoadWasm |
    14. | v | LoadWasm
    15. | |========================| |
    16. |--------| VM: Validated | |
    17. | |========================| |
    18. | | ^ |
    19. | Instantiate | |
    20. | | RegisterModule |
    21. | v | |
    22. | |========================| |
    23. |--------| VM: Instantiated |--------|
    24. |========================|
    25. | ^
    26. | |
    27. --------------
    28. Instantiate, Execute, ExecuteRegistered

    The status of the VM context would be Inited when created. After loading WASM successfully, the status will be Loaded. After validating WASM successfully, the status will be Validated. After instantiating WASM successfully, the status will be Instantiated, and developers can invoke functions. Developers can register WASM or import objects in any status, but they should instantiate WASM again. Developers can also load WASM in any status, and they should validate and instantiate the WASM module before function invocation. When in the Instantiated status, developers can instantiate the WASM module again to reset the old WASM runtime structures.

VM Creations

The VM creation API accepts the Configure context and the Store context. If developers only need the default settings, just pass NULL to the creation API. The details of the Store context will be introduced in Store.

  1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
  2. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
  3. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(ConfCxt, StoreCxt);
  4. /* The caller should guarantee the life cycle if the store context. */
  5. WasmEdge_StatisticsContext *StatCxt = WasmEdge_VMGetStatisticsContext(VMCxt);
  6. /* The VM context already contains the statistics context and can be retrieved by this API. */
  7. /*
  8. * Note that the retrieved store and statistics contexts from the VM contexts by VM APIs
  9. * should __NOT__ be destroyed and owned by the VM contexts.
  10. */
  11. WasmEdge_VMDelete(VMCxt);
  12. WasmEdge_StoreDelete(StoreCxt);
  13. WasmEdge_ConfigureDelete(ConfCxt);

Preregistrations

WasmEdge provides the following built-in pre-registrations.

  1. WASI (WebAssembly System Interface)

    Developers can turn on the WASI support for VM in the Configure context.

    1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    2. WasmEdge_ConfigureAddHostRegistration(ConfCxt, WasmEdge_HostRegistration_Wasi);
    3. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(ConfCxt, NULL);
    4. /* The following API can retrieve the pre-registration import objects from the VM context. */
    5. /* This API will return `NULL` if the corresponding pre-registration is not set into the configuration. */
    6. WasmEdge_ImportObjectContext *WasiObject =
    7. WasmEdge_VMGetImportModuleContext(VMCxt, WasmEdge_HostRegistration_Wasi);
    8. /* Initialize the WASI. */
    9. WasmEdge_ImportObjectInitWASI(WasiObject, /* ... ignored */ );
    10. WasmEdge_VMDelete(VMCxt);
    11. WasmEdge_ConfigureDelete(ConfCxt);

    And also can create the WASI import object from API. The details will be introduced in the Host Functions and the Host Module Registrations.

  2. WasmEdge_Process

    This pre-registration is for the process interface for WasmEdge on Rust sources. After turning on this pre-registration, the VM will support the wasmedge_process host functions.

    1. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
    2. WasmEdge_ConfigureAddHostRegistration(ConfCxt, WasmEdge_HostRegistration_WasmEdge_Process);
    3. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(ConfCxt, NULL);
    4. /* The following API can retrieve the pre-registration import objects from the VM context. */
    5. /* This API will return `NULL` if the corresponding pre-registration is not set into the configuration. */
    6. WasmEdge_ImportObjectContext *ProcObject =
    7. WasmEdge_VMGetImportModuleContext(VMCxt, WasmEdge_HostRegistration_WasmEdge_Process);
    8. /* Initialize the WasmEdge_Process. */
    9. WasmEdge_ImportObjectInitWasmEdgeProcess(ProcObject, /* ... ignored */ );
    10. WasmEdge_VMDelete(VMCxt);
    11. WasmEdge_ConfigureDelete(ConfCxt);

    And also can create the WasmEdge_Process import object from API. The details will be introduced in the Host Functions and the Host Module Registrations.

Host Module Registrations

Host functions are functions outside WebAssembly and passed to WASM modules as imports. In WasmEdge, the host functions are composed into host modules as WasmEdge_ImportObjectContext objects with module names. Please refer to the Host Functions in WasmEdge Runtime for the details. In this chapter, we show the example for registering the host modules into a VM context.

  1. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
  2. WasmEdge_ImportObjectContext *WasiObject =
  3. WasmEdge_ImportObjectCreateWASI( /* ... ignored ... */ );
  4. /* You can also create and register the WASI host modules by this API. */
  5. WasmEdge_Result Res = WasmEdge_VMRegisterModuleFromImport(VMCxt, WasiObject);
  6. /* The result status should be checked. */
  7. WasmEdge_ImportObjectDelete(WasiObject);
  8. /* The created import objects should be deleted. */
  9. WasmEdge_VMDelete(VMCxt);

WASM Registrations And Executions

In WebAssembly, the instances in WASM modules can be exported and can be imported by other WASM modules. WasmEdge VM provides APIs for developers to register and export any WASM modules, and execute the functions or host functions in the registered WASM modules.

  1. Register the WASM modules with exported module names

    Unless the import objects have already contained the module names, every WASM module should be named uniquely when registering. Assume that the WASM file fibonacci.wasm is copied into the current directory.

    1. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    2. WasmEdge_String ModName = WasmEdge_StringCreateByCString("mod");
    3. WasmEdge_Result Res = WasmEdge_VMRegisterModuleFromFile(VMCxt, ModName, "fibonacci.wasm");
    4. /*
    5. * Developers can register the WASM module from buffer with the `WasmEdge_VMRegisterModuleFromBuffer()` API,
    6. * or from `WasmEdge_ASTModuleContext` object with the `WasmEdge_VMRegisterModuleFromASTModule()` API.
    7. */
    8. /*
    9. * The result status should be checked.
    10. * The error will occur if the WASM module instantiation failed or the module name conflicts.
    11. */
    12. WasmEdge_StringDelete(ModName);
    13. WasmEdge_VMDelete(VMCxt);
  2. Execute the functions in registered WASM modules

    Assume that the C file test.c is as follows:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    5. /* The parameters and returns arrays. */
    6. WasmEdge_Value Params[1] = { WasmEdge_ValueGenI32(20) };
    7. WasmEdge_Value Returns[1];
    8. /* Names. */
    9. WasmEdge_String ModName = WasmEdge_StringCreateByCString("mod");
    10. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    11. /* Result. */
    12. WasmEdge_Result Res;
    13. /* Register the WASM module into VM. */
    14. Res = WasmEdge_VMRegisterModuleFromFile(VMCxt, ModName, "fibonacci.wasm");
    15. /*
    16. * Developers can register the WASM module from buffer with the `WasmEdge_VMRegisterModuleFromBuffer()` API,
    17. * or from `WasmEdge_ASTModuleContext` object with the `WasmEdge_VMRegisterModuleFromASTModule()` API.
    18. */
    19. if (!WasmEdge_ResultOK(Res)) {
    20. printf("WASM registration failed: %s\n", WasmEdge_ResultGetMessage(Res));
    21. return 1;
    22. }
    23. /*
    24. * The function "fib" in the "fibonacci.wasm" was exported with the module name "mod".
    25. * As the same as host functions, other modules can import the function `"mod" "fib"`.
    26. */
    27. /*
    28. * Execute WASM functions in registered modules.
    29. * Unlike the execution of functions, the registered functions can be invoked without
    30. * `WasmEdge_VMInstantiate()` because the WASM module was instantiated when registering.
    31. * Developers can also invoke the host functions directly with this API.
    32. */
    33. Res = WasmEdge_VMExecuteRegistered(VMCxt, ModName, FuncName, Params, 1, Returns, 1);
    34. if (WasmEdge_ResultOK(Res)) {
    35. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    36. } else {
    37. printf("Execution phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    38. }
    39. WasmEdge_StringDelete(ModName);
    40. WasmEdge_StringDelete(FuncName);
    41. WasmEdge_VMDelete(VMCxt);
    42. return 0;
    43. }

    Then you can compile and run: (the 20th Fibonacci number is 89 in 0-based index)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Get the result: 10946

Asynchronous Execution

  1. Asynchronously run WASM functions rapidly

    Assume that the WASM file fibonacci.wasm is copied into the current directory, and the C file test.c is as following:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. /* Create the VM context. */
    5. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    6. /* The parameters and returns arrays. */
    7. WasmEdge_Value Params[1] = { WasmEdge_ValueGenI32(20) };
    8. WasmEdge_Value Returns[1];
    9. /* Function name. */
    10. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    11. /* Asynchronously run the WASM function from file and get the `WasmEdge_Async` object. */
    12. WasmEdge_Async *Async = WasmEdge_VMAsyncRunWasmFromFile(VMCxt, "fibonacci.wasm", FuncName, Params, 1);
    13. /*
    14. * Developers can run the WASM binary from buffer with the `WasmEdge_VMAsyncRunWasmFromBuffer()` API,
    15. * or from `WasmEdge_ASTModuleContext` object with the `WasmEdge_VMAsyncRunWasmFromASTModule()` API.
    16. */
    17. /* Wait for the execution. */
    18. WasmEdge_AsyncWait(Async);
    19. /*
    20. * Developers can also use the `WasmEdge_AsyncGetReturnsLength()` or `WasmEdge_AsyncGet()` APIs
    21. * to wait for the asynchronous execution. These APIs will wait until the execution finished.
    22. */
    23. /* Check the return values length. */
    24. uint32_t Arity = WasmEdge_AsyncGetReturnsLength(Async);
    25. /* The `Arity` should be 1. Developers can skip this step if they have known the return arity. */
    26. /* Get the result. */
    27. WasmEdge_Result Res = WasmEdge_AsyncGet(Async, Returns, Arity);
    28. if (WasmEdge_ResultOK(Res)) {
    29. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    30. } else {
    31. printf("Error message: %s\n", WasmEdge_ResultGetMessage(Res));
    32. }
    33. /* Resources deallocations. */
    34. WasmEdge_AsyncDelete(Async);
    35. WasmEdge_VMDelete(VMCxt);
    36. WasmEdge_StringDelete(FuncName);
    37. return 0;
    38. }

    Then you can compile and run: (the 20th Fibonacci number is 10946 in 0-based index)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Get the result: 10946
  2. Instantiate and asynchronously run WASM functions manually

    Besides the above example, developers can run the WASM functions step-by-step with VM context APIs:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. /* Create the VM context. */
    5. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    6. /* The parameters and returns arrays. */
    7. WasmEdge_Value Params[1] = { WasmEdge_ValueGenI32(25) };
    8. WasmEdge_Value Returns[1];
    9. /* Function name. */
    10. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    11. /* Result. */
    12. WasmEdge_Result Res;
    13. /* Step 1: Load WASM file. */
    14. Res = WasmEdge_VMLoadWasmFromFile(VMCxt, "fibonacci.wasm");
    15. /*
    16. * Developers can load the WASM binary from buffer with the `WasmEdge_VMLoadWasmFromBuffer()` API,
    17. * or from `WasmEdge_ASTModuleContext` object with the `WasmEdge_VMLoadWasmFromASTModule()` API.
    18. */
    19. if (!WasmEdge_ResultOK(Res)) {
    20. printf("Loading phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    21. return 1;
    22. }
    23. /* Step 2: Validate the WASM module. */
    24. Res = WasmEdge_VMValidate(VMCxt);
    25. if (!WasmEdge_ResultOK(Res)) {
    26. printf("Validation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    27. return 1;
    28. }
    29. /* Step 3: Instantiate the WASM module. */
    30. Res = WasmEdge_VMInstantiate(VMCxt);
    31. /*
    32. * Developers can load, validate, and instantiate another WASM module to replace the
    33. * instantiated one. In this case, the old module will be cleared, but the registered
    34. * modules are still kept.
    35. */
    36. if (!WasmEdge_ResultOK(Res)) {
    37. printf("Instantiation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    38. return 1;
    39. }
    40. /* Step 4: Asynchronously execute the WASM function and get the `WasmEdge_Async` object. */
    41. WasmEdge_Async *Async = WasmEdge_VMAsyncExecute(VMCxt, FuncName, Params, 1);
    42. /*
    43. * Developers can execute functions repeatedly after instantiation.
    44. * For invoking the registered functions, you can use the `WasmEdge_VMAsyncExecuteRegistered()` API.
    45. */
    46. /* Wait and check the return values length. */
    47. uint32_t Arity = WasmEdge_AsyncGetReturnsLength(Async);
    48. /* The `Arity` should be 1. Developers can skip this step if they have known the return arity. */
    49. /* Get the result. */
    50. Res = WasmEdge_AsyncGet(Async, Returns, Arity);
    51. if (WasmEdge_ResultOK(Res)) {
    52. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    53. } else {
    54. printf("Execution phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
    55. }
    56. /* Resources deallocations. */
    57. WasmEdge_AsyncDelete(Async);
    58. WasmEdge_VMDelete(VMCxt);
    59. WasmEdge_StringDelete(FuncName);
    60. }

    Then you can compile and run: (the 25th Fibonacci number is 121393 in 0-based index)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Get the result: 121393

Instance Tracing

Sometimes the developers may have requirements to get the instances of the WASM runtime. The VM context supplies the APIs to retrieve the instances.

  1. Store

    If the VM context is created without assigning a Store context, the VM context will allocate and own a Store context.

    1. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    2. WasmEdge_StoreContext *StoreCxt = WasmEdge_VMGetStoreContext(VMCxt);
    3. /* The object should __NOT__ be deleted by `WasmEdge_StoreDelete()`. */
    4. WasmEdge_VMDelete(VMCxt);

    Developers can also create the VM context with a Store context. In this case, developers should guarantee the life cycle of the Store context. Please refer to the Store Contexts for the details about the Store context APIs.

    1. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    2. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, StoreCxt);
    3. WasmEdge_StoreContext *StoreCxtMock = WasmEdge_VMGetStoreContext(VMCxt);
    4. /* The `StoreCxt` and the `StoreCxtMock` are the same. */
    5. WasmEdge_VMDelete(VMCxt);
    6. WasmEdge_StoreDelete(StoreCxt);
  2. List exported functions

    After the WASM module instantiation, developers can use the WasmEdge_VMExecute() API to invoke the exported WASM functions. For this purpose, developers may need information about the exported WASM function list. Please refer to the Instances in runtime for the details about the function types. Assume that the WASM file fibonacci.wasm is copied into the current directory, and the C file test.c is as following:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. int main() {
    4. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    5. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, StoreCxt);
    6. WasmEdge_VMLoadWasmFromFile(VMCxt, "fibonacci.wasm");
    7. WasmEdge_VMValidate(VMCxt);
    8. WasmEdge_VMInstantiate(VMCxt);
    9. /* List the exported functions. */
    10. /* Get the number of exported functions. */
    11. uint32_t FuncNum = WasmEdge_VMGetFunctionListLength(VMCxt);
    12. /* Create the name buffers and the function type buffers. */
    13. const uint32_t BUF_LEN = 256;
    14. WasmEdge_String FuncNames[BUF_LEN];
    15. WasmEdge_FunctionTypeContext *FuncTypes[BUF_LEN];
    16. /*
    17. * Get the export function list.
    18. * If the function list length is larger than the buffer length, the overflowed data will be discarded.
    19. * The `FuncNames` and `FuncTypes` can be NULL if developers don't need them.
    20. */
    21. uint32_t RealFuncNum = WasmEdge_VMGetFunctionList(VMCxt, FuncNames, FuncTypes, BUF_LEN);
    22. for (uint32_t I = 0; I < RealFuncNum && I < BUF_LEN; I++) {
    23. char Buf[BUF_LEN];
    24. uint32_t Size = WasmEdge_StringCopy(FuncNames[I], Buf, sizeof(Buf));
    25. printf("Get exported function string length: %u, name: %s\n", Size, Buf);
    26. /*
    27. * The function names should be __NOT__ destroyed.
    28. * The returned function type contexts should __NOT__ be destroyed.
    29. */
    30. }
    31. return 0;
    32. }

    Then you can compile and run: (the only exported function in fibonacci.wasm is fib)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Get exported function string length: 3, name: fib

    If developers want to get the exported function names in the registered WASM modules, please retrieve the Store context from the VM context and refer to the APIs of Store Contexts to list the registered functions by the module name.

  3. Get function types

    The VM context provides APIs to find the function type by function name. Please refer to the Instances in runtime for the details about the function types.

    1. /*
    2. * ...
    3. * Assume that a WASM module is instantiated in `VMCxt`.
    4. */
    5. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    6. const WasmEdge_FunctionTypeContext *FuncType = WasmEdge_VMGetFunctionType(VMCxt, FuncName);
    7. /*
    8. * Developers can get the function types of functions in the registered modules
    9. * via the `WasmEdge_VMGetFunctionTypeRegistered()` API with the module name.
    10. * If the function is not found, these APIs will return `NULL`.
    11. * The returned function type contexts should __NOT__ be destroyed.
    12. */
    13. WasmEdge_StringDelete(FuncName);

WasmEdge Runtime

In this partition, we will introduce the objects of WasmEdge runtime manually.

WASM Execution Example Step-By-Step

Besides the WASM execution through the VM context, developers can execute the WASM functions or instantiate WASM modules step-by-step with the Loader, Validator, Executor, and Store contexts. Assume that the WASM file fibonacci.wasm is copied into the current directory, and the C file test.c is as following:

  1. #include <wasmedge/wasmedge.h>
  2. #include <stdio.h>
  3. int main() {
  4. /* Create the configure context. This step is not necessary because we didn't adjust any setting. */
  5. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
  6. /* Create the statistics context. This step is not necessary if the statistics in runtime is not needed. */
  7. WasmEdge_StatisticsContext *StatCxt = WasmEdge_StatisticsCreate();
  8. /* Create the store context. The store context is the WASM runtime structure core. */
  9. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
  10. /* Result. */
  11. WasmEdge_Result Res;
  12. /* Create the loader context. The configure context can be NULL. */
  13. WasmEdge_LoaderContext *LoadCxt = WasmEdge_LoaderCreate(ConfCxt);
  14. /* Create the validator context. The configure context can be NULL. */
  15. WasmEdge_ValidatorContext *ValidCxt = WasmEdge_ValidatorCreate(ConfCxt);
  16. /* Create the executor context. The configure context and the statistics context can be NULL. */
  17. WasmEdge_ExecutorContext *ExecCxt = WasmEdge_ExecutorCreate(ConfCxt, StatCxt);
  18. /* Load the WASM file or the compiled-WASM file and convert into the AST module context. */
  19. WasmEdge_ASTModuleContext *ASTCxt = NULL;
  20. Res = WasmEdge_LoaderParseFromFile(LoadCxt, &ASTCxt, "fibonacci.wasm");
  21. if (!WasmEdge_ResultOK(Res)) {
  22. printf("Loading phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  23. return 1;
  24. }
  25. /* Validate the WASM module. */
  26. Res = WasmEdge_ValidatorValidate(ValidCxt, ASTCxt);
  27. if (!WasmEdge_ResultOK(Res)) {
  28. printf("Validation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  29. return 1;
  30. }
  31. /* Instantiate the WASM module into store context. */
  32. Res = WasmEdge_ExecutorInstantiate(ExecCxt, StoreCxt, ASTCxt);
  33. if (!WasmEdge_ResultOK(Res)) {
  34. printf("Instantiation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  35. return 1;
  36. }
  37. /* Try to list the exported functions of the instantiated WASM module. */
  38. uint32_t FuncNum = WasmEdge_StoreListFunctionLength(StoreCxt);
  39. /* Create the name buffers. */
  40. const uint32_t BUF_LEN = 256;
  41. WasmEdge_String FuncNames[BUF_LEN];
  42. /* If the list length is larger than the buffer length, the overflowed data will be discarded. */
  43. uint32_t RealFuncNum = WasmEdge_StoreListFunction(StoreCxt, FuncNames, BUF_LEN);
  44. for (uint32_t I = 0; I < RealFuncNum && I < BUF_LEN; I++) {
  45. char Buf[BUF_LEN];
  46. uint32_t Size = WasmEdge_StringCopy(FuncNames[I], Buf, sizeof(Buf));
  47. printf("Get exported function string length: %u, name: %s\n", Size, Buf);
  48. /* The function names should __NOT__ be destroyed. */
  49. }
  50. /* The parameters and returns arrays. */
  51. WasmEdge_Value Params[1] = { WasmEdge_ValueGenI32(18) };
  52. WasmEdge_Value Returns[1];
  53. /* Function name. */
  54. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
  55. /* Invoke the WASM fnction. */
  56. Res = WasmEdge_ExecutorInvoke(ExecCxt, StoreCxt, FuncName, Params, 1, Returns, 1);
  57. if (WasmEdge_ResultOK(Res)) {
  58. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
  59. } else {
  60. printf("Execution phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  61. }
  62. /* Resources deallocations. */
  63. WasmEdge_StringDelete(FuncName);
  64. WasmEdge_ASTModuleDelete(ASTCxt);
  65. WasmEdge_LoaderDelete(LoadCxt);
  66. WasmEdge_ValidatorDelete(ValidCxt);
  67. WasmEdge_ExecutorDelete(ExecCxt);
  68. WasmEdge_ConfigureDelete(ConfCxt);
  69. WasmEdge_StoreDelete(StoreCxt);
  70. WasmEdge_StatisticsDelete(StatCxt);
  71. return 0;
  72. }

Then you can compile and run: (the 18th Fibonacci number is 4181 in 0-based index)

  1. $ gcc test.c -lwasmedge_c
  2. $ ./a.out
  3. Get exported function string length: 3, name: fib
  4. Get the result: 4181

Loader

The Loader context loads the WASM binary from files or buffers. Both the WASM and the compiled-WASM from the WasmEdge AOT Compiler are supported.

  1. uint8_t Buf[4096];
  2. /* ... Read the WASM code to the buffer. */
  3. uint32_t FileSize = ...;
  4. /* The `FileSize` is the length of the WASM code. */
  5. /* Developers can adjust settings in the configure context. */
  6. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
  7. /* Create the loader context. The configure context can be NULL. */
  8. WasmEdge_LoaderContext *LoadCxt = WasmEdge_LoaderCreate(ConfCxt);
  9. WasmEdge_ASTModuleContext *ASTCxt = NULL;
  10. WasmEdge_Result Res;
  11. /* Load WASM or compiled-WASM from the file. */
  12. Res = WasmEdge_LoaderParseFromFile(LoadCxt, &ASTCxt, "fibonacci.wasm");
  13. if (!WasmEdge_ResultOK(Res)) {
  14. printf("Loading phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  15. }
  16. /* The output AST module context should be destroyed. */
  17. WasmEdge_ASTModuleDelete(ASTCxt);
  18. /* Load WASM or compiled-WASM from the buffer. */
  19. Res = WasmEdge_LoaderParseFromBuffer(LoadCxt, &ASTCxt, Buf, FileSize);
  20. if (!WasmEdge_ResultOK(Res)) {
  21. printf("Loading phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  22. }
  23. /* The output AST module context should be destroyed. */
  24. WasmEdge_ASTModuleDelete(ASTCxt);
  25. WasmEdge_LoaderDelete(LoadCxt);
  26. WasmEdge_ConfigureDelete(ConfCxt);

Validator

The Validator context can validate the WASM module. Every WASM module should be validated before instantiation.

  1. /*
  2. * ...
  3. * Assume that the `ASTCxt` is the output AST module context from the loader context.
  4. * Assume that the `ConfCxt` is the configure context.
  5. */
  6. /* Create the validator context. The configure context can be NULL. */
  7. WasmEdge_ValidatorContext *ValidCxt = WasmEdge_ValidatorCreate(ConfCxt);
  8. WasmEdge_Result Res = WasmEdge_ValidatorValidate(ValidCxt, ASTCxt);
  9. if (!WasmEdge_ResultOK(Res)) {
  10. printf("Validation phase failed: %s\n", WasmEdge_ResultGetMessage(Res));
  11. }
  12. WasmEdge_ValidatorDelete(ValidCxt);

Executor

The Executor context is the executor for both WASM and compiled-WASM. This object should work base on the Store context. For the details of the Store context, please refer to the next chapter.

  1. Register modules

    As the same of registering host modules or importing WASM modules in VM context, developers can register Import Object or AST module contexts into the Store context by the Executor APIs. For the details of import objects, please refer to the Host Functions.

    1. /*
    2. * ...
    3. * Assume that the `ASTCxt` is the output AST module context from the loader context
    4. * and has passed the validation.
    5. * Assume that the `ConfCxt` is the configure context.
    6. */
    7. /* Create the statistics context. This step is not necessary. */
    8. WasmEdge_StatisticsContext *StatCxt = WasmEdge_StatisticsCreate();
    9. /* Create the executor context. The configure and the statistics contexts can be NULL. */
    10. WasmEdge_ExecutorContext *ExecCxt = WasmEdge_ExecutorCreate(ConfCxt, StatCxt);
    11. /* Create the store context. The store context is the WASM runtime structure core. */
    12. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    13. /* Result. */
    14. WasmEdge_Result Res;
    15. /* Register the WASM module into store with the export module name "mod". */
    16. WasmEdge_String ModName = WasmEdge_StringCreateByCString("mod");
    17. Res = WasmEdge_ExecutorRegisterModule(ExecCxt, StoreCxt, ASTCxt, ModName);
    18. if (!WasmEdge_ResultOK(Res)) {
    19. printf("WASM registration failed: %s\n", WasmEdge_ResultGetMessage(Res));
    20. }
    21. WasmEdge_StringDelete(ModName);
    22. /*
    23. * Assume that the `ImpCxt` is the import object context for host functions.
    24. */
    25. WasmEdge_ImportObjectContext *ImpCxt = ...;
    26. /* The import module context has already contained the export module name. */
    27. Res = WasmEdge_ExecutorRegisterImport(ExecCxt, StoreCxt, ImpCxt);
    28. if (!WasmEdge_ResultOK(Res)) {
    29. printf("Import object registration failed: %s\n", WasmEdge_ResultGetMessage(Res));
    30. }
    31. WasmEdge_ImportObjectDelete(ImpCxt);
    32. WasmEdge_ExecutorDelete(ExecCxt);
    33. WasmEdge_StatisticsDelete(StatCxt);
    34. WasmEdge_StoreDelete(StoreCxt);
  2. Instantiate modules

    WASM or compiled-WASM modules should be instantiated before the function invocation. Note that developers can only instantiate one module into the Store context, and in that case, the old instantiated module will be cleaned. Before instantiating a WASM module, please check the import section for ensuring the imports are registered into the Store context.

    1. /*
    2. * ...
    3. * Assume that the `ASTCxt` is the output AST module context from the loader context
    4. * and has passed the validation.
    5. * Assume that the `ConfCxt` is the configure context.
    6. */
    7. /* Create the statistics context. This step is not necessary. */
    8. WasmEdge_StatisticsContext *StatCxt = WasmEdge_StatisticsCreate();
    9. /* Create the executor context. The configure and the statistics contexts can be NULL. */
    10. WasmEdge_ExecutorContext *ExecCxt = WasmEdge_ExecutorCreate(ConfCxt, StatCxt);
    11. /* Create the store context. The store context is the WASM runtime structure core. */
    12. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    13. /* Instantiate the WASM module. */
    14. WasmEdge_Result Res = WasmEdge_ExecutorInstantiate(ExecCxt, StoreCxt, ASTCxt);
    15. if (!WasmEdge_ResultOK(Res)) {
    16. printf("WASM instantiation failed: %s\n", WasmEdge_ResultGetMessage(Res));
    17. }
    18. WasmEdge_ExecutorDelete(ExecCxt);
    19. WasmEdge_StatisticsDelete(StatCxt);
    20. WasmEdge_StoreDelete(StoreCxt);
  3. Invoke functions

    As the same as function invocation via the VM context, developers can invoke the functions of the instantiated or registered modules. The APIs, WasmEdge_ExecutorInvoke() and WasmEdge_ExecutorInvokeRegistered(), are similar as the APIs of the VM context. Please refer to the VM context workflows for details.

AST Module

The AST Module context presents the loaded structure from a WASM file or buffer. Developer will get this object after loading a WASM file or buffer from Loader. Before instantiation, developers can also query the imports and exports of an AST Module context.

  1. WasmEdge_ASTModuleContext *ASTCxt = ...;
  2. /* Assume that a WASM is loaded into an AST module context. */
  3. /* Create the import type context buffers. */
  4. const uint32_t BUF_LEN = 256;
  5. const WasmEdge_ImportTypeContext *ImpTypes[BUF_LEN];
  6. uint32_t ImportNum = WasmEdge_ASTModuleListImportsLength(ASTCxt);
  7. /* If the list length is larger than the buffer length, the overflowed data will be discarded. */
  8. uint32_t RealImportNum = WasmEdge_ASTModuleListImports(ASTCxt, ImpTypes, BUF_LEN);
  9. for (uint32_t I = 0; I < RealImportNum && I < BUF_LEN; I++) {
  10. /* Working with the import type `ImpTypes[I]` ... */
  11. }
  12. /* Create the export type context buffers. */
  13. const WasmEdge_ExportTypeContext *ExpTypes[BUF_LEN];
  14. uint32_t ExportNum = WasmEdge_ASTModuleListExportsLength(ASTCxt);
  15. /* If the list length is larger than the buffer length, the overflowed data will be discarded. */
  16. uint32_t RealExportNum = WasmEdge_ASTModuleListExports(ASTCxt, ExpTypes, BUF_LEN);
  17. for (uint32_t I = 0; I < RealExportNum && I < BUF_LEN; I++) {
  18. /* Working with the export type `ExpTypes[I]` ... */
  19. }
  20. WasmEdge_ASTModuleDelete(ASTCxt);
  21. /* After deletion of `ASTCxt`, all data queried from the `ASTCxt` should not be accessed. */

Store

Store is the runtime structure for the representation of all instances of Functions, Tables, Memorys, and Globals that have been allocated during the lifetime of the abstract machine. The Store context in WasmEdge provides APIs to list the exported instances with their names or find the instances by exported names. For adding instances into Store contexts, please instantiate or register WASM modules or Import Object contexts via the Executor context.

  1. List instances

    1. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    2. /* ... Instantiate a WASM module via the executor context. */
    3. ...
    4. /* Try to list the exported functions of the instantiated WASM module. */
    5. /* Take the function instances for example here. */
    6. uint32_t FuncNum = WasmEdge_StoreListFunctionLength(StoreCxt);
    7. /* Create the name buffers. */
    8. const uint32_t BUF_LEN = 256;
    9. WasmEdge_String FuncNames[BUF_LEN];
    10. /* If the list length is larger than the buffer length, the overflowed data will be discarded. */
    11. uint32_t RealFuncNum = WasmEdge_StoreListFunction(StoreCxt, FuncNames, BUF_LEN);
    12. for (uint32_t I = 0; I < RealFuncNum && I < BUF_LEN; I++) {
    13. /* Working with the function name `FuncNames[I]` ... */
    14. /* The function names should __NOT__ be destroyed. */
    15. }

    Developers can list the function instance exported names of the registered modules via the WasmEdge_StoreListFunctionRegisteredLength() and the WasmEdge_StoreListFunctionRegistered() APIs with the module name.

  2. Find instances

    1. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    2. /* ... Instantiate a WASM module via the executor context. */
    3. ...
    4. /* Try to find the exported instance of the instantiated WASM module. */
    5. /* Take the function instances for example here. */
    6. /* Function name. */
    7. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("fib");
    8. WasmEdge_FunctionInstanceContext *FuncCxt = WasmEdge_StoreFindFunction(StoreCxt, FuncName);
    9. /* `FuncCxt` will be `NULL` if the function not found. */
    10. /* The returned instance is owned by the store context and should __NOT__ be destroyed. */
    11. WasmEdge_StringDelete(FuncName);

    Developers can retrieve the exported function instances of the registered modules via the WasmEdge_StoreFindFunctionRegistered() API with the module name.

  3. List registered modules

    With the module names, developers can list the exported instances of the registered modules with their names.

    1. WasmEdge_StoreContext *StoreCxt = WasmEdge_StoreCreate();
    2. /* ... Register a WASM module via the executor context. */
    3. ...
    4. /* Try to list the registered WASM modules. */
    5. uint32_t ModNum = WasmEdge_StoreListModuleLength(StoreCxt);
    6. /* Create the name buffers. */
    7. const uint32_t BUF_LEN = 256;
    8. WasmEdge_String ModNames[BUF_LEN];
    9. /* If the list length is larger than the buffer length, the overflowed data will be discarded. */
    10. uint32_t RealModNum = WasmEdge_StoreListModule(StoreCxt, ModNames, BUF_LEN);
    11. for (uint32_t I = 0; I < RealModNum && I < BUF_LEN; I++) {
    12. /* Working with the module name `ModNames[I]` ... */
    13. /* The module names should __NOT__ be destroyed. */
    14. }

Instances

The instances are the runtime structures of WASM. Developers can retrieve the instances from the Store contexts. The Store contexts will allocate instances when a WASM module or Import Object is registered or instantiated through the Executor. A single instance can be allocated by its creation function. Developers can construct instances into an Import Object for registration. Please refer to the Host Functions for details. The instances created by their creation functions should be destroyed, EXCEPT they are added into an Import Object context.

  1. Function instance

    Host functions are functions outside WebAssembly and passed to WASM modules as imports. In WasmEdge, developers can create the Function contexts for host functions and add them into an Import Object context for registering into a VM or a Store. For both host functions and the functions get from Store, developers can retrieve the Function Type from the Function contexts. For the details of the Host Function guide, please refer to the next chapter.

    1. /* Retrieve the function instance from the store context. */
    2. WasmEdge_FunctionInstanceContext *FuncCxt = ...;
    3. WasmEdge_FunctionTypeContext *FuncTypeCxt = WasmEdge_FunctionInstanceGetFunctionType(FuncCxt);
    4. /* The `FuncTypeCxt` is owned by the `FuncCxt` and should __NOT__ be destroyed. */
  2. Table instance

    In WasmEdge, developers can create the Table contexts and add them into an Import Object context for registering into a VM or a Store. The Table contexts supply APIs to control the data in table instances.

    1. WasmEdge_Limit TabLimit = {.HasMax = true, .Min = 10, .Max = 20};
    2. /* Create the table type with limit and the `FuncRef` element type. */
    3. WasmEdge_TableTypeContext *TabTypeCxt = WasmEdge_TableTypeCreate(WasmEdge_RefType_FuncRef, TabLimit);
    4. /* Create the table instance with table type. */
    5. WasmEdge_TableInstanceContext *HostTable = WasmEdge_TableInstanceCreate(TabTypeCxt);
    6. /* Delete the table type. */
    7. WasmEdge_TableTypeDelete(TabTypeCxt);
    8. WasmEdge_Result Res;
    9. WasmEdge_Value Data;
    10. TabTypeCxt = WasmEdge_TableInstanceGetTableType(HostTable);
    11. /* The `TabTypeCxt` got from table instance is owned by the `HostTable` and should __NOT__ be destroyed. */
    12. enum WasmEdge_RefType RefType = WasmEdge_TableTypeGetRefType(TabTypeCxt);
    13. /* `RefType` will be `WasmEdge_RefType_FuncRef`. */
    14. Data = WasmEdge_ValueGenFuncRef(5);
    15. Res = WasmEdge_TableInstanceSetData(HostTable, Data, 3);
    16. /* Set the function index 5 to the table[3]. */
    17. /*
    18. * This will get an "out of bounds table access" error
    19. * because the position (13) is out of the table size (10):
    20. * Res = WasmEdge_TableInstanceSetData(HostTable, Data, 13);
    21. */
    22. Res = WasmEdge_TableInstanceGetData(HostTable, &Data, 3);
    23. /* Get the FuncRef value of the table[3]. */
    24. /*
    25. * This will get an "out of bounds table access" error
    26. * because the position (13) is out of the table size (10):
    27. * Res = WasmEdge_TableInstanceGetData(HostTable, &Data, 13);
    28. */
    29. uint32_t Size = WasmEdge_TableInstanceGetSize(HostTable);
    30. /* `Size` will be 10. */
    31. Res = WasmEdge_TableInstanceGrow(HostTable, 6);
    32. /* Grow the table size of 6, the table size will be 16. */
    33. /*
    34. * This will get an "out of bounds table access" error because
    35. * the size (16 + 6) will reach the table limit(20):
    36. * Res = WasmEdge_TableInstanceGrow(HostTable, 6);
    37. */
    38. WasmEdge_TableInstanceDelete(HostTable);
  3. Memory instance

    In WasmEdge, developers can create the Memory contexts and add them into an Import Object context for registering into a VM or a Store. The Memory contexts supply APIs to control the data in memory instances.

    1. WasmEdge_Limit MemLimit = {.HasMax = true, .Min = 1, .Max = 5};
    2. /* Create the memory type with limit. The memory page size is 64KiB. */
    3. WasmEdge_MemoryTypeContext *MemTypeCxt = WasmEdge_MemoryTypeCreate(MemLimit);
    4. /* Create the memory instance with memory type. */
    5. WasmEdge_MemoryInstanceContext *HostMemory = WasmEdge_MemoryInstanceCreate(MemTypeCxt);
    6. /* Delete the memory type. */
    7. WasmEdge_MemoryTypeDelete(MemTypeCxt);
    8. WasmEdge_Result Res;
    9. uint8_t Buf[256];
    10. Buf[0] = 0xAA;
    11. Buf[1] = 0xBB;
    12. Buf[2] = 0xCC;
    13. Res = WasmEdge_MemoryInstanceSetData(HostMemory, Buf, 0x1000, 3);
    14. /* Set the data[0:2] to the memory[4096:4098]. */
    15. /*
    16. * This will get an "out of bounds memory access" error
    17. * because [65535:65537] is out of 1 page size (65536):
    18. * Res = WasmEdge_MemoryInstanceSetData(HostMemory, Buf, 0xFFFF, 3);
    19. */
    20. Buf[0] = 0;
    21. Buf[1] = 0;
    22. Buf[2] = 0;
    23. Res = WasmEdge_MemoryInstanceGetData(HostMemory, Buf, 0x1000, 3);
    24. /* Get the memory[4096:4098]. Buf[0:2] will be `{0xAA, 0xBB, 0xCC}`. */
    25. /*
    26. * This will get an "out of bounds memory access" error
    27. * because [65535:65537] is out of 1 page size (65536):
    28. * Res = WasmEdge_MemoryInstanceSetData(HostMemory, Buf, 0xFFFF, 3);
    29. */
    30. uint32_t PageSize = WasmEdge_MemoryInstanceGetPageSize(HostMemory);
    31. /* `PageSize` will be 1. */
    32. Res = WasmEdge_MemoryInstanceGrowPage(HostMemory, 2);
    33. /* Grow the page size of 2, the page size of the memory instance will be 3. */
    34. /*
    35. * This will get an "out of bounds memory access" error because
    36. * the page size (3 + 3) will reach the memory limit(5):
    37. * Res = WasmEdge_MemoryInstanceGrowPage(HostMemory, 3);
    38. */
    39. WasmEdge_MemoryInstanceDelete(HostMemory);
  4. Global instance

    In WasmEdge, developers can create the Global contexts and add them into an Import Object context for registering into a VM or a Store. The Global contexts supply APIs to control the value in global instances.

    1. WasmEdge_Value Val = WasmEdge_ValueGenI64(1000);
    2. /* Create the global type with value type and mutation. */
    3. WasmEdge_GlobalTypeContext *GlobTypeCxt = WasmEdge_GlobalTypeCreate(WasmEdge_ValType_I64, WasmEdge_Mutability_Var);
    4. /* Create the global instance with value and global type. */
    5. WasmEdge_GlobalInstanceContext *HostGlobal = WasmEdge_GlobalInstanceCreate(GlobTypeCxt, Val);
    6. /* Delete the global type. */
    7. WasmEdge_GlobalTypeDelete(GlobTypeCxt);
    8. WasmEdge_Result Res;
    9. GlobTypeCxt = WasmEdge_GlobalInstanceGetGlobalType(HostGlobal);
    10. /* The `GlobTypeCxt` got from global instance is owned by the `HostGlobal` and should __NOT__ be destroyed. */
    11. enum WasmEdge_ValType ValType = WasmEdge_GlobalTypeGetValType(GlobTypeCxt);
    12. /* `ValType` will be `WasmEdge_ValType_I64`. */
    13. enum WasmEdge_Mutability ValMut = WasmEdge_GlobalTypeGetMutability(GlobTypeCxt);
    14. /* `ValMut` will be `WasmEdge_Mutability_Var`. */
    15. WasmEdge_GlobalInstanceSetValue(HostGlobal, WasmEdge_ValueGenI64(888));
    16. /*
    17. * Set the value u64(888) to the global.
    18. * This function will do nothing if the value type mismatched or
    19. * the global mutability is `WasmEdge_Mutability_Const`.
    20. */
    21. WasmEdge_Value GlobVal = WasmEdge_GlobalInstanceGetValue(HostGlobal);
    22. /* Get the value (888 now) of the global context. */
    23. WasmEdge_GlobalInstanceDelete(HostGlobal);

Host Functions

Host functions are functions outside WebAssembly and passed to WASM modules as imports. In WasmEdge, developers can create the Function, Memory, Table, and Global contexts and add them into an Import Object context for registering into a VM or a Store.

  1. Host function allocation

    Developers can define C functions with the following function signature as the host function body:

    1. typedef WasmEdge_Result (*WasmEdge_HostFunc_t)(
    2. void *Data,
    3. WasmEdge_MemoryInstanceContext *MemCxt,
    4. const WasmEdge_Value *Params,
    5. WasmEdge_Value *Returns);

    The example of an add host function to add 2 i32 values:

    1. WasmEdge_Result Add(void *, WasmEdge_MemoryInstanceContext *,
    2. const WasmEdge_Value *In, WasmEdge_Value *Out) {
    3. /*
    4. * Params: {i32, i32}
    5. * Returns: {i32}
    6. * Developers should take care about the function type.
    7. */
    8. /* Retrieve the value 1. */
    9. int32_t Val1 = WasmEdge_ValueGetI32(In[0]);
    10. /* Retrieve the value 2. */
    11. int32_t Val2 = WasmEdge_ValueGetI32(In[1]);
    12. /* Output value 1 is Val1 + Val2. */
    13. Out[0] = WasmEdge_ValueGenI32(Val1 + Val2);
    14. /* Return the status of success. */
    15. return WasmEdge_Result_Success;
    16. }

    Then developers can create Function context with the host function body and function type:

    1. enum WasmEdge_ValType ParamList[2] = { WasmEdge_ValType_I32, WasmEdge_ValType_I32 };
    2. enum WasmEdge_ValType ReturnList[1] = { WasmEdge_ValType_I32 };
    3. /* Create a function type: {i32, i32} -> {i32}. */
    4. HostFType = WasmEdge_FunctionTypeCreate(ParamList, 2, ReturnList, 1);
    5. /*
    6. * Create a function context with the function type and host function body.
    7. * The `Cost` parameter can be 0 if developers do not need the cost measuring.
    8. */
    9. WasmEdge_FunctionInstanceContext *HostFunc = WasmEdge_FunctionInstanceCreate(HostFType, Add, NULL, 0);
    10. /*
    11. * The third parameter is the pointer to the additional data.
    12. * Developers should guarantee the life cycle of the data, and it can be
    13. * `NULL` if the external data is not needed.
    14. */
    15. /* If the function instance is not added into an import object context, it should be deleted. */
    16. WasmEdge_FunctionInstanceDelete(HostFunc);
  2. Import object context

    The Import Object context holds an exporting module name and the instances. Developers can add the Function, Memory, Table, and Global instances with their exporting names.

    1. /* Host function body definition. */
    2. WasmEdge_Result Add(void *Data, WasmEdge_MemoryInstanceContext *MemCxt,
    3. const WasmEdge_Value *In, WasmEdge_Value *Out) {
    4. int32_t Val1 = WasmEdge_ValueGetI32(In[0]);
    5. int32_t Val2 = WasmEdge_ValueGetI32(In[1]);
    6. Out[0] = WasmEdge_ValueGenI32(Val1 + Val2);
    7. return WasmEdge_Result_Success;
    8. }
    9. /* Create the import object. */
    10. WasmEdge_String ExportName = WasmEdge_StringCreateByCString("module");
    11. WasmEdge_ImportObjectContext *ImpObj = WasmEdge_ImportObjectCreate(ExportName);
    12. WasmEdge_StringDelete(ExportName);
    13. /* Create and add a function instance into the import object. */
    14. enum WasmEdge_ValType ParamList[2] = { WasmEdge_ValType_I32, WasmEdge_ValType_I32 };
    15. enum WasmEdge_ValType ReturnList[1] = { WasmEdge_ValType_I32 };
    16. WasmEdge_FunctionTypeContext *HostFType =
    17. WasmEdge_FunctionTypeCreate(ParamList, 2, ReturnList, 1);
    18. WasmEdge_FunctionInstanceContext *HostFunc =
    19. WasmEdge_FunctionInstanceCreate(HostFType, Add, NULL, 0);
    20. /*
    21. * The third parameter is the pointer to the additional data object.
    22. * Developers should guarantee the life cycle of the data, and it can be
    23. * `NULL` if the external data is not needed.
    24. */
    25. WasmEdge_FunctionTypeDelete(HostFType);
    26. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("add");
    27. WasmEdge_ImportObjectAddFunction(ImpObj, FuncName, HostFunc);
    28. WasmEdge_StringDelete(FuncName);
    29. /* Create and add a table instance into the import object. */
    30. WasmEdge_Limit TableLimit = {.HasMax = true, .Min = 10, .Max = 20};
    31. WasmEdge_TableTypeContext *HostTType =
    32. WasmEdge_TableTypeCreate(WasmEdge_RefType_FuncRef, TableLimit);
    33. WasmEdge_TableInstanceContext *HostTable = WasmEdge_TableInstanceCreate(HostTType);
    34. WasmEdge_TableTypeDelete(HostTType);
    35. WasmEdge_String TableName = WasmEdge_StringCreateByCString("table");
    36. WasmEdge_ImportObjectAddTable(ImpObj, TableName, HostTable);
    37. WasmEdge_StringDelete(TableName);
    38. /* Create and add a memory instance into the import object. */
    39. WasmEdge_Limit MemoryLimit = {.HasMax = true, .Min = 1, .Max = 2};
    40. WasmEdge_MemoryTypeContext *HostMType = WasmEdge_MemoryTypeCreate(MemoryLimit);
    41. WasmEdge_MemoryInstanceContext *HostMemory = WasmEdge_MemoryInstanceCreate(HostMType);
    42. WasmEdge_MemoryTypeDelete(HostMType);
    43. WasmEdge_String MemoryName = WasmEdge_StringCreateByCString("memory");
    44. WasmEdge_ImportObjectAddMemory(ImpObj, MemoryName, HostMemory);
    45. WasmEdge_StringDelete(MemoryName);
    46. /* Create and add a global instance into the import object. */
    47. WasmEdge_GlobalTypeContext *HostGType =
    48. WasmEdge_GlobalTypeCreate(WasmEdge_ValType_I32, WasmEdge_Mutability_Var);
    49. WasmEdge_GlobalInstanceContext *HostGlobal =
    50. WasmEdge_GlobalInstanceCreate(HostGType, WasmEdge_ValueGenI32(666));
    51. WasmEdge_GlobalTypeDelete(HostGType);
    52. WasmEdge_String GlobalName = WasmEdge_StringCreateByCString("global");
    53. WasmEdge_ImportObjectAddGlobal(ImpObj, GlobalName, HostGlobal);
    54. WasmEdge_StringDelete(GlobalName);
    55. /*
    56. * The import objects should be deleted.
    57. * Developers should __NOT__ destroy the instances added into the import object contexts.
    58. */
    59. WasmEdge_ImportObjectDelete(ImpObj);
  3. Specified import object

    WasmEdge_ImportObjectCreateWASI() API can create and initialize the WASI import object. WasmEdge_ImportObjectCreateWasmEdgeProcess() API can create and initialize the wasmedge_process import object. Developers can create these import object contexts and register them into the Store or VM contexts rather than adjust the settings in the Configure contexts.

    1. WasmEdge_ImportObjectContext *WasiObj = WasmEdge_ImportObjectCreateWASI( /* ... ignored */ );
    2. WasmEdge_ImportObjectContext *ProcObj = WasmEdge_ImportObjectCreateWasmEdgeProcess( /* ... ignored */ );
    3. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    4. /* Register the WASI and WasmEdge_Process into the VM context. */
    5. WasmEdge_VMRegisterModuleFromImport(VMCxt, WasiObj);
    6. WasmEdge_VMRegisterModuleFromImport(VMCxt, ProcObj);
    7. /* Get the WASI exit code. */
    8. uint32_t ExitCode = WasmEdge_ImportObjectWASIGetExitCode(WasiObj);
    9. /*
    10. * The `ExitCode` will be EXIT_SUCCESS if the execution has no error.
    11. * Otherwise, it will return with the related exit code.
    12. */
    13. WasmEdge_VMDelete(VMCxt);
    14. /* The import objects should be deleted. */
    15. WasmEdge_ImportObjectDelete(WasiObj);
    16. WasmEdge_ImportObjectDelete(ProcObj);
  4. Example

    Assume that a simple WASM from the WAT as following:

    1. (module
    2. (type $t0 (func (param i32 i32) (result i32)))
    3. (import "extern" "func-add" (func $f-add (type $t0)))
    4. (func (export "addTwo") (param i32 i32) (result i32)
    5. local.get 0
    6. local.get 1
    7. call $f-add)
    8. )

    And the test.c as following:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. /* Host function body definition. */
    4. WasmEdge_Result Add(void *Data, WasmEdge_MemoryInstanceContext *MemCxt,
    5. const WasmEdge_Value *In, WasmEdge_Value *Out) {
    6. int32_t Val1 = WasmEdge_ValueGetI32(In[0]);
    7. int32_t Val2 = WasmEdge_ValueGetI32(In[1]);
    8. printf("Host function \"Add\": %d + %d\n", Val1, Val2);
    9. Out[0] = WasmEdge_ValueGenI32(Val1 + Val2);
    10. return WasmEdge_Result_Success;
    11. }
    12. int main() {
    13. /* Create the VM context. */
    14. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    15. /* The WASM module buffer. */
    16. uint8_t WASM[] = {
    17. /* WASM header */
    18. 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00,
    19. /* Type section */
    20. 0x01, 0x07, 0x01,
    21. /* function type {i32, i32} -> {i32} */
    22. 0x60, 0x02, 0x7F, 0x7F, 0x01, 0x7F,
    23. /* Import section */
    24. 0x02, 0x13, 0x01,
    25. /* module name: "extern" */
    26. 0x06, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6E,
    27. /* extern name: "func-add" */
    28. 0x08, 0x66, 0x75, 0x6E, 0x63, 0x2D, 0x61, 0x64, 0x64,
    29. /* import desc: func 0 */
    30. 0x00, 0x00,
    31. /* Function section */
    32. 0x03, 0x02, 0x01, 0x00,
    33. /* Export section */
    34. 0x07, 0x0A, 0x01,
    35. /* export name: "addTwo" */
    36. 0x06, 0x61, 0x64, 0x64, 0x54, 0x77, 0x6F,
    37. /* export desc: func 0 */
    38. 0x00, 0x01,
    39. /* Code section */
    40. 0x0A, 0x0A, 0x01,
    41. /* code body */
    42. 0x08, 0x00, 0x20, 0x00, 0x20, 0x01, 0x10, 0x00, 0x0B
    43. };
    44. /* Create the import object. */
    45. WasmEdge_String ExportName = WasmEdge_StringCreateByCString("extern");
    46. WasmEdge_ImportObjectContext *ImpObj = WasmEdge_ImportObjectCreate(ExportName);
    47. enum WasmEdge_ValType ParamList[2] = { WasmEdge_ValType_I32, WasmEdge_ValType_I32 };
    48. enum WasmEdge_ValType ReturnList[1] = { WasmEdge_ValType_I32 };
    49. WasmEdge_FunctionTypeContext *HostFType = WasmEdge_FunctionTypeCreate(ParamList, 2, ReturnList, 1);
    50. WasmEdge_FunctionInstanceContext *HostFunc = WasmEdge_FunctionInstanceCreate(HostFType, Add, NULL, 0);
    51. WasmEdge_FunctionTypeDelete(HostFType);
    52. WasmEdge_String HostFuncName = WasmEdge_StringCreateByCString("func-add");
    53. WasmEdge_ImportObjectAddFunction(ImpObj, HostFuncName, HostFunc);
    54. WasmEdge_StringDelete(HostFuncName);
    55. WasmEdge_VMRegisterModuleFromImport(VMCxt, ImpObj);
    56. /* The parameters and returns arrays. */
    57. WasmEdge_Value Params[2] = { WasmEdge_ValueGenI32(1234), WasmEdge_ValueGenI32(5678) };
    58. WasmEdge_Value Returns[1];
    59. /* Function name. */
    60. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("addTwo");
    61. /* Run the WASM function from file. */
    62. WasmEdge_Result Res = WasmEdge_VMRunWasmFromBuffer(
    63. VMCxt, WASM, sizeof(WASM), FuncName, Params, 2, Returns, 1);
    64. if (WasmEdge_ResultOK(Res)) {
    65. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    66. } else {
    67. printf("Error message: %s\n", WasmEdge_ResultGetMessage(Res));
    68. }
    69. /* Resources deallocations. */
    70. WasmEdge_VMDelete(VMCxt);
    71. WasmEdge_StringDelete(FuncName);
    72. WasmEdge_ImportObjectDelete(ImpObj);
    73. return 0;
    74. }

    Then you can compile and run: (the result of 1234 + 5678 is 6912)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Host function "Add": 1234 + 5678
    4. Get the result: 6912
  5. Host Data Example

    Developers can set a external data object to the function context, and access to the object in the function body. Assume that a simple WASM from the WAT as following:

    1. (module
    2. (type $t0 (func (param i32 i32) (result i32)))
    3. (import "extern" "func-add" (func $f-add (type $t0)))
    4. (func (export "addTwo") (param i32 i32) (result i32)
    5. local.get 0
    6. local.get 1
    7. call $f-add)
    8. )

    And the test.c as following:

    1. #include <wasmedge/wasmedge.h>
    2. #include <stdio.h>
    3. /* Host function body definition. */
    4. WasmEdge_Result Add(void *Data, WasmEdge_MemoryInstanceContext *MemCxt,
    5. const WasmEdge_Value *In, WasmEdge_Value *Out) {
    6. int32_t Val1 = WasmEdge_ValueGetI32(In[0]);
    7. int32_t Val2 = WasmEdge_ValueGetI32(In[1]);
    8. printf("Host function \"Add\": %d + %d\n", Val1, Val2);
    9. Out[0] = WasmEdge_ValueGenI32(Val1 + Val2);
    10. /* Also set the result to the data. */
    11. int32_t *DataPtr = (int32_t *)Data;
    12. *DataPtr = Val1 + Val2;
    13. return WasmEdge_Result_Success;
    14. }
    15. int main() {
    16. /* Create the VM context. */
    17. WasmEdge_VMContext *VMCxt = WasmEdge_VMCreate(NULL, NULL);
    18. /* The WASM module buffer. */
    19. uint8_t WASM[] = {
    20. /* WASM header */
    21. 0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00,
    22. /* Type section */
    23. 0x01, 0x07, 0x01,
    24. /* function type {i32, i32} -> {i32} */
    25. 0x60, 0x02, 0x7F, 0x7F, 0x01, 0x7F,
    26. /* Import section */
    27. 0x02, 0x13, 0x01,
    28. /* module name: "extern" */
    29. 0x06, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6E,
    30. /* extern name: "func-add" */
    31. 0x08, 0x66, 0x75, 0x6E, 0x63, 0x2D, 0x61, 0x64, 0x64,
    32. /* import desc: func 0 */
    33. 0x00, 0x00,
    34. /* Function section */
    35. 0x03, 0x02, 0x01, 0x00,
    36. /* Export section */
    37. 0x07, 0x0A, 0x01,
    38. /* export name: "addTwo" */
    39. 0x06, 0x61, 0x64, 0x64, 0x54, 0x77, 0x6F,
    40. /* export desc: func 0 */
    41. 0x00, 0x01,
    42. /* Code section */
    43. 0x0A, 0x0A, 0x01,
    44. /* code body */
    45. 0x08, 0x00, 0x20, 0x00, 0x20, 0x01, 0x10, 0x00, 0x0B
    46. };
    47. /* The external data object: an integer. */
    48. int32_t Data;
    49. /* Create the import object. */
    50. WasmEdge_String ExportName = WasmEdge_StringCreateByCString("extern");
    51. WasmEdge_ImportObjectContext *ImpObj = WasmEdge_ImportObjectCreate(ExportName);
    52. enum WasmEdge_ValType ParamList[2] = { WasmEdge_ValType_I32, WasmEdge_ValType_I32 };
    53. enum WasmEdge_ValType ReturnList[1] = { WasmEdge_ValType_I32 };
    54. WasmEdge_FunctionTypeContext *HostFType = WasmEdge_FunctionTypeCreate(ParamList, 2, ReturnList, 1);
    55. WasmEdge_FunctionInstanceContext *HostFunc = WasmEdge_FunctionInstanceCreate(HostFType, Add, &Data, 0);
    56. WasmEdge_FunctionTypeDelete(HostFType);
    57. WasmEdge_String HostFuncName = WasmEdge_StringCreateByCString("func-add");
    58. WasmEdge_ImportObjectAddFunction(ImpObj, HostFuncName, HostFunc);
    59. WasmEdge_StringDelete(HostFuncName);
    60. WasmEdge_VMRegisterModuleFromImport(VMCxt, ImpObj);
    61. /* The parameters and returns arrays. */
    62. WasmEdge_Value Params[2] = { WasmEdge_ValueGenI32(1234), WasmEdge_ValueGenI32(5678) };
    63. WasmEdge_Value Returns[1];
    64. /* Function name. */
    65. WasmEdge_String FuncName = WasmEdge_StringCreateByCString("addTwo");
    66. /* Run the WASM function from file. */
    67. WasmEdge_Result Res = WasmEdge_VMRunWasmFromBuffer(
    68. VMCxt, WASM, sizeof(WASM), FuncName, Params, 2, Returns, 1);
    69. if (WasmEdge_ResultOK(Res)) {
    70. printf("Get the result: %d\n", WasmEdge_ValueGetI32(Returns[0]));
    71. } else {
    72. printf("Error message: %s\n", WasmEdge_ResultGetMessage(Res));
    73. }
    74. printf("Data value: %d\n", Data);
    75. /* Resources deallocations. */
    76. WasmEdge_VMDelete(VMCxt);
    77. WasmEdge_StringDelete(FuncName);
    78. WasmEdge_ImportObjectDelete(ImpObj);
    79. return 0;
    80. }

    Then you can compile and run: (the result of 1234 + 5678 is 6912)

    1. $ gcc test.c -lwasmedge_c
    2. $ ./a.out
    3. Host function "Add": 1234 + 5678
    4. Get the result: 6912
    5. Data value: 6912

WasmEdge AOT Compiler

In this partition, we will introduce the WasmEdge AOT compiler and the options.

WasmEdge runs the WASM files in interpreter mode, and WasmEdge also supports the AOT (ahead-of-time) mode running without modifying any code. The WasmEdge AOT (ahead-of-time) compiler compiles the WASM files for running in AOT mode which is much faster than interpreter mode. Developers can compile the WASM files into the compiled-WASM files in shared library format for universal WASM format for the AOT mode execution.

Compilation Example

Assume that the WASM file fibonacci.wasm is copied into the current directory, and the C file test.c is as following:

  1. #include <wasmedge/wasmedge.h>
  2. #include <stdio.h>
  3. int main() {
  4. /* Create the configure context. */
  5. WasmEdge_ConfigureContext *ConfCxt = WasmEdge_ConfigureCreate();
  6. /* ... Adjust settings in the configure context. */
  7. /* Result. */
  8. WasmEdge_Result Res;
  9. /* Create the compiler context. The configure context can be NULL. */
  10. WasmEdge_CompilerContext *CompilerCxt = WasmEdge_CompilerCreate(ConfCxt);
  11. /* Compile the WASM file with input and output paths. */
  12. Res = WasmEdge_CompilerCompile(CompilerCxt, "fibonacci.wasm", "fibonacci.wasm.so");
  13. if (!WasmEdge_ResultOK(Res)) {
  14. printf("Compilation failed: %s\n", WasmEdge_ResultGetMessage(Res));
  15. return 1;
  16. }
  17. WasmEdge_CompilerDelete(CompilerCxt);
  18. WasmEdge_ConfigureDelete(ConfCxt);
  19. return 0;
  20. }

Then you can compile and run (the output file is “fibonacci.wasm.so”):

  1. $ gcc test.c -lwasmedge_c
  2. $ ./a.out
  3. [2021-07-02 11:08:08.651] [info] compile start
  4. [2021-07-02 11:08:08.653] [info] verify start
  5. [2021-07-02 11:08:08.653] [info] optimize start
  6. [2021-07-02 11:08:08.670] [info] codegen start
  7. [2021-07-02 11:08:08.706] [info] compile done

Compiler Options

Developers can set options for AOT compilers such as optimization level and output format:

  1. /// AOT compiler optimization level enumeration.
  2. enum WasmEdge_CompilerOptimizationLevel {
  3. /// Disable as many optimizations as possible.
  4. WasmEdge_CompilerOptimizationLevel_O0 = 0,
  5. /// Optimize quickly without destroying debuggability.
  6. WasmEdge_CompilerOptimizationLevel_O1,
  7. /// Optimize for fast execution as much as possible without triggering
  8. /// significant incremental compile time or code size growth.
  9. WasmEdge_CompilerOptimizationLevel_O2,
  10. /// Optimize for fast execution as much as possible.
  11. WasmEdge_CompilerOptimizationLevel_O3,
  12. /// Optimize for small code size as much as possible without triggering
  13. /// significant incremental compile time or execution time slowdowns.
  14. WasmEdge_CompilerOptimizationLevel_Os,
  15. /// Optimize for small code size as much as possible.
  16. WasmEdge_CompilerOptimizationLevel_Oz
  17. };
  18. /// AOT compiler output binary format enumeration.
  19. enum WasmEdge_CompilerOutputFormat {
  20. /// Native dynamic library format.
  21. WasmEdge_CompilerOutputFormat_Native = 0,
  22. /// WebAssembly with AOT compiled codes in custom sections.
  23. WasmEdge_CompilerOutputFormat_Wasm
  24. };

Please refer to the AOT compiler options configuration for details.