2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Bjoern Graf (bjoern.graf@gmail.com)
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.
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.
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.
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"
32 #include "JSCTypedArrayStubs.h"
33 #include "JSFunction.h"
36 #include <wtf/MainThread.h>
37 #include "SamplingTool.h"
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>
64 #if COMPILER(MSVC) && !OS(WINCE)
71 #include <QCoreApplication>
83 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
85 static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
86 static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
87 static EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState*);
88 static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
89 static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
91 static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
92 static EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState*);
94 static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
95 static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
96 static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
97 static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
98 static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
99 static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
100 static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
102 #if ENABLE(SAMPLING_FLAGS)
103 static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
104 static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
111 Script(bool isFile, char *argument)
120 CommandLine(int argc, char** argv)
121 : m_interactive(false)
125 parseArguments(argc, argv);
131 Vector<Script> m_scripts;
132 Vector<UString> m_arguments;
134 void parseArguments(int, char**);
137 static const char interactivePrompt[] = "> ";
143 long getElapsedMS(); // call stop() first
150 void StopWatch::start()
152 m_startTime = currentTime();
155 void StopWatch::stop()
157 m_stopTime = currentTime();
160 long StopWatch::getElapsedMS()
162 return static_cast<long>((m_stopTime - m_startTime) * 1000);
165 class GlobalObject : public JSGlobalObject {
167 GlobalObject(JSGlobalData&, Structure*);
170 typedef JSGlobalObject Base;
172 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
174 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure);
175 object->finishCreation(globalData, arguments);
179 static const ClassInfo s_info;
180 static const GlobalObjectMethodTable s_globalObjectMethodTable;
182 static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
184 return Structure::create(globalData, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), &s_info);
187 static bool javaScriptExperimentsEnabled(const JSGlobalObject*) { return true; }
190 void finishCreation(JSGlobalData& globalData, const Vector<UString>& arguments)
192 Base::finishCreation(globalData);
194 addFunction(globalData, "debug", functionDebug, 1);
195 addFunction(globalData, "describe", functionDescribe, 1);
196 addFunction(globalData, "print", functionPrint, 1);
197 addFunction(globalData, "quit", functionQuit, 0);
198 addFunction(globalData, "gc", functionGC, 0);
200 addFunction(globalData, "dumpCallFrame", functionDumpCallFrame, 0);
201 addFunction(globalData, "releaseExecutableMemory", functionReleaseExecutableMemory, 0);
203 addFunction(globalData, "version", functionVersion, 1);
204 addFunction(globalData, "run", functionRun, 1);
205 addFunction(globalData, "load", functionLoad, 1);
206 addFunction(globalData, "checkSyntax", functionCheckSyntax, 1);
207 addFunction(globalData, "jscStack", functionJSCStack, 1);
208 addFunction(globalData, "readline", functionReadline, 0);
209 addFunction(globalData, "preciseTime", functionPreciseTime, 0);
210 #if ENABLE(SAMPLING_FLAGS)
211 addFunction(globalData, "setSamplingFlags", functionSetSamplingFlags, 1);
212 addFunction(globalData, "clearSamplingFlags", functionClearSamplingFlags, 1);
215 addConstructableFunction(globalData, "Uint8Array", constructJSUint8Array, 1);
216 addConstructableFunction(globalData, "Uint8ClampedArray", constructJSUint8ClampedArray, 1);
217 addConstructableFunction(globalData, "Uint16Array", constructJSUint16Array, 1);
218 addConstructableFunction(globalData, "Uint32Array", constructJSUint32Array, 1);
219 addConstructableFunction(globalData, "Int8Array", constructJSInt8Array, 1);
220 addConstructableFunction(globalData, "Int16Array", constructJSInt16Array, 1);
221 addConstructableFunction(globalData, "Int32Array", constructJSInt32Array, 1);
222 addConstructableFunction(globalData, "Float32Array", constructJSFloat32Array, 1);
223 addConstructableFunction(globalData, "Float64Array", constructJSFloat64Array, 1);
225 JSArray* array = constructEmptyArray(globalExec());
226 for (size_t i = 0; i < arguments.size(); ++i)
227 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]), false);
228 putDirect(globalData, Identifier(globalExec(), "arguments"), array);
231 void addFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
233 Identifier identifier(globalExec(), name);
234 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier.ustring(), function));
237 void addConstructableFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
239 Identifier identifier(globalExec(), name);
240 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier.ustring(), function, NoIntrinsic, function));
243 COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
244 ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
246 const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, 0, ExecState::globalObjectTable, CREATE_METHOD_TABLE(GlobalObject) };
247 const GlobalObjectMethodTable GlobalObject::s_globalObjectMethodTable = { &allowsAccessFrom, &supportsProfiling, &supportsRichSourceInfo, &shouldInterruptScript, &javaScriptExperimentsEnabled };
250 GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure)
251 : JSGlobalObject(globalData, structure, &s_globalObjectMethodTable)
255 static inline SourceCode jscSource(const char* utf8, const UString& filename)
257 // Find the the first non-ascii character, or nul.
258 const char* pos = utf8;
261 size_t asciiLength = pos - utf8;
263 // Fast case - string is all ascii.
265 return makeSource(UString(utf8, asciiLength), filename);
267 // Slow case - contains non-ascii characters, use fromUTF8WithLatin1Fallback.
269 ASSERT(strlen(utf8) == asciiLength + strlen(pos));
270 String source = String::fromUTF8WithLatin1Fallback(utf8, asciiLength + strlen(pos));
271 return makeSource(source.impl(), filename);
274 EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
276 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
280 printf("%s", exec->argument(i).toString(exec)->value(exec).utf8().data());
285 return JSValue::encode(jsUndefined());
289 EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState* exec)
291 if (!exec->callerFrame()->hasHostCallFrameFlag())
292 exec->globalData().interpreter->dumpCallFrame(exec->callerFrame());
293 return JSValue::encode(jsUndefined());
297 EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
299 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec)->value(exec).utf8().data());
300 return JSValue::encode(jsUndefined());
303 EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState* exec)
305 fprintf(stderr, "--> %s\n", exec->argument(0).description());
306 return JSValue::encode(jsUndefined());
309 EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
311 String trace = "--> Stack trace:\n";
312 Vector<StackFrame> stackTrace;
313 Interpreter::getStackTrace(&exec->globalData(), stackTrace);
316 for (Vector<StackFrame>::iterator iter = stackTrace.begin(); iter < stackTrace.end(); iter++) {
317 StackFrame level = *iter;
318 trace += String::format(" %i %s\n", i, level.toString(exec).utf8().data());
321 fprintf(stderr, "%s", trace.utf8().data());
322 return JSValue::encode(jsUndefined());
325 EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
327 JSLockHolder lock(exec);
328 exec->heap()->collectAllGarbage();
329 return JSValue::encode(jsUndefined());
333 EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
335 JSLockHolder lock(exec);
336 exec->globalData().releaseExecutableMemory();
337 return JSValue::encode(jsUndefined());
341 EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
343 // We need this function for compatibility with the Mozilla JS tests but for now
344 // we don't actually do any version-specific handling
345 return JSValue::encode(jsUndefined());
348 EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
350 UString fileName = exec->argument(0).toString(exec)->value(exec);
352 if (!fillBufferWithContentsOfFile(fileName, script))
353 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
355 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
360 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &exception);
364 throwError(globalObject->globalExec(), exception);
365 return JSValue::encode(jsUndefined());
368 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
371 EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
373 UString fileName = exec->argument(0).toString(exec)->value(exec);
375 if (!fillBufferWithContentsOfFile(fileName, script))
376 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
378 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
380 JSValue evaluationException;
381 JSValue result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &evaluationException);
382 if (evaluationException)
383 throwError(exec, evaluationException);
384 return JSValue::encode(result);
387 EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
389 UString fileName = exec->argument(0).toString(exec)->value(exec);
391 if (!fillBufferWithContentsOfFile(fileName, script))
392 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
394 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
399 JSValue syntaxException;
400 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script.data(), fileName), &syntaxException);
404 throwError(exec, syntaxException);
405 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
408 #if ENABLE(SAMPLING_FLAGS)
409 EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
411 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
412 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
413 if ((flag >= 1) && (flag <= 32))
414 SamplingFlags::setFlag(flag);
416 return JSValue::encode(jsNull());
419 EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
421 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
422 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
423 if ((flag >= 1) && (flag <= 32))
424 SamplingFlags::clearFlag(flag);
426 return JSValue::encode(jsNull());
430 EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
432 Vector<char, 256> line;
434 while ((c = getchar()) != EOF) {
435 // FIXME: Should we also break on \r?
441 return JSValue::encode(jsString(exec, line.data()));
444 EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
446 return JSValue::encode(jsNumber(currentTime()));
449 EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*)
453 #if COMPILER(MSVC) && OS(WINCE)
454 // Without this, Visual Studio will complain that this method does not return a value.
455 return JSValue::encode(jsUndefined());
459 // Use SEH for Release builds only to get rid of the crash report dialog
460 // (luckily the same tests fail in Release and Debug builds so far). Need to
461 // be in a separate main function because the jscmain function requires object
464 #if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
466 #define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
472 int jscmain(int argc, char** argv);
474 int main(int argc, char** argv)
477 // Enabled IEEE754 denormal support.
480 env.__fpscr &= ~0x01000000u;
486 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
487 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
488 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
493 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
494 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
495 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
496 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
497 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
498 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
505 QCoreApplication app(argc, argv);
508 // Initialize JSC before getting JSGlobalData.
509 #if ENABLE(SAMPLING_REGIONS)
510 WTF::initializeMainThread();
512 JSC::initializeThreading();
514 // We can't use destructors in the following code because it uses Windows
515 // Structured Exception Handling
518 res = jscmain(argc, argv);
523 static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
527 Vector<char> scriptBuffer;
530 BytecodeGenerator::setDumpsGeneratedCode(true);
532 JSGlobalData& globalData = globalObject->globalData();
534 #if ENABLE(SAMPLING_FLAGS)
535 SamplingFlags::start();
539 for (size_t i = 0; i < scripts.size(); i++) {
540 if (scripts[i].isFile) {
541 fileName = scripts[i].argument;
542 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
543 return false; // fail early so we can catch missing files
544 script = scriptBuffer.data();
546 script = scripts[i].argument;
547 fileName = "[Command Line]";
550 globalData.startSampling();
552 JSValue evaluationException;
553 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script, fileName), JSValue(), &evaluationException);
554 success = success && !evaluationException;
555 if (dump && !evaluationException)
556 printf("End: %s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
557 if (evaluationException) {
558 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
559 Identifier stackID(globalObject->globalExec(), "stack");
560 JSValue stackValue = evaluationException.get(globalObject->globalExec(), stackID);
561 if (!stackValue.isUndefinedOrNull())
562 printf("%s\n", stackValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
565 globalData.stopSampling();
566 globalObject->globalExec()->clearException();
569 #if ENABLE(SAMPLING_FLAGS)
570 SamplingFlags::stop();
572 #if ENABLE(SAMPLING_REGIONS)
573 SamplingRegion::dump();
575 globalData.dumpSampleData(globalObject->globalExec());
576 #if ENABLE(SAMPLING_COUNTERS)
577 AbstractSamplingCounter::dump();
579 #if ENABLE(REGEXP_TRACING)
580 globalData.dumpRegExpTrace();
585 #define RUNNING_FROM_XCODE 0
587 static void runInteractive(GlobalObject* globalObject)
589 UString interpreterName("Interpreter");
592 #if HAVE(READLINE) && !RUNNING_FROM_XCODE
593 char* line = readline(interactivePrompt);
598 JSValue evaluationException;
599 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line, interpreterName), JSValue(), &evaluationException);
602 printf("%s", interactivePrompt);
603 Vector<char, 256> line;
605 while ((c = getchar()) != EOF) {
606 // FIXME: Should we also break on \r?
615 JSValue evaluationException;
616 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line.data(), interpreterName), JSValue(), &evaluationException);
618 if (evaluationException)
619 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
621 printf("%s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
623 globalObject->globalExec()->clearException();
628 static NO_RETURN void printUsageStatement(bool help = false)
630 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
631 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
632 fprintf(stderr, " -e Evaluate argument as script code\n");
633 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
634 fprintf(stderr, " -h|--help Prints this help message\n");
635 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
637 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
639 fprintf(stderr, " -x Output exit code before terminating\n");
640 fprintf(stderr, "\n");
641 fprintf(stderr, " --options Dumps all JSC VM options and exits\n");
642 fprintf(stderr, " --dumpOptions Dumps all JSC VM options before continuing\n");
643 fprintf(stderr, " --<jsc VM option>=<value> Sets the specified JSC VM option\n");
644 fprintf(stderr, "\n");
646 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
649 void CommandLine::parseArguments(int argc, char** argv)
652 bool needToDumpOptions = false;
653 bool needToExit = false;
655 for (; i < argc; ++i) {
656 const char* arg = argv[i];
657 if (!strcmp(arg, "-f")) {
659 printUsageStatement();
660 m_scripts.append(Script(true, argv[i]));
663 if (!strcmp(arg, "-e")) {
665 printUsageStatement();
666 m_scripts.append(Script(false, argv[i]));
669 if (!strcmp(arg, "-i")) {
670 m_interactive = true;
673 if (!strcmp(arg, "-d")) {
677 if (!strcmp(arg, "-s")) {
679 signal(SIGILL, _exit);
680 signal(SIGFPE, _exit);
681 signal(SIGBUS, _exit);
682 signal(SIGSEGV, _exit);
686 if (!strcmp(arg, "-x")) {
690 if (!strcmp(arg, "--")) {
694 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
695 printUsageStatement(true);
697 if (!strcmp(arg, "--options")) {
698 needToDumpOptions = true;
702 if (!strcmp(arg, "--dumpOptions")) {
703 needToDumpOptions = true;
707 // See if the -- option is a JSC VM option.
708 // NOTE: At this point, we know that the arg starts with "--". Skip it.
709 if (JSC::Options::setOption(&arg[2])) {
710 // The arg was recognized as a VM option and has been parsed.
711 continue; // Just continue with the next arg.
714 // This arg is not recognized by the VM nor by jsc. Pass it on to the
716 m_scripts.append(Script(true, argv[i]));
719 if (m_scripts.isEmpty())
720 m_interactive = true;
722 for (; i < argc; ++i)
723 m_arguments.append(argv[i]);
725 if (needToDumpOptions)
726 JSC::Options::dumpAllOptions(stderr);
731 int jscmain(int argc, char** argv)
733 // Note that the options parsing can affect JSGlobalData creation, and thus
735 CommandLine options(argc, argv);
736 RefPtr<JSGlobalData> globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap);
737 JSLockHolder lock(globalData.get());
740 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.m_arguments);
741 bool success = runWithScripts(globalObject, options.m_scripts, options.m_dump);
742 if (options.m_interactive && success)
743 runInteractive(globalObject);
745 result = success ? 0 : 3;
747 if (options.m_exitCode)
748 printf("jsc exiting %d\n", result);
753 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
755 FILE* f = fopen(fileName.utf8().data(), "r");
757 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
761 size_t bufferSize = 0;
762 size_t bufferCapacity = 1024;
764 buffer.resize(bufferCapacity);
766 while (!feof(f) && !ferror(f)) {
767 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
768 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
770 buffer.resize(bufferCapacity);
774 buffer[bufferSize] = '\0';
776 if (buffer[0] == '#' && buffer[1] == '!')
777 buffer[0] = buffer[1] = '/';