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

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

[BlackBerry] Set up logging buffer on start of jsc executable
https://bugs.webkit.org/show_bug.cgi?id=114688

Patch by Joe Mason <[email protected]> on 2013-05-09
Reviewed by Rob Buis.

Internal PR: 322715
Internally Reviewed By: Jeff Rogers

  • jsc.cpp:

(main): call BB::Platform::setupApplicationLogging

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