Debian Codegraph @

quickjs/quickjs-libc.c

raw symbols SCIP
1 /*
2 * QuickJS C library
3 *
4 * Copyright (c) 2017-2021 Fabrice Bellard
5 * Copyright (c) 2017-2021 Charlie Gordon
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <stdarg.h>
28 #include <inttypes.h>
29 #include <string.h>
30 #include <assert.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <sys/time.h>
35 #include <time.h>
36 #include <signal.h>
37 #include <limits.h>
38 #include <sys/stat.h>
39 #include <dirent.h>
40 #if defined(_WIN32)
41 #include <windows.h>
42 #include <conio.h>
43 #include <utime.h>
44 #else
45 #include <dlfcn.h>
46 #include <termios.h>
47 #include <sys/ioctl.h>
48 #include <sys/wait.h>
49
50 #if defined(__APPLE__)
51 typedef sig_t sighandler_t;
52 #if !defined(environ)
53 #include <crt_externs.h>
54 #define environ (*_NSGetEnviron())
55 #endif
56 #endif /* __APPLE__ */
57
58 #if defined(__FreeBSD__) || defined(__OpenBSD__)
59 extern char **environ;
60 typedef sig_t sighandler_t;
61 #endif
62
63 #endif
64
65 #if !defined(_WIN32)
66 /* enable the os.Worker API. IT relies on POSIX threads */
67 #define USE_WORKER
68 #endif
69
70 #ifdef USE_WORKER
71 #include <pthread.h>
72 #include <stdatomic.h>
73 #endif
74
75 #include "cutils.h"
76 #include "list.h"
77 #include "quickjs-libc.h"
78
79 /* TODO:
80 - add socket calls
81 */
82
83 typedef struct {
84 struct list_head link;
85 int fd;
86 JSValue rw_func[2];
87 } JSOSRWHandler;
88
89 typedef struct {
90 struct list_head link;
91 int sig_num;
92 JSValue func;
93 } JSOSSignalHandler;
94
95 typedef struct {
96 struct list_head link;
97 BOOL has_object;
98 int64_t timeout;
99 JSValue func;
100 } JSOSTimer;
101
102 typedef struct {
103 struct list_head link;
104 uint8_t *data;
105 size_t data_len;
106 /* list of SharedArrayBuffers, necessary to free the message */
107 uint8_t **sab_tab;
108 size_t sab_tab_len;
109 } JSWorkerMessage;
110
111 typedef struct {
112 int ref_count;
113 #ifdef USE_WORKER
114 pthread_mutex_t mutex;
115 #endif
116 struct list_head msg_queue; /* list of JSWorkerMessage.link */
117 int read_fd;
118 int write_fd;
119 } JSWorkerMessagePipe;
120
121 typedef struct {
122 struct list_head link;
123 JSWorkerMessagePipe *recv_pipe;
124 JSValue on_message_func;
125 } JSWorkerMessageHandler;
126
127 typedef struct JSThreadState {
128 struct list_head os_rw_handlers; /* list of JSOSRWHandler.link */
129 struct list_head os_signal_handlers; /* list JSOSSignalHandler.link */
130 struct list_head os_timers; /* list of JSOSTimer.link */
131 struct list_head port_list; /* list of JSWorkerMessageHandler.link */
132 int eval_script_recurse; /* only used in the main thread */
133 /* not used in the main thread */
134 JSWorkerMessagePipe *recv_pipe, *send_pipe;
135 } JSThreadState;
136
137 static uint64_t os_pending_signals;
138 static int (*os_poll_func)(JSContext *ctx);
139
140 static void js_std_dbuf_init(JSContext *ctx, DynBuf *s)
141 {
142 dbuf_init2(s, JS_GetRuntime(ctx), (DynBufReallocFunc *)js_realloc_rt);
143 }
144
145 static BOOL my_isdigit(int c)
146 {
147 return (c >= '0' && c <= '9');
148 }
149
150 static JSValue js_printf_internal(JSContext *ctx,
151 int argc, JSValueConst *argv, FILE *fp)
152 {
153 char fmtbuf[32];
154 uint8_t cbuf[UTF8_CHAR_LEN_MAX+1];
155 JSValue res;
156 DynBuf dbuf;
157 const char *fmt_str;
158 const uint8_t *fmt, *fmt_end;
159 const uint8_t *p;
160 char *q;
161 int i, c, len, mod;
162 size_t fmt_len;
163 int32_t int32_arg;
164 int64_t int64_arg;
165 double double_arg;
166 const char *string_arg;
167 /* Use indirect call to dbuf_printf to prevent gcc warning */
168 int (*dbuf_printf_fun)(DynBuf *s, const char *fmt, ...) = (void*)dbuf_printf;
169
170 js_std_dbuf_init(ctx, &dbuf);
171
172 if (argc > 0) {
173 fmt_str = JS_ToCStringLen(ctx, &fmt_len, argv[0]);
174 if (!fmt_str)
175 goto fail;
176
177 i = 1;
178 fmt = (const uint8_t *)fmt_str;
179 fmt_end = fmt + fmt_len;
180 while (fmt < fmt_end) {
181 for (p = fmt; fmt < fmt_end && *fmt != '%'; fmt++)
182 continue;
183 dbuf_put(&dbuf, p, fmt - p);
184 if (fmt >= fmt_end)
185 break;
186 q = fmtbuf;
187 *q++ = *fmt++; /* copy '%' */
188
189 /* flags */
190 for(;;) {
191 c = *fmt;
192 if (c == '0' || c == '#' || c == '+' || c == '-' || c == ' ' ||
193 c == '\'') {
194 if (q >= fmtbuf + sizeof(fmtbuf) - 1)
195 goto invalid;
196 *q++ = c;
197 fmt++;
198 } else {
199 break;
200 }
201 }
202 /* width */
203 if (*fmt == '*') {
204 if (i >= argc)
205 goto missing;
206 if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
207 goto fail;
208 q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg);
209 fmt++;
210 } else {
211 while (my_isdigit(*fmt)) {
212 if (q >= fmtbuf + sizeof(fmtbuf) - 1)
213 goto invalid;
214 *q++ = *fmt++;
215 }
216 }
217 if (*fmt == '.') {
218 if (q >= fmtbuf + sizeof(fmtbuf) - 1)
219 goto invalid;
220 *q++ = *fmt++;
221 if (*fmt == '*') {
222 if (i >= argc)
223 goto missing;
224 if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
225 goto fail;
226 q += snprintf(q, fmtbuf + sizeof(fmtbuf) - q, "%d", int32_arg);
227 fmt++;
228 } else {
229 while (my_isdigit(*fmt)) {
230 if (q >= fmtbuf + sizeof(fmtbuf) - 1)
231 goto invalid;
232 *q++ = *fmt++;
233 }
234 }
235 }
236
237 /* we only support the "l" modifier for 64 bit numbers */
238 mod = ' ';
239 if (*fmt == 'l') {
240 mod = *fmt++;
241 }
242
243 /* type */
244 c = *fmt++;
245 if (q >= fmtbuf + sizeof(fmtbuf) - 1)
246 goto invalid;
247 *q++ = c;
248 *q = '\0';
249
250 switch (c) {
251 case 'c':
252 if (i >= argc)
253 goto missing;
254 if (JS_IsString(argv[i])) {
255 string_arg = JS_ToCString(ctx, argv[i++]);
256 if (!string_arg)
257 goto fail;
258 int32_arg = unicode_from_utf8((uint8_t *)string_arg, UTF8_CHAR_LEN_MAX, &p);
259 JS_FreeCString(ctx, string_arg);
260 } else {
261 if (JS_ToInt32(ctx, &int32_arg, argv[i++]))
262 goto fail;
263 }
264 /* handle utf-8 encoding explicitly */
265 if ((unsigned)int32_arg > 0x10FFFF)
266 int32_arg = 0xFFFD;
267 /* ignore conversion flags, width and precision */
268 len = unicode_to_utf8(cbuf, int32_arg);
269 dbuf_put(&dbuf, cbuf, len);
270 break;
271
272 case 'd':
273 case 'i':
274 case 'o':
275 case 'u':
276 case 'x':
277 case 'X':
278 if (i >= argc)
279 goto missing;
280 if (JS_ToInt64Ext(ctx, &int64_arg, argv[i++]))
281 goto fail;
282 if (mod == 'l') {
283 /* 64 bit number */
284 #if defined(_WIN32)
285 if (q >= fmtbuf + sizeof(fmtbuf) - 3)
286 goto invalid;
287 q[2] = q[-1];
288 q[-1] = 'I';
289 q[0] = '6';
290 q[1] = '4';
291 q[3] = '\0';
292 dbuf_printf_fun(&dbuf, fmtbuf, (int64_t)int64_arg);
293 #else
294 if (q >= fmtbuf + sizeof(fmtbuf) - 2)
295 goto invalid;
296 q[1] = q[-1];
297 q[-1] = q[0] = 'l';
298 q[2] = '\0';
299 dbuf_printf_fun(&dbuf, fmtbuf, (long long)int64_arg);
300 #endif
301 } else {
302 dbuf_printf_fun(&dbuf, fmtbuf, (int)int64_arg);
303 }
304 break;
305
306 case 's':
307 if (i >= argc)
308 goto missing;
309 /* XXX: handle strings containing null characters */
310 string_arg = JS_ToCString(ctx, argv[i++]);
311 if (!string_arg)
312 goto fail;
313 dbuf_printf_fun(&dbuf, fmtbuf, string_arg);
314 JS_FreeCString(ctx, string_arg);
315 break;
316
317 case 'e':
318 case 'f':
319 case 'g':
320 case 'a':
321 case 'E':
322 case 'F':
323 case 'G':
324 case 'A':
325 if (i >= argc)
326 goto missing;
327 if (JS_ToFloat64(ctx, &double_arg, argv[i++]))
328 goto fail;
329 dbuf_printf_fun(&dbuf, fmtbuf, double_arg);
330 break;
331
332 case '%':
333 dbuf_putc(&dbuf, '%');
334 break;
335
336 default:
337 /* XXX: should support an extension mechanism */
338 invalid:
339 JS_ThrowTypeError(ctx, "invalid conversion specifier in format string");
340 goto fail;
341 missing:
342 JS_ThrowReferenceError(ctx, "missing argument for conversion specifier");
343 goto fail;
344 }
345 }
346 JS_FreeCString(ctx, fmt_str);
347 }
348 if (dbuf.error) {
349 res = JS_ThrowOutOfMemory(ctx);
350 } else {
351 if (fp) {
352 len = fwrite(dbuf.buf, 1, dbuf.size, fp);
353 res = JS_NewInt32(ctx, len);
354 } else {
355 res = JS_NewStringLen(ctx, (char *)dbuf.buf, dbuf.size);
356 }
357 }
358 dbuf_free(&dbuf);
359 return res;
360
361 fail:
362 dbuf_free(&dbuf);
363 return JS_EXCEPTION;
364 }
365
366 uint8_t *js_load_file(JSContext *ctx, size_t *pbuf_len, const char *filename)
367 {
368 FILE *f;
369 uint8_t *buf;
370 size_t buf_len;
371 long lret;
372
373 f = fopen(filename, "rb");
374 if (!f)
375 return NULL;
376 if (fseek(f, 0, SEEK_END) < 0)
377 goto fail;
378 lret = ftell(f);
379 if (lret < 0)
380 goto fail;
381 /* XXX: on Linux, ftell() return LONG_MAX for directories */
382 if (lret == LONG_MAX) {
383 errno = EISDIR;
384 goto fail;
385 }
386 buf_len = lret;
387 if (fseek(f, 0, SEEK_SET) < 0)
388 goto fail;
389 if (ctx)
390 buf = js_malloc(ctx, buf_len + 1);
391 else
392 buf = malloc(buf_len + 1);
393 if (!buf)
394 goto fail;
395 if (fread(buf, 1, buf_len, f) != buf_len) {
396 errno = EIO;
397 if (ctx)
398 js_free(ctx, buf);
399 else
400 free(buf);
401 fail:
402 fclose(f);
403 return NULL;
404 }
405 buf[buf_len] = '\0';
406 fclose(f);
407 *pbuf_len = buf_len;
408 return buf;
409 }
410
411 /* load and evaluate a file */
412 static JSValue js_loadScript(JSContext *ctx, JSValueConst this_val,
413 int argc, JSValueConst *argv)
414 {
415 uint8_t *buf;
416 const char *filename;
417 JSValue ret;
418 size_t buf_len;
419
420 filename = JS_ToCString(ctx, argv[0]);
421 if (!filename)
422 return JS_EXCEPTION;
423 buf = js_load_file(ctx, &buf_len, filename);
424 if (!buf) {
425 JS_ThrowReferenceError(ctx, "could not load '%s'", filename);
426 JS_FreeCString(ctx, filename);
427 return JS_EXCEPTION;
428 }
429 ret = JS_Eval(ctx, (char *)buf, buf_len, filename,
430 JS_EVAL_TYPE_GLOBAL);
431 js_free(ctx, buf);
432 JS_FreeCString(ctx, filename);
433 return ret;
434 }
435
436 /* load a file as a UTF-8 encoded string */
437 static JSValue js_std_loadFile(JSContext *ctx, JSValueConst this_val,
438 int argc, JSValueConst *argv)
439 {
440 uint8_t *buf;
441 const char *filename;
442 JSValue ret;
443 size_t buf_len;
444
445 filename = JS_ToCString(ctx, argv[0]);
446 if (!filename)
447 return JS_EXCEPTION;
448 buf = js_load_file(ctx, &buf_len, filename);
449 JS_FreeCString(ctx, filename);
450 if (!buf)
451 return JS_NULL;
452 ret = JS_NewStringLen(ctx, (char *)buf, buf_len);
453 js_free(ctx, buf);
454 return ret;
455 }
456
457 typedef JSModuleDef *(JSInitModuleFunc)(JSContext *ctx,
458 const char *module_name);
459
460
461 #if defined(_WIN32)
462 static JSModuleDef *js_module_loader_so(JSContext *ctx,
463 const char *module_name)
464 {
465 JS_ThrowReferenceError(ctx, "shared library modules are not supported yet");
466 return NULL;
467 }
468 #else
469 static JSModuleDef *js_module_loader_so(JSContext *ctx,
470 const char *module_name)
471 {
472 JSModuleDef *m;
473 void *hd;
474 JSInitModuleFunc *init;
475 char *filename;
476
477 if (!strchr(module_name, '/')) {
478 /* must add a '/' so that the DLL is not searched in the
479 system library paths */
480 filename = js_malloc(ctx, strlen(module_name) + 2 + 1);
481 if (!filename)
482 return NULL;
483 strcpy(filename, "./");
484 strcpy(filename + 2, module_name);
485 } else {
486 filename = (char *)module_name;
487 }
488
489 /* C module */
490 hd = dlopen(filename, RTLD_NOW | RTLD_LOCAL);
491 if (filename != module_name)
492 js_free(ctx, filename);
493 if (!hd) {
494 JS_ThrowReferenceError(ctx, "could not load module filename '%s' as shared library",
495 module_name);
496 goto fail;
497 }
498
499 init = dlsym(hd, "js_init_module");
500 if (!init) {
501 JS_ThrowReferenceError(ctx, "could not load module filename '%s': js_init_module not found",
502 module_name);
503 goto fail;
504 }
505
506 m = init(ctx, module_name);
507 if (!m) {
508 JS_ThrowReferenceError(ctx, "could not load module filename '%s': initialization error",
509 module_name);
510 fail:
511 if (hd)
512 dlclose(hd);
513 return NULL;
514 }
515 return m;
516 }
517 #endif /* !_WIN32 */
518
519 int js_module_set_import_meta(JSContext *ctx, JSValueConst func_val,
520 JS_BOOL use_realpath, JS_BOOL is_main)
521 {
522 JSModuleDef *m;
523 char buf[PATH_MAX + 16];
524 JSValue meta_obj;
525 JSAtom module_name_atom;
526 const char *module_name;
527
528 assert(JS_VALUE_GET_TAG(func_val) == JS_TAG_MODULE);
529 m = JS_VALUE_GET_PTR(func_val);
530
531 module_name_atom = JS_GetModuleName(ctx, m);
532 module_name = JS_AtomToCString(ctx, module_name_atom);
533 JS_FreeAtom(ctx, module_name_atom);
534 if (!module_name)
535 return -1;
536 if (!strchr(module_name, ':')) {
537 strcpy(buf, "file://");
538 #if !defined(_WIN32)
539 /* realpath() cannot be used with modules compiled with qjsc
540 because the corresponding module source code is not
541 necessarily present */
542 if (use_realpath) {
543 char *res = realpath(module_name, buf + strlen(buf));
544 if (!res) {
545 JS_ThrowTypeError(ctx, "realpath failure");
546 JS_FreeCString(ctx, module_name);
547 return -1;
548 }
549 } else
550 #endif
551 {
552 pstrcat(buf, sizeof(buf), module_name);
553 }
554 } else {
555 pstrcpy(buf, sizeof(buf), module_name);
556 }
557 JS_FreeCString(ctx, module_name);
558
559 meta_obj = JS_GetImportMeta(ctx, m);
560 if (JS_IsException(meta_obj))
561 return -1;
562 JS_DefinePropertyValueStr(ctx, meta_obj, "url",
563 JS_NewString(ctx, buf),
564 JS_PROP_C_W_E);
565 JS_DefinePropertyValueStr(ctx, meta_obj, "main",
566 JS_NewBool(ctx, is_main),
567 JS_PROP_C_W_E);
568 JS_FreeValue(ctx, meta_obj);
569 return 0;
570 }
571
572 JSModuleDef *js_module_loader(JSContext *ctx,
573 const char *module_name, void *opaque)
574 {
575 JSModuleDef *m;
576
577 if (has_suffix(module_name, ".so")) {
578 m = js_module_loader_so(ctx, module_name);
579 } else {
580 size_t buf_len;
581 uint8_t *buf;
582 JSValue func_val;
583
584 buf = js_load_file(ctx, &buf_len, module_name);
585 if (!buf) {
586 JS_ThrowReferenceError(ctx, "could not load module filename '%s'",
587 module_name);
588 return NULL;
589 }
590
591 /* compile the module */
592 func_val = JS_Eval(ctx, (char *)buf, buf_len, module_name,
593 JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
594 js_free(ctx, buf);
595 if (JS_IsException(func_val))
596 return NULL;
597 /* XXX: could propagate the exception */
598 js_module_set_import_meta(ctx, func_val, TRUE, FALSE);
599 /* the module is already referenced, so we must free it */
600 m = JS_VALUE_GET_PTR(func_val);
601 JS_FreeValue(ctx, func_val);
602 }
603 return m;
604 }
605
606 static JSValue js_std_exit(JSContext *ctx, JSValueConst this_val,
607 int argc, JSValueConst *argv)
608 {
609 int status;
610 if (JS_ToInt32(ctx, &status, argv[0]))
611 status = -1;
612 exit(status);
613 return JS_UNDEFINED;
614 }
615
616 static JSValue js_std_getenv(JSContext *ctx, JSValueConst this_val,
617 int argc, JSValueConst *argv)
618 {
619 const char *name, *str;
620 name = JS_ToCString(ctx, argv[0]);
621 if (!name)
622 return JS_EXCEPTION;
623 str = getenv(name);
624 JS_FreeCString(ctx, name);
625 if (!str)
626 return JS_UNDEFINED;
627 else
628 return JS_NewString(ctx, str);
629 }
630
631 #if defined(_WIN32)
632 static void setenv(const char *name, const char *value, int overwrite)
633 {
634 char *str;
635 size_t name_len, value_len;
636 name_len = strlen(name);
637 value_len = strlen(value);
638 str = malloc(name_len + 1 + value_len + 1);
639 memcpy(str, name, name_len);
640 str[name_len] = '=';
641 memcpy(str + name_len + 1, value, value_len);
642 str[name_len + 1 + value_len] = '\0';
643 _putenv(str);
644 free(str);
645 }
646
647 static void unsetenv(const char *name)
648 {
649 setenv(name, "", TRUE);
650 }
651 #endif /* _WIN32 */
652
653 static JSValue js_std_setenv(JSContext *ctx, JSValueConst this_val,
654 int argc, JSValueConst *argv)
655 {
656 const char *name, *value;
657 name = JS_ToCString(ctx, argv[0]);
658 if (!name)
659 return JS_EXCEPTION;
660 value = JS_ToCString(ctx, argv[1]);
661 if (!value) {
662 JS_FreeCString(ctx, name);
663 return JS_EXCEPTION;
664 }
665 setenv(name, value, TRUE);
666 JS_FreeCString(ctx, name);
667 JS_FreeCString(ctx, value);
668 return JS_UNDEFINED;
669 }
670
671 static JSValue js_std_unsetenv(JSContext *ctx, JSValueConst this_val,
672 int argc, JSValueConst *argv)
673 {
674 const char *name;
675 name = JS_ToCString(ctx, argv[0]);
676 if (!name)
677 return JS_EXCEPTION;
678 unsetenv(name);
679 JS_FreeCString(ctx, name);
680 return JS_UNDEFINED;
681 }
682
683 /* return an object containing the list of the available environment
684 variables. */
685 static JSValue js_std_getenviron(JSContext *ctx, JSValueConst this_val,
686 int argc, JSValueConst *argv)
687 {
688 char **envp;
689 const char *name, *p, *value;
690 JSValue obj;
691 uint32_t idx;
692 size_t name_len;
693 JSAtom atom;
694 int ret;
695
696 obj = JS_NewObject(ctx);
697 if (JS_IsException(obj))
698 return JS_EXCEPTION;
699 envp = environ;
700 for(idx = 0; envp[idx] != NULL; idx++) {
701 name = envp[idx];
702 p = strchr(name, '=');
703 name_len = p - name;
704 if (!p)
705 continue;
706 value = p + 1;
707 atom = JS_NewAtomLen(ctx, name, name_len);
708 if (atom == JS_ATOM_NULL)
709 goto fail;
710 ret = JS_DefinePropertyValue(ctx, obj, atom, JS_NewString(ctx, value),
711 JS_PROP_C_W_E);
712 JS_FreeAtom(ctx, atom);
713 if (ret < 0)
714 goto fail;
715 }
716 return obj;
717 fail:
718 JS_FreeValue(ctx, obj);
719 return JS_EXCEPTION;
720 }
721
722 static JSValue js_std_gc(JSContext *ctx, JSValueConst this_val,
723 int argc, JSValueConst *argv)
724 {
725 JS_RunGC(JS_GetRuntime(ctx));
726 return JS_UNDEFINED;
727 }
728
729 static int interrupt_handler(JSRuntime *rt, void *opaque)
730 {
731 return (os_pending_signals >> SIGINT) & 1;
732 }
733
734 static int get_bool_option(JSContext *ctx, BOOL *pbool,
735 JSValueConst obj,
736 const char *option)
737 {
738 JSValue val;
739 val = JS_GetPropertyStr(ctx, obj, option);
740 if (JS_IsException(val))
741 return -1;
742 if (!JS_IsUndefined(val)) {
743 *pbool = JS_ToBool(ctx, val);
744 }
745 JS_FreeValue(ctx, val);
746 return 0;
747 }
748
749 static JSValue js_evalScript(JSContext *ctx, JSValueConst this_val,
750 int argc, JSValueConst *argv)
751 {
752 JSRuntime *rt = JS_GetRuntime(ctx);
753 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
754 const char *str;
755 size_t len;
756 JSValue ret;
757 JSValueConst options_obj;
758 BOOL backtrace_barrier = FALSE;
759 BOOL is_async = FALSE;
760 int flags;
761
762 if (argc >= 2) {
763 options_obj = argv[1];
764 if (get_bool_option(ctx, &backtrace_barrier, options_obj,
765 "backtrace_barrier"))
766 return JS_EXCEPTION;
767 if (get_bool_option(ctx, &is_async, options_obj,
768 "async"))
769 return JS_EXCEPTION;
770 }
771
772 str = JS_ToCStringLen(ctx, &len, argv[0]);
773 if (!str)
774 return JS_EXCEPTION;
775 if (!ts->recv_pipe && ++ts->eval_script_recurse == 1) {
776 /* install the interrupt handler */
777 JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL);
778 }
779 flags = JS_EVAL_TYPE_GLOBAL;
780 if (backtrace_barrier)
781 flags |= JS_EVAL_FLAG_BACKTRACE_BARRIER;
782 if (is_async)
783 flags |= JS_EVAL_FLAG_ASYNC;
784 ret = JS_Eval(ctx, str, len, "<evalScript>", flags);
785 JS_FreeCString(ctx, str);
786 if (!ts->recv_pipe && --ts->eval_script_recurse == 0) {
787 /* remove the interrupt handler */
788 JS_SetInterruptHandler(JS_GetRuntime(ctx), NULL, NULL);
789 os_pending_signals &= ~((uint64_t)1 << SIGINT);
790 /* convert the uncatchable "interrupted" error into a normal error
791 so that it can be caught by the REPL */
792 if (JS_IsException(ret))
793 JS_ResetUncatchableError(ctx);
794 }
795 return ret;
796 }
797
798 static JSClassID js_std_file_class_id;
799
800 typedef struct {
801 FILE *f;
802 BOOL close_in_finalizer;
803 BOOL is_popen;
804 } JSSTDFile;
805
806 static void js_std_file_finalizer(JSRuntime *rt, JSValue val)
807 {
808 JSSTDFile *s = JS_GetOpaque(val, js_std_file_class_id);
809 if (s) {
810 if (s->f && s->close_in_finalizer) {
811 if (s->is_popen)
812 pclose(s->f);
813 else
814 fclose(s->f);
815 }
816 js_free_rt(rt, s);
817 }
818 }
819
820 static ssize_t js_get_errno(ssize_t ret)
821 {
822 if (ret == -1)
823 ret = -errno;
824 return ret;
825 }
826
827 static JSValue js_std_strerror(JSContext *ctx, JSValueConst this_val,
828 int argc, JSValueConst *argv)
829 {
830 int err;
831 if (JS_ToInt32(ctx, &err, argv[0]))
832 return JS_EXCEPTION;
833 return JS_NewString(ctx, strerror(err));
834 }
835
836 static JSValue js_std_parseExtJSON(JSContext *ctx, JSValueConst this_val,
837 int argc, JSValueConst *argv)
838 {
839 JSValue obj;
840 const char *str;
841 size_t len;
842
843 str = JS_ToCStringLen(ctx, &len, argv[0]);
844 if (!str)
845 return JS_EXCEPTION;
846 obj = JS_ParseJSON2(ctx, str, len, "<input>", JS_PARSE_JSON_EXT);
847 JS_FreeCString(ctx, str);
848 return obj;
849 }
850
851 static JSValue js_new_std_file(JSContext *ctx, FILE *f,
852 BOOL close_in_finalizer,
853 BOOL is_popen)
854 {
855 JSSTDFile *s;
856 JSValue obj;
857 obj = JS_NewObjectClass(ctx, js_std_file_class_id);
858 if (JS_IsException(obj))
859 return obj;
860 s = js_mallocz(ctx, sizeof(*s));
861 if (!s) {
862 JS_FreeValue(ctx, obj);
863 return JS_EXCEPTION;
864 }
865 s->close_in_finalizer = close_in_finalizer;
866 s->is_popen = is_popen;
867 s->f = f;
868 JS_SetOpaque(obj, s);
869 return obj;
870 }
871
872 static void js_set_error_object(JSContext *ctx, JSValue obj, int err)
873 {
874 if (!JS_IsUndefined(obj)) {
875 JS_SetPropertyStr(ctx, obj, "errno", JS_NewInt32(ctx, err));
876 }
877 }
878
879 static JSValue js_std_open(JSContext *ctx, JSValueConst this_val,
880 int argc, JSValueConst *argv)
881 {
882 const char *filename, *mode = NULL;
883 FILE *f;
884 int err;
885
886 filename = JS_ToCString(ctx, argv[0]);
887 if (!filename)
888 goto fail;
889 mode = JS_ToCString(ctx, argv[1]);
890 if (!mode)
891 goto fail;
892 if (mode[strspn(mode, "rwa+b")] != '\0') {
893 JS_ThrowTypeError(ctx, "invalid file mode");
894 goto fail;
895 }
896
897 f = fopen(filename, mode);
898 if (!f)
899 err = errno;
900 else
901 err = 0;
902 if (argc >= 3)
903 js_set_error_object(ctx, argv[2], err);
904 JS_FreeCString(ctx, filename);
905 JS_FreeCString(ctx, mode);
906 if (!f)
907 return JS_NULL;
908 return js_new_std_file(ctx, f, TRUE, FALSE);
909 fail:
910 JS_FreeCString(ctx, filename);
911 JS_FreeCString(ctx, mode);
912 return JS_EXCEPTION;
913 }
914
915 static JSValue js_std_popen(JSContext *ctx, JSValueConst this_val,
916 int argc, JSValueConst *argv)
917 {
918 const char *filename, *mode = NULL;
919 FILE *f;
920 int err;
921
922 filename = JS_ToCString(ctx, argv[0]);
923 if (!filename)
924 goto fail;
925 mode = JS_ToCString(ctx, argv[1]);
926 if (!mode)
927 goto fail;
928 if (mode[strspn(mode, "rw")] != '\0') {
929 JS_ThrowTypeError(ctx, "invalid file mode");
930 goto fail;
931 }
932
933 f = popen(filename, mode);
934 if (!f)
935 err = errno;
936 else
937 err = 0;
938 if (argc >= 3)
939 js_set_error_object(ctx, argv[2], err);
940 JS_FreeCString(ctx, filename);
941 JS_FreeCString(ctx, mode);
942 if (!f)
943 return JS_NULL;
944 return js_new_std_file(ctx, f, TRUE, TRUE);
945 fail:
946 JS_FreeCString(ctx, filename);
947 JS_FreeCString(ctx, mode);
948 return JS_EXCEPTION;
949 }
950
951 static JSValue js_std_fdopen(JSContext *ctx, JSValueConst this_val,
952 int argc, JSValueConst *argv)
953 {
954 const char *mode;
955 FILE *f;
956 int fd, err;
957
958 if (JS_ToInt32(ctx, &fd, argv[0]))
959 return JS_EXCEPTION;
960 mode = JS_ToCString(ctx, argv[1]);
961 if (!mode)
962 goto fail;
963 if (mode[strspn(mode, "rwa+")] != '\0') {
964 JS_ThrowTypeError(ctx, "invalid file mode");
965 goto fail;
966 }
967
968 f = fdopen(fd, mode);
969 if (!f)
970 err = errno;
971 else
972 err = 0;
973 if (argc >= 3)
974 js_set_error_object(ctx, argv[2], err);
975 JS_FreeCString(ctx, mode);
976 if (!f)
977 return JS_NULL;
978 return js_new_std_file(ctx, f, TRUE, FALSE);
979 fail:
980 JS_FreeCString(ctx, mode);
981 return JS_EXCEPTION;
982 }
983
984 static JSValue js_std_tmpfile(JSContext *ctx, JSValueConst this_val,
985 int argc, JSValueConst *argv)
986 {
987 FILE *f;
988 f = tmpfile();
989 if (argc >= 1)
990 js_set_error_object(ctx, argv[0], f ? 0 : errno);
991 if (!f)
992 return JS_NULL;
993 return js_new_std_file(ctx, f, TRUE, FALSE);
994 }
995
996 static JSValue js_std_sprintf(JSContext *ctx, JSValueConst this_val,
997 int argc, JSValueConst *argv)
998 {
999 return js_printf_internal(ctx, argc, argv, NULL);
1000 }
1001
1002 static JSValue js_std_printf(JSContext *ctx, JSValueConst this_val,
1003 int argc, JSValueConst *argv)
1004 {
1005 return js_printf_internal(ctx, argc, argv, stdout);
1006 }
1007
1008 static FILE *js_std_file_get(JSContext *ctx, JSValueConst obj)
1009 {
1010 JSSTDFile *s = JS_GetOpaque2(ctx, obj, js_std_file_class_id);
1011 if (!s)
1012 return NULL;
1013 if (!s->f) {
1014 JS_ThrowTypeError(ctx, "invalid file handle");
1015 return NULL;
1016 }
1017 return s->f;
1018 }
1019
1020 static JSValue js_std_file_puts(JSContext *ctx, JSValueConst this_val,
1021 int argc, JSValueConst *argv, int magic)
1022 {
1023 FILE *f;
1024 int i;
1025 const char *str;
1026 size_t len;
1027
1028 if (magic == 0) {
1029 f = stdout;
1030 } else {
1031 f = js_std_file_get(ctx, this_val);
1032 if (!f)
1033 return JS_EXCEPTION;
1034 }
1035
1036 for(i = 0; i < argc; i++) {
1037 str = JS_ToCStringLen(ctx, &len, argv[i]);
1038 if (!str)
1039 return JS_EXCEPTION;
1040 fwrite(str, 1, len, f);
1041 JS_FreeCString(ctx, str);
1042 }
1043 return JS_UNDEFINED;
1044 }
1045
1046 static JSValue js_std_file_close(JSContext *ctx, JSValueConst this_val,
1047 int argc, JSValueConst *argv)
1048 {
1049 JSSTDFile *s = JS_GetOpaque2(ctx, this_val, js_std_file_class_id);
1050 int err;
1051 if (!s)
1052 return JS_EXCEPTION;
1053 if (!s->f)
1054 return JS_ThrowTypeError(ctx, "invalid file handle");
1055 if (s->is_popen)
1056 err = js_get_errno(pclose(s->f));
1057 else
1058 err = js_get_errno(fclose(s->f));
1059 s->f = NULL;
1060 return JS_NewInt32(ctx, err);
1061 }
1062
1063 static JSValue js_std_file_printf(JSContext *ctx, JSValueConst this_val,
1064 int argc, JSValueConst *argv)
1065 {
1066 FILE *f = js_std_file_get(ctx, this_val);
1067 if (!f)
1068 return JS_EXCEPTION;
1069 return js_printf_internal(ctx, argc, argv, f);
1070 }
1071
1072 static JSValue js_std_file_flush(JSContext *ctx, JSValueConst this_val,
1073 int argc, JSValueConst *argv)
1074 {
1075 FILE *f = js_std_file_get(ctx, this_val);
1076 if (!f)
1077 return JS_EXCEPTION;
1078 fflush(f);
1079 return JS_UNDEFINED;
1080 }
1081
1082 static JSValue js_std_file_tell(JSContext *ctx, JSValueConst this_val,
1083 int argc, JSValueConst *argv, int is_bigint)
1084 {
1085 FILE *f = js_std_file_get(ctx, this_val);
1086 int64_t pos;
1087 if (!f)
1088 return JS_EXCEPTION;
1089 #if defined(__linux__)
1090 pos = ftello(f);
1091 #else
1092 pos = ftell(f);
1093 #endif
1094 if (is_bigint)
1095 return JS_NewBigInt64(ctx, pos);
1096 else
1097 return JS_NewInt64(ctx, pos);
1098 }
1099
1100 static JSValue js_std_file_seek(JSContext *ctx, JSValueConst this_val,
1101 int argc, JSValueConst *argv)
1102 {
1103 FILE *f = js_std_file_get(ctx, this_val);
1104 int64_t pos;
1105 int whence, ret;
1106 if (!f)
1107 return JS_EXCEPTION;
1108 if (JS_ToInt64Ext(ctx, &pos, argv[0]))
1109 return JS_EXCEPTION;
1110 if (JS_ToInt32(ctx, &whence, argv[1]))
1111 return JS_EXCEPTION;
1112 #if defined(__linux__)
1113 ret = fseeko(f, pos, whence);
1114 #else
1115 ret = fseek(f, pos, whence);
1116 #endif
1117 if (ret < 0)
1118 ret = -errno;
1119 return JS_NewInt32(ctx, ret);
1120 }
1121
1122 static JSValue js_std_file_eof(JSContext *ctx, JSValueConst this_val,
1123 int argc, JSValueConst *argv)
1124 {
1125 FILE *f = js_std_file_get(ctx, this_val);
1126 if (!f)
1127 return JS_EXCEPTION;
1128 return JS_NewBool(ctx, feof(f));
1129 }
1130
1131 static JSValue js_std_file_error(JSContext *ctx, JSValueConst this_val,
1132 int argc, JSValueConst *argv)
1133 {
1134 FILE *f = js_std_file_get(ctx, this_val);
1135 if (!f)
1136 return JS_EXCEPTION;
1137 return JS_NewBool(ctx, ferror(f));
1138 }
1139
1140 static JSValue js_std_file_clearerr(JSContext *ctx, JSValueConst this_val,
1141 int argc, JSValueConst *argv)
1142 {
1143 FILE *f = js_std_file_get(ctx, this_val);
1144 if (!f)
1145 return JS_EXCEPTION;
1146 clearerr(f);
1147 return JS_UNDEFINED;
1148 }
1149
1150 static JSValue js_std_file_fileno(JSContext *ctx, JSValueConst this_val,
1151 int argc, JSValueConst *argv)
1152 {
1153 FILE *f = js_std_file_get(ctx, this_val);
1154 if (!f)
1155 return JS_EXCEPTION;
1156 return JS_NewInt32(ctx, fileno(f));
1157 }
1158
1159 static JSValue js_std_file_read_write(JSContext *ctx, JSValueConst this_val,
1160 int argc, JSValueConst *argv, int magic)
1161 {
1162 FILE *f = js_std_file_get(ctx, this_val);
1163 uint64_t pos, len;
1164 size_t size, ret;
1165 uint8_t *buf;
1166
1167 if (!f)
1168 return JS_EXCEPTION;
1169 if (JS_ToIndex(ctx, &pos, argv[1]))
1170 return JS_EXCEPTION;
1171 if (JS_ToIndex(ctx, &len, argv[2]))
1172 return JS_EXCEPTION;
1173 buf = JS_GetArrayBuffer(ctx, &size, argv[0]);
1174 if (!buf)
1175 return JS_EXCEPTION;
1176 if (pos + len > size)
1177 return JS_ThrowRangeError(ctx, "read/write array buffer overflow");
1178 if (magic)
1179 ret = fwrite(buf + pos, 1, len, f);
1180 else
1181 ret = fread(buf + pos, 1, len, f);
1182 return JS_NewInt64(ctx, ret);
1183 }
1184
1185 /* XXX: could use less memory and go faster */
1186 static JSValue js_std_file_getline(JSContext *ctx, JSValueConst this_val,
1187 int argc, JSValueConst *argv)
1188 {
1189 FILE *f = js_std_file_get(ctx, this_val);
1190 int c;
1191 DynBuf dbuf;
1192 JSValue obj;
1193
1194 if (!f)
1195 return JS_EXCEPTION;
1196
1197 js_std_dbuf_init(ctx, &dbuf);
1198 for(;;) {
1199 c = fgetc(f);
1200 if (c == EOF) {
1201 if (dbuf.size == 0) {
1202 /* EOF */
1203 dbuf_free(&dbuf);
1204 return JS_NULL;
1205 } else {
1206 break;
1207 }
1208 }
1209 if (c == '\n')
1210 break;
1211 if (dbuf_putc(&dbuf, c)) {
1212 dbuf_free(&dbuf);
1213 return JS_ThrowOutOfMemory(ctx);
1214 }
1215 }
1216 obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);
1217 dbuf_free(&dbuf);
1218 return obj;
1219 }
1220
1221 /* XXX: could use less memory and go faster */
1222 static JSValue js_std_file_readAsString(JSContext *ctx, JSValueConst this_val,
1223 int argc, JSValueConst *argv)
1224 {
1225 FILE *f = js_std_file_get(ctx, this_val);
1226 int c;
1227 DynBuf dbuf;
1228 JSValue obj;
1229 uint64_t max_size64;
1230 size_t max_size;
1231 JSValueConst max_size_val;
1232
1233 if (!f)
1234 return JS_EXCEPTION;
1235
1236 if (argc >= 1)
1237 max_size_val = argv[0];
1238 else
1239 max_size_val = JS_UNDEFINED;
1240 max_size = (size_t)-1;
1241 if (!JS_IsUndefined(max_size_val)) {
1242 if (JS_ToIndex(ctx, &max_size64, max_size_val))
1243 return JS_EXCEPTION;
1244 if (max_size64 < max_size)
1245 max_size = max_size64;
1246 }
1247
1248 js_std_dbuf_init(ctx, &dbuf);
1249 while (max_size != 0) {
1250 c = fgetc(f);
1251 if (c == EOF)
1252 break;
1253 if (dbuf_putc(&dbuf, c)) {
1254 dbuf_free(&dbuf);
1255 return JS_EXCEPTION;
1256 }
1257 max_size--;
1258 }
1259 obj = JS_NewStringLen(ctx, (const char *)dbuf.buf, dbuf.size);
1260 dbuf_free(&dbuf);
1261 return obj;
1262 }
1263
1264 static JSValue js_std_file_getByte(JSContext *ctx, JSValueConst this_val,
1265 int argc, JSValueConst *argv)
1266 {
1267 FILE *f = js_std_file_get(ctx, this_val);
1268 if (!f)
1269 return JS_EXCEPTION;
1270 return JS_NewInt32(ctx, fgetc(f));
1271 }
1272
1273 static JSValue js_std_file_putByte(JSContext *ctx, JSValueConst this_val,
1274 int argc, JSValueConst *argv)
1275 {
1276 FILE *f = js_std_file_get(ctx, this_val);
1277 int c;
1278 if (!f)
1279 return JS_EXCEPTION;
1280 if (JS_ToInt32(ctx, &c, argv[0]))
1281 return JS_EXCEPTION;
1282 c = fputc(c, f);
1283 return JS_NewInt32(ctx, c);
1284 }
1285
1286 /* urlGet */
1287
1288 #define URL_GET_PROGRAM "curl -s -i"
1289 #define URL_GET_BUF_SIZE 4096
1290
1291 static int http_get_header_line(FILE *f, char *buf, size_t buf_size,
1292 DynBuf *dbuf)
1293 {
1294 int c;
1295 char *p;
1296
1297 p = buf;
1298 for(;;) {
1299 c = fgetc(f);
1300 if (c < 0)
1301 return -1;
1302 if ((p - buf) < buf_size - 1)
1303 *p++ = c;
1304 if (dbuf)
1305 dbuf_putc(dbuf, c);
1306 if (c == '\n')
1307 break;
1308 }
1309 *p = '\0';
1310 return 0;
1311 }
1312
1313 static int http_get_status(const char *buf)
1314 {
1315 const char *p = buf;
1316 while (*p != ' ' && *p != '\0')
1317 p++;
1318 if (*p != ' ')
1319 return 0;
1320 while (*p == ' ')
1321 p++;
1322 return atoi(p);
1323 }
1324
1325 static JSValue js_std_urlGet(JSContext *ctx, JSValueConst this_val,
1326 int argc, JSValueConst *argv)
1327 {
1328 const char *url;
1329 DynBuf cmd_buf;
1330 DynBuf data_buf_s, *data_buf = &data_buf_s;
1331 DynBuf header_buf_s, *header_buf = &header_buf_s;
1332 char *buf;
1333 size_t i, len;
1334 int c, status;
1335 JSValue response = JS_UNDEFINED, ret_obj;
1336 JSValueConst options_obj;
1337 FILE *f;
1338 BOOL binary_flag, full_flag;
1339
1340 url = JS_ToCString(ctx, argv[0]);
1341 if (!url)
1342 return JS_EXCEPTION;
1343
1344 binary_flag = FALSE;
1345 full_flag = FALSE;
1346
1347 if (argc >= 2) {
1348 options_obj = argv[1];
1349
1350 if (get_bool_option(ctx, &binary_flag, options_obj, "binary"))
1351 goto fail_obj;
1352
1353 if (get_bool_option(ctx, &full_flag, options_obj, "full")) {
1354 fail_obj:
1355 JS_FreeCString(ctx, url);
1356 return JS_EXCEPTION;
1357 }
1358 }
1359
1360 js_std_dbuf_init(ctx, &cmd_buf);
1361 dbuf_printf(&cmd_buf, "%s ''", URL_GET_PROGRAM);
1362 len = strlen(url);
1363 for(i = 0; i < len; i++) {
1364 c = url[i];
1365 if (c == '\'' || c == '\\')
1366 dbuf_putc(&cmd_buf, '\\');
1367 dbuf_putc(&cmd_buf, c);
1368 }
1369 JS_FreeCString(ctx, url);
1370 dbuf_putstr(&cmd_buf, "''");
1371 dbuf_putc(&cmd_buf, '\0');
1372 if (dbuf_error(&cmd_buf)) {
1373 dbuf_free(&cmd_buf);
1374 return JS_EXCEPTION;
1375 }
1376 // printf("%s\n", (char *)cmd_buf.buf);
1377 f = popen((char *)cmd_buf.buf, "r");
1378 dbuf_free(&cmd_buf);
1379 if (!f) {
1380 return JS_ThrowTypeError(ctx, "could not start curl");
1381 }
1382
1383 js_std_dbuf_init(ctx, data_buf);
1384 js_std_dbuf_init(ctx, header_buf);
1385
1386 buf = js_malloc(ctx, URL_GET_BUF_SIZE);
1387 if (!buf)
1388 goto fail;
1389
1390 /* get the HTTP status */
1391 if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, NULL) < 0) {
1392 status = 0;
1393 goto bad_header;
1394 }
1395 status = http_get_status(buf);
1396 if (!full_flag && !(status >= 200 && status <= 299)) {
1397 goto bad_header;
1398 }
1399
1400 /* wait until there is an empty line */
1401 for(;;) {
1402 if (http_get_header_line(f, buf, URL_GET_BUF_SIZE, header_buf) < 0) {
1403 bad_header:
1404 response = JS_NULL;
1405 goto done;
1406 }
1407 if (!strcmp(buf, "\r\n"))
1408 break;
1409 }
1410 if (dbuf_error(header_buf))
1411 goto fail;
1412 header_buf->size -= 2; /* remove the trailing CRLF */
1413
1414 /* download the data */
1415 for(;;) {
1416 len = fread(buf, 1, URL_GET_BUF_SIZE, f);
1417 if (len == 0)
1418 break;
1419 dbuf_put(data_buf, (uint8_t *)buf, len);
1420 }
1421 if (dbuf_error(data_buf))
1422 goto fail;
1423 if (binary_flag) {
1424 response = JS_NewArrayBufferCopy(ctx,
1425 data_buf->buf, data_buf->size);
1426 } else {
1427 response = JS_NewStringLen(ctx, (char *)data_buf->buf, data_buf->size);
1428 }
1429 if (JS_IsException(response))
1430 goto fail;
1431 done:
1432 js_free(ctx, buf);
1433 buf = NULL;
1434 pclose(f);
1435 f = NULL;
1436 dbuf_free(data_buf);
1437 data_buf = NULL;
1438
1439 if (full_flag) {
1440 ret_obj = JS_NewObject(ctx);
1441 if (JS_IsException(ret_obj))
1442 goto fail;
1443 JS_DefinePropertyValueStr(ctx, ret_obj, "response",
1444 response,
1445 JS_PROP_C_W_E);
1446 if (!JS_IsNull(response)) {
1447 JS_DefinePropertyValueStr(ctx, ret_obj, "responseHeaders",
1448 JS_NewStringLen(ctx, (char *)header_buf->buf,
1449 header_buf->size),
1450 JS_PROP_C_W_E);
1451 JS_DefinePropertyValueStr(ctx, ret_obj, "status",
1452 JS_NewInt32(ctx, status),
1453 JS_PROP_C_W_E);
1454 }
1455 } else {
1456 ret_obj = response;
1457 }
1458 dbuf_free(header_buf);
1459 return ret_obj;
1460 fail:
1461 if (f)
1462 pclose(f);
1463 js_free(ctx, buf);
1464 if (data_buf)
1465 dbuf_free(data_buf);
1466 if (header_buf)
1467 dbuf_free(header_buf);
1468 JS_FreeValue(ctx, response);
1469 return JS_EXCEPTION;
1470 }
1471
1472 static JSClassDef js_std_file_class = {
1473 "FILE",
1474 .finalizer = js_std_file_finalizer,
1475 };
1476
1477 static const JSCFunctionListEntry js_std_error_props[] = {
1478 /* various errno values */
1479 #define DEF(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )
1480 DEF(EINVAL),
1481 DEF(EIO),
1482 DEF(EACCES),
1483 DEF(EEXIST),
1484 DEF(ENOSPC),
1485 DEF(ENOSYS),
1486 DEF(EBUSY),
1487 DEF(ENOENT),
1488 DEF(EPERM),
1489 DEF(EPIPE),
1490 DEF(EBADF),
1491 #undef DEF
1492 };
1493
1494 static const JSCFunctionListEntry js_std_funcs[] = {
1495 JS_CFUNC_DEF("exit", 1, js_std_exit ),
1496 JS_CFUNC_DEF("gc", 0, js_std_gc ),
1497 JS_CFUNC_DEF("evalScript", 1, js_evalScript ),
1498 JS_CFUNC_DEF("loadScript", 1, js_loadScript ),
1499 JS_CFUNC_DEF("getenv", 1, js_std_getenv ),
1500 JS_CFUNC_DEF("setenv", 1, js_std_setenv ),
1501 JS_CFUNC_DEF("unsetenv", 1, js_std_unsetenv ),
1502 JS_CFUNC_DEF("getenviron", 1, js_std_getenviron ),
1503 JS_CFUNC_DEF("urlGet", 1, js_std_urlGet ),
1504 JS_CFUNC_DEF("loadFile", 1, js_std_loadFile ),
1505 JS_CFUNC_DEF("strerror", 1, js_std_strerror ),
1506 JS_CFUNC_DEF("parseExtJSON", 1, js_std_parseExtJSON ),
1507
1508 /* FILE I/O */
1509 JS_CFUNC_DEF("open", 2, js_std_open ),
1510 JS_CFUNC_DEF("popen", 2, js_std_popen ),
1511 JS_CFUNC_DEF("fdopen", 2, js_std_fdopen ),
1512 JS_CFUNC_DEF("tmpfile", 0, js_std_tmpfile ),
1513 JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 0 ),
1514 JS_CFUNC_DEF("printf", 1, js_std_printf ),
1515 JS_CFUNC_DEF("sprintf", 1, js_std_sprintf ),
1516 JS_PROP_INT32_DEF("SEEK_SET", SEEK_SET, JS_PROP_CONFIGURABLE ),
1517 JS_PROP_INT32_DEF("SEEK_CUR", SEEK_CUR, JS_PROP_CONFIGURABLE ),
1518 JS_PROP_INT32_DEF("SEEK_END", SEEK_END, JS_PROP_CONFIGURABLE ),
1519 JS_OBJECT_DEF("Error", js_std_error_props, countof(js_std_error_props), JS_PROP_CONFIGURABLE),
1520 };
1521
1522 static const JSCFunctionListEntry js_std_file_proto_funcs[] = {
1523 JS_CFUNC_DEF("close", 0, js_std_file_close ),
1524 JS_CFUNC_MAGIC_DEF("puts", 1, js_std_file_puts, 1 ),
1525 JS_CFUNC_DEF("printf", 1, js_std_file_printf ),
1526 JS_CFUNC_DEF("flush", 0, js_std_file_flush ),
1527 JS_CFUNC_MAGIC_DEF("tell", 0, js_std_file_tell, 0 ),
1528 JS_CFUNC_MAGIC_DEF("tello", 0, js_std_file_tell, 1 ),
1529 JS_CFUNC_DEF("seek", 2, js_std_file_seek ),
1530 JS_CFUNC_DEF("eof", 0, js_std_file_eof ),
1531 JS_CFUNC_DEF("fileno", 0, js_std_file_fileno ),
1532 JS_CFUNC_DEF("error", 0, js_std_file_error ),
1533 JS_CFUNC_DEF("clearerr", 0, js_std_file_clearerr ),
1534 JS_CFUNC_MAGIC_DEF("read", 3, js_std_file_read_write, 0 ),
1535 JS_CFUNC_MAGIC_DEF("write", 3, js_std_file_read_write, 1 ),
1536 JS_CFUNC_DEF("getline", 0, js_std_file_getline ),
1537 JS_CFUNC_DEF("readAsString", 0, js_std_file_readAsString ),
1538 JS_CFUNC_DEF("getByte", 0, js_std_file_getByte ),
1539 JS_CFUNC_DEF("putByte", 1, js_std_file_putByte ),
1540 /* setvbuf, ... */
1541 };
1542
1543 static int js_std_init(JSContext *ctx, JSModuleDef *m)
1544 {
1545 JSValue proto;
1546
1547 /* FILE class */
1548 /* the class ID is created once */
1549 JS_NewClassID(&js_std_file_class_id);
1550 /* the class is created once per runtime */
1551 JS_NewClass(JS_GetRuntime(ctx), js_std_file_class_id, &js_std_file_class);
1552 proto = JS_NewObject(ctx);
1553 JS_SetPropertyFunctionList(ctx, proto, js_std_file_proto_funcs,
1554 countof(js_std_file_proto_funcs));
1555 JS_SetClassProto(ctx, js_std_file_class_id, proto);
1556
1557 JS_SetModuleExportList(ctx, m, js_std_funcs,
1558 countof(js_std_funcs));
1559 JS_SetModuleExport(ctx, m, "in", js_new_std_file(ctx, stdin, FALSE, FALSE));
1560 JS_SetModuleExport(ctx, m, "out", js_new_std_file(ctx, stdout, FALSE, FALSE));
1561 JS_SetModuleExport(ctx, m, "err", js_new_std_file(ctx, stderr, FALSE, FALSE));
1562 return 0;
1563 }
1564
1565 JSModuleDef *js_init_module_std(JSContext *ctx, const char *module_name)
1566 {
1567 JSModuleDef *m;
1568 m = JS_NewCModule(ctx, module_name, js_std_init);
1569 if (!m)
1570 return NULL;
1571 JS_AddModuleExportList(ctx, m, js_std_funcs, countof(js_std_funcs));
1572 JS_AddModuleExport(ctx, m, "in");
1573 JS_AddModuleExport(ctx, m, "out");
1574 JS_AddModuleExport(ctx, m, "err");
1575 return m;
1576 }
1577
1578 /**********************************************************/
1579 /* 'os' object */
1580
1581 static JSValue js_os_open(JSContext *ctx, JSValueConst this_val,
1582 int argc, JSValueConst *argv)
1583 {
1584 const char *filename;
1585 int flags, mode, ret;
1586
1587 filename = JS_ToCString(ctx, argv[0]);
1588 if (!filename)
1589 return JS_EXCEPTION;
1590 if (JS_ToInt32(ctx, &flags, argv[1]))
1591 goto fail;
1592 if (argc >= 3 && !JS_IsUndefined(argv[2])) {
1593 if (JS_ToInt32(ctx, &mode, argv[2])) {
1594 fail:
1595 JS_FreeCString(ctx, filename);
1596 return JS_EXCEPTION;
1597 }
1598 } else {
1599 mode = 0666;
1600 }
1601 #if defined(_WIN32)
1602 /* force binary mode by default */
1603 if (!(flags & O_TEXT))
1604 flags |= O_BINARY;
1605 #endif
1606 ret = js_get_errno(open(filename, flags, mode));
1607 JS_FreeCString(ctx, filename);
1608 return JS_NewInt32(ctx, ret);
1609 }
1610
1611 static JSValue js_os_close(JSContext *ctx, JSValueConst this_val,
1612 int argc, JSValueConst *argv)
1613 {
1614 int fd, ret;
1615 if (JS_ToInt32(ctx, &fd, argv[0]))
1616 return JS_EXCEPTION;
1617 ret = js_get_errno(close(fd));
1618 return JS_NewInt32(ctx, ret);
1619 }
1620
1621 static JSValue js_os_seek(JSContext *ctx, JSValueConst this_val,
1622 int argc, JSValueConst *argv)
1623 {
1624 int fd, whence;
1625 int64_t pos, ret;
1626 BOOL is_bigint;
1627
1628 if (JS_ToInt32(ctx, &fd, argv[0]))
1629 return JS_EXCEPTION;
1630 is_bigint = JS_IsBigInt(ctx, argv[1]);
1631 if (JS_ToInt64Ext(ctx, &pos, argv[1]))
1632 return JS_EXCEPTION;
1633 if (JS_ToInt32(ctx, &whence, argv[2]))
1634 return JS_EXCEPTION;
1635 ret = lseek(fd, pos, whence);
1636 if (ret == -1)
1637 ret = -errno;
1638 if (is_bigint)
1639 return JS_NewBigInt64(ctx, ret);
1640 else
1641 return JS_NewInt64(ctx, ret);
1642 }
1643
1644 static JSValue js_os_read_write(JSContext *ctx, JSValueConst this_val,
1645 int argc, JSValueConst *argv, int magic)
1646 {
1647 int fd;
1648 uint64_t pos, len;
1649 size_t size;
1650 ssize_t ret;
1651 uint8_t *buf;
1652
1653 if (JS_ToInt32(ctx, &fd, argv[0]))
1654 return JS_EXCEPTION;
1655 if (JS_ToIndex(ctx, &pos, argv[2]))
1656 return JS_EXCEPTION;
1657 if (JS_ToIndex(ctx, &len, argv[3]))
1658 return JS_EXCEPTION;
1659 buf = JS_GetArrayBuffer(ctx, &size, argv[1]);
1660 if (!buf)
1661 return JS_EXCEPTION;
1662 if (pos + len > size)
1663 return JS_ThrowRangeError(ctx, "read/write array buffer overflow");
1664 if (magic)
1665 ret = js_get_errno(write(fd, buf + pos, len));
1666 else
1667 ret = js_get_errno(read(fd, buf + pos, len));
1668 return JS_NewInt64(ctx, ret);
1669 }
1670
1671 static JSValue js_os_isatty(JSContext *ctx, JSValueConst this_val,
1672 int argc, JSValueConst *argv)
1673 {
1674 int fd;
1675 if (JS_ToInt32(ctx, &fd, argv[0]))
1676 return JS_EXCEPTION;
1677 return JS_NewBool(ctx, (isatty(fd) != 0));
1678 }
1679
1680 #if defined(_WIN32)
1681 static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,
1682 int argc, JSValueConst *argv)
1683 {
1684 int fd;
1685 HANDLE handle;
1686 CONSOLE_SCREEN_BUFFER_INFO info;
1687 JSValue obj;
1688
1689 if (JS_ToInt32(ctx, &fd, argv[0]))
1690 return JS_EXCEPTION;
1691 handle = (HANDLE)_get_osfhandle(fd);
1692
1693 if (!GetConsoleScreenBufferInfo(handle, &info))
1694 return JS_NULL;
1695 obj = JS_NewArray(ctx);
1696 if (JS_IsException(obj))
1697 return obj;
1698 JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, info.dwSize.X), JS_PROP_C_W_E);
1699 JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, info.dwSize.Y), JS_PROP_C_W_E);
1700 return obj;
1701 }
1702
1703 /* Windows 10 built-in VT100 emulation */
1704 #define __ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
1705 #define __ENABLE_VIRTUAL_TERMINAL_INPUT 0x0200
1706
1707 static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,
1708 int argc, JSValueConst *argv)
1709 {
1710 int fd;
1711 HANDLE handle;
1712
1713 if (JS_ToInt32(ctx, &fd, argv[0]))
1714 return JS_EXCEPTION;
1715 handle = (HANDLE)_get_osfhandle(fd);
1716 SetConsoleMode(handle, ENABLE_WINDOW_INPUT | __ENABLE_VIRTUAL_TERMINAL_INPUT);
1717 _setmode(fd, _O_BINARY);
1718 if (fd == 0) {
1719 handle = (HANDLE)_get_osfhandle(1); /* corresponding output */
1720 SetConsoleMode(handle, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT | __ENABLE_VIRTUAL_TERMINAL_PROCESSING);
1721 }
1722 return JS_UNDEFINED;
1723 }
1724 #else
1725 static JSValue js_os_ttyGetWinSize(JSContext *ctx, JSValueConst this_val,
1726 int argc, JSValueConst *argv)
1727 {
1728 int fd;
1729 struct winsize ws;
1730 JSValue obj;
1731
1732 if (JS_ToInt32(ctx, &fd, argv[0]))
1733 return JS_EXCEPTION;
1734 if (ioctl(fd, TIOCGWINSZ, &ws) == 0 &&
1735 ws.ws_col >= 4 && ws.ws_row >= 4) {
1736 obj = JS_NewArray(ctx);
1737 if (JS_IsException(obj))
1738 return obj;
1739 JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ws.ws_col), JS_PROP_C_W_E);
1740 JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, ws.ws_row), JS_PROP_C_W_E);
1741 return obj;
1742 } else {
1743 return JS_NULL;
1744 }
1745 }
1746
1747 static struct termios oldtty;
1748
1749 static void term_exit(void)
1750 {
1751 tcsetattr(0, TCSANOW, &oldtty);
1752 }
1753
1754 /* XXX: should add a way to go back to normal mode */
1755 static JSValue js_os_ttySetRaw(JSContext *ctx, JSValueConst this_val,
1756 int argc, JSValueConst *argv)
1757 {
1758 struct termios tty;
1759 int fd;
1760
1761 if (JS_ToInt32(ctx, &fd, argv[0]))
1762 return JS_EXCEPTION;
1763
1764 memset(&tty, 0, sizeof(tty));
1765 tcgetattr(fd, &tty);
1766 oldtty = tty;
1767
1768 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1769 |INLCR|IGNCR|ICRNL|IXON);
1770 tty.c_oflag |= OPOST;
1771 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1772 tty.c_cflag &= ~(CSIZE|PARENB);
1773 tty.c_cflag |= CS8;
1774 tty.c_cc[VMIN] = 1;
1775 tty.c_cc[VTIME] = 0;
1776
1777 tcsetattr(fd, TCSANOW, &tty);
1778
1779 atexit(term_exit);
1780 return JS_UNDEFINED;
1781 }
1782
1783 #endif /* !_WIN32 */
1784
1785 static JSValue js_os_remove(JSContext *ctx, JSValueConst this_val,
1786 int argc, JSValueConst *argv)
1787 {
1788 const char *filename;
1789 int ret;
1790
1791 filename = JS_ToCString(ctx, argv[0]);
1792 if (!filename)
1793 return JS_EXCEPTION;
1794 #if defined(_WIN32)
1795 {
1796 struct stat st;
1797 if (stat(filename, &st) == 0 && S_ISDIR(st.st_mode)) {
1798 ret = rmdir(filename);
1799 } else {
1800 ret = unlink(filename);
1801 }
1802 }
1803 #else
1804 ret = remove(filename);
1805 #endif
1806 ret = js_get_errno(ret);
1807 JS_FreeCString(ctx, filename);
1808 return JS_NewInt32(ctx, ret);
1809 }
1810
1811 static JSValue js_os_rename(JSContext *ctx, JSValueConst this_val,
1812 int argc, JSValueConst *argv)
1813 {
1814 const char *oldpath, *newpath;
1815 int ret;
1816
1817 oldpath = JS_ToCString(ctx, argv[0]);
1818 if (!oldpath)
1819 return JS_EXCEPTION;
1820 newpath = JS_ToCString(ctx, argv[1]);
1821 if (!newpath) {
1822 JS_FreeCString(ctx, oldpath);
1823 return JS_EXCEPTION;
1824 }
1825 ret = js_get_errno(rename(oldpath, newpath));
1826 JS_FreeCString(ctx, oldpath);
1827 JS_FreeCString(ctx, newpath);
1828 return JS_NewInt32(ctx, ret);
1829 }
1830
1831 static BOOL is_main_thread(JSRuntime *rt)
1832 {
1833 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
1834 return !ts->recv_pipe;
1835 }
1836
1837 static JSOSRWHandler *find_rh(JSThreadState *ts, int fd)
1838 {
1839 JSOSRWHandler *rh;
1840 struct list_head *el;
1841
1842 list_for_each(el, &ts->os_rw_handlers) {
1843 rh = list_entry(el, JSOSRWHandler, link);
1844 if (rh->fd == fd)
1845 return rh;
1846 }
1847 return NULL;
1848 }
1849
1850 static void free_rw_handler(JSRuntime *rt, JSOSRWHandler *rh)
1851 {
1852 int i;
1853 list_del(&rh->link);
1854 for(i = 0; i < 2; i++) {
1855 JS_FreeValueRT(rt, rh->rw_func[i]);
1856 }
1857 js_free_rt(rt, rh);
1858 }
1859
1860 static JSValue js_os_setReadHandler(JSContext *ctx, JSValueConst this_val,
1861 int argc, JSValueConst *argv, int magic)
1862 {
1863 JSRuntime *rt = JS_GetRuntime(ctx);
1864 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
1865 JSOSRWHandler *rh;
1866 int fd;
1867 JSValueConst func;
1868
1869 if (JS_ToInt32(ctx, &fd, argv[0]))
1870 return JS_EXCEPTION;
1871 func = argv[1];
1872 if (JS_IsNull(func)) {
1873 rh = find_rh(ts, fd);
1874 if (rh) {
1875 JS_FreeValue(ctx, rh->rw_func[magic]);
1876 rh->rw_func[magic] = JS_NULL;
1877 if (JS_IsNull(rh->rw_func[0]) &&
1878 JS_IsNull(rh->rw_func[1])) {
1879 /* remove the entry */
1880 free_rw_handler(JS_GetRuntime(ctx), rh);
1881 }
1882 }
1883 } else {
1884 if (!JS_IsFunction(ctx, func))
1885 return JS_ThrowTypeError(ctx, "not a function");
1886 rh = find_rh(ts, fd);
1887 if (!rh) {
1888 rh = js_mallocz(ctx, sizeof(*rh));
1889 if (!rh)
1890 return JS_EXCEPTION;
1891 rh->fd = fd;
1892 rh->rw_func[0] = JS_NULL;
1893 rh->rw_func[1] = JS_NULL;
1894 list_add_tail(&rh->link, &ts->os_rw_handlers);
1895 }
1896 JS_FreeValue(ctx, rh->rw_func[magic]);
1897 rh->rw_func[magic] = JS_DupValue(ctx, func);
1898 }
1899 return JS_UNDEFINED;
1900 }
1901
1902 static JSOSSignalHandler *find_sh(JSThreadState *ts, int sig_num)
1903 {
1904 JSOSSignalHandler *sh;
1905 struct list_head *el;
1906 list_for_each(el, &ts->os_signal_handlers) {
1907 sh = list_entry(el, JSOSSignalHandler, link);
1908 if (sh->sig_num == sig_num)
1909 return sh;
1910 }
1911 return NULL;
1912 }
1913
1914 static void free_sh(JSRuntime *rt, JSOSSignalHandler *sh)
1915 {
1916 list_del(&sh->link);
1917 JS_FreeValueRT(rt, sh->func);
1918 js_free_rt(rt, sh);
1919 }
1920
1921 static void os_signal_handler(int sig_num)
1922 {
1923 os_pending_signals |= ((uint64_t)1 << sig_num);
1924 }
1925
1926 #if defined(_WIN32)
1927 typedef void (*sighandler_t)(int sig_num);
1928 #endif
1929
1930 static JSValue js_os_signal(JSContext *ctx, JSValueConst this_val,
1931 int argc, JSValueConst *argv)
1932 {
1933 JSRuntime *rt = JS_GetRuntime(ctx);
1934 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
1935 JSOSSignalHandler *sh;
1936 uint32_t sig_num;
1937 JSValueConst func;
1938 sighandler_t handler;
1939
1940 if (!is_main_thread(rt))
1941 return JS_ThrowTypeError(ctx, "signal handler can only be set in the main thread");
1942
1943 if (JS_ToUint32(ctx, &sig_num, argv[0]))
1944 return JS_EXCEPTION;
1945 if (sig_num >= 64)
1946 return JS_ThrowRangeError(ctx, "invalid signal number");
1947 func = argv[1];
1948 /* func = null: SIG_DFL, func = undefined, SIG_IGN */
1949 if (JS_IsNull(func) || JS_IsUndefined(func)) {
1950 sh = find_sh(ts, sig_num);
1951 if (sh) {
1952 free_sh(JS_GetRuntime(ctx), sh);
1953 }
1954 if (JS_IsNull(func))
1955 handler = SIG_DFL;
1956 else
1957 handler = SIG_IGN;
1958 signal(sig_num, handler);
1959 } else {
1960 if (!JS_IsFunction(ctx, func))
1961 return JS_ThrowTypeError(ctx, "not a function");
1962 sh = find_sh(ts, sig_num);
1963 if (!sh) {
1964 sh = js_mallocz(ctx, sizeof(*sh));
1965 if (!sh)
1966 return JS_EXCEPTION;
1967 sh->sig_num = sig_num;
1968 list_add_tail(&sh->link, &ts->os_signal_handlers);
1969 }
1970 JS_FreeValue(ctx, sh->func);
1971 sh->func = JS_DupValue(ctx, func);
1972 signal(sig_num, os_signal_handler);
1973 }
1974 return JS_UNDEFINED;
1975 }
1976
1977 #if defined(__linux__) || defined(__APPLE__)
1978 static int64_t get_time_ms(void)
1979 {
1980 struct timespec ts;
1981 clock_gettime(CLOCK_MONOTONIC, &ts);
1982 return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);
1983 }
1984
1985 static int64_t get_time_ns(void)
1986 {
1987 struct timespec ts;
1988 clock_gettime(CLOCK_MONOTONIC, &ts);
1989 return (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
1990 }
1991 #else
1992 /* more portable, but does not work if the date is updated */
1993 static int64_t get_time_ms(void)
1994 {
1995 struct timeval tv;
1996 gettimeofday(&tv, NULL);
1997 return (int64_t)tv.tv_sec * 1000 + (tv.tv_usec / 1000);
1998 }
1999
2000 static int64_t get_time_ns(void)
2001 {
2002 struct timeval tv;
2003 gettimeofday(&tv, NULL);
2004 return (int64_t)tv.tv_sec * 1000000000 + (tv.tv_usec * 1000);
2005 }
2006 #endif
2007
2008 static JSValue js_os_now(JSContext *ctx, JSValue this_val,
2009 int argc, JSValue *argv)
2010 {
2011 return JS_NewFloat64(ctx, (double)get_time_ns() / 1e6);
2012 }
2013
2014 static void unlink_timer(JSRuntime *rt, JSOSTimer *th)
2015 {
2016 if (th->link.prev) {
2017 list_del(&th->link);
2018 th->link.prev = th->link.next = NULL;
2019 }
2020 }
2021
2022 static void free_timer(JSRuntime *rt, JSOSTimer *th)
2023 {
2024 JS_FreeValueRT(rt, th->func);
2025 js_free_rt(rt, th);
2026 }
2027
2028 static JSClassID js_os_timer_class_id;
2029
2030 static void js_os_timer_finalizer(JSRuntime *rt, JSValue val)
2031 {
2032 JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id);
2033 if (th) {
2034 th->has_object = FALSE;
2035 if (!th->link.prev)
2036 free_timer(rt, th);
2037 }
2038 }
2039
2040 static void js_os_timer_mark(JSRuntime *rt, JSValueConst val,
2041 JS_MarkFunc *mark_func)
2042 {
2043 JSOSTimer *th = JS_GetOpaque(val, js_os_timer_class_id);
2044 if (th) {
2045 JS_MarkValue(rt, th->func, mark_func);
2046 }
2047 }
2048
2049 static JSValue js_os_setTimeout(JSContext *ctx, JSValueConst this_val,
2050 int argc, JSValueConst *argv)
2051 {
2052 JSRuntime *rt = JS_GetRuntime(ctx);
2053 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
2054 int64_t delay;
2055 JSValueConst func;
2056 JSOSTimer *th;
2057 JSValue obj;
2058
2059 func = argv[0];
2060 if (!JS_IsFunction(ctx, func))
2061 return JS_ThrowTypeError(ctx, "not a function");
2062 if (JS_ToInt64(ctx, &delay, argv[1]))
2063 return JS_EXCEPTION;
2064 obj = JS_NewObjectClass(ctx, js_os_timer_class_id);
2065 if (JS_IsException(obj))
2066 return obj;
2067 th = js_mallocz(ctx, sizeof(*th));
2068 if (!th) {
2069 JS_FreeValue(ctx, obj);
2070 return JS_EXCEPTION;
2071 }
2072 th->has_object = TRUE;
2073 th->timeout = get_time_ms() + delay;
2074 th->func = JS_DupValue(ctx, func);
2075 list_add_tail(&th->link, &ts->os_timers);
2076 JS_SetOpaque(obj, th);
2077 return obj;
2078 }
2079
2080 static JSValue js_os_clearTimeout(JSContext *ctx, JSValueConst this_val,
2081 int argc, JSValueConst *argv)
2082 {
2083 JSOSTimer *th = JS_GetOpaque2(ctx, argv[0], js_os_timer_class_id);
2084 if (!th)
2085 return JS_EXCEPTION;
2086 unlink_timer(JS_GetRuntime(ctx), th);
2087 return JS_UNDEFINED;
2088 }
2089
2090 static JSClassDef js_os_timer_class = {
2091 "OSTimer",
2092 .finalizer = js_os_timer_finalizer,
2093 .gc_mark = js_os_timer_mark,
2094 };
2095
2096 /* return a promise */
2097 static JSValue js_os_sleepAsync(JSContext *ctx, JSValueConst this_val,
2098 int argc, JSValueConst *argv)
2099 {
2100 JSRuntime *rt = JS_GetRuntime(ctx);
2101 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
2102 int64_t delay;
2103 JSOSTimer *th;
2104 JSValue promise, resolving_funcs[2];
2105
2106 if (JS_ToInt64(ctx, &delay, argv[0]))
2107 return JS_EXCEPTION;
2108 promise = JS_NewPromiseCapability(ctx, resolving_funcs);
2109 if (JS_IsException(promise))
2110 return JS_EXCEPTION;
2111
2112 th = js_mallocz(ctx, sizeof(*th));
2113 if (!th) {
2114 JS_FreeValue(ctx, promise);
2115 JS_FreeValue(ctx, resolving_funcs[0]);
2116 JS_FreeValue(ctx, resolving_funcs[1]);
2117 return JS_EXCEPTION;
2118 }
2119 th->has_object = FALSE;
2120 th->timeout = get_time_ms() + delay;
2121 th->func = JS_DupValue(ctx, resolving_funcs[0]);
2122 list_add_tail(&th->link, &ts->os_timers);
2123 JS_FreeValue(ctx, resolving_funcs[0]);
2124 JS_FreeValue(ctx, resolving_funcs[1]);
2125 return promise;
2126 }
2127
2128 static void call_handler(JSContext *ctx, JSValueConst func)
2129 {
2130 JSValue ret, func1;
2131 /* 'func' might be destroyed when calling itself (if it frees the
2132 handler), so must take extra care */
2133 func1 = JS_DupValue(ctx, func);
2134 ret = JS_Call(ctx, func1, JS_UNDEFINED, 0, NULL);
2135 JS_FreeValue(ctx, func1);
2136 if (JS_IsException(ret))
2137 js_std_dump_error(ctx);
2138 JS_FreeValue(ctx, ret);
2139 }
2140
2141 #if defined(_WIN32)
2142
2143 static int js_os_poll(JSContext *ctx)
2144 {
2145 JSRuntime *rt = JS_GetRuntime(ctx);
2146 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
2147 int min_delay, console_fd;
2148 int64_t cur_time, delay;
2149 JSOSRWHandler *rh;
2150 struct list_head *el;
2151
2152 /* XXX: handle signals if useful */
2153
2154 if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers))
2155 return -1; /* no more events */
2156
2157 /* XXX: only timers and basic console input are supported */
2158 if (!list_empty(&ts->os_timers)) {
2159 cur_time = get_time_ms();
2160 min_delay = 10000;
2161 list_for_each(el, &ts->os_timers) {
2162 JSOSTimer *th = list_entry(el, JSOSTimer, link);
2163 delay = th->timeout - cur_time;
2164 if (delay <= 0) {
2165 JSValue func;
2166 /* the timer expired */
2167 func = th->func;
2168 th->func = JS_UNDEFINED;
2169 unlink_timer(rt, th);
2170 if (!th->has_object)
2171 free_timer(rt, th);
2172 call_handler(ctx, func);
2173 JS_FreeValue(ctx, func);
2174 return 0;
2175 } else if (delay < min_delay) {
2176 min_delay = delay;
2177 }
2178 }
2179 } else {
2180 min_delay = -1;
2181 }
2182
2183 console_fd = -1;
2184 list_for_each(el, &ts->os_rw_handlers) {
2185 rh = list_entry(el, JSOSRWHandler, link);
2186 if (rh->fd == 0 && !JS_IsNull(rh->rw_func[0])) {
2187 console_fd = rh->fd;
2188 break;
2189 }
2190 }
2191
2192 if (console_fd >= 0) {
2193 DWORD ti, ret;
2194 HANDLE handle;
2195 if (min_delay == -1)
2196 ti = INFINITE;
2197 else
2198 ti = min_delay;
2199 handle = (HANDLE)_get_osfhandle(console_fd);
2200 ret = WaitForSingleObject(handle, ti);
2201 if (ret == WAIT_OBJECT_0) {
2202 list_for_each(el, &ts->os_rw_handlers) {
2203 rh = list_entry(el, JSOSRWHandler, link);
2204 if (rh->fd == console_fd && !JS_IsNull(rh->rw_func[0])) {
2205 call_handler(ctx, rh->rw_func[0]);
2206 /* must stop because the list may have been modified */
2207 break;
2208 }
2209 }
2210 }
2211 } else {
2212 Sleep(min_delay);
2213 }
2214 return 0;
2215 }
2216 #else
2217
2218 #ifdef USE_WORKER
2219
2220 static void js_free_message(JSWorkerMessage *msg);
2221
2222 /* return 1 if a message was handled, 0 if no message */
2223 static int handle_posted_message(JSRuntime *rt, JSContext *ctx,
2224 JSWorkerMessageHandler *port)
2225 {
2226 JSWorkerMessagePipe *ps = port->recv_pipe;
2227 int ret;
2228 struct list_head *el;
2229 JSWorkerMessage *msg;
2230 JSValue obj, data_obj, func, retval;
2231
2232 pthread_mutex_lock(&ps->mutex);
2233 if (!list_empty(&ps->msg_queue)) {
2234 el = ps->msg_queue.next;
2235 msg = list_entry(el, JSWorkerMessage, link);
2236
2237 /* remove the message from the queue */
2238 list_del(&msg->link);
2239
2240 if (list_empty(&ps->msg_queue)) {
2241 uint8_t buf[16];
2242 int ret;
2243 for(;;) {
2244 ret = read(ps->read_fd, buf, sizeof(buf));
2245 if (ret >= 0)
2246 break;
2247 if (errno != EAGAIN && errno != EINTR)
2248 break;
2249 }
2250 }
2251
2252 pthread_mutex_unlock(&ps->mutex);
2253
2254 data_obj = JS_ReadObject(ctx, msg->data, msg->data_len,
2255 JS_READ_OBJ_SAB | JS_READ_OBJ_REFERENCE);
2256
2257 js_free_message(msg);
2258
2259 if (JS_IsException(data_obj))
2260 goto fail;
2261 obj = JS_NewObject(ctx);
2262 if (JS_IsException(obj)) {
2263 JS_FreeValue(ctx, data_obj);
2264 goto fail;
2265 }
2266 JS_DefinePropertyValueStr(ctx, obj, "data", data_obj, JS_PROP_C_W_E);
2267
2268 /* 'func' might be destroyed when calling itself (if it frees the
2269 handler), so must take extra care */
2270 func = JS_DupValue(ctx, port->on_message_func);
2271 retval = JS_Call(ctx, func, JS_UNDEFINED, 1, (JSValueConst *)&obj);
2272 JS_FreeValue(ctx, obj);
2273 JS_FreeValue(ctx, func);
2274 if (JS_IsException(retval)) {
2275 fail:
2276 js_std_dump_error(ctx);
2277 } else {
2278 JS_FreeValue(ctx, retval);
2279 }
2280 ret = 1;
2281 } else {
2282 pthread_mutex_unlock(&ps->mutex);
2283 ret = 0;
2284 }
2285 return ret;
2286 }
2287 #else
2288 static int handle_posted_message(JSRuntime *rt, JSContext *ctx,
2289 JSWorkerMessageHandler *port)
2290 {
2291 return 0;
2292 }
2293 #endif
2294
2295 static int js_os_poll(JSContext *ctx)
2296 {
2297 JSRuntime *rt = JS_GetRuntime(ctx);
2298 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
2299 int ret, fd_max, min_delay;
2300 int64_t cur_time, delay;
2301 fd_set rfds, wfds;
2302 JSOSRWHandler *rh;
2303 struct list_head *el;
2304 struct timeval tv, *tvp;
2305
2306 /* only check signals in the main thread */
2307 if (!ts->recv_pipe &&
2308 unlikely(os_pending_signals != 0)) {
2309 JSOSSignalHandler *sh;
2310 uint64_t mask;
2311
2312 list_for_each(el, &ts->os_signal_handlers) {
2313 sh = list_entry(el, JSOSSignalHandler, link);
2314 mask = (uint64_t)1 << sh->sig_num;
2315 if (os_pending_signals & mask) {
2316 os_pending_signals &= ~mask;
2317 call_handler(ctx, sh->func);
2318 return 0;
2319 }
2320 }
2321 }
2322
2323 if (list_empty(&ts->os_rw_handlers) && list_empty(&ts->os_timers) &&
2324 list_empty(&ts->port_list))
2325 return -1; /* no more events */
2326
2327 if (!list_empty(&ts->os_timers)) {
2328 cur_time = get_time_ms();
2329 min_delay = 10000;
2330 list_for_each(el, &ts->os_timers) {
2331 JSOSTimer *th = list_entry(el, JSOSTimer, link);
2332 delay = th->timeout - cur_time;
2333 if (delay <= 0) {
2334 JSValue func;
2335 /* the timer expired */
2336 func = th->func;
2337 th->func = JS_UNDEFINED;
2338 unlink_timer(rt, th);
2339 if (!th->has_object)
2340 free_timer(rt, th);
2341 call_handler(ctx, func);
2342 JS_FreeValue(ctx, func);
2343 return 0;
2344 } else if (delay < min_delay) {
2345 min_delay = delay;
2346 }
2347 }
2348 tv.tv_sec = min_delay / 1000;
2349 tv.tv_usec = (min_delay % 1000) * 1000;
2350 tvp = &tv;
2351 } else {
2352 tvp = NULL;
2353 }
2354
2355 FD_ZERO(&rfds);
2356 FD_ZERO(&wfds);
2357 fd_max = -1;
2358 list_for_each(el, &ts->os_rw_handlers) {
2359 rh = list_entry(el, JSOSRWHandler, link);
2360 fd_max = max_int(fd_max, rh->fd);
2361 if (!JS_IsNull(rh->rw_func[0]))
2362 FD_SET(rh->fd, &rfds);
2363 if (!JS_IsNull(rh->rw_func[1]))
2364 FD_SET(rh->fd, &wfds);
2365 }
2366
2367 list_for_each(el, &ts->port_list) {
2368 JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);
2369 if (!JS_IsNull(port->on_message_func)) {
2370 JSWorkerMessagePipe *ps = port->recv_pipe;
2371 fd_max = max_int(fd_max, ps->read_fd);
2372 FD_SET(ps->read_fd, &rfds);
2373 }
2374 }
2375
2376 ret = select(fd_max + 1, &rfds, &wfds, NULL, tvp);
2377 if (ret > 0) {
2378 list_for_each(el, &ts->os_rw_handlers) {
2379 rh = list_entry(el, JSOSRWHandler, link);
2380 if (!JS_IsNull(rh->rw_func[0]) &&
2381 FD_ISSET(rh->fd, &rfds)) {
2382 call_handler(ctx, rh->rw_func[0]);
2383 /* must stop because the list may have been modified */
2384 goto done;
2385 }
2386 if (!JS_IsNull(rh->rw_func[1]) &&
2387 FD_ISSET(rh->fd, &wfds)) {
2388 call_handler(ctx, rh->rw_func[1]);
2389 /* must stop because the list may have been modified */
2390 goto done;
2391 }
2392 }
2393
2394 list_for_each(el, &ts->port_list) {
2395 JSWorkerMessageHandler *port = list_entry(el, JSWorkerMessageHandler, link);
2396 if (!JS_IsNull(port->on_message_func)) {
2397 JSWorkerMessagePipe *ps = port->recv_pipe;
2398 if (FD_ISSET(ps->read_fd, &rfds)) {
2399 if (handle_posted_message(rt, ctx, port))
2400 goto done;
2401 }
2402 }
2403 }
2404 }
2405 done:
2406 return 0;
2407 }
2408 #endif /* !_WIN32 */
2409
2410 static JSValue make_obj_error(JSContext *ctx,
2411 JSValue obj,
2412 int err)
2413 {
2414 JSValue arr;
2415 if (JS_IsException(obj))
2416 return obj;
2417 arr = JS_NewArray(ctx);
2418 if (JS_IsException(arr))
2419 return JS_EXCEPTION;
2420 JS_DefinePropertyValueUint32(ctx, arr, 0, obj,
2421 JS_PROP_C_W_E);
2422 JS_DefinePropertyValueUint32(ctx, arr, 1, JS_NewInt32(ctx, err),
2423 JS_PROP_C_W_E);
2424 return arr;
2425 }
2426
2427 static JSValue make_string_error(JSContext *ctx,
2428 const char *buf,
2429 int err)
2430 {
2431 return make_obj_error(ctx, JS_NewString(ctx, buf), err);
2432 }
2433
2434 /* return [cwd, errorcode] */
2435 static JSValue js_os_getcwd(JSContext *ctx, JSValueConst this_val,
2436 int argc, JSValueConst *argv)
2437 {
2438 char buf[PATH_MAX];
2439 int err;
2440
2441 if (!getcwd(buf, sizeof(buf))) {
2442 buf[0] = '\0';
2443 err = errno;
2444 } else {
2445 err = 0;
2446 }
2447 return make_string_error(ctx, buf, err);
2448 }
2449
2450 static JSValue js_os_chdir(JSContext *ctx, JSValueConst this_val,
2451 int argc, JSValueConst *argv)
2452 {
2453 const char *target;
2454 int err;
2455
2456 target = JS_ToCString(ctx, argv[0]);
2457 if (!target)
2458 return JS_EXCEPTION;
2459 err = js_get_errno(chdir(target));
2460 JS_FreeCString(ctx, target);
2461 return JS_NewInt32(ctx, err);
2462 }
2463
2464 static JSValue js_os_mkdir(JSContext *ctx, JSValueConst this_val,
2465 int argc, JSValueConst *argv)
2466 {
2467 int mode, ret;
2468 const char *path;
2469
2470 if (argc >= 2) {
2471 if (JS_ToInt32(ctx, &mode, argv[1]))
2472 return JS_EXCEPTION;
2473 } else {
2474 mode = 0777;
2475 }
2476 path = JS_ToCString(ctx, argv[0]);
2477 if (!path)
2478 return JS_EXCEPTION;
2479 #if defined(_WIN32)
2480 (void)mode;
2481 ret = js_get_errno(mkdir(path));
2482 #else
2483 ret = js_get_errno(mkdir(path, mode));
2484 #endif
2485 JS_FreeCString(ctx, path);
2486 return JS_NewInt32(ctx, ret);
2487 }
2488
2489 /* return [array, errorcode] */
2490 static JSValue js_os_readdir(JSContext *ctx, JSValueConst this_val,
2491 int argc, JSValueConst *argv)
2492 {
2493 const char *path;
2494 DIR *f;
2495 struct dirent *d;
2496 JSValue obj;
2497 int err;
2498 uint32_t len;
2499
2500 path = JS_ToCString(ctx, argv[0]);
2501 if (!path)
2502 return JS_EXCEPTION;
2503 obj = JS_NewArray(ctx);
2504 if (JS_IsException(obj)) {
2505 JS_FreeCString(ctx, path);
2506 return JS_EXCEPTION;
2507 }
2508 f = opendir(path);
2509 if (!f)
2510 err = errno;
2511 else
2512 err = 0;
2513 JS_FreeCString(ctx, path);
2514 if (!f)
2515 goto done;
2516 len = 0;
2517 for(;;) {
2518 errno = 0;
2519 d = readdir(f);
2520 if (!d) {
2521 err = errno;
2522 break;
2523 }
2524 JS_DefinePropertyValueUint32(ctx, obj, len++,
2525 JS_NewString(ctx, d->d_name),
2526 JS_PROP_C_W_E);
2527 }
2528 closedir(f);
2529 done:
2530 return make_obj_error(ctx, obj, err);
2531 }
2532
2533 #if !defined(_WIN32)
2534 static int64_t timespec_to_ms(const struct timespec *tv)
2535 {
2536 return (int64_t)tv->tv_sec * 1000 + (tv->tv_nsec / 1000000);
2537 }
2538 #endif
2539
2540 /* return [obj, errcode] */
2541 static JSValue js_os_stat(JSContext *ctx, JSValueConst this_val,
2542 int argc, JSValueConst *argv, int is_lstat)
2543 {
2544 const char *path;
2545 int err, res;
2546 struct stat st;
2547 JSValue obj;
2548
2549 path = JS_ToCString(ctx, argv[0]);
2550 if (!path)
2551 return JS_EXCEPTION;
2552 #if defined(_WIN32)
2553 res = stat(path, &st);
2554 #else
2555 if (is_lstat)
2556 res = lstat(path, &st);
2557 else
2558 res = stat(path, &st);
2559 #endif
2560 JS_FreeCString(ctx, path);
2561 if (res < 0) {
2562 err = errno;
2563 obj = JS_NULL;
2564 } else {
2565 err = 0;
2566 obj = JS_NewObject(ctx);
2567 if (JS_IsException(obj))
2568 return JS_EXCEPTION;
2569 JS_DefinePropertyValueStr(ctx, obj, "dev",
2570 JS_NewInt64(ctx, st.st_dev),
2571 JS_PROP_C_W_E);
2572 JS_DefinePropertyValueStr(ctx, obj, "ino",
2573 JS_NewInt64(ctx, st.st_ino),
2574 JS_PROP_C_W_E);
2575 JS_DefinePropertyValueStr(ctx, obj, "mode",
2576 JS_NewInt32(ctx, st.st_mode),
2577 JS_PROP_C_W_E);
2578 JS_DefinePropertyValueStr(ctx, obj, "nlink",
2579 JS_NewInt64(ctx, st.st_nlink),
2580 JS_PROP_C_W_E);
2581 JS_DefinePropertyValueStr(ctx, obj, "uid",
2582 JS_NewInt64(ctx, st.st_uid),
2583 JS_PROP_C_W_E);
2584 JS_DefinePropertyValueStr(ctx, obj, "gid",
2585 JS_NewInt64(ctx, st.st_gid),
2586 JS_PROP_C_W_E);
2587 JS_DefinePropertyValueStr(ctx, obj, "rdev",
2588 JS_NewInt64(ctx, st.st_rdev),
2589 JS_PROP_C_W_E);
2590 JS_DefinePropertyValueStr(ctx, obj, "size",
2591 JS_NewInt64(ctx, st.st_size),
2592 JS_PROP_C_W_E);
2593 #if !defined(_WIN32)
2594 JS_DefinePropertyValueStr(ctx, obj, "blocks",
2595 JS_NewInt64(ctx, st.st_blocks),
2596 JS_PROP_C_W_E);
2597 #endif
2598 #if defined(_WIN32)
2599 JS_DefinePropertyValueStr(ctx, obj, "atime",
2600 JS_NewInt64(ctx, (int64_t)st.st_atime * 1000),
2601 JS_PROP_C_W_E);
2602 JS_DefinePropertyValueStr(ctx, obj, "mtime",
2603 JS_NewInt64(ctx, (int64_t)st.st_mtime * 1000),
2604 JS_PROP_C_W_E);
2605 JS_DefinePropertyValueStr(ctx, obj, "ctime",
2606 JS_NewInt64(ctx, (int64_t)st.st_ctime * 1000),
2607 JS_PROP_C_W_E);
2608 #elif defined(__APPLE__)
2609 JS_DefinePropertyValueStr(ctx, obj, "atime",
2610 JS_NewInt64(ctx, timespec_to_ms(&st.st_atimespec)),
2611 JS_PROP_C_W_E);
2612 JS_DefinePropertyValueStr(ctx, obj, "mtime",
2613 JS_NewInt64(ctx, timespec_to_ms(&st.st_mtimespec)),
2614 JS_PROP_C_W_E);
2615 JS_DefinePropertyValueStr(ctx, obj, "ctime",
2616 JS_NewInt64(ctx, timespec_to_ms(&st.st_ctimespec)),
2617 JS_PROP_C_W_E);
2618 #else
2619 JS_DefinePropertyValueStr(ctx, obj, "atime",
2620 JS_NewInt64(ctx, timespec_to_ms(&st.st_atim)),
2621 JS_PROP_C_W_E);
2622 JS_DefinePropertyValueStr(ctx, obj, "mtime",
2623 JS_NewInt64(ctx, timespec_to_ms(&st.st_mtim)),
2624 JS_PROP_C_W_E);
2625 JS_DefinePropertyValueStr(ctx, obj, "ctime",
2626 JS_NewInt64(ctx, timespec_to_ms(&st.st_ctim)),
2627 JS_PROP_C_W_E);
2628 #endif
2629 }
2630 return make_obj_error(ctx, obj, err);
2631 }
2632
2633 #if !defined(_WIN32)
2634 static void ms_to_timeval(struct timeval *tv, uint64_t v)
2635 {
2636 tv->tv_sec = v / 1000;
2637 tv->tv_usec = (v % 1000) * 1000;
2638 }
2639 #endif
2640
2641 static JSValue js_os_utimes(JSContext *ctx, JSValueConst this_val,
2642 int argc, JSValueConst *argv)
2643 {
2644 const char *path;
2645 int64_t atime, mtime;
2646 int ret;
2647
2648 if (JS_ToInt64(ctx, &atime, argv[1]))
2649 return JS_EXCEPTION;
2650 if (JS_ToInt64(ctx, &mtime, argv[2]))
2651 return JS_EXCEPTION;
2652 path = JS_ToCString(ctx, argv[0]);
2653 if (!path)
2654 return JS_EXCEPTION;
2655 #if defined(_WIN32)
2656 {
2657 struct _utimbuf times;
2658 times.actime = atime / 1000;
2659 times.modtime = mtime / 1000;
2660 ret = js_get_errno(_utime(path, &times));
2661 }
2662 #else
2663 {
2664 struct timeval times[2];
2665 ms_to_timeval(&times[0], atime);
2666 ms_to_timeval(&times[1], mtime);
2667 ret = js_get_errno(utimes(path, times));
2668 }
2669 #endif
2670 JS_FreeCString(ctx, path);
2671 return JS_NewInt32(ctx, ret);
2672 }
2673
2674 /* sleep(delay_ms) */
2675 static JSValue js_os_sleep(JSContext *ctx, JSValueConst this_val,
2676 int argc, JSValueConst *argv)
2677 {
2678 int64_t delay;
2679 int ret;
2680
2681 if (JS_ToInt64(ctx, &delay, argv[0]))
2682 return JS_EXCEPTION;
2683 if (delay < 0)
2684 delay = 0;
2685 #if defined(_WIN32)
2686 {
2687 if (delay > INT32_MAX)
2688 delay = INT32_MAX;
2689 Sleep(delay);
2690 ret = 0;
2691 }
2692 #else
2693 {
2694 struct timespec ts;
2695
2696 ts.tv_sec = delay / 1000;
2697 ts.tv_nsec = (delay % 1000) * 1000000;
2698 ret = js_get_errno(nanosleep(&ts, NULL));
2699 }
2700 #endif
2701 return JS_NewInt32(ctx, ret);
2702 }
2703
2704 #if defined(_WIN32)
2705 static char *realpath(const char *path, char *buf)
2706 {
2707 if (!_fullpath(buf, path, PATH_MAX)) {
2708 errno = ENOENT;
2709 return NULL;
2710 } else {
2711 return buf;
2712 }
2713 }
2714 #endif
2715
2716 /* return [path, errorcode] */
2717 static JSValue js_os_realpath(JSContext *ctx, JSValueConst this_val,
2718 int argc, JSValueConst *argv)
2719 {
2720 const char *path;
2721 char buf[PATH_MAX], *res;
2722 int err;
2723
2724 path = JS_ToCString(ctx, argv[0]);
2725 if (!path)
2726 return JS_EXCEPTION;
2727 res = realpath(path, buf);
2728 JS_FreeCString(ctx, path);
2729 if (!res) {
2730 buf[0] = '\0';
2731 err = errno;
2732 } else {
2733 err = 0;
2734 }
2735 return make_string_error(ctx, buf, err);
2736 }
2737
2738 #if !defined(_WIN32)
2739 static JSValue js_os_symlink(JSContext *ctx, JSValueConst this_val,
2740 int argc, JSValueConst *argv)
2741 {
2742 const char *target, *linkpath;
2743 int err;
2744
2745 target = JS_ToCString(ctx, argv[0]);
2746 if (!target)
2747 return JS_EXCEPTION;
2748 linkpath = JS_ToCString(ctx, argv[1]);
2749 if (!linkpath) {
2750 JS_FreeCString(ctx, target);
2751 return JS_EXCEPTION;
2752 }
2753 err = js_get_errno(symlink(target, linkpath));
2754 JS_FreeCString(ctx, target);
2755 JS_FreeCString(ctx, linkpath);
2756 return JS_NewInt32(ctx, err);
2757 }
2758
2759 /* return [path, errorcode] */
2760 static JSValue js_os_readlink(JSContext *ctx, JSValueConst this_val,
2761 int argc, JSValueConst *argv)
2762 {
2763 const char *path;
2764 char buf[PATH_MAX];
2765 int err;
2766 ssize_t res;
2767
2768 path = JS_ToCString(ctx, argv[0]);
2769 if (!path)
2770 return JS_EXCEPTION;
2771 res = readlink(path, buf, sizeof(buf) - 1);
2772 if (res < 0) {
2773 buf[0] = '\0';
2774 err = errno;
2775 } else {
2776 buf[res] = '\0';
2777 err = 0;
2778 }
2779 JS_FreeCString(ctx, path);
2780 return make_string_error(ctx, buf, err);
2781 }
2782
2783 static char **build_envp(JSContext *ctx, JSValueConst obj)
2784 {
2785 uint32_t len, i;
2786 JSPropertyEnum *tab;
2787 char **envp, *pair;
2788 const char *key, *str;
2789 JSValue val;
2790 size_t key_len, str_len;
2791
2792 if (JS_GetOwnPropertyNames(ctx, &tab, &len, obj,
2793 JS_GPN_STRING_MASK | JS_GPN_ENUM_ONLY) < 0)
2794 return NULL;
2795 envp = js_mallocz(ctx, sizeof(envp[0]) * ((size_t)len + 1));
2796 if (!envp)
2797 goto fail;
2798 for(i = 0; i < len; i++) {
2799 val = JS_GetProperty(ctx, obj, tab[i].atom);
2800 if (JS_IsException(val))
2801 goto fail;
2802 str = JS_ToCString(ctx, val);
2803 JS_FreeValue(ctx, val);
2804 if (!str)
2805 goto fail;
2806 key = JS_AtomToCString(ctx, tab[i].atom);
2807 if (!key) {
2808 JS_FreeCString(ctx, str);
2809 goto fail;
2810 }
2811 key_len = strlen(key);
2812 str_len = strlen(str);
2813 pair = js_malloc(ctx, key_len + str_len + 2);
2814 if (!pair) {
2815 JS_FreeCString(ctx, key);
2816 JS_FreeCString(ctx, str);
2817 goto fail;
2818 }
2819 memcpy(pair, key, key_len);
2820 pair[key_len] = '=';
2821 memcpy(pair + key_len + 1, str, str_len);
2822 pair[key_len + 1 + str_len] = '\0';
2823 envp[i] = pair;
2824 JS_FreeCString(ctx, key);
2825 JS_FreeCString(ctx, str);
2826 }
2827 done:
2828 for(i = 0; i < len; i++)
2829 JS_FreeAtom(ctx, tab[i].atom);
2830 js_free(ctx, tab);
2831 return envp;
2832 fail:
2833 if (envp) {
2834 for(i = 0; i < len; i++)
2835 js_free(ctx, envp[i]);
2836 js_free(ctx, envp);
2837 envp = NULL;
2838 }
2839 goto done;
2840 }
2841
2842 /* execvpe is not available on non GNU systems */
2843 static int my_execvpe(const char *filename, char **argv, char **envp)
2844 {
2845 char *path, *p, *p_next, *p1;
2846 char buf[PATH_MAX];
2847 size_t filename_len, path_len;
2848 BOOL eacces_error;
2849
2850 filename_len = strlen(filename);
2851 if (filename_len == 0) {
2852 errno = ENOENT;
2853 return -1;
2854 }
2855 if (strchr(filename, '/'))
2856 return execve(filename, argv, envp);
2857
2858 path = getenv("PATH");
2859 if (!path)
2860 path = (char *)"/bin:/usr/bin";
2861 eacces_error = FALSE;
2862 p = path;
2863 for(p = path; p != NULL; p = p_next) {
2864 p1 = strchr(p, ':');
2865 if (!p1) {
2866 p_next = NULL;
2867 path_len = strlen(p);
2868 } else {
2869 p_next = p1 + 1;
2870 path_len = p1 - p;
2871 }
2872 /* path too long */
2873 if ((path_len + 1 + filename_len + 1) > PATH_MAX)
2874 continue;
2875 memcpy(buf, p, path_len);
2876 buf[path_len] = '/';
2877 memcpy(buf + path_len + 1, filename, filename_len);
2878 buf[path_len + 1 + filename_len] = '\0';
2879
2880 execve(buf, argv, envp);
2881
2882 switch(errno) {
2883 case EACCES:
2884 eacces_error = TRUE;
2885 break;
2886 case ENOENT:
2887 case ENOTDIR:
2888 break;
2889 default:
2890 return -1;
2891 }
2892 }
2893 if (eacces_error)
2894 errno = EACCES;
2895 return -1;
2896 }
2897
2898 /* exec(args[, options]) -> exitcode */
2899 static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val,
2900 int argc, JSValueConst *argv)
2901 {
2902 JSValueConst options, args = argv[0];
2903 JSValue val, ret_val;
2904 const char **exec_argv, *file = NULL, *str, *cwd = NULL;
2905 char **envp = environ;
2906 uint32_t exec_argc, i;
2907 int ret, pid, status;
2908 BOOL block_flag = TRUE, use_path = TRUE;
2909 static const char *std_name[3] = { "stdin", "stdout", "stderr" };
2910 int std_fds[3];
2911 uint32_t uid = -1, gid = -1;
2912
2913 val = JS_GetPropertyStr(ctx, args, "length");
2914 if (JS_IsException(val))
2915 return JS_EXCEPTION;
2916 ret = JS_ToUint32(ctx, &exec_argc, val);
2917 JS_FreeValue(ctx, val);
2918 if (ret)
2919 return JS_EXCEPTION;
2920 /* arbitrary limit to avoid overflow */
2921 if (exec_argc < 1 || exec_argc > 65535) {
2922 return JS_ThrowTypeError(ctx, "invalid number of arguments");
2923 }
2924 exec_argv = js_mallocz(ctx, sizeof(exec_argv[0]) * (exec_argc + 1));
2925 if (!exec_argv)
2926 return JS_EXCEPTION;
2927 for(i = 0; i < exec_argc; i++) {
2928 val = JS_GetPropertyUint32(ctx, args, i);
2929 if (JS_IsException(val))
2930 goto exception;
2931 str = JS_ToCString(ctx, val);
2932 JS_FreeValue(ctx, val);
2933 if (!str)
2934 goto exception;
2935 exec_argv[i] = str;
2936 }
2937 exec_argv[exec_argc] = NULL;
2938
2939 for(i = 0; i < 3; i++)
2940 std_fds[i] = i;
2941
2942 /* get the options, if any */
2943 if (argc >= 2) {
2944 options = argv[1];
2945
2946 if (get_bool_option(ctx, &block_flag, options, "block"))
2947 goto exception;
2948 if (get_bool_option(ctx, &use_path, options, "usePath"))
2949 goto exception;
2950
2951 val = JS_GetPropertyStr(ctx, options, "file");
2952 if (JS_IsException(val))
2953 goto exception;
2954 if (!JS_IsUndefined(val)) {
2955 file = JS_ToCString(ctx, val);
2956 JS_FreeValue(ctx, val);
2957 if (!file)
2958 goto exception;
2959 }
2960
2961 val = JS_GetPropertyStr(ctx, options, "cwd");
2962 if (JS_IsException(val))
2963 goto exception;
2964 if (!JS_IsUndefined(val)) {
2965 cwd = JS_ToCString(ctx, val);
2966 JS_FreeValue(ctx, val);
2967 if (!cwd)
2968 goto exception;
2969 }
2970
2971 /* stdin/stdout/stderr handles */
2972 for(i = 0; i < 3; i++) {
2973 val = JS_GetPropertyStr(ctx, options, std_name[i]);
2974 if (JS_IsException(val))
2975 goto exception;
2976 if (!JS_IsUndefined(val)) {
2977 int fd;
2978 ret = JS_ToInt32(ctx, &fd, val);
2979 JS_FreeValue(ctx, val);
2980 if (ret)
2981 goto exception;
2982 std_fds[i] = fd;
2983 }
2984 }
2985
2986 val = JS_GetPropertyStr(ctx, options, "env");
2987 if (JS_IsException(val))
2988 goto exception;
2989 if (!JS_IsUndefined(val)) {
2990 envp = build_envp(ctx, val);
2991 JS_FreeValue(ctx, val);
2992 if (!envp)
2993 goto exception;
2994 }
2995
2996 val = JS_GetPropertyStr(ctx, options, "uid");
2997 if (JS_IsException(val))
2998 goto exception;
2999 if (!JS_IsUndefined(val)) {
3000 ret = JS_ToUint32(ctx, &uid, val);
3001 JS_FreeValue(ctx, val);
3002 if (ret)
3003 goto exception;
3004 }
3005
3006 val = JS_GetPropertyStr(ctx, options, "gid");
3007 if (JS_IsException(val))
3008 goto exception;
3009 if (!JS_IsUndefined(val)) {
3010 ret = JS_ToUint32(ctx, &gid, val);
3011 JS_FreeValue(ctx, val);
3012 if (ret)
3013 goto exception;
3014 }
3015 }
3016
3017 pid = fork();
3018 if (pid < 0) {
3019 JS_ThrowTypeError(ctx, "fork error");
3020 goto exception;
3021 }
3022 if (pid == 0) {
3023 /* child */
3024 int fd_max = sysconf(_SC_OPEN_MAX);
3025
3026 /* remap the stdin/stdout/stderr handles if necessary */
3027 for(i = 0; i < 3; i++) {
3028 if (std_fds[i] != i) {
3029 if (dup2(std_fds[i], i) < 0)
3030 _exit(127);
3031 }
3032 }
3033
3034 for(i = 3; i < fd_max; i++)
3035 close(i);
3036 if (cwd) {
3037 if (chdir(cwd) < 0)
3038 _exit(127);
3039 }
3040 if (uid != -1) {
3041 if (setuid(uid) < 0)
3042 _exit(127);
3043 }
3044 if (gid != -1) {
3045 if (setgid(gid) < 0)
3046 _exit(127);
3047 }
3048
3049 if (!file)
3050 file = exec_argv[0];
3051 if (use_path)
3052 ret = my_execvpe(file, (char **)exec_argv, envp);
3053 else
3054 ret = execve(file, (char **)exec_argv, envp);
3055 _exit(127);
3056 }
3057 /* parent */
3058 if (block_flag) {
3059 for(;;) {
3060 ret = waitpid(pid, &status, 0);
3061 if (ret == pid) {
3062 if (WIFEXITED(status)) {
3063 ret = WEXITSTATUS(status);
3064 break;
3065 } else if (WIFSIGNALED(status)) {
3066 ret = -WTERMSIG(status);
3067 break;
3068 }
3069 }
3070 }
3071 } else {
3072 ret = pid;
3073 }
3074 ret_val = JS_NewInt32(ctx, ret);
3075 done:
3076 JS_FreeCString(ctx, file);
3077 JS_FreeCString(ctx, cwd);
3078 for(i = 0; i < exec_argc; i++)
3079 JS_FreeCString(ctx, exec_argv[i]);
3080 js_free(ctx, exec_argv);
3081 if (envp != environ) {
3082 char **p;
3083 p = envp;
3084 while (*p != NULL) {
3085 js_free(ctx, *p);
3086 p++;
3087 }
3088 js_free(ctx, envp);
3089 }
3090 return ret_val;
3091 exception:
3092 ret_val = JS_EXCEPTION;
3093 goto done;
3094 }
3095
3096 /* getpid() -> pid */
3097 static JSValue js_os_getpid(JSContext *ctx, JSValueConst this_val,
3098 int argc, JSValueConst *argv)
3099 {
3100 return JS_NewInt32(ctx, getpid());
3101 }
3102
3103 /* waitpid(pid, block) -> [pid, status] */
3104 static JSValue js_os_waitpid(JSContext *ctx, JSValueConst this_val,
3105 int argc, JSValueConst *argv)
3106 {
3107 int pid, status, options, ret;
3108 JSValue obj;
3109
3110 if (JS_ToInt32(ctx, &pid, argv[0]))
3111 return JS_EXCEPTION;
3112 if (JS_ToInt32(ctx, &options, argv[1]))
3113 return JS_EXCEPTION;
3114
3115 ret = waitpid(pid, &status, options);
3116 if (ret < 0) {
3117 ret = -errno;
3118 status = 0;
3119 }
3120
3121 obj = JS_NewArray(ctx);
3122 if (JS_IsException(obj))
3123 return obj;
3124 JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, ret),
3125 JS_PROP_C_W_E);
3126 JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, status),
3127 JS_PROP_C_W_E);
3128 return obj;
3129 }
3130
3131 /* pipe() -> [read_fd, write_fd] or null if error */
3132 static JSValue js_os_pipe(JSContext *ctx, JSValueConst this_val,
3133 int argc, JSValueConst *argv)
3134 {
3135 int pipe_fds[2], ret;
3136 JSValue obj;
3137
3138 ret = pipe(pipe_fds);
3139 if (ret < 0)
3140 return JS_NULL;
3141 obj = JS_NewArray(ctx);
3142 if (JS_IsException(obj))
3143 return obj;
3144 JS_DefinePropertyValueUint32(ctx, obj, 0, JS_NewInt32(ctx, pipe_fds[0]),
3145 JS_PROP_C_W_E);
3146 JS_DefinePropertyValueUint32(ctx, obj, 1, JS_NewInt32(ctx, pipe_fds[1]),
3147 JS_PROP_C_W_E);
3148 return obj;
3149 }
3150
3151 /* kill(pid, sig) */
3152 static JSValue js_os_kill(JSContext *ctx, JSValueConst this_val,
3153 int argc, JSValueConst *argv)
3154 {
3155 int pid, sig, ret;
3156
3157 if (JS_ToInt32(ctx, &pid, argv[0]))
3158 return JS_EXCEPTION;
3159 if (JS_ToInt32(ctx, &sig, argv[1]))
3160 return JS_EXCEPTION;
3161 ret = js_get_errno(kill(pid, sig));
3162 return JS_NewInt32(ctx, ret);
3163 }
3164
3165 /* dup(fd) */
3166 static JSValue js_os_dup(JSContext *ctx, JSValueConst this_val,
3167 int argc, JSValueConst *argv)
3168 {
3169 int fd, ret;
3170
3171 if (JS_ToInt32(ctx, &fd, argv[0]))
3172 return JS_EXCEPTION;
3173 ret = js_get_errno(dup(fd));
3174 return JS_NewInt32(ctx, ret);
3175 }
3176
3177 /* dup2(fd) */
3178 static JSValue js_os_dup2(JSContext *ctx, JSValueConst this_val,
3179 int argc, JSValueConst *argv)
3180 {
3181 int fd, fd2, ret;
3182
3183 if (JS_ToInt32(ctx, &fd, argv[0]))
3184 return JS_EXCEPTION;
3185 if (JS_ToInt32(ctx, &fd2, argv[1]))
3186 return JS_EXCEPTION;
3187 ret = js_get_errno(dup2(fd, fd2));
3188 return JS_NewInt32(ctx, ret);
3189 }
3190
3191 #endif /* !_WIN32 */
3192
3193 #ifdef USE_WORKER
3194
3195 /* Worker */
3196
3197 typedef struct {
3198 JSWorkerMessagePipe *recv_pipe;
3199 JSWorkerMessagePipe *send_pipe;
3200 JSWorkerMessageHandler *msg_handler;
3201 } JSWorkerData;
3202
3203 typedef struct {
3204 char *filename; /* module filename */
3205 char *basename; /* module base name */
3206 JSWorkerMessagePipe *recv_pipe, *send_pipe;
3207 } WorkerFuncArgs;
3208
3209 typedef struct {
3210 int ref_count;
3211 uint64_t buf[0];
3212 } JSSABHeader;
3213
3214 static JSClassID js_worker_class_id;
3215 static JSContext *(*js_worker_new_context_func)(JSRuntime *rt);
3216
3217 static int atomic_add_int(int *ptr, int v)
3218 {
3219 return atomic_fetch_add((_Atomic(uint32_t) *)ptr, v) + v;
3220 }
3221
3222 /* shared array buffer allocator */
3223 static void *js_sab_alloc(void *opaque, size_t size)
3224 {
3225 JSSABHeader *sab;
3226 sab = malloc(sizeof(JSSABHeader) + size);
3227 if (!sab)
3228 return NULL;
3229 sab->ref_count = 1;
3230 return sab->buf;
3231 }
3232
3233 static void js_sab_free(void *opaque, void *ptr)
3234 {
3235 JSSABHeader *sab;
3236 int ref_count;
3237 sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));
3238 ref_count = atomic_add_int(&sab->ref_count, -1);
3239 assert(ref_count >= 0);
3240 if (ref_count == 0) {
3241 free(sab);
3242 }
3243 }
3244
3245 static void js_sab_dup(void *opaque, void *ptr)
3246 {
3247 JSSABHeader *sab;
3248 sab = (JSSABHeader *)((uint8_t *)ptr - sizeof(JSSABHeader));
3249 atomic_add_int(&sab->ref_count, 1);
3250 }
3251
3252 static JSWorkerMessagePipe *js_new_message_pipe(void)
3253 {
3254 JSWorkerMessagePipe *ps;
3255 int pipe_fds[2];
3256
3257 if (pipe(pipe_fds) < 0)
3258 return NULL;
3259
3260 ps = malloc(sizeof(*ps));
3261 if (!ps) {
3262 close(pipe_fds[0]);
3263 close(pipe_fds[1]);
3264 return NULL;
3265 }
3266 ps->ref_count = 1;
3267 init_list_head(&ps->msg_queue);
3268 pthread_mutex_init(&ps->mutex, NULL);
3269 ps->read_fd = pipe_fds[0];
3270 ps->write_fd = pipe_fds[1];
3271 return ps;
3272 }
3273
3274 static JSWorkerMessagePipe *js_dup_message_pipe(JSWorkerMessagePipe *ps)
3275 {
3276 atomic_add_int(&ps->ref_count, 1);
3277 return ps;
3278 }
3279
3280 static void js_free_message(JSWorkerMessage *msg)
3281 {
3282 size_t i;
3283 /* free the SAB */
3284 for(i = 0; i < msg->sab_tab_len; i++) {
3285 js_sab_free(NULL, msg->sab_tab[i]);
3286 }
3287 free(msg->sab_tab);
3288 free(msg->data);
3289 free(msg);
3290 }
3291
3292 static void js_free_message_pipe(JSWorkerMessagePipe *ps)
3293 {
3294 struct list_head *el, *el1;
3295 JSWorkerMessage *msg;
3296 int ref_count;
3297
3298 if (!ps)
3299 return;
3300
3301 ref_count = atomic_add_int(&ps->ref_count, -1);
3302 assert(ref_count >= 0);
3303 if (ref_count == 0) {
3304 list_for_each_safe(el, el1, &ps->msg_queue) {
3305 msg = list_entry(el, JSWorkerMessage, link);
3306 js_free_message(msg);
3307 }
3308 pthread_mutex_destroy(&ps->mutex);
3309 close(ps->read_fd);
3310 close(ps->write_fd);
3311 free(ps);
3312 }
3313 }
3314
3315 static void js_free_port(JSRuntime *rt, JSWorkerMessageHandler *port)
3316 {
3317 if (port) {
3318 js_free_message_pipe(port->recv_pipe);
3319 JS_FreeValueRT(rt, port->on_message_func);
3320 list_del(&port->link);
3321 js_free_rt(rt, port);
3322 }
3323 }
3324
3325 static void js_worker_finalizer(JSRuntime *rt, JSValue val)
3326 {
3327 JSWorkerData *worker = JS_GetOpaque(val, js_worker_class_id);
3328 if (worker) {
3329 js_free_message_pipe(worker->recv_pipe);
3330 js_free_message_pipe(worker->send_pipe);
3331 js_free_port(rt, worker->msg_handler);
3332 js_free_rt(rt, worker);
3333 }
3334 }
3335
3336 static JSClassDef js_worker_class = {
3337 "Worker",
3338 .finalizer = js_worker_finalizer,
3339 };
3340
3341 static void *worker_func(void *opaque)
3342 {
3343 WorkerFuncArgs *args = opaque;
3344 JSRuntime *rt;
3345 JSThreadState *ts;
3346 JSContext *ctx;
3347 JSValue promise;
3348
3349 rt = JS_NewRuntime();
3350 if (rt == NULL) {
3351 fprintf(stderr, "JS_NewRuntime failure");
3352 exit(1);
3353 }
3354 js_std_init_handlers(rt);
3355
3356 JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);
3357
3358 /* set the pipe to communicate with the parent */
3359 ts = JS_GetRuntimeOpaque(rt);
3360 ts->recv_pipe = args->recv_pipe;
3361 ts->send_pipe = args->send_pipe;
3362
3363 /* function pointer to avoid linking the whole JS_NewContext() if
3364 not needed */
3365 ctx = js_worker_new_context_func(rt);
3366 if (ctx == NULL) {
3367 fprintf(stderr, "JS_NewContext failure");
3368 }
3369
3370 JS_SetCanBlock(rt, TRUE);
3371
3372 js_std_add_helpers(ctx, -1, NULL);
3373
3374 promise = JS_LoadModule(ctx, args->basename, args->filename);
3375 if (JS_IsException(promise))
3376 js_std_dump_error(ctx);
3377 /* XXX: check */
3378 JS_FreeValue(ctx, promise);
3379 free(args->filename);
3380 free(args->basename);
3381 free(args);
3382
3383 js_std_loop(ctx);
3384
3385 JS_FreeContext(ctx);
3386 js_std_free_handlers(rt);
3387 JS_FreeRuntime(rt);
3388 return NULL;
3389 }
3390
3391 static JSValue js_worker_ctor_internal(JSContext *ctx, JSValueConst new_target,
3392 JSWorkerMessagePipe *recv_pipe,
3393 JSWorkerMessagePipe *send_pipe)
3394 {
3395 JSValue obj = JS_UNDEFINED, proto;
3396 JSWorkerData *s;
3397
3398 /* create the object */
3399 if (JS_IsUndefined(new_target)) {
3400 proto = JS_GetClassProto(ctx, js_worker_class_id);
3401 } else {
3402 proto = JS_GetPropertyStr(ctx, new_target, "prototype");
3403 if (JS_IsException(proto))
3404 goto fail;
3405 }
3406 obj = JS_NewObjectProtoClass(ctx, proto, js_worker_class_id);
3407 JS_FreeValue(ctx, proto);
3408 if (JS_IsException(obj))
3409 goto fail;
3410 s = js_mallocz(ctx, sizeof(*s));
3411 if (!s)
3412 goto fail;
3413 s->recv_pipe = js_dup_message_pipe(recv_pipe);
3414 s->send_pipe = js_dup_message_pipe(send_pipe);
3415
3416 JS_SetOpaque(obj, s);
3417 return obj;
3418 fail:
3419 JS_FreeValue(ctx, obj);
3420 return JS_EXCEPTION;
3421 }
3422
3423 static JSValue js_worker_ctor(JSContext *ctx, JSValueConst new_target,
3424 int argc, JSValueConst *argv)
3425 {
3426 JSRuntime *rt = JS_GetRuntime(ctx);
3427 WorkerFuncArgs *args = NULL;
3428 pthread_t tid;
3429 pthread_attr_t attr;
3430 JSValue obj = JS_UNDEFINED;
3431 int ret;
3432 const char *filename = NULL, *basename;
3433 JSAtom basename_atom;
3434
3435 /* XXX: in order to avoid problems with resource liberation, we
3436 don't support creating workers inside workers */
3437 if (!is_main_thread(rt))
3438 return JS_ThrowTypeError(ctx, "cannot create a worker inside a worker");
3439
3440 /* base name, assuming the calling function is a normal JS
3441 function */
3442 basename_atom = JS_GetScriptOrModuleName(ctx, 1);
3443 if (basename_atom == JS_ATOM_NULL) {
3444 return JS_ThrowTypeError(ctx, "could not determine calling script or module name");
3445 }
3446 basename = JS_AtomToCString(ctx, basename_atom);
3447 JS_FreeAtom(ctx, basename_atom);
3448 if (!basename)
3449 goto fail;
3450
3451 /* module name */
3452 filename = JS_ToCString(ctx, argv[0]);
3453 if (!filename)
3454 goto fail;
3455
3456 args = malloc(sizeof(*args));
3457 if (!args)
3458 goto oom_fail;
3459 memset(args, 0, sizeof(*args));
3460 args->filename = strdup(filename);
3461 args->basename = strdup(basename);
3462
3463 /* ports */
3464 args->recv_pipe = js_new_message_pipe();
3465 if (!args->recv_pipe)
3466 goto oom_fail;
3467 args->send_pipe = js_new_message_pipe();
3468 if (!args->send_pipe)
3469 goto oom_fail;
3470
3471 obj = js_worker_ctor_internal(ctx, new_target,
3472 args->send_pipe, args->recv_pipe);
3473 if (JS_IsException(obj))
3474 goto fail;
3475
3476 pthread_attr_init(&attr);
3477 /* no join at the end */
3478 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3479 ret = pthread_create(&tid, &attr, worker_func, args);
3480 pthread_attr_destroy(&attr);
3481 if (ret != 0) {
3482 JS_ThrowTypeError(ctx, "could not create worker");
3483 goto fail;
3484 }
3485 JS_FreeCString(ctx, basename);
3486 JS_FreeCString(ctx, filename);
3487 return obj;
3488 oom_fail:
3489 JS_ThrowOutOfMemory(ctx);
3490 fail:
3491 JS_FreeCString(ctx, basename);
3492 JS_FreeCString(ctx, filename);
3493 if (args) {
3494 free(args->filename);
3495 free(args->basename);
3496 js_free_message_pipe(args->recv_pipe);
3497 js_free_message_pipe(args->send_pipe);
3498 free(args);
3499 }
3500 JS_FreeValue(ctx, obj);
3501 return JS_EXCEPTION;
3502 }
3503
3504 static JSValue js_worker_postMessage(JSContext *ctx, JSValueConst this_val,
3505 int argc, JSValueConst *argv)
3506 {
3507 JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);
3508 JSWorkerMessagePipe *ps;
3509 size_t data_len, sab_tab_len, i;
3510 uint8_t *data;
3511 JSWorkerMessage *msg;
3512 uint8_t **sab_tab;
3513
3514 if (!worker)
3515 return JS_EXCEPTION;
3516
3517 data = JS_WriteObject2(ctx, &data_len, argv[0],
3518 JS_WRITE_OBJ_SAB | JS_WRITE_OBJ_REFERENCE,
3519 &sab_tab, &sab_tab_len);
3520 if (!data)
3521 return JS_EXCEPTION;
3522
3523 msg = malloc(sizeof(*msg));
3524 if (!msg)
3525 goto fail;
3526 msg->data = NULL;
3527 msg->sab_tab = NULL;
3528
3529 /* must reallocate because the allocator may be different */
3530 msg->data = malloc(data_len);
3531 if (!msg->data)
3532 goto fail;
3533 memcpy(msg->data, data, data_len);
3534 msg->data_len = data_len;
3535
3536 msg->sab_tab = malloc(sizeof(msg->sab_tab[0]) * sab_tab_len);
3537 if (!msg->sab_tab)
3538 goto fail;
3539 memcpy(msg->sab_tab, sab_tab, sizeof(msg->sab_tab[0]) * sab_tab_len);
3540 msg->sab_tab_len = sab_tab_len;
3541
3542 js_free(ctx, data);
3543 js_free(ctx, sab_tab);
3544
3545 /* increment the SAB reference counts */
3546 for(i = 0; i < msg->sab_tab_len; i++) {
3547 js_sab_dup(NULL, msg->sab_tab[i]);
3548 }
3549
3550 ps = worker->send_pipe;
3551 pthread_mutex_lock(&ps->mutex);
3552 /* indicate that data is present */
3553 if (list_empty(&ps->msg_queue)) {
3554 uint8_t ch = '\0';
3555 int ret;
3556 for(;;) {
3557 ret = write(ps->write_fd, &ch, 1);
3558 if (ret == 1)
3559 break;
3560 if (ret < 0 && (errno != EAGAIN || errno != EINTR))
3561 break;
3562 }
3563 }
3564 list_add_tail(&msg->link, &ps->msg_queue);
3565 pthread_mutex_unlock(&ps->mutex);
3566 return JS_UNDEFINED;
3567 fail:
3568 if (msg) {
3569 free(msg->data);
3570 free(msg->sab_tab);
3571 free(msg);
3572 }
3573 js_free(ctx, data);
3574 js_free(ctx, sab_tab);
3575 return JS_EXCEPTION;
3576
3577 }
3578
3579 static JSValue js_worker_set_onmessage(JSContext *ctx, JSValueConst this_val,
3580 JSValueConst func)
3581 {
3582 JSRuntime *rt = JS_GetRuntime(ctx);
3583 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
3584 JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);
3585 JSWorkerMessageHandler *port;
3586
3587 if (!worker)
3588 return JS_EXCEPTION;
3589
3590 port = worker->msg_handler;
3591 if (JS_IsNull(func)) {
3592 if (port) {
3593 js_free_port(rt, port);
3594 worker->msg_handler = NULL;
3595 }
3596 } else {
3597 if (!JS_IsFunction(ctx, func))
3598 return JS_ThrowTypeError(ctx, "not a function");
3599 if (!port) {
3600 port = js_mallocz(ctx, sizeof(*port));
3601 if (!port)
3602 return JS_EXCEPTION;
3603 port->recv_pipe = js_dup_message_pipe(worker->recv_pipe);
3604 port->on_message_func = JS_NULL;
3605 list_add_tail(&port->link, &ts->port_list);
3606 worker->msg_handler = port;
3607 }
3608 JS_FreeValue(ctx, port->on_message_func);
3609 port->on_message_func = JS_DupValue(ctx, func);
3610 }
3611 return JS_UNDEFINED;
3612 }
3613
3614 static JSValue js_worker_get_onmessage(JSContext *ctx, JSValueConst this_val)
3615 {
3616 JSWorkerData *worker = JS_GetOpaque2(ctx, this_val, js_worker_class_id);
3617 JSWorkerMessageHandler *port;
3618 if (!worker)
3619 return JS_EXCEPTION;
3620 port = worker->msg_handler;
3621 if (port) {
3622 return JS_DupValue(ctx, port->on_message_func);
3623 } else {
3624 return JS_NULL;
3625 }
3626 }
3627
3628 static const JSCFunctionListEntry js_worker_proto_funcs[] = {
3629 JS_CFUNC_DEF("postMessage", 1, js_worker_postMessage ),
3630 JS_CGETSET_DEF("onmessage", js_worker_get_onmessage, js_worker_set_onmessage ),
3631 };
3632
3633 #endif /* USE_WORKER */
3634
3635 void js_std_set_worker_new_context_func(JSContext *(*func)(JSRuntime *rt))
3636 {
3637 #ifdef USE_WORKER
3638 js_worker_new_context_func = func;
3639 #endif
3640 }
3641
3642 #if defined(_WIN32)
3643 #define OS_PLATFORM "win32"
3644 #elif defined(__APPLE__)
3645 #define OS_PLATFORM "darwin"
3646 #elif defined(EMSCRIPTEN)
3647 #define OS_PLATFORM "js"
3648 #else
3649 #define OS_PLATFORM "linux"
3650 #endif
3651
3652 #define OS_FLAG(x) JS_PROP_INT32_DEF(#x, x, JS_PROP_CONFIGURABLE )
3653
3654 static const JSCFunctionListEntry js_os_funcs[] = {
3655 JS_CFUNC_DEF("open", 2, js_os_open ),
3656 OS_FLAG(O_RDONLY),
3657 OS_FLAG(O_WRONLY),
3658 OS_FLAG(O_RDWR),
3659 OS_FLAG(O_APPEND),
3660 OS_FLAG(O_CREAT),
3661 OS_FLAG(O_EXCL),
3662 OS_FLAG(O_TRUNC),
3663 #if defined(_WIN32)
3664 OS_FLAG(O_BINARY),
3665 OS_FLAG(O_TEXT),
3666 #endif
3667 JS_CFUNC_DEF("close", 1, js_os_close ),
3668 JS_CFUNC_DEF("seek", 3, js_os_seek ),
3669 JS_CFUNC_MAGIC_DEF("read", 4, js_os_read_write, 0 ),
3670 JS_CFUNC_MAGIC_DEF("write", 4, js_os_read_write, 1 ),
3671 JS_CFUNC_DEF("isatty", 1, js_os_isatty ),
3672 JS_CFUNC_DEF("ttyGetWinSize", 1, js_os_ttyGetWinSize ),
3673 JS_CFUNC_DEF("ttySetRaw", 1, js_os_ttySetRaw ),
3674 JS_CFUNC_DEF("remove", 1, js_os_remove ),
3675 JS_CFUNC_DEF("rename", 2, js_os_rename ),
3676 JS_CFUNC_MAGIC_DEF("setReadHandler", 2, js_os_setReadHandler, 0 ),
3677 JS_CFUNC_MAGIC_DEF("setWriteHandler", 2, js_os_setReadHandler, 1 ),
3678 JS_CFUNC_DEF("signal", 2, js_os_signal ),
3679 OS_FLAG(SIGINT),
3680 OS_FLAG(SIGABRT),
3681 OS_FLAG(SIGFPE),
3682 OS_FLAG(SIGILL),
3683 OS_FLAG(SIGSEGV),
3684 OS_FLAG(SIGTERM),
3685 #if !defined(_WIN32)
3686 OS_FLAG(SIGQUIT),
3687 OS_FLAG(SIGPIPE),
3688 OS_FLAG(SIGALRM),
3689 OS_FLAG(SIGUSR1),
3690 OS_FLAG(SIGUSR2),
3691 OS_FLAG(SIGCHLD),
3692 OS_FLAG(SIGCONT),
3693 OS_FLAG(SIGSTOP),
3694 OS_FLAG(SIGTSTP),
3695 OS_FLAG(SIGTTIN),
3696 OS_FLAG(SIGTTOU),
3697 #endif
3698 JS_CFUNC_DEF("now", 0, js_os_now ),
3699 JS_CFUNC_DEF("setTimeout", 2, js_os_setTimeout ),
3700 JS_CFUNC_DEF("clearTimeout", 1, js_os_clearTimeout ),
3701 JS_CFUNC_DEF("sleepAsync", 1, js_os_sleepAsync ),
3702 JS_PROP_STRING_DEF("platform", OS_PLATFORM, 0 ),
3703 JS_CFUNC_DEF("getcwd", 0, js_os_getcwd ),
3704 JS_CFUNC_DEF("chdir", 0, js_os_chdir ),
3705 JS_CFUNC_DEF("mkdir", 1, js_os_mkdir ),
3706 JS_CFUNC_DEF("readdir", 1, js_os_readdir ),
3707 /* st_mode constants */
3708 OS_FLAG(S_IFMT),
3709 OS_FLAG(S_IFIFO),
3710 OS_FLAG(S_IFCHR),
3711 OS_FLAG(S_IFDIR),
3712 OS_FLAG(S_IFBLK),
3713 OS_FLAG(S_IFREG),
3714 #if !defined(_WIN32)
3715 OS_FLAG(S_IFSOCK),
3716 OS_FLAG(S_IFLNK),
3717 OS_FLAG(S_ISGID),
3718 OS_FLAG(S_ISUID),
3719 #endif
3720 JS_CFUNC_MAGIC_DEF("stat", 1, js_os_stat, 0 ),
3721 JS_CFUNC_DEF("utimes", 3, js_os_utimes ),
3722 JS_CFUNC_DEF("sleep", 1, js_os_sleep ),
3723 JS_CFUNC_DEF("realpath", 1, js_os_realpath ),
3724 #if !defined(_WIN32)
3725 JS_CFUNC_MAGIC_DEF("lstat", 1, js_os_stat, 1 ),
3726 JS_CFUNC_DEF("symlink", 2, js_os_symlink ),
3727 JS_CFUNC_DEF("readlink", 1, js_os_readlink ),
3728 JS_CFUNC_DEF("exec", 1, js_os_exec ),
3729 JS_CFUNC_DEF("getpid", 0, js_os_getpid ),
3730 JS_CFUNC_DEF("waitpid", 2, js_os_waitpid ),
3731 OS_FLAG(WNOHANG),
3732 JS_CFUNC_DEF("pipe", 0, js_os_pipe ),
3733 JS_CFUNC_DEF("kill", 2, js_os_kill ),
3734 JS_CFUNC_DEF("dup", 1, js_os_dup ),
3735 JS_CFUNC_DEF("dup2", 2, js_os_dup2 ),
3736 #endif
3737 };
3738
3739 static int js_os_init(JSContext *ctx, JSModuleDef *m)
3740 {
3741 os_poll_func = js_os_poll;
3742
3743 /* OSTimer class */
3744 JS_NewClassID(&js_os_timer_class_id);
3745 JS_NewClass(JS_GetRuntime(ctx), js_os_timer_class_id, &js_os_timer_class);
3746
3747 #ifdef USE_WORKER
3748 {
3749 JSRuntime *rt = JS_GetRuntime(ctx);
3750 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
3751 JSValue proto, obj;
3752 /* Worker class */
3753 JS_NewClassID(&js_worker_class_id);
3754 JS_NewClass(JS_GetRuntime(ctx), js_worker_class_id, &js_worker_class);
3755 proto = JS_NewObject(ctx);
3756 JS_SetPropertyFunctionList(ctx, proto, js_worker_proto_funcs, countof(js_worker_proto_funcs));
3757
3758 obj = JS_NewCFunction2(ctx, js_worker_ctor, "Worker", 1,
3759 JS_CFUNC_constructor, 0);
3760 JS_SetConstructor(ctx, obj, proto);
3761
3762 JS_SetClassProto(ctx, js_worker_class_id, proto);
3763
3764 /* set 'Worker.parent' if necessary */
3765 if (ts->recv_pipe && ts->send_pipe) {
3766 JS_DefinePropertyValueStr(ctx, obj, "parent",
3767 js_worker_ctor_internal(ctx, JS_UNDEFINED, ts->recv_pipe, ts->send_pipe),
3768 JS_PROP_C_W_E);
3769 }
3770
3771 JS_SetModuleExport(ctx, m, "Worker", obj);
3772 }
3773 #endif /* USE_WORKER */
3774
3775 return JS_SetModuleExportList(ctx, m, js_os_funcs,
3776 countof(js_os_funcs));
3777 }
3778
3779 JSModuleDef *js_init_module_os(JSContext *ctx, const char *module_name)
3780 {
3781 JSModuleDef *m;
3782 m = JS_NewCModule(ctx, module_name, js_os_init);
3783 if (!m)
3784 return NULL;
3785 JS_AddModuleExportList(ctx, m, js_os_funcs, countof(js_os_funcs));
3786 #ifdef USE_WORKER
3787 JS_AddModuleExport(ctx, m, "Worker");
3788 #endif
3789 return m;
3790 }
3791
3792 /**********************************************************/
3793
3794 static JSValue js_print(JSContext *ctx, JSValueConst this_val,
3795 int argc, JSValueConst *argv)
3796 {
3797 int i;
3798 const char *str;
3799 size_t len;
3800
3801 for(i = 0; i < argc; i++) {
3802 if (i != 0)
3803 putchar(' ');
3804 str = JS_ToCStringLen(ctx, &len, argv[i]);
3805 if (!str)
3806 return JS_EXCEPTION;
3807 fwrite(str, 1, len, stdout);
3808 JS_FreeCString(ctx, str);
3809 }
3810 putchar('\n');
3811 return JS_UNDEFINED;
3812 }
3813
3814 void js_std_add_helpers(JSContext *ctx, int argc, char **argv)
3815 {
3816 JSValue global_obj, console, args;
3817 int i;
3818
3819 /* XXX: should these global definitions be enumerable? */
3820 global_obj = JS_GetGlobalObject(ctx);
3821
3822 console = JS_NewObject(ctx);
3823 JS_SetPropertyStr(ctx, console, "log",
3824 JS_NewCFunction(ctx, js_print, "log", 1));
3825 JS_SetPropertyStr(ctx, global_obj, "console", console);
3826
3827 /* same methods as the mozilla JS shell */
3828 if (argc >= 0) {
3829 args = JS_NewArray(ctx);
3830 for(i = 0; i < argc; i++) {
3831 JS_SetPropertyUint32(ctx, args, i, JS_NewString(ctx, argv[i]));
3832 }
3833 JS_SetPropertyStr(ctx, global_obj, "scriptArgs", args);
3834 }
3835
3836 JS_SetPropertyStr(ctx, global_obj, "print",
3837 JS_NewCFunction(ctx, js_print, "print", 1));
3838 JS_SetPropertyStr(ctx, global_obj, "__loadScript",
3839 JS_NewCFunction(ctx, js_loadScript, "__loadScript", 1));
3840
3841 JS_FreeValue(ctx, global_obj);
3842 }
3843
3844 void js_std_init_handlers(JSRuntime *rt)
3845 {
3846 JSThreadState *ts;
3847
3848 ts = malloc(sizeof(*ts));
3849 if (!ts) {
3850 fprintf(stderr, "Could not allocate memory for the worker");
3851 exit(1);
3852 }
3853 memset(ts, 0, sizeof(*ts));
3854 init_list_head(&ts->os_rw_handlers);
3855 init_list_head(&ts->os_signal_handlers);
3856 init_list_head(&ts->os_timers);
3857 init_list_head(&ts->port_list);
3858
3859 JS_SetRuntimeOpaque(rt, ts);
3860
3861 #ifdef USE_WORKER
3862 /* set the SharedArrayBuffer memory handlers */
3863 {
3864 JSSharedArrayBufferFunctions sf;
3865 memset(&sf, 0, sizeof(sf));
3866 sf.sab_alloc = js_sab_alloc;
3867 sf.sab_free = js_sab_free;
3868 sf.sab_dup = js_sab_dup;
3869 JS_SetSharedArrayBufferFunctions(rt, &sf);
3870 }
3871 #endif
3872 }
3873
3874 void js_std_free_handlers(JSRuntime *rt)
3875 {
3876 JSThreadState *ts = JS_GetRuntimeOpaque(rt);
3877 struct list_head *el, *el1;
3878
3879 list_for_each_safe(el, el1, &ts->os_rw_handlers) {
3880 JSOSRWHandler *rh = list_entry(el, JSOSRWHandler, link);
3881 free_rw_handler(rt, rh);
3882 }
3883
3884 list_for_each_safe(el, el1, &ts->os_signal_handlers) {
3885 JSOSSignalHandler *sh = list_entry(el, JSOSSignalHandler, link);
3886 free_sh(rt, sh);
3887 }
3888
3889 list_for_each_safe(el, el1, &ts->os_timers) {
3890 JSOSTimer *th = list_entry(el, JSOSTimer, link);
3891 unlink_timer(rt, th);
3892 if (!th->has_object)
3893 free_timer(rt, th);
3894 }
3895
3896 #ifdef USE_WORKER
3897 /* XXX: free port_list ? */
3898 js_free_message_pipe(ts->recv_pipe);
3899 js_free_message_pipe(ts->send_pipe);
3900 #endif
3901
3902 free(ts);
3903 JS_SetRuntimeOpaque(rt, NULL); /* fail safe */
3904 }
3905
3906 static void js_dump_obj(JSContext *ctx, FILE *f, JSValueConst val)
3907 {
3908 const char *str;
3909
3910 str = JS_ToCString(ctx, val);
3911 if (str) {
3912 fprintf(f, "%s\n", str);
3913 JS_FreeCString(ctx, str);
3914 } else {
3915 fprintf(f, "[exception]\n");
3916 }
3917 }
3918
3919 static void js_std_dump_error1(JSContext *ctx, JSValueConst exception_val)
3920 {
3921 JSValue val;
3922 BOOL is_error;
3923
3924 is_error = JS_IsError(ctx, exception_val);
3925 js_dump_obj(ctx, stderr, exception_val);
3926 if (is_error) {
3927 val = JS_GetPropertyStr(ctx, exception_val, "stack");
3928 if (!JS_IsUndefined(val)) {
3929 js_dump_obj(ctx, stderr, val);
3930 }
3931 JS_FreeValue(ctx, val);
3932 }
3933 }
3934
3935 void js_std_dump_error(JSContext *ctx)
3936 {
3937 JSValue exception_val;
3938
3939 exception_val = JS_GetException(ctx);
3940 js_std_dump_error1(ctx, exception_val);
3941 JS_FreeValue(ctx, exception_val);
3942 }
3943
3944 void js_std_promise_rejection_tracker(JSContext *ctx, JSValueConst promise,
3945 JSValueConst reason,
3946 BOOL is_handled, void *opaque)
3947 {
3948 if (!is_handled) {
3949 fprintf(stderr, "Possibly unhandled promise rejection: ");
3950 js_std_dump_error1(ctx, reason);
3951 }
3952 }
3953
3954 /* main loop which calls the user JS callbacks */
3955 void js_std_loop(JSContext *ctx)
3956 {
3957 JSContext *ctx1;
3958 int err;
3959
3960 for(;;) {
3961 /* execute the pending jobs */
3962 for(;;) {
3963 err = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);
3964 if (err <= 0) {
3965 if (err < 0) {
3966 js_std_dump_error(ctx1);
3967 }
3968 break;
3969 }
3970 }
3971
3972 if (!os_poll_func || os_poll_func(ctx))
3973 break;
3974 }
3975 }
3976
3977 void js_std_eval_binary(JSContext *ctx, const uint8_t *buf, size_t buf_len,
3978 int load_only)
3979 {
3980 JSValue obj, val;
3981 obj = JS_ReadObject(ctx, buf, buf_len, JS_READ_OBJ_BYTECODE);
3982 if (JS_IsException(obj))
3983 goto exception;
3984 if (load_only) {
3985 if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {
3986 js_module_set_import_meta(ctx, obj, FALSE, FALSE);
3987 }
3988 } else {
3989 if (JS_VALUE_GET_TAG(obj) == JS_TAG_MODULE) {
3990 if (JS_ResolveModule(ctx, obj) < 0) {
3991 JS_FreeValue(ctx, obj);
3992 goto exception;
3993 }
3994 js_module_set_import_meta(ctx, obj, FALSE, TRUE);
3995 }
3996 val = JS_EvalFunction(ctx, obj);
3997 if (JS_IsException(val)) {
3998 exception:
3999 js_std_dump_error(ctx);
4000 exit(1);
4001 }
4002 JS_FreeValue(ctx, val);
4003 }
4004 }