-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickjs-libc.c
3927 lines (3548 loc) · 109 KB
/
quickjs-libc.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
/*
* QuickJS C library
*
* Copyright (c) 2017-2021 Fabrice Bellard
* Copyright (c) 2017-2021 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 <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <limits.h>
#include <sys/stat.h>
#include <dirent.h>
#if defined(_WIN32)
#include <windows.h>
#include <conio.h>
#include <utime.h>
#else
#include <dlfcn.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#if defined(__APPLE__)
typedef sig_t sighandler_t;
#if !defined(environ)
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#endif
#endif /* __APPLE__ */
#endif
#if !defined(_WIN32)
/* enable the os.Worker API. IT relies on POSIX threads */
#define USE_WORKER
#endif
#ifdef USE_WORKER
#include <pthread.h>
#include <stdatomic.h>
#endif
#include "cutils.h"
#include "list.h"
#include "quickjs-libc.h"
/* TODO:
- add socket calls
*/
typedef struct {
struct list_head link;
int fd;
JSValue rw_func[2];
} JSOSRWHandler;
typedef struct {
struct list_head link;
int sig_num;
JSValue func;
} JSOSSignalHandler;
typedef struct {
struct list_head link;
BOOL has_object;
int64_t timeout;
JSValue func;
} JSOSTimer;
typedef struct {
struct list_head link;
uint8_t *data;
size_t data_len;
/* list of SharedArrayBuffers, necessary to free the message */
uint8_t **sab_tab;
size_t sab_tab_len;
} JSWorkerMessage;
typedef struct {
int ref_count;
#ifdef USE_WORKER
pthread_mutex_t mutex;
#endif
struct list_head msg_queue; /* list of JSWorkerMessage.link */
int read_fd;
int write_fd;
} JSWorkerMessagePipe;
typedef struct {
struct list_head link;
JSWorkerMessagePipe *recv_pipe;
JSValue on_message_func;
} JSWorkerMessageHandler;
typedef struct JSThreadState {
struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */
struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */
struct list_head os_timers; /* list of JSOSTimer.link */
struct list_head port_list; /* list of JSWorkerMessageHandler.link */
int eval_script_recurse; /* only used in the main thread */
/* not used in the main thread */
JSWorkerMessagePipe *recv_pipe, *send_pipe;
} JSThreadState;
static uint64_t os_pending_signals;
static int (*os_poll_func)(JSContext *ctx);
static void js_std_dbuf_init(JSContext *ctx, DynBuf *s)
{
dbuf_init2(s, JS_GetRuntime(ctx), (DynBufReallocFunc *)js_realloc_rt);
}
static BOOL my_isdigit(int c)
{
return (c >= '0' && c <= '9');
}
static JSValue js_printf_internal(JSContext *ctx,
int argc, JSValueConst *argv, FILE *fp)
{
char fmtbuf[32];
uint8_t cbuf[UTF8_CHAR_LEN_MAX+1];
JSValue res;
DynBuf dbuf;
const char *fmt_str;
const uint8_t *fmt, *fmt_end;
const uint8_t *p;
char *q;
int i, c, len, mod;
size_t fmt_len;
int32_t int32_arg;
int64_t int64_arg;
double double_arg;
const char *string_arg;
/* Use indirect call to dbuf_printf to prevent gcc warning */
int (*dbuf_printf_fun)(DynBuf *s, const char *fmt, ...) = (void*)dbuf_printf;
js_std_dbuf_init(ctx, &dbuf);
if (argc > 0) {
fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]);
if (!fmt_str)
goto fail;
i = 1;
fmt = (const uint8_t *)fmt_str;
fmt_end = fmt + fmt_len;
while (fmt < fmt_end) {
for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++)
continue;
dbuf_put(&dbuf, p, fmt - p);
if (fmt >= fmt_end)
break;
q = fmtbuf;
*q++ = *fmt++; /* copy '%' */
/* flags */
for(;;) {
c = *fmt;
if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' ||
c == '\'') {
if (q >= fmtbuf + sizeof(fmtbuf) - 1)
goto invalid;
*q++ = c;
fmt++;
} else {
break;
}
}
/* width */
if (*fmt == '*') {
if (i >= argc)
goto missing;
if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
goto fail;
q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg);
fmt++;
} else {
while (my_isdigit(*fmt)) {
if (q >= fmtbuf + sizeof(fmtbuf) - 1)
goto invalid;
*q++ = *fmt++;
}
}
if (*fmt == '.') {
if (q >= fmtbuf + sizeof(fmtbuf) - 1)
goto invalid;
*q++ = *fmt++;
if (*fmt == '*') {
if (i >= argc)
goto missing;
if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
goto fail;
q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg);
fmt++;
} else {
while (my_isdigit(*fmt)) {
if (q >= fmtbuf + sizeof(fmtbuf) - 1)
goto invalid;
*q++ = *fmt++;
}
}
}
/* we only support the "l" modifier for 64 bit numbers */
mod = ' ';
if (*fmt == 'l') {
mod = *fmt++;
}
/* type */
c = *fmt++;
if (q >= fmtbuf + sizeof(fmtbuf) - 1)
goto invalid;
*q++ = c;
*q = '\0';
switch (c) {
case 'c':
if (i >= argc)
goto missing;
if (JS_IsString(argv[i])) {
string_arg = JS_ToCString(ctx, argv[i++]);
if (!string_arg)
goto fail;
int32_arg = unicode_from_utf8((uint8_t *)string_arg, UTF8_CHAR_LEN_MAX, &p);
JS_FreeCString(ctx, string_arg);
} else {
if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
goto fail;
}
/* handle utf-8 encoding explicitly */
if ((unsigned)int32_arg > 0x10FFFF)
int32_arg = 0xFFFD;
/* ignore conversion flags, width and precision */
len = unicode_to_utf8(cbuf, int32_arg);
dbuf_put(&dbuf, cbuf, len);
break;
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'X':
if (i >= argc)
goto missing;
if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++]))
goto fail;
if (mod == 'l') {
/* 64 bit number */
#if defined(_WIN32)
if (q >= fmtbuf + sizeof(fmtbuf) - 3)
goto invalid;
q[2] = q[-1];
q[-1] = 'I';
q[0] = '6';
q[1] = '4';
q[3] = '\0';
dbuf_printf_fun(&dbuf, fmtbuf, (int64_t)int64_arg);
#else
if (q >= fmtbuf + sizeof(fmtbuf) - 2)
goto invalid;
q[1] = q[-1];
q[-1] = q[0] = 'l';
q[2] = '\0';
dbuf_printf_fun(&dbuf, fmtbuf, (long long)int64_arg);
#endif
} else {
dbuf_printf_fun(&dbuf, fmtbuf, (int)int64_arg);
}
break;
case 's':
if (i >= argc)
goto missing;
/* XXX: handle strings containing null characters */
string_arg = JS_ToCString(ctx, argv[i++]);
if (!string_arg)
goto fail;
dbuf_printf_fun(&dbuf, fmtbuf, string_arg);
JS_FreeCString(ctx, string_arg);
break;
case 'e':
case 'f':
case 'g':
case 'a':
case 'E':
case 'F':
case 'G':
case 'A':
if (i >= argc)
goto missing;
if (JS_ToFloat64(ctx, &double_arg, argv[i++]))
goto fail;
dbuf_printf_fun(&dbuf, fmtbuf, double_arg);
break;
case '%':
dbuf_putc(&dbuf, '%');
break;
default:
/* XXX: should support an extension mechanism */
invalid:
JS_ThrowTypeError(ctx, "invalid conversion specifier in format string");
goto fail;
missing:
JS_ThrowReferenceError(ctx, "missing argument for conversion specifier");
goto fail;
}
}
JS_FreeCString(ctx, fmt_str);
}
if (dbuf.error) {
res = JS_ThrowOutOfMemory(ctx);
} else {
if (fp) {
len = fwrite(dbuf.buf, 1, dbuf.size, fp);
res = JS_NewInt32(ctx, len);
} else {
res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size);
}
}
dbuf_free(&dbuf);
return res;
fail:
dbuf_free(&dbuf);
return JS_EXCEPTION;
}
uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename)
{
FILE *f;
uint8_t *buf;
size_t buf_len;
long lret;
f = fopen(filename, "rb");
if (!f)
return NULL;
if (fseek(f, 0, SEEK_END) < 0)
goto fail;
lret = ftell(f);
if (lret < 0)
goto fail;
/* XXX: on Linux, ftell() return LONG_MAX for directories */
if (lret == LONG_MAX) {
errno = EISDIR;
goto fail;
}
buf_len = lret;
if (fseek(f, 0, SEEK_SET) < 0)
goto fail;
if (ctx)
buf = js_malloc(ctx, buf_len + 1);
else
buf = malloc(buf_len + 1);
if (!buf)
goto fail;
if (fread(buf, 1, buf_len, f) != buf_len) {
errno = EIO;
if (ctx)
js_free(ctx, buf);
else
free(buf);
fail:
fclose(f);
return NULL;
}
buf[buf_len] = '\0';
fclose(f);
*pbuf_len = buf_len;
return buf;
}
/* load and evaluate a file */
static JSValue js_loadScript(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
uint8_t *buf;
const char *filename;
JSValue ret;
size_t buf_len;
filename = JS_ToCString(ctx, argv[0]);
if (!filename)
return JS_EXCEPTION;
buf = js_load_file(ctx, &buf_len, filename);
if (!buf) {
JS_ThrowReferenceError(ctx, "could not load '%s'", filename);
JS_FreeCString(ctx, filename);
return JS_EXCEPTION;
}
ret = JS_Eval(ctx, (char *)buf, buf_len, filename,
JS_EVAL_TYPE_GLOBAL);
js_free(ctx, buf);
JS_FreeCString(ctx, filename);
return ret;
}
/* load a file as a UTF-8 encoded string */
static JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
uint8_t *buf;
const char *filename;
JSValue ret;
size_t buf_len;
filename = JS_ToCString(ctx, argv[0]);
if (!filename)
return JS_EXCEPTION;
buf = js_load_file(ctx, &buf_len, filename);
JS_FreeCString(ctx, filename);
if (!buf)
return JS_NULL;
ret = JS_NewStringLen(ctx, (char *)buf, buf_len);
js_free(ctx, buf);
return ret;
}
typedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx,
const char *module_name);
#if defined(_WIN32)
static JSModuleDef *js_module_loader_so(JSContext *ctx,
const char *module_name)
{
JS_ThrowReferenceError(ctx, "shared library modules are not supported yet");
return NULL;
}
#else
static JSModuleDef *js_module_loader_so(JSContext *ctx,
const char *module_name)
{
JSModuleDef *m;
void *hd;
JSInitModuleFunc *init;
char *filename;
if (!strchr(module_name, '/')) {
/* must add a '/' so that the DLL is not searched in the
system library paths */
filename = js_malloc(ctx, strlen(module_name) + 2 + 1);
if (!filename)
return NULL;
strcpy(filename, "./");
strcpy(filename + 2, module_name);
} else {
filename = (char *)module_name;
}
/* C module */
hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL);
if (filename != module_name)
js_free(ctx, filename);
if (!hd) {
JS_ThrowReferenceError(ctx, "could not load module filename '%s' as shared library",
module_name);
goto fail;
}
init = dlsym(hd, "js_init_module");
if (!init) {
JS_ThrowReferenceError(ctx, "could not load module filename '%s': js_init_module not found",
module_name);
goto fail;
}
m = init(ctx, module_name);
if (!m) {
JS_ThrowReferenceError(ctx, "could not load module filename '%s': initialization error",
module_name);
fail:
if (hd)
dlclose(hd);
return NULL;
}
return m;
}
#endif /* !_WIN32 */
int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,
JS_BOOL use_realpath, JS_BOOL is_main)
{
JSModuleDef *m;
char buf[PATH_MAX + 16];
JSValue meta_obj;
JSAtom module_name_atom;
const char *module_name;
assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE);
m = JS_VALUE_GET_PTR(func_val);
module_name_atom = JS_GetModuleName(ctx, m);
module_name = JS_AtomToCString(ctx, module_name_atom);
JS_FreeAtom(ctx, module_name_atom);
if (!module_name)
return -1;
if (!strchr(module_name, ':')) {
strcpy(buf, "file://");
#if !defined(_WIN32)
/* realpath() cannot be used with modules compiled with qjsc
because the corresponding module source code is not
necessarily present */
if (use_realpath) {
char *res = realpath(module_name, buf + strlen(buf));
if (!res) {
JS_ThrowTypeError(ctx, "realpath failure");
JS_FreeCString(ctx, module_name);
return -1;
}
} else
#endif
{
pstrcat(buf, sizeof(buf), module_name);
}
} else {
pstrcpy(buf, sizeof(buf), module_name);
}
JS_FreeCString(ctx, module_name);
meta_obj = JS_GetImportMeta(ctx, m);
if (JS_IsException(meta_obj))
return -1;
JS_DefinePropertyValueStr(ctx, meta_obj, "url",
JS_NewString(ctx, buf),
JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, meta_obj, "main",
JS_NewBool(ctx, is_main),
JS_PROP_C_W_E);
JS_FreeValue(ctx, meta_obj);
return 0;
}
JSModuleDef *js_module_loader(JSContext *ctx,
const char *module_name, void *opaque)
{
JSModuleDef *m;
if (has_suffix(module_name, ".so")) {
m = js_module_loader_so(ctx, module_name);
} else {
size_t buf_len;
uint8_t *buf;
JSValue func_val;
buf = js_load_file(ctx, &buf_len, module_name);
if (!buf) {
JS_ThrowReferenceError(ctx, "could not load module filename '%s'",
module_name);
return NULL;
}
/* compile the module */
func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,
JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
js_free(ctx, buf);
if (JS_IsException(func_val))
return NULL;
/* XXX: could propagate the exception */
js_module_set_import_meta(ctx, func_val, TRUE, FALSE);
/* the module is already referenced, so we must free it */
m = JS_VALUE_GET_PTR(func_val);
JS_FreeValue(ctx, func_val);
}
return m;
}
static JSValue js_std_exit(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
int status;
if (JS_ToInt32(ctx, &status, argv[0]))
status = -1;
exit(status);
return JS_UNDEFINED;
}
static JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
const char *name, *str;
name = JS_ToCString(ctx, argv[0]);
if (!name)
return JS_EXCEPTION;
str = getenv(name);
JS_FreeCString(ctx, name);
if (!str)
return JS_UNDEFINED;
else
return JS_NewString(ctx, str);
}
#if defined(_WIN32)
static void setenv(const char *name, const char *value, int overwrite)
{
char *str;
size_t name_len, value_len;
name_len = strlen(name);
value_len = strlen(value);
str = malloc(name_len + 1 + value_len + 1);
memcpy(str, name, name_len);
str[name_len] = '=';
memcpy(str + name_len + 1, value, value_len);
str[name_len + 1 + value_len] = '\0';
_putenv(str);
free(str);
}
static void unsetenv(const char *name)
{
setenv(name, "", TRUE);
}
#endif /* _WIN32 */
static JSValue js_std_setenv(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
const char *name, *value;
name = JS_ToCString(ctx, argv[0]);
if (!name)
return JS_EXCEPTION;
value = JS_ToCString(ctx, argv[1]);
if (!value) {
JS_FreeCString(ctx, name);
return JS_EXCEPTION;
}
setenv(name, value, TRUE);
JS_FreeCString(ctx, name);
JS_FreeCString(ctx, value);
return JS_UNDEFINED;
}
static JSValue js_std_unsetenv(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
const char *name;
name = JS_ToCString(ctx, argv[0]);
if (!name)
return JS_EXCEPTION;
unsetenv(name);
JS_FreeCString(ctx, name);
return JS_UNDEFINED;
}
/* return an object containing the list of the available environment
variables. */
static JSValue js_std_getenviron(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
char **envp;
const char *name, *p, *value;
JSValue obj;
uint32_t idx;
size_t name_len;
JSAtom atom;
int ret;
obj = JS_NewObject(ctx);
if (JS_IsException(obj))
return JS_EXCEPTION;
envp = environ;
for(idx = 0; envp[idx] != NULL; idx++) {
name = envp[idx];
p = strchr(name, '=');
name_len = p - name;
if (!p)
continue;
value = p + 1;
atom = JS_NewAtomLen(ctx, name, name_len);
if (atom == JS_ATOM_NULL)
goto fail;
ret = JS_DefinePropertyValue(ctx, obj, atom, JS_NewString(ctx, value),
JS_PROP_C_W_E);
JS_FreeAtom(ctx, atom);
if (ret < 0)
goto fail;
}
return obj;
fail:
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
static JSValue js_std_gc(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
JS_RunGC(JS_GetRuntime(ctx));
return JS_UNDEFINED;
}
static int interrupt_handler(JSRuntime *rt, void *opaque)
{
return (os_pending_signals >> SIGINT) & 1;
}
static int get_bool_option(JSContext *ctx, BOOL *pbool,
JSValueConst obj,
const char *option)
{
JSValue val;
val = JS_GetPropertyStr(ctx, obj, option);
if (JS_IsException(val))
return -1;
if (!JS_IsUndefined(val)) {
*pbool = JS_ToBool(ctx, val);
}
JS_FreeValue(ctx, val);
return 0;
}
static JSValue js_evalScript(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
JSRuntime *rt = JS_GetRuntime(ctx);
JSThreadState *ts = JS_GetRuntimeOpaque(rt);
const char *str;
size_t len;
JSValue ret;
JSValueConst options_obj;
BOOL backtrace_barrier = FALSE;
int flags;
if (argc >= 2) {
options_obj = argv[1];
if (get_bool_option(ctx, &backtrace_barrier, options_obj,
"backtrace_barrier"))
return JS_EXCEPTION;
}
str = JS_ToCStringLen(ctx, &len, argv[0]);
if (!str)
return JS_EXCEPTION;
if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) {
/* install the interrupt handler */
JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL);
}
flags = JS_EVAL_TYPE_GLOBAL;
if (backtrace_barrier)
flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER;
ret = JS_Eval(ctx, str, len, "<evalScript>", flags);
JS_FreeCString(ctx, str);
if (!ts->recv_pipe && --ts->eval_script_recurse == 0) {
/* remove the interrupt handler */
JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL);
os_pending_signals &= ~((uint64_t)1 << SIGINT);
/* convert the uncatchable "interrupted" error into a normal error
so that it can be caught by the REPL */
if (JS_IsException(ret))
JS_ResetUncatchableError(ctx);
}
return ret;
}
static JSClassID js_std_file_class_id;
typedef struct {
FILE *f;
BOOL close_in_finalizer;
BOOL is_popen;
} JSSTDFile;
static void js_std_file_finalizer(JSRuntime *rt, JSValue val)
{
JSSTDFile *s = JS_GetOpaque(val, js_std_file_class_id);
if (s) {
if (s->f && s->close_in_finalizer) {
if (s->is_popen)
pclose(s->f);
else
fclose(s->f);
}
js_free_rt(rt, s);
}
}
static ssize_t js_get_errno(ssize_t ret)
{
if (ret == -1)
ret = -errno;
return ret;
}
static JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
int err;
if (JS_ToInt32(ctx, &err, argv[0]))
return JS_EXCEPTION;
return JS_NewString(ctx, strerror(err));
}
static JSValue js_std_parseExtJSON(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
JSValue obj;
const char *str;
size_t len;
str = JS_ToCStringLen(ctx, &len, argv[0]);
if (!str)
return JS_EXCEPTION;
obj = JS_ParseJSON2(ctx, str, len, "<input>", JS_PARSE_JSON_EXT);
JS_FreeCString(ctx, str);
return obj;
}
static JSValue js_new_std_file(JSContext *ctx, FILE *f,
BOOL close_in_finalizer,
BOOL is_popen)
{
JSSTDFile *s;
JSValue obj;
obj = JS_NewObjectClass(ctx, js_std_file_class_id);
if (JS_IsException(obj))
return obj;
s = js_mallocz(ctx, sizeof(*s));
if (!s) {
JS_FreeValue(ctx, obj);
return JS_EXCEPTION;
}
s->close_in_finalizer = close_in_finalizer;
s->is_popen = is_popen;
s->f = f;
JS_SetOpaque(obj, s);
return obj;
}
static void js_set_error_object(JSContext *ctx, JSValue obj, int err)
{
if (!JS_IsUndefined(obj)) {
JS_SetPropertyStr(ctx, obj, "errno", JS_NewInt32(ctx, err));
}
}
static JSValue js_std_open(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
const char *filename, *mode = NULL;
FILE *f;
int err;
filename = JS_ToCString(ctx, argv[0]);
if (!filename)
goto fail;
mode = JS_ToCString(ctx, argv[1]);
if (!mode)
goto fail;
if (mode[strspn(mode, "rwa+b")] != '\0') {
JS_ThrowTypeError(ctx, "invalid file mode");
goto fail;
}
f = fopen(filename, mode);
if (!f)
err = errno;
else
err = 0;
if (argc >= 3)
js_set_error_object(ctx, argv[2], err);
JS_FreeCString(ctx, filename);
JS_FreeCString(ctx, mode);
if (!f)
return JS_NULL;
return js_new_std_file(ctx, f, TRUE, FALSE);
fail:
JS_FreeCString(ctx, filename);
JS_FreeCString(ctx, mode);
return JS_EXCEPTION;
}
static JSValue js_std_popen(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
const char *filename, *mode = NULL;
FILE *f;
int err;
filename = JS_ToCString(ctx, argv[0]);
if (!filename)
goto fail;
mode = JS_ToCString(ctx, argv[1]);
if (!mode)
goto fail;
if (mode[strspn(mode, "rw")] != '\0') {
JS_ThrowTypeError(ctx, "invalid file mode");
goto fail;
}
f = popen(filename, mode);
if (!f)
err = errno;
else
err = 0;
if (argc >= 3)
js_set_error_object(ctx, argv[2], err);
JS_FreeCString(ctx, filename);
JS_FreeCString(ctx, mode);
if (!f)
return JS_NULL;
return js_new_std_file(ctx, f, TRUE, TRUE);
fail:
JS_FreeCString(ctx, filename);
JS_FreeCString(ctx, mode);
return JS_EXCEPTION;
}
static JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
const char *mode;
FILE *f;
int fd, err;
if (JS_ToInt32(ctx, &fd, argv[0]))
return JS_EXCEPTION;
mode = JS_ToCString(ctx, argv[1]);
if (!mode)
goto fail;
if (mode[strspn(mode, "rwa+")] != '\0') {
JS_ThrowTypeError(ctx, "invalid file mode");
goto fail;
}
f = fdopen(fd, mode);
if (!f)
err = errno;
else
err = 0;
if (argc >= 3)
js_set_error_object(ctx, argv[2], err);
JS_FreeCString(ctx, mode);
if (!f)
return JS_NULL;
return js_new_std_file(ctx, f, TRUE, FALSE);
fail:
JS_FreeCString(ctx, mode);
return JS_EXCEPTION;
}
static JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
FILE *f;
f = tmpfile();
if (argc >= 1)
js_set_error_object(ctx, argv[0], f ? 0 : errno);
if (!f)
return JS_NULL;
return js_new_std_file(ctx, f, TRUE, FALSE);
}
static JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
return js_printf_internal(ctx, argc, argv, NULL);
}
static JSValue js_std_printf(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
return js_printf_internal(ctx, argc, argv, stdout);
}
static FILE *js_std_file_get(JSContext *ctx, JSValueConst obj)
{
JSSTDFile *s = JS_GetOpaque2(ctx, obj, js_std_file_class_id);
if (!s)