目录

Working with Wasm Using JSVM-API

Introduction

JSVM-API provides APIs for compiling the WebAssembly (Wasm) bytecode, optimizing Wasm functions, and serializing and deserializing Wasm caches.

Permission requirements: To run the Wasm APIs, the application must have the JIT permission. For details about how to apply for the permission, see Requesting the JIT Permission.

Running restrictions: In the current JSVM version, all functional modules of WebAssembly are disabled in Secure Shield mode. You need to evaluate application compatibility based on the restrictions. For details, see JSVM-API Secure Shield Mode.

Basic Concepts

Available APIs

API Description
OH_JSVM_CompileWasmModule Synchronously compiles Wasm bytecode into a Wasm module. If the cache parameter is provided, the API first attempts to deserialize the cache into a Wasm module. If deserialization fails, it compiles the Wasm bytecode instead. If JIT permission is not granted, a log message is printed to notify the developer.
OH_JSVM_CompileWasmFunction Compiles the function with the specified ID in a Wasm module into the optimized machine code. Currently, only the highest optimization level is enabled. The validity of the function ID is ensured by the caller. If the JIT permission is not supported, a log is printed for notification.
OH_JSVM_IsWasmModuleObject Checks whether the input value is a Wasm module.
OH_JSVM_CreateWasmCache Serializes the machine code in a Wasm module into a Wasm cache. If the Wasm module does not contain machine code, the serialization will fail. If the JIT permission is not supported, a log is printed for notification.
OH_JSVM_ReleaseCache Releases a Wasm cache instance created by JSVM-API. The cacheType and cacheData passed in must match. Otherwise, undefined behavior may occur.

Code Cache Verification Specifications

Specification Description
Integrity verification Executed by the developer.
Compatibility verification Checks whether the JSVM version and compilation options of the generated cache are the same as the current one.
Consistency verification Executed by the developer.

Example

If you are just starting out with JSVM-API, see JSVM-API Development Process. The following demonstrates only the C++ code involved in related APIs.

CPP code:

#include "napi/native_api.h"
#include "hilog/log.h"
#include "ark_runtime/jsvm.h"
#include <vector>
// ...

#ifndef CHECK_STATUS
#define CHECK_STATUS(cond)                           \
    do {                                             \
        if (!(cond)) {                               \
            OH_LOG_ERROR(LOG_APP, "CHECK FAILED");   \
        }                                            \
    } while (0)
#endif

// Check whether a JSVM_Value is a wasm module.
static bool IsWasmModuleObject(JSVM_Env env, JSVM_Value value)
{
    bool result = false;
    JSVM_Status status = OH_JSVM_IsWasmModuleObject(env, value, &result);
    CHECK_STATUS(status == JSVM_OK);
    return result;
}

// Create a JSVM string from a C string.
static JSVM_Value CreateString(JSVM_Env env, const char *str)
{
    JSVM_Value jsvmStr;
    JSVM_Status status = OH_JSVM_CreateStringUtf8(env, str, JSVM_AUTO_LENGTH, &jsvmStr);
    CHECK_STATUS(status == JSVM_OK);
    return jsvmStr;
}

// Create a JSVM number from a C int32_t.
static JSVM_Value CreateInt32(JSVM_Env env, int32_t val)
{
    JSVM_Value jsvmInt32;
    JSVM_Status status = OH_JSVM_CreateInt32(env, val, &jsvmInt32);
    CHECK_STATUS(status == JSVM_OK);
    return jsvmInt32;
}

// Instantiate the wasm module.
static JSVM_Value InstantiateWasmModule(JSVM_Env env, JSVM_Value wasmModule)
{
    JSVM_Status status = JSVM_OK;
    JSVM_Value globalThis;
    status = OH_JSVM_GetGlobal(env, &globalThis);
    CHECK_STATUS(status == JSVM_OK);

    JSVM_Value webAssembly;
    status = OH_JSVM_GetProperty(env, globalThis, CreateString(env, "WebAssembly"), &webAssembly);
    CHECK_STATUS(status == JSVM_OK);

    JSVM_Value webAssemblyInstance;
    status = OH_JSVM_GetProperty(env, webAssembly, CreateString(env, "Instance"), &webAssemblyInstance);
    CHECK_STATUS(status == JSVM_OK);

    JSVM_Value instance;
    JSVM_Value argv[] = {wasmModule};
    status = OH_JSVM_NewInstance(env, webAssemblyInstance, 1, argv, &instance);
    CHECK_STATUS(status == JSVM_OK);
    return instance;
}

// Obtain the wasm bytecode (add module).
static std::vector<uint8_t> GetAddWasmBuffer()
{
    /*The wasm bytecode text format corresponding to wasmBuffer is as follows. It contains only one function, add.
     * (module
     *   (func $add (param $lhs i32) (param $rhs i32) (result i32)
     *     local.get $lhs
     *     local.get $rhs
     *     i32.add
     *   )
     *   (export "add" (func $add))
     * )
     */
    std::vector<uint8_t> wasmBuffer = {0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01,
                                       0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07,
                                       0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, 0x01,
                                       0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b};
    return wasmBuffer;
}

