]> git.saurik.com Git - apple/javascriptcore.git/blame - jsc.cpp
JavaScriptCore-1097.3.3.tar.gz
[apple/javascriptcore.git] / jsc.cpp
CommitLineData
9dae56ea
A
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)
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
25#include "BytecodeGenerator.h"
26#include "Completion.h"
6fe7ccc8 27#include <wtf/CurrentTime.h>
14957cd0 28#include "ExceptionHelpers.h"
9dae56ea 29#include "InitializeThreading.h"
6fe7ccc8 30#include "Interpreter.h"
9dae56ea 31#include "JSArray.h"
6fe7ccc8 32#include "JSCTypedArrayStubs.h"
ba379fdc 33#include "JSFunction.h"
9dae56ea 34#include "JSLock.h"
f9bf01c6 35#include "JSString.h"
6fe7ccc8 36#include <wtf/MainThread.h>
9dae56ea
A
37#include "SamplingTool.h"
38#include <math.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42
f9bf01c6 43#if !OS(WINDOWS)
9dae56ea
A
44#include <unistd.h>
45#endif
46
47#if HAVE(READLINE)
6fe7ccc8
A
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
9dae56ea
A
51#include <readline/history.h>
52#include <readline/readline.h>
6fe7ccc8 53#undef Function
9dae56ea
A
54#endif
55
56#if HAVE(SYS_TIME_H)
57#include <sys/time.h>
58#endif
59
ba379fdc 60#if HAVE(SIGNAL_H)
9dae56ea
A
61#include <signal.h>
62#endif
63
f9bf01c6 64#if COMPILER(MSVC) && !OS(WINCE)
9dae56ea 65#include <crtdbg.h>
ba379fdc 66#include <mmsystem.h>
f9bf01c6 67#include <windows.h>
9dae56ea
A
68#endif
69
70#if PLATFORM(QT)
71#include <QCoreApplication>
72#include <QDateTime>
73#endif
74
6fe7ccc8
A
75#if CPU(ARM_THUMB2)
76#include <fenv.h>
77#include <arm/arch.h>
78#endif
79
9dae56ea
A
80using namespace JSC;
81using namespace WTF;
82
9dae56ea
A
83static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
84
14957cd0
A
85static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
86static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
6fe7ccc8 87static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
14957cd0
A
88static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
89#ifndef NDEBUG
90static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
91#endif
92static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
93static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
94static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
95static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
96static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
6fe7ccc8 97static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
14957cd0 98static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
ba379fdc
A
99
100#if ENABLE(SAMPLING_FLAGS)
14957cd0
A
101static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
102static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
ba379fdc
A
103#endif
104
105struct Script {
106 bool isFile;
f9bf01c6
A
107 char* argument;
108
ba379fdc
A
109 Script(bool isFile, char *argument)
110 : isFile(isFile)
111 , argument(argument)
112 {
113 }
114};
9dae56ea 115
6fe7ccc8
A
116struct CommandLine {
117 CommandLine()
9dae56ea
A
118 : interactive(false)
119 , dump(false)
120 {
121 }
122
123 bool interactive;
124 bool dump;
ba379fdc 125 Vector<Script> scripts;
9dae56ea
A
126 Vector<UString> arguments;
127};
128
129static const char interactivePrompt[] = "> ";
9dae56ea
A
130
131class StopWatch {
132public:
133 void start();
134 void stop();
135 long getElapsedMS(); // call stop() first
136
137private:
f9bf01c6
A
138 double m_startTime;
139 double m_stopTime;
9dae56ea
A
140};
141
142void StopWatch::start()
143{
f9bf01c6 144 m_startTime = currentTime();
9dae56ea
A
145}
146
147void StopWatch::stop()
148{
f9bf01c6 149 m_stopTime = currentTime();
9dae56ea
A
150}
151
152long StopWatch::getElapsedMS()
153{
f9bf01c6 154 return static_cast<long>((m_stopTime - m_startTime) * 1000);
9dae56ea
A
155}
156
157class GlobalObject : public JSGlobalObject {
6fe7ccc8
A
158private:
159 GlobalObject(JSGlobalData&, Structure*);
160
9dae56ea 161public:
6fe7ccc8
A
162 typedef JSGlobalObject Base;
163
164 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
165 {
166 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure);
167 object->finishCreation(globalData, arguments);
168 return object;
169 }
170
171 static const ClassInfo s_info;
172
173 static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
174 {
175 return Structure::create(globalData, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), &s_info);
176 }
177
178protected:
179 void finishCreation(JSGlobalData& globalData, const Vector<UString>& arguments)
180 {
181 Base::finishCreation(globalData);
182
183 addFunction(globalData, "debug", functionDebug, 1);
184 addFunction(globalData, "print", functionPrint, 1);
185 addFunction(globalData, "quit", functionQuit, 0);
186 addFunction(globalData, "gc", functionGC, 0);
187#ifndef NDEBUG
188 addFunction(globalData, "releaseExecutableMemory", functionReleaseExecutableMemory, 0);
189#endif
190 addFunction(globalData, "version", functionVersion, 1);
191 addFunction(globalData, "run", functionRun, 1);
192 addFunction(globalData, "load", functionLoad, 1);
193 addFunction(globalData, "checkSyntax", functionCheckSyntax, 1);
194 addFunction(globalData, "jscStack", functionJSCStack, 1);
195 addFunction(globalData, "readline", functionReadline, 0);
196 addFunction(globalData, "preciseTime", functionPreciseTime, 0);
197#if ENABLE(SAMPLING_FLAGS)
198 addFunction(globalData, "setSamplingFlags", functionSetSamplingFlags, 1);
199 addFunction(globalData, "clearSamplingFlags", functionClearSamplingFlags, 1);
200#endif
201
202 addConstructableFunction(globalData, "Uint8Array", constructJSUint8Array, 1);
203 addConstructableFunction(globalData, "Uint8ClampedArray", constructJSUint8ClampedArray, 1);
204 addConstructableFunction(globalData, "Uint16Array", constructJSUint16Array, 1);
205 addConstructableFunction(globalData, "Uint32Array", constructJSUint32Array, 1);
206 addConstructableFunction(globalData, "Int8Array", constructJSInt8Array, 1);
207 addConstructableFunction(globalData, "Int16Array", constructJSInt16Array, 1);
208 addConstructableFunction(globalData, "Int32Array", constructJSInt32Array, 1);
209 addConstructableFunction(globalData, "Float32Array", constructJSFloat32Array, 1);
210 addConstructableFunction(globalData, "Float64Array", constructJSFloat64Array, 1);
211
212 JSArray* array = constructEmptyArray(globalExec());
213 for (size_t i = 0; i < arguments.size(); ++i)
214 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]), false);
215 putDirect(globalData, Identifier(globalExec(), "arguments"), array);
216 }
217
218 void addFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
219 {
220 Identifier identifier(globalExec(), name);
221 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier, function));
222 }
223
224 void addConstructableFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
225 {
226 Identifier identifier(globalExec(), name);
227 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier, function, NoIntrinsic, function));
228 }
9dae56ea
A
229};
230COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
231ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
232
6fe7ccc8
A
233const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, 0, ExecState::globalObjectTable, CREATE_METHOD_TABLE(GlobalObject) };
234
235GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure)
14957cd0 236 : JSGlobalObject(globalData, structure)
9dae56ea 237{
6fe7ccc8 238}
9dae56ea 239
6fe7ccc8
A
240static inline SourceCode jscSource(const char* utf8, const UString& filename)
241{
242 // Find the the first non-ascii character, or nul.
243 const char* pos = utf8;
244 while (*pos > 0)
245 pos++;
246 size_t asciiLength = pos - utf8;
247
248 // Fast case - string is all ascii.
249 if (!*pos)
250 return makeSource(UString(utf8, asciiLength), filename);
251
252 // Slow case - contains non-ascii characters, use fromUTF8WithLatin1Fallback.
253 ASSERT(*pos < 0);
254 ASSERT(strlen(utf8) == asciiLength + strlen(pos));
255 String source = String::fromUTF8WithLatin1Fallback(utf8, asciiLength + strlen(pos));
256 return makeSource(source.impl(), filename);
9dae56ea
A
257}
258
14957cd0 259EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
9dae56ea 260{
14957cd0 261 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
f9bf01c6 262 if (i)
9dae56ea 263 putchar(' ');
f9bf01c6 264
6fe7ccc8 265 printf("%s", exec->argument(i).toString(exec)->value(exec).utf8().data());
9dae56ea 266 }
f9bf01c6 267
9dae56ea
A
268 putchar('\n');
269 fflush(stdout);
14957cd0 270 return JSValue::encode(jsUndefined());
9dae56ea
A
271}
272
14957cd0 273EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
9dae56ea 274{
6fe7ccc8
A
275 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec)->value(exec).utf8().data());
276 return JSValue::encode(jsUndefined());
277}
278
279EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
280{
281 String trace = "--> Stack trace:\n";
282 Vector<StackFrame> stackTrace;
283 Interpreter::getStackTrace(&exec->globalData(), stackTrace);
284 int i = 0;
285
286 for (Vector<StackFrame>::iterator iter = stackTrace.begin(); iter < stackTrace.end(); iter++) {
287 StackFrame level = *iter;
288 trace += String::format(" %i %s\n", i, level.toString(exec).utf8().data());
289 i++;
290 }
291 fprintf(stderr, "%s", trace.utf8().data());
14957cd0 292 return JSValue::encode(jsUndefined());
9dae56ea
A
293}
294
14957cd0 295EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
9dae56ea 296{
6fe7ccc8 297 JSLockHolder lock(exec);
f9bf01c6 298 exec->heap()->collectAllGarbage();
14957cd0
A
299 return JSValue::encode(jsUndefined());
300}
301
302#ifndef NDEBUG
303EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
304{
6fe7ccc8 305 JSLockHolder lock(exec);
14957cd0
A
306 exec->globalData().releaseExecutableMemory();
307 return JSValue::encode(jsUndefined());
9dae56ea 308}
14957cd0 309#endif
9dae56ea 310
14957cd0 311EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
9dae56ea
A
312{
313 // We need this function for compatibility with the Mozilla JS tests but for now
314 // we don't actually do any version-specific handling
14957cd0 315 return JSValue::encode(jsUndefined());
9dae56ea
A
316}
317
14957cd0 318EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
9dae56ea 319{
6fe7ccc8 320 UString fileName = exec->argument(0).toString(exec)->value(exec);
9dae56ea
A
321 Vector<char> script;
322 if (!fillBufferWithContentsOfFile(fileName, script))
14957cd0 323 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
9dae56ea 324
6fe7ccc8 325 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
9dae56ea 326
6fe7ccc8 327 JSValue exception;
14957cd0 328 StopWatch stopWatch;
9dae56ea 329 stopWatch.start();
6fe7ccc8 330 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &exception);
9dae56ea
A
331 stopWatch.stop();
332
6fe7ccc8
A
333 if (!!exception) {
334 throwError(globalObject->globalExec(), exception);
335 return JSValue::encode(jsUndefined());
336 }
337
14957cd0 338 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
9dae56ea
A
339}
340
14957cd0 341EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
9dae56ea 342{
6fe7ccc8 343 UString fileName = exec->argument(0).toString(exec)->value(exec);
9dae56ea
A
344 Vector<char> script;
345 if (!fillBufferWithContentsOfFile(fileName, script))
14957cd0 346 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
9dae56ea
A
347
348 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
6fe7ccc8
A
349
350 JSValue evaluationException;
351 JSValue result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &evaluationException);
352 if (evaluationException)
353 throwError(exec, evaluationException);
354 return JSValue::encode(result);
ba379fdc 355}
9dae56ea 356
14957cd0 357EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
ba379fdc 358{
6fe7ccc8 359 UString fileName = exec->argument(0).toString(exec)->value(exec);
ba379fdc
A
360 Vector<char> script;
361 if (!fillBufferWithContentsOfFile(fileName, script))
14957cd0 362 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
ba379fdc
A
363
364 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
14957cd0
A
365
366 StopWatch stopWatch;
367 stopWatch.start();
6fe7ccc8
A
368
369 JSValue syntaxException;
370 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script.data(), fileName), &syntaxException);
14957cd0
A
371 stopWatch.stop();
372
6fe7ccc8
A
373 if (!validSyntax)
374 throwError(exec, syntaxException);
14957cd0 375 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
9dae56ea
A
376}
377
ba379fdc 378#if ENABLE(SAMPLING_FLAGS)
14957cd0 379EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
ba379fdc 380{
14957cd0
A
381 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
382 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
ba379fdc
A
383 if ((flag >= 1) && (flag <= 32))
384 SamplingFlags::setFlag(flag);
385 }
14957cd0 386 return JSValue::encode(jsNull());
ba379fdc
A
387}
388
14957cd0 389EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
ba379fdc 390{
14957cd0
A
391 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
392 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
ba379fdc
A
393 if ((flag >= 1) && (flag <= 32))
394 SamplingFlags::clearFlag(flag);
395 }
14957cd0 396 return JSValue::encode(jsNull());
ba379fdc
A
397}
398#endif
399
14957cd0 400EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
9dae56ea
A
401{
402 Vector<char, 256> line;
403 int c;
404 while ((c = getchar()) != EOF) {
405 // FIXME: Should we also break on \r?
406 if (c == '\n')
407 break;
408 line.append(c);
409 }
410 line.append('\0');
14957cd0 411 return JSValue::encode(jsString(exec, line.data()));
9dae56ea
A
412}
413
6fe7ccc8 414EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
9dae56ea 415{
6fe7ccc8
A
416 return JSValue::encode(jsNumber(currentTime()));
417}
f9bf01c6 418
6fe7ccc8
A
419EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*)
420{
9dae56ea 421 exit(EXIT_SUCCESS);
f9bf01c6
A
422
423#if COMPILER(MSVC) && OS(WINCE)
424 // Without this, Visual Studio will complain that this method does not return a value.
14957cd0 425 return JSValue::encode(jsUndefined());
f9bf01c6 426#endif
9dae56ea
A
427}
428
429// Use SEH for Release builds only to get rid of the crash report dialog
430// (luckily the same tests fail in Release and Debug builds so far). Need to
431// be in a separate main function because the jscmain function requires object
432// unwinding.
433
6fe7ccc8 434#if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
9dae56ea
A
435#define TRY __try {
436#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
437#else
438#define TRY
439#define EXCEPT(x)
440#endif
441
6fe7ccc8 442int jscmain(int argc, char** argv);
9dae56ea
A
443
444int main(int argc, char** argv)
445{
6fe7ccc8
A
446#if CPU(ARM_THUMB2)
447 // Enabled IEEE754 denormal support.
448 fenv_t env;
449 fegetenv( &env );
450 env.__fpscr &= ~0x01000000u;
451 fesetenv( &env );
452#endif
453
14957cd0
A
454#if OS(WINDOWS)
455#if !OS(WINCE)
456 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
457 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
458 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
459 ::SetErrorMode(0);
460#endif
461
462#if defined(_DEBUG)
9dae56ea
A
463 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
464 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
465 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
466 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
467 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
468 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
469#endif
470
ba379fdc
A
471 timeBeginPeriod(1);
472#endif
473
9dae56ea
A
474#if PLATFORM(QT)
475 QCoreApplication app(argc, argv);
476#endif
477
478 // Initialize JSC before getting JSGlobalData.
6fe7ccc8 479 WTF::initializeMainThread();
9dae56ea
A
480 JSC::initializeThreading();
481
482 // We can't use destructors in the following code because it uses Windows
483 // Structured Exception Handling
484 int res = 0;
9dae56ea 485 TRY
6fe7ccc8 486 res = jscmain(argc, argv);
9dae56ea 487 EXCEPT(res = 3)
9dae56ea
A
488 return res;
489}
490
ba379fdc 491static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
9dae56ea 492{
6fe7ccc8 493 const char* script;
ba379fdc
A
494 UString fileName;
495 Vector<char> scriptBuffer;
9dae56ea
A
496
497 if (dump)
498 BytecodeGenerator::setDumpsGeneratedCode(true);
499
14957cd0 500 JSGlobalData& globalData = globalObject->globalData();
f9bf01c6 501
ba379fdc
A
502#if ENABLE(SAMPLING_FLAGS)
503 SamplingFlags::start();
9dae56ea
A
504#endif
505
506 bool success = true;
ba379fdc
A
507 for (size_t i = 0; i < scripts.size(); i++) {
508 if (scripts[i].isFile) {
509 fileName = scripts[i].argument;
510 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
511 return false; // fail early so we can catch missing files
512 script = scriptBuffer.data();
513 } else {
514 script = scripts[i].argument;
515 fileName = "[Command Line]";
516 }
9dae56ea 517
14957cd0 518 globalData.startSampling();
ba379fdc 519
6fe7ccc8
A
520 JSValue evaluationException;
521 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script, fileName), JSValue(), &evaluationException);
522 success = success && !evaluationException;
523 if (dump && !evaluationException)
524 printf("End: %s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
525 if (evaluationException) {
526 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
527 Identifier stackID(globalObject->globalExec(), "stack");
528 JSValue stackValue = evaluationException.get(globalObject->globalExec(), stackID);
529 if (!stackValue.isUndefinedOrNull())
530 printf("%s\n", stackValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
9dae56ea
A
531 }
532
14957cd0 533 globalData.stopSampling();
ba379fdc 534 globalObject->globalExec()->clearException();
9dae56ea
A
535 }
536
ba379fdc
A
537#if ENABLE(SAMPLING_FLAGS)
538 SamplingFlags::stop();
6fe7ccc8
A
539#endif
540#if ENABLE(SAMPLING_REGIONS)
541 SamplingRegion::dump();
ba379fdc 542#endif
14957cd0 543 globalData.dumpSampleData(globalObject->globalExec());
ba379fdc
A
544#if ENABLE(SAMPLING_COUNTERS)
545 AbstractSamplingCounter::dump();
14957cd0
A
546#endif
547#if ENABLE(REGEXP_TRACING)
548 globalData.dumpRegExpTrace();
9dae56ea
A
549#endif
550 return success;
551}
552
ba379fdc
A
553#define RUNNING_FROM_XCODE 0
554
9dae56ea
A
555static void runInteractive(GlobalObject* globalObject)
556{
6fe7ccc8
A
557 UString interpreterName("Interpreter");
558
9dae56ea 559 while (true) {
ba379fdc 560#if HAVE(READLINE) && !RUNNING_FROM_XCODE
9dae56ea
A
561 char* line = readline(interactivePrompt);
562 if (!line)
563 break;
564 if (line[0])
565 add_history(line);
6fe7ccc8
A
566 JSValue evaluationException;
567 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line, interpreterName), JSValue(), &evaluationException);
9dae56ea
A
568 free(line);
569#else
ba379fdc 570 printf("%s", interactivePrompt);
9dae56ea
A
571 Vector<char, 256> line;
572 int c;
573 while ((c = getchar()) != EOF) {
574 // FIXME: Should we also break on \r?
575 if (c == '\n')
576 break;
577 line.append(c);
578 }
ba379fdc
A
579 if (line.isEmpty())
580 break;
9dae56ea 581 line.append('\0');
6fe7ccc8
A
582
583 JSValue evaluationException;
584 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line.data(), interpreterName), JSValue(), &evaluationException);
9dae56ea 585#endif
6fe7ccc8
A
586 if (evaluationException)
587 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
9dae56ea 588 else
6fe7ccc8 589 printf("%s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
9dae56ea
A
590
591 globalObject->globalExec()->clearException();
592 }
593 printf("\n");
594}
595
6fe7ccc8 596static NO_RETURN void printUsageStatement(bool help = false)
9dae56ea
A
597{
598 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
599 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
ba379fdc 600 fprintf(stderr, " -e Evaluate argument as script code\n");
9dae56ea
A
601 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
602 fprintf(stderr, " -h|--help Prints this help message\n");
603 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
ba379fdc 604#if HAVE(SIGNAL_H)
9dae56ea 605 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
ba379fdc
A
606#endif
607
ba379fdc 608 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
9dae56ea
A
609}
610
6fe7ccc8 611static void parseArguments(int argc, char** argv, CommandLine& options)
9dae56ea
A
612{
613 int i = 1;
614 for (; i < argc; ++i) {
615 const char* arg = argv[i];
f9bf01c6 616 if (!strcmp(arg, "-f")) {
9dae56ea 617 if (++i == argc)
6fe7ccc8 618 printUsageStatement();
ba379fdc
A
619 options.scripts.append(Script(true, argv[i]));
620 continue;
621 }
f9bf01c6 622 if (!strcmp(arg, "-e")) {
ba379fdc 623 if (++i == argc)
6fe7ccc8 624 printUsageStatement();
ba379fdc 625 options.scripts.append(Script(false, argv[i]));
9dae56ea
A
626 continue;
627 }
f9bf01c6 628 if (!strcmp(arg, "-i")) {
9dae56ea
A
629 options.interactive = true;
630 continue;
631 }
f9bf01c6 632 if (!strcmp(arg, "-d")) {
9dae56ea
A
633 options.dump = true;
634 continue;
635 }
f9bf01c6 636 if (!strcmp(arg, "-s")) {
ba379fdc 637#if HAVE(SIGNAL_H)
9dae56ea
A
638 signal(SIGILL, _exit);
639 signal(SIGFPE, _exit);
640 signal(SIGBUS, _exit);
641 signal(SIGSEGV, _exit);
642#endif
643 continue;
644 }
f9bf01c6 645 if (!strcmp(arg, "--")) {
9dae56ea
A
646 ++i;
647 break;
648 }
f9bf01c6 649 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
6fe7ccc8 650 printUsageStatement(true);
ba379fdc 651 options.scripts.append(Script(true, argv[i]));
9dae56ea 652 }
f9bf01c6 653
ba379fdc 654 if (options.scripts.isEmpty())
9dae56ea 655 options.interactive = true;
f9bf01c6 656
9dae56ea
A
657 for (; i < argc; ++i)
658 options.arguments.append(argv[i]);
659}
660
6fe7ccc8 661int jscmain(int argc, char** argv)
9dae56ea 662{
6fe7ccc8
A
663
664 RefPtr<JSGlobalData> globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap);
665 JSLockHolder lock(globalData.get());
9dae56ea 666
6fe7ccc8
A
667 CommandLine options;
668 parseArguments(argc, argv, options);
9dae56ea 669
6fe7ccc8 670 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.arguments);
ba379fdc 671 bool success = runWithScripts(globalObject, options.scripts, options.dump);
9dae56ea
A
672 if (options.interactive && success)
673 runInteractive(globalObject);
674
675 return success ? 0 : 3;
676}
677
678static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
679{
14957cd0 680 FILE* f = fopen(fileName.utf8().data(), "r");
9dae56ea 681 if (!f) {
14957cd0 682 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
9dae56ea
A
683 return false;
684 }
685
f9bf01c6
A
686 size_t bufferSize = 0;
687 size_t bufferCapacity = 1024;
9dae56ea 688
f9bf01c6 689 buffer.resize(bufferCapacity);
9dae56ea
A
690
691 while (!feof(f) && !ferror(f)) {
f9bf01c6
A
692 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
693 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
694 bufferCapacity *= 2;
695 buffer.resize(bufferCapacity);
9dae56ea
A
696 }
697 }
698 fclose(f);
f9bf01c6 699 buffer[bufferSize] = '\0';
9dae56ea 700
14957cd0
A
701 if (buffer[0] == '#' && buffer[1] == '!')
702 buffer[0] = buffer[1] = '/';
703
9dae56ea
A
704 return true;
705}