2009-06-25 Dimitri Glazkov <dglazkov@chromium.org>
[webbrowser.git] / JavaScriptCore / jsc.cpp
blob20d6694ab56f54fee2e030db77e32e28d2d0f0b0
1 /*
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.
23 #include "config.h"
25 #include "BytecodeGenerator.h"
26 #include "Completion.h"
27 #include "InitializeThreading.h"
28 #include "JSArray.h"
29 #include "JSFunction.h"
30 #include "JSLock.h"
31 #include "PrototypeFunction.h"
32 #include "SamplingTool.h"
33 #include <math.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
38 #if !PLATFORM(WIN_OS)
39 #include <unistd.h>
40 #endif
42 #if HAVE(READLINE)
43 #include <readline/history.h>
44 #include <readline/readline.h>
45 #endif
47 #if HAVE(SYS_TIME_H)
48 #include <sys/time.h>
49 #endif
51 #if PLATFORM(UNIX)
52 #include <signal.h>
53 #endif
55 #if COMPILER(MSVC) && !PLATFORM(WINCE)
56 #include <crtdbg.h>
57 #include <windows.h>
58 #include <mmsystem.h>
59 #endif
61 #if PLATFORM(QT)
62 #include <QCoreApplication>
63 #include <QDateTime>
64 #endif
66 using namespace JSC;
67 using namespace WTF;
69 static void cleanupGlobalData(JSGlobalData*);
70 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
72 static JSValue JSC_HOST_CALL functionPrint(ExecState*, JSObject*, JSValue, const ArgList&);
73 static JSValue JSC_HOST_CALL functionDebug(ExecState*, JSObject*, JSValue, const ArgList&);
74 static JSValue JSC_HOST_CALL functionGC(ExecState*, JSObject*, JSValue, const ArgList&);
75 static JSValue JSC_HOST_CALL functionVersion(ExecState*, JSObject*, JSValue, const ArgList&);
76 static JSValue JSC_HOST_CALL functionRun(ExecState*, JSObject*, JSValue, const ArgList&);
77 static JSValue JSC_HOST_CALL functionLoad(ExecState*, JSObject*, JSValue, const ArgList&);
78 static JSValue JSC_HOST_CALL functionCheckSyntax(ExecState*, JSObject*, JSValue, const ArgList&);
79 static JSValue JSC_HOST_CALL functionReadline(ExecState*, JSObject*, JSValue, const ArgList&);
80 static NO_RETURN JSValue JSC_HOST_CALL functionQuit(ExecState*, JSObject*, JSValue, const ArgList&);
82 #if ENABLE(SAMPLING_FLAGS)
83 static JSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*, JSObject*, JSValue, const ArgList&);
84 static JSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*, JSObject*, JSValue, const ArgList&);
85 #endif
87 struct Script {
88 bool isFile;
89 char *argument;
91 Script(bool isFile, char *argument)
92 : isFile(isFile)
93 , argument(argument)
98 struct Options {
99 Options()
100 : interactive(false)
101 , dump(false)
105 bool interactive;
106 bool dump;
107 Vector<Script> scripts;
108 Vector<UString> arguments;
111 static const char interactivePrompt[] = "> ";
112 static const UString interpreterName("Interpreter");
114 class StopWatch {
115 public:
116 void start();
117 void stop();
118 long getElapsedMS(); // call stop() first
120 private:
121 #if PLATFORM(QT)
122 uint m_startTime;
123 uint m_stopTime;
124 #elif PLATFORM(WIN_OS)
125 DWORD m_startTime;
126 DWORD m_stopTime;
127 #else
128 // Windows does not have timeval, disabling this class for now (bug 7399)
129 timeval m_startTime;
130 timeval m_stopTime;
131 #endif
134 void StopWatch::start()
136 #if PLATFORM(QT)
137 QDateTime t = QDateTime::currentDateTime();
138 m_startTime = t.toTime_t() * 1000 + t.time().msec();
139 #elif PLATFORM(WIN_OS)
140 m_startTime = timeGetTime();
141 #else
142 gettimeofday(&m_startTime, 0);
143 #endif
146 void StopWatch::stop()
148 #if PLATFORM(QT)
149 QDateTime t = QDateTime::currentDateTime();
150 m_stopTime = t.toTime_t() * 1000 + t.time().msec();
151 #elif PLATFORM(WIN_OS)
152 m_stopTime = timeGetTime();
153 #else
154 gettimeofday(&m_stopTime, 0);
155 #endif
158 long StopWatch::getElapsedMS()
160 #if PLATFORM(WIN_OS) || PLATFORM(QT)
161 return m_stopTime - m_startTime;
162 #else
163 timeval elapsedTime;
164 timersub(&m_stopTime, &m_startTime, &elapsedTime);
166 return elapsedTime.tv_sec * 1000 + lroundf(elapsedTime.tv_usec / 1000.0f);
167 #endif
170 class GlobalObject : public JSGlobalObject {
171 public:
172 GlobalObject(const Vector<UString>& arguments);
173 virtual UString className() const { return "global"; }
175 COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
176 ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
178 GlobalObject::GlobalObject(const Vector<UString>& arguments)
179 : JSGlobalObject()
181 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "debug"), functionDebug));
182 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "print"), functionPrint));
183 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 0, Identifier(globalExec(), "quit"), functionQuit));
184 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 0, Identifier(globalExec(), "gc"), functionGC));
185 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "version"), functionVersion));
186 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "run"), functionRun));
187 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "load"), functionLoad));
188 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "checkSyntax"), functionCheckSyntax));
189 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 0, Identifier(globalExec(), "readline"), functionReadline));
191 #if ENABLE(SAMPLING_FLAGS)
192 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "setSamplingFlags"), functionSetSamplingFlags));
193 putDirectFunction(globalExec(), new (globalExec()) NativeFunctionWrapper(globalExec(), prototypeFunctionStructure(), 1, Identifier(globalExec(), "clearSamplingFlags"), functionClearSamplingFlags));
194 #endif
196 JSObject* array = constructEmptyArray(globalExec());
197 for (size_t i = 0; i < arguments.size(); ++i)
198 array->put(globalExec(), i, jsString(globalExec(), arguments[i]));
199 putDirect(Identifier(globalExec(), "arguments"), array);
202 JSValue JSC_HOST_CALL functionPrint(ExecState* exec, JSObject*, JSValue, const ArgList& args)
204 for (unsigned i = 0; i < args.size(); ++i) {
205 if (i != 0)
206 putchar(' ');
208 printf("%s", args.at(i).toString(exec).UTF8String().c_str());
211 putchar('\n');
212 fflush(stdout);
213 return jsUndefined();
216 JSValue JSC_HOST_CALL functionDebug(ExecState* exec, JSObject*, JSValue, const ArgList& args)
218 fprintf(stderr, "--> %s\n", args.at(0).toString(exec).UTF8String().c_str());
219 return jsUndefined();
222 JSValue JSC_HOST_CALL functionGC(ExecState* exec, JSObject*, JSValue, const ArgList&)
224 JSLock lock(false);
225 exec->heap()->collect();
226 return jsUndefined();
229 JSValue JSC_HOST_CALL functionVersion(ExecState*, JSObject*, JSValue, const ArgList&)
231 // We need this function for compatibility with the Mozilla JS tests but for now
232 // we don't actually do any version-specific handling
233 return jsUndefined();
236 JSValue JSC_HOST_CALL functionRun(ExecState* exec, JSObject*, JSValue, const ArgList& args)
238 StopWatch stopWatch;
239 UString fileName = args.at(0).toString(exec);
240 Vector<char> script;
241 if (!fillBufferWithContentsOfFile(fileName, script))
242 return throwError(exec, GeneralError, "Could not open file.");
244 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
246 stopWatch.start();
247 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
248 stopWatch.stop();
250 return jsNumber(globalObject->globalExec(), stopWatch.getElapsedMS());
253 JSValue JSC_HOST_CALL functionLoad(ExecState* exec, JSObject* o, JSValue v, const ArgList& args)
255 UNUSED_PARAM(o);
256 UNUSED_PARAM(v);
257 UString fileName = args.at(0).toString(exec);
258 Vector<char> script;
259 if (!fillBufferWithContentsOfFile(fileName, script))
260 return throwError(exec, GeneralError, "Could not open file.");
262 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
263 Completion result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
264 if (result.complType() == Throw)
265 exec->setException(result.value());
266 return result.value();
269 JSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec, JSObject* o, JSValue v, const ArgList& args)
271 UNUSED_PARAM(o);
272 UNUSED_PARAM(v);
273 UString fileName = args.at(0).toString(exec);
274 Vector<char> script;
275 if (!fillBufferWithContentsOfFile(fileName, script))
276 return throwError(exec, GeneralError, "Could not open file.");
278 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
279 Completion result = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName));
280 if (result.complType() == Throw)
281 exec->setException(result.value());
282 return result.value();
285 #if ENABLE(SAMPLING_FLAGS)
286 JSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec, JSObject*, JSValue, const ArgList& args)
288 for (unsigned i = 0; i < args.size(); ++i) {
289 unsigned flag = static_cast<unsigned>(args.at(i).toNumber(exec));
290 if ((flag >= 1) && (flag <= 32))
291 SamplingFlags::setFlag(flag);
293 return jsNull();
296 JSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec, JSObject*, JSValue, const ArgList& args)
298 for (unsigned i = 0; i < args.size(); ++i) {
299 unsigned flag = static_cast<unsigned>(args.at(i).toNumber(exec));
300 if ((flag >= 1) && (flag <= 32))
301 SamplingFlags::clearFlag(flag);
303 return jsNull();
305 #endif
307 JSValue JSC_HOST_CALL functionReadline(ExecState* exec, JSObject*, JSValue, const ArgList&)
309 Vector<char, 256> line;
310 int c;
311 while ((c = getchar()) != EOF) {
312 // FIXME: Should we also break on \r?
313 if (c == '\n')
314 break;
315 line.append(c);
317 line.append('\0');
318 return jsString(exec, line.data());
321 JSValue JSC_HOST_CALL functionQuit(ExecState* exec, JSObject*, JSValue, const ArgList&)
323 cleanupGlobalData(&exec->globalData());
324 exit(EXIT_SUCCESS);
327 // Use SEH for Release builds only to get rid of the crash report dialog
328 // (luckily the same tests fail in Release and Debug builds so far). Need to
329 // be in a separate main function because the jscmain function requires object
330 // unwinding.
332 #if COMPILER(MSVC) && !defined(_DEBUG)
333 #define TRY __try {
334 #define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
335 #else
336 #define TRY
337 #define EXCEPT(x)
338 #endif
340 int jscmain(int argc, char** argv, JSGlobalData*);
342 int main(int argc, char** argv)
344 #if defined(_DEBUG) && PLATFORM(WIN_OS)
345 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
346 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
347 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
348 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
349 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
350 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
351 #endif
353 #if COMPILER(MSVC) && !PLATFORM(WINCE)
354 timeBeginPeriod(1);
355 #endif
357 #if PLATFORM(QT)
358 QCoreApplication app(argc, argv);
359 #endif
361 // Initialize JSC before getting JSGlobalData.
362 JSC::initializeThreading();
364 // We can't use destructors in the following code because it uses Windows
365 // Structured Exception Handling
366 int res = 0;
367 JSGlobalData* globalData = JSGlobalData::create().releaseRef();
369 res = jscmain(argc, argv, globalData);
370 EXCEPT(res = 3)
372 cleanupGlobalData(globalData);
373 return res;
376 static void cleanupGlobalData(JSGlobalData* globalData)
378 JSLock lock(false);
379 globalData->heap.destroy();
380 globalData->deref();
383 static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
385 UString script;
386 UString fileName;
387 Vector<char> scriptBuffer;
389 if (dump)
390 BytecodeGenerator::setDumpsGeneratedCode(true);
392 #if ENABLE(OPCODE_SAMPLING)
393 Interpreter* interpreter = globalObject->globalData()->interpreter;
394 interpreter->setSampler(new SamplingTool(interpreter));
395 interpreter->sampler()->setup();
396 #endif
397 #if ENABLE(SAMPLING_FLAGS)
398 SamplingFlags::start();
399 #endif
401 bool success = true;
402 for (size_t i = 0; i < scripts.size(); i++) {
403 if (scripts[i].isFile) {
404 fileName = scripts[i].argument;
405 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
406 return false; // fail early so we can catch missing files
407 script = scriptBuffer.data();
408 } else {
409 script = scripts[i].argument;
410 fileName = "[Command Line]";
413 #if ENABLE(SAMPLING_THREAD)
414 SamplingThread::start();
415 #endif
417 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName));
418 success = success && completion.complType() != Throw;
419 if (dump) {
420 if (completion.complType() == Throw)
421 printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).ascii());
422 else
423 printf("End: %s\n", completion.value().toString(globalObject->globalExec()).ascii());
426 #if ENABLE(SAMPLING_THREAD)
427 SamplingThread::stop();
428 #endif
430 globalObject->globalExec()->clearException();
433 #if ENABLE(SAMPLING_FLAGS)
434 SamplingFlags::stop();
435 #endif
436 #if ENABLE(OPCODE_SAMPLING)
437 interpreter->sampler()->dump(globalObject->globalExec());
438 delete interpreter->sampler();
439 #endif
440 #if ENABLE(SAMPLING_COUNTERS)
441 AbstractSamplingCounter::dump();
442 #endif
443 return success;
446 static
447 #if !HAVE(READLINE)
448 NO_RETURN
449 #endif
450 void runInteractive(GlobalObject* globalObject)
452 while (true) {
453 #if HAVE(READLINE)
454 char* line = readline(interactivePrompt);
455 if (!line)
456 break;
457 if (line[0])
458 add_history(line);
459 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line, interpreterName));
460 free(line);
461 #else
462 puts(interactivePrompt);
463 Vector<char, 256> line;
464 int c;
465 while ((c = getchar()) != EOF) {
466 // FIXME: Should we also break on \r?
467 if (c == '\n')
468 break;
469 line.append(c);
471 line.append('\0');
472 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line.data(), interpreterName));
473 #endif
474 if (completion.complType() == Throw)
475 printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).ascii());
476 else
477 printf("%s\n", completion.value().toString(globalObject->globalExec()).UTF8String().c_str());
479 globalObject->globalExec()->clearException();
481 printf("\n");
484 static NO_RETURN void printUsageStatement(JSGlobalData* globalData, bool help = false)
486 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
487 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
488 fprintf(stderr, " -e Evaluate argument as script code\n");
489 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
490 fprintf(stderr, " -h|--help Prints this help message\n");
491 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
492 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
494 cleanupGlobalData(globalData);
495 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
498 static void parseArguments(int argc, char** argv, Options& options, JSGlobalData* globalData)
500 int i = 1;
501 for (; i < argc; ++i) {
502 const char* arg = argv[i];
503 if (strcmp(arg, "-f") == 0) {
504 if (++i == argc)
505 printUsageStatement(globalData);
506 options.scripts.append(Script(true, argv[i]));
507 continue;
509 if (strcmp(arg, "-e") == 0) {
510 if (++i == argc)
511 printUsageStatement(globalData);
512 options.scripts.append(Script(false, argv[i]));
513 continue;
515 if (strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) {
516 printUsageStatement(globalData, true);
518 if (strcmp(arg, "-i") == 0) {
519 options.interactive = true;
520 continue;
522 if (strcmp(arg, "-d") == 0) {
523 options.dump = true;
524 continue;
526 if (strcmp(arg, "-s") == 0) {
527 #if PLATFORM(UNIX)
528 signal(SIGILL, _exit);
529 signal(SIGFPE, _exit);
530 signal(SIGBUS, _exit);
531 signal(SIGSEGV, _exit);
532 #endif
533 continue;
535 if (strcmp(arg, "--") == 0) {
536 ++i;
537 break;
539 options.scripts.append(Script(true, argv[i]));
542 if (options.scripts.isEmpty())
543 options.interactive = true;
545 for (; i < argc; ++i)
546 options.arguments.append(argv[i]);
549 int jscmain(int argc, char** argv, JSGlobalData* globalData)
551 JSLock lock(false);
553 Options options;
554 parseArguments(argc, argv, options, globalData);
556 GlobalObject* globalObject = new (globalData) GlobalObject(options.arguments);
557 bool success = runWithScripts(globalObject, options.scripts, options.dump);
558 if (options.interactive && success)
559 runInteractive(globalObject);
561 return success ? 0 : 3;
564 static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
566 FILE* f = fopen(fileName.UTF8String().c_str(), "r");
567 if (!f) {
568 fprintf(stderr, "Could not open file: %s\n", fileName.UTF8String().c_str());
569 return false;
572 size_t buffer_size = 0;
573 size_t buffer_capacity = 1024;
575 buffer.resize(buffer_capacity);
577 while (!feof(f) && !ferror(f)) {
578 buffer_size += fread(buffer.data() + buffer_size, 1, buffer_capacity - buffer_size, f);
579 if (buffer_size == buffer_capacity) { // guarantees space for trailing '\0'
580 buffer_capacity *= 2;
581 buffer.resize(buffer_capacity);
584 fclose(f);
585 buffer[buffer_size] = '\0';
587 return true;