interface.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. #ifdef __EMSCRIPTEN__
  36. #include <emscripten.h>
  37. #endif
  38. #include <math.h> // For NAN
  39. #include <stdbool.h>
  40. #include <stdio.h>
  41. #include <string.h>
  42. #ifdef QTS_SANITIZE_LEAK
  43. #include <sanitizer/lsan_interface.h>
  44. #endif
  45. #include "../quickjs/cutils.h"
  46. #include "../quickjs/quickjs-libc.h"
  47. #include "../quickjs/quickjs.h"
  48. #define PKG "quickjs-emscripten: "
  49. #ifdef QTS_DEBUG_MODE
  50. #define QTS_DEBUG(msg) qts_log(msg);
  51. #define QTS_DUMP(value) qts_dump(ctx, value);
  52. #else
  53. #define QTS_DEBUG(msg) ;
  54. #define QTS_DUMP(value) ;
  55. #endif
  56. /**
  57. * Signal to our FFI code generator that this string argument should be passed as a pointer
  58. * allocated by the caller on the heap, not a JS string on the stack.
  59. * https://github.com/emscripten-core/emscripten/issues/6860#issuecomment-405818401
  60. */
  61. #define BorrowedHeapChar const char
  62. #define OwnedHeapChar char
  63. #define JSBorrowedChar const char
  64. /**
  65. * Signal to our FFI code generator that this function should be called
  66. * asynchronously when compiled with ASYNCIFY.
  67. */
  68. #define MaybeAsync(T) T
  69. /**
  70. * Signal to our FFI code generator that this function is only available in
  71. * ASYNCIFY builds.
  72. */
  73. #define AsyncifyOnly(T) T
  74. #define JSVoid void
  75. #define EvalFlags int
  76. #define EvalDetectModule int
  77. void qts_log(char *msg) {
  78. fputs(PKG, stderr);
  79. fputs(msg, stderr);
  80. fputs("\n", stderr);
  81. }
  82. void qts_dump(JSContext *ctx, JSValueConst value) {
  83. const char *str = JS_ToCString(ctx, value);
  84. if (!str) {
  85. QTS_DEBUG("QTS_DUMP: can't dump");
  86. return;
  87. }
  88. fputs(str, stderr);
  89. JS_FreeCString(ctx, str);
  90. putchar('\n');
  91. }
  92. void copy_prop_if_needed(JSContext *ctx, JSValueConst dest, JSValueConst src, const char *prop_name) {
  93. JSAtom prop_atom = JS_NewAtom(ctx, prop_name);
  94. JSValue dest_prop = JS_GetProperty(ctx, dest, prop_atom);
  95. if (JS_IsUndefined(dest_prop)) {
  96. JSValue src_prop = JS_GetProperty(ctx, src, prop_atom);
  97. if (!JS_IsUndefined(src_prop) && !JS_IsException(src_prop)) {
  98. JS_SetProperty(ctx, dest, prop_atom, src_prop);
  99. }
  100. } else {
  101. JS_FreeValue(ctx, dest_prop);
  102. }
  103. JS_FreeAtom(ctx, prop_atom);
  104. }
  105. JSValue *jsvalue_to_heap(JSValueConst value) {
  106. JSValue *result = malloc(sizeof(JSValue));
  107. if (result) {
  108. // Could be better optimized, but at -0z / -ftlo, it
  109. // appears to produce the same binary code as a memcpy.
  110. *result = value;
  111. }
  112. return result;
  113. }
  114. JSValue *QTS_Throw(JSContext *ctx, JSValueConst *error) {
  115. JSValue copy = JS_DupValue(ctx, *error);
  116. return jsvalue_to_heap(JS_Throw(ctx, copy));
  117. }
  118. JSValue *QTS_NewError(JSContext *ctx) {
  119. return jsvalue_to_heap(JS_NewError(ctx));
  120. }
  121. /**
  122. * Limits.
  123. */
  124. /**
  125. * Memory limit. Set to -1 to disable.
  126. */
  127. void QTS_RuntimeSetMemoryLimit(JSRuntime *rt, size_t limit) {
  128. JS_SetMemoryLimit(rt, limit);
  129. }
  130. /**
  131. * Memory diagnostics
  132. */
  133. JSValue *QTS_RuntimeComputeMemoryUsage(JSRuntime *rt, JSContext *ctx) {
  134. JSMemoryUsage s;
  135. JS_ComputeMemoryUsage(rt, &s);
  136. // Note that we're going to allocate more memory just to report the memory usage.
  137. // A more sound approach would be to bind JSMemoryUsage struct directly - but that's
  138. // a lot of work. This should be okay in the mean time.
  139. JSValue result = JS_NewObject(ctx);
  140. // Manually generated via editor-fu from JSMemoryUsage struct definition in quickjs.h
  141. JS_SetPropertyStr(ctx, result, "malloc_limit", JS_NewInt64(ctx, s.malloc_limit));
  142. JS_SetPropertyStr(ctx, result, "memory_used_size", JS_NewInt64(ctx, s.memory_used_size));
  143. JS_SetPropertyStr(ctx, result, "malloc_count", JS_NewInt64(ctx, s.malloc_count));
  144. JS_SetPropertyStr(ctx, result, "memory_used_count", JS_NewInt64(ctx, s.memory_used_count));
  145. JS_SetPropertyStr(ctx, result, "atom_count", JS_NewInt64(ctx, s.atom_count));
  146. JS_SetPropertyStr(ctx, result, "atom_size", JS_NewInt64(ctx, s.atom_size));
  147. JS_SetPropertyStr(ctx, result, "str_count", JS_NewInt64(ctx, s.str_count));
  148. JS_SetPropertyStr(ctx, result, "str_size", JS_NewInt64(ctx, s.str_size));
  149. JS_SetPropertyStr(ctx, result, "obj_count", JS_NewInt64(ctx, s.obj_count));
  150. JS_SetPropertyStr(ctx, result, "obj_size", JS_NewInt64(ctx, s.obj_size));
  151. JS_SetPropertyStr(ctx, result, "prop_count", JS_NewInt64(ctx, s.prop_count));
  152. JS_SetPropertyStr(ctx, result, "prop_size", JS_NewInt64(ctx, s.prop_size));
  153. JS_SetPropertyStr(ctx, result, "shape_count", JS_NewInt64(ctx, s.shape_count));
  154. JS_SetPropertyStr(ctx, result, "shape_size", JS_NewInt64(ctx, s.shape_size));
  155. JS_SetPropertyStr(ctx, result, "js_func_count", JS_NewInt64(ctx, s.js_func_count));
  156. JS_SetPropertyStr(ctx, result, "js_func_size", JS_NewInt64(ctx, s.js_func_size));
  157. JS_SetPropertyStr(ctx, result, "js_func_code_size", JS_NewInt64(ctx, s.js_func_code_size));
  158. JS_SetPropertyStr(ctx, result, "js_func_pc2line_count", JS_NewInt64(ctx, s.js_func_pc2line_count));
  159. JS_SetPropertyStr(ctx, result, "js_func_pc2line_size", JS_NewInt64(ctx, s.js_func_pc2line_size));
  160. JS_SetPropertyStr(ctx, result, "c_func_count", JS_NewInt64(ctx, s.c_func_count));
  161. JS_SetPropertyStr(ctx, result, "array_count", JS_NewInt64(ctx, s.array_count));
  162. JS_SetPropertyStr(ctx, result, "fast_array_count", JS_NewInt64(ctx, s.fast_array_count));
  163. JS_SetPropertyStr(ctx, result, "fast_array_elements", JS_NewInt64(ctx, s.fast_array_elements));
  164. JS_SetPropertyStr(ctx, result, "binary_object_count", JS_NewInt64(ctx, s.binary_object_count));
  165. JS_SetPropertyStr(ctx, result, "binary_object_size", JS_NewInt64(ctx, s.binary_object_size));
  166. return jsvalue_to_heap(result);
  167. }
  168. OwnedHeapChar *QTS_RuntimeDumpMemoryUsage(JSRuntime *rt) {
  169. char *result = malloc(sizeof(char) * 1024);
  170. FILE *memfile = fmemopen(result, 1024, "w");
  171. JSMemoryUsage s;
  172. JS_ComputeMemoryUsage(rt, &s);
  173. JS_DumpMemoryUsage(memfile, &s, rt);
  174. fclose(memfile);
  175. return result;
  176. }
  177. int QTS_RecoverableLeakCheck() {
  178. #ifdef QTS_SANITIZE_LEAK
  179. return __lsan_do_recoverable_leak_check();
  180. #else
  181. return 0;
  182. #endif
  183. }
  184. int QTS_BuildIsSanitizeLeak() {
  185. #ifdef QTS_SANITIZE_LEAK
  186. return 1;
  187. #else
  188. return 0;
  189. #endif
  190. }
  191. #ifdef QTS_ASYNCIFY
  192. EM_JS(void, set_asyncify_stack_size, (size_t size), {
  193. Asyncify.StackSize = size || 81920;
  194. });
  195. #endif
  196. /**
  197. * Set the stack size limit, in bytes. Set to 0 to disable.
  198. */
  199. void QTS_RuntimeSetMaxStackSize(JSRuntime *rt, size_t stack_size) {
  200. #ifdef QTS_ASYNCIFY
  201. set_asyncify_stack_size(stack_size);
  202. #endif
  203. JS_SetMaxStackSize(rt, stack_size);
  204. }
  205. /**
  206. * Constant pointers. Because we always use JSValue* from the host Javascript environment,
  207. * we need helper fuctions to return pointers to these constants.
  208. */
  209. JSValueConst QTS_Undefined = JS_UNDEFINED;
  210. JSValueConst *QTS_GetUndefined() {
  211. return &QTS_Undefined;
  212. }
  213. JSValueConst QTS_Null = JS_NULL;
  214. JSValueConst *QTS_GetNull() {
  215. return &QTS_Null;
  216. }
  217. JSValueConst QTS_False = JS_FALSE;
  218. JSValueConst *QTS_GetFalse() {
  219. return &QTS_False;
  220. }
  221. JSValueConst QTS_True = JS_TRUE;
  222. JSValueConst *QTS_GetTrue() {
  223. return &QTS_True;
  224. }
  225. /**
  226. * Standard FFI functions
  227. */
  228. JSRuntime *QTS_NewRuntime() {
  229. return JS_NewRuntime();
  230. }
  231. void QTS_FreeRuntime(JSRuntime *rt) {
  232. JS_FreeRuntime(rt);
  233. }
  234. JSContext *QTS_NewContext(JSRuntime *rt) {
  235. return JS_NewContext(rt);
  236. }
  237. void QTS_FreeContext(JSContext *ctx) {
  238. JS_FreeContext(ctx);
  239. }
  240. void QTS_FreeValuePointer(JSContext *ctx, JSValue *value) {
  241. JS_FreeValue(ctx, *value);
  242. free(value);
  243. }
  244. void QTS_FreeValuePointerRuntime(JSRuntime *rt, JSValue *value) {
  245. JS_FreeValueRT(rt, *value);
  246. free(value);
  247. }
  248. void QTS_FreeVoidPointer(JSContext *ctx, JSVoid *ptr) {
  249. js_free(ctx, ptr);
  250. }
  251. void QTS_FreeCString(JSContext *ctx, JSBorrowedChar *str) {
  252. JS_FreeCString(ctx, str);
  253. }
  254. JSValue *QTS_DupValuePointer(JSContext *ctx, JSValueConst *val) {
  255. return jsvalue_to_heap(JS_DupValue(ctx, *val));
  256. }
  257. JSValue *QTS_NewObject(JSContext *ctx) {
  258. return jsvalue_to_heap(JS_NewObject(ctx));
  259. }
  260. JSValue *QTS_NewObjectProto(JSContext *ctx, JSValueConst *proto) {
  261. return jsvalue_to_heap(JS_NewObjectProto(ctx, *proto));
  262. }
  263. JSValue *QTS_NewArray(JSContext *ctx) {
  264. return jsvalue_to_heap(JS_NewArray(ctx));
  265. }
  266. JSValue *QTS_NewFloat64(JSContext *ctx, double num) {
  267. return jsvalue_to_heap(JS_NewFloat64(ctx, num));
  268. }
  269. double QTS_GetFloat64(JSContext *ctx, JSValueConst *value) {
  270. double result = NAN;
  271. JS_ToFloat64(ctx, &result, *value);
  272. return result;
  273. }
  274. JSValue *QTS_NewString(JSContext *ctx, BorrowedHeapChar *string) {
  275. return jsvalue_to_heap(JS_NewString(ctx, string));
  276. }
  277. JSBorrowedChar *QTS_GetString(JSContext *ctx, JSValueConst *value) {
  278. return JS_ToCString(ctx, *value);
  279. }
  280. JSValue qts_get_symbol_key(JSContext *ctx, JSValueConst *value) {
  281. JSValue global = JS_GetGlobalObject(ctx);
  282. JSValue Symbol = JS_GetPropertyStr(ctx, global, "Symbol");
  283. JS_FreeValue(ctx, global);
  284. JSValue Symbol_keyFor = JS_GetPropertyStr(ctx, Symbol, "keyFor");
  285. JSValue key = JS_Call(ctx, Symbol_keyFor, Symbol, 1, value);
  286. JS_FreeValue(ctx, Symbol_keyFor);
  287. JS_FreeValue(ctx, Symbol);
  288. return key;
  289. }
  290. JSValue *QTS_NewSymbol(JSContext *ctx, BorrowedHeapChar *description, int isGlobal) {
  291. JSValue global = JS_GetGlobalObject(ctx);
  292. JSValue Symbol = JS_GetPropertyStr(ctx, global, "Symbol");
  293. JS_FreeValue(ctx, global);
  294. JSValue descriptionValue = JS_NewString(ctx, description);
  295. JSValue symbol;
  296. if (isGlobal != 0) {
  297. JSValue Symbol_for = JS_GetPropertyStr(ctx, Symbol, "for");
  298. symbol = JS_Call(ctx, Symbol_for, Symbol, 1, &descriptionValue);
  299. JS_FreeValue(ctx, descriptionValue);
  300. JS_FreeValue(ctx, Symbol_for);
  301. JS_FreeValue(ctx, Symbol);
  302. return jsvalue_to_heap(symbol);
  303. }
  304. symbol = JS_Call(ctx, Symbol, JS_UNDEFINED, 1, &descriptionValue);
  305. JS_FreeValue(ctx, descriptionValue);
  306. JS_FreeValue(ctx, Symbol);
  307. return jsvalue_to_heap(symbol);
  308. }
  309. MaybeAsync(JSBorrowedChar *) QTS_GetSymbolDescriptionOrKey(JSContext *ctx, JSValueConst *value) {
  310. JSBorrowedChar *result;
  311. JSValue key = qts_get_symbol_key(ctx, value);
  312. if (!JS_IsUndefined(key)) {
  313. result = JS_ToCString(ctx, key);
  314. JS_FreeValue(ctx, key);
  315. return result;
  316. }
  317. JSValue description = JS_GetPropertyStr(ctx, *value, "description");
  318. result = JS_ToCString(ctx, description);
  319. JS_FreeValue(ctx, description);
  320. return result;
  321. }
  322. int QTS_IsGlobalSymbol(JSContext *ctx, JSValueConst *value) {
  323. JSValue key = qts_get_symbol_key(ctx, value);
  324. int undefined = JS_IsUndefined(key);
  325. JS_FreeValue(ctx, key);
  326. if (undefined) {
  327. return 0;
  328. } else {
  329. return 1;
  330. }
  331. }
  332. int QTS_IsJobPending(JSRuntime *rt) {
  333. return JS_IsJobPending(rt);
  334. }
  335. /*
  336. runs pending jobs (Promises/async functions) until it encounters
  337. an exception or it executed the passed maxJobsToExecute jobs.
  338. Passing a negative value will run the loop until there are no more
  339. pending jobs or an exception happened
  340. Returns the executed number of jobs or the exception encountered
  341. */
  342. MaybeAsync(JSValue *) QTS_ExecutePendingJob(JSRuntime *rt, int maxJobsToExecute, JSContext **lastJobContext) {
  343. JSContext *pctx;
  344. int status = 1;
  345. int executed = 0;
  346. while (executed != maxJobsToExecute && status == 1) {
  347. status = JS_ExecutePendingJob(rt, &pctx);
  348. if (status == -1) {
  349. *lastJobContext = pctx;
  350. return jsvalue_to_heap(JS_GetException(pctx));
  351. } else if (status == 1) {
  352. *lastJobContext = pctx;
  353. executed++;
  354. }
  355. }
  356. #ifdef QTS_DEBUG_MODE
  357. char msg[500];
  358. sprintf(msg, "QTS_ExecutePendingJob(executed: %d, pctx: %p, lastJobExecuted: %p)", executed, pctx, *lastJobContext);
  359. QTS_DEBUG(msg)
  360. #endif
  361. return jsvalue_to_heap(JS_NewFloat64(pctx, executed));
  362. }
  363. MaybeAsync(JSValue *) QTS_GetProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name) {
  364. JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name);
  365. JSValue prop_val = JS_GetProperty(ctx, *this_val, prop_atom);
  366. JS_FreeAtom(ctx, prop_atom);
  367. return jsvalue_to_heap(prop_val);
  368. }
  369. MaybeAsync(void) QTS_SetProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name, JSValueConst *prop_value) {
  370. JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name);
  371. JSValue extra_prop_value = JS_DupValue(ctx, *prop_value);
  372. // TODO: should we use DefineProperty internally if this object doesn't have the property yet?
  373. JS_SetProperty(ctx, *this_val, prop_atom, extra_prop_value); // consumes extra_prop_value
  374. JS_FreeAtom(ctx, prop_atom);
  375. }
  376. void QTS_DefineProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name, JSValueConst *prop_value, JSValueConst *get, JSValueConst *set, bool configurable, bool enumerable, bool has_value) {
  377. JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name);
  378. int flags = 0;
  379. if (configurable) {
  380. flags = flags | JS_PROP_CONFIGURABLE;
  381. if (has_value) {
  382. flags = flags | JS_PROP_HAS_CONFIGURABLE;
  383. }
  384. }
  385. if (enumerable) {
  386. flags = flags | JS_PROP_ENUMERABLE;
  387. if (has_value) {
  388. flags = flags | JS_PROP_HAS_ENUMERABLE;
  389. }
  390. }
  391. if (!JS_IsUndefined(*get)) {
  392. flags = flags | JS_PROP_HAS_GET;
  393. }
  394. if (!JS_IsUndefined(*set)) {
  395. flags = flags | JS_PROP_HAS_SET;
  396. }
  397. if (has_value) {
  398. flags = flags | JS_PROP_HAS_VALUE;
  399. }
  400. JS_DefineProperty(ctx, *this_val, prop_atom, *prop_value, *get, *set, flags);
  401. JS_FreeAtom(ctx, prop_atom);
  402. }
  403. MaybeAsync(JSValue *) QTS_Call(JSContext *ctx, JSValueConst *func_obj, JSValueConst *this_obj, int argc, JSValueConst **argv_ptrs) {
  404. // convert array of pointers to array of values
  405. JSValueConst argv[argc];
  406. int i;
  407. for (i = 0; i < argc; i++) {
  408. argv[i] = *(argv_ptrs[i]);
  409. }
  410. return jsvalue_to_heap(JS_Call(ctx, *func_obj, *this_obj, argc, argv));
  411. }
  412. /**
  413. * If maybe_exception is an exception, get the error.
  414. * Otherwise, return NULL.
  415. */
  416. JSValue *QTS_ResolveException(JSContext *ctx, JSValue *maybe_exception) {
  417. if (JS_IsException(*maybe_exception)) {
  418. return jsvalue_to_heap(JS_GetException(ctx));
  419. }
  420. return NULL;
  421. }
  422. MaybeAsync(JSBorrowedChar *) QTS_Dump(JSContext *ctx, JSValueConst *obj) {
  423. JSValue obj_json_value = JS_JSONStringify(ctx, *obj, JS_UNDEFINED, JS_UNDEFINED);
  424. if (!JS_IsException(obj_json_value)) {
  425. const char *obj_json_chars = JS_ToCString(ctx, obj_json_value);
  426. JS_FreeValue(ctx, obj_json_value);
  427. if (obj_json_chars != NULL) {
  428. JSValue enumerable_props = JS_ParseJSON(ctx, obj_json_chars, strlen(obj_json_chars), "<dump>");
  429. JS_FreeCString(ctx, obj_json_chars);
  430. if (!JS_IsException(enumerable_props)) {
  431. // Copy common non-enumerable props for different object types.
  432. // Errors:
  433. copy_prop_if_needed(ctx, enumerable_props, *obj, "name");
  434. copy_prop_if_needed(ctx, enumerable_props, *obj, "message");
  435. copy_prop_if_needed(ctx, enumerable_props, *obj, "stack");
  436. // Serialize again.
  437. JSValue enumerable_json = JS_JSONStringify(ctx, enumerable_props, JS_UNDEFINED, JS_UNDEFINED);
  438. JS_FreeValue(ctx, enumerable_props);
  439. JSBorrowedChar *result = QTS_GetString(ctx, &enumerable_json);
  440. JS_FreeValue(ctx, enumerable_json);
  441. return result;
  442. }
  443. }
  444. }
  445. #ifdef QTS_DEBUG_MODE
  446. qts_log("Error dumping JSON:");
  447. js_std_dump_error(ctx);
  448. #endif
  449. // Fallback: convert to string
  450. return QTS_GetString(ctx, obj);
  451. }
  452. MaybeAsync(JSValue *) QTS_Eval(JSContext *ctx, BorrowedHeapChar *js_code, const char *filename, EvalDetectModule detectModule, EvalFlags evalFlags) {
  453. size_t js_code_len = strlen(js_code);
  454. if (detectModule) {
  455. if (JS_DetectModule((const char *)js_code, js_code_len)) {
  456. QTS_DEBUG("QTS_Eval: Detected module = true");
  457. evalFlags |= JS_EVAL_TYPE_MODULE;
  458. } else {
  459. QTS_DEBUG("QTS_Eval: Detected module = false");
  460. }
  461. } else {
  462. QTS_DEBUG("QTS_Eval: do not detect module");
  463. }
  464. return jsvalue_to_heap(JS_Eval(ctx, js_code, strlen(js_code), filename, evalFlags));
  465. }
  466. OwnedHeapChar *QTS_Typeof(JSContext *ctx, JSValueConst *value) {
  467. const char *result = "unknown";
  468. uint32_t tag = JS_VALUE_GET_TAG(*value);
  469. if (JS_IsNumber(*value)) {
  470. result = "number";
  471. } else if (JS_IsBigInt(ctx, *value)) {
  472. result = "bigint";
  473. } else if (JS_IsBigFloat(*value)) {
  474. result = "bigfloat";
  475. } else if (JS_IsBigDecimal(*value)) {
  476. result = "bigdecimal";
  477. } else if (JS_IsFunction(ctx, *value)) {
  478. result = "function";
  479. } else if (JS_IsBool(*value)) {
  480. result = "boolean";
  481. } else if (JS_IsNull(*value)) {
  482. result = "object";
  483. } else if (JS_IsUndefined(*value)) {
  484. result = "undefined";
  485. } else if (JS_IsUninitialized(*value)) {
  486. result = "undefined";
  487. } else if (JS_IsString(*value)) {
  488. result = "string";
  489. } else if (JS_IsSymbol(*value)) {
  490. result = "symbol";
  491. } else if (JS_IsObject(*value)) {
  492. result = "object";
  493. }
  494. char *out = strdup(result);
  495. return out;
  496. }
  497. JSValue *QTS_GetGlobalObject(JSContext *ctx) {
  498. return jsvalue_to_heap(JS_GetGlobalObject(ctx));
  499. }
  500. JSValue *QTS_NewPromiseCapability(JSContext *ctx, JSValue **resolve_funcs_out) {
  501. JSValue resolve_funcs[2];
  502. JSValue promise = JS_NewPromiseCapability(ctx, resolve_funcs);
  503. resolve_funcs_out[0] = jsvalue_to_heap(resolve_funcs[0]);
  504. resolve_funcs_out[1] = jsvalue_to_heap(resolve_funcs[1]);
  505. return jsvalue_to_heap(promise);
  506. }
  507. void QTS_TestStringArg(const char *string) {
  508. // pass
  509. }
  510. int QTS_BuildIsDebug() {
  511. #ifdef QTS_DEBUG_MODE
  512. return 1;
  513. #else
  514. return 0;
  515. #endif
  516. }
  517. int QTS_BuildIsAsyncify() {
  518. #ifdef QTS_ASYNCIFY
  519. return 1;
  520. #else
  521. return 0;
  522. #endif
  523. }
  524. // ----------------------------------------------------------------------------
  525. // Module loading helpers
  526. // ----------------------------------------------------------------------------
  527. // C -> Host Callbacks
  528. // Note: inside EM_JS, we need to use ['...'] subscript syntax for accessing JS
  529. // objects, because in optimized builds, Closure compiler will mangle all the
  530. // names.
  531. // -------------------
  532. // function: C -> Host
  533. #ifdef __EMSCRIPTEN__
  534. EM_JS(MaybeAsync(JSValue *), qts_host_call_function, (JSContext * ctx, JSValueConst *this_ptr, int argc, JSValueConst *argv, uint32_t magic_func_id), {
  535. #ifdef QTS_ASYNCIFY
  536. const asyncify = {['handleSleep'] : Asyncify.handleSleep};
  537. #else
  538. const asyncify = undefined;
  539. #endif
  540. return Module['callbacks']['callFunction'](asyncify, ctx, this_ptr, argc, argv, magic_func_id);
  541. });
  542. #endif
  543. // Function: QuickJS -> C
  544. JSValue qts_call_function(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic) {
  545. JSValue *result_ptr = qts_host_call_function(ctx, &this_val, argc, argv, magic);
  546. if (result_ptr == NULL) {
  547. return JS_UNDEFINED;
  548. }
  549. JSValue result = *result_ptr;
  550. free(result_ptr);
  551. return result;
  552. }
  553. // Function: Host -> QuickJS
  554. JSValue *QTS_NewFunction(JSContext *ctx, uint32_t func_id, const char *name) {
  555. #ifdef QTS_DEBUG_MODE
  556. char msg[500];
  557. sprintf(msg, "new_function(name: %s, magic: %d)", name, func_id);
  558. QTS_DEBUG(msg)
  559. #endif
  560. JSValue func_obj = JS_NewCFunctionMagic(
  561. /* context */ ctx,
  562. /* JSCFunctionMagic* */ &qts_call_function,
  563. /* name */ name,
  564. /* min argc */ 0,
  565. /* function type */ JS_CFUNC_generic_magic,
  566. /* magic: fn id */ func_id);
  567. return jsvalue_to_heap(func_obj);
  568. }
  569. JSValueConst *QTS_ArgvGetJSValueConstPointer(JSValueConst *argv, int index) {
  570. return &argv[index];
  571. }
  572. // --------------------
  573. // interrupt: C -> Host
  574. #ifdef __EMSCRIPTEN__
  575. EM_JS(int, qts_host_interrupt_handler, (JSRuntime * rt), {
  576. // Async not supported here.
  577. // #ifdef QTS_ASYNCIFY
  578. // const asyncify = Asyncify;
  579. // #else
  580. const asyncify = undefined;
  581. // #endif
  582. return Module['callbacks']['shouldInterrupt'](asyncify, rt);
  583. });
  584. #endif
  585. // interrupt: QuickJS -> C
  586. int qts_interrupt_handler(JSRuntime *rt, void *_unused) {
  587. return qts_host_interrupt_handler(rt);
  588. }
  589. // interrupt: Host -> QuickJS
  590. void QTS_RuntimeEnableInterruptHandler(JSRuntime *rt) {
  591. JS_SetInterruptHandler(rt, &qts_interrupt_handler, NULL);
  592. }
  593. void QTS_RuntimeDisableInterruptHandler(JSRuntime *rt) {
  594. JS_SetInterruptHandler(rt, NULL, NULL);
  595. }
  596. // --------------------
  597. // load module: C -> Host
  598. // TODO: a future version can support host returning JSModuleDef* directly;
  599. // for now we only support loading module source code.
  600. /*
  601. The module loading model under ASYNCIFY is convoluted. We need to make sure we
  602. never have an async request running concurrently for loading modules.
  603. The first implemenation looked like this:
  604. C HOST SUSPENDED
  605. qts_host_load_module(name) ------> false
  606. call rt.loadModule(name) false
  607. Start async load module false
  608. Suspend C true
  609. Async load complete true
  610. < --------------- QTS_CompileModule(source) true
  611. QTS_Eval(source, COMPILE_ONLY) true
  612. Loaded module has import true
  613. qts_host_load_module(dep) -------> true
  614. call rt.loadModule(dep) true
  615. Start async load module true
  616. ALREADY SUSPENDED, CRASH
  617. We can solve this in two different ways:
  618. 1. Return to C as soon as we async load the module source.
  619. That way, we unsuspend before calling QTS_CompileModule.
  620. 2. Once we load the module, use a new API to detect and async
  621. load the module's downstream dependencies. This way
  622. they're loaded synchronously so we don't need to suspend "again".
  623. Probably we could optimize (2) to make it more performant, eg with parallel
  624. loading, but (1) seems much easier to implement in the sort run.
  625. */
  626. JSModuleDef *qts_compile_module(JSContext *ctx, const char *module_name, BorrowedHeapChar *module_body) {
  627. #ifdef QTS_DEBUG_MODE
  628. char msg[500];
  629. sprintf(msg, "QTS_CompileModule(ctx: %p, name: %s, bodyLength: %lu)", ctx, module_name, strlen(module_body));
  630. QTS_DEBUG(msg)
  631. #endif
  632. JSValue func_val = JS_Eval(ctx, module_body, strlen(module_body), module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  633. if (JS_IsException(func_val)) {
  634. return NULL;
  635. }
  636. // TODO: Is exception ok?
  637. // TODO: set import.meta?
  638. JSModuleDef *module = JS_VALUE_GET_PTR(func_val);
  639. JS_FreeValue(ctx, func_val);
  640. return module;
  641. }
  642. #ifdef __EMSCRIPTEN__
  643. EM_JS(MaybeAsync(char *), qts_host_load_module_source, (JSRuntime * rt, JSContext *ctx, const char *module_name), {
  644. #ifdef QTS_ASYNCIFY
  645. const asyncify = {['handleSleep'] : Asyncify.handleSleep};
  646. #else
  647. const asyncify = undefined;
  648. #endif
  649. // https://emscripten.org/docs/api_reference/preamble.js.html#UTF8ToString
  650. const moduleNameString = UTF8ToString(module_name);
  651. return Module['callbacks']['loadModuleSource'](asyncify, rt, ctx, moduleNameString);
  652. });
  653. EM_JS(MaybeAsync(char *), qts_host_normalize_module, (JSRuntime * rt, JSContext *ctx, const char *module_base_name, const char *module_name), {
  654. #ifdef QTS_ASYNCIFY
  655. const asyncify = {['handleSleep'] : Asyncify.handleSleep};
  656. #else
  657. const asyncify = undefined;
  658. #endif
  659. // https://emscripten.org/docs/api_reference/preamble.js.html#UTF8ToString
  660. const moduleBaseNameString = UTF8ToString(module_base_name);
  661. const moduleNameString = UTF8ToString(module_name);
  662. return Module['callbacks']['normalizeModule'](asyncify, rt, ctx, moduleBaseNameString, moduleNameString);
  663. });
  664. #endif
  665. // load module: QuickJS -> C
  666. // See js_module_loader in quickjs/quickjs-libc.c:567
  667. JSModuleDef *qts_load_module(JSContext *ctx, const char *module_name, void *_unused) {
  668. JSRuntime *rt = JS_GetRuntime(ctx);
  669. #ifdef QTS_DEBUG_MODE
  670. char msg[500];
  671. sprintf(msg, "qts_load_module(rt: %p, ctx: %p, name: %s)", rt, ctx, module_name);
  672. QTS_DEBUG(msg)
  673. #endif
  674. char *module_source = qts_host_load_module_source(rt, ctx, module_name);
  675. if (module_source == NULL) {
  676. return NULL;
  677. }
  678. JSModuleDef *module = qts_compile_module(ctx, module_name, module_source);
  679. free(module_source);
  680. return module;
  681. }
  682. char *qts_normalize_module(JSContext *ctx, const char *module_base_name, const char *module_name, void *_unused) {
  683. JSRuntime *rt = JS_GetRuntime(ctx);
  684. #ifdef QTS_DEBUG_MODE
  685. char msg[500];
  686. sprintf(msg, "qts_normalize_module(rt: %p, ctx: %p, base_name: %s, name: %s)", rt, ctx, module_base_name, module_name);
  687. QTS_DEBUG(msg)
  688. #endif
  689. char *em_module_name = qts_host_normalize_module(rt, ctx, module_base_name, module_name);
  690. char *js_module_name = js_strdup(ctx, em_module_name);
  691. free(em_module_name);
  692. return js_module_name;
  693. }
  694. // Load module: Host -> QuickJS
  695. void QTS_RuntimeEnableModuleLoader(JSRuntime *rt, int use_custom_normalize) {
  696. JSModuleNormalizeFunc *module_normalize = NULL; /* use default name normalizer */
  697. if (use_custom_normalize) {
  698. module_normalize = &qts_normalize_module;
  699. }
  700. JS_SetModuleLoaderFunc(rt, module_normalize, &qts_load_module, NULL);
  701. }
  702. void QTS_RuntimeDisableModuleLoader(JSRuntime *rt) {
  703. JS_SetModuleLoaderFunc(rt, NULL, NULL, NULL);
  704. }