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 "CurrentTime.h"
28 #include "ExceptionHelpers.h"
29 #include "InitializeThreading.h"
31 #include "JSFunction.h"
34 #include "SamplingTool.h"
45 #include <readline/history.h>
46 #include <readline/readline.h>
57 #if COMPILER(MSVC) && !OS(WINCE)
64 #include <QCoreApplication>
71 static void cleanupGlobalData(JSGlobalData*);
72 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
74 static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
75 static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
76 static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
78 static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
80 static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
81 static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
82 static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
83 static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
84 static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
85 static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
86 static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
88 #if ENABLE(SAMPLING_FLAGS)
89 static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
90 static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
97 Script(bool isFile, char *argument)
113 Vector<Script> scripts;
114 Vector<UString> arguments;
117 static const char interactivePrompt[] = "> ";
118 static const UString interpreterName("Interpreter");
124 long getElapsedMS(); // call stop() first
131 void StopWatch::start()
133 m_startTime = currentTime();
136 void StopWatch::stop()
138 m_stopTime = currentTime();
141 long StopWatch::getElapsedMS()
143 return static_cast<long>((m_stopTime - m_startTime) * 1000);
146 class GlobalObject : public JSGlobalObject {
148 GlobalObject(JSGlobalData&, Structure*);
151 typedef JSGlobalObject Base;
153 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
155 GlobalObject* object = new (allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure);
156 object->finishCreation(globalData, arguments);
159 virtual UString className() const { return "global"; }
162 void finishCreation(JSGlobalData& globalData, const Vector<UString>& arguments)
164 Base::finishCreation(globalData, this);
165 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "debug"), functionDebug));
166 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "print"), functionPrint));
167 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "quit"), functionQuit));
168 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "gc"), functionGC));
170 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "releaseExecutableMemory"), functionReleaseExecutableMemory));
172 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "version"), functionVersion));
173 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "run"), functionRun));
174 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "load"), functionLoad));
175 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "checkSyntax"), functionCheckSyntax));
176 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "readline"), functionReadline));
177 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "preciseTime"), functionPreciseTime));
179 #if ENABLE(SAMPLING_FLAGS)
180 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "setSamplingFlags"), functionSetSamplingFlags));
181 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "clearSamplingFlags"), functionClearSamplingFlags));
184 JSObject* array = constructEmptyArray(globalExec());
185 for (size_t i = 0; i < arguments.size(); ++i)
186 array->put(globalExec(), i, jsString(globalExec(), arguments[i]));
187 putDirect(globalExec()->globalData(), Identifier(globalExec(), "arguments"), array);
190 COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
191 ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
193 GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure)
194 : JSGlobalObject(globalData, structure)
198 EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
200 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
204 printf("%s", exec->argument(i).toString(exec).utf8().data());
209 return JSValue::encode(jsUndefined());
212 EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
214 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec).utf8().data());
215 return JSValue::encode(jsUndefined());
218 EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
220 JSLock lock(SilenceAssertionsOnly);
221 exec->heap()->collectAllGarbage();
222 return JSValue::encode(jsUndefined());
226 EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
228 JSLock lock(SilenceAssertionsOnly);
229 exec->globalData().releaseExecutableMemory();
230 return JSValue::encode(jsUndefined());
234 EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
236 // We need this function for compatibility with the Mozilla JS tests but for now
237 // we don't actually do any version-specific handling
238 return JSValue::encode(jsUndefined());
241 EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
243 UString fileName = exec->argument(0).toString(exec);
245 if (!fillBufferWithContentsOfFile(fileName, script))
246 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
248 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
252 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
255 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
258 EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
260 UString fileName = exec->argument(0).toString(exec);
262 if (!fillBufferWithContentsOfFile(fileName, script))
263 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
265 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
267 JSValue evaluationException;
268 JSValue result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName), JSValue(), &evaluationException);
269 if (evaluationException)
270 throwError(exec, evaluationException);
271 return JSValue::encode(result);
274 EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
276 UString fileName = exec->argument(0).toString(exec);
278 if (!fillBufferWithContentsOfFile(fileName, script))
279 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
281 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
286 JSValue syntaxException;
287 bool validSyntax = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName), &syntaxException);
291 throwError(exec, syntaxException);
292 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
295 #if ENABLE(SAMPLING_FLAGS)
296 EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
298 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
299 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
300 if ((flag >= 1) && (flag <= 32))
301 SamplingFlags::setFlag(flag);
303 return JSValue::encode(jsNull());
306 EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
308 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
309 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
310 if ((flag >= 1) && (flag <= 32))
311 SamplingFlags::clearFlag(flag);
313 return JSValue::encode(jsNull());
317 EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
319 Vector<char, 256> line;
321 while ((c = getchar()) != EOF) {
322 // FIXME: Should we also break on \r?
328 return JSValue::encode(jsString(exec, line.data()));
331 EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
333 return JSValue::encode(jsNumber(currentTime()));
336 EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
338 // Technically, destroying the heap in the middle of JS execution is a no-no,
339 // but we want to maintain compatibility with the Mozilla test suite, so
340 // we pretend that execution has terminated to avoid ASSERTs, then tear down the heap.
341 exec->globalData().dynamicGlobalObject = 0;
343 cleanupGlobalData(&exec->globalData());
346 #if COMPILER(MSVC) && OS(WINCE)
347 // Without this, Visual Studio will complain that this method does not return a value.
348 return JSValue::encode(jsUndefined());
352 // Use SEH for Release builds only to get rid of the crash report dialog
353 // (luckily the same tests fail in Release and Debug builds so far). Need to
354 // be in a separate main function because the jscmain function requires object
357 #if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
359 #define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
365 int jscmain(int argc, char** argv, JSGlobalData*);
367 int main(int argc, char** argv)
371 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
372 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
373 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
378 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
379 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
380 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
381 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
382 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
383 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
390 QCoreApplication app(argc, argv);
393 // Initialize JSC before getting JSGlobalData.
394 JSC::initializeThreading();
396 // We can't use destructors in the following code because it uses Windows
397 // Structured Exception Handling
399 JSGlobalData* globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap).leakRef();
401 res = jscmain(argc, argv, globalData);
404 cleanupGlobalData(globalData);
408 static void cleanupGlobalData(JSGlobalData* globalData)
410 JSLock lock(SilenceAssertionsOnly);
411 globalData->clearBuiltinStructures();
412 globalData->heap.destroy();
416 static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
420 Vector<char> scriptBuffer;
423 BytecodeGenerator::setDumpsGeneratedCode(true);
425 JSGlobalData& globalData = globalObject->globalData();
427 #if ENABLE(SAMPLING_FLAGS)
428 SamplingFlags::start();
432 for (size_t i = 0; i < scripts.size(); i++) {
433 if (scripts[i].isFile) {
434 fileName = scripts[i].argument;
435 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
436 return false; // fail early so we can catch missing files
437 script = scriptBuffer.data();
439 script = scripts[i].argument;
440 fileName = "[Command Line]";
443 globalData.startSampling();
445 JSValue evaluationException;
446 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName), JSValue(), &evaluationException);
447 success = success && !evaluationException;
449 if (evaluationException)
450 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec()).utf8().data());
452 printf("End: %s\n", returnValue.toString(globalObject->globalExec()).utf8().data());
455 globalData.stopSampling();
456 globalObject->globalExec()->clearException();
459 #if ENABLE(SAMPLING_FLAGS)
460 SamplingFlags::stop();
462 globalData.dumpSampleData(globalObject->globalExec());
463 #if ENABLE(SAMPLING_COUNTERS)
464 AbstractSamplingCounter::dump();
466 #if ENABLE(REGEXP_TRACING)
467 globalData.dumpRegExpTrace();
472 #define RUNNING_FROM_XCODE 0
474 static void runInteractive(GlobalObject* globalObject)
477 #if HAVE(READLINE) && !RUNNING_FROM_XCODE
478 char* line = readline(interactivePrompt);
483 JSValue evaluationException;
484 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line, interpreterName), JSValue(), &evaluationException);
487 printf("%s", interactivePrompt);
488 Vector<char, 256> line;
490 while ((c = getchar()) != EOF) {
491 // FIXME: Should we also break on \r?
500 JSValue evaluationException;
501 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line.data(), interpreterName), JSValue(), &evaluationException);
503 if (evaluationException)
504 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec()).utf8().data());
506 printf("%s\n", returnValue.toString(globalObject->globalExec()).utf8().data());
508 globalObject->globalExec()->clearException();
513 static NO_RETURN void printUsageStatement(JSGlobalData* globalData, bool help = false)
515 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
516 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
517 fprintf(stderr, " -e Evaluate argument as script code\n");
518 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
519 fprintf(stderr, " -h|--help Prints this help message\n");
520 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
522 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
525 cleanupGlobalData(globalData);
526 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
529 static void parseArguments(int argc, char** argv, Options& options, JSGlobalData* globalData)
532 for (; i < argc; ++i) {
533 const char* arg = argv[i];
534 if (!strcmp(arg, "-f")) {
536 printUsageStatement(globalData);
537 options.scripts.append(Script(true, argv[i]));
540 if (!strcmp(arg, "-e")) {
542 printUsageStatement(globalData);
543 options.scripts.append(Script(false, argv[i]));
546 if (!strcmp(arg, "-i")) {
547 options.interactive = true;
550 if (!strcmp(arg, "-d")) {
554 if (!strcmp(arg, "-s")) {
556 signal(SIGILL, _exit);
557 signal(SIGFPE, _exit);
558 signal(SIGBUS, _exit);
559 signal(SIGSEGV, _exit);
563 if (!strcmp(arg, "--")) {
567 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
568 printUsageStatement(globalData, true);
569 options.scripts.append(Script(true, argv[i]));
572 if (options.scripts.isEmpty())
573 options.interactive = true;
575 for (; i < argc; ++i)
576 options.arguments.append(argv[i]);
579 int jscmain(int argc, char** argv, JSGlobalData* globalData)
581 JSLock lock(SilenceAssertionsOnly);
584 parseArguments(argc, argv, options, globalData);
586 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.arguments);
587 bool success = runWithScripts(globalObject, options.scripts, options.dump);
588 if (options.interactive && success)
589 runInteractive(globalObject);
591 return success ? 0 : 3;
594 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
596 FILE* f = fopen(fileName.utf8().data(), "r");
598 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
602 size_t bufferSize = 0;
603 size_t bufferCapacity = 1024;
605 buffer.resize(bufferCapacity);
607 while (!feof(f) && !ferror(f)) {
608 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
609 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
611 buffer.resize(bufferCapacity);
615 buffer[bufferSize] = '\0';
617 if (buffer[0] == '#' && buffer[1] == '!')
618 buffer[0] = buffer[1] = '/';