source: webkit/trunk/Source/JavaScriptCore/jsc.cpp@ 122341

Last change on this file since 122341 was 122341, checked in by [email protected], 13 years ago

jsc: Parse options before creating global data
https://bugs.webkit.org/show_bug.cgi?id=90975

Reviewed by Filip Pizlo.

This patch moves the options parsing in "jsc" before the creation
of the JSGlobalData, so that --useJIT=no has a chance to take
effect.

  • jsc.cpp:

(CommandLine::parseArguments): Refactor to be a class, and take
argc and argv as constructor arguments.
(jscmain): Move arg parsing before JSGlobalData creation.

  • Property svn:eol-style set to native
File size: 24.8 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Bjoern Graf ([email protected])
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#include "config.h"
24
25#include "BytecodeGenerator.h"
26#include "Completion.h"
27#include <wtf/CurrentTime.h>
28#include "ExceptionHelpers.h"
29#include "InitializeThreading.h"
30#include "Interpreter.h"
31#include "JSArray.h"
32#include "JSCTypedArrayStubs.h"
33#include "JSFunction.h"
34#include "JSLock.h"
35#include "JSString.h"
36#include <wtf/MainThread.h>
37#include "SamplingTool.h"
38#include <math.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42
43#if !OS(WINDOWS)
44#include <unistd.h>
45#endif
46
47#if HAVE(READLINE)
48// readline/history.h has a Function typedef which conflicts with the WTF::Function template from WTF/Forward.h
49// We #define it to something else to avoid this conflict.
50#define Function ReadlineFunction
51#include <readline/history.h>
52#include <readline/readline.h>
53#undef Function
54#endif
55
56#if HAVE(SYS_TIME_H)
57#include <sys/time.h>
58#endif
59
60#if HAVE(SIGNAL_H)
61#include <signal.h>
62#endif
63
64#if COMPILER(MSVC) && !OS(WINCE)
65#include <crtdbg.h>
66#include <mmsystem.h>
67#include <windows.h>
68#endif
69
70#if PLATFORM(QT)
71#include <QCoreApplication>
72#include <QDateTime>
73#endif
74
75#if PLATFORM(IOS)
76#include <fenv.h>
77#include <arm/arch.h>
78#endif
79
80using namespace JSC;
81using namespace WTF;
82
83static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
84
85static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
86static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
87static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
88static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
89#ifndef NDEBUG
90static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
91#endif
92static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
93static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
94static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
95static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
96static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
97static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
98static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
99
100#if ENABLE(SAMPLING_FLAGS)
101static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
102static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
103#endif
104
105struct Script {
106 bool isFile;
107 char* argument;
108
109 Script(bool isFile, char *argument)
110 : isFile(isFile)
111 , argument(argument)
112 {
113 }
114};
115
116class CommandLine {
117public:
118 CommandLine(int argc, char** argv)
119 : m_interactive(false)
120 , m_dump(false)
121 , m_exitCode(false)
122 {
123 parseArguments(argc, argv);
124 }
125
126 bool m_interactive;
127 bool m_dump;
128 bool m_exitCode;
129 Vector<Script> m_scripts;
130 Vector<UString> m_arguments;
131
132 void parseArguments(int, char**);
133};
134
135static const char interactivePrompt[] = "> ";
136
137class StopWatch {
138public:
139 void start();
140 void stop();
141 long getElapsedMS(); // call stop() first
142
143private:
144 double m_startTime;
145 double m_stopTime;
146};
147
148void StopWatch::start()
149{
150 m_startTime = currentTime();
151}
152
153void StopWatch::stop()
154{
155 m_stopTime = currentTime();
156}
157
158long StopWatch::getElapsedMS()
159{
160 return static_cast<long>((m_stopTime - m_startTime) * 1000);
161}
162
163class GlobalObject : public JSGlobalObject {
164private:
165 GlobalObject(JSGlobalData&, Structure*);
166
167public:
168 typedef JSGlobalObject Base;
169
170 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
171 {
172 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure);
173 object->finishCreation(globalData, arguments);
174 return object;
175 }
176
177 static const ClassInfo s_info;
178 static const GlobalObjectMethodTable s_globalObjectMethodTable;
179
180 static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
181 {
182 return Structure::create(globalData, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), &s_info);
183 }
184
185 static bool javaScriptExperimentsEnabled(const JSGlobalObject*) { return true; }
186
187protected:
188 void finishCreation(JSGlobalData& globalData, const Vector<UString>& arguments)
189 {
190 Base::finishCreation(globalData);
191
192 addFunction(globalData, "debug", functionDebug, 1);
193 addFunction(globalData, "print", functionPrint, 1);
194 addFunction(globalData, "quit", functionQuit, 0);
195 addFunction(globalData, "gc", functionGC, 0);
196#ifndef NDEBUG
197 addFunction(globalData, "releaseExecutableMemory", functionReleaseExecutableMemory, 0);
198#endif
199 addFunction(globalData, "version", functionVersion, 1);
200 addFunction(globalData, "run", functionRun, 1);
201 addFunction(globalData, "load", functionLoad, 1);
202 addFunction(globalData, "checkSyntax", functionCheckSyntax, 1);
203 addFunction(globalData, "jscStack", functionJSCStack, 1);
204 addFunction(globalData, "readline", functionReadline, 0);
205 addFunction(globalData, "preciseTime", functionPreciseTime, 0);
206#if ENABLE(SAMPLING_FLAGS)
207 addFunction(globalData, "setSamplingFlags", functionSetSamplingFlags, 1);
208 addFunction(globalData, "clearSamplingFlags", functionClearSamplingFlags, 1);
209#endif
210
211 addConstructableFunction(globalData, "Uint8Array", constructJSUint8Array, 1);
212 addConstructableFunction(globalData, "Uint8ClampedArray", constructJSUint8ClampedArray, 1);
213 addConstructableFunction(globalData, "Uint16Array", constructJSUint16Array, 1);
214 addConstructableFunction(globalData, "Uint32Array", constructJSUint32Array, 1);
215 addConstructableFunction(globalData, "Int8Array", constructJSInt8Array, 1);
216 addConstructableFunction(globalData, "Int16Array", constructJSInt16Array, 1);
217 addConstructableFunction(globalData, "Int32Array", constructJSInt32Array, 1);
218 addConstructableFunction(globalData, "Float32Array", constructJSFloat32Array, 1);
219 addConstructableFunction(globalData, "Float64Array", constructJSFloat64Array, 1);
220
221 JSArray* array = constructEmptyArray(globalExec());
222 for (size_t i = 0; i < arguments.size(); ++i)
223 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]), false);
224 putDirect(globalData, Identifier(globalExec(), "arguments"), array);
225 }
226
227 void addFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
228 {
229 Identifier identifier(globalExec(), name);
230 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier.ustring(), function));
231 }
232
233 void addConstructableFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
234 {
235 Identifier identifier(globalExec(), name);
236 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier.ustring(), function, NoIntrinsic, function));
237 }
238};
239COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
240ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
241
242const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, 0, ExecState::globalObjectTable, CREATE_METHOD_TABLE(GlobalObject) };
243const GlobalObjectMethodTable GlobalObject::s_globalObjectMethodTable = { &allowsAccessFrom, &supportsProfiling, &supportsRichSourceInfo, &shouldInterruptScript, &javaScriptExperimentsEnabled };
244
245
246GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure)
247 : JSGlobalObject(globalData, structure, &s_globalObjectMethodTable)
248{
249}
250
251static inline SourceCode jscSource(const char* utf8, const UString& filename)
252{
253 // Find the the first non-ascii character, or nul.
254 const char* pos = utf8;
255 while (*pos > 0)
256 pos++;
257 size_t asciiLength = pos - utf8;
258
259 // Fast case - string is all ascii.
260 if (!*pos)
261 return makeSource(UString(utf8, asciiLength), filename);
262
263 // Slow case - contains non-ascii characters, use fromUTF8WithLatin1Fallback.
264 ASSERT(*pos < 0);
265 ASSERT(strlen(utf8) == asciiLength + strlen(pos));
266 String source = String::fromUTF8WithLatin1Fallback(utf8, asciiLength + strlen(pos));
267 return makeSource(source.impl(), filename);
268}
269
270EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
271{
272 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
273 if (i)
274 putchar(' ');
275
276 printf("%s", exec->argument(i).toString(exec)->value(exec).utf8().data());
277 }
278
279 putchar('\n');
280 fflush(stdout);
281 return JSValue::encode(jsUndefined());
282}
283
284EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
285{
286 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec)->value(exec).utf8().data());
287 return JSValue::encode(jsUndefined());
288}
289
290EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
291{
292 String trace = "--> Stack trace:\n";
293 Vector<StackFrame> stackTrace;
294 Interpreter::getStackTrace(&exec->globalData(), stackTrace);
295 int i = 0;
296
297 for (Vector<StackFrame>::iterator iter = stackTrace.begin(); iter < stackTrace.end(); iter++) {
298 StackFrame level = *iter;
299 trace += String::format(" %i %s\n", i, level.toString(exec).utf8().data());
300 i++;
301 }
302 fprintf(stderr, "%s", trace.utf8().data());
303 return JSValue::encode(jsUndefined());
304}
305
306EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
307{
308 JSLockHolder lock(exec);
309 exec->heap()->collectAllGarbage();
310 return JSValue::encode(jsUndefined());
311}
312
313#ifndef NDEBUG
314EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
315{
316 JSLockHolder lock(exec);
317 exec->globalData().releaseExecutableMemory();
318 return JSValue::encode(jsUndefined());
319}
320#endif
321
322EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
323{
324 // We need this function for compatibility with the Mozilla JS tests but for now
325 // we don't actually do any version-specific handling
326 return JSValue::encode(jsUndefined());
327}
328
329EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
330{
331 UString fileName = exec->argument(0).toString(exec)->value(exec);
332 Vector<char> script;
333 if (!fillBufferWithContentsOfFile(fileName, script))
334 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
335
336 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
337
338 JSValue exception;
339 StopWatch stopWatch;
340 stopWatch.start();
341 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &exception);
342 stopWatch.stop();
343
344 if (!!exception) {
345 throwError(globalObject->globalExec(), exception);
346 return JSValue::encode(jsUndefined());
347 }
348
349 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
350}
351
352EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
353{
354 UString fileName = exec->argument(0).toString(exec)->value(exec);
355 Vector<char> script;
356 if (!fillBufferWithContentsOfFile(fileName, script))
357 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
358
359 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
360
361 JSValue evaluationException;
362 JSValue result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &evaluationException);
363 if (evaluationException)
364 throwError(exec, evaluationException);
365 return JSValue::encode(result);
366}
367
368EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
369{
370 UString fileName = exec->argument(0).toString(exec)->value(exec);
371 Vector<char> script;
372 if (!fillBufferWithContentsOfFile(fileName, script))
373 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
374
375 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
376
377 StopWatch stopWatch;
378 stopWatch.start();
379
380 JSValue syntaxException;
381 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script.data(), fileName), &syntaxException);
382 stopWatch.stop();
383
384 if (!validSyntax)
385 throwError(exec, syntaxException);
386 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
387}
388
389#if ENABLE(SAMPLING_FLAGS)
390EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
391{
392 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
393 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
394 if ((flag >= 1) && (flag <= 32))
395 SamplingFlags::setFlag(flag);
396 }
397 return JSValue::encode(jsNull());
398}
399
400EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
401{
402 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
403 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
404 if ((flag >= 1) && (flag <= 32))
405 SamplingFlags::clearFlag(flag);
406 }
407 return JSValue::encode(jsNull());
408}
409#endif
410
411EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
412{
413 Vector<char, 256> line;
414 int c;
415 while ((c = getchar()) != EOF) {
416 // FIXME: Should we also break on \r?
417 if (c == '\n')
418 break;
419 line.append(c);
420 }
421 line.append('\0');
422 return JSValue::encode(jsString(exec, line.data()));
423}
424
425EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
426{
427 return JSValue::encode(jsNumber(currentTime()));
428}
429
430EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*)
431{
432 exit(EXIT_SUCCESS);
433
434#if COMPILER(MSVC) && OS(WINCE)
435 // Without this, Visual Studio will complain that this method does not return a value.
436 return JSValue::encode(jsUndefined());
437#endif
438}
439
440// Use SEH for Release builds only to get rid of the crash report dialog
441// (luckily the same tests fail in Release and Debug builds so far). Need to
442// be in a separate main function because the jscmain function requires object
443// unwinding.
444
445#if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
446#define TRY __try {
447#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
448#else
449#define TRY
450#define EXCEPT(x)
451#endif
452
453int jscmain(int argc, char** argv);
454
455int main(int argc, char** argv)
456{
457#if PLATFORM(IOS)
458 // Enabled IEEE754 denormal support.
459 fenv_t env;
460 fegetenv( &env );
461 env.__fpscr &= ~0x01000000u;
462 fesetenv( &env );
463#endif
464
465#if OS(WINDOWS)
466#if !OS(WINCE)
467 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
468 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
469 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
470 ::SetErrorMode(0);
471#endif
472
473#if defined(_DEBUG)
474 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
475 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
476 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
477 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
478 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
479 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
480#endif
481
482 timeBeginPeriod(1);
483#endif
484
485#if PLATFORM(QT)
486 QCoreApplication app(argc, argv);
487#endif
488
489 // Initialize JSC before getting JSGlobalData.
490#if ENABLE(SAMPLING_REGIONS)
491 WTF::initializeMainThread();
492#endif
493 JSC::initializeThreading();
494
495 // We can't use destructors in the following code because it uses Windows
496 // Structured Exception Handling
497 int res = 0;
498 TRY
499 res = jscmain(argc, argv);
500 EXCEPT(res = 3)
501 return res;
502}
503
504static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
505{
506 const char* script;
507 UString fileName;
508 Vector<char> scriptBuffer;
509
510 if (dump)
511 BytecodeGenerator::setDumpsGeneratedCode(true);
512
513 JSGlobalData& globalData = globalObject->globalData();
514
515#if ENABLE(SAMPLING_FLAGS)
516 SamplingFlags::start();
517#endif
518
519 bool success = true;
520 for (size_t i = 0; i < scripts.size(); i++) {
521 if (scripts[i].isFile) {
522 fileName = scripts[i].argument;
523 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
524 return false; // fail early so we can catch missing files
525 script = scriptBuffer.data();
526 } else {
527 script = scripts[i].argument;
528 fileName = "[Command Line]";
529 }
530
531 globalData.startSampling();
532
533 JSValue evaluationException;
534 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script, fileName), JSValue(), &evaluationException);
535 success = success && !evaluationException;
536 if (dump && !evaluationException)
537 printf("End: %s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
538 if (evaluationException) {
539 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
540 Identifier stackID(globalObject->globalExec(), "stack");
541 JSValue stackValue = evaluationException.get(globalObject->globalExec(), stackID);
542 if (!stackValue.isUndefinedOrNull())
543 printf("%s\n", stackValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
544 }
545
546 globalData.stopSampling();
547 globalObject->globalExec()->clearException();
548 }
549
550#if ENABLE(SAMPLING_FLAGS)
551 SamplingFlags::stop();
552#endif
553#if ENABLE(SAMPLING_REGIONS)
554 SamplingRegion::dump();
555#endif
556 globalData.dumpSampleData(globalObject->globalExec());
557#if ENABLE(SAMPLING_COUNTERS)
558 AbstractSamplingCounter::dump();
559#endif
560#if ENABLE(REGEXP_TRACING)
561 globalData.dumpRegExpTrace();
562#endif
563 return success;
564}
565
566#define RUNNING_FROM_XCODE 0
567
568static void runInteractive(GlobalObject* globalObject)
569{
570 UString interpreterName("Interpreter");
571
572 while (true) {
573#if HAVE(READLINE) && !RUNNING_FROM_XCODE
574 char* line = readline(interactivePrompt);
575 if (!line)
576 break;
577 if (line[0])
578 add_history(line);
579 JSValue evaluationException;
580 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line, interpreterName), JSValue(), &evaluationException);
581 free(line);
582#else
583 printf("%s", interactivePrompt);
584 Vector<char, 256> line;
585 int c;
586 while ((c = getchar()) != EOF) {
587 // FIXME: Should we also break on \r?
588 if (c == '\n')
589 break;
590 line.append(c);
591 }
592 if (line.isEmpty())
593 break;
594 line.append('\0');
595
596 JSValue evaluationException;
597 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line.data(), interpreterName), JSValue(), &evaluationException);
598#endif
599 if (evaluationException)
600 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
601 else
602 printf("%s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
603
604 globalObject->globalExec()->clearException();
605 }
606 printf("\n");
607}
608
609static NO_RETURN void printUsageStatement(bool help = false)
610{
611 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
612 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
613 fprintf(stderr, " -e Evaluate argument as script code\n");
614 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
615 fprintf(stderr, " -h|--help Prints this help message\n");
616 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
617#if HAVE(SIGNAL_H)
618 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
619#endif
620 fprintf(stderr, " -x Output exit code before terminating\n");
621 fprintf(stderr, "\n");
622 fprintf(stderr, " --options Dumps all JSC VM options and exits\n");
623 fprintf(stderr, " --dumpOptions Dumps all JSC VM options before continuing\n");
624 fprintf(stderr, " --<jsc VM option>=<value> Sets the specified JSC VM option\n");
625 fprintf(stderr, "\n");
626
627 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
628}
629
630void CommandLine::parseArguments(int argc, char** argv)
631{
632 int i = 1;
633 bool needToDumpOptions = false;
634 bool needToExit = false;
635
636 for (; i < argc; ++i) {
637 const char* arg = argv[i];
638 if (!strcmp(arg, "-f")) {
639 if (++i == argc)
640 printUsageStatement();
641 m_scripts.append(Script(true, argv[i]));
642 continue;
643 }
644 if (!strcmp(arg, "-e")) {
645 if (++i == argc)
646 printUsageStatement();
647 m_scripts.append(Script(false, argv[i]));
648 continue;
649 }
650 if (!strcmp(arg, "-i")) {
651 m_interactive = true;
652 continue;
653 }
654 if (!strcmp(arg, "-d")) {
655 m_dump = true;
656 continue;
657 }
658 if (!strcmp(arg, "-s")) {
659#if HAVE(SIGNAL_H)
660 signal(SIGILL, _exit);
661 signal(SIGFPE, _exit);
662 signal(SIGBUS, _exit);
663 signal(SIGSEGV, _exit);
664#endif
665 continue;
666 }
667 if (!strcmp(arg, "-x")) {
668 m_exitCode = true;
669 continue;
670 }
671 if (!strcmp(arg, "--")) {
672 ++i;
673 break;
674 }
675 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
676 printUsageStatement(true);
677
678 if (!strcmp(arg, "--options")) {
679 needToDumpOptions = true;
680 needToExit = true;
681 continue;
682 }
683 if (!strcmp(arg, "--dumpOptions")) {
684 needToDumpOptions = true;
685 continue;
686 }
687
688 // See if the -- option is a JSC VM option.
689 // NOTE: At this point, we know that the arg starts with "--". Skip it.
690 if (JSC::Options::setOption(&arg[2])) {
691 // The arg was recognized as a VM option and has been parsed.
692 continue; // Just continue with the next arg.
693 }
694
695 // This arg is not recognized by the VM nor by jsc. Pass it on to the
696 // script.
697 m_scripts.append(Script(true, argv[i]));
698 }
699
700 if (m_scripts.isEmpty())
701 m_interactive = true;
702
703 for (; i < argc; ++i)
704 m_arguments.append(argv[i]);
705
706 if (needToDumpOptions)
707 JSC::Options::dumpAllOptions(stderr);
708 if (needToExit)
709 exit(EXIT_SUCCESS);
710}
711
712int jscmain(int argc, char** argv)
713{
714 // Note that the options parsing can affect JSGlobalData creation, and thus
715 // comes first.
716 CommandLine options(argc, argv);
717 RefPtr<JSGlobalData> globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap);
718 JSLockHolder lock(globalData.get());
719 int result;
720
721 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.m_arguments);
722 bool success = runWithScripts(globalObject, options.m_scripts, options.m_dump);
723 if (options.m_interactive && success)
724 runInteractive(globalObject);
725
726 result = success ? 0 : 3;
727
728 if (options.m_exitCode)
729 printf("jsc exiting %d\n", result);
730
731 return result;
732}
733
734static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
735{
736 FILE* f = fopen(fileName.utf8().data(), "r");
737 if (!f) {
738 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
739 return false;
740 }
741
742 size_t bufferSize = 0;
743 size_t bufferCapacity = 1024;
744
745 buffer.resize(bufferCapacity);
746
747 while (!feof(f) && !ferror(f)) {
748 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
749 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
750 bufferCapacity *= 2;
751 buffer.resize(bufferCapacity);
752 }
753 }
754 fclose(f);
755 buffer[bufferSize] = '\0';
756
757 if (buffer[0] == '#' && buffer[1] == '!')
758 buffer[0] = buffer[1] = '/';
759
760 return true;
761}
Note: See TracBrowser for help on using the repository browser.