1# Working with Wasm Using JSVM-API 2 3 4## Introduction 5 6JSVM-API provides APIs for compiling WebAssembly (Wasm) bytecode, optimizing Wasm functions, and serializing and deserializing Wasm caches. 7 8## Basic Concepts 9 10- Wasm module: a binary format that contains compiled Wasm code. You can use **OH_JSVM_CompileWasmModule** to create a Wasm module from Wasm bytecode or a Wasm cache, and use **OH_JSVM_IsWasmModuleObject** to check whether a **JSVM_Value** is a Wasm module. 11- Wasm function: a function defined in a Wasm module. The functions in a Wasm module can be used by external code after being imported. You can use **OH_JSVM_CompileWasmFunction** to convert Wasm bytecode into the format that JSVM can execute efficiently. 12- Wasm cache: data generated by serializing the bytecode in a Wasm module. The cache holds the compiled Wasm code so that it can be reused, eliminating the need for recompiling the code. You can use **OH_JSVM_CreateWasmCache** (with **cacheType** set to **JSVM_CACHE_TYPE_WASM**) to create a Wasm cache instance and use **OH_JSVM_ReleaseCache** to release it. 13 14## Available APIs 15 16| API | Description | 17| --------------------------- | ------------------------------------------------------------------------------------ | 18| OH_JSVM_CompileWasmModule | Compiles the Wasm bytecode into a Wasm module. If the **cache** parameter is passed in, the cache will be deserialized into a Wasm module first. The compilation is performed when the deserialization fails.| 19| 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. | 20| OH_JSVM_IsWasmModuleObject | Checks whether the input value is a Wasm module. | 21| 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. | 22| 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. | 23 24## Example 25 26If you are just starting out with JSVM-API, see [JSVM-API Development Process](use-jsvm-process.md). The following demonstrates only the C++ code involved in the APIs for Wasm. 27 28CPP code: 29 30```cpp 31// hello.cpp 32#include "napi/native_api.h" 33#include "ark_runtime/jsvm.h" 34#include <hilog/log.h> 35 36#ifndef CHECK 37#define CHECK(cond) \ 38 do { \ 39 if (!(cond)) { \ 40 OH_LOG_ERROR(LOG_APP, "CHECK FAILED"); \ 41 abort(); \ 42 } \ 43 } while (0) 44#endif 45 46// Check whether a JSVM_Value is a Wasm module. 47static bool IsWasmModuleObject(JSVM_Env env, JSVM_Value value) { 48 bool result; 49 JSVM_Status status = OH_JSVM_IsWasmModuleObject(env, value, &result); 50 CHECK(status == JSVM_OK); 51 return result; 52} 53 54// Create a JSVM string from a C string. 55static JSVM_Value CreateString(JSVM_Env env, const char *str) { 56 JSVM_Value jsvmStr; 57 JSVM_Status status = OH_JSVM_CreateStringUtf8(env, str, JSVM_AUTO_LENGTH, &jsvmStr); 58 CHECK(status == JSVM_OK); 59 return jsvmStr; 60} 61 62// Create a JSVM number from a C int32_t value. 63static JSVM_Value CreateInt32(JSVM_Env env, int32_t val) { 64 JSVM_Value jsvmInt32; 65 JSVM_Status status = OH_JSVM_CreateInt32(env, val, &jsvmInt32); 66 CHECK(status == JSVM_OK); 67 return jsvmInt32; 68} 69 70// Instantiate the Wasm module. 71static JSVM_Value InstantiateWasmModule(JSVM_Env env, JSVM_Value wasmModule) { 72 JSVM_Status status = JSVM_OK; 73 JSVM_Value globalThis; 74 status = OH_JSVM_GetGlobal(env, &globalThis); 75 CHECK(status == JSVM_OK); 76 77 JSVM_Value webAssembly; 78 status = OH_JSVM_GetProperty(env, globalThis, CreateString(env, "WebAssembly"), &webAssembly); 79 CHECK(status == JSVM_OK); 80 81 JSVM_Value webAssemblyInstance; 82 status = OH_JSVM_GetProperty(env, webAssembly, CreateString(env, "Instance"), &webAssemblyInstance); 83 CHECK(status == JSVM_OK); 84 85 JSVM_Value instance; 86 JSVM_Value argv[] = {wasmModule}; 87 status = OH_JSVM_NewInstance(env, WebAssemblyInstance, 1, argv, &instance); 88 CHECK(status == JSVM_OK); 89 return instance; 90} 91 92// Obtain the Wasm bytecode (add module). 93static std::vector<uint8_t> GetAddWasmBuffer() { 94 // The following is the text format of the Wasm bytecode corresponding to wasmBuffer, which contains only the add function. 95 // (module 96 // (func $add (param $lhs i32) (param $rhs i32) (result i32) 97 // local.get $lhs 98 // local.get $rhs 99 // i32.add 100 // ) 101 // (export "add" (func $add)) 102 // ) 103 std::vector<uint8_t> wasmBuffer = {0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 104 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 105 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09, 0x01, 106 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b}; 107 return wasmBuffer; 108} 109 110// Verify the Wasm instance function (add module). 111static void VerifyAddWasmInstance(JSVM_Env env, JSVM_Value wasmInstance) { 112 JSVM_Status status = JSVM_OK; 113 // Obtain the exports.add function from the Wasm instance. 114 JSVM_Value exports; 115 status = OH_JSVM_GetProperty(env, wasmInstance, CreateString(env, "exports"), &exports); 116 CHECK(status == JSVM_OK); 117 118 JSVM_Value add; 119 status = OH_JSVM_GetProperty(env, exports, CreateString(env, "add"), &add); 120 CHECK(status == JSVM_OK); 121 122 // Run the exports.add(1, 2). The expected result is 3. 123 JSVM_Value undefined; 124 OH_JSVM_GetUndefined(env, &undefined); 125 JSVM_Value one = CreateInt32(env, 1); 126 JSVM_Value two = CreateInt32(env, 2); 127 JSVM_Value argv[] = {one, two}; 128 JSVM_Value result; 129 status = OH_JSVM_CallFunction(env, undefined, add, 2, argv, &result); 130 CHECK(status == JSVM_OK); 131 int32_t resultInt32; 132 OH_JSVM_GetValueInt32(env, result, &resultInt32); 133 CHECK(resultInt32 == 3); 134} 135 136// Wasm demo main function. 137static JSVM_Value WasmDemo(JSVM_Env env, JSVM_CallbackInfo info) { 138 JSVM_Status status = JSVM_OK; 139 std::vector<uint8_t> wasmBuffer = GetAddWasmBuffer(); 140 uint8_t *wasmBytecode = wasmBuffer.data(); 141 size_t wasmBytecodeLength = wasmBuffer.size(); 142 JSVM_Value wasmModule; 143 // Obtain the Wasm module based on the Wasm bytecode. 144 status = OH_JSVM_CompileWasmModule(env, wasmBytecode, wasmBytecodeLength, NULL, 0, NULL, &wasmModule); 145 CHECK(status == JSVM_OK); 146 CHECK(IsWasmModuleObject(env, wasmModule)); 147 148 // Perform compilation optimization on the first function (add) defined in the Wasm module. 149 int32_t functionIndex = 0; 150 // Currently, only high-level optimization is supported. That is, the effect is the same no matter whether JSVM_WASM_OPT_BASELINE or JSVM_WASM_OPT_HIGH is passed in. 151 status = OH_JSVM_CompileWasmFunction(env, wasmModule, functionIndex, JSVM_WASM_OPT_HIGH); 152 CHECK(status == JSVM_OK); 153 // Instantiate the compiled Wasm module. 154 JSVM_Value wasmInstance = InstantiateWasmModule(env, wasmModule); 155 // Verify the function in the instantiated Wasm instance. 156 VerifyAddWasmInstance(env, wasmInstance); 157 158 // Create a Wasm cache. 159 const uint8_t *wasmCacheData = NULL; 160 size_t wasmCacheLength = 0; 161 status = OH_JSVM_CreateWasmCache(env, wasmModule, &wasmCacheData, &wasmCacheLength); 162 CHECK(status == JSVM_OK); 163 // The Wasm cache is created successfully. 164 CHECK(wasmCacheData != NULL); 165 CHECK(wasmCacheLength > 0); 166 167 // Assign a value to the Wasm cache to simulate cache persistence. In actual scenarios, the Wasm cache may be saved to a file. 168 std::vector<uint8_t> cacheBuffer(wasmCacheData, wasmCacheData + wasmCacheLength); 169 170 // Once the cache is saved, it needs to be released explicitly to avoid memory leaks. 171 // Note that the input JSVM_CacheType must match the cache data. 172 status = OH_JSVM_ReleaseCache(env, wasmCacheData, JSVM_CACHE_TYPE_WASM); 173 CHECK(status == JSVM_OK); 174 175 // Deserialize the Wasm code to generate a Wasm module. 176 bool cacheRejected; 177 JSVM_Value wasmModule2; 178 status = OH_JSVM_CompileWasmModule(env, wasmBytecode, wasmBytecodeLength, cacheBuffer.data(), cacheBuffer.size(), 179 &cacheRejected, &wasmModule2); 180 CHECK(status == JSVM_OK); 181 // If the input Wasm cache is matched and the internal verification (such as the version) is successful, the cache will be accepted. 182 CHECK(cacheRejected == false); 183 CHECK(IsWasmModuleObject(env, wasmModule2)); 184 185 // For wasmModule2 (obtained through deserialization), perform the same operations, including function compilation, instantiation, and verification. 186 status = OH_JSVM_CompileWasmFunction(env, wasmModule2, functionIndex, JSVM_WASM_OPT_HIGH); 187 CHECK(status == JSVM_OK); 188 JSVM_Value wasmInstance2 = InstantiateWasmModule(env, wasmModule); 189 VerifyAddWasmInstance(env, wasmInstance2); 190 191 JSVM_Value result; 192 OH_JSVM_GetBoolean(env, true, &result); 193 return result; 194} 195 196// Register a WasmDemo callback. 197static JSVM_CallbackStruct param[] = { 198 {.data = nullptr, .callback = WasmDemo} 199}; 200static JSVM_CallbackStruct *method = param; 201// Register the C++ WasmDemo callback as a JSVM globalThis.wasmDemo property for the JS to call. 202static JSVM_PropertyDescriptor descriptor[] = { 203 {"wasmDemo", nullptr, method++, nullptr, nullptr, nullptr, JSVM_DEFAULT}, 204}; 205 206// Call the C++ callback from JS. 207const char *srcCallNative = R"JS(wasmDemo())JS"; 208``` 209