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