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