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