-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathinterface.c
1252 lines (1088 loc) · 38.7 KB
/
interface.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* interface.c
*
* We primarily use JSValue* (pointer to JSValue) when communicating with the
* host javascript environment, because pointers are trivial to use for calls
* into emscripten because they're just a number!
*
* As with the quickjs.h API, a JSValueConst* value is "borrowed" and should
* not be freed. A JSValue* is "owned" and should be freed by the owner.
*
* Functions starting with "QTS_" are exported by generate.ts to:
* - interface.h for native C code.
* - ffi.ts for emscripten.
*
* We support building the following build outputs:
*
* ## 1. Native machine code
* For internal development testing purposes.
*
* ## 2. WASM via Emscripten
* For general production use.
*
* ## 3. Experimental: Asyncified WASM via Emscripten with -s ASYNCIFY=1.
* This variant supports treating async host Javascript calls as synchronous
* from the perspective of the WASM c code.
*
* The way this works is described here:
* https://emscripten.org/docs/porting/asyncify.html
*
* In this variant, any call into our C code could return a promise if it ended
* up suspended. We mark the methods we suspect might suspend due to users' code
* as returning MaybeAsync(T). This information is ignored for the regular
* build.
*/
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#include <math.h> // For NAN
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#ifdef QTS_SANITIZE_LEAK
#include <sanitizer/lsan_interface.h>
#endif
#ifdef QTS_USE_QUICKJS_NG
#include "../vendor/quickjs-ng/cutils.h"
#include "../vendor/quickjs-ng/quickjs-libc.h"
#include "../vendor/quickjs-ng/quickjs.h"
#else
#include "../vendor/quickjs/cutils.h"
#include "../vendor/quickjs/quickjs-libc.h"
#include "../vendor/quickjs/quickjs.h"
#endif
#define PKG "quickjs-emscripten: "
#define LOG_LEN 500
#ifdef QTS_DEBUG_MODE
#define IF_DEBUG if (qts_get_context_rt_data(ctx)->debug_log)
#define IF_DEBUG_RT if (qts_get_runtime_data(rt)->debug_log)
#define QTS_DEBUG(msg) IF_DEBUG qts_log(msg);
#define QTS_DEBUG_RT(msg) IF_DEBUG_RT qts_log(msg);
#define QTS_DUMP(value) IF_DEBUG qts_dump(ctx, value);
#else
#define IF_DEBUG if (0)
#define IF_DEBUG_RT if (0)
#define QTS_DEBUG(msg) ;
#define QTS_DEBUG_RT(msg) ;
#define QTS_DUMP(value) ;
#endif
/**
* Signal to our FFI code generator that this string argument should be passed as a pointer
* allocated by the caller on the heap, not a JS string on the stack.
* https://github.com/emscripten-core/emscripten/issues/6860#issuecomment-405818401
*/
#define BorrowedHeapChar const char
#define OwnedHeapChar char
#define JSBorrowedChar const char
/**
* Signal to our FFI code generator that this function should be called
* asynchronously when compiled with ASYNCIFY.
*/
#define MaybeAsync(T) T
/**
* Signal to our FFI code generator that this function is only available in
* ASYNCIFY builds.
*/
#define AsyncifyOnly(T) T
#define JSVoid void
#define EvalFlags int
#define IntrinsicsFlags enum QTS_Intrinsic
#define EvalDetectModule int
typedef struct qts_RuntimeData {
bool debug_log;
} qts_RuntimeData;
qts_RuntimeData *qts_get_runtime_data(JSRuntime *rt) {
qts_RuntimeData *data = JS_GetRuntimeOpaque(rt);
if (data == NULL) {
data = malloc(sizeof(qts_RuntimeData));
data->debug_log = false;
JS_SetRuntimeOpaque(rt, data);
}
return data;
}
qts_RuntimeData *qts_get_context_rt_data(JSContext *ctx) {
return qts_get_runtime_data(JS_GetRuntime(ctx));
}
void qts_log(char *msg) {
fputs(PKG, stderr);
fputs(msg, stderr);
fputs("\n", stderr);
}
void qts_dump(JSContext *ctx, JSValueConst value) {
const char *str = JS_ToCString(ctx, value);
if (!str) {
QTS_DEBUG("QTS_DUMP: can't dump");
return;
}
fputs(str, stderr);
JS_FreeCString(ctx, str);
putchar('\n');
}
void copy_prop_if_needed(JSContext *ctx, JSValueConst dest, JSValueConst src, const char *prop_name) {
JSAtom prop_atom = JS_NewAtom(ctx, prop_name);
JSValue dest_prop = JS_GetProperty(ctx, dest, prop_atom);
if (JS_IsUndefined(dest_prop)) {
JSValue src_prop = JS_GetProperty(ctx, src, prop_atom);
if (!JS_IsUndefined(src_prop) && !JS_IsException(src_prop)) {
JS_SetProperty(ctx, dest, prop_atom, src_prop);
}
} else {
JS_FreeValue(ctx, dest_prop);
}
JS_FreeAtom(ctx, prop_atom);
}
JSValue *jsvalue_to_heap(JSValueConst value) {
JSValue *result = malloc(sizeof(JSValue));
if (result) {
// Could be better optimized, but at -0z / -ftlo, it
// appears to produce the same binary code as a memcpy.
*result = value;
}
return result;
}
JSValue *QTS_Throw(JSContext *ctx, JSValueConst *error) {
JSValue copy = JS_DupValue(ctx, *error);
return jsvalue_to_heap(JS_Throw(ctx, copy));
}
JSValue *QTS_NewError(JSContext *ctx) {
return jsvalue_to_heap(JS_NewError(ctx));
}
/**
* Limits.
*/
/**
* Memory limit. Set to -1 to disable.
*/
void QTS_RuntimeSetMemoryLimit(JSRuntime *rt, size_t limit) {
JS_SetMemoryLimit(rt, limit);
}
/**
* Memory diagnostics
*/
JSValue *QTS_RuntimeComputeMemoryUsage(JSRuntime *rt, JSContext *ctx) {
JSMemoryUsage s;
JS_ComputeMemoryUsage(rt, &s);
// Note that we're going to allocate more memory just to report the memory usage.
// A more sound approach would be to bind JSMemoryUsage struct directly - but that's
// a lot of work. This should be okay in the mean time.
JSValue result = JS_NewObject(ctx);
// Manually generated via editor-fu from JSMemoryUsage struct definition in quickjs.h
JS_SetPropertyStr(ctx, result, "malloc_limit", JS_NewInt64(ctx, s.malloc_limit));
JS_SetPropertyStr(ctx, result, "memory_used_size", JS_NewInt64(ctx, s.memory_used_size));
JS_SetPropertyStr(ctx, result, "malloc_count", JS_NewInt64(ctx, s.malloc_count));
JS_SetPropertyStr(ctx, result, "memory_used_count", JS_NewInt64(ctx, s.memory_used_count));
JS_SetPropertyStr(ctx, result, "atom_count", JS_NewInt64(ctx, s.atom_count));
JS_SetPropertyStr(ctx, result, "atom_size", JS_NewInt64(ctx, s.atom_size));
JS_SetPropertyStr(ctx, result, "str_count", JS_NewInt64(ctx, s.str_count));
JS_SetPropertyStr(ctx, result, "str_size", JS_NewInt64(ctx, s.str_size));
JS_SetPropertyStr(ctx, result, "obj_count", JS_NewInt64(ctx, s.obj_count));
JS_SetPropertyStr(ctx, result, "obj_size", JS_NewInt64(ctx, s.obj_size));
JS_SetPropertyStr(ctx, result, "prop_count", JS_NewInt64(ctx, s.prop_count));
JS_SetPropertyStr(ctx, result, "prop_size", JS_NewInt64(ctx, s.prop_size));
JS_SetPropertyStr(ctx, result, "shape_count", JS_NewInt64(ctx, s.shape_count));
JS_SetPropertyStr(ctx, result, "shape_size", JS_NewInt64(ctx, s.shape_size));
JS_SetPropertyStr(ctx, result, "js_func_count", JS_NewInt64(ctx, s.js_func_count));
JS_SetPropertyStr(ctx, result, "js_func_size", JS_NewInt64(ctx, s.js_func_size));
JS_SetPropertyStr(ctx, result, "js_func_code_size", JS_NewInt64(ctx, s.js_func_code_size));
JS_SetPropertyStr(ctx, result, "js_func_pc2line_count", JS_NewInt64(ctx, s.js_func_pc2line_count));
JS_SetPropertyStr(ctx, result, "js_func_pc2line_size", JS_NewInt64(ctx, s.js_func_pc2line_size));
JS_SetPropertyStr(ctx, result, "c_func_count", JS_NewInt64(ctx, s.c_func_count));
JS_SetPropertyStr(ctx, result, "array_count", JS_NewInt64(ctx, s.array_count));
JS_SetPropertyStr(ctx, result, "fast_array_count", JS_NewInt64(ctx, s.fast_array_count));
JS_SetPropertyStr(ctx, result, "fast_array_elements", JS_NewInt64(ctx, s.fast_array_elements));
JS_SetPropertyStr(ctx, result, "binary_object_count", JS_NewInt64(ctx, s.binary_object_count));
JS_SetPropertyStr(ctx, result, "binary_object_size", JS_NewInt64(ctx, s.binary_object_size));
return jsvalue_to_heap(result);
}
OwnedHeapChar *QTS_RuntimeDumpMemoryUsage(JSRuntime *rt) {
char *result = malloc(sizeof(char) * 1024);
FILE *memfile = fmemopen(result, 1024, "w");
JSMemoryUsage s;
JS_ComputeMemoryUsage(rt, &s);
JS_DumpMemoryUsage(memfile, &s, rt);
fclose(memfile);
return result;
}
int QTS_RecoverableLeakCheck() {
#ifdef QTS_SANITIZE_LEAK
return __lsan_do_recoverable_leak_check();
#else
return 0;
#endif
}
int QTS_BuildIsSanitizeLeak() {
#ifdef QTS_SANITIZE_LEAK
return 1;
#else
return 0;
#endif
}
#ifdef QTS_ASYNCIFY
EM_JS(void, set_asyncify_stack_size, (size_t size, size_t default_size), {
Asyncify.StackSize = size || default_size;
});
#endif
/**
* Set the stack size limit, in bytes. Set to 0 to disable.
*/
void QTS_RuntimeSetMaxStackSize(JSRuntime *rt, size_t stack_size) {
#ifdef QTS_ASYNCIFY
set_asyncify_stack_size(stack_size, QTS_ASYNCIFY_DEFAULT_STACK_SIZE);
#endif
JS_SetMaxStackSize(rt, stack_size);
}
/**
* Constant pointers. Because we always use JSValue* from the host Javascript environment,
* we need helper fuctions to return pointers to these constants.
*/
JSValueConst QTS_Undefined = JS_UNDEFINED;
JSValueConst *QTS_GetUndefined() {
return &QTS_Undefined;
}
JSValueConst QTS_Null = JS_NULL;
JSValueConst *QTS_GetNull() {
return &QTS_Null;
}
JSValueConst QTS_False = JS_FALSE;
JSValueConst *QTS_GetFalse() {
return &QTS_False;
}
JSValueConst QTS_True = JS_TRUE;
JSValueConst *QTS_GetTrue() {
return &QTS_True;
}
/**
* Standard FFI functions
*/
JSRuntime *QTS_NewRuntime() {
return JS_NewRuntime();
}
void QTS_FreeRuntime(JSRuntime *rt) {
void *data = JS_GetRuntimeOpaque(rt);
if (data) {
free(data);
}
JS_FreeRuntime(rt);
}
enum QTS_Intrinsic {
QTS_Intrinsic_BaseObjects = 1 << 0,
QTS_Intrinsic_Date = 1 << 1,
QTS_Intrinsic_Eval = 1 << 2,
QTS_Intrinsic_StringNormalize = 1 << 3,
QTS_Intrinsic_RegExp = 1 << 4,
QTS_Intrinsic_RegExpCompiler = 1 << 5,
QTS_Intrinsic_JSON = 1 << 6,
QTS_Intrinsic_Proxy = 1 << 7,
QTS_Intrinsic_MapSet = 1 << 8,
QTS_Intrinsic_TypedArrays = 1 << 9,
QTS_Intrinsic_Promise = 1 << 10,
QTS_Intrinsic_BigInt = 1 << 11,
QTS_Intrinsic_BigFloat = 1 << 12,
QTS_Intrinsic_BigDecimal = 1 << 13,
QTS_Intrinsic_OperatorOverloading = 1 << 14,
QTS_Intrinsic_BignumExt = 1 << 15,
};
JSContext *QTS_NewContext(JSRuntime *rt, IntrinsicsFlags intrinsics) {
if (intrinsics == 0) {
return JS_NewContext(rt);
}
JSContext *ctx = JS_NewContextRaw(rt);
if (ctx == NULL) {
return NULL;
}
if (intrinsics & QTS_Intrinsic_BaseObjects) {
JS_AddIntrinsicBaseObjects(ctx);
}
if (intrinsics & QTS_Intrinsic_Date) {
JS_AddIntrinsicDate(ctx);
}
if (intrinsics & QTS_Intrinsic_Eval) {
JS_AddIntrinsicEval(ctx);
}
#ifndef QTS_USE_QUICKJS_NG
if (intrinsics & QTS_Intrinsic_StringNormalize) {
JS_AddIntrinsicStringNormalize(ctx);
}
#endif
if (intrinsics & QTS_Intrinsic_RegExp) {
JS_AddIntrinsicRegExp(ctx);
}
if (intrinsics & QTS_Intrinsic_RegExpCompiler) {
JS_AddIntrinsicRegExpCompiler(ctx);
}
if (intrinsics & QTS_Intrinsic_JSON) {
JS_AddIntrinsicJSON(ctx);
}
if (intrinsics & QTS_Intrinsic_Proxy) {
JS_AddIntrinsicProxy(ctx);
}
if (intrinsics & QTS_Intrinsic_MapSet) {
JS_AddIntrinsicMapSet(ctx);
}
if (intrinsics & QTS_Intrinsic_TypedArrays) {
JS_AddIntrinsicTypedArrays(ctx);
}
if (intrinsics & QTS_Intrinsic_Promise) {
JS_AddIntrinsicPromise(ctx);
}
if (intrinsics & QTS_Intrinsic_BigInt) {
JS_AddIntrinsicBigInt(ctx);
}
#ifdef CONFIG_BIGNUM
if (intrinsics & QTS_Intrinsic_BigFloat) {
JS_AddIntrinsicBigFloat(ctx);
}
if (intrinsics & QTS_Intrinsic_BigDecimal) {
JS_AddIntrinsicBigDecimal(ctx);
}
if (intrinsics & QTS_Intrinsic_BignumExt) {
JS_EnableBignumExt(ctx, TRUE);
}
if (intrinsics & QTS_Intrinsic_OperatorOverloading) {
JS_AddIntrinsicOperators(ctx);
}
#endif
return ctx;
}
void QTS_FreeContext(JSContext *ctx) {
JS_FreeContext(ctx);
}
void QTS_FreeValuePointer(JSContext *ctx, JSValue *value) {
JS_FreeValue(ctx, *value);
free(value);
}
void QTS_FreeValuePointerRuntime(JSRuntime *rt, JSValue *value) {
JS_FreeValueRT(rt, *value);
free(value);
}
void QTS_FreeVoidPointer(JSContext *ctx, JSVoid *ptr) {
js_free(ctx, ptr);
}
void QTS_FreeCString(JSContext *ctx, JSBorrowedChar *str) {
JS_FreeCString(ctx, str);
}
JSValue *QTS_DupValuePointer(JSContext *ctx, JSValueConst *val) {
return jsvalue_to_heap(JS_DupValue(ctx, *val));
}
JSValue *QTS_NewObject(JSContext *ctx) {
return jsvalue_to_heap(JS_NewObject(ctx));
}
JSValue *QTS_NewObjectProto(JSContext *ctx, JSValueConst *proto) {
return jsvalue_to_heap(JS_NewObjectProto(ctx, *proto));
}
JSValue *QTS_NewArray(JSContext *ctx) {
return jsvalue_to_heap(JS_NewArray(ctx));
}
void qts_free_buffer(JSRuntime *unused_rt, void *unused_opaque, void *ptr) { free(ptr); }
JSValue *QTS_NewArrayBuffer(JSContext *ctx, JSVoid *buffer, size_t length) {
return jsvalue_to_heap(
JS_NewArrayBuffer(ctx, (uint8_t *)buffer, length, qts_free_buffer, NULL, false));
}
JSValue *QTS_NewFloat64(JSContext *ctx, double num) {
return jsvalue_to_heap(JS_NewFloat64(ctx, num));
}
double QTS_GetFloat64(JSContext *ctx, JSValueConst *value) {
double result = NAN;
JS_ToFloat64(ctx, &result, *value);
return result;
}
JSValue *QTS_NewString(JSContext *ctx, BorrowedHeapChar *string) {
return jsvalue_to_heap(JS_NewString(ctx, string));
}
JSBorrowedChar *QTS_GetString(JSContext *ctx, JSValueConst *value) {
return JS_ToCString(ctx, *value);
}
JSVoid *QTS_GetArrayBuffer(JSContext *ctx, JSValueConst *data) {
size_t length;
uint8_t *buffer = JS_GetArrayBuffer(ctx, &length, *data);
if (!buffer)
return 0;
uint8_t *result = malloc(length);
if (!result)
return result;
memcpy(result, buffer, length);
return result;
}
// I don't know how to return two values in C, maybe allocate memory in stack?
size_t QTS_GetArrayBufferLength(JSContext *ctx, JSValueConst *data) {
size_t length;
uint8_t *buffer = JS_GetArrayBuffer(ctx, &length, *data);
return length;
}
JSValue qts_get_symbol_key(JSContext *ctx, JSValueConst *value) {
JSValue global = JS_GetGlobalObject(ctx);
JSValue Symbol = JS_GetPropertyStr(ctx, global, "Symbol");
JS_FreeValue(ctx, global);
JSValue Symbol_keyFor = JS_GetPropertyStr(ctx, Symbol, "keyFor");
JSValue key = JS_Call(ctx, Symbol_keyFor, Symbol, 1, value);
JS_FreeValue(ctx, Symbol_keyFor);
JS_FreeValue(ctx, Symbol);
return key;
}
JSValue *QTS_NewSymbol(JSContext *ctx, BorrowedHeapChar *description, int isGlobal) {
JSValue global = JS_GetGlobalObject(ctx);
JSValue Symbol = JS_GetPropertyStr(ctx, global, "Symbol");
JS_FreeValue(ctx, global);
JSValue descriptionValue = JS_NewString(ctx, description);
JSValue symbol;
if (isGlobal != 0) {
JSValue Symbol_for = JS_GetPropertyStr(ctx, Symbol, "for");
symbol = JS_Call(ctx, Symbol_for, Symbol, 1, &descriptionValue);
JS_FreeValue(ctx, descriptionValue);
JS_FreeValue(ctx, Symbol_for);
JS_FreeValue(ctx, Symbol);
return jsvalue_to_heap(symbol);
}
symbol = JS_Call(ctx, Symbol, JS_UNDEFINED, 1, &descriptionValue);
JS_FreeValue(ctx, descriptionValue);
JS_FreeValue(ctx, Symbol);
return jsvalue_to_heap(symbol);
}
MaybeAsync(JSBorrowedChar *) QTS_GetSymbolDescriptionOrKey(JSContext *ctx, JSValueConst *value) {
JSBorrowedChar *result;
JSValue key = qts_get_symbol_key(ctx, value);
if (!JS_IsUndefined(key)) {
result = JS_ToCString(ctx, key);
JS_FreeValue(ctx, key);
return result;
}
JSValue description = JS_GetPropertyStr(ctx, *value, "description");
result = JS_ToCString(ctx, description);
JS_FreeValue(ctx, description);
return result;
}
int QTS_IsGlobalSymbol(JSContext *ctx, JSValueConst *value) {
JSValue key = qts_get_symbol_key(ctx, value);
int undefined = JS_IsUndefined(key);
JS_FreeValue(ctx, key);
if (undefined) {
return 0;
} else {
return 1;
}
}
int QTS_IsJobPending(JSRuntime *rt) {
return JS_IsJobPending(rt);
}
/*
runs pending jobs (Promises/async functions) until it encounters
an exception or it executed the passed maxJobsToExecute jobs.
Passing a negative value will run the loop until there are no more
pending jobs or an exception happened
Returns the executed number of jobs or the exception encountered
*/
MaybeAsync(JSValue *) QTS_ExecutePendingJob(JSRuntime *rt, int maxJobsToExecute, JSContext **lastJobContext) {
JSContext *pctx;
int status = 1;
int executed = 0;
while (executed != maxJobsToExecute && status == 1) {
status = JS_ExecutePendingJob(rt, &pctx);
if (status == -1) {
*lastJobContext = pctx;
return jsvalue_to_heap(JS_GetException(pctx));
} else if (status == 1) {
*lastJobContext = pctx;
executed++;
}
}
IF_DEBUG_RT {
char msg[LOG_LEN];
snprintf(msg, LOG_LEN, "QTS_ExecutePendingJob(executed: %d, pctx: %p, lastJobExecuted: %p)", executed, pctx, *lastJobContext);
qts_log(msg);
}
return jsvalue_to_heap(JS_NewFloat64(pctx, executed));
}
MaybeAsync(JSValue *) QTS_GetProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name) {
JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name);
JSValue prop_val = JS_GetProperty(ctx, *this_val, prop_atom);
JS_FreeAtom(ctx, prop_atom);
return jsvalue_to_heap(prop_val);
}
MaybeAsync(JSValue *) QTS_GetPropNumber(JSContext *ctx, JSValueConst *this_val, int prop_name) {
JSValue prop_val = JS_GetPropertyUint32(ctx, *this_val, (uint32_t)prop_name);
return jsvalue_to_heap(prop_val);
}
MaybeAsync(void) QTS_SetProp(JSContext *ctx, JSValueConst *this_val, JSValueConst *prop_name, JSValueConst *prop_value) {
JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name);
JSValue extra_prop_value = JS_DupValue(ctx, *prop_value);
// TODO: should we use DefineProperty internally if this object doesn't have the property yet?
JS_SetProperty(ctx, *this_val, prop_atom, extra_prop_value); // consumes extra_prop_value
JS_FreeAtom(ctx, prop_atom);
}
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) {
JSAtom prop_atom = JS_ValueToAtom(ctx, *prop_name);
int flags = 0;
if (configurable) {
flags = flags | JS_PROP_CONFIGURABLE;
if (has_value) {
flags = flags | JS_PROP_HAS_CONFIGURABLE;
}
}
if (enumerable) {
flags = flags | JS_PROP_ENUMERABLE;
if (has_value) {
flags = flags | JS_PROP_HAS_ENUMERABLE;
}
}
if (!JS_IsUndefined(*get)) {
flags = flags | JS_PROP_HAS_GET;
}
if (!JS_IsUndefined(*set)) {
flags = flags | JS_PROP_HAS_SET;
}
if (has_value) {
flags = flags | JS_PROP_HAS_VALUE;
}
JS_DefineProperty(ctx, *this_val, prop_atom, *prop_value, *get, *set, flags);
JS_FreeAtom(ctx, prop_atom);
}
#define JS_ATOM_TAG_INT (1U << 31)
static inline BOOL __JS_AtomIsTaggedInt(JSAtom v) {
return (v & JS_ATOM_TAG_INT) != 0;
}
static inline uint32_t __JS_AtomToUInt32(JSAtom atom) {
return atom & ~JS_ATOM_TAG_INT;
}
/* include numbers. when only this is set, we filter out strings */
#define QTS_GPN_NUMBER_MASK (1 << 6)
/* Treat numbers as strings */
#define QTS_STANDARD_COMPLIANT_NUMBER (1 << 7)
MaybeAsync(JSValue *) QTS_GetOwnPropertyNames(JSContext *ctx, JSValue ***out_ptrs, uint32_t *out_len, JSValueConst *obj, int flags) {
JSPropertyEnum *tab = NULL;
uint32_t total_props = 0;
uint32_t out_props = 0;
BOOL qts_standard_compliant_number = (flags & QTS_STANDARD_COMPLIANT_NUMBER) != 0;
BOOL qts_include_string = (flags & JS_GPN_STRING_MASK) != 0;
BOOL qts_include_number = qts_standard_compliant_number ? 0 : (flags & QTS_GPN_NUMBER_MASK) != 0;
if (qts_include_number) {
// if we want numbers, we must include strings in call down
flags = flags | JS_GPN_STRING_MASK;
}
int status = 0;
status = JS_GetOwnPropertyNames(ctx, &tab, &total_props, *obj, flags);
if (status < 0) {
if (tab != NULL) {
js_free(ctx, tab);
}
return jsvalue_to_heap(JS_GetException(ctx));
}
*out_ptrs = malloc(sizeof(JSValue) * *out_len);
for (int i = 0; i < total_props; i++) {
JSAtom atom = tab[i].atom;
if (__JS_AtomIsTaggedInt(atom)) {
if (qts_include_number) {
uint32_t v = __JS_AtomToUInt32(atom);
(*out_ptrs)[out_props++] = jsvalue_to_heap(JS_NewUint32(ctx, v));
} else if (qts_include_string && qts_standard_compliant_number) {
(*out_ptrs)[out_props++] = jsvalue_to_heap(JS_AtomToValue(ctx, tab[i].atom));
}
JS_FreeAtom(ctx, atom);
continue;
}
JSValue atom_value = JS_AtomToValue(ctx, atom);
JS_FreeAtom(ctx, atom);
if (JS_IsString(atom_value)) {
if (qts_include_string) {
(*out_ptrs)[out_props++] = jsvalue_to_heap(atom_value);
} else {
JS_FreeValue(ctx, atom_value);
}
} else { // Symbol
// We must have set the includeSymbol or includePrivate flags
// if it's present
(*out_ptrs)[out_props++] = jsvalue_to_heap(atom_value);
}
}
js_free(ctx, tab);
*out_len = out_props;
return NULL;
}
MaybeAsync(JSValue *) QTS_Call(JSContext *ctx, JSValueConst *func_obj, JSValueConst *this_obj, int argc, JSValueConst **argv_ptrs) {
// convert array of pointers to array of values
JSValueConst argv[argc];
int i;
for (i = 0; i < argc; i++) {
argv[i] = *(argv_ptrs[i]);
}
return jsvalue_to_heap(JS_Call(ctx, *func_obj, *this_obj, argc, argv));
}
/**
* If maybe_exception is an exception, get the error.
* Otherwise, return NULL.
*/
JSValue *QTS_ResolveException(JSContext *ctx, JSValue *maybe_exception) {
if (JS_IsException(*maybe_exception)) {
return jsvalue_to_heap(JS_GetException(ctx));
}
return NULL;
}
MaybeAsync(JSBorrowedChar *) QTS_Dump(JSContext *ctx, JSValueConst *obj) {
JSValue obj_json_value = JS_JSONStringify(ctx, *obj, JS_UNDEFINED, JS_UNDEFINED);
if (!JS_IsException(obj_json_value)) {
const char *obj_json_chars = JS_ToCString(ctx, obj_json_value);
JS_FreeValue(ctx, obj_json_value);
if (obj_json_chars != NULL) {
JSValue enumerable_props = JS_ParseJSON(ctx, obj_json_chars, strlen(obj_json_chars), "<dump>");
JS_FreeCString(ctx, obj_json_chars);
if (!JS_IsException(enumerable_props)) {
// Copy common non-enumerable props for different object types.
// Errors:
copy_prop_if_needed(ctx, enumerable_props, *obj, "name");
copy_prop_if_needed(ctx, enumerable_props, *obj, "message");
copy_prop_if_needed(ctx, enumerable_props, *obj, "stack");
copy_prop_if_needed(ctx, enumerable_props, *obj, "fileName");
copy_prop_if_needed(ctx, enumerable_props, *obj, "lineNumber");
// Serialize again.
JSValue enumerable_json = JS_JSONStringify(ctx, enumerable_props, JS_UNDEFINED, JS_UNDEFINED);
JS_FreeValue(ctx, enumerable_props);
JSBorrowedChar *result = QTS_GetString(ctx, &enumerable_json);
JS_FreeValue(ctx, enumerable_json);
return result;
}
}
}
IF_DEBUG {
qts_log("Error dumping JSON:");
js_std_dump_error(ctx);
}
// Fallback: convert to string
return QTS_GetString(ctx, obj);
}
JSValue qts_resolve_func_data(
JSContext *ctx,
JSValueConst this_val,
int argc,
JSValueConst *argv,
int magic,
JSValue *func_data) {
return JS_DupValue(ctx, func_data[0]);
}
MaybeAsync(JSValue *) QTS_Eval(JSContext *ctx, BorrowedHeapChar *js_code, size_t js_code_length, const char *filename, EvalDetectModule detectModule, EvalFlags evalFlags) {
char msg[LOG_LEN];
if (detectModule) {
if (JS_DetectModule((const char *)js_code, js_code_length)) {
QTS_DEBUG("QTS_Eval: Detected module = true");
evalFlags |= JS_EVAL_TYPE_MODULE;
} else {
QTS_DEBUG("QTS_Eval: Detected module = false");
}
} else {
QTS_DEBUG("QTS_Eval: do not detect module");
}
JSModuleDef *module;
JSValue eval_result;
if (
(evalFlags & JS_EVAL_TYPE_MODULE) != 0 &&
(evalFlags & JS_EVAL_FLAG_COMPILE_ONLY) == 0) {
QTS_DEBUG("QTS_Eval: JS_EVAL_TYPE_MODULE");
JSValue func_obj = JS_Eval(ctx, js_code, js_code_length, filename, evalFlags | JS_EVAL_FLAG_COMPILE_ONLY);
if (JS_IsException(func_obj)) {
QTS_DEBUG("QTS_Eval: JS_EVAL_FLAG_COMPILE_ONLY exception")
return jsvalue_to_heap(func_obj);
}
if (JS_VALUE_GET_TAG(func_obj) != JS_TAG_MODULE) {
QTS_DEBUG("QTS_Eval: JS_EVAL_FLAG_COMPILE_ONLY result != JS_TAG_MODULE")
JS_FreeValue(ctx, func_obj);
return jsvalue_to_heap(JS_ThrowInternalError(ctx, "Module code compiled to non-module object"));
}
module = JS_VALUE_GET_PTR(func_obj);
if (module == NULL) {
QTS_DEBUG("QTS_Eval: JSModuleDef == NULL")
JS_FreeValue(ctx, func_obj);
return jsvalue_to_heap(JS_ThrowInternalError(ctx, "Module compiled to null"));
}
eval_result = JS_EvalFunction(ctx, func_obj);
QTS_DEBUG("QTS_Eval: JS_EVAL_TYPE_MODULE eval_result")
// It seems like this is a double-free.
// JS_FreeValue(ctx, func_obj);
} else {
eval_result = JS_Eval(ctx, js_code, js_code_length, filename, evalFlags);
QTS_DEBUG("QTS_Eval: JS_EVAL_TYPE_GLOBAL eval_result")
}
IF_DEBUG {
snprintf(msg, LOG_LEN, "QTS_Eval: eval_result = %d", eval_result);
qts_log(msg);
}
if (
// Error - nothing more to do.
JS_IsException(eval_result)
// Non-module eval - return the result
|| (evalFlags & JS_EVAL_TYPE_MODULE) == 0) {
QTS_DEBUG("QTS_Eval: non-module or exception")
return jsvalue_to_heap(eval_result);
}
// We eval'd a module.
// Make our return type `ModuleExports | Promise<ModuleExports>>`
JSPromiseStateEnum state = JS_PromiseState(ctx, eval_result);
IF_DEBUG {
snprintf(msg, LOG_LEN, "QTS_Eval: eval_result JS_PromiseState = %i", state);
qts_log(msg);
}
if (
// quickjs@2024-01-14 evaluating module
// produced a promise
(state == JS_PROMISE_FULFILLED)
// quickjs in compile mode
// quickjs-ng before rebasing on quickjs@2024-01-14
// not a promise.
|| (state == -1)) {
QTS_DEBUG("QTS_Eval: result: JS_PROMISE_FULFILLED or not a promise")
JS_FreeValue(ctx, eval_result);
return jsvalue_to_heap(JS_GetModuleNamespace(ctx, module));
} else if (state == JS_PROMISE_REJECTED) {
// Throw the rejection response, to match evaluation of non-module code,
// or of code with a syntax error.
QTS_DEBUG("QTS_Eval: result: JS_PROMISE_REJECTED - throw rejection reason")
JS_Throw(ctx, JS_PromiseResult(ctx, eval_result));
JS_FreeValue(ctx, eval_result);
return jsvalue_to_heap(JS_EXCEPTION);
} else if (state == JS_PROMISE_PENDING) {
QTS_DEBUG("QTS_Eval: result: JS_PROMISE_PENDING")
// return moduleDone.then(() => module_namespace)
JSValue module_namespace = JS_GetModuleNamespace(ctx, module);
if (JS_IsException(module_namespace)) {
QTS_DEBUG("QTS_Eval: module_namespace exception")
JS_FreeValue(ctx, eval_result);
return jsvalue_to_heap(module_namespace);
}
JSValue then_resolve_module_namespace = JS_NewCFunctionData(ctx, &qts_resolve_func_data, 0, 0, 1, &module_namespace);
JS_FreeValue(ctx, module_namespace);
if (JS_IsException(then_resolve_module_namespace)) {
QTS_DEBUG("QTS_Eval: then_resolve_module_namespace exception")
JS_FreeValue(ctx, eval_result);
return jsvalue_to_heap(then_resolve_module_namespace);
}
JSAtom then_atom = JS_NewAtom(ctx, "then");
JSValue new_promise = JS_Invoke(ctx, eval_result, then_atom, 1, &then_resolve_module_namespace);
QTS_DEBUG("QTS_Eval: new_promise = promise.then(() => resolveModuleNamespace())")
JS_FreeAtom(ctx, then_atom);
JS_FreeValue(ctx, then_resolve_module_namespace);
JS_FreeValue(ctx, eval_result);
return jsvalue_to_heap(new_promise);
} else {
// Unknown case
QTS_DEBUG("QTS_Eval: unknown JSPromiseStateEnum")
return jsvalue_to_heap(eval_result);
}
}
JSValue *QTS_GetModuleNamespace(JSContext *ctx, JSValueConst *module_func_obj) {
if (JS_VALUE_GET_TAG(*module_func_obj) != JS_TAG_MODULE) {
return jsvalue_to_heap(JS_ThrowInternalError(ctx, "Not a module"));
}
JSModuleDef *module = JS_VALUE_GET_PTR(*module_func_obj);
return jsvalue_to_heap(JS_GetModuleNamespace(ctx, module));
}
OwnedHeapChar *QTS_Typeof(JSContext *ctx, JSValueConst *value) {
const char *result = "unknown";
if (JS_IsNumber(*value)) {
result = "number";
} else if (JS_IsBigInt(ctx, *value)) {
result = "bigint";
#ifdef CONFIG_BIGNUM
} else if (JS_IsBigFloat(*value)) {
result = "bigfloat";
} else if (JS_IsBigDecimal(*value)) {
result = "bigdecimal";
#endif
} else if (JS_IsFunction(ctx, *value)) {
result = "function";
} else if (JS_IsBool(*value)) {
result = "boolean";
} else if (JS_IsNull(*value)) {
result = "object";
} else if (JS_IsUndefined(*value)) {
result = "undefined";
} else if (JS_IsUninitialized(*value)) {
result = "undefined";
} else if (JS_IsString(*value)) {
result = "string";
} else if (JS_IsSymbol(*value)) {
result = "symbol";
} else if (JS_IsObject(*value)) {
result = "object";
}
char *out = strdup(result);
return out;
}
JSAtom QTS_AtomLength = 0;
int QTS_GetLength(JSContext *ctx, uint32_t *out_len, JSValueConst *value) {
JSValue len_val;
int result;
if (!JS_IsObject(*value)) {
return -1;
}
if (QTS_AtomLength == 0) {
// This should result in a constant static atom we don't actually need to
// free, since it's interned within quickjs.c
QTS_AtomLength = JS_NewAtom(ctx, "length");
}
len_val = JS_GetProperty(ctx, *value, QTS_AtomLength);
if (JS_IsException(len_val)) {
return -1;
}
result = JS_ToUint32(ctx, out_len, len_val);
JS_FreeValue(ctx, len_val);
return result;
}
typedef enum IsEqualOp {
QTS_EqualOp_StrictEq = 0,
QTS_EqualOp_SameValue = 1,
QTS_EqualOp_SameValueZero = 2,
} IsEqualOp;
int QTS_IsEqual(JSContext *ctx, JSValueConst *a, JSValueConst *b, IsEqualOp op) {
#ifdef QTS_USE_QUICKJS_NG
return -1;
#else
switch (op) {
case QTS_EqualOp_SameValue:
return JS_SameValue(ctx, *a, *b);
case QTS_EqualOp_SameValueZero:
return JS_SameValueZero(ctx, *a, *b);
default:
case QTS_EqualOp_StrictEq:
return JS_StrictEq(ctx, *a, *b);
}
#endif
}
JSValue *QTS_GetGlobalObject(JSContext *ctx) {
return jsvalue_to_heap(JS_GetGlobalObject(ctx));
}
JSValue *QTS_NewPromiseCapability(JSContext *ctx, JSValue **resolve_funcs_out) {
JSValue resolve_funcs[2];
JSValue promise = JS_NewPromiseCapability(ctx, resolve_funcs);
resolve_funcs_out[0] = jsvalue_to_heap(resolve_funcs[0]);
resolve_funcs_out[1] = jsvalue_to_heap(resolve_funcs[1]);
return jsvalue_to_heap(promise);
}
JSPromiseStateEnum QTS_PromiseState(JSContext *ctx, JSValueConst *promise) {
return JS_PromiseState(ctx, *promise);
}
JSValue *QTS_PromiseResult(JSContext *ctx, JSValueConst *promise) {
return jsvalue_to_heap(JS_PromiseResult(ctx, *promise));
}
void QTS_TestStringArg(const char *string) {
// pass
}
int QTS_GetDebugLogEnabled(JSRuntime *rt) {
IF_DEBUG_RT {
return 1;