forked from bellard/mquickjs
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmquickjs.c
More file actions
18494 lines (16991 loc) · 563 KB
/
mquickjs.c
File metadata and controls
18494 lines (16991 loc) · 563 KB
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
/*
* Micro QuickJS Javascript Engine
*
* Copyright (c) 2017-2025 Fabrice Bellard
* Copyright (c) 2017-2025 Charlie Gordon
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <inttypes.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <setjmp.h>
#include "cutils.h"
#include "dtoa.h"
#include "mquickjs_priv.h"
/*
TODO:
- regexp: better error position info
- use a specific MTAG for short functions instead of an immediate value
- use hash table for atoms
- set the length accessors as non configurable so that the
'get_length' instruction optimizations are always safe.
- memory:
- fix stack_bottom logic
- launch gc at regular intervals
- only launch compaction when needed (handle free blocks in malloc())
- avoid pass to rehash the properties
- ensure no undefined bytes (e.g. at end of JSString) in
saved bytecode ?
- reduced memory usage:
- reduce JSFunctionBytecode size (remove source_pos)
- do not explicitly store function names for get/set/bound
- use JSSTDLibraryDef fields instead of copying them to JSContext ?
*/
#define __exception __attribute__((warn_unused_result))
#define JS_STACK_SLACK 16 /* additional free space on the stack */
/* min free size in bytes between heap_free and the bottom of the stack */
#define JS_MIN_FREE_SIZE 512
/* minimum free size in bytes to create the out of memory object */
#define JS_MIN_CRITICAL_FREE_SIZE (JS_MIN_FREE_SIZE - 256)
#define JS_MAX_LOCAL_VARS 65535
#define JS_MAX_FUNC_STACK_SIZE 65535
#define JS_MAX_ARGC 65535
/* maximum number of recursing JS_Call() */
#define JS_MAX_CALL_RECURSE 8
#define JS_VALUE_IS_BOTH_INT(a, b) ((((a) | (b)) & 1) == 0)
#define JS_VALUE_IS_BOTH_SHORT_FLOAT(a, b) (((((a) - JS_TAG_SHORT_FLOAT) | ((b) - JS_TAG_SHORT_FLOAT)) & 7) == 0)
static __maybe_unused const char *js_mtag_name[JS_MTAG_COUNT] = {
"free",
"object",
"float64",
"string",
"func_bytecode",
"value_array",
"byte_array",
"varref",
};
/* function call flags (max 31 bits) */
#define FRAME_CF_ARGC_MASK 0xffff
/* FRAME_CF_CTOR */
#define FRAME_CF_POP_RET (1 << 17) /* pop the return value */
#define FRAME_CF_PC_ADD1 (1 << 18) /* increment the PC by 1 instead of 3 */
#define JS_MB_PAD(n) (JSW * 8 - (n))
typedef struct {
JS_MB_HEADER;
JSWord dummy: JS_MB_PAD(JS_MTAG_BITS);
} JSMemBlockHeader;
typedef struct {
JS_MB_HEADER;
/* in JSWords excluding the header. Free blocks of JSW bytes
are only generated by js_shrink() and may not be always
compacted */
JSWord size: JS_MB_PAD(JS_MTAG_BITS);
} JSFreeBlock;
#if JSW == 8
#define JS_STRING_LEN_MAX 0x7ffffffe
#else
#define JS_STRING_LEN_MAX ((1 << (32 - JS_MTAG_BITS - 3)) - 1)
#endif
typedef struct {
JS_MB_HEADER;
JSWord is_unique: 1;
JSWord is_ascii: 1;
/* true if the string content represents a number, only meaningful
is is_unique = true */
JSWord is_numeric: 1;
JSWord len: JS_MB_PAD(JS_MTAG_BITS + 3);
uint8_t buf[];
} JSString;
typedef struct {
JSWord string_buf[sizeof(JSString) / sizeof(JSWord)]; /* for JSString */
uint8_t buf[5];
} JSStringCharBuf;
#define JS_BYTE_ARRAY_SIZE_MAX ((1 << (32 - JS_MTAG_BITS)) - 1)
typedef struct {
JS_MB_HEADER;
JSWord size: JS_MB_PAD(JS_MTAG_BITS);
uint8_t buf[];
} JSByteArray;
#define JS_VALUE_ARRAY_SIZE_MAX ((1 << (32 - JS_MTAG_BITS)) - 1)
typedef struct {
JS_MB_HEADER;
JSWord size: JS_MB_PAD(JS_MTAG_BITS);
JSValue arr[];
} JSValueArray;
typedef struct JSVarRef {
JS_MB_HEADER;
JSWord is_detached : 1;
JSWord dummy: JS_MB_PAD(JS_MTAG_BITS + 1);
union {
JSValue value; /* is_detached = true */
struct {
JSValue next; /* is_detached = false: JS_NULL or JSVarRef,
must be at the same address as 'value' */
JSValue *pvalue;
};
} u;
} JSVarRef;
typedef struct {
JS_MB_HEADER;
JSWord dummy: JS_MB_PAD(JS_MTAG_BITS);
#ifdef JS_PTR64
struct {
double dval;
} u;
#else
/* unaligned 64 bit access in 32-bit mode */
struct __attribute__((packed)) {
double dval;
} u;
#endif
} JSFloat64;
typedef struct JSROMClass {
JS_MB_HEADER;
JSWord dummy: JS_MB_PAD(JS_MTAG_BITS);
JSValue props;
int32_t ctor_idx; /* -1 if defining a normal object */
JSValue proto_props;
JSValue parent_class; /* JSROMClass or JS_NULL */
} JSROMClass;
#define N_ROM_ATOM_TABLES_MAX 2
/* must be large enough to have a negligible runtime cost and small
enough to call the interrupt callback often. */
#define JS_INTERRUPT_COUNTER_INIT 10000
#define JS_STRING_POS_CACHE_SIZE 2
#define JS_STRING_POS_CACHE_MIN_LEN 16
typedef enum {
POS_TYPE_UTF8,
POS_TYPE_UTF16,
} StringPosTypeEnum;
typedef struct {
JSValue str; /* JS_NULL or weak reference to a JSString. It
contains at least JS_STRING_POS_CACHE_MIN_LEN
bytes and is a non ascii string */
uint32_t str_pos[2]; /* 0 = UTF-8 pos (in bytes), 1 = UTF-16 pos */
} JSStringPosCacheEntry;
struct JSContext {
/* memory map:
Stack
Free area
Heap
JSContext
*/
uint8_t *heap_base;
uint8_t *heap_free; /* first free area */
uint8_t *stack_top;
JSValue *stack_bottom; /* sp must always be higher than stack_bottom */
JSValue *sp; /* current stack pointer */
JSValue *fp; /* current frame pointer, stack_top if none */
uint32_t min_free_size; /* min free size between heap_free and the
bottom of the stack */
BOOL in_out_of_memory : 8; /* != 0 if generating the out of memory object */
uint8_t n_rom_atom_tables;
uint8_t string_pos_cache_counter; /* used for string_pos_cache[] update */
uint16_t class_count; /* number of classes including user classes */
int16_t interrupt_counter;
BOOL current_exception_is_uncatchable : 8;
struct JSParseState *parse_state; /* != NULL during JS_Eval() */
int unique_strings_len;
int js_call_rec_count; /* number of recursing JS_Call() */
JSGCRef *top_gc_ref; /* used to reference temporary GC roots (stack top) */
JSGCRef *last_gc_ref; /* used to reference temporary GC roots (list) */
const JSWord *atom_table; /* constant atom table */
/* 'n_rom_atom_tables' atom tables from code loaded from rom */
const JSValueArray *rom_atom_tables[N_ROM_ATOM_TABLES_MAX];
const JSCFunctionDef *c_function_table;
const JSCFinalizer *c_finalizer_table;
uint64_t random_state;
JSInterruptHandler *interrupt_handler;
JSWriteFunc *write_func; /* for the various dump functions */
void *opaque;
JSValue *class_obj; /* same as class_proto + class_count */
JSStringPosCacheEntry string_pos_cache[JS_STRING_POS_CACHE_SIZE];
/* must only contain JSValue from this point (see JS_GC()) */
JSValue unique_strings; /* JSValueArray of sorted strings or JS_NULL */
JSValue current_exception; /* currently pending exception, must
come after unique_strings */
#ifdef DEBUG_GC
JSValue dummy_block; /* dummy memory block near the start of the memory */
#endif
JSValue empty_props; /* empty prop list, for objects with no properties */
JSValue global_obj;
JSValue minus_zero; /* minus zero float64 value */
JSValue class_proto[]; /* prototype for each class (class_count
element, then class_count elements for
class_obj */
};
typedef enum {
JS_VARREF_KIND_ARG, /* var_idx is an argument of the parent function */
JS_VARREF_KIND_VAR, /* var_idx is a local variable of the parent function */
JS_VARREF_KIND_VAR_REF, /* var_idx is a var ref of the parent function */
JS_VARREF_KIND_GLOBAL, /* to debug */
} JSVarRefKindEnum;
typedef struct JSObject JSObject;
typedef struct {
/* string, short integer or JS_UNINITIALIZED if no property. If
the last property is uninitialized, hash_next = 2 *
first_free. */
JSValue key;
/* JS_PROP_GETSET: JSValueArray of two elements
JS_PROP_VARREF: JSVarRef */
JSValue value;
/* XXX: when JSW = 8, could use 32 bits for hash_next (faster) */
uint32_t hash_next : 30; /* low bit at zero */
uint32_t prop_type : 2;
} JSProperty;
typedef struct {
JSValue func_bytecode; /* JSFunctionBytecode */
JSValue var_refs[]; /* JSValueArray */
} JSClosureData;
typedef struct {
uint32_t idx;
JSValue params; /* optional associated parameters */
} JSCFunctionData;
typedef struct {
JSValue tab; /* JS_NULL or JSValueArray */
uint32_t len; /* maximum value: 2^30-1 */
} JSArrayData;
typedef struct {
JSValue message; /* string or JS_NULL */
JSValue stack; /* string or JS_NULL */
} JSErrorData;
typedef struct {
JSValue byte_buffer; /* JSByteBuffer */
} JSArrayBuffer;
typedef struct {
JSValue buffer; /* corresponding array buffer */
uint32_t len; /* in elements */
uint32_t offset; /* in elements */
} JSTypedArray;
typedef struct {
JSValue source;
JSValue byte_code;
int last_index;
} JSRegExp;
typedef struct {
void *opaque;
} JSObjectUserData;
struct JSObject {
JS_MB_HEADER;
JSWord class_id: 8;
JSWord extra_size: JS_MB_PAD(JS_MTAG_BITS + 8); /* object additional size, in JSValue */
JSValue proto; /* JSObject or JS_NULL */
/* JSValueArray. structure:
prop_count (number of properties excluding deleted ones)
hash_mask (= hash_size - 1)
hash_table[hash_size] (0 = end of list or offset in array)
JSProperty props[]
*/
JSValue props;
/* number of additional fields depends on the object */
union {
JSClosureData closure;
JSCFunctionData cfunc;
JSArrayData array;
JSErrorData error;
JSArrayBuffer array_buffer;
JSTypedArray typed_array;
JSRegExp regexp;
JSObjectUserData user;
} u;
};
typedef struct JSFunctionBytecode {
JS_MB_HEADER;
JSWord has_arguments : 1; /* only used during parsing */
JSWord has_local_func_name : 1; /* only used during parsing */
JSWord has_column : 1; /* column debug info is present */
/* during parse: variable index + 1 of hoisted function, 0 otherwise */
JSWord arg_count : 16;
JSWord dummy: JS_MB_PAD(JS_MTAG_BITS + 3 + 16);
JSValue func_name; /* JS_NULL if anonymous function */
JSValue byte_code; /* JS_NULL if the function is not parsed yet */
JSValue cpool; /* constant pool */
JSValue vars; /* only for debug */
JSValue ext_vars; /* records of (var_name, var_kind (2 bits) var_idx (16 bits)) */
uint16_t stack_size; /* maximum stack size */
uint16_t ext_vars_len; /* XXX: only used during parsing */
JSValue filename; /* filename in which the function is defined */
JSValue pc2line; /* JSByteArray or JS_NULL if not initialized */
uint32_t source_pos; /* only used during parsing (XXX: shrink) */
} JSFunctionBytecode;
static JSValue js_resize_value_array(JSContext *ctx, JSValue val, int new_size);
static int get_mblock_size(const void *ptr);
static JSValue JS_NewObjectProtoClass(JSContext *ctx, JSValue proto, int class_id, int extra_size);
static void js_shrink_byte_array(JSContext *ctx, JSValue *pval, int new_size);
static void build_backtrace(JSContext *ctx, JSValue error_obj,
const char *filename, int line_num, int col_num, int skip_level);
static JSValue JS_ToPropertyKey(JSContext *ctx, JSValue val);
static JSByteArray *js_alloc_byte_array(JSContext *ctx, int size);
static JSValue js_new_c_function_proto(JSContext *ctx, int func_idx, JSValue proto, BOOL has_params,
JSValue params);
static int JS_ToUint8Clamp(JSContext *ctx, int *pres, JSValue val);
static JSValue js_set_prototype_internal(JSContext *ctx, JSValue obj, JSValue proto);
static JSValue js_resize_byte_array(JSContext *ctx, JSValue val, int new_size);
static JSValueArray *js_alloc_props(JSContext *ctx, int n);
typedef enum OPCodeFormat {
#define FMT(f) OP_FMT_ ## f,
#define DEF(id, size, n_pop, n_push, f)
#include "mquickjs_opcode.h"
#undef DEF
#undef FMT
} OPCodeFormat;
typedef enum OPCodeEnum {
#define FMT(f)
#define DEF(id, size, n_pop, n_push, f) OP_ ## id,
#define def(id, size, n_pop, n_push, f)
#include "mquickjs_opcode.h"
#undef def
#undef DEF
#undef FMT
OP_COUNT,
} OPCodeEnum;
typedef struct {
#ifdef DUMP_BYTECODE
const char *name;
#endif
uint8_t size; /* in bytes */
/* the opcodes remove n_pop items from the top of the stack, then
pushes n_pusch items */
uint8_t n_pop;
uint8_t n_push;
uint8_t fmt;
} JSOpCode;
static __maybe_unused const JSOpCode opcode_info[OP_COUNT] = {
#define FMT(f)
#ifdef DUMP_BYTECODE
#define DEF(id, size, n_pop, n_push, f) { #id, size, n_pop, n_push, OP_FMT_ ## f },
#else
#define DEF(id, size, n_pop, n_push, f) { size, n_pop, n_push, OP_FMT_ ## f },
#endif
#include "mquickjs_opcode.h"
#undef DEF
#undef FMT
};
#include "mquickjs_atom.h"
JSValue *JS_PushGCRef(JSContext *ctx, JSGCRef *ref)
{
ref->prev = ctx->top_gc_ref;
ctx->top_gc_ref = ref;
ref->val = JS_UNDEFINED;
return &ref->val;
}
JSValue JS_PopGCRef(JSContext *ctx, JSGCRef *ref)
{
ctx->top_gc_ref = ref->prev;
return ref->val;
}
JSValue *JS_AddGCRef(JSContext *ctx, JSGCRef *ref)
{
ref->prev = ctx->last_gc_ref;
ctx->last_gc_ref = ref;
ref->val = JS_UNDEFINED;
return &ref->val;
}
void JS_DeleteGCRef(JSContext *ctx, JSGCRef *ref)
{
JSGCRef **pref, *ref1;
pref = &ctx->last_gc_ref;
for(;;) {
ref1 = *pref;
if (ref1 == NULL)
abort();
if (ref1 == ref) {
*pref = ref1->prev;
break;
}
pref = &ref1->prev;
}
}
#undef JS_PUSH_VALUE
#undef JS_POP_VALUE
#define JS_PUSH_VALUE(ctx, v) do { \
v ## _ref.prev = ctx->top_gc_ref; \
ctx->top_gc_ref = &v ## _ref; \
v ## _ref.val = v; \
} while (0)
#define JS_POP_VALUE(ctx, v) do { \
v = v ## _ref.val; \
ctx->top_gc_ref = v ## _ref.prev; \
} while (0)
static JSValue js_get_atom(JSContext *ctx, int a)
{
return JS_VALUE_FROM_PTR(&ctx->atom_table[a]);
}
static force_inline JSValue JS_NewTailCall(int val)
{
return JS_VALUE_MAKE_SPECIAL(JS_TAG_EXCEPTION, JS_EX_CALL + val);
}
static inline JS_BOOL JS_IsExceptionOrTailCall(JSValue v)
{
return JS_VALUE_GET_SPECIAL_TAG(v) == JS_TAG_EXCEPTION;
}
static int js_get_mtag(void *ptr)
{
return ((JSMemBlockHeader *)ptr)->mtag;
}
static int check_free_mem(JSContext *ctx, JSValue *stack_bottom, uint32_t size)
{
#ifdef DEBUG_GC
assert(ctx->sp >= stack_bottom);
/* don't start the GC before dummy_block is allocated */
if (JS_IsPtr(ctx->dummy_block)) {
JS_GC(ctx);
}
#endif
if (((uint8_t *)stack_bottom - ctx->heap_free) < size + ctx->min_free_size) {
JS_GC(ctx);
if (((uint8_t *)stack_bottom - ctx->heap_free) < size + ctx->min_free_size) {
JS_ThrowOutOfMemory(ctx);
return -1;
}
}
return 0;
}
/* check that 'len' values can be pushed on the stack. Return 0 if OK,
-1 if not enough space. May trigger a GC(). */
int JS_StackCheck(JSContext *ctx, uint32_t len)
{
JSValue *new_stack_bottom;
len += JS_STACK_SLACK;
new_stack_bottom = ctx->sp - len;
if (check_free_mem(ctx, new_stack_bottom, len * sizeof(JSValue)))
return -1;
ctx->stack_bottom = new_stack_bottom;
return 0;
}
static void *js_malloc(JSContext *ctx, uint32_t size, int mtag)
{
JSMemBlockHeader *p;
if (size == 0)
return NULL;
size = (size + JSW - 1) & ~(JSW - 1);
if (check_free_mem(ctx, ctx->stack_bottom, size))
return NULL;
p = (JSMemBlockHeader *)ctx->heap_free;
ctx->heap_free += size;
p->mtag = mtag;
p->gc_mark = 0;
p->dummy = 0;
return p;
}
static void *js_mallocz(JSContext *ctx, uint32_t size, int mtag)
{
uint8_t *ptr;
ptr = js_malloc(ctx, size, mtag);
if (!ptr)
return NULL;
if (size > sizeof(uint32_t)) {
memset(ptr + sizeof(uint32_t), 0, size - sizeof(uint32_t));
}
return ptr;
}
/* currently only free the last element */
static void js_free(JSContext *ctx, void *ptr)
{
uint8_t *ptr1;
if (!ptr)
return;
ptr1 = ptr;
ptr1 += get_mblock_size(ptr1);
if (ptr1 == ctx->heap_free)
ctx->heap_free = ptr;
}
/* 'size' is in bytes and must be multiple of JSW and > 0 */
static void set_free_block(void *ptr, uint32_t size)
{
JSFreeBlock *p;
p = (JSFreeBlock *)ptr;
p->mtag = JS_MTAG_FREE;
p->gc_mark = 0;
p->size = (size - sizeof(JSFreeBlock)) / sizeof(JSWord);
}
/* 'ptr' must be != NULL. new_size must be less or equal to the
current block size. */
static void *js_shrink(JSContext *ctx, void *ptr, uint32_t new_size)
{
uint32_t old_size;
uint32_t diff;
new_size = (new_size + (JSW - 1)) & ~(JSW - 1);
if (new_size == 0) {
js_free(ctx, ptr);
return NULL;
}
old_size = get_mblock_size(ptr);
assert(new_size <= old_size);
diff = old_size - new_size;
if (diff == 0)
return ptr;
set_free_block((uint8_t *)ptr + new_size, diff);
/* add a new free block after 'ptr' */
return ptr;
}
JSValue JS_Throw(JSContext *ctx, JSValue obj)
{
ctx->current_exception = obj;
ctx->current_exception_is_uncatchable = FALSE;
return JS_EXCEPTION;
}
/* return the byte length. 'buf' must contain UTF8_CHAR_LEN_MAX + 1 bytes */
static int get_short_string(uint8_t *buf, JSValue val)
{
int len;
len = unicode_to_utf8(buf, JS_VALUE_GET_SPECIAL_VALUE(val));
buf[len] = '\0';
return len;
}
/* printf utility */
#define PF_ZERO_PAD (1 << 0) /* 0 */
#define PF_ALT_FORM (1 << 1) /* # */
#define PF_MARK_POS (1 << 2) /* + */
#define PF_LEFT_ADJ (1 << 3) /* - */
#define PF_PAD_POS (1 << 4) /* ' ' */
#define PF_INT64 (1 << 5) /* l/ll */
static BOOL is_digit(int c)
{
return (c >= '0' && c <= '9');
}
/* pad with chars 'c' */
static void pad(JSWriteFunc *write_func, void *opaque, char c,
int width, int len)
{
char buf[16];
int l;
if (len >= width)
return;
width -= len;
memset(buf, c, min_int(sizeof(buf), width));
while (width != 0) {
l = min_int(width, sizeof(buf));
write_func(opaque, buf, l);
width -= l;
}
}
/* The 'o' format can be used to print a JSValue. Only short int,
bool, null, undefined and string types are supported. */
static void js_vprintf(JSWriteFunc *write_func, void *opaque, const char *fmt, va_list ap)
{
const char *p;
int width, prec, flags, c;
char tmp_buf[32], *buf;
size_t len;
while (*fmt != '\0') {
p = fmt;
while (*fmt != '%' && *fmt != '\0')
fmt++;
if (fmt > p)
write_func(opaque, p, fmt - p);
if (*fmt == '\0')
break;
fmt++;
/* get the flags */
flags = 0;
for(;;) {
c = *fmt;
if (c == '0') {
flags |= PF_ZERO_PAD;
} else if (c == '#') {
flags |= PF_ALT_FORM;
} else if (c == '+') {
flags |= PF_MARK_POS;
} else if (c == '-') {
flags |= PF_LEFT_ADJ;
} else if (c == ' ') {
flags |= PF_MARK_POS;
} else {
break;
}
fmt++;
}
width = 0;
if (*fmt == '*') {
width = va_arg(ap, int);
} else {
while (is_digit(*fmt)) {
width = width * 10 + *fmt - '0';
fmt++;
}
}
prec = 0;
if (*fmt == '.') {
fmt++;
if (*fmt == '*') {
prec = va_arg(ap, int);
} else {
while (is_digit(*fmt)) {
prec = prec * 10 + *fmt - '0';
fmt++;
}
}
}
/* modifiers */
for(;;) {
c = *fmt;
if (c == 'l') {
if (sizeof(long) == sizeof(int64_t) || fmt[-1] == 'l')
flags |= PF_INT64;
} else
if (c == 'z' || c == 't') {
if (sizeof(size_t) == sizeof(uint64_t))
flags |= PF_INT64;
} else {
break;
}
fmt++;
}
c = *fmt++;
/* XXX: not complete, just enough for our needs */
buf = tmp_buf;
len = 0;
switch(c) {
case '%':
write_func(opaque, fmt - 1, 1);
break;
case 'c':
buf[0] = va_arg(ap, int);
len = 1;
flags &= ~PF_ZERO_PAD;
break;
case 's':
buf = va_arg(ap, char *);
if (!buf)
buf = "null";
len = strlen(buf);
flags &= ~PF_ZERO_PAD;
break;
case 'd':
if (flags & PF_INT64)
len = i64toa(buf, va_arg(ap, int64_t));
else
len = i32toa(buf, va_arg(ap, int32_t));
break;
case 'u':
if (flags & PF_INT64)
len = u64toa(buf, va_arg(ap, uint64_t));
else
len = u32toa(buf, va_arg(ap, uint32_t));
break;
case 'x':
if (flags & PF_INT64)
len = u64toa_radix(buf, va_arg(ap, uint64_t), 16);
else
len = u64toa_radix(buf, va_arg(ap, uint32_t), 16);
break;
case 'p':
buf[0] = '0';
buf[1] = 'x';
len = u64toa_radix(buf + 2, (uintptr_t)va_arg(ap, void *), 16);
len += 2;
break;
case 'o':
{
JSValue val = (flags & PF_INT64) ? va_arg(ap, uint64_t) : va_arg(ap, uint32_t);
if (JS_IsInt(val)) {
len = i32toa(buf, JS_VALUE_GET_INT(val));
} else
#ifdef JS_USE_SHORT_FLOAT
if (JS_IsShortFloat(val)) {
/* XXX: print it */
buf = "[short_float]";
goto do_strlen;
} else
#endif
if (!JS_IsPtr(val)) {
switch(JS_VALUE_GET_SPECIAL_TAG(val)) {
case JS_TAG_NULL:
buf = "null";
goto do_strlen;
case JS_TAG_UNDEFINED:
buf = "undefined";
goto do_strlen;
case JS_TAG_UNINITIALIZED:
buf = "uninitialized";
goto do_strlen;
case JS_TAG_BOOL:
buf = JS_VALUE_GET_SPECIAL_VALUE(val) ? "true" : "false";
goto do_strlen;
case JS_TAG_STRING_CHAR:
len = get_short_string((uint8_t *)buf, val);
break;
default:
buf = "[tag]";
goto do_strlen;
}
} else {
void *ptr = JS_VALUE_TO_PTR(val);
int mtag = ((JSMemBlockHeader *)ptr)->mtag;
switch(mtag) {
case JS_MTAG_STRING:
{
JSString *p = ptr;
buf = (char *)p->buf;
len = p->len;
}
break;
default:
buf = "[mtag]";
do_strlen:
len = strlen(buf);
break;
}
}
/* remove the trailing '\n' if any (used in error output) */
if ((flags & PF_ALT_FORM) && len > 0 && buf[len - 1] == '\n')
len--;
flags &= ~PF_ZERO_PAD;
}
break;
default:
goto error;
}
if (flags & PF_ZERO_PAD) {
/* XXX: incorrect with prefix */
pad(write_func, opaque, '0', width, len);
} else {
if (!(flags & PF_LEFT_ADJ))
pad(write_func, opaque, ' ', width, len);
}
write_func(opaque, buf, len);
if (flags & PF_LEFT_ADJ)
pad(write_func, opaque, ' ', width, len);
}
return;
error:
return;
}
/* used for the debug output */
static void __js_printf_like(2, 3) js_printf(JSContext *ctx,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
js_vprintf(ctx->write_func, ctx->opaque, fmt, ap);
va_end(ap);
}
static __maybe_unused void js_putchar(JSContext *ctx, uint8_t c)
{
ctx->write_func(ctx->opaque, &c, 1);
}
typedef struct {
char *ptr;
char *buf_end;
int len;
} SNPrintfState;
static void snprintf_write_func(void *opaque, const void *buf, size_t buf_len)
{
SNPrintfState *s = opaque;
size_t l;
s->len += buf_len;
l = min_size_t(buf_len, s->buf_end - s->ptr);
if (l != 0) {
memcpy(s->ptr, buf, l);
s->ptr += l;
}
}
static int js_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap)
{
SNPrintfState ss, *s = &ss;
s->ptr = buf;
s->buf_end = buf + max_size_t(buf_size, 1) - 1;
s->len = 0;
js_vprintf(snprintf_write_func, s, fmt, ap);
if (buf_size > 0)
*s->ptr = '\0';
return s->len;
}
static int __maybe_unused __js_printf_like(3, 4) js_snprintf(char *buf, size_t buf_size, const char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
ret = js_vsnprintf(buf, buf_size, fmt, ap);
va_end(ap);
return ret;
}
JSValue __js_printf_like(3, 4) JS_ThrowError(JSContext *ctx, JSObjectClassEnum error_num,
const char *fmt, ...)
{
JSObject *p;
va_list ap;
char buf[128];
JSValue msg, error_obj;
JSGCRef msg_ref, error_obj_ref;
va_start(ap, fmt);
js_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
msg = JS_NewString(ctx, buf);
JS_PUSH_VALUE(ctx, msg);
error_obj = JS_NewObjectProtoClass(ctx, ctx->class_proto[error_num], JS_CLASS_ERROR,
sizeof(JSErrorData));
JS_POP_VALUE(ctx, msg);
if (JS_IsException(error_obj))
return error_obj;
p = JS_VALUE_TO_PTR(error_obj);
p->u.error.message = msg;
p->u.error.stack = JS_NULL;
/* in case of syntax error, the backtrace is added later */
if (error_num != JS_CLASS_SYNTAX_ERROR) {
JS_PUSH_VALUE(ctx, error_obj);
build_backtrace(ctx, error_obj, NULL, 0, 0, 0);
JS_POP_VALUE(ctx, error_obj);
}
return JS_Throw(ctx, error_obj);
}
JSValue JS_ThrowOutOfMemory(JSContext *ctx)
{
JSValue val;
if (ctx->in_out_of_memory)
return JS_Throw(ctx, JS_NULL);
ctx->in_out_of_memory = TRUE;
ctx->min_free_size = JS_MIN_CRITICAL_FREE_SIZE;
val = JS_ThrowInternalError(ctx, "out of memory");
ctx->in_out_of_memory = FALSE;
ctx->min_free_size = JS_MIN_FREE_SIZE;
return val;
}
#define JS_SHORTINT_MIN (-(1 << 30))
#define JS_SHORTINT_MAX ((1 << 30) - 1)
#ifdef JS_USE_SHORT_FLOAT
#define JS_FLOAT64_VALUE_EXP_MIN (1023 - 127)
#define JS_FLOAT64_VALUE_ADDEND ((uint64_t)(JS_FLOAT64_VALUE_EXP_MIN - (JS_TAG_SHORT_FLOAT << 8)) << 52)
/* 1 <= n <= 63 */
static inline uint64_t rotl64(uint64_t a, int n)
{
return (a << n) | (a >> (64 - n));
}
static double js_get_short_float(JSValue v)
{
return uint64_as_float64(rotl64(v, 60) + JS_FLOAT64_VALUE_ADDEND);
}
static JSValue js_to_short_float(double d)
{
return rotl64(float64_as_uint64(d) - JS_FLOAT64_VALUE_ADDEND, 4);
}
#endif /* JS_USE_SHORT_FLOAT */
static JSValue js_alloc_float64(JSContext *ctx, double d)
{
JSFloat64 *f;
f = js_malloc(ctx, sizeof(JSFloat64), JS_MTAG_FLOAT64);
if (!f)
return JS_EXCEPTION;
f->u.dval = d;
return JS_VALUE_FROM_PTR(f);
}
/* create a new float64 value which is known not to be a short integer */
static JSValue __JS_NewFloat64(JSContext *ctx, double d)
{
if (float64_as_uint64(d) == 0x8000000000000000) {
/* minus zero often happens, so it is worth having a constant
value */
return ctx->minus_zero;
} else
#ifdef JS_USE_SHORT_FLOAT
/* Note: this test is false for NaN */
if (fabs(d) >= 0x1p-127 && fabs(d) <= 0x1p+128) {