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

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

Rename JSC::Heuristics to JSC::Options
https://bugs.webkit.org/show_bug.cgi?id=72889

Patch by Andy Wingo <[email protected]> on 2011-12-15
Reviewed by Filip Pizlo.

  • runtime/Options.cpp: Renamed from Source/JavaScriptCore/runtime/Heuristics.cpp.
  • runtime/Options.h: Renamed from Source/JavaScriptCore/runtime/Heuristics.h.
  • CMakeLists.txt:
  • GNUmakefile.list.am:
  • JavaScriptCore.vcproj/JavaScriptCore/JavaScriptCore.vcproj:
  • JavaScriptCore.xcodeproj/project.pbxproj:
  • Target.pri:
  • bytecode/CodeBlock.cpp:

(JSC::CodeBlock::shouldOptimizeNow):

  • bytecode/CodeBlock.h:

(JSC::CodeBlock::likelyToTakeSlowCase):
(JSC::CodeBlock::couldTakeSlowCase):
(JSC::CodeBlock::likelyToTakeSpecialFastCase):
(JSC::CodeBlock::likelyToTakeDeepestSlowCase):
(JSC::CodeBlock::likelyToTakeAnySlowCase):
(JSC::CodeBlock::reoptimizationRetryCounter):
(JSC::CodeBlock::countReoptimization):
(JSC::CodeBlock::counterValueForOptimizeAfterWarmUp):
(JSC::CodeBlock::counterValueForOptimizeAfterLongWarmUp):
(JSC::CodeBlock::optimizeNextInvocation):
(JSC::CodeBlock::dontOptimizeAnytimeSoon):
(JSC::CodeBlock::optimizeSoon):
(JSC::CodeBlock::largeFailCountThreshold):
(JSC::CodeBlock::largeFailCountThresholdForLoop):
(JSC::CodeBlock::shouldReoptimizeNow):
(JSC::CodeBlock::shouldReoptimizeFromLoopNow):

  • dfg/DFGByteCodeParser.cpp:

(JSC::DFG::ByteCodeParser::handleInlining):

  • dfg/DFGCapabilities.h:

(JSC::DFG::mightCompileEval):
(JSC::DFG::mightCompileProgram):
(JSC::DFG::mightCompileFunctionForCall):
(JSC::DFG::mightCompileFunctionForConstruct):
(JSC::DFG::mightInlineFunctionForCall):
(JSC::DFG::mightInlineFunctionForConstruct):

  • dfg/DFGOSRExit.cpp:

(JSC::DFG::OSRExit::considerAddingAsFrequentExitSiteSlow):

  • dfg/DFGOSRExitCompiler32_64.cpp:

(JSC::DFG::OSRExitCompiler::compileExit):

  • dfg/DFGOSRExitCompiler64.cpp:

(JSC::DFG::OSRExitCompiler::compileExit):

  • dfg/DFGVariableAccessData.h:

(JSC::DFG::VariableAccessData::shouldUseDoubleFormatAccordingToVote):

  • heap/MarkStack.cpp:

(JSC::MarkStackSegmentAllocator::allocate):
(JSC::MarkStackSegmentAllocator::shrinkReserve):
(JSC::MarkStackArray::MarkStackArray):
(JSC::MarkStackArray::donateSomeCellsTo):
(JSC::MarkStackArray::stealSomeCellsFrom):
(JSC::MarkStackThreadSharedData::MarkStackThreadSharedData):
(JSC::SlotVisitor::donateSlow):
(JSC::SlotVisitor::drain):
(JSC::SlotVisitor::drainFromShared):

  • heap/MarkStack.h:

(JSC::MarkStack::mergeOpaqueRootsIfProfitable):
(JSC::MarkStack::addOpaqueRoot):
(JSC::MarkStackArray::canDonateSomeCells):

  • heap/SlotVisitor.h:

(JSC::SlotVisitor::donate):

  • jit/JIT.cpp:

(JSC::JIT::emitOptimizationCheck):

  • runtime/InitializeThreading.cpp:

(JSC::initializeThreadingOnce): Adapt callers and build systems.

  • testRegExp.cpp:

