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

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

<rdar://problem/7909395> Math in JavaScript is inaccurate on iOS

By defalut IEEE754 denormal support is disabled on iOS;
turn it on.

Reviewed by Filip Pizlo.

  • jsc.cpp:

(main):

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