| 1 | /** |
| 2 | * interface.c |
| 3 | * |
| 4 | * We primarily use JSValue* (pointer to JSValue) when communicating with the |
| 5 | * host javascript environment, because pointers are trivial to use for calls |
| 6 | * into emscripten because they're just a number! |
| 7 | * |
| 8 | * As with the quickjs.h API, a JSValueConst* value is "borrowed" and should |
| 9 | * not be freed. A JSValue* is "owned" and should be freed by the owner. |
| 10 | * |
| 11 | * Functions starting with "QTS_" are exported by generate.ts to: |
| 12 | * - interface.h for native C code. |
| 13 | * - ffi.ts for emscripten. |
| 14 | * |
| 15 | * We support building the following build outputs: |
| 16 | * |
| 17 | * ## 1. Native machine code |
| 18 | * For internal development testing purposes. |
| 19 | * |
| 20 | * ## 2. WASM via Emscripten |
| 21 | * For general production use. |
| 22 | * |
| 23 | * ## 3. Experimental: Asyncified WASM via Emscripten with -s ASYNCIFY=1. |
| 24 | * This variant supports treating async host Javascript calls as synchronous |
| 25 | * from the perspective of the WASM c code. |
| 26 | * |
| 27 | * The way this works is described here: |
| 28 | * https://emscripten.org/docs/porting/asyncify.html |
| 29 | * |
| 30 | * In this variant, any call into our C code could return a promise if it ended |
| 31 | * up suspended. We mark the methods we suspect might suspend due to users' code |
| 32 | * as returning MaybeAsync(T). This information is ignored for the regular |
| 33 | * build. |
| 34 | */ |
| 35 | |
| 36 | #ifdef __EMSCRIPTEN__ |
| 37 | #include <emscripten.h> |
| 38 | #endif |
| 39 | |
| 40 | #include <math.h> // For NAN |
| 41 | #include <stdbool.h> |
| 42 | #include <stdio.h> |
| 43 | #include <string.h> |
| 44 | #ifdef QTS_SANITIZE_LEAK |
| 45 | #include <sanitizer/lsan_interface.h> |
| 46 | #endif |
| 47 | |
| 48 | #ifdef QTS_USE_QUICKJS_NG |
| 49 | // quickjs-ng amalgam only provides quickjs.h and quickjs-libc.h |
| 50 | #include "../vendor/quickjs-ng/quickjs-libc.h" |
| 51 | #include "../vendor/quickjs-ng/quickjs.h" |
| 52 | // Compatibility: quickjs-ng uses C99 bool instead of custom BOOL type |
| 53 | #ifndef BOOL |
| 54 | #define BOOL bool |
| 55 | #define TRUE true |
| 56 | #define FALSE false |
| 57 | #endif |
| 58 | // Compatibility: quickjs-ng JS_IsBigInt takes only 1 argument |
| 59 | #define QTS_JS_IsBigInt(ctx, v) JS_IsBigInt(v) |
| 60 | // Forward declaration for js_std_dump_error (defined in amalgam with QJS_BUILD_LIBC) |
| 61 | void js_std_dump_error(JSContext *ctx); |
| 62 | #else |
| 63 | #include "../vendor/quickjs/cutils.h" |
| 64 | #include "../vendor/quickjs/quickjs-libc.h" |
| 65 | #include "../vendor/quickjs/quickjs.h" |
| 66 | // bellard/quickjs JS_IsBigInt takes 2 arguments |
| 67 | #define QTS_JS_IsBigInt(ctx, v) JS_IsBigInt(ctx, v) |
| 68 | #endif |
| 69 | |
| 70 | #define PKG "quickjs-emscripten: " |
| 71 | #define LOG_LEN 500 |
| 72 | |
| 73 | #ifdef QTS_DEBUG_MODE |
| 74 | #define IF_DEBUG if (qts_get_context_rt_data(ctx)->debug_log) |
| 75 | #define IF_DEBUG_RT if (qts_get_runtime_data(rt)->debug_log) |
| 76 | |
| 77 | #define QTS_DEBUG(msg) IF_DEBUG qts_log(msg); |
| 78 | #define QTS_DEBUG_RT(msg) IF_DEBUG_RT qts_log(msg); |
| 79 | #define QTS_DUMP(value) IF_DEBUG qts_dump(ctx, value); |
| 80 | |
| 81 | #else |
| 82 | #define IF_DEBUG if (0) |
| 83 | #define IF_DEBUG_RT if (0) |
| 84 | #define QTS_DEBUG(msg) ; |
| 85 | #define QTS_DEBUG_RT(msg) ; |
| 86 | #define QTS_DUMP(value) ; |
| 87 | #endif |
| 88 | |
| 89 | /** |
| 90 | * Signal to our FFI code generator that this string argument should be passed as a pointer |
| 91 | * allocated by the caller on the heap, not a JS string on the stack. |
| 92 | * https://github.com/emscripten-core/emscripten/issues/6860#issuecomment-405818401 |
| 93 | */ |
| 94 | #define BorrowedHeapChar const char |
| 95 | #define OwnedHeapChar char |
| 96 | #define JSBorrowedChar const char |
| 97 | #define HostRefId int32_t |
| 98 | |
| 99 | /** |
| 100 | * Signal to our FFI code generator that this function should be called |
| 101 | * asynchronously when compiled with ASYNCIFY. |
| 102 | */ |
| 103 | #define MaybeAsync(T) T |
| 104 | |
| 105 | /** |
| 106 | * Signal to our FFI code generator that this function is only available in |
| 107 | * ASYNCIFY builds. |
| 108 | */ |
| 109 | #define AsyncifyOnly(T) T |
| 110 | |
| 111 | #define JSVoid void |
| 112 | |
| 113 | #define EvalFlags int |
| 114 | #define IntrinsicsFlags enum QTS_Intrinsic |
| 115 | #define EvalDetectModule int |
| 116 | |
| 117 | // Forward declarations for EM_JS callback functions |
| 118 | // These are implemented via EM_JS macro but need forward declarations for C99 compliance |
| 119 | #ifdef __EMSCRIPTEN__ |
| 120 | JSValue *qts_host_call_function(JSContext *ctx, JSValueConst *this_ptr, int argc, JSValueConst *argv, int32_t host_ref_id); |
| 121 | int qts_host_interrupt_handler(JSRuntime *rt); |
| 122 | char *qts_host_load_module_source(JSRuntime *rt, JSContext *ctx, const char *module_name); |
| 123 | char *qts_host_normalize_module(JSRuntime *rt, JSContext *ctx, const char *module_base_name, const char *module_name); |
| 124 | #endif |
| 125 | |
| 126 | typedef struct qts_RuntimeData { |
| 127 | bool debug_log; |
| 128 | } qts_RuntimeData; |
| 129 | |
| 130 | qts_RuntimeData *qts_get_runtime_data(JSRuntime *rt) { |
| 131 | qts_RuntimeData *data = JS_GetRuntimeOpaque(rt); |
| 132 | if (data == NULL) { |
| 133 | data = malloc(sizeof(qts_RuntimeData)); |
| 134 | data->debug_log = false; |
| 135 | JS_SetRuntimeOpaque(rt, data); |
| 136 | } |
| 137 | return data; |
| 138 | } |
| 139 | |
| 140 | qts_RuntimeData *qts_get_context_rt_data(JSContext *ctx) { |
| 141 | return qts_get_runtime_data(JS_GetRuntime(ctx)); |
| 142 | } |
| 143 | |
| 144 | void qts_log(char *msg) { |
| 145 | fputs(PKG, stderr); |
| 146 | fputs(msg, stderr); |
| 147 | fputs("\n", stderr); |
| 148 | } |
| 149 | |
| 150 | void qts_dump(JSContext *ctx, JSValueConst value) { |
| 151 | const char *str = JS_ToCString(ctx, value); |
| 152 | if (!str) { |
| 153 | QTS_DEBUG("QTS_DUMP: can't dump"); |
| 154 | return; |
| 155 | } |
| 156 | fputs(str, stderr); |
| 157 | JS_FreeCString(ctx, str); |
| 158 | putchar('\n'); |
| 159 | } |
| 160 | |
| 161 | void copy_prop_if_needed(JSContext *ctx, JSValueConst dest, JSValueConst src, const char *prop_name) { |
| 162 | JSAtom prop_atom = JS_NewAtom(ctx, prop_name); |
| 163 | JSValue dest_prop = JS_GetProperty(ctx, dest, prop_atom); |
| 164 | if (JS_IsUndefined(dest_prop)) { |
| 165 | JSValue src_prop = JS_GetProperty(ctx, src, prop_atom); |
| 166 | if (!JS_IsUndefined(src_prop) && !JS_IsException(src_prop)) { |
| 167 | JS_SetProperty(ctx, dest, prop_atom, src_prop); |
| 168 | } |
| 169 | } else { |
| 170 | JS_FreeValue(ctx, dest_prop); |
| 171 | } |
| 172 | JS_FreeAtom(ctx, prop_atom); |
| 173 | } |
| 174 | |
| 175 | JSValue *jsvalue_to_heap(JSValueConst value) { |
| 176 | JSValue *result = malloc(sizeof(JSValue)); |
| 177 | if (result) { |
| 178 | // Could be better optimized, but at -0z / -ftlo, it |
| 179 | // appears to produce the same binary code as a memcpy. |
| 180 | *result = value; |
| 181 | } |
| 182 | return result; |
| 183 | } |
| 184 | |
| 185 | JSValue *QTS_Throw(JSContext *ctx, JSValueConst *error) { |
| 186 | JSValue copy = JS_DupValue(ctx, *error); |
| 187 | return jsvalue_to_heap(JS_Throw(ctx, copy)); |
| 188 | } |
| 189 | |
| 190 | JSValue *QTS_NewError(JSContext *ctx) { |
| 191 | return jsvalue_to_heap(JS_NewError(ctx)); |
| 192 | } |
| 193 | |
| 194 | /** |
| 195 | * Limits. |
| 196 | */ |
| 197 | |
| 198 | /** |
| 199 | * Memory limit. Set to -1 to disable. |
| 200 | */ |
| 201 | void QTS_RuntimeSetMemoryLimit(JSRuntime *rt, size_t limit) { |
| 202 | JS_SetMemoryLimit(rt, limit); |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Memory diagnostics |
| 207 | */ |
| 208 | |
| 209 | JSValue *QTS_RuntimeComputeMemoryUsage(JSRuntime *rt, JSContext *ctx) { |
| 210 | JSMemoryUsage s; |
| 211 | JS_ComputeMemoryUsage(rt, &s); |
| 212 | |
| 213 | // Note that we're going to allocate more memory just to report the memory usage. |
| 214 | // A more sound approach would be to bind JSMemoryUsage struct directly - but that's |
| 215 | // a lot of work. This should be okay in the mean time. |
| 216 | JSValue result = JS_NewObject(ctx); |
| 217 | |
| 218 | // Manually generated via editor-fu from JSMemoryUsage struct definition in quickjs.h |
| 219 | JS_SetPropertyStr(ctx, result, "malloc_limit", JS_NewInt64(ctx, s.malloc_limit)); |
| 220 | JS_SetPropertyStr(ctx, result, "memory_used_size", JS_NewInt64(ctx, s.memory_used_size)); |
| 221 | JS_SetPropertyStr(ctx, result, "malloc_count", JS_NewInt64(ctx, s.malloc_count)); |
| 222 | JS_SetPropertyStr(ctx, result, "memory_used_count", JS_NewInt64(ctx, s.memory_used_count)); |
| 223 | JS_SetPropertyStr(ctx, result, "atom_count", JS_NewInt64(ctx, s.atom_count)); |
| 224 | JS_SetPropertyStr(ctx, result, "atom_size", JS_NewInt64(ctx, s.atom_size)); |
| 225 | JS_SetPropertyStr(ctx, result, "str_count", JS_NewInt64(ctx, s.str_count)); |
| 226 | JS_SetPropertyStr(ctx, result, "str_size", JS_NewInt64(ctx, s.str_size)); |
| 227 | JS_SetPropertyStr(ctx, result, "obj_count", JS_NewInt64(ctx, s.obj_count)); |
| 228 | JS_SetPropertyStr(ctx, result, "obj_size", JS_NewInt64(ctx, s.obj_size)); |
| 229 | JS_SetPropertyStr(ctx, result, "prop_count", JS_NewInt64(ctx, s.prop_count)); |
| 230 | JS_SetPropertyStr(ctx, result, "prop_size", JS_NewInt64(ctx, s.prop_size)); |
| 231 | JS_SetPropertyStr(ctx, result, "shape_count", JS_NewInt64(ctx, s.shape_count)); |
| 232 | JS_SetPropertyStr(ctx, result, "shape_size", JS_NewInt64(ctx, s.shape_size)); |
| 233 | JS_SetPropertyStr(ctx, result, "js_func_count", JS_NewInt64(ctx, s.js_func_count)); |
| 234 | JS_SetPropertyStr(ctx, result, "js_func_size", JS_NewInt64(ctx, s.js_func_size)); |
| 235 | JS_SetPropertyStr(ctx, result, "js_func_code_size", JS_NewInt64(ctx, s.js_func_code_size)); |
| 236 | JS_SetPropertyStr(ctx, result, "js_func_pc2line_count", JS_NewInt64(ctx, s.js_func_pc2line_count)); |
| 237 | JS_SetPropertyStr(ctx, result, "js_func_pc2line_size", JS_NewInt64(ctx, s.js_func_pc2line_size)); |
| 238 | JS_SetPropertyStr(ctx, result, "c_func_count", JS_NewInt64(ctx, s.c_func_count)); |
| 239 | JS_SetPropertyStr(ctx, result, "array_count", JS_NewInt64(ctx, s.array_count)); |
| 240 | JS_SetPropertyStr(ctx, result, "fast_array_count", JS_NewInt64(ctx, s.fast_array_count)); |
| 241 | JS_SetPropertyStr(ctx, result, "fast_array_elements", JS_NewInt64(ctx, s.fast_array_elements)); |
| 242 | JS_SetPropertyStr(ctx, result, "binary_object_count", JS_NewInt64(ctx, s.binary_object_count)); |
| 243 | JS_SetPropertyStr(ctx, result, "binary_object_size", JS_NewInt64(ctx, s.binary_object_size)); |
| 244 | |
| 245 | return jsvalue_to_heap(result); |
| 246 | } |
| 247 | |
| 248 | OwnedHeapChar *QTS_RuntimeDumpMemoryUsage(JSRuntime *rt) { |
| 249 | char *result = malloc(sizeof(char) * 1024); |
| 250 | FILE *memfile = fmemopen(result, 1024, "w"); |
| 251 | JSMemoryUsage s; |
| 252 | JS_ComputeMemoryUsage(rt, &s); |
| 253 | JS_DumpMemoryUsage(memfile, &s, rt); |
| 254 | fclose(memfile); |
| 255 | return result; |
| 256 | } |
| 257 | |
| 258 | int QTS_RecoverableLeakCheck() { |
| 259 | #ifdef QTS_SANITIZE_LEAK |
| 260 | return __lsan_do_recoverable_leak_check(); |
| 261 | #else |
| 262 | return 0; |
| 263 | #endif |
| 264 | } |
| 265 | |
| 266 | int QTS_BuildIsSanitizeLeak() { |
| 267 | #ifdef QTS_SANITIZE_LEAK |
| 268 | return 1; |
| 269 | #else |
| 270 | return 0; |
| 271 | #endif |
| 272 | } |
| 273 | |
| 274 | #ifdef QTS_ASYNCIFY |
| 275 | EM_JS(void, set_asyncify_stack_size, (size_t size, size_t default_size), { |
| 276 | Asyncify.StackSize = size || default_size; |
| 277 | }); |
| 278 | #endif |
| 279 | |
| 280 | /** |
| 281 | * Set the stack size limit, in bytes. Set to 0 to disable. |
| 282 | */ |
| 283 | |
| 284 | void QTS_RuntimeSetMaxStackSize(JSRuntime *rt, size_t stack_size) { |
| 285 | #ifdef QTS_ASYNCIFY |
| 286 | set_asyncify_stack_size(stack_size, QTS_ASYNCIFY_DEFAULT_STACK_SIZE); |
| 287 | #endif |
| 288 | JS_SetMaxStackSize(rt, stack_size); |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Constant pointers. Because we always use JSValue* from the host Javascript environment, |
| 293 | * we need helper fuctions to return pointers to these constants. |
| 294 | */ |
| 295 | |
| 296 | JSValueConst QTS_Undefined = JS_UNDEFINED; |
| 297 | JSValueConst *QTS_GetUndefined() { |
| 298 | return &QTS_Undefined; |
| 299 | } |
| 300 | |
| 301 | JSValueConst QTS_Null = JS_NULL; |
| 302 | JSValueConst *QTS_GetNull() { |
| 303 | return &QTS_Null; |
| 304 | } |
| 305 | |
| 306 | JSValueConst QTS_False = JS_FALSE; |
| 307 | JSValueConst *QTS_GetFalse() { |
| 308 | return &QTS_False; |
| 309 | } |
| 310 | |
| 311 | JSValueConst QTS_True = JS_TRUE; |
| 312 | JSValueConst *QTS_GetTrue() { |
| 313 | return &QTS_True; |
| 314 | } |
| 315 | |
| 316 | // ---------------------------------------------------------------------------- |
| 317 | // HostRef - De-reference host value based on JSValue GC. |
| 318 | // Used for functions |
| 319 | |
| 320 | static JSClassID host_ref_class_id; |
| 321 | // todo: variant with mark callback |
| 322 | |
| 323 | typedef struct HostRef { |
| 324 | int32_t id; |
| 325 | } HostRef; |
| 326 | |
| 327 | #ifdef __EMSCRIPTEN__ |
| 328 | EM_JS(void, qts_host_ref_free, (JSRuntime *rt, int32_t id), { |
| 329 | // For now we don't allow for async freeHostRef. |
| 330 | const asyncify = undefined; |
| 331 | Module['callbacks']['freeHostRef'](asyncify, rt, id); |
| 332 | }); |
| 333 | #endif |
| 334 | |
| 335 | static void host_ref_finalizer(JSRuntime *rt, JSValue val) { |
| 336 | HostRef *hv = JS_GetOpaque(val, host_ref_class_id); |
| 337 | if (hv) { |
| 338 | #ifdef __EMSCRIPTEN__ |
| 339 | qts_host_ref_free(rt, hv->id); |
| 340 | #endif |
| 341 | js_free_rt(rt, hv); |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | static JSClassDef host_ref_class = { |
| 346 | .class_name = "HostRef", |
| 347 | .finalizer = host_ref_finalizer, |
| 348 | }; |
| 349 | |
| 350 | static int host_ref_class_init(JSRuntime *rt) { |
| 351 | // Only allocate class ID once globally |
| 352 | if (host_ref_class_id == 0) { |
| 353 | #ifdef QTS_USE_QUICKJS_NG |
| 354 | JS_NewClassID(rt, &host_ref_class_id); |
| 355 | #else |
| 356 | JS_NewClassID(&host_ref_class_id); |
| 357 | #endif |
| 358 | } |
| 359 | // Register class with this runtime if not already registered |
| 360 | // JS_NewClass returns 0 on success, -1 if already registered (which is fine) |
| 361 | if (!JS_IsRegisteredClass(rt, host_ref_class_id)) { |
| 362 | return JS_NewClass(rt, host_ref_class_id, &host_ref_class); |
| 363 | } |
| 364 | return 0; |
| 365 | } |
| 366 | |
| 367 | static JSValue new_host_ref(JSContext *ctx, HostRefId id) { |
| 368 | HostRef *hv; |
| 369 | JSValue obj; |
| 370 | obj = JS_NewObjectClass(ctx, host_ref_class_id); |
| 371 | if (JS_IsException(obj)) { |
| 372 | return obj; |
| 373 | } |
| 374 | |
| 375 | hv = js_mallocz(ctx, sizeof(*hv)); |
| 376 | if (!hv) { |
| 377 | // js_mallocz returns NULL on failure and sets rt.exception to OutOfMemory |
| 378 | JS_FreeValue(ctx, obj); |
| 379 | return JS_EXCEPTION; |
| 380 | } |
| 381 | |
| 382 | hv->id = id; |
| 383 | JS_SetOpaque(obj, hv); |
| 384 | return obj; |
| 385 | } |
| 386 | |
| 387 | JSValue *QTS_NewHostRef(JSContext *ctx, HostRefId id) { |
| 388 | return jsvalue_to_heap(new_host_ref(ctx, id)); |
| 389 | } |
| 390 | |
| 391 | HostRefId QTS_GetHostRefId(JSValueConst *value) { |
| 392 | HostRef *hv = JS_GetOpaque(*value, host_ref_class_id); |
| 393 | if (hv) { |
| 394 | return hv->id; |
| 395 | } |
| 396 | return 0; |
| 397 | } |
| 398 | |
| 399 | // ---------------------------------------------------------------------------- |
| 400 | // Context & Runtime |
| 401 | |
| 402 | /** |
| 403 | * Standard FFI functions |
| 404 | */ |
| 405 | |
| 406 | JSRuntime *QTS_NewRuntime() { |
| 407 | return JS_NewRuntime(); |
| 408 | } |
| 409 | |
| 410 | void QTS_FreeRuntime(JSRuntime *rt) { |
| 411 | void *data = JS_GetRuntimeOpaque(rt); |
| 412 | if (data) { |
| 413 | free(data); |
| 414 | } |
| 415 | JS_FreeRuntime(rt); |
| 416 | } |
| 417 | |
| 418 | enum QTS_Intrinsic { |
| 419 | QTS_Intrinsic_BaseObjects = 1 << 0, |
| 420 | QTS_Intrinsic_Date = 1 << 1, |
| 421 | QTS_Intrinsic_Eval = 1 << 2, |
| 422 | QTS_Intrinsic_StringNormalize = 1 << 3, |
| 423 | QTS_Intrinsic_RegExp = 1 << 4, |
| 424 | QTS_Intrinsic_RegExpCompiler = 1 << 5, |
| 425 | QTS_Intrinsic_JSON = 1 << 6, |
| 426 | QTS_Intrinsic_Proxy = 1 << 7, |
| 427 | QTS_Intrinsic_MapSet = 1 << 8, |
| 428 | QTS_Intrinsic_TypedArrays = 1 << 9, |
| 429 | QTS_Intrinsic_Promise = 1 << 10, |
| 430 | QTS_Intrinsic_BigInt = 1 << 11, |
| 431 | }; |
| 432 | |
| 433 | JSContext *QTS_NewContext(JSRuntime *rt, IntrinsicsFlags intrinsics) { |
| 434 | JSContext *ctx; |
| 435 | |
| 436 | if (intrinsics == 0) { |
| 437 | ctx = JS_NewContext(rt); |
| 438 | if (ctx == NULL) { |
| 439 | return NULL; |
| 440 | } |
| 441 | } else { |
| 442 | ctx = JS_NewContextRaw(rt); |
| 443 | if (ctx == NULL) { |
| 444 | return NULL; |
| 445 | } |
| 446 | |
| 447 | if (intrinsics & QTS_Intrinsic_BaseObjects) { |
| 448 | JS_AddIntrinsicBaseObjects(ctx); |
| 449 | } |
| 450 | if (intrinsics & QTS_Intrinsic_Date) { |
| 451 | JS_AddIntrinsicDate(ctx); |
| 452 | } |
| 453 | if (intrinsics & QTS_Intrinsic_Eval) { |
| 454 | JS_AddIntrinsicEval(ctx); |
| 455 | } |
| 456 | #ifndef QTS_USE_QUICKJS_NG |
| 457 | if (intrinsics & QTS_Intrinsic_StringNormalize) { |
| 458 | JS_AddIntrinsicStringNormalize(ctx); |
| 459 | } |
| 460 | #endif |
| 461 | if (intrinsics & QTS_Intrinsic_RegExp) { |
| 462 | JS_AddIntrinsicRegExp(ctx); |
| 463 | } |
| 464 | if (intrinsics & QTS_Intrinsic_RegExpCompiler) { |
| 465 | JS_AddIntrinsicRegExpCompiler(ctx); |
| 466 | } |
| 467 | if (intrinsics & QTS_Intrinsic_JSON) { |
| 468 | JS_AddIntrinsicJSON(ctx); |
| 469 | } |
| 470 | if (intrinsics & QTS_Intrinsic_Proxy) { |
| 471 | JS_AddIntrinsicProxy(ctx); |
| 472 | } |
| 473 | if (intrinsics & QTS_Intrinsic_MapSet) { |
| 474 | JS_AddIntrinsicMapSet(ctx); |
| 475 | } |
| 476 | if (intrinsics & QTS_Intrinsic_TypedArrays) { |
| 477 | JS_AddIntrinsicTypedArrays(ctx); |
| 478 | } |
| 479 | if (intrinsics & QTS_Intrinsic_Promise) { |
| 480 | JS_AddIntrinsicPromise(ctx); |
| 481 | } |
| 482 | |
| 483 | // Note: BigInt is now always part of QuickJS core, no need for separate intrinsic |
| 484 | } |
| 485 | |
| 486 | if (host_ref_class_init(JS_GetRuntime(ctx)) != 0) { |
| 487 | JS_FreeContext(ctx); |
| 488 | return NULL; |
| 489 | } |
| 490 | |
| 491 | return ctx; |
| 492 | } |
| 493 | |
| 494 | void QTS_FreeContext(JSContext *ctx) { |
| 495 | JS_FreeContext(ctx); |
| 496 | } |
| 497 | |
| 498 | void QTS_FreeValuePointer(JSContext *ctx, JSValue *value) { |
| 499 | JS_FreeValue(ctx, *value); |
| 500 | free(value); |
| 501 | } |
| 502 | |
| 503 | void QTS_FreeValuePointerRuntime(JSRuntime *rt, JSValue *value) { |
| 504 | JS_FreeValueRT(rt, *value); |
| 505 | free(value); |
| 506 | } |
| 507 | |
| 508 | void QTS_FreeVoidPointer(JSContext *ctx, JSVoid *ptr) { |
| 509 | js_free(ctx, ptr); |
| 510 | } |
| 511 | |
| 512 | void QTS_FreeCString(JSContext *ctx, JSBorrowedChar *str) { |
| 513 | JS_FreeCString(ctx, str); |
| 514 | } |
| 515 | |
| 516 | JSValue *QTS_DupValuePointer(JSContext *ctx, JSValueConst *val) { |
| 517 | return jsvalue_to_heap(JS_DupValue(ctx, *val)); |
| 518 | } |
| 519 | |
| 520 | JSValue *QTS_NewObject(JSContext *ctx) { |
| 521 | return jsvalue_to_heap(JS_NewObject(ctx)); |
| 522 | } |
| 523 | |
| 524 | JSValue *QTS_NewObjectProto(JSContext *ctx, JSValueConst *proto) { |
| 525 | return jsvalue_to_heap(JS_NewObjectProto(ctx, *proto)); |
| 526 | } |
| 527 | |
| 528 | JSValue *QTS_NewArray(JSContext *ctx) { |
| 529 | return jsvalue_to_heap(JS_NewArray(ctx)); |
| 530 | } |
| 531 | |
| 532 | #if defined(QJS_VERSION_MAJOR) && (QJS_VERSION_MAJOR > 0 || QJS_VERSION_MINOR >= 17) |
| 533 | /* quickjs-ng 0.17: external ArrayBuffer memory is managed through a realloc function (size 0 frees). */ |
| 534 | void *qts_realloc_buffer(JSRuntime *unused_rt, void *unused_opaque, void *ptr, size_t size) { |
| 535 | if (size == 0) { |
| 536 | free(ptr); |
| 537 | return NULL; |
| 538 | } |
| 539 | return realloc(ptr, size); |
| 540 | } |
| 541 | |
| 542 | JSValue *QTS_NewArrayBuffer(JSContext *ctx, JSVoid *buffer, size_t length) { |
| 543 | return jsvalue_to_heap( |
| 544 | JS_NewArrayBuffer(ctx, (uint8_t *)buffer, length, 0, qts_realloc_buffer, NULL, false)); |
| 545 | } |
| 546 | #else |
| 547 | void qts_free_buffer(JSRuntime *unused_rt, void *unused_opaque, void *ptr) { free(ptr); } |
| 548 | |
| 549 | JSValue *QTS_NewArrayBuffer(JSContext *ctx, JSVoid *buffer, size_t length) { |
| 550 | return jsvalue_to_heap( |
| 551 | JS_NewArrayBuffer(ctx, (uint8_t *)buffer, length, qts_free_buffer, NULL, false)); |
| 552 | } |
| 553 | #endif |
| 554 | |
| 555 | JSValue *QTS_NewFloat64(JSContext *ctx, double num) { |
| 556 | return jsvalue_to_heap(JS_NewFloat64(ctx, num)); |
| 557 | } |
| 558 | |
| 559 | double QTS_GetFloat64(JSContext *ctx, JSValueConst *value) { |
| 560 | double result = NAN; |
| 561 | JS_ToFloat64(ctx, &result, *value); |
| 562 | return result; |
| 563 | } |
| 564 | |
| 565 | JSValue *QTS_NewString(JSContext *ctx, BorrowedHeapChar *string) { |
| 566 | return jsvalue_to_heap(JS_NewString(ctx, string)); |
| 567 | } |
| 568 | |
| 569 | JSBorrowedChar *QTS_GetString(JSContext *ctx, JSValueConst *value) { |
| 570 | return JS_ToCString(ctx, *value); |
| 571 | } |
| 572 | |
| 573 | JSVoid *QTS_GetArrayBuffer(JSContext *ctx, JSValueConst *data) { |
| 574 | size_t length; |
| 575 | uint8_t *buffer = JS_GetArrayBuffer(ctx, &length, *data); |
| 576 | if (!buffer) |
| 577 | return 0; |
| 578 | uint8_t *result = malloc(length); |
| 579 | if (!result) |
| 580 | return result; |
| 581 | memcpy(result, buffer, length); |
| 582 | return result; |
| 583 | } |
| 584 | |
| 585 | // I don't know how to return two values in C, maybe allocate memory in stack? |
| 586 | size_t QTS_GetArrayBufferLength(JSContext *ctx, JSValueConst *data) { |
| 587 | size_t length; |
| 588 | uint8_t *buffer = JS_GetArrayBuffer(ctx, &length, *data); |
| 589 | return length; |
| 590 | } |
| 591 | |
| 592 | JSValue qts_get_symbol_key(JSContext *ctx, JSValueConst *value) { |
| 593 | JSValue global = JS_GetGlobalObject(ctx); |
| 594 | JSValue Symbol = JS_GetPropertyStr(ctx, global, "Symbol"); |
| 595 | JS_FreeValue(ctx, global); |
| 596 | |
| 597 | JSValue Symbol_keyFor = JS_GetPropertyStr(ctx, Symbol, "keyFor"); |
| 598 | JSValue key = JS_Call(ctx, Symbol_keyFor, Symbol, 1, value); |
| 599 | JS_FreeValue(ctx, Symbol_keyFor); |
| 600 | JS_FreeValue(ctx, Symbol); |
| 601 | return key; |
| 602 | } |
| 603 | |
| 604 | JSValue *QTS_NewSymbol(JSContext *ctx, BorrowedHeapChar *description, int isGlobal) { |
| 605 | JSValue global = JS_GetGlobalObject(ctx); |
| 606 | JSValue Symbol = JS_GetPropertyStr(ctx, global, "Symbol"); |
| 607 | JS_FreeValue(ctx, global); |
| 608 | JSValue descriptionValue = JS_NewString(ctx, description); |
| 609 | JSValue symbol; |
| 610 | |
| 611 | if (isGlobal != 0) { |
| 612 | JSValue Symbol_for = JS_GetPropertyStr(ctx, Symbol, "for"); |
| 613 | symbol = JS_Call(ctx, Symbol_for, Symbol, 1, &descriptionValue); |
| 614 | JS_FreeValue(ctx, descriptionValue); |
| 615 | JS_FreeValue(ctx, Symbol_for); |
| 616 | JS_FreeValue(ctx, Symbol); |
| 617 | return jsvalue_to_heap(symbol); |
| 618 | } |
| 619 | |
| 620 | symbol = JS_Call(ctx, Symbol, JS_UNDEFINED, 1, &descriptionValue); |
| 621 | JS_FreeValue(ctx, descriptionValue); |
| 622 | JS_FreeValue(ctx, Symbol); |
| 623 | |
| 624 | return jsvalue_to_heap(symbol); |
| 625 | } |
| 626 | |
| 627 | MaybeAsync(JSBorrowedChar *) QTS_GetSymbolDescriptionOrKey(JSContext *ctx, JSValueConst *value) { |
| 628 | JSBorrowedChar *result; |
| 629 | |
| 630 | JSValue key = qts_get_symbol_key(ctx, value); |
| 631 | if (!JS_IsUndefined(key)) { |
| 632 | result = JS_ToCString(ctx, key); |
| 633 | JS_FreeValue(ctx, key); |
| 634 | return result; |
| 635 | } |
| 636 | |
| 637 | JSValue description = JS_GetPropertyStr(ctx, *value, "description"); |
| 638 | result = JS_ToCString(ctx, description); |
| 639 | JS_FreeValue(ctx, description); |
| 640 | return result; |
| 641 | } |
| 642 | |
| 643 | int QTS_IsGlobalSymbol(JSContext *ctx, JSValueConst *value) { |
| 644 | JSValue key = qts_get_symbol_key(ctx, value); |
| 645 | int undefined = JS_IsUndefined(key); |
| 646 | JS_FreeValue(ctx, key); |
| 647 | |
| 648 | if (undefined) { |
| 649 | return 0; |
| 650 | } else { |
| 651 | return 1; |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | int QTS_IsJobPending(JSRuntime *rt) { |
| 656 | return JS_IsJobPending(rt); |
| 657 | } |
| 658 | |
| 659 | /* |
| 660 | runs pending jobs (Promises/async functions) until it encounters |
| 661 | an exception or it executed the passed maxJobsToExecute jobs. |
| 662 | |
| 663 | Passing a negative value will run the loop until there are no more |
| 664 | pending jobs or an exception happened |
| 665 | |
| 666 | Returns the executed number of jobs or the exception encountered |
| 667 | */ |
| 668 | MaybeAsync(JSValue *) QTS_ExecutePendingJob(JSRuntime *rt, int maxJobsToExecute, JSContext **lastJobContext) { |
| 669 | JSContext *pctx; |
| 670 | int status = 1; |
| 671 | int executed = 0; |
| 672 | while (executed != maxJobsToExecute && status == 1) { |
| 673 | status = JS_ExecutePendingJob(rt, &pctx); |
| 674 | if (status == -1) { |
| 675 | *lastJobContext = pctx; |
| 676 | return jsvalue_to_heap(JS_GetException(pctx)); |
| 677 | } else if (status == 1) { |
| 678 | *lastJobContext = pctx; |
| 679 | executed++; |
| 680 | } |
| 681 | } |
| 682 | IF_DEBUG_RT { |
| 683 | char msg[LOG_LEN]; |
| 684 | snprintf(msg, LOG_LEN, "QTS_ExecutePendingJob(executed: %d, pctx: %p, lastJobExecuted: %p)", executed, pctx, *lastJobContext); |
| 685 | qts_log(msg); |
| 686 | } |
| 687 | return jsvalue_to_heap(JS_NewFloat64(pctx, executed)); |
| 688 | } |
| 689 | |
| 690 | MaybeAsync(JSValue *) QTS_GetProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name) { |
| 691 | JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name); |
| 692 | JSValue prop_val = JS_GetProperty(ctx, *this_val, prop_atom); |
| 693 | JS_FreeAtom(ctx, prop_atom); |
| 694 | return jsvalue_to_heap(prop_val); |
| 695 | } |
| 696 | |
| 697 | MaybeAsync(JSValue *) QTS_GetPropNumber(JSContext *ctx, JSValueConst *this_val, int prop_name) { |
| 698 | JSValue prop_val = JS_GetPropertyUint32(ctx, *this_val, (uint32_t)prop_name); |
| 699 | return jsvalue_to_heap(prop_val); |
| 700 | } |
| 701 | |
| 702 | MaybeAsync(void) QTS_SetProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name, JSValueConst *prop_value) { |
| 703 | JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name); |
| 704 | JSValue extra_prop_value = JS_DupValue(ctx, *prop_value); |
| 705 | // TODO: should we use DefineProperty internally if this object doesn't have the property yet? |
| 706 | JS_SetProperty(ctx, *this_val, prop_atom, extra_prop_value); // consumes extra_prop_value |
| 707 | JS_FreeAtom(ctx, prop_atom); |
| 708 | } |
| 709 | |
| 710 | void QTS_DefineProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name, JSValueConst *prop_value, JSValueConst *get, JSValueConst *set, bool configurable, bool enumerable, |
| 711 | JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name); |
| 712 | |
| 713 | int flags = 0; |
| 714 | if (configurable) { |
| 715 | flags = flags | JS_PROP_CONFIGURABLE; |
| 716 | if (has_value) { |
| 717 | flags = flags | JS_PROP_HAS_CONFIGURABLE; |
| 718 | } |
| 719 | } |
| 720 | if (enumerable) { |
| 721 | flags = flags | JS_PROP_ENUMERABLE; |
| 722 | if (has_value) { |
| 723 | flags = flags | JS_PROP_HAS_ENUMERABLE; |
| 724 | } |
| 725 | } |
| 726 | if (!JS_IsUndefined(*get)) { |
| 727 | flags = flags | JS_PROP_HAS_GET; |
| 728 | } |
| 729 | if (!JS_IsUndefined(*set)) { |
| 730 | flags = flags | JS_PROP_HAS_SET; |
| 731 | } |
| 732 | if (has_value) { |
| 733 | flags = flags | JS_PROP_HAS_VALUE; |
| 734 | } |
| 735 | |
| 736 | JS_DefineProperty(ctx, *this_val, prop_atom, *prop_value, *get, *set, flags); |
| 737 | JS_FreeAtom(ctx, prop_atom); |
| 738 | } |
| 739 | |
| 740 | #define JS_ATOM_TAG_INT (1U << 31) |
| 741 | static inline BOOL __JS_AtomIsTaggedInt(JSAtom v) { |
| 742 | return (v & JS_ATOM_TAG_INT) != 0; |
| 743 | } |
| 744 | |
| 745 | static inline uint32_t __JS_AtomToUInt32(JSAtom atom) { |
| 746 | return atom & ~JS_ATOM_TAG_INT; |
| 747 | } |
| 748 | |
| 749 | /* include numbers. when only this is set, we filter out strings */ |
| 750 | #define QTS_GPN_NUMBER_MASK (1 << 6) |
| 751 | /* Treat numbers as strings */ |
| 752 | #define QTS_STANDARD_COMPLIANT_NUMBER (1 << 7) |
| 753 | |
| 754 | MaybeAsync(JSValue *) QTS_GetOwnPropertyNames(JSContext *ctx, JSValue ***out_ptrs, uint32_t *out_len, JSValueConst *obj, int flags) { |
| 755 | JSPropertyEnum *tab = NULL; |
| 756 | uint32_t total_props = 0; |
| 757 | uint32_t out_props = 0; |
| 758 | |
| 759 | BOOL qts_standard_compliant_number = (flags & QTS_STANDARD_COMPLIANT_NUMBER) != 0; |
| 760 | BOOL qts_include_string = (flags & JS_GPN_STRING_MASK) != 0; |
| 761 | BOOL qts_include_number = qts_standard_compliant_number ? 0 : (flags & QTS_GPN_NUMBER_MASK) != 0; |
| 762 | if (qts_include_number) { |
| 763 | // if we want numbers, we must include strings in call down |
| 764 | flags = flags | JS_GPN_STRING_MASK; |
| 765 | } |
| 766 | |
| 767 | int status = 0; |
| 768 | status = JS_GetOwnPropertyNames(ctx, &tab, &total_props, *obj, flags); |
| 769 | if (status < 0) { |
| 770 | if (tab != NULL) { |
| 771 | js_free(ctx, tab); |
| 772 | } |
| 773 | return jsvalue_to_heap(JS_GetException(ctx)); |
| 774 | } |
| 775 | *out_ptrs = malloc(sizeof(JSValue) * total_props); |
| 776 | for (int i = 0; i < total_props; i++) { |
| 777 | JSAtom atom = tab[i].atom; |
| 778 | |
| 779 | if (__JS_AtomIsTaggedInt(atom)) { |
| 780 | if (qts_include_number) { |
| 781 | uint32_t v = __JS_AtomToUInt32(atom); |
| 782 | (*out_ptrs)[out_props++] = jsvalue_to_heap(JS_NewUint32(ctx, v)); |
| 783 | } else if (qts_include_string && qts_standard_compliant_number) { |
| 784 | (*out_ptrs)[out_props++] = jsvalue_to_heap(JS_AtomToValue(ctx, tab[i].atom)); |
| 785 | } |
| 786 | JS_FreeAtom(ctx, atom); |
| 787 | continue; |
| 788 | } |
| 789 | |
| 790 | JSValue atom_value = JS_AtomToValue(ctx, atom); |
| 791 | JS_FreeAtom(ctx, atom); |
| 792 | |
| 793 | if (JS_IsString(atom_value)) { |
| 794 | if (qts_include_string) { |
| 795 | (*out_ptrs)[out_props++] = jsvalue_to_heap(atom_value); |
| 796 | } else { |
| 797 | JS_FreeValue(ctx, atom_value); |
| 798 | } |
| 799 | } else { // Symbol |
| 800 | // We must have set the includeSymbol or includePrivate flags |
| 801 | // if it's present |
| 802 | (*out_ptrs)[out_props++] = jsvalue_to_heap(atom_value); |
| 803 | } |
| 804 | } |
| 805 | js_free(ctx, tab); |
| 806 | *out_len = out_props; |
| 807 | return NULL; |
| 808 | } |
| 809 | |
| 810 | MaybeAsync(JSValue *) QTS_Call(JSContext *ctx, JSValueConst *func_obj, JSValueConst *this_obj, int argc, JSValueConst **argv_ptrs) { |
| 811 | // convert array of pointers to array of values |
| 812 | JSValueConst argv[argc]; |
| 813 | int i; |
| 814 | for (i = 0; i < argc; i++) { |
| 815 | argv[i] = *(argv_ptrs[i]); |
| 816 | } |
| 817 | |
| 818 | return jsvalue_to_heap(JS_Call(ctx, *func_obj, *this_obj, argc, argv)); |
| 819 | } |
| 820 | |
| 821 | /** |
| 822 | * If maybe_exception is an exception, get the error. |
| 823 | * Otherwise, return NULL. |
| 824 | */ |
| 825 | JSValue *QTS_ResolveException(JSContext *ctx, JSValue *maybe_exception) { |
| 826 | if (JS_IsException(*maybe_exception)) { |
| 827 | return jsvalue_to_heap(JS_GetException(ctx)); |
| 828 | } |
| 829 | |
| 830 | return NULL; |
| 831 | } |
| 832 | |
| 833 | MaybeAsync(JSBorrowedChar *) QTS_Dump(JSContext *ctx, JSValueConst *obj) { |
| 834 | JSValue obj_json_value = JS_JSONStringify(ctx, *obj, JS_UNDEFINED, JS_UNDEFINED); |
| 835 | if (!JS_IsException(obj_json_value)) { |
| 836 | const char *obj_json_chars = JS_ToCString(ctx, obj_json_value); |
| 837 | JS_FreeValue(ctx, obj_json_value); |
| 838 | if (obj_json_chars != NULL) { |
| 839 | JSValue enumerable_props = JS_ParseJSON(ctx, obj_json_chars, strlen(obj_json_chars), "<dump>"); |
| 840 | JS_FreeCString(ctx, obj_json_chars); |
| 841 | if (!JS_IsException(enumerable_props)) { |
| 842 | // Copy common non-enumerable props for different object types. |
| 843 | // Errors: |
| 844 | copy_prop_if_needed(ctx, enumerable_props, *obj, "name"); |
| 845 | copy_prop_if_needed(ctx, enumerable_props, *obj, "message"); |
| 846 | copy_prop_if_needed(ctx, enumerable_props, *obj, "stack"); |
| 847 | copy_prop_if_needed(ctx, enumerable_props, *obj, "fileName"); |
| 848 | copy_prop_if_needed(ctx, enumerable_props, *obj, "lineNumber"); |
| 849 | |
| 850 | // Serialize again. |
| 851 | JSValue enumerable_json = JS_JSONStringify(ctx, enumerable_props, JS_UNDEFINED, JS_UNDEFINED); |
| 852 | JS_FreeValue(ctx, enumerable_props); |
| 853 | |
| 854 | JSBorrowedChar *result = QTS_GetString(ctx, &enumerable_json); |
| 855 | JS_FreeValue(ctx, enumerable_json); |
| 856 | return result; |
| 857 | } |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | IF_DEBUG { |
| 862 | qts_log("Error dumping JSON:"); |
| 863 | js_std_dump_error(ctx); |
| 864 | } |
| 865 | |
| 866 | // Fallback: convert to string |
| 867 | return QTS_GetString(ctx, obj); |
| 868 | } |
| 869 | |
| 870 | JSValue qts_resolve_func_data( |
| 871 | JSContext *ctx, |
| 872 | JSValueConst this_val, |
| 873 | int argc, |
| 874 | JSValueConst *argv, |
| 875 | int magic, |
| 876 | JSValue *func_data) { |
| 877 | return JS_DupValue(ctx, func_data[0]); |
| 878 | } |
| 879 | |
| 880 | // QTS_DetectModule - bellard/quickjs style module detection heuristic. |
| 881 | // For quickjs-ng, this is patched into the amalgam (see vendor/quickjs-ng-patches/). |
| 882 | // It uses bellard's approach: skip whitespace/comments, check for 'import' or 'export'. |
| 883 | #ifdef QTS_USE_QUICKJS_NG |
| 884 | extern bool QTS_DetectModule(const char *input, size_t input_len); |
| 885 | #endif |
| 886 | |
| 887 | MaybeAsync(JSValue *) QTS_Eval(JSContext *ctx, BorrowedHeapChar *js_code, size_t js_code_length, const char *filename, EvalDetectModule detectModule, EvalFlags evalFlags) { |
| 888 | char msg[LOG_LEN]; |
| 889 | #ifdef QTS_USE_QUICKJS_NG |
| 890 | // quickjs-ng's JS_DetectModule has different behavior - it parses the code |
| 891 | // as a module and returns true if parsing succeeds. Since any valid JS |
| 892 | // expression is valid module syntax, this incorrectly detects non-modules. |
| 893 | // Use bellard/quickjs heuristic: check for import/export keywords at start. |
| 894 | if (detectModule) { |
| 895 | if (QTS_DetectModule((const char *)js_code, js_code_length)) { |
| 896 | QTS_DEBUG("QTS_Eval: quickjs-ng heuristic detected module = true"); |
| 897 | evalFlags |= JS_EVAL_TYPE_MODULE; |
| 898 | } else { |
| 899 | QTS_DEBUG("QTS_Eval: quickjs-ng heuristic detected module = false"); |
| 900 | } |
| 901 | } else { |
| 902 | QTS_DEBUG("QTS_Eval: do not detect module"); |
| 903 | } |
| 904 | #else |
| 905 | if (detectModule) { |
| 906 | if (JS_DetectModule((const char *)js_code, js_code_length)) { |
| 907 | QTS_DEBUG("QTS_Eval: Detected module = true"); |
| 908 | evalFlags |= JS_EVAL_TYPE_MODULE; |
| 909 | } else { |
| 910 | QTS_DEBUG("QTS_Eval: Detected module = false"); |
| 911 | } |
| 912 | } else { |
| 913 | QTS_DEBUG("QTS_Eval: do not detect module"); |
| 914 | } |
| 915 | #endif |
| 916 | |
| 917 | JSModuleDef *module; |
| 918 | JSValue eval_result; |
| 919 | if ( |
| 920 | (evalFlags & JS_EVAL_TYPE_MODULE) != 0 && |
| 921 | (evalFlags & JS_EVAL_FLAG_COMPILE_ONLY) == 0) { |
| 922 | QTS_DEBUG("QTS_Eval: JS_EVAL_TYPE_MODULE"); |
| 923 | JSValue func_obj = JS_Eval(ctx, js_code, js_code_length, filename, evalFlags | JS_EVAL_FLAG_COMPILE_ONLY); |
| 924 | if (JS_IsException(func_obj)) { |
| 925 | QTS_DEBUG("QTS_Eval: JS_EVAL_FLAG_COMPILE_ONLY exception") |
| 926 | return jsvalue_to_heap(func_obj); |
| 927 | } |
| 928 | |
| 929 | if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_MODULE) { |
| 930 | QTS_DEBUG("QTS_Eval: JS_EVAL_FLAG_COMPILE_ONLY result != JS_TAG_MODULE") |
| 931 | JS_FreeValue(ctx, func_obj); |
| 932 | return jsvalue_to_heap(JS_ThrowInternalError(ctx, "Module code compiled to non-module object")); |
| 933 | } |
| 934 | |
| 935 | module = JS_VALUE_GET_PTR(func_obj); |
| 936 | if (module == NULL) { |
| 937 | QTS_DEBUG("QTS_Eval: JSModuleDef == NULL") |
| 938 | JS_FreeValue(ctx, func_obj); |
| 939 | return jsvalue_to_heap(JS_ThrowInternalError(ctx, "Module compiled to null")); |
| 940 | } |
| 941 | |
| 942 | eval_result = JS_EvalFunction(ctx, func_obj); |
| 943 | QTS_DEBUG("QTS_Eval: JS_EVAL_TYPE_MODULE eval_result") |
| 944 | // It seems like this is a double-free. |
| 945 | // JS_FreeValue(ctx, func_obj); |
| 946 | } else { |
| 947 | eval_result = JS_Eval(ctx, js_code, js_code_length, filename, evalFlags); |
| 948 | QTS_DEBUG("QTS_Eval: JS_EVAL_TYPE_GLOBAL eval_result") |
| 949 | } |
| 950 | |
| 951 | IF_DEBUG { |
| 952 | snprintf(msg, LOG_LEN, "QTS_Eval: eval_result = %d", JS_VALUE_GET_TAG(eval_result)); |
| 953 | qts_log(msg); |
| 954 | } |
| 955 | |
| 956 | if ( |
| 957 | // Error - nothing more to do. |
| 958 | JS_IsException(eval_result) |
| 959 | // Non-module eval - return the result |
| 960 | || (evalFlags & JS_EVAL_TYPE_MODULE) == 0) { |
| 961 | QTS_DEBUG("QTS_Eval: non-module or exception") |
| 962 | return jsvalue_to_heap(eval_result); |
| 963 | } |
| 964 | |
| 965 | // We eval'd a module. |
| 966 | // Make our return type `ModuleExports | Promise<ModuleExports>>` |
| 967 | JSPromiseStateEnum state = JS_PromiseState(ctx, eval_result); |
| 968 | IF_DEBUG { |
| 969 | snprintf(msg, LOG_LEN, "QTS_Eval: eval_result JS_PromiseState = %i", state); |
| 970 | qts_log(msg); |
| 971 | } |
| 972 | if ( |
| 973 | // quickjs@2024-01-14 evaluating module |
| 974 | // produced a promise |
| 975 | (state == JS_PROMISE_FULFILLED) |
| 976 | // quickjs in compile mode |
| 977 | // quickjs-ng before rebasing on quickjs@2024-01-14 |
| 978 | // not a promise. |
| 979 | || (state == -1)) { |
| 980 | QTS_DEBUG("QTS_Eval: result: JS_PROMISE_FULFILLED or not a promise") |
| 981 | JS_FreeValue(ctx, eval_result); |
| 982 | return jsvalue_to_heap(JS_GetModuleNamespace(ctx, module)); |
| 983 | } else if (state == JS_PROMISE_REJECTED) { |
| 984 | // Throw the rejection response, to match evaluation of non-module code, |
| 985 | // or of code with a syntax error. |
| 986 | QTS_DEBUG("QTS_Eval: result: JS_PROMISE_REJECTED - throw rejection reason") |
| 987 | JS_Throw(ctx, JS_PromiseResult(ctx, eval_result)); |
| 988 | JS_FreeValue(ctx, eval_result); |
| 989 | return jsvalue_to_heap(JS_EXCEPTION); |
| 990 | } else if (state == JS_PROMISE_PENDING) { |
| 991 | QTS_DEBUG("QTS_Eval: result: JS_PROMISE_PENDING") |
| 992 | // return moduleDone.then(() => module_namespace) |
| 993 | JSValue module_namespace = JS_GetModuleNamespace(ctx, module); |
| 994 | if (JS_IsException(module_namespace)) { |
| 995 | QTS_DEBUG("QTS_Eval: module_namespace exception") |
| 996 | JS_FreeValue(ctx, eval_result); |
| 997 | return jsvalue_to_heap(module_namespace); |
| 998 | } |
| 999 | |
| 1000 | JSValue then_resolve_module_namespace = JS_NewCFunctionData(ctx, &qts_resolve_func_data, 0, 0, 1, &module_namespace); |
| 1001 | JS_FreeValue(ctx, module_namespace); |
| 1002 | if (JS_IsException(then_resolve_module_namespace)) { |
| 1003 | QTS_DEBUG("QTS_Eval: then_resolve_module_namespace exception") |
| 1004 | JS_FreeValue(ctx, eval_result); |
| 1005 | return jsvalue_to_heap(then_resolve_module_namespace); |
| 1006 | } |
| 1007 | |
| 1008 | JSAtom then_atom = JS_NewAtom(ctx, "then"); |
| 1009 | JSValue new_promise = JS_Invoke(ctx, eval_result, then_atom, 1, &then_resolve_module_namespace); |
| 1010 | QTS_DEBUG("QTS_Eval: new_promise = promise.then(() => resolveModuleNamespace())") |
| 1011 | JS_FreeAtom(ctx, then_atom); |
| 1012 | JS_FreeValue(ctx, then_resolve_module_namespace); |
| 1013 | JS_FreeValue(ctx, eval_result); |
| 1014 | |
| 1015 | return jsvalue_to_heap(new_promise); |
| 1016 | } else { |
| 1017 | // Unknown case |
| 1018 | QTS_DEBUG("QTS_Eval: unknown JSPromiseStateEnum") |
| 1019 | return jsvalue_to_heap(eval_result); |
| 1020 | } |
| 1021 | } |
| 1022 | |
| 1023 | JSValue *QTS_GetModuleNamespace(JSContext *ctx, JSValueConst *module_func_obj) { |
| 1024 | if (JS_VALUE_GET_TAG(*module_func_obj) != JS_TAG_MODULE) { |
| 1025 | return jsvalue_to_heap(JS_ThrowInternalError(ctx, "Not a module")); |
| 1026 | } |
| 1027 | |
| 1028 | JSModuleDef *module = JS_VALUE_GET_PTR(*module_func_obj); |
| 1029 | return jsvalue_to_heap(JS_GetModuleNamespace(ctx, module)); |
| 1030 | } |
| 1031 | |
| 1032 | OwnedHeapChar *QTS_Typeof(JSContext *ctx, JSValueConst *value) { |
| 1033 | const char *result = "unknown"; |
| 1034 | |
| 1035 | if (JS_IsNumber(*value)) { |
| 1036 | result = "number"; |
| 1037 | } else if (QTS_JS_IsBigInt(ctx, *value)) { |
| 1038 | result = "bigint"; |
| 1039 | } else if (JS_IsFunction(ctx, *value)) { |
| 1040 | result = "function"; |
| 1041 | } else if (JS_IsBool(*value)) { |
| 1042 | result = "boolean"; |
| 1043 | } else if (JS_IsNull(*value)) { |
| 1044 | result = "object"; |
| 1045 | } else if (JS_IsUndefined(*value)) { |
| 1046 | result = "undefined"; |
| 1047 | } else if (JS_IsUninitialized(*value)) { |
| 1048 | result = "undefined"; |
| 1049 | } else if (JS_IsString(*value)) { |
| 1050 | result = "string"; |
| 1051 | } else if (JS_IsSymbol(*value)) { |
| 1052 | result = "symbol"; |
| 1053 | } else if (JS_IsObject(*value)) { |
| 1054 | result = "object"; |
| 1055 | } |
| 1056 | |
| 1057 | char *out = strdup(result); |
| 1058 | return out; |
| 1059 | } |
| 1060 | |
| 1061 | JSAtom QTS_AtomLength = 0; |
| 1062 | int QTS_GetLength(JSContext *ctx, uint32_t *out_len, JSValueConst *value) { |
| 1063 | JSValue len_val; |
| 1064 | int result; |
| 1065 | |
| 1066 | if (!JS_IsObject(*value)) { |
| 1067 | return -1; |
| 1068 | } |
| 1069 | |
| 1070 | if (QTS_AtomLength == 0) { |
| 1071 | // This should result in a constant static atom we don't actually need to |
| 1072 | // free, since it's interned within quickjs.c |
| 1073 | QTS_AtomLength = JS_NewAtom(ctx, "length"); |
| 1074 | } |
| 1075 | |
| 1076 | len_val = JS_GetProperty(ctx, *value, QTS_AtomLength); |
| 1077 | if (JS_IsException(len_val)) { |
| 1078 | return -1; |
| 1079 | } |
| 1080 | |
| 1081 | result = JS_ToUint32(ctx, out_len, len_val); |
| 1082 | JS_FreeValue(ctx, len_val); |
| 1083 | return result; |
| 1084 | } |
| 1085 | |
| 1086 | typedef enum IsEqualOp { |
| 1087 | QTS_EqualOp_StrictEq = 0, |
| 1088 | QTS_EqualOp_SameValue = 1, |
| 1089 | QTS_EqualOp_SameValueZero = 2, |
| 1090 | } IsEqualOp; |
| 1091 | |
| 1092 | int QTS_IsEqual(JSContext *ctx, JSValueConst *a, JSValueConst *b, IsEqualOp op) { |
| 1093 | #ifdef QTS_USE_QUICKJS_NG |
| 1094 | return -1; |
| 1095 | #else |
| 1096 | switch (op) { |
| 1097 | case QTS_EqualOp_SameValue: |
| 1098 | return JS_SameValue(ctx, *a, *b); |
| 1099 | case QTS_EqualOp_SameValueZero: |
| 1100 | return JS_SameValueZero(ctx, *a, *b); |
| 1101 | default: |
| 1102 | case QTS_EqualOp_StrictEq: |
| 1103 | return JS_StrictEq(ctx, *a, *b); |
| 1104 | } |
| 1105 | #endif |
| 1106 | } |
| 1107 | |
| 1108 | JSValue *QTS_GetGlobalObject(JSContext *ctx) { |
| 1109 | return jsvalue_to_heap(JS_GetGlobalObject(ctx)); |
| 1110 | } |
| 1111 | |
| 1112 | JSValue *QTS_NewPromiseCapability(JSContext *ctx, JSValue **resolve_funcs_out) { |
| 1113 | JSValue resolve_funcs[2]; |
| 1114 | JSValue promise = JS_NewPromiseCapability(ctx, resolve_funcs); |
| 1115 | resolve_funcs_out[0] = jsvalue_to_heap(resolve_funcs[0]); |
| 1116 | resolve_funcs_out[1] = jsvalue_to_heap(resolve_funcs[1]); |
| 1117 | return jsvalue_to_heap(promise); |
| 1118 | } |
| 1119 | |
| 1120 | JSPromiseStateEnum QTS_PromiseState(JSContext *ctx, JSValueConst *promise) { |
| 1121 | return JS_PromiseState(ctx, *promise); |
| 1122 | } |
| 1123 | |
| 1124 | JSValue *QTS_PromiseResult(JSContext *ctx, JSValueConst *promise) { |
| 1125 | return jsvalue_to_heap(JS_PromiseResult(ctx, *promise)); |
| 1126 | } |
| 1127 | |
| 1128 | void QTS_TestStringArg(const char *string) { |
| 1129 | // pass |
| 1130 | } |
| 1131 | |
| 1132 | int QTS_GetDebugLogEnabled(JSRuntime *rt) { |
| 1133 | IF_DEBUG_RT { |
| 1134 | return 1; |
| 1135 | } |
| 1136 | return 0; |
| 1137 | } |
| 1138 | |
| 1139 | void QTS_SetDebugLogEnabled(JSRuntime *rt, int is_enabled) { |
| 1140 | #ifdef QTS_DEBUG_MODE |
| 1141 | qts_get_runtime_data(rt)->debug_log = (bool)is_enabled; |
| 1142 | #endif |
| 1143 | } |
| 1144 | |
| 1145 | int QTS_BuildIsDebug() { |
| 1146 | #ifdef QTS_DEBUG_MODE |
| 1147 | return 1; |
| 1148 | #else |
| 1149 | return 0; |
| 1150 | #endif |
| 1151 | } |
| 1152 | |
| 1153 | int QTS_BuildIsAsyncify() { |
| 1154 | #ifdef QTS_ASYNCIFY |
| 1155 | return 1; |
| 1156 | #else |
| 1157 | return 0; |
| 1158 | #endif |
| 1159 | } |
| 1160 | |
| 1161 | // ---------------------------------------------------------------------------- |
| 1162 | // C -> Host Callbacks |
| 1163 | // Note: inside EM_JS, we need to use ['...'] subscript syntax for accessing JS |
| 1164 | // objects, because in optimized builds, Closure compiler will mangle all the |
| 1165 | // names. |
| 1166 | |
| 1167 | // ------------------- |
| 1168 | // function: C -> Host |
| 1169 | #ifdef __EMSCRIPTEN__ |
| 1170 | EM_JS(MaybeAsync(JSValue *), qts_host_call_function, (JSContext * ctx, JSValueConst *this_ptr, int argc, JSValueConst *argv, HostRefId host_ref_id), { |
| 1171 | #ifdef QTS_ASYNCIFY |
| 1172 | const asyncify = {['handleSleep'] : Asyncify.handleSleep}; |
| 1173 | #else |
| 1174 | const asyncify = undefined; |
| 1175 | #endif |
| 1176 | return Module['callbacks']['callFunction'](asyncify, ctx, this_ptr, argc, argv, host_ref_id); |
| 1177 | }); |
| 1178 | #endif |
| 1179 | |
| 1180 | // Function: QuickJS -> C |
| 1181 | JSValue qts_call_function(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data) { |
| 1182 | int32_t host_ref_id = 0; |
| 1183 | HostRef *host_ref = JS_GetOpaque(*func_data, host_ref_class_id); |
| 1184 | if (host_ref) { |
| 1185 | host_ref_id = host_ref->id; |
| 1186 | } |
| 1187 | |
| 1188 | JSValue *result_ptr = qts_host_call_function(ctx, &this_val, argc, argv, host_ref_id); |
| 1189 | if (result_ptr == NULL) { |
| 1190 | return JS_UNDEFINED; |
| 1191 | } |
| 1192 | JSValue result = *result_ptr; |
| 1193 | free(result_ptr); |
| 1194 | return result; |
| 1195 | } |
| 1196 | |
| 1197 | // Function: Host -> QuickJS |
| 1198 | JSValue *QTS_NewFunction(JSContext *ctx, const char *name, int arg_length, bool is_constructor, HostRefId host_ref_id) { |
| 1199 | IF_DEBUG { |
| 1200 | char msg[LOG_LEN]; |
| 1201 | snprintf(msg, LOG_LEN, "new_function(name: %s, length: %d, is_constructor: %d, host_ref_id: %d)", name, arg_length, is_constructor, host_ref_id); |
| 1202 | qts_log(msg); |
| 1203 | } |
| 1204 | |
| 1205 | JSValue host_ref = new_host_ref(ctx, host_ref_id); |
| 1206 | if (JS_IsException(host_ref)) { |
| 1207 | return jsvalue_to_heap(host_ref); |
| 1208 | } |
| 1209 | |
| 1210 | JSValue func_obj = JS_NewCFunctionData( |
| 1211 | /* context */ ctx, |
| 1212 | /* JSCFunctionData* */ &qts_call_function, |
| 1213 | /* fn.length */ 0, |
| 1214 | /* magic */ 0, |
| 1215 | /* data length */ 1, |
| 1216 | /* data */ &host_ref |
| 1217 | ); |
| 1218 | JS_FreeValue(ctx, host_ref); |
| 1219 | |
| 1220 | if (JS_IsException(func_obj)) { |
| 1221 | return jsvalue_to_heap(func_obj); |
| 1222 | } |
| 1223 | |
| 1224 | if (name && strlen(name) > 0) { |
| 1225 | JSValue name_val = JS_NewString(ctx, name); |
| 1226 | if (JS_IsException(name_val)) { |
| 1227 | JS_FreeValue(ctx, func_obj); |
| 1228 | return jsvalue_to_heap(name_val); |
| 1229 | } |
| 1230 | // JS_DefinePropertyValueStr takes ownership of name_val and frees it |
| 1231 | JS_DefinePropertyValueStr(ctx, func_obj, "name", name_val, JS_PROP_CONFIGURABLE); |
| 1232 | } |
| 1233 | |
| 1234 | if (is_constructor) { |
| 1235 | JS_SetConstructorBit(ctx, func_obj, is_constructor); |
| 1236 | } |
| 1237 | |
| 1238 | return jsvalue_to_heap(func_obj); |
| 1239 | } |
| 1240 | |
| 1241 | JSValueConst *QTS_ArgvGetJSValueConstPointer(JSValueConst *argv, int index) { |
| 1242 | return &argv[index]; |
| 1243 | } |
| 1244 | |
| 1245 | // -------------------- |
| 1246 | // interrupt: C -> Host |
| 1247 | #ifdef __EMSCRIPTEN__ |
| 1248 | EM_JS(int, qts_host_interrupt_handler, (JSRuntime * rt), { |
| 1249 | // Async not supported here. |
| 1250 | // #ifdef QTS_ASYNCIFY |
| 1251 | // const asyncify = Asyncify; |
| 1252 | // #else |
| 1253 | const asyncify = undefined; |
| 1254 | // #endif |
| 1255 | return Module['callbacks']['shouldInterrupt'](asyncify, rt); |
| 1256 | }); |
| 1257 | #endif |
| 1258 | |
| 1259 | // interrupt: QuickJS -> C |
| 1260 | #if defined(QJS_VERSION_MAJOR) && (QJS_VERSION_MAJOR > 0 || QJS_VERSION_MINOR >= 17) |
| 1261 | /* quickjs-ng 0.17: the interrupt handler receives the context; the host still keys on the runtime. */ |
| 1262 | int qts_interrupt_handler(JSContext *ctx, void *_unused) { |
| 1263 | return qts_host_interrupt_handler(JS_GetRuntime(ctx)); |
| 1264 | } |
| 1265 | #else |
| 1266 | int qts_interrupt_handler(JSRuntime *rt, void *_unused) { |
| 1267 | return qts_host_interrupt_handler(rt); |
| 1268 | } |
| 1269 | #endif |
| 1270 | |
| 1271 | // interrupt: Host -> QuickJS |
| 1272 | void QTS_RuntimeEnableInterruptHandler(JSRuntime *rt) { |
| 1273 | JS_SetInterruptHandler(rt, &qts_interrupt_handler, NULL); |
| 1274 | } |
| 1275 | |
| 1276 | void QTS_RuntimeDisableInterruptHandler(JSRuntime *rt) { |
| 1277 | JS_SetInterruptHandler(rt, NULL, NULL); |
| 1278 | } |
| 1279 | |
| 1280 | // ---------------------------------------------------------------------------- |
| 1281 | // Module loading helpers |
| 1282 | // -------------------- |
| 1283 | // load module: C -> Host |
| 1284 | // TODO: a future version can support host returning JSModuleDef* directly; |
| 1285 | // for now we only support loading module source code. |
| 1286 | |
| 1287 | /* |
| 1288 | The module loading model under ASYNCIFY is convoluted. We need to make sure we |
| 1289 | never have an async request running concurrently for loading modules. |
| 1290 | |
| 1291 | The first implemenation looked like this: |
| 1292 | |
| 1293 | C HOST SUSPENDED |
| 1294 | qts_host_load_module(name) ------> false |
| 1295 | call rt.loadModule(name) false |
| 1296 | Start async load module false |
| 1297 | Suspend C true |
| 1298 | Async load complete true |
| 1299 | < --------------- QTS_CompileModule(source) true |
| 1300 | QTS_Eval(source, COMPILE_ONLY) true |
| 1301 | Loaded module has import true |
| 1302 | qts_host_load_module(dep) -------> true |
| 1303 | call rt.loadModule(dep) true |
| 1304 | Start async load module true |
| 1305 | ALREADY SUSPENDED, CRASH |
| 1306 | |
| 1307 | We can solve this in two different ways: |
| 1308 | |
| 1309 | 1. Return to C as soon as we async load the module source. |
| 1310 | That way, we unsuspend before calling QTS_CompileModule. |
| 1311 | 2. Once we load the module, use a new API to detect and async |
| 1312 | load the module's downstream dependencies. This way |
| 1313 | they're loaded synchronously so we don't need to suspend "again". |
| 1314 | |
| 1315 | Probably we could optimize (2) to make it more performant, eg with parallel |
| 1316 | loading, but (1) seems much easier to implement in the sort run. |
| 1317 | */ |
| 1318 | |
| 1319 | JSModuleDef *qts_compile_module(JSContext *ctx, const char *module_name, BorrowedHeapChar *module_body) { |
| 1320 | IF_DEBUG { |
| 1321 | char msg[LOG_LEN]; |
| 1322 | sprintf(msg, "QTS_CompileModule(ctx: %p, name: %s, bodyLength: %lu)", ctx, module_name, strlen(module_body)); |
| 1323 | qts_log(msg); |
| 1324 | } |
| 1325 | JSValue func_val = JS_Eval(ctx, module_body, strlen(module_body), module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); |
| 1326 | if (JS_IsException(func_val)) { |
| 1327 | return NULL; |
| 1328 | } |
| 1329 | // TODO: Is exception ok? |
| 1330 | // TODO: set import.meta? |
| 1331 | JSModuleDef *module = JS_VALUE_GET_PTR(func_val); |
| 1332 | JS_FreeValue(ctx, func_val); |
| 1333 | return module; |
| 1334 | } |
| 1335 | |
| 1336 | #ifdef __EMSCRIPTEN__ |
| 1337 | EM_JS(MaybeAsync(char *), qts_host_load_module_source, (JSRuntime * rt, JSContext *ctx, const char *module_name), { |
| 1338 | #ifdef QTS_ASYNCIFY |
| 1339 | const asyncify = {['handleSleep'] : Asyncify.handleSleep}; |
| 1340 | #else |
| 1341 | const asyncify = undefined; |
| 1342 | #endif |
| 1343 | // https://emscripten.org/docs/api_reference/preamble.js.html#UTF8ToString |
| 1344 | const moduleNameString = UTF8ToString(module_name); |
| 1345 | return Module['callbacks']['loadModuleSource'](asyncify, rt, ctx, moduleNameString); |
| 1346 | }); |
| 1347 | |
| 1348 | EM_JS(MaybeAsync(char *), qts_host_normalize_module, (JSRuntime * rt, JSContext *ctx, const char *module_base_name, const char *module_name), { |
| 1349 | #ifdef QTS_ASYNCIFY |
| 1350 | const asyncify = {['handleSleep'] : Asyncify.handleSleep}; |
| 1351 | #else |
| 1352 | const asyncify = undefined; |
| 1353 | #endif |
| 1354 | // https://emscripten.org/docs/api_reference/preamble.js.html#UTF8ToString |
| 1355 | const moduleBaseNameString = UTF8ToString(module_base_name); |
| 1356 | const moduleNameString = UTF8ToString(module_name); |
| 1357 | return Module['callbacks']['normalizeModule'](asyncify, rt, ctx, moduleBaseNameString, moduleNameString); |
| 1358 | }); |
| 1359 | #endif |
| 1360 | |
| 1361 | // load module: QuickJS -> C |
| 1362 | // See js_module_loader in quickjs/quickjs-libc.c:567 |
| 1363 | JSModuleDef *qts_load_module(JSContext *ctx, const char *module_name, void *_unused) { |
| 1364 | JSRuntime *rt = JS_GetRuntime(ctx); |
| 1365 | IF_DEBUG_RT { |
| 1366 | char msg[LOG_LEN]; |
| 1367 | sprintf(msg, "qts_load_module(rt: %p, ctx: %p, name: %s)", rt, ctx, module_name); |
| 1368 | qts_log(msg); |
| 1369 | } |
| 1370 | char *module_source = qts_host_load_module_source(rt, ctx, module_name); |
| 1371 | if (module_source == NULL) { |
| 1372 | return NULL; |
| 1373 | } |
| 1374 | |
| 1375 | JSModuleDef *module = qts_compile_module(ctx, module_name, module_source); |
| 1376 | free(module_source); |
| 1377 | return module; |
| 1378 | } |
| 1379 | |
| 1380 | char *qts_normalize_module(JSContext *ctx, const char *module_base_name, const char *module_name, void *_unused) { |
| 1381 | JSRuntime *rt = JS_GetRuntime(ctx); |
| 1382 | IF_DEBUG_RT { |
| 1383 | char msg[LOG_LEN]; |
| 1384 | sprintf(msg, "qts_normalize_module(rt: %p, ctx: %p, base_name: %s, name: %s)", rt, ctx, module_base_name, module_name); |
| 1385 | qts_log(msg); |
| 1386 | } |
| 1387 | char *em_module_name = qts_host_normalize_module(rt, ctx, module_base_name, module_name); |
| 1388 | char *js_module_name = js_strdup(ctx, em_module_name); |
| 1389 | free(em_module_name); |
| 1390 | return js_module_name; |
| 1391 | } |
| 1392 | |
| 1393 | // Load module: Host -> QuickJS |
| 1394 | void QTS_RuntimeEnableModuleLoader(JSRuntime *rt, int use_custom_normalize) { |
| 1395 | JSModuleNormalizeFunc *module_normalize = NULL; /* use default name normalizer */ |
| 1396 | if (use_custom_normalize) { |
| 1397 | module_normalize = &qts_normalize_module; |
| 1398 | } |
| 1399 | JS_SetModuleLoaderFunc(rt, module_normalize, &qts_load_module, NULL); |
| 1400 | } |
| 1401 | |
| 1402 | void QTS_RuntimeDisableModuleLoader(JSRuntime *rt) { |
| 1403 | JS_SetModuleLoaderFunc(rt, NULL, NULL, NULL); |
| 1404 | } |
| 1405 | |
| 1406 | JSValue *QTS_bjson_encode(JSContext *ctx, JSValueConst *val) { |
| 1407 | size_t length; |
| 1408 | uint8_t *buffer = JS_WriteObject(ctx, &length, *val, JS_WRITE_OBJ_REFERENCE); |
| 1409 | if (!buffer) |
| 1410 | return jsvalue_to_heap(JS_EXCEPTION); |
| 1411 | |
| 1412 | JSValue array = JS_NewArrayBufferCopy(ctx, buffer, length); |
| 1413 | js_free(ctx, buffer); |
| 1414 | return jsvalue_to_heap(array); |
| 1415 | } |
| 1416 | |
| 1417 | JSValue *QTS_bjson_decode(JSContext *ctx, JSValueConst *data) { |
| 1418 | size_t length; |
| 1419 | uint8_t *buffer = JS_GetArrayBuffer(ctx, &length, *data); |
| 1420 | if (!buffer) |
| 1421 | return jsvalue_to_heap(JS_EXCEPTION); |
| 1422 | |
| 1423 | JSValue value = JS_ReadObject(ctx, buffer, length, 0); |
| 1424 | return jsvalue_to_heap(value); |
| 1425 | } |