(CommandLine::CommandLine):

  • jsc.cpp:

(CommandLine::CommandLine):
Rename from Options, to avoid name conflict.

  • Property svn:eol-style set to native
File size: 20.0 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 "CurrentTime.h"
28#include "ExceptionHelpers.h"
29#include "InitializeThreading.h"
30#include "JSArray.h"
31#include "JSFunction.h"
32#include "JSLock.h"
33#include "JSString.h"
34#include "MainThread.h"
35#include "SamplingTool.h"
36#include <math.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40
41#if !OS(WINDOWS)
42#include <unistd.h>
43#endif
44
45#if HAVE(READLINE)
46#include <readline/history.h>
47#include <readline/readline.h>
48#endif
49
50#if HAVE(SYS_TIME_H)
51#include <sys/time.h>
52#endif
53
54#if HAVE(SIGNAL_H)
55#include <signal.h>
56#endif
57
58#if COMPILER(MSVC) && !OS(WINCE)
59#include <crtdbg.h>
60#include <mmsystem.h>
61#include <windows.h>
62#endif
63
64#if PLATFORM(QT)
65#include <QCoreApplication>
66#include <QDateTime>
67#endif
68
69using namespace JSC;
70using namespace WTF;
71
72static void cleanupGlobalData(JSGlobalData*);
73static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
74
75static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
76static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
77static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
78#ifndef NDEBUG
79static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
80#endif
81static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
82static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
83static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
84static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
85static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
86static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
87static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
88
89#if ENABLE(SAMPLING_FLAGS)
90static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
91static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
92#endif
93
94struct Script {
95 bool isFile;
96 char* argument;
97
98 Script(bool isFile, char *argument)
99 : isFile(isFile)
100 , argument(argument)
101 {
102 }
103};
104
105struct CommandLine {
106 CommandLine()
107 : interactive(false)
108 , dump(false)
109 {
110 }
111
112 bool interactive;
113 bool dump;
114 Vector<Script> scripts;
115 Vector<UString> arguments;
116};
117
118static const char interactivePrompt[] = "> ";
119
120class StopWatch {
121public:
122 void start();
123 void stop();
124 long getElapsedMS(); // call stop() first
125
126private:
127 double m_startTime;
128 double m_stopTime;
129};
130
131void StopWatch::start()
132{
133 m_startTime = currentTime();
134}
135
136void StopWatch::stop()
137{
138 m_stopTime = currentTime();
139}
140
141long StopWatch::getElapsedMS()
142{
143 return static_cast<long>((m_stopTime - m_startTime) * 1000);
144}
145
146class GlobalObject : public JSGlobalObject {
147private:
148 GlobalObject(JSGlobalData&, Structure*);
149
150public:
151 typedef JSGlobalObject Base;
152
153 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
154 {
155 GlobalObject* object = new (allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure);
156 object->finishCreation(globalData, arguments);
157 return object;
158 }
159
160 static const ClassInfo s_info;
161
162 static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
163 {
164 return Structure::create(globalData, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), &s_info);
165 }
166
167protected:
168 void finishCreation(JSGlobalData& globalData, const Vector<UString>& arguments)
169 {
170 Base::finishCreation(globalData);
171
172 addFunction(globalData, "debug", functionDebug, 1);
173 addFunction(globalData, "print", functionPrint, 1);
174 addFunction(globalData, "quit", functionQuit, 0);
175 addFunction(globalData, "gc", functionGC, 0);
176#ifndef NDEBUG
177 addFunction(globalData, "releaseExecutableMemory", functionReleaseExecutableMemory, 0);
178#endif
179 addFunction(globalData, "version", functionVersion, 1);
180 addFunction(globalData, "run", functionRun, 1);
181 addFunction(globalData, "load", functionLoad, 1);
182 addFunction(globalData, "checkSyntax", functionCheckSyntax, 1);
183 addFunction(globalData, "readline", functionReadline, 0);
184 addFunction(globalData, "preciseTime", functionPreciseTime, 0);
185#if ENABLE(SAMPLING_FLAGS)
186 addFunction(globalData, "setSamplingFlags", functionSetSamplingFlags, 1);
187 addFunction(globalData, "clearSamplingFlags", functionClearSamplingFlags, 1);
188#endif
189
190 JSObject* array = constructEmptyArray(globalExec());
191 for (size_t i = 0; i < arguments.size(); ++i)
192 array->methodTable()->putByIndex(array, globalExec(), i, jsString(globalExec(), arguments[i]));
193 putDirect(globalData, Identifier(globalExec(), "arguments"), array);
194 }
195
196 void addFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
197 {
198 Identifier identifier(globalExec(), name);
199 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier, function));
200 }
201};
202COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
203ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
204
205const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, 0, ExecState::globalObjectTable, CREATE_METHOD_TABLE(GlobalObject) };
206
207GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure)
208 : JSGlobalObject(globalData, structure)
209{
210}
211
212EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
213{
214 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
215 if (i)
216 putchar(' ');
217
218 printf("%s", exec->argument(i).toString(exec).utf8().data());
219 }
220
221 putchar('\n');
222 fflush(stdout);
223 return JSValue::encode(jsUndefined());
224}
225
226EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
227{
228 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec).utf8().data());
229 return JSValue::encode(jsUndefined());
230}
231
232EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
233{
234 JSLock lock(SilenceAssertionsOnly);
235 exec->heap()->collectAllGarbage();
236 return JSValue::encode(jsUndefined());
237}
238
239#ifndef NDEBUG
240EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
241{
242 JSLock lock(SilenceAssertionsOnly);
243 exec->globalData().releaseExecutableMemory();
244 return JSValue::encode(jsUndefined());
245}
246#endif
247
248EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
249{
250 // We need this function for compatibility with the Mozilla JS tests but for now
251 // we don't actually do any version-specific handling
252 return JSValue::encode(jsUndefined());
253}
254
255EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
256{
257 UString fileName = exec->argument(0).toString(exec);
258 Vector<char> script;
259 if (!fillBufferWithContentsOfFile(fileName, script))
260 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
261
262 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
263
264 StopWatch stopWatch;
265 stopWatch.start();
266 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
267 stopWatch.stop();
268
269 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
270}
271
272EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
273{
274 UString fileName = exec->argument(0).toString(exec);
275 Vector<char> script;
276 if (!fillBufferWithContentsOfFile(fileName, script))
277 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
278
279 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
280
281 JSValue evaluationException;
282 JSValue result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName), JSValue(), &evaluationException);
283 if (evaluationException)
284 throwError(exec, evaluationException);
285 return JSValue::encode(result);
286}
287
288EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
289{
290 UString fileName = exec->argument(0).toString(exec);
291 Vector<char> script;
292 if (!fillBufferWithContentsOfFile(fileName, script))
293 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
294
295 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
296
297 StopWatch stopWatch;
298 stopWatch.start();
299
300 JSValue syntaxException;
301 bool validSyntax = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName), &syntaxException);
302 stopWatch.stop();
303
304 if (!validSyntax)
305 throwError(exec, syntaxException);
306 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
307}
308
309#if ENABLE(SAMPLING_FLAGS)
310EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
311{
312 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
313 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
314 if ((flag >= 1) && (flag <= 32))
315 SamplingFlags::setFlag(flag);
316 }
317 return JSValue::encode(jsNull());
318}
319
320EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
321{
322 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
323 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
324 if ((flag >= 1) && (flag <= 32))
325 SamplingFlags::clearFlag(flag);
326 }
327 return JSValue::encode(jsNull());
328}
329#endif
330
331EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
332{
333 Vector<char, 256> line;
334 int c;
335 while ((c = getchar()) != EOF) {
336 // FIXME: Should we also break on \r?
337 if (c == '\n')
338 break;
339 line.append(c);
340 }
341 line.append('\0');
342 return JSValue::encode(jsString(exec, line.data()));
343}
344
345EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
346{
347 return JSValue::encode(jsNumber(currentTime()));
348}
349
350EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
351{
352 // Technically, destroying the heap in the middle of JS execution is a no-no,
353 // but we want to maintain compatibility with the Mozilla test suite, so
354 // we pretend that execution has terminated to avoid ASSERTs, then tear down the heap.
355 exec->globalData().dynamicGlobalObject = 0;
356
357 cleanupGlobalData(&exec->globalData());
358 exit(EXIT_SUCCESS);
359
360#if COMPILER(MSVC) && OS(WINCE)
361 // Without this, Visual Studio will complain that this method does not return a value.
362 return JSValue::encode(jsUndefined());
363#endif
364}
365
366// Use SEH for Release builds only to get rid of the crash report dialog
367// (luckily the same tests fail in Release and Debug builds so far). Need to
368// be in a separate main function because the jscmain function requires object
369// unwinding.
370
371#if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
372#define TRY __try {
373#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
374#else
375#define TRY
376#define EXCEPT(x)
377#endif
378
379int jscmain(int argc, char** argv, JSGlobalData*);
380
381int main(int argc, char** argv)
382{
383#if OS(WINDOWS)
384#if !OS(WINCE)
385 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
386 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
387 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
388 ::SetErrorMode(0);
389#endif
390
391#if defined(_DEBUG)
392 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
393 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
394 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
395 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
396 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
397 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
398#endif
399
400 timeBeginPeriod(1);
401#endif
402
403#if PLATFORM(QT)
404 QCoreApplication app(argc, argv);
405#endif
406
407 // Initialize JSC before getting JSGlobalData.
408#if ENABLE(SAMPLING_REGIONS)
409 WTF::initializeMainThread();
410#endif
411 JSC::initializeThreading();
412
413 // We can't use destructors in the following code because it uses Windows
414 // Structured Exception Handling
415 int res = 0;
416 JSGlobalData* globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap).leakRef();
417 TRY
418 res = jscmain(argc, argv, globalData);
419 EXCEPT(res = 3)
420
421 cleanupGlobalData(globalData);
422 return res;
423}
424
425static void cleanupGlobalData(JSGlobalData* globalData)
426{
427 JSLock lock(SilenceAssertionsOnly);
428 globalData->clearBuiltinStructures();
429 globalData->heap.destroy();
430 globalData->deref();
431}
432
433static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
434{
435 UString script;
436 UString fileName;
437 Vector<char> scriptBuffer;
438
439 if (dump)
440 BytecodeGenerator::setDumpsGeneratedCode(true);
441
442 JSGlobalData& globalData = globalObject->globalData();
443
444#if ENABLE(SAMPLING_FLAGS)
445 SamplingFlags::start();
446#endif
447
448 bool success = true;
449 for (size_t i = 0; i < scripts.size(); i++) {
450 if (scripts[i].isFile) {
451 fileName = scripts[i].argument;
452 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
453 return false; // fail early so we can catch missing files
454 script = scriptBuffer.data();
455 } else {
456 script = scripts[i].argument;
457 fileName = "[Command Line]";
458 }
459
460 globalData.startSampling();
461
462 JSValue evaluationException;
463 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName), JSValue(), &evaluationException);
464 success = success && !evaluationException;
465 if (dump) {
466 if (evaluationException)
467 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec()).utf8().data());
468 else
469 printf("End: %s\n", returnValue.toString(globalObject->globalExec()).utf8().data());
470 }
471
472 globalData.stopSampling();
473 globalObject->globalExec()->clearException();
474 }
475
476#if ENABLE(SAMPLING_FLAGS)
477 SamplingFlags::stop();
478#endif
479#if ENABLE(SAMPLING_REGIONS)
480 SamplingRegion::dump();
481#endif
482 globalData.dumpSampleData(globalObject->globalExec());
483#if ENABLE(SAMPLING_COUNTERS)
484 AbstractSamplingCounter::dump();
485#endif
486#if ENABLE(REGEXP_TRACING)
487 globalData.dumpRegExpTrace();
488#endif
489 return success;
490}
491
492#define RUNNING_FROM_XCODE 0
493
494static void runInteractive(GlobalObject* globalObject)
495{
496 UString interpreterName("Interpreter");
497
498 while (true) {
499#if HAVE(READLINE) && !RUNNING_FROM_XCODE
500 char* line = readline(interactivePrompt);
501 if (!line)
502 break;
503 if (line[0])
504 add_history(line);
505 JSValue evaluationException;
506 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line, interpreterName), JSValue(), &evaluationException);
507 free(line);
508#else
509 printf("%s", interactivePrompt);
510 Vector<char, 256> line;
511 int c;
512 while ((c = getchar()) != EOF) {
513 // FIXME: Should we also break on \r?
514 if (c == '\n')
515 break;
516 line.append(c);
517 }
518 if (line.isEmpty())
519 break;
520 line.append('\0');
521
522 JSValue evaluationException;
523 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line.data(), interpreterName), JSValue(), &evaluationException);
524#endif
525 if (evaluationException)
526 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec()).utf8().data());
527 else
528 printf("%s\n", returnValue.toString(globalObject->globalExec()).utf8().data());
529
530 globalObject->globalExec()->clearException();
531 }
532 printf("\n");
533}
534
535static NO_RETURN void printUsageStatement(JSGlobalData* globalData, bool help = false)
536{
537 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
538 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
539 fprintf(stderr, " -e Evaluate argument as script code\n");
540 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
541 fprintf(stderr, " -h|--help Prints this help message\n");
542 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
543#if HAVE(SIGNAL_H)
544 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
545#endif
546
547 cleanupGlobalData(globalData);
548 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
549}
550
551static void parseArguments(int argc, char** argv, CommandLine& options, JSGlobalData* globalData)
552{
553 int i = 1;
554 for (; i < argc; ++i) {
555 const char* arg = argv[i];
556 if (!strcmp(arg, "-f")) {
557 if (++i == argc)
558 printUsageStatement(globalData);
559 options.scripts.append(Script(true, argv[i]));
560 continue;
561 }
562 if (!strcmp(arg, "-e")) {
563 if (++i == argc)
564 printUsageStatement(globalData);
565 options.scripts.append(Script(false, argv[i]));
566 continue;
567 }
568 if (!strcmp(arg, "-i")) {
569 options.interactive = true;
570 continue;
571 }
572 if (!strcmp(arg, "-d")) {
573 options.dump = true;
574 continue;
575 }
576 if (!strcmp(arg, "-s")) {
577#if HAVE(SIGNAL_H)
578 signal(SIGILL, _exit);
579 signal(SIGFPE, _exit);
580 signal(SIGBUS, _exit);
581 signal(SIGSEGV, _exit);
582#endif
583 continue;
584 }
585 if (!strcmp(arg, "--")) {
586 ++i;
587 break;
588 }
589 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
590 printUsageStatement(globalData, true);
591 options.scripts.append(Script(true, argv[i]));
592 }
593
594 if (options.scripts.isEmpty())
595 options.interactive = true;
596
597 for (; i < argc; ++i)
598 options.arguments.append(argv[i]);
599}
600
601int jscmain(int argc, char** argv, JSGlobalData* globalData)
602{
603 JSLock lock(SilenceAssertionsOnly);
604
605 CommandLine options;
606 parseArguments(argc, argv, options, globalData);
607
608 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.arguments);
609 bool success = runWithScripts(globalObject, options.scripts, options.dump);
610 if (options.interactive && success)
611 runInteractive(globalObject);
612
613 return success ? 0 : 3;
614}
615
616static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
617{
618 FILE* f = fopen(fileName.utf8().data(), "r");
619 if (!f) {
620 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
621 return false;
622 }
623
624 size_t bufferSize = 0;
625 size_t bufferCapacity = 1024;
626
627 buffer.resize(bufferCapacity);
628
629 while (!feof(f) && !ferror(f)) {
630 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
631 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
632 bufferCapacity *= 2;
633 buffer.resize(bufferCapacity);
634 }
635 }
636 fclose(f);
637 buffer[bufferSize] = '\0';
638
639 if (buffer[0] == '#' && buffer[1] == '!')
640 buffer[0] = buffer[1] = '/';
641
642 return true;
643}
Note: See TracBrowser for help on using the repository browser.