// Verify the wasm instance functionality (add module).
static void VerifyAddWasmInstance(JSVM_Env env, JSVM_Value wasmInstance)
{
    JSVM_Status status = JSVM_OK;
    // Obtain the exports.add function from the wasm instance.
    JSVM_Value exports;
    status = OH_JSVM_GetProperty(env, wasmInstance, CreateString(env, "exports"), &exports);
    CHECK_STATUS(status == JSVM_OK);

    JSVM_Value add;
    status = OH_JSVM_GetProperty(env, exports, CreateString(env, "add"), &add);
    CHECK_STATUS(status == JSVM_OK);

    // Execute exports.add(1, 2) and expect the result 3.
    JSVM_Value undefined;
    OH_JSVM_GetUndefined(env, &undefined);
    JSVM_Value one = CreateInt32(env, 1);
    JSVM_Value two = CreateInt32(env, 2);
    JSVM_Value argv[] = {one, two};
    JSVM_Value result;
    const int argumentCount = 2;
    status = OH_JSVM_CallFunction(env, undefined, add, argumentCount, argv, &result);
    CHECK_STATUS(status == JSVM_OK);
    int32_t resultInt32 = 0;
    OH_JSVM_GetValueInt32(env, result, &resultInt32);
    CHECK_STATUS(resultInt32 == 3);
}

// Main function of the WebAssembly demo.
static JSVM_Value WasmDemo(JSVM_Env env, JSVM_CallbackInfo info)
{
    JSVM_Status status = JSVM_OK;
    std::vector<uint8_t> wasmBuffer = GetAddWasmBuffer();
    uint8_t *wasmBytecode = wasmBuffer.data();
    size_t wasmBytecodeLength = wasmBuffer.size();
    JSVM_Value wasmModule;
    // Obtain the wasm module from the wasm bytecode.
    status = OH_JSVM_CompileWasmModule(env, wasmBytecode, wasmBytecodeLength, NULL, 0, NULL, &wasmModule);
    CHECK_STATUS(status == JSVM_OK);
    CHECK_STATUS(IsWasmModuleObject(env, wasmModule));

    // Perform compilation optimization on the first function (add) defined in the current wasm module.
    int32_t functionIndex = 0;
    // Note: Currently only high level optimization is supported, meaning that passing JSVM_WASM_OPT_BASELINE and passing JSVM_WASM_OPT_HIGH have the same effect.
    status = OH_JSVM_CompileWasmFunction(env, wasmModule, functionIndex, JSVM_WASM_OPT_HIGH);
    CHECK_STATUS(status == JSVM_OK);
    // Instantiate the compiled wasm module.
    JSVM_Value wasmInstance = InstantiateWasmModule(env, wasmModule);
    // Verify the functionality of the functions in the instantiated wasm instance.
    VerifyAddWasmInstance(env, wasmInstance);

    // Create a wasm cache.
    const uint8_t *wasmCacheData = NULL;
    size_t wasmCacheLength = 0;
    status = OH_JSVM_CreateWasmCache(env, wasmModule, &wasmCacheData, &wasmCacheLength);
    CHECK_STATUS(status == JSVM_OK);
    // Expect the wasm cache to be created successfully.
    CHECK_STATUS(wasmCacheData != NULL);
    CHECK_STATUS(wasmCacheLength > 0);

    // Simulate cache persistence by assigning the wasm cache. In actual usage scenarios, the wasm cache may be saved to a file.
    std::vector<uint8_t> cacheBuffer(wasmCacheData, wasmCacheData + wasmCacheLength);

    // Once the cache is saved, explicitly release it to avoid memory leaks.
    // Note: The JSVM_CacheType passed in must match.
    status = OH_JSVM_ReleaseCache(env, wasmCacheData, JSVM_CACHE_TYPE_WASM);
    CHECK_STATUS(status == JSVM_OK);

    // Use wasm code deserialization to generate a wasm module.
    bool cacheRejected = false;
    JSVM_Value wasmModule2;
    status = OH_JSVM_CompileWasmModule(env, wasmBytecode, wasmBytecodeLength, cacheBuffer.data(), cacheBuffer.size(),
                                       &cacheRejected, &wasmModule2);

    // If the passed wasm cache matches and passes internal verification (such as version), the cache will be accepted.
    CHECK_STATUS(!cacheRejected);
    CHECK_STATUS(IsWasmModuleObject(env, wasmModule2));

    // Perform the same operations on the deserialized wasmModule2: function compilation, instantiation, and functionality verification. All are expected to pass.
    status = OH_JSVM_CompileWasmFunction(env, wasmModule2, functionIndex, JSVM_WASM_OPT_HIGH);
    CHECK_STATUS(status == JSVM_OK);

    JSVM_Value wasmInstance2 = InstantiateWasmModule(env, wasmModule2);
    VerifyAddWasmInstance(env, wasmInstance2);

    JSVM_Value result;
    OH_JSVM_GetBoolean(env, true, &result);
    OH_LOG_INFO(LOG_APP, "JSVM resultInt: %{public}d", result);
    return result;
}

// Register the WasmDemo method callback.
static JSVM_CallbackStruct param[] = {
    {.data = nullptr, .callback = WasmDemo}
};
static JSVM_CallbackStruct *method = param;
// Register the C++ callback WasmDemo function as the JSVM globalThis.wasmDemo property for JS-side invocation.
static JSVM_PropertyDescriptor descriptor[] = {
    {"wasmDemo", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT},
};

// Sample test JS.
const char *SRC_CALL_NATIVE = R"JS(wasmDemo())JS";

Expected output: No errors