-
Notifications
You must be signed in to change notification settings - Fork 514
/
duk_cmdline.c
1927 lines (1677 loc) · 50.2 KB
/
duk_cmdline.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Command line execution tool. Useful for test cases and manual testing.
* Also demonstrates some basic integration techniques.
*
* Optional features include:
*
* - To enable print()/alert() bindings, define DUK_CMDLINE_PRINTALERT_SUPPORT
* and add extras/print-alert/duk_print_alert.c to compilation.
*
* - To enable console.log() etc, define DUK_CMDLINE_CONSOLE_SUPPORT
* and add extras/console/duk_console.c to compilation.
*
* - To enable Duktape.Logger, define DUK_CMDLINE_LOGGING_SUPPORT
* and add extras/logging/duk_logging.c to compilation.
*
* - To enable Duktape 1.x module loading support (require(),
* Duktape.modSearch() etc), define DUK_CMDLINE_MODULE_SUPPORT and add
* extras/module-duktape/duk_module_duktape.c to compilation.
*
* - To enable linenoise and other fancy stuff, compile with -DDUK_CMDLINE_FANCY.
* It is not the default to maximize portability. You can also compile in
* support for example allocators, grep for DUK_CMDLINE_*.
*/
/* Helper define to enable a feature set; can also use separate defines. */
#if defined(DUK_CMDLINE_FANCY)
#define DUK_CMDLINE_LINENOISE
#define DUK_CMDLINE_LINENOISE_COMPLETION /* Enables completion and hints. */
#define DUK_CMDLINE_RLIMIT
#define DUK_CMDLINE_SIGNAL
#endif
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || \
defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
/* Suppress warnings about plain fopen() etc. */
#define _CRT_SECURE_NO_WARNINGS
#if defined(_MSC_VER) && (_MSC_VER < 1900)
/* Workaround for snprintf() missing in older MSVC versions.
* Note that _snprintf() may not NUL terminate the string, but
* this difference does not matter here as a NUL terminator is
* always explicitly added.
*/
#define snprintf _snprintf
#endif
#endif
#if defined(DUK_CMDLINE_PTHREAD_STACK_CHECK)
#define _GNU_SOURCE
#include <pthread.h>
#include <unistd.h>
#if defined(__linux)
#include <sys/syscall.h>
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(DUK_CMDLINE_SIGNAL)
#include <signal.h>
#endif
#if defined(DUK_CMDLINE_RLIMIT)
#include <sys/resource.h>
#endif
#if defined(DUK_CMDLINE_LINENOISE)
#include "linenoise.h"
#include <stdint.h> /* Assume C99/C++11 with linenoise. */
#endif
#if defined(DUK_CMDLINE_PRINTALERT_SUPPORT)
#include "duk_print_alert.h"
#endif
#if defined(DUK_CMDLINE_CONSOLE_SUPPORT)
#include "duk_console.h"
#endif
#if defined(DUK_CMDLINE_LOGGING_SUPPORT)
#include "duk_logging.h"
#endif
#if defined(DUK_CMDLINE_MODULE_SUPPORT)
#include "duk_module_duktape.h"
#endif
#if defined(DUK_CMDLINE_FILEIO)
#include <errno.h>
#endif
#if defined(EMSCRIPTEN)
#include <emscripten.h>
#endif
#if defined(DUK_CMDLINE_ALLOC_LOGGING)
#include "duk_alloc_logging.h"
#endif
#if defined(DUK_CMDLINE_ALLOC_TORTURE)
#include "duk_alloc_torture.h"
#endif
#if defined(DUK_CMDLINE_ALLOC_HYBRID)
#include "duk_alloc_hybrid.h"
#endif
#include "duktape.h"
#include "duk_cmdline.h"
#if defined(DUK_CMDLINE_LOWMEM)
#include "duk_alloc_pool.h"
#endif
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
#include "duk_trans_socket.h"
#endif
#if defined(DUK_USE_FUZZILLI)
/* REPRL Pipe file descriptors for quicker fuzzing. */
#define REPRL_CRFD 100
#define REPRL_CWFD 101
#define REPRL_DRFD 102
#define REPRL_DWFD 103
/* Required includes for coverage tracking. */
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#define MEM_LIMIT_NORMAL (128*1024*1024) /* 128 MB */
#define MEM_LIMIT_HIGH (2047*1024*1024) /* ~2 GB */
static int main_argc = 0;
static const char **main_argv = NULL;
static int interactive_mode = 0;
static int allow_bytecode = 0;
#if defined(DUK_CMDLINE_DEBUGGER_SUPPORT)
static int debugger_reattach = 0;
#endif
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
static int no_auto_complete = 0;
#endif
int duk_cmdline_stack_check(void);
/*
* Misc helpers
*/
static void print_greet_line(void) {
printf("((o) Duktape%s %d.%d.%d (%s)\n",
#if defined(DUK_CMDLINE_LINENOISE)
" [linenoise]",
#else
"",
#endif
(int) (DUK_VERSION / 10000),
(int) ((DUK_VERSION / 100) % 100),
(int) (DUK_VERSION % 100),
DUK_GIT_DESCRIBE);
}
#if defined(DUK_CMDLINE_RLIMIT)
static void set_resource_limits(rlim_t mem_limit_value) {
int rc;
struct rlimit lim;
rc = getrlimit(RLIMIT_AS, &lim);
if (rc != 0) {
fprintf(stderr, "Warning: cannot read RLIMIT_AS\n");
return;
}
if (lim.rlim_max < mem_limit_value) {
fprintf(stderr, "Warning: rlim_max < mem_limit_value (%d < %d)\n", (int) lim.rlim_max, (int) mem_limit_value);
return;
}
lim.rlim_cur = mem_limit_value;
lim.rlim_max = mem_limit_value;
rc = setrlimit(RLIMIT_AS, &lim);
if (rc != 0) {
fprintf(stderr, "Warning: setrlimit failed\n");
return;
}
#if 0
fprintf(stderr, "Set RLIMIT_AS to %d\n", (int) mem_limit_value);
#endif
}
#endif /* DUK_CMDLINE_RLIMIT */
#if defined(DUK_CMDLINE_SIGNAL)
static void my_sighandler(int x) {
fprintf(stderr, "Got signal %d\n", x);
fflush(stderr);
}
static void set_sigint_handler(void) {
(void) signal(SIGINT, my_sighandler);
(void) signal(SIGPIPE, SIG_IGN); /* avoid SIGPIPE killing process */
}
#endif /* DUK_CMDLINE_SIGNAL */
static void cmdline_fatal_handler(void *udata, const char *msg) {
(void) udata;
fprintf(stderr, "*** FATAL ERROR: %s\n", msg ? msg : "no message");
fprintf(stderr, "Causing intentional segfault...\n");
fflush(stderr);
*((volatile unsigned int *) 0) = (unsigned int) 0xdeadbeefUL;
abort();
}
/* Print error to stderr and pop error. */
static void print_pop_error(duk_context *ctx, FILE *f) {
fprintf(f, "%s\n", duk_safe_to_stacktrace(ctx, -1));
fflush(f);
duk_pop(ctx);
}
static duk_ret_t wrapped_compile_execute(duk_context *ctx, void *udata) {
const char *src_data;
duk_size_t src_len;
duk_uint_t comp_flags;
(void) udata;
/* XXX: Here it'd be nice to get some stats for the compilation result
* when a suitable command line is given (e.g. code size, constant
* count, function count. These are available internally but not through
* the public API.
*/
/* Use duk_compile_lstring_filename() variant which avoids interning
* the source code. This only really matters for low memory environments.
*/
/* [ ... bytecode_filename src_data src_len filename ] */
src_data = (const char *) duk_require_pointer(ctx, -3);
src_len = (duk_size_t) duk_require_uint(ctx, -2);
if (src_data != NULL && src_len >= 1 && src_data[0] == (char) 0xbf) {
/* Bytecode. */
if (allow_bytecode) {
void *buf;
buf = duk_push_fixed_buffer(ctx, src_len);
memcpy(buf, (const void *) src_data, src_len);
duk_load_function(ctx);
} else {
(void) duk_type_error(ctx, "bytecode input rejected (use -b to allow bytecode inputs)");
}
} else {
/* Source code. */
comp_flags = DUK_COMPILE_SHEBANG;
duk_compile_lstring_filename(ctx, comp_flags, src_data, src_len);
}
/* [ ... bytecode_filename src_data src_len function ] */
/* Optional bytecode dump. */
if (duk_is_string(ctx, -4)) {
FILE *f;
void *bc_ptr;
duk_size_t bc_len;
size_t wrote;
char fnbuf[256];
const char *filename;
duk_dup_top(ctx);
duk_dump_function(ctx);
bc_ptr = duk_require_buffer_data(ctx, -1, &bc_len);
filename = duk_require_string(ctx, -5);
#if defined(EMSCRIPTEN)
if (filename[0] == '/') {
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
} else {
snprintf(fnbuf, sizeof(fnbuf), "/working/%s", filename);
}
#else
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
#endif
fnbuf[sizeof(fnbuf) - 1] = (char) 0;
f = fopen(fnbuf, "wb");
if (!f) {
(void) duk_generic_error(ctx, "failed to open bytecode output file");
}
wrote = fwrite(bc_ptr, 1, (size_t) bc_len, f); /* XXX: handle partial writes */
(void) fclose(f);
if (wrote != bc_len) {
(void) duk_generic_error(ctx, "failed to write all bytecode");
}
return 0; /* duk_safe_call() cleans up */
}
#if 0
/* Manual test for bytecode dump/load cycle: dump and load before
* execution. Enable manually, then run "make ecmatest" for a
* reasonably good coverage of different functions and programs.
*/
duk_dump_function(ctx);
duk_load_function(ctx);
#endif
#if defined(DUK_CMDLINE_LOWMEM)
lowmem_start_exec_timeout();
#endif
duk_push_global_object(ctx); /* 'this' binding */
duk_call_method(ctx, 0);
#if defined(DUK_CMDLINE_LOWMEM)
lowmem_clear_exec_timeout();
#endif
if (interactive_mode) {
/*
* In interactive mode, write to stdout so output won't
* interleave as easily.
*
* NOTE: the ToString() coercion may fail in some cases;
* for instance, if you evaluate:
*
* ( {valueOf: function() {return {}},
* toString: function() {return {}}});
*
* The error is:
*
* TypeError: coercion to primitive failed
* duk_api.c:1420
*
* These are handled now by the caller which also has stack
* trace printing support. User code can print out errors
* safely using duk_safe_to_string().
*/
duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, "dukFormat");
duk_dup(ctx, -3);
duk_call(ctx, 1); /* -> [ ... res stash formatted ] */
fprintf(stdout, "= %s\n", duk_to_string(ctx, -1));
fflush(stdout);
} else {
/* In non-interactive mode, success results are not written at all.
* It is important that the result value is not string coerced,
* as the string coercion may cause an error in some cases.
*/
}
return 0; /* duk_safe_call() cleans up */
}
/*
* Minimal Linenoise completion support
*/
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
static duk_context *completion_ctx;
static const char *linenoise_completion_script =
"(function linenoiseCompletion(input, addCompletion) {\n"
" // Find maximal trailing string which looks like a property\n"
" // access. Look up all the components (starting from the global\n"
" // object now) except the last; treat the last component as a\n"
" // partial name and use it as a filter for possible properties.\n"
" var match, propseq, obj, i, partial, names, name, sanity;\n"
"\n"
" if (!input) { return; }\n"
" match = /^.*?((?:\\w+\\.)*\\w*)$/.exec(input);\n"
" if (!match || !match[1]) { return; }\n"
" var propseq = match[1].split('.');\n"
"\n"
" obj = Function('return this')();\n"
" for (i = 0; i < propseq.length - 1; i++) {\n"
" if (obj === void 0 || obj === null) { return; }\n"
" obj = obj[propseq[i]];\n"
" }\n"
" if (obj === void 0 || obj === null) { return; }\n"
"\n"
" partial = propseq[propseq.length - 1];\n"
" sanity = 1000;\n"
" while (obj != null) {\n"
" if (--sanity < 0) { throw new Error('sanity'); }\n"
" names = Object.getOwnPropertyNames(Object(obj));\n"
" for (i = 0; i < names.length; i++) {\n"
" if (--sanity < 0) { throw new Error('sanity'); }\n"
" name = names[i];\n"
" if (Number(name) >= 0) { continue; } // ignore array keys\n"
" if (name.substring(0, partial.length) !== partial) { continue; }\n"
" if (name === partial) { addCompletion(input + '.'); continue; }\n"
" addCompletion(input + name.substring(partial.length));\n"
" }\n"
" obj = Object.getPrototypeOf(Object(obj));\n"
" }\n"
"})";
static const char *linenoise_hints_script =
"(function linenoiseHints(input) {\n"
" // Similar to completions but different handling for final results.\n"
" var match, propseq, obj, i, partial, names, name, res, found, first, sanity;\n"
"\n"
" if (!input) { return; }\n"
" match = /^.*?((?:\\w+\\.)*\\w*)$/.exec(input);\n"
" if (!match || !match[1]) { return; }\n"
" var propseq = match[1].split('.');\n"
"\n"
" obj = Function('return this')();\n"
" for (i = 0; i < propseq.length - 1; i++) {\n"
" if (obj === void 0 || obj === null) { return; }\n"
" obj = obj[propseq[i]];\n"
" }\n"
" if (obj === void 0 || obj === null) { return; }\n"
"\n"
" partial = propseq[propseq.length - 1];\n"
" res = [];\n"
" found = Object.create(null); // keys already handled\n"
" sanity = 1000;\n"
" while (obj != null) {\n"
" if (--sanity < 0) { throw new Error('sanity'); }\n"
" names = Object.getOwnPropertyNames(Object(obj));\n"
" first = true;\n"
" for (i = 0; i < names.length; i++) {\n"
" if (--sanity < 0) { throw new Error('sanity'); }\n"
" name = names[i];\n"
" if (Number(name) >= 0) { continue; } // ignore array keys\n"
" if (name.substring(0, partial.length) !== partial) { continue; }\n"
" if (name === partial) { continue; }\n"
" if (found[name]) { continue; }\n"
" found[name] = true;\n"
" res.push(res.length === 0 ? name.substring(partial.length) : (first ? ' || ' : ' | ') + name);\n"
" first = false;\n"
" }\n"
" obj = Object.getPrototypeOf(Object(obj));\n"
" }\n"
" return { hints: res.join(''), color: 35, bold: 1 };\n"
"})";
static duk_ret_t linenoise_add_completion(duk_context *ctx) {
linenoiseCompletions *lc;
duk_push_current_function(ctx);
duk_get_prop_string(ctx, -1, "lc");
lc = duk_require_pointer(ctx, -1);
linenoiseAddCompletion(lc, duk_require_string(ctx, 0));
return 0;
}
static char *linenoise_hints(const char *buf, int *color, int *bold) {
duk_context *ctx;
duk_int_t rc;
ctx = completion_ctx;
if (!ctx) {
return NULL;
}
duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, "linenoiseHints");
if (!buf) {
duk_push_undefined(ctx);
} else {
duk_push_string(ctx, buf);
}
rc = duk_pcall(ctx, 1 /*nargs*/); /* [ stash func ] -> [ stash result ] */
if (rc != 0) {
const char *res;
res = strdup(duk_safe_to_string(ctx, -1));
*color = 31; /* red */
*bold = 1;
duk_pop_2(ctx);
return (char *) (uintptr_t) res; /* uintptr_t cast to avoid const discard warning. */
}
if (duk_is_object(ctx, -1)) {
const char *tmp;
const char *res = NULL;
duk_get_prop_string(ctx, -1, "hints");
tmp = duk_get_string(ctx, -1);
if (tmp) {
res = strdup(tmp);
}
duk_pop(ctx);
duk_get_prop_string(ctx, -1, "color");
*color = duk_to_int(ctx, -1);
duk_pop(ctx);
duk_get_prop_string(ctx, -1, "bold");
*bold = duk_to_int(ctx, -1);
duk_pop(ctx);
duk_pop_2(ctx);
return (char *) (uintptr_t) res; /* uintptr_t cast to avoid const discard warning. */
}
duk_pop_2(ctx);
return NULL;
}
static void linenoise_freehints(void *ptr) {
#if 0
printf("free hint: %p\n", (void *) ptr);
#endif
free(ptr);
}
static void linenoise_completion(const char *buf, linenoiseCompletions *lc) {
duk_context *ctx;
duk_int_t rc;
ctx = completion_ctx;
if (!ctx) {
return;
}
duk_push_global_stash(ctx);
duk_get_prop_string(ctx, -1, "linenoiseCompletion");
if (!buf) {
duk_push_undefined(ctx);
} else {
duk_push_string(ctx, buf);
}
duk_push_c_function(ctx, linenoise_add_completion, 2 /*nargs*/);
duk_push_pointer(ctx, (void *) lc);
duk_put_prop_string(ctx, -2, "lc");
rc = duk_pcall(ctx, 2 /*nargs*/); /* [ stash func callback ] -> [ stash result ] */
if (rc != 0) {
linenoiseAddCompletion(lc, duk_safe_to_string(ctx, -1));
}
duk_pop_2(ctx);
}
#endif /* DUK_CMDLINE_LINENOISE_COMPLETION */
/*
* Execute from file handle etc
*/
static int handle_fh(duk_context *ctx, FILE *f, const char *filename, const char *bytecode_filename) {
char *buf = NULL;
size_t bufsz;
size_t bufoff;
size_t got;
int rc;
int retval = -1;
buf = (char *) malloc(1024);
if (!buf) {
goto error;
}
bufsz = 1024;
bufoff = 0;
/* Read until EOF, avoid fseek/stat because it won't work with stdin. */
for (;;) {
size_t avail;
avail = bufsz - bufoff;
if (avail < 1024) {
size_t newsz;
char *buf_new;
#if 0
fprintf(stderr, "resizing read buffer: %ld -> %ld\n", (long) bufsz, (long) (bufsz * 2));
#endif
newsz = bufsz + (bufsz >> 2) + 1024; /* +25% and some extra */
if (newsz < bufsz) {
goto error;
}
buf_new = (char *) realloc(buf, newsz);
if (!buf_new) {
goto error;
}
buf = buf_new;
bufsz = newsz;
}
avail = bufsz - bufoff;
#if 0
fprintf(stderr, "reading input: buf=%p bufsz=%ld bufoff=%ld avail=%ld\n",
(void *) buf, (long) bufsz, (long) bufoff, (long) avail);
#endif
got = fread((void *) (buf + bufoff), (size_t) 1, avail, f);
#if 0
fprintf(stderr, "got=%ld\n", (long) got);
#endif
if (got == 0) {
break;
}
bufoff += got;
/* Emscripten specific: stdin EOF doesn't work as expected.
* Instead, when 'emduk' is executed using Node.js, a file
* piped to stdin repeats (!). Detect that repeat and cut off
* the stdin read. Ensure the loop repeats enough times to
* avoid detecting spurious loops.
*
* This only seems to work for inputs up to 256 bytes long.
*/
#if defined(EMSCRIPTEN)
if (bufoff >= 16384) {
size_t i, j, nloops;
int looped = 0;
for (i = 16; i < bufoff / 8; i++) {
int ok;
nloops = bufoff / i;
ok = 1;
for (j = 1; j < nloops; j++) {
if (memcmp((void *) buf, (void *) (buf + i * j), i) != 0) {
ok = 0;
break;
}
}
if (ok) {
fprintf(stderr, "emscripten workaround: detect looping at index %ld, verified with %ld loops\n", (long) i, (long) (nloops - 1));
bufoff = i;
looped = 1;
break;
}
}
if (looped) {
break;
}
}
#endif
}
duk_push_string(ctx, bytecode_filename);
duk_push_pointer(ctx, (void *) buf);
duk_push_uint(ctx, (duk_uint_t) bufoff);
duk_push_string(ctx, filename);
interactive_mode = 0; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, NULL /*udata*/, 4 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_LOWMEM)
lowmem_clear_exec_timeout();
#endif
free(buf);
buf = NULL;
if (rc != DUK_EXEC_SUCCESS) {
print_pop_error(ctx, stderr);
goto error;
} else {
duk_pop(ctx);
retval = 0;
}
/* fall thru */
cleanup:
if (buf) {
free(buf);
buf = NULL;
}
return retval;
error:
fprintf(stderr, "error in executing file %s\n", filename);
fflush(stderr);
goto cleanup;
}
static int handle_file(duk_context *ctx, const char *filename, const char *bytecode_filename) {
FILE *f = NULL;
int retval;
char fnbuf[256];
/* Example of sending an application specific debugger notification. */
duk_push_string(ctx, "DebuggerHandleFile");
duk_push_string(ctx, filename);
duk_debugger_notify(ctx, 2);
#if defined(EMSCRIPTEN)
if (filename[0] == '/') {
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
} else {
snprintf(fnbuf, sizeof(fnbuf), "/working/%s", filename);
}
#else
snprintf(fnbuf, sizeof(fnbuf), "%s", filename);
#endif
fnbuf[sizeof(fnbuf) - 1] = (char) 0;
f = fopen(fnbuf, "rb");
if (!f) {
fprintf(stderr, "failed to open source file: %s\n", filename);
fflush(stderr);
goto error;
}
retval = handle_fh(ctx, f, filename, bytecode_filename);
fclose(f);
return retval;
error:
return -1;
}
static int handle_eval(duk_context *ctx, const char *code) {
int rc;
int retval = -1;
union {
void *ptr;
const void *constptr;
} u;
u.constptr = code; /* Lose 'const' without warning. */
duk_push_pointer(ctx, u.ptr);
duk_push_uint(ctx, (duk_uint_t) strlen(code));
duk_push_string(ctx, "eval");
interactive_mode = 0; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, NULL /*udata*/, 3 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_LOWMEM)
lowmem_clear_exec_timeout();
#endif
if (rc != DUK_EXEC_SUCCESS) {
print_pop_error(ctx, stderr);
} else {
duk_pop(ctx);
retval = 0;
}
return retval;
}
#if defined(DUK_CMDLINE_LINENOISE)
static int handle_interactive(duk_context *ctx) {
const char *prompt = "duk> ";
char *buffer = NULL;
int retval = 0;
int rc;
linenoiseSetMultiLine(1);
linenoiseHistorySetMaxLen(64);
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
if (!no_auto_complete) {
linenoiseSetCompletionCallback(linenoise_completion);
linenoiseSetHintsCallback(linenoise_hints);
linenoiseSetFreeHintsCallback(linenoise_freehints);
duk_push_global_stash(ctx);
duk_eval_string(ctx, linenoise_completion_script);
duk_put_prop_string(ctx, -2, "linenoiseCompletion");
duk_eval_string(ctx, linenoise_hints_script);
duk_put_prop_string(ctx, -2, "linenoiseHints");
duk_pop(ctx);
}
#endif
for (;;) {
if (buffer) {
linenoiseFree(buffer);
buffer = NULL;
}
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
completion_ctx = ctx;
#endif
buffer = linenoise(prompt);
#if defined(DUK_CMDLINE_LINENOISE_COMPLETION)
completion_ctx = NULL;
#endif
if (!buffer) {
break;
}
if (buffer && buffer[0] != (char) 0) {
linenoiseHistoryAdd(buffer);
}
duk_push_pointer(ctx, (void *) buffer);
duk_push_uint(ctx, (duk_uint_t) strlen(buffer));
duk_push_string(ctx, "input");
interactive_mode = 1; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, NULL /*udata*/, 3 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_LOWMEM)
lowmem_clear_exec_timeout();
#endif
if (buffer) {
linenoiseFree(buffer);
buffer = NULL;
}
if (rc != DUK_EXEC_SUCCESS) {
/* in interactive mode, write to stdout */
print_pop_error(ctx, stdout);
retval = -1; /* an error 'taints' the execution */
} else {
duk_pop(ctx);
}
}
if (buffer) {
linenoiseFree(buffer);
buffer = NULL;
}
return retval;
}
#else /* DUK_CMDLINE_LINENOISE */
static int handle_interactive(duk_context *ctx) {
const char *prompt = "duk> ";
size_t bufsize = 0;
char *buffer = NULL;
int retval = 0;
int rc;
int got_eof = 0;
while (!got_eof) {
size_t idx = 0;
fwrite(prompt, 1, strlen(prompt), stdout);
fflush(stdout);
for (;;) {
int c;
if (idx >= bufsize) {
size_t newsize = bufsize + (bufsize >> 2) + 1024; /* +25% and some extra */
char *newptr;
if (newsize < bufsize) {
goto fail_realloc;
}
newptr = (char *) realloc(buffer, newsize);
if (!newptr) {
goto fail_realloc;
}
buffer = newptr;
bufsize = newsize;
}
c = fgetc(stdin);
if (c == EOF) {
got_eof = 1;
break;
} else if (c == '\n') {
break;
} else {
buffer[idx++] = (char) c;
}
}
duk_push_pointer(ctx, (void *) buffer);
duk_push_uint(ctx, (duk_uint_t) idx);
duk_push_string(ctx, "input");
interactive_mode = 1; /* global */
rc = duk_safe_call(ctx, wrapped_compile_execute, NULL /*udata*/, 3 /*nargs*/, 1 /*nret*/);
#if defined(DUK_CMDLINE_LOWMEM)
lowmem_clear_exec_timeout();
#endif
if (rc != DUK_EXEC_SUCCESS) {
/* in interactive mode, write to stdout */
print_pop_error(ctx, stdout);
retval = -1; /* an error 'taints' the execution */
} else {
duk_pop(ctx);
}
}
done:
if (buffer) {
free(buffer);
buffer = NULL;
}
return retval;
fail_realloc:
fprintf(stderr, "failed to extend line buffer\n");
fflush(stderr);
retval = -1;
goto done;
}
#endif /* DUK_CMDLINE_LINENOISE */
/*
* Simple file read/write bindings
*/
#if defined(DUK_CMDLINE_FILEIO)
static duk_ret_t fileio_read_file(duk_context *ctx) {
const char *fn;
char *buf;
size_t len;
size_t off;
int rc;
FILE *f;
fn = duk_require_string(ctx, 0);
f = fopen(fn, "rb");
if (!f) {
(void) duk_type_error(ctx, "cannot open file %s for reading, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
rc = fseek(f, 0, SEEK_END);
if (rc < 0) {
(void) fclose(f);
(void) duk_type_error(ctx, "fseek() failed for %s, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
len = (size_t) ftell(f);
rc = fseek(f, 0, SEEK_SET);
if (rc < 0) {
(void) fclose(f);
(void) duk_type_error(ctx, "fseek() failed for %s, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
buf = (char *) duk_push_fixed_buffer(ctx, (duk_size_t) len);
for (off = 0; off < len;) {
size_t got;
got = fread((void *) (buf + off), 1, len - off, f);
if (ferror(f)) {
(void) fclose(f);
(void) duk_type_error(ctx, "error while reading %s", fn);
}
if (got == 0) {
if (feof(f)) {
break;
} else {
(void) fclose(f);
(void) duk_type_error(ctx, "error while reading %s", fn);
}
}
off += got;
}
if (f) {
(void) fclose(f);
}
return 1;
}
static duk_ret_t fileio_write_file(duk_context *ctx) {
const char *fn;
const char *buf;
size_t len;
size_t off;
FILE *f;
fn = duk_require_string(ctx, 0);
f = fopen(fn, "wb");
if (!f) {
(void) duk_type_error(ctx, "cannot open file %s for writing, errno %ld: %s",
fn, (long) errno, strerror(errno));
}
len = 0;
buf = (char *) duk_require_buffer_data(ctx, 1, &len);
for (off = 0; off < len;) {
size_t got;
got = fwrite((const void *) (buf + off), 1, len - off, f);
if (ferror(f)) {
(void) fclose(f);
(void) duk_type_error(ctx, "error while writing %s", fn);
}
if (got == 0) {
(void) fclose(f);
(void) duk_type_error(ctx, "error while writing %s", fn);
}
off += got;
}
if (f) {
(void) fclose(f);
}
return 0;
}
static duk_ret_t sys_execute(duk_context *ctx) {
const char *command = duk_require_string(ctx, 0);
int rc;
rc = system(command);
if (rc != 0) {
duk_push_error_object(ctx, DUK_ERR_TYPE_ERROR, "system() failed with code %d", rc);
duk_push_int(ctx, rc);
duk_put_prop_string(ctx, -2, "exitCode");