-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs.cpp
More file actions
5815 lines (5124 loc) · 163 KB
/
js.cpp
File metadata and controls
5815 lines (5124 loc) · 163 KB
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sw=4 et tw=99:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Communicator client code, released
* March 31, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#define __STDC_LIMIT_MACROS
/*
* JS shell.
*/
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <locale.h>
#include "jstypes.h"
#include "jsstdint.h"
#include "jsarena.h"
#include "jsutil.h"
#include "jsprf.h"
#include "jswrapper.h"
#include "jsapi.h"
#include "jsarray.h"
#include "jsatom.h"
#include "jsbuiltins.h"
#include "jscntxt.h"
#include "jsdate.h"
#include "jsdbgapi.h"
#include "jsemit.h"
#include "jsfun.h"
#include "jsgc.h"
#include "jsiter.h"
#include "jslock.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jsparse.h"
#include "jsreflect.h"
#include "jsscope.h"
#include "jsscript.h"
#include "jstracer.h"
#include "jstypedarray.h"
#include "jsxml.h"
#include "jsperf.h"
#include "prmjtime.h"
#ifdef JSDEBUGGER
#include "jsdebug.h"
#ifdef JSDEBUGGER_JAVA_UI
#include "jsdjava.h"
#endif /* JSDEBUGGER_JAVA_UI */
#ifdef JSDEBUGGER_C_UI
#include "jsdb.h"
#endif /* JSDEBUGGER_C_UI */
#endif /* JSDEBUGGER */
#include "jsworkers.h"
#include "jsinterpinlines.h"
#include "jsobjinlines.h"
#include "jsscriptinlines.h"
#ifdef XP_UNIX
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#endif
#if defined(XP_WIN) || defined(XP_OS2)
#include <io.h> /* for isatty() */
#endif
#ifdef XP_WIN
#include "jswin.h"
#endif
using namespace js;
typedef enum JSShellExitCode {
EXITCODE_RUNTIME_ERROR = 3,
EXITCODE_FILE_NOT_FOUND = 4,
EXITCODE_OUT_OF_MEMORY = 5,
EXITCODE_TIMEOUT = 6
} JSShellExitCode;
size_t gStackChunkSize = 8192;
/* Assume that we can not use more than 5e5 bytes of C stack by default. */
#if (defined(DEBUG) && defined(__SUNPRO_CC)) || defined(JS_CPU_SPARC)
/* Sun compiler uses larger stack space for js_Interpret() with debug
Use a bigger gMaxStackSize to make "make check" happy. */
#define DEFAULT_MAX_STACK_SIZE 5000000
#else
#define DEFAULT_MAX_STACK_SIZE 500000
#endif
size_t gMaxStackSize = DEFAULT_MAX_STACK_SIZE;
#ifdef JS_THREADSAFE
static PRUintn gStackBaseThreadIndex;
#else
static jsuword gStackBase;
#endif
static size_t gScriptStackQuota = JS_DEFAULT_SCRIPT_STACK_QUOTA;
/*
* Limit the timeout to 30 minutes to prevent an overflow on platfoms
* that represent the time internally in microseconds using 32-bit int.
*/
static jsdouble MAX_TIMEOUT_INTERVAL = 1800.0;
static jsdouble gTimeoutInterval = -1.0;
static volatile bool gCanceled = false;
static bool enableTraceJit = false;
static bool enableMethodJit = false;
static bool enableProfiling = false;
static bool printTiming = false;
static JSBool
SetTimeoutValue(JSContext *cx, jsdouble t);
static bool
InitWatchdog(JSRuntime *rt);
static void
KillWatchdog();
static bool
ScheduleWatchdog(JSRuntime *rt, jsdouble t);
static void
CancelExecution(JSRuntime *rt);
/*
* Watchdog thread state.
*/
#ifdef JS_THREADSAFE
static PRLock *gWatchdogLock = NULL;
static PRCondVar *gWatchdogWakeup = NULL;
static PRThread *gWatchdogThread = NULL;
static bool gWatchdogHasTimeout = false;
static PRIntervalTime gWatchdogTimeout = 0;
static PRCondVar *gSleepWakeup = NULL;
#else
static JSRuntime *gRuntime = NULL;
#endif
int gExitCode = 0;
JSBool gQuitting = JS_FALSE;
FILE *gErrFile = NULL;
FILE *gOutFile = NULL;
#ifdef JS_THREADSAFE
JSObject *gWorkers = NULL;
js::workers::ThreadPool *gWorkerThreadPool = NULL;
#endif
static JSBool reportWarnings = JS_TRUE;
static JSBool compileOnly = JS_FALSE;
typedef enum JSShellErrNum {
#define MSG_DEF(name, number, count, exception, format) \
name = number,
#include "jsshell.msg"
#undef MSG_DEF
JSShellErr_Limit
#undef MSGDEF
} JSShellErrNum;
static JSContext *
NewContext(JSRuntime *rt);
static void
DestroyContext(JSContext *cx, bool withGC);
static const JSErrorFormatString *
my_GetErrorMessage(void *userRef, const char *locale, const uintN errorNumber);
static JSObject *
split_setup(JSContext *cx, JSBool evalcx);
#ifdef EDITLINE
JS_BEGIN_EXTERN_C
JS_EXTERN_API(char) *readline(const char *prompt);
JS_EXTERN_API(void) add_history(char *line);
JS_END_EXTERN_C
#endif
static void
ReportException(JSContext *cx)
{
if (JS_IsExceptionPending(cx)) {
if (!JS_ReportPendingException(cx))
JS_ClearPendingException(cx);
}
}
class ToString {
public:
ToString(JSContext *aCx, jsval v, JSBool aThrow = JS_FALSE)
: cx(aCx), mThrow(aThrow)
{
mStr = JS_ValueToString(cx, v);
if (!aThrow && !mStr)
ReportException(cx);
JS_AddNamedStringRoot(cx, &mStr, "Value ToString helper");
}
~ToString() {
JS_RemoveStringRoot(cx, &mStr);
}
JSBool threw() { return !mStr; }
jsval getJSVal() { return STRING_TO_JSVAL(mStr); }
const char *getBytes() {
if (mStr && (mBytes.ptr() || mBytes.encode(cx, mStr)))
return mBytes.ptr();
return "(error converting value)";
}
private:
JSContext *cx;
JSString *mStr;
JSBool mThrow;
JSAutoByteString mBytes;
};
class IdToString : public ToString {
public:
IdToString(JSContext *cx, jsid id, JSBool aThrow = JS_FALSE)
: ToString(cx, IdToJsval(id), aThrow)
{ }
};
static char *
GetLine(FILE *file, const char * prompt)
{
size_t size;
char *buffer;
#ifdef EDITLINE
/*
* Use readline only if file is stdin, because there's no way to specify
* another handle. Are other filehandles interactive?
*/
if (file == stdin) {
char *linep = readline(prompt);
/*
* We set it to zero to avoid complaining about inappropriate ioctl
* for device in the case of EOF. Looks like errno == 251 if line is
* finished with EOF and errno == 25 (EINVAL on Mac) if there is
* nothing left to read.
*/
if (errno == 251 || errno == 25 || errno == EINVAL)
errno = 0;
if (!linep)
return NULL;
if (linep[0] != '\0')
add_history(linep);
return linep;
}
#endif
size_t len = 0;
if (*prompt != '\0') {
fprintf(gOutFile, "%s", prompt);
fflush(gOutFile);
}
size = 80;
buffer = (char *) malloc(size);
if (!buffer)
return NULL;
char *current = buffer;
while (fgets(current, size - len, file)) {
len += strlen(current);
char *t = buffer + len - 1;
if (*t == '\n') {
/* Line was read. We remove '\n' and exit. */
*t = '\0';
return buffer;
}
if (len + 1 == size) {
size = size * 2;
char *tmp = (char *) realloc(buffer, size);
if (!tmp) {
free(buffer);
return NULL;
}
buffer = tmp;
}
current = buffer + len;
}
if (len && !ferror(file))
return buffer;
free(buffer);
return NULL;
}
/*
* State to store as JSContext private.
*
* We declare such timestamp as volatile as they are updated in the operation
* callback without taking any locks. Any possible race can only lead to more
* frequent callback calls. This is safe as the callback does everything based
* on timing.
*/
struct JSShellContextData {
volatile JSIntervalTime startTime;
};
static JSShellContextData *
NewContextData()
{
/* Prevent creation of new contexts after we have been canceled. */
if (gCanceled)
return NULL;
JSShellContextData *data = (JSShellContextData *)
calloc(sizeof(JSShellContextData), 1);
if (!data)
return NULL;
data->startTime = js_IntervalNow();
return data;
}
static inline JSShellContextData *
GetContextData(JSContext *cx)
{
JSShellContextData *data = (JSShellContextData *) JS_GetContextPrivate(cx);
JS_ASSERT(data);
return data;
}
static JSBool
ShellOperationCallback(JSContext *cx)
{
if (!gCanceled)
return JS_TRUE;
JS_ClearPendingException(cx);
return JS_FALSE;
}
static void
SetContextOptions(JSContext *cx)
{
JS_SetNativeStackQuota(cx, gMaxStackSize);
JS_SetScriptStackQuota(cx, gScriptStackQuota);
JS_SetOperationCallback(cx, ShellOperationCallback);
}
#ifdef WINCE
int errno;
#endif
static void
Process(JSContext *cx, JSObject *obj, char *filename, JSBool forceTTY)
{
JSBool ok, hitEOF;
JSObject *scriptObj;
jsval result;
JSString *str;
char *buffer;
size_t size;
int lineno;
int startline;
FILE *file;
uint32 oldopts;
if (forceTTY || !filename || strcmp(filename, "-") == 0) {
file = stdin;
} else {
file = fopen(filename, "r");
if (!file) {
JS_ReportErrorNumber(cx, my_GetErrorMessage, NULL,
JSSMSG_CANT_OPEN, filename, strerror(errno));
gExitCode = EXITCODE_FILE_NOT_FOUND;
return;
}
}
SetContextOptions(cx);
#ifndef WINCE
/* windows mobile (and possibly other os's) does not have a TTY */
if (!forceTTY && !isatty(fileno(file)))
#endif
{
/*
* It's not interactive - just execute it.
*
* Support the UNIX #! shell hack; gobble the first line if it starts
* with '#'. TODO - this isn't quite compatible with sharp variables,
* as a legal js program (using sharp variables) might start with '#'.
* But that would require multi-character lookahead.
*/
int ch = fgetc(file);
if (ch == '#') {
while((ch = fgetc(file)) != EOF) {
if (ch == '\n' || ch == '\r')
break;
}
}
ungetc(ch, file);
int64 t1 = PRMJ_Now();
oldopts = JS_GetOptions(cx);
JS_SetOptions(cx, oldopts | JSOPTION_COMPILE_N_GO | JSOPTION_NO_SCRIPT_RVAL);
scriptObj = JS_CompileFileHandle(cx, obj, filename, file);
JS_SetOptions(cx, oldopts);
if (scriptObj && !compileOnly) {
(void) JS_ExecuteScript(cx, obj, scriptObj, NULL);
int64 t2 = PRMJ_Now() - t1;
if (printTiming)
printf("runtime = %.3f ms\n", double(t2) / PRMJ_USEC_PER_MSEC);
}
goto cleanup;
}
/* It's an interactive filehandle; drop into read-eval-print loop. */
lineno = 1;
hitEOF = JS_FALSE;
buffer = NULL;
size = 0; /* assign here to avoid warnings */
do {
/*
* Accumulate lines until we get a 'compilable unit' - one that either
* generates an error (before running out of source) or that compiles
* cleanly. This should be whenever we get a complete statement that
* coincides with the end of a line.
*/
startline = lineno;
size_t len = 0; /* initialize to avoid warnings */
do {
ScheduleWatchdog(cx->runtime, -1);
gCanceled = false;
errno = 0;
char *line;
{
JSAutoSuspendRequest suspended(cx);
line = GetLine(file, startline == lineno ? "js> " : "");
}
if (!line) {
if (errno) {
JS_ReportError(cx, strerror(errno));
free(buffer);
goto cleanup;
}
hitEOF = JS_TRUE;
break;
}
if (!buffer) {
buffer = line;
len = strlen(buffer);
size = len + 1;
} else {
/*
* len + 1 is required to store '\n' in the end of line.
*/
size_t newlen = strlen(line) + (len ? len + 1 : 0);
if (newlen + 1 > size) {
size = newlen + 1 > size * 2 ? newlen + 1 : size * 2;
char *newBuf = (char *) realloc(buffer, size);
if (!newBuf) {
free(buffer);
free(line);
JS_ReportOutOfMemory(cx);
goto cleanup;
}
buffer = newBuf;
}
char *current = buffer + len;
if (startline != lineno)
*current++ = '\n';
strcpy(current, line);
len = newlen;
free(line);
}
lineno++;
if (!ScheduleWatchdog(cx->runtime, gTimeoutInterval)) {
hitEOF = JS_TRUE;
break;
}
} while (!JS_BufferIsCompilableUnit(cx, obj, buffer, len));
if (hitEOF && !buffer)
break;
/* Clear any pending exception from previous failed compiles. */
JS_ClearPendingException(cx);
/* Even though we're interactive, we have a compile-n-go opportunity. */
oldopts = JS_GetOptions(cx);
if (!compileOnly)
JS_SetOptions(cx, oldopts | JSOPTION_COMPILE_N_GO);
scriptObj = JS_CompileScript(cx, obj, buffer, len, "typein",
startline);
if (!compileOnly)
JS_SetOptions(cx, oldopts);
if (scriptObj && !compileOnly) {
ok = JS_ExecuteScript(cx, obj, scriptObj, &result);
if (ok && !JSVAL_IS_VOID(result)) {
str = JS_ValueToSource(cx, result);
ok = !!str;
if (ok) {
JSAutoByteString bytes(cx, str);
ok = !!bytes;
if (ok)
fprintf(gOutFile, "%s\n", bytes.ptr());
}
}
}
*buffer = '\0';
} while (!hitEOF && !gQuitting);
free(buffer);
fprintf(gOutFile, "\n");
cleanup:
if (file != stdin)
fclose(file);
return;
}
static int
usage(void)
{
fprintf(gErrFile, "%s\n", JS_GetImplementationVersion());
fprintf(gErrFile, "usage: js [options] [scriptfile] [scriptarg...]\n"
"Options:\n"
" -h Display this information\n"
" -z Create a split global object\n"
" Warning: this option is probably not useful\n"
" -P Deeply freeze the global object prototype\n"
" -s Toggle JSOPTION_STRICT flag\n"
" -w Report strict warnings\n"
" -W Do not report strict warnings\n"
" -x Toggle JSOPTION_XML flag\n"
" -C Compile-only; do not execute\n"
" -i Enable interactive read-eval-print loop\n"
" -j Enable the TraceMonkey tracing JIT\n"
" -m Enable the JaegerMonkey method JIT\n"
" -a Always method JIT, ignore internal tuning\n"
" This only has effect with -m\n"
" -p Enable loop profiling for TraceMonkey\n"
" -d Enable debug mode\n"
" -b Print timing statistics\n"
" -t <timeout> Interrupt long-running execution after <timeout> seconds, where\n"
" <timeout> <= 1800.0. Negative values indicate no timeout (default).\n"
" -c <size> Suggest stack chunk size of <size> bytes. Default is 8192.\n"
" Warning: this option is currently ignored.\n"
" -o <option> Enable a context option flag by name\n"
" Possible values:\n"
" anonfunfix: JSOPTION_ANONFUNFIX\n"
" atline: JSOPTION_ATLINE\n"
" tracejit: JSOPTION_JIT\n"
" methodjit: JSOPTION_METHODJIT\n"
" relimit: JSOPTION_RELIMIT\n"
" strict: JSOPTION_STRICT\n"
" werror: JSOPTION_WERROR\n"
" xml: JSOPTION_XML\n"
" -v <version> Set the JavaScript language version\n"
" Possible values:\n"
" 150: JavaScript 1.5\n"
" 160: JavaScript 1.6\n"
" 170: JavaScript 1.7\n"
" 180: JavaScript 1.8\n"
" 185: JavaScript 1.8.5 (default)\n"
" -f <file> Load and execute JavaScript source <file>\n"
" Note: this option switches to non-interactive mode.\n"
" -e <source> Execute JavaScript <source>\n"
" Note: this option switches to non-interactive mode.\n"
" -S <size> Set the maximum size of the stack to <size> bytes\n"
" Default is %u.\n", DEFAULT_MAX_STACK_SIZE);
#ifdef JS_THREADSAFE
fprintf(gErrFile, " -g <n> Sleep for <n> seconds before starting (default: 0)\n");
#endif
#ifdef JS_GC_ZEAL
fprintf(gErrFile, " -Z <n> Toggle GC zeal: low if <n> is 0 (default), high if non-zero\n");
#endif
#ifdef MOZ_TRACEVIS
fprintf(gErrFile, " -T Start TraceVis\n");
#endif
return 2;
}
/*
* JSContext option name to flag map. The option names are in alphabetical
* order for better reporting.
*/
static const struct {
const char *name;
uint32 flag;
} js_options[] = {
{"anonfunfix", JSOPTION_ANONFUNFIX},
{"atline", JSOPTION_ATLINE},
{"jitprofiling", JSOPTION_PROFILING},
{"tracejit", JSOPTION_JIT},
{"methodjit", JSOPTION_METHODJIT},
{"methodjit_always",JSOPTION_METHODJIT_ALWAYS},
{"relimit", JSOPTION_RELIMIT},
{"strict", JSOPTION_STRICT},
{"werror", JSOPTION_WERROR},
{"xml", JSOPTION_XML},
};
static uint32
MapContextOptionNameToFlag(JSContext* cx, const char* name)
{
for (size_t i = 0; i != JS_ARRAY_LENGTH(js_options); ++i) {
if (strcmp(name, js_options[i].name) == 0)
return js_options[i].flag;
}
char* msg = JS_sprintf_append(NULL,
"unknown option name '%s'."
" The valid names are ", name);
for (size_t i = 0; i != JS_ARRAY_LENGTH(js_options); ++i) {
if (!msg)
break;
msg = JS_sprintf_append(msg, "%s%s", js_options[i].name,
(i + 2 < JS_ARRAY_LENGTH(js_options)
? ", "
: i + 2 == JS_ARRAY_LENGTH(js_options)
? " and "
: "."));
}
if (!msg) {
JS_ReportOutOfMemory(cx);
} else {
JS_ReportError(cx, msg);
free(msg);
}
return 0;
}
extern JSClass global_class;
#if defined(JS_TRACER) && defined(DEBUG)
namespace js {
extern struct JSClass jitstats_class;
void InitJITStatsClass(JSContext *cx, JSObject *glob);
}
#endif
static int
ProcessArgs(JSContext *cx, JSObject *obj, char **argv, int argc)
{
int i, j, length;
JSObject *argsObj;
char *filename = NULL;
JSBool isInteractive = JS_TRUE;
JSBool forceTTY = JS_FALSE;
/*
* Scan past all optional arguments so we can create the arguments object
* before processing any -f options, which must interleave properly with
* -v and -w options. This requires two passes, and without getopt, we'll
* have to keep the option logic here and in the second for loop in sync.
*/
for (i = 0; i < argc; i++) {
if (argv[i][0] != '-' || argv[i][1] == '\0') {
++i;
break;
}
switch (argv[i][1]) {
case 'c':
case 'f':
case 'e':
case 'v':
case 'S':
case 't':
#ifdef JS_GC_ZEAL
case 'Z':
#endif
#ifdef MOZ_TRACEVIS
case 'T':
#endif
case 'g':
++i;
break;
default:;
}
}
/*
* Create arguments early and define it to root it, so it's safe from any
* GC calls nested below, and so it is available to -f <file> arguments.
*/
argsObj = JS_NewArrayObject(cx, 0, NULL);
if (!argsObj)
return 1;
if (!JS_DefineProperty(cx, obj, "arguments", OBJECT_TO_JSVAL(argsObj),
NULL, NULL, 0)) {
return 1;
}
length = argc - i;
for (j = 0; j < length; j++) {
JSString *str = JS_NewStringCopyZ(cx, argv[i++]);
if (!str)
return 1;
if (!JS_DefineElement(cx, argsObj, j, STRING_TO_JSVAL(str),
NULL, NULL, JSPROP_ENUMERATE)) {
return 1;
}
}
for (i = 0; i < argc; i++) {
if (argv[i][0] != '-' || argv[i][1] == '\0') {
filename = argv[i++];
isInteractive = JS_FALSE;
break;
}
switch (argv[i][1]) {
case 'v':
if (++i == argc)
return usage();
JS_SetVersion(cx, (JSVersion) atoi(argv[i]));
break;
#ifdef JS_GC_ZEAL
case 'Z':
if (++i == argc)
return usage();
JS_SetGCZeal(cx, !!(atoi(argv[i])));
break;
#endif
case 'w':
reportWarnings = JS_TRUE;
break;
case 'W':
reportWarnings = JS_FALSE;
break;
case 's':
JS_ToggleOptions(cx, JSOPTION_STRICT);
break;
case 'E':
JS_ToggleOptions(cx, JSOPTION_RELIMIT);
break;
case 'x':
JS_ToggleOptions(cx, JSOPTION_XML);
break;
case 'b':
printTiming = true;
break;
case 'j':
enableTraceJit = !enableTraceJit;
JS_ToggleOptions(cx, JSOPTION_JIT);
#if defined(JS_TRACER) && defined(DEBUG)
js::InitJITStatsClass(cx, JS_GetGlobalObject(cx));
JS_DefineObject(cx, JS_GetGlobalObject(cx), "tracemonkey",
&js::jitstats_class, NULL, 0);
#endif
break;
case 'm':
enableMethodJit = !enableMethodJit;
JS_ToggleOptions(cx, JSOPTION_METHODJIT);
break;
case 'a':
JS_ToggleOptions(cx, JSOPTION_METHODJIT_ALWAYS);
break;
case 'p':
enableProfiling = !enableProfiling;
JS_ToggleOptions(cx, JSOPTION_PROFILING);
break;
case 'o':
{
if (++i == argc)
return usage();
uint32 flag = MapContextOptionNameToFlag(cx, argv[i]);
if (flag == 0)
return gExitCode;
JS_ToggleOptions(cx, flag);
break;
}
case 'P':
if (JS_GET_CLASS(cx, JS_GetPrototype(cx, obj)) != &global_class) {
JSObject *gobj;
if (!JS_DeepFreezeObject(cx, obj))
return JS_FALSE;
gobj = JS_NewGlobalObject(cx, &global_class);
if (!gobj)
return JS_FALSE;
if (!JS_SetPrototype(cx, gobj, obj))
return JS_FALSE;
JS_SetParent(cx, gobj, NULL);
JS_SetGlobalObject(cx, gobj);
obj = gobj;
}
break;
case 't':
if (++i == argc)
return usage();
if (!SetTimeoutValue(cx, atof(argv[i])))
return JS_FALSE;
break;
case 'c':
/* set stack chunk size */
gStackChunkSize = atoi(argv[++i]);
break;
case 'f':
if (++i == argc)
return usage();
Process(cx, obj, argv[i], JS_FALSE);
if (gExitCode != 0)
return gExitCode;
/*
* XXX: js -f foo.js should interpret foo.js and then
* drop into interactive mode, but that breaks the test
* harness. Just execute foo.js for now.
*/
isInteractive = JS_FALSE;
break;
case 'e':
{
jsval rval;
if (++i == argc)
return usage();
/* Pass a filename of -e to imitate PERL */
JS_EvaluateScript(cx, obj, argv[i], strlen(argv[i]),
"-e", 1, &rval);
isInteractive = JS_FALSE;
break;
}
case 'C':
compileOnly = JS_TRUE;
isInteractive = JS_FALSE;
break;
case 'i':
isInteractive = forceTTY = JS_TRUE;
break;
case 'S':
if (++i == argc)
return usage();
/* Set maximum stack size. */
gMaxStackSize = atoi(argv[i]);
break;
case 'd':
JS_SetRuntimeDebugMode(JS_GetRuntime(cx), JS_TRUE);
JS_SetDebugMode(cx, JS_TRUE);
break;
case 'z':
obj = split_setup(cx, JS_FALSE);
if (!obj)
return gExitCode;
break;
#ifdef MOZ_TRACEVIS
case 'T':
if (++i == argc)
return usage();
StartTraceVis(argv[i]);
break;
#endif
#ifdef JS_THREADSAFE
case 'g':
if (++i == argc)
return usage();
PR_Sleep(PR_SecondsToInterval(atoi(argv[i])));
break;
#endif
default:
return usage();
}
}
if (filename || isInteractive)
Process(cx, obj, filename, forceTTY);
return gExitCode;
}
static JSBool
Version(JSContext *cx, uintN argc, jsval *vp)
{
jsval *argv = JS_ARGV(cx, vp);
if (argc > 0 && JSVAL_IS_INT(argv[0]))
*vp = INT_TO_JSVAL(JS_SetVersion(cx, (JSVersion) JSVAL_TO_INT(argv[0])));
else
*vp = INT_TO_JSVAL(JS_GetVersion(cx));
return JS_TRUE;
}
static JSBool
RevertVersion(JSContext *cx, uintN argc, jsval *vp)
{
js_RevertVersion(cx);
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return JS_TRUE;
}
static JSBool
Options(JSContext *cx, uintN argc, jsval *vp)
{
uint32 optset, flag;
JSString *str;
char *names;
JSBool found;
optset = 0;
jsval *argv = JS_ARGV(cx, vp);
for (uintN i = 0; i < argc; i++) {
str = JS_ValueToString(cx, argv[i]);
if (!str)
return JS_FALSE;
argv[i] = STRING_TO_JSVAL(str);
JSAutoByteString opt(cx, str);
if (!opt)
return JS_FALSE;
flag = MapContextOptionNameToFlag(cx, opt.ptr());
if (!flag)
return JS_FALSE;
optset |= flag;
}
optset = JS_ToggleOptions(cx, optset);
names = NULL;
found = JS_FALSE;
for (size_t i = 0; i != JS_ARRAY_LENGTH(js_options); i++) {
if (js_options[i].flag & optset) {
found = JS_TRUE;
names = JS_sprintf_append(names, "%s%s",
names ? "," : "", js_options[i].name);
if (!names)