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 "PrototypeFunction.h"
35 #include "SamplingTool.h"
46 #include <readline/history.h>
47 #include <readline/readline.h>
58 #if COMPILER(MSVC) && !OS(WINCE)
65 #include <QCoreApplication>
72 static void cleanupGlobalData(JSGlobalData*);
73 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
75 static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
76 static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
77 static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
78 static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
79 static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
80 static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
81 static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
82 static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
83 static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
85 #if ENABLE(SAMPLING_FLAGS)
86 static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
87 static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
94 Script(bool isFile, char *argument)
110 Vector<Script> scripts;
111 Vector<UString> arguments;
114 static const char interactivePrompt[] = "> ";
115 static const UString interpreterName("Interpreter");
121 long getElapsedMS(); // call stop() first
128 void StopWatch::start()
130 m_startTime = currentTime();
133 void StopWatch::stop()
135 m_stopTime = currentTime();
138 long StopWatch::getElapsedMS()
140 return static_cast<long>((m_stopTime - m_startTime) * 1000);
143 class GlobalObject : public JSGlobalObject {
145 GlobalObject(const Vector<UString>& arguments);
146 virtual UString className() const { return "global"; }
148 COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
149 ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
151 GlobalObject::GlobalObject(const Vector<UString>& arguments)
154 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "debug"), functionDebug));
155 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "print"), functionPrint));
156 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 0, Identifier(globalExec(), "quit"), functionQuit));
157 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 0, Identifier(globalExec(), "gc"), functionGC));
158 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "version"), functionVersion));
159 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "run"), functionRun));
160 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "load"), functionLoad));
161 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "checkSyntax"), functionCheckSyntax));
162 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 0, Identifier(globalExec(), "readline"), functionReadline));
164 #if ENABLE(SAMPLING_FLAGS)
165 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "setSamplingFlags"), functionSetSamplingFlags));
166 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), this, prototypeFunctionStructure(), 1, Identifier(globalExec(), "clearSamplingFlags"), functionClearSamplingFlags));
169 JSObject* array = constructEmptyArray(globalExec());
170 for (size_t i = 0; i < arguments.size(); ++i)
171 array->put(globalExec(), i, jsString(globalExec(), arguments[i]));
172 putDirect(globalExec()->globalData(), Identifier(globalExec(), "arguments"), array);
175 EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
177 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
181 printf("%s", exec->argument(i).toString(exec).utf8().data());
186 return JSValue::encode(jsUndefined());
189 EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
191 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec).utf8().data());
192 return JSValue::encode(jsUndefined());
195 EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
197 JSLock lock(SilenceAssertionsOnly);
198 exec->heap()->collectAllGarbage();
199 return JSValue::encode(jsUndefined());
202 EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
204 // We need this function for compatibility with the Mozilla JS tests but for now
205 // we don't actually do any version-specific handling
206 return JSValue::encode(jsUndefined());
209 EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
211 UString fileName = exec->argument(0).toString(exec);
213 if (!fillBufferWithContentsOfFile(fileName, script))
214 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
216 GlobalObject* globalObject = new (&exec->globalData()) GlobalObject(Vector<UString>());
220 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
223 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
226 EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
228 UString fileName = exec->argument(0).toString(exec);
230 if (!fillBufferWithContentsOfFile(fileName, script))
231 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
233 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
234 Completion result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
235 if (result.complType() == Throw)
236 throwError(exec, result.value());
237 return JSValue::encode(result.value());
240 EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
242 UString fileName = exec->argument(0).toString(exec);
244 if (!fillBufferWithContentsOfFile(fileName, script))
245 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
247 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
251 Completion result = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName));
254 if (result.complType() == Throw)
255 throwError(exec, result.value());
256 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
259 #if ENABLE(SAMPLING_FLAGS)
260 EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
262 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
263 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
264 if ((flag >= 1) && (flag <= 32))
265 SamplingFlags::setFlag(flag);
267 return JSValue::encode(jsNull());
270 EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
272 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
273 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
274 if ((flag >= 1) && (flag <= 32))
275 SamplingFlags::clearFlag(flag);
277 return JSValue::encode(jsNull());
281 EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
283 Vector<char, 256> line;
285 while ((c = getchar()) != EOF) {
286 // FIXME: Should we also break on \r?
292 return JSValue::encode(jsString(exec, line.data()));
295 EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
297 // Technically, destroying the heap in the middle of JS execution is a no-no,
298 // but we want to maintain compatibility with the Mozilla test suite, so
299 // we pretend that execution has terminated to avoid ASSERTs, then tear down the heap.
300 exec->globalData().dynamicGlobalObject = 0;
302 cleanupGlobalData(&exec->globalData());
305 #if COMPILER(MSVC) && OS(WINCE)
306 // Without this, Visual Studio will complain that this method does not return a value.
307 return JSValue::encode(jsUndefined());
311 // Use SEH for Release builds only to get rid of the crash report dialog
312 // (luckily the same tests fail in Release and Debug builds so far). Need to
313 // be in a separate main function because the jscmain function requires object
316 #if COMPILER(MSVC) && !defined(_DEBUG) && !OS(WINCE)
318 #define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
324 int jscmain(int argc, char** argv, JSGlobalData*);
326 int main(int argc, char** argv)
328 #if defined(_DEBUG) && OS(WINDOWS)
329 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
330 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
331 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
332 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
333 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
334 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
337 #if COMPILER(MSVC) && !OS(WINCE)
342 QCoreApplication app(argc, argv);
345 // Initialize JSC before getting JSGlobalData.
346 JSC::initializeThreading();
348 // We can't use destructors in the following code because it uses Windows
349 // Structured Exception Handling
351 JSGlobalData* globalData = JSGlobalData::create(ThreadStackTypeLarge).leakRef();
353 res = jscmain(argc, argv, globalData);
356 cleanupGlobalData(globalData);
360 static void cleanupGlobalData(JSGlobalData* globalData)
362 JSLock lock(SilenceAssertionsOnly);
363 globalData->heap.destroy();
367 static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
371 Vector<char> scriptBuffer;
374 BytecodeGenerator::setDumpsGeneratedCode(true);
376 JSGlobalData& globalData = globalObject->globalData();
378 #if ENABLE(SAMPLING_FLAGS)
379 SamplingFlags::start();
383 for (size_t i = 0; i < scripts.size(); i++) {
384 if (scripts[i].isFile) {
385 fileName = scripts[i].argument;
386 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
387 return false; // fail early so we can catch missing files
388 script = scriptBuffer.data();
390 script = scripts[i].argument;
391 fileName = "[Command Line]";
394 globalData.startSampling();
396 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName));
397 success = success && completion.complType() != Throw;
399 if (completion.complType() == Throw)
400 printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
402 printf("End: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
405 globalData.stopSampling();
406 globalObject->globalExec()->clearException();
409 #if ENABLE(SAMPLING_FLAGS)
410 SamplingFlags::stop();
412 globalData.dumpSampleData(globalObject->globalExec());
413 #if ENABLE(SAMPLING_COUNTERS)
414 AbstractSamplingCounter::dump();
416 #if ENABLE(REGEXP_TRACING)
417 globalData.dumpRegExpTrace();
422 #define RUNNING_FROM_XCODE 0
424 static void runInteractive(GlobalObject* globalObject)
427 #if HAVE(READLINE) && !RUNNING_FROM_XCODE
428 char* line = readline(interactivePrompt);
433 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line, interpreterName));
436 printf("%s", interactivePrompt);
437 Vector<char, 256> line;
439 while ((c = getchar()) != EOF) {
440 // FIXME: Should we also break on \r?
448 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line.data(), interpreterName));
450 if (completion.complType() == Throw)
451 printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
453 printf("%s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
455 globalObject->globalExec()->clearException();
460 static NO_RETURN void printUsageStatement(JSGlobalData* globalData, bool help = false)
462 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
463 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
464 fprintf(stderr, " -e Evaluate argument as script code\n");
465 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
466 fprintf(stderr, " -h|--help Prints this help message\n");
467 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
469 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
472 cleanupGlobalData(globalData);
473 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
476 static void parseArguments(int argc, char** argv, Options& options, JSGlobalData* globalData)
479 for (; i < argc; ++i) {
480 const char* arg = argv[i];
481 if (!strcmp(arg, "-f")) {
483 printUsageStatement(globalData);
484 options.scripts.append(Script(true, argv[i]));
487 if (!strcmp(arg, "-e")) {
489 printUsageStatement(globalData);
490 options.scripts.append(Script(false, argv[i]));
493 if (!strcmp(arg, "-i")) {
494 options.interactive = true;
497 if (!strcmp(arg, "-d")) {
501 if (!strcmp(arg, "-s")) {
503 signal(SIGILL, _exit);
504 signal(SIGFPE, _exit);
505 signal(SIGBUS, _exit);
506 signal(SIGSEGV, _exit);
510 if (!strcmp(arg, "--")) {
514 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
515 printUsageStatement(globalData, true);
516 options.scripts.append(Script(true, argv[i]));
519 if (options.scripts.isEmpty())
520 options.interactive = true;
522 for (; i < argc; ++i)
523 options.arguments.append(argv[i]);
526 int jscmain(int argc, char** argv, JSGlobalData* globalData)
528 JSLock lock(SilenceAssertionsOnly);
531 parseArguments(argc, argv, options, globalData);
533 GlobalObject* globalObject = new (globalData) GlobalObject(options.arguments);
534 bool success = runWithScripts(globalObject, options.scripts, options.dump);
535 if (options.interactive && success)
536 runInteractive(globalObject);
538 return success ? 0 : 3;
541 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
543 FILE* f = fopen(fileName.utf8().data(), "r");
545 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
549 size_t bufferSize = 0;
550 size_t bufferCapacity = 1024;
552 buffer.resize(bufferCapacity);
554 while (!feof(f) && !ferror(f)) {
555 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
556 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
558 buffer.resize(bufferCapacity);
562 buffer[bufferSize] = '\0';
564 if (buffer[0] == '#' && buffer[1] == '!')
565 buffer[0] = buffer[1] = '/';