Debian Codegraph @

quickjs/qjs.c

raw symbols SCIP
1 /*
2 * QuickJS stand alone interpreter
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 <time.h>
35 #if defined(__APPLE__)
36 #include <malloc/malloc.h>
37 #elif defined(__linux__)
38 #include <malloc.h>
39 #endif
40
41 #include "cutils.h"
42 #include "quickjs-libc.h"
43
44 extern const uint8_t qjsc_repl[];
45 extern const uint32_t qjsc_repl_size;
46 #ifdef CONFIG_BIGNUM
47 extern const uint8_t qjsc_qjscalc[];
48 extern const uint32_t qjsc_qjscalc_size;
49 static int bignum_ext;
50 #endif
51
52 static int eval_buf(JSContext *ctx, const void *buf, int buf_len,
53 const char *filename, int eval_flags)
54 {
55 JSValue val;
56 int ret;
57
58 if ((eval_flags & JS_EVAL_TYPE_MASK) == JS_EVAL_TYPE_MODULE) {
59 /* for the modules, we compile then run to be able to set
60 import.meta */
61 val = JS_Eval(ctx, buf, buf_len, filename,
62 eval_flags | JS_EVAL_FLAG_COMPILE_ONLY);
63 if (!JS_IsException(val)) {
64 js_module_set_import_meta(ctx, val, TRUE, TRUE);
65 val = JS_EvalFunction(ctx, val);
66 }
67 } else {
68 val = JS_Eval(ctx, buf, buf_len, filename, eval_flags);
69 }
70 if (JS_IsException(val)) {
71 js_std_dump_error(ctx);
72 ret = -1;
73 } else {
74 ret = 0;
75 }
76 JS_FreeValue(ctx, val);
77 return ret;
78 }
79
80 static int eval_file(JSContext *ctx, const char *filename, int module)
81 {
82 uint8_t *buf;
83 int ret, eval_flags;
84 size_t buf_len;
85
86 buf = js_load_file(ctx, &buf_len, filename);
87 if (!buf) {
88 perror(filename);
89 exit(1);
90 }
91
92 if (module < 0) {
93 module = (has_suffix(filename, ".mjs") ||
94 JS_DetectModule((const char *)buf, buf_len));
95 }
96 if (module)
97 eval_flags = JS_EVAL_TYPE_MODULE;
98 else
99 eval_flags = JS_EVAL_TYPE_GLOBAL;
100 ret = eval_buf(ctx, buf, buf_len, filename, eval_flags);
101 js_free(ctx, buf);
102 return ret;
103 }
104
105 /* also used to initialize the worker context */
106 static JSContext *JS_NewCustomContext(JSRuntime *rt)
107 {
108 JSContext *ctx;
109 ctx = JS_NewContext(rt);
110 if (!ctx)
111 return NULL;
112 #ifdef CONFIG_BIGNUM
113 if (bignum_ext) {
114 JS_AddIntrinsicBigFloat(ctx);
115 JS_AddIntrinsicBigDecimal(ctx);
116 JS_AddIntrinsicOperators(ctx);
117 JS_EnableBignumExt(ctx, TRUE);
118 }
119 #endif
120 /* system modules */
121 js_init_module_std(ctx, "std");
122 js_init_module_os(ctx, "os");
123 return ctx;
124 }
125
126 #if defined(__APPLE__)
127 #define MALLOC_OVERHEAD 0
128 #else
129 #define MALLOC_OVERHEAD 8
130 #endif
131
132 struct trace_malloc_data {
133 uint8_t *base;
134 };
135
136 static inline unsigned long long js_trace_malloc_ptr_offset(uint8_t *ptr,
137 struct trace_malloc_data *dp)
138 {
139 return ptr - dp->base;
140 }
141
142 /* default memory allocation functions with memory limitation */
143 static size_t js_trace_malloc_usable_size(const void *ptr)
144 {
145 #if defined(__APPLE__)
146 return malloc_size(ptr);
147 #elif defined(_WIN32)
148 return _msize((void *)ptr);
149 #elif defined(EMSCRIPTEN)
150 return 0;
151 #elif defined(__linux__)
152 return malloc_usable_size((void *)ptr);
153 #else
154 /* change this to `return 0;` if compilation fails */
155 return malloc_usable_size((void *)ptr);
156 #endif
157 }
158
159 static void
160 #ifdef _WIN32
161 /* mingw printf is used */
162 __attribute__((format(gnu_printf, 2, 3)))
163 #else
164 __attribute__((format(printf, 2, 3)))
165 #endif
166 js_trace_malloc_printf(JSMallocState *s, const char *fmt, ...)
167 {
168 va_list ap;
169 int c;
170
171 va_start(ap, fmt);
172 while ((c = *fmt++) != '\0') {
173 if (c == '%') {
174 /* only handle %p and %zd */
175 if (*fmt == 'p') {
176 uint8_t *ptr = va_arg(ap, void *);
177 if (ptr == NULL) {
178 printf("NULL");
179 } else {
180 printf("H%+06lld.%zd",
181 js_trace_malloc_ptr_offset(ptr, s->opaque),
182 js_trace_malloc_usable_size(ptr));
183 }
184 fmt++;
185 continue;
186 }
187 if (fmt[0] == 'z' && fmt[1] == 'd') {
188 size_t sz = va_arg(ap, size_t);
189 printf("%zd", sz);
190 fmt += 2;
191 continue;
192 }
193 }
194 putc(c, stdout);
195 }
196 va_end(ap);
197 }
198
199 static void js_trace_malloc_init(struct trace_malloc_data *s)
200 {
201 free(s->base = malloc(8));
202 }
203
204 static void *js_trace_malloc(JSMallocState *s, size_t size)
205 {
206 void *ptr;
207
208 /* Do not allocate zero bytes: behavior is platform dependent */
209 assert(size != 0);
210
211 if (unlikely(s->malloc_size + size > s->malloc_limit))
212 return NULL;
213 ptr = malloc(size);
214 js_trace_malloc_printf(s, "A %zd -> %p\n", size, ptr);
215 if (ptr) {
216 s->malloc_count++;
217 s->malloc_size += js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD;
218 }
219 return ptr;
220 }
221
222 static void js_trace_free(JSMallocState *s, void *ptr)
223 {
224 if (!ptr)
225 return;
226
227 js_trace_malloc_printf(s, "F %p\n", ptr);
228 s->malloc_count--;
229 s->malloc_size -= js_trace_malloc_usable_size(ptr) + MALLOC_OVERHEAD;
230 free(ptr);
231 }
232
233 static void *js_trace_realloc(JSMallocState *s, void *ptr, size_t size)
234 {
235 size_t old_size;
236
237 if (!ptr) {
238 if (size == 0)
239 return NULL;
240 return js_trace_malloc(s, size);
241 }
242 old_size = js_trace_malloc_usable_size(ptr);
243 if (size == 0) {
244 js_trace_malloc_printf(s, "R %zd %p\n", size, ptr);
245 s->malloc_count--;
246 s->malloc_size -= old_size + MALLOC_OVERHEAD;
247 free(ptr);
248 return NULL;
249 }
250 if (s->malloc_size + size - old_size > s->malloc_limit)
251 return NULL;
252
253 js_trace_malloc_printf(s, "R %zd %p", size, ptr);
254
255 ptr = realloc(ptr, size);
256 js_trace_malloc_printf(s, " -> %p\n", ptr);
257 if (ptr) {
258 s->malloc_size += js_trace_malloc_usable_size(ptr) - old_size;
259 }
260 return ptr;
261 }
262
263 static const JSMallocFunctions trace_mf = {
264 js_trace_malloc,
265 js_trace_free,
266 js_trace_realloc,
267 js_trace_malloc_usable_size,
268 };
269
270 #define PROG_NAME "qjs"
271
272 void help(void)
273 {
274 printf("QuickJS version " CONFIG_VERSION "\n"
275 "usage: " PROG_NAME " [options] [file [args]]\n"
276 "-h --help list options\n"
277 "-e --eval EXPR evaluate EXPR\n"
278 "-i --interactive go to interactive mode\n"
279 "-m --module load as ES6 module (default=autodetect)\n"
280 " --script load as ES6 script (default=autodetect)\n"
281 "-I --include file include an additional file\n"
282 " --std make 'std' and 'os' available to the loaded script\n"
283 #ifdef CONFIG_BIGNUM
284 " --bignum enable the bignum extensions (BigFloat, BigDecimal)\n"
285 " --qjscalc load the QJSCalc runtime (default if invoked as qjscalc)\n"
286 #endif
287 "-T --trace trace memory allocation\n"
288 "-d --dump dump the memory usage stats\n"
289 " --memory-limit n limit the memory usage to 'n' bytes\n"
290 " --stack-size n limit the stack size to 'n' bytes\n"
291 " --unhandled-rejection dump unhandled promise rejections\n"
292 "-q --quit just instantiate the interpreter and quit\n");
293 exit(1);
294 }
295
296 int main(int argc, char **argv)
297 {
298 JSRuntime *rt;
299 JSContext *ctx;
300 struct trace_malloc_data trace_data = { NULL };
301 int optind;
302 char *expr = NULL;
303 int interactive = 0;
304 int dump_memory = 0;
305 int trace_memory = 0;
306 int empty_run = 0;
307 int module = -1;
308 int load_std = 0;
309 int dump_unhandled_promise_rejection = 0;
310 size_t memory_limit = 0;
311 char *include_list[32];
312 int i, include_count = 0;
313 #ifdef CONFIG_BIGNUM
314 int load_jscalc;
315 #endif
316 size_t stack_size = 0;
317
318 #ifdef CONFIG_BIGNUM
319 /* load jscalc runtime if invoked as 'qjscalc' */
320 {
321 const char *p, *exename;
322 exename = argv[0];
323 p = strrchr(exename, '/');
324 if (p)
325 exename = p + 1;
326 load_jscalc = !strcmp(exename, "qjscalc");
327 }
328 #endif
329
330 /* cannot use getopt because we want to pass the command line to
331 the script */
332 optind = 1;
333 while (optind < argc && *argv[optind] == '-') {
334 char *arg = argv[optind] + 1;
335 const char *longopt = "";
336 /* a single - is not an option, it also stops argument scanning */
337 if (!*arg)
338 break;
339 optind++;
340 if (*arg == '-') {
341 longopt = arg + 1;
342 arg += strlen(arg);
343 /* -- stops argument scanning */
344 if (!*longopt)
345 break;
346 }
347 for (; *arg || *longopt; longopt = "") {
348 char opt = *arg;
349 if (opt)
350 arg++;
351 if (opt == 'h' || opt == '?' || !strcmp(longopt, "help")) {
352 help();
353 continue;
354 }
355 if (opt == 'e' || !strcmp(longopt, "eval")) {
356 if (*arg) {
357 expr = arg;
358 break;
359 }
360 if (optind < argc) {
361 expr = argv[optind++];
362 break;
363 }
364 fprintf(stderr, "qjs: missing expression for -e\n");
365 exit(2);
366 }
367 if (opt == 'I' || !strcmp(longopt, "include")) {
368 if (optind >= argc) {
369 fprintf(stderr, "expecting filename");
370 exit(1);
371 }
372 if (include_count >= countof(include_list)) {
373 fprintf(stderr, "too many included files");
374 exit(1);
375 }
376 include_list[include_count++] = argv[optind++];
377 continue;
378 }
379 if (opt == 'i' || !strcmp(longopt, "interactive")) {
380 interactive++;
381 continue;
382 }
383 if (opt == 'm' || !strcmp(longopt, "module")) {
384 module = 1;
385 continue;
386 }
387 if (!strcmp(longopt, "script")) {
388 module = 0;
389 continue;
390 }
391 if (opt == 'd' || !strcmp(longopt, "dump")) {
392 dump_memory++;
393 continue;
394 }
395 if (opt == 'T' || !strcmp(longopt, "trace")) {
396 trace_memory++;
397 continue;
398 }
399 if (!strcmp(longopt, "std")) {
400 load_std = 1;
401 continue;
402 }
403 if (!strcmp(longopt, "unhandled-rejection")) {
404 dump_unhandled_promise_rejection = 1;
405 continue;
406 }
407 #ifdef CONFIG_BIGNUM
408 if (!strcmp(longopt, "bignum")) {
409 bignum_ext = 1;
410 continue;
411 }
412 if (!strcmp(longopt, "qjscalc")) {
413 load_jscalc = 1;
414 continue;
415 }
416 #endif
417 if (opt == 'q' || !strcmp(longopt, "quit")) {
418 empty_run++;
419 continue;
420 }
421 if (!strcmp(longopt, "memory-limit")) {
422 if (optind >= argc) {
423 fprintf(stderr, "expecting memory limit");
424 exit(1);
425 }
426 memory_limit = (size_t)strtod(argv[optind++], NULL);
427 continue;
428 }
429 if (!strcmp(longopt, "stack-size")) {
430 if (optind >= argc) {
431 fprintf(stderr, "expecting stack size");
432 exit(1);
433 }
434 stack_size = (size_t)strtod(argv[optind++], NULL);
435 continue;
436 }
437 if (opt) {
438 fprintf(stderr, "qjs: unknown option '-%c'\n", opt);
439 } else {
440 fprintf(stderr, "qjs: unknown option '--%s'\n", longopt);
441 }
442 help();
443 }
444 }
445
446 #ifdef CONFIG_BIGNUM
447 if (load_jscalc)
448 bignum_ext = 1;
449 #endif
450
451 if (trace_memory) {
452 js_trace_malloc_init(&trace_data);
453 rt = JS_NewRuntime2(&trace_mf, &trace_data);
454 } else {
455 rt = JS_NewRuntime();
456 }
457 if (!rt) {
458 fprintf(stderr, "qjs: cannot allocate JS runtime\n");
459 exit(2);
460 }
461 if (memory_limit != 0)
462 JS_SetMemoryLimit(rt, memory_limit);
463 if (stack_size != 0)
464 JS_SetMaxStackSize(rt, stack_size);
465 js_std_set_worker_new_context_func(JS_NewCustomContext);
466 js_std_init_handlers(rt);
467 ctx = JS_NewCustomContext(rt);
468 if (!ctx) {
469 fprintf(stderr, "qjs: cannot allocate JS context\n");
470 exit(2);
471 }
472
473 /* loader for ES6 modules */
474 JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);
475
476 if (dump_unhandled_promise_rejection) {
477 JS_SetHostPromiseRejectionTracker(rt, js_std_promise_rejection_tracker,
478 NULL);
479 }
480
481 if (!empty_run) {
482 #ifdef CONFIG_BIGNUM
483 if (load_jscalc) {
484 js_std_eval_binary(ctx, qjsc_qjscalc, qjsc_qjscalc_size, 0);
485 }
486 #endif
487 js_std_add_helpers(ctx, argc - optind, argv + optind);
488
489 /* make 'std' and 'os' visible to non module code */
490 if (load_std) {
491 const char *str = "import * as std from 'std';\n"
492 "import * as os from 'os';\n"
493 "globalThis.std = std;\n"
494 "globalThis.os = os;\n";
495 eval_buf(ctx, str, strlen(str), "<input>", JS_EVAL_TYPE_MODULE);
496 }
497
498 for(i = 0; i < include_count; i++) {
499 if (eval_file(ctx, include_list[i], module))
500 goto fail;
501 }
502
503 if (expr) {
504 if (eval_buf(ctx, expr, strlen(expr), "<cmdline>", 0))
505 goto fail;
506 } else
507 if (optind >= argc) {
508 /* interactive mode */
509 interactive = 1;
510 } else {
511 const char *filename;
512 filename = argv[optind];
513 if (eval_file(ctx, filename, module))
514 goto fail;
515 }
516 if (interactive) {
517 js_std_eval_binary(ctx, qjsc_repl, qjsc_repl_size, 0);
518 }
519 js_std_loop(ctx);
520 }
521
522 if (dump_memory) {
523 JSMemoryUsage stats;
524 JS_ComputeMemoryUsage(rt, &stats);
525 JS_DumpMemoryUsage(stdout, &stats, rt);
526 }
527 js_std_free_handlers(rt);
528 JS_FreeContext(ctx);
529 JS_FreeRuntime(rt);
530
531 if (empty_run && dump_memory) {
532 clock_t t[5];
533 double best[5];
534 int i, j;
535 for (i = 0; i < 100; i++) {
536 t[0] = clock();
537 rt = JS_NewRuntime();
538 t[1] = clock();
539 ctx = JS_NewContext(rt);
540 t[2] = clock();
541 JS_FreeContext(ctx);
542 t[3] = clock();
543 JS_FreeRuntime(rt);
544 t[4] = clock();
545 for (j = 4; j > 0; j--) {
546 double ms = 1000.0 * (t[j] - t[j - 1]) / CLOCKS_PER_SEC;
547 if (i == 0 || best[j] > ms)
548 best[j] = ms;
549 }
550 }
551 printf("\nInstantiation times (ms): %.3f = %.3f+%.3f+%.3f+%.3f\n",
552 best[1] + best[2] + best[3] + best[4],
553 best[1], best[2], best[3], best[4]);
554 }
555 return 0;
556 fail:
557 js_std_free_handlers(rt);
558 JS_FreeContext(ctx);
559 JS_FreeRuntime(rt);
560 return 1;
561 }