source: webkit/trunk/Source/JavaScriptCore/jsc.cpp@ 92706

Last change on this file since 92706 was 92706, checked in by [email protected], 14 years ago

Add ParentClass typedef in all JSC classes
https://bugs.webkit.org/show_bug.cgi?id=65731

Patch by Mark Hahnenberg <[email protected]> on 2011-08-09
Reviewed by Oliver Hunt.

Source/JavaScriptCore:

Just added the Base typedefs in all the classes that are a subclass of JSCell
to point at their parent classes. This is a change to support future changes to the way
constructors and destructors are implemented in JS objects, among other things.

  • API/JSCallbackConstructor.h:
  • API/JSCallbackFunction.h:
  • API/JSCallbackObject.h:

(JSC::JSCallbackObject::createStructure):
(JSC::JSCallbackObject::visitChildren):

  • API/JSCallbackObjectFunctions.h:

(JSC::::asCallbackObject):
(JSC::::JSCallbackObject):
(JSC::::init):
(JSC::::className):
(JSC::::getOwnPropertySlot):
(JSC::::getOwnPropertyDescriptor):
(JSC::::put):
(JSC::::deleteProperty):
(JSC::::getConstructData):
(JSC::::construct):
(JSC::::hasInstance):
(JSC::::getCallData):
(JSC::::call):
(JSC::::getOwnPropertyNames):
(JSC::::toNumber):
(JSC::::toString):
(JSC::::setPrivate):
(JSC::::getPrivate):
(JSC::::inherits):
(JSC::::getStaticValue):
(JSC::::staticFunctionGetter):
(JSC::::callbackGetter):

  • debugger/DebuggerActivation.h:
  • jsc.cpp:
  • runtime/Arguments.h:
  • runtime/ArrayConstructor.h:
  • runtime/ArrayPrototype.h:
  • runtime/BooleanConstructor.h:
  • runtime/BooleanObject.h:
  • runtime/BooleanPrototype.h:
  • runtime/DateConstructor.h:
  • runtime/DateInstance.h:
  • runtime/DatePrototype.h:
  • runtime/Error.cpp:
  • runtime/ErrorConstructor.h:
  • runtime/ErrorInstance.h:
  • runtime/ErrorPrototype.h:
  • runtime/ExceptionHelpers.cpp:
  • runtime/Executable.h:
  • runtime/FunctionConstructor.h:
  • runtime/FunctionPrototype.h:
  • runtime/GetterSetter.h:
  • runtime/InternalFunction.h:
  • runtime/JSAPIValueWrapper.h:
  • runtime/JSActivation.h:
  • runtime/JSArray.h:
  • runtime/JSFunction.h:
  • runtime/JSGlobalObject.h:
  • runtime/JSNotAnObject.h:
  • runtime/JSONObject.h:
  • runtime/JSObject.h:
  • runtime/JSPropertyNameIterator.h:
  • runtime/JSStaticScopeObject.h:
  • runtime/JSString.h:
  • runtime/JSVariableObject.h:
  • runtime/JSWrapperObject.h:
  • runtime/MathObject.h:
  • runtime/NativeErrorConstructor.h:
  • runtime/NativeErrorPrototype.h:
  • runtime/NumberConstructor.h:
  • runtime/NumberObject.h:
  • runtime/NumberPrototype.h:
  • runtime/ObjectConstructor.h:
  • runtime/ObjectPrototype.h:
  • runtime/RegExp.h:
  • runtime/RegExpConstructor.h:
  • runtime/RegExpMatchesArray.h:
  • runtime/RegExpObject.h:

(JSC::RegExpObject::create):

  • runtime/RegExpPrototype.h:
  • runtime/ScopeChain.h:
  • runtime/StrictEvalActivation.h:
  • runtime/StringConstructor.h:
  • runtime/StringObject.h:
  • runtime/StringObjectThatMasqueradesAsUndefined.h:
  • runtime/StringPrototype.h:
  • runtime/Structure.h:
  • runtime/StructureChain.h:

Source/JavaScriptGlue:

Just added the Base typedefs in all the classes that are a subclass of JSCell
to point at their parent classes. This is a change to support future changes to the way
constructors and destructors are implemented in JS objects, among other things.

  • JSRun.h:
  • UserObjectImp.h:

Source/WebCore:

No new tests.

Just added the Base typedefs in all the classes that are a subclass of JSCell
to point at their parent classes. This is a change to support future changes to the way
constructors and destructors are implemented in JS objects, among other things.

  • bindings/js/JSAudioConstructor.h:
  • bindings/js/JSImageConstructor.h:
  • bindings/js/JSOptionConstructor.h:
  • bindings/scripts/CodeGeneratorJS.pm:

(GenerateHeader):
(GenerateConstructorDeclaration):

  • bindings/scripts/test/JS/JSTestInterface.cpp:
  • bindings/scripts/test/JS/JSTestInterface.h:
  • bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
  • bindings/scripts/test/JS/JSTestMediaQueryListListener.h:
  • bindings/scripts/test/JS/JSTestObj.cpp:
  • bindings/scripts/test/JS/JSTestObj.h:
  • bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
  • bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.h:
  • bridge/c/CRuntimeObject.h:
  • bridge/c/c_instance.cpp:
  • bridge/jni/jsc/JavaInstanceJSC.cpp:
  • bridge/jni/jsc/JavaRuntimeObject.h:
  • bridge/objc/ObjCRuntimeObject.h:
  • bridge/objc/objc_runtime.h:
  • bridge/qt/qt_instance.cpp:
  • bridge/qt/qt_pixmapruntime.cpp:
  • bridge/qt/qt_runtime.h:
  • bridge/runtime_array.h:
  • bridge/runtime_method.h:
  • bridge/runtime_object.h:
  • bridge/testqtbindings.cpp:

(Global::className):

Source/WebKit/mac:

Just added the Base typedefs in all the classes that are a subclass of JSCell
to point at their parent classes. This is a change to support future changes to the way
constructors and destructors are implemented in JS objects, among other things.

  • Plugins/Hosted/ProxyInstance.mm:
  • Plugins/Hosted/ProxyRuntimeObject.h:

Source/WebKit2:

Just added the Base typedefs in all the classes that are a subclass of JSCell
to point at their parent classes. This is a change to support future changes to the way
constructors and destructors are implemented in JS objects, among other things.

  • WebProcess/Plugins/Netscape/JSNPMethod.h:
  • WebProcess/Plugins/Netscape/JSNPObject.h:
  • Property svn:eol-style set to native
File size: 19.9 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Bjoern Graf ([email protected])
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"
27#include "CurrentTime.h"
28#include "ExceptionHelpers.h"
29#include "InitializeThreading.h"
30#include "JSArray.h"
31#include "JSFunction.h"
32#include "JSLock.h"
33#include "JSString.h"
34#include "SamplingTool.h"
35#include <math.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39
40#if !OS(WINDOWS)
41#include <unistd.h>
42#endif
43
44#if HAVE(READLINE)
45#include <readline/history.h>
46#include <readline/readline.h>
47#endif
48
49#if HAVE(SYS_TIME_H)
50#include <sys/time.h>
51#endif
52
53#if HAVE(SIGNAL_H)
54#include <signal.h>
55#endif
56
57#if COMPILER(MSVC) && !OS(WINCE)
58#include <crtdbg.h>
59#include <mmsystem.h>
60#include <windows.h>
61#endif
62
63#if PLATFORM(QT)
64#include <QCoreApplication>
65#include <QDateTime>
66#endif
67
68using namespace JSC;
69using namespace WTF;
70
71static void cleanupGlobalData(JSGlobalData*);
72static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
73
74static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
75static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
76static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
77#ifndef NDEBUG
78static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
79#endif
80static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
81static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
82static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
83static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
84static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
85static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
86static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
87
88#if ENABLE(SAMPLING_FLAGS)
89static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
90static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
91#endif
92
93struct Script {
94 bool isFile;
95 char* argument;
96
97 Script(bool isFile, char *argument)
98 : isFile(isFile)
99 , argument(argument)
100 {
101 }
102};
103
104struct Options {
105 Options()
106 : interactive(false)
107 , dump(false)
108 {
109 }
110
111 bool interactive;
112 bool dump;
113 Vector<Script> scripts;
114 Vector<UString> arguments;
115};
116
117static const char interactivePrompt[] = "> ";
118static const UString interpreterName("Interpreter");
119
120class StopWatch {
121public:
122 void start();
123 void stop();
124 long getElapsedMS(); // call stop() first
125
126private:
127 double m_startTime;
128 double m_stopTime;
129};
130
131void StopWatch::start()
132{
133 m_startTime = currentTime();
134}
135
136void StopWatch::stop()
137{
138 m_stopTime = currentTime();
139}
140
141long StopWatch::getElapsedMS()
142{
143 return static_cast<long>((m_stopTime - m_startTime) * 1000);
144}
145
146class GlobalObject : public JSGlobalObject {
147private:
148 GlobalObject(JSGlobalData&, Structure*, const Vector<UString>& arguments);
149
150public:
151 typedef JSGlobalObject Base;
152
153 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
154 {
155 return new (allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure, arguments);
156 }
157 virtual UString className() const { return "global"; }
158};
159COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
160ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
161
162GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
163 : JSGlobalObject(globalData, structure)
164{
165 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "debug"), functionDebug));
166 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "print"), functionPrint));
167 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "quit"), functionQuit));
168 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "gc"), functionGC));
169#ifndef NDEBUG
170 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "releaseExecutableMemory"), functionReleaseExecutableMemory));
171#endif
172 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "version"), functionVersion));
173 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "run"), functionRun));
174 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "load"), functionLoad));
175 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "checkSyntax"), functionCheckSyntax));
176 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "readline"), functionReadline));
177 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 0, Identifier(globalExec(), "preciseTime"), functionPreciseTime));
178
179#if ENABLE(SAMPLING_FLAGS)
180 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "setSamplingFlags"), functionSetSamplingFlags));
181 putDirectFunction(globalExec(), JSFunction::create(globalExec(), this, functionStructure(), 1, Identifier(globalExec(), "clearSamplingFlags"), functionClearSamplingFlags));
182#endif
183
184 JSObject* array = constructEmptyArray(globalExec());
185 for (size_t i = 0; i < arguments.size(); ++i)
186 array->put(globalExec(), i, jsString(globalExec(), arguments[i]));
187 putDirect(globalExec()->globalData(), Identifier(globalExec(), "arguments"), array);
188}
189
190EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
191{
192 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
193 if (i)
194 putchar(' ');
195
196 printf("%s", exec->argument(i).toString(exec).utf8().data());
197 }
198
199 putchar('\n');
200 fflush(stdout);
201 return JSValue::encode(jsUndefined());
202}
203
204EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
205{
206 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec).utf8().data());
207 return JSValue::encode(jsUndefined());
208}
209
210EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
211{
212 JSLock lock(SilenceAssertionsOnly);
213 exec->heap()->collectAllGarbage();
214 return JSValue::encode(jsUndefined());
215}
216
217#ifndef NDEBUG
218EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
219{
220 JSLock lock(SilenceAssertionsOnly);
221 exec->globalData().releaseExecutableMemory();
222 return JSValue::encode(jsUndefined());
223}
224#endif
225
226EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
227{
228 // We need this function for compatibility with the Mozilla JS tests but for now
229 // we don't actually do any version-specific handling
230 return JSValue::encode(jsUndefined());
231}
232
233EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
234{
235 UString fileName = exec->argument(0).toString(exec);
236 Vector<char> script;
237 if (!fillBufferWithContentsOfFile(fileName, script))
238 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
239
240 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
241
242 StopWatch stopWatch;
243 stopWatch.start();
244 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
245 stopWatch.stop();
246
247 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
248}
249
250EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
251{
252 UString fileName = exec->argument(0).toString(exec);
253 Vector<char> script;
254 if (!fillBufferWithContentsOfFile(fileName, script))
255 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
256
257 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
258 Completion result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script.data(), fileName));
259 if (result.complType() == Throw)
260 throwError(exec, result.value());
261 return JSValue::encode(result.value());
262}
263
264EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
265{
266 UString fileName = exec->argument(0).toString(exec);
267 Vector<char> script;
268 if (!fillBufferWithContentsOfFile(fileName, script))
269 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
270
271 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
272
273 StopWatch stopWatch;
274 stopWatch.start();
275 Completion result = checkSyntax(globalObject->globalExec(), makeSource(script.data(), fileName));
276 stopWatch.stop();
277
278 if (result.complType() == Throw)
279 throwError(exec, result.value());
280 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
281}
282
283#if ENABLE(SAMPLING_FLAGS)
284EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
285{
286 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
287 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
288 if ((flag >= 1) && (flag <= 32))
289 SamplingFlags::setFlag(flag);
290 }
291 return JSValue::encode(jsNull());
292}
293
294EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
295{
296 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
297 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
298 if ((flag >= 1) && (flag <= 32))
299 SamplingFlags::clearFlag(flag);
300 }
301 return JSValue::encode(jsNull());
302}
303#endif
304
305EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
306{
307 Vector<char, 256> line;
308 int c;
309 while ((c = getchar()) != EOF) {
310 // FIXME: Should we also break on \r?
311 if (c == '\n')
312 break;
313 line.append(c);
314 }
315 line.append('\0');
316 return JSValue::encode(jsString(exec, line.data()));
317}
318
319EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
320{
321 return JSValue::encode(jsNumber(currentTime()));
322}
323
324EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
325{
326 // Technically, destroying the heap in the middle of JS execution is a no-no,
327 // but we want to maintain compatibility with the Mozilla test suite, so
328 // we pretend that execution has terminated to avoid ASSERTs, then tear down the heap.
329 exec->globalData().dynamicGlobalObject = 0;
330
331 cleanupGlobalData(&exec->globalData());
332 exit(EXIT_SUCCESS);
333
334#if COMPILER(MSVC) && OS(WINCE)
335 // Without this, Visual Studio will complain that this method does not return a value.
336 return JSValue::encode(jsUndefined());
337#endif
338}
339
340// Use SEH for Release builds only to get rid of the crash report dialog
341// (luckily the same tests fail in Release and Debug builds so far). Need to
342// be in a separate main function because the jscmain function requires object
343// unwinding.
344
345#if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
346#define TRY __try {
347#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
348#else
349#define TRY
350#define EXCEPT(x)
351#endif
352
353int jscmain(int argc, char** argv, JSGlobalData*);
354
355int main(int argc, char** argv)
356{
357#if OS(WINDOWS)
358#if !OS(WINCE)
359 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
360 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
361 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
362 ::SetErrorMode(0);
363#endif
364
365#if defined(_DEBUG)
366 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
367 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
368 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
369 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
370 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
371 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
372#endif
373
374 timeBeginPeriod(1);
375#endif
376
377#if PLATFORM(QT)
378 QCoreApplication app(argc, argv);
379#endif
380
381 // Initialize JSC before getting JSGlobalData.
382 JSC::initializeThreading();
383
384 // We can't use destructors in the following code because it uses Windows
385 // Structured Exception Handling
386 int res = 0;
387 JSGlobalData* globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap).leakRef();
388 TRY
389 res = jscmain(argc, argv, globalData);
390 EXCEPT(res = 3)
391
392 cleanupGlobalData(globalData);
393 return res;
394}
395
396static void cleanupGlobalData(JSGlobalData* globalData)
397{
398 JSLock lock(SilenceAssertionsOnly);
399 globalData->clearBuiltinStructures();
400 globalData->heap.destroy();
401 globalData->deref();
402}
403
404static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
405{
406 UString script;
407 UString fileName;
408 Vector<char> scriptBuffer;
409
410 if (dump)
411 BytecodeGenerator::setDumpsGeneratedCode(true);
412
413 JSGlobalData& globalData = globalObject->globalData();
414
415#if ENABLE(SAMPLING_FLAGS)
416 SamplingFlags::start();
417#endif
418
419 bool success = true;
420 for (size_t i = 0; i < scripts.size(); i++) {
421 if (scripts[i].isFile) {
422 fileName = scripts[i].argument;
423 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
424 return false; // fail early so we can catch missing files
425 script = scriptBuffer.data();
426 } else {
427 script = scripts[i].argument;
428 fileName = "[Command Line]";
429 }
430
431 globalData.startSampling();
432
433 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(script, fileName));
434 success = success && completion.complType() != Throw;
435 if (dump) {
436 if (completion.complType() == Throw)
437 printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
438 else
439 printf("End: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
440 }
441
442 globalData.stopSampling();
443 globalObject->globalExec()->clearException();
444 }
445
446#if ENABLE(SAMPLING_FLAGS)
447 SamplingFlags::stop();
448#endif
449 globalData.dumpSampleData(globalObject->globalExec());
450#if ENABLE(SAMPLING_COUNTERS)
451 AbstractSamplingCounter::dump();
452#endif
453#if ENABLE(REGEXP_TRACING)
454 globalData.dumpRegExpTrace();
455#endif
456 return success;
457}
458
459#define RUNNING_FROM_XCODE 0
460
461static void runInteractive(GlobalObject* globalObject)
462{
463 while (true) {
464#if HAVE(READLINE) && !RUNNING_FROM_XCODE
465 char* line = readline(interactivePrompt);
466 if (!line)
467 break;
468 if (line[0])
469 add_history(line);
470 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line, interpreterName));
471 free(line);
472#else
473 printf("%s", interactivePrompt);
474 Vector<char, 256> line;
475 int c;
476 while ((c = getchar()) != EOF) {
477 // FIXME: Should we also break on \r?
478 if (c == '\n')
479 break;
480 line.append(c);
481 }
482 if (line.isEmpty())
483 break;
484 line.append('\0');
485 Completion completion = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), makeSource(line.data(), interpreterName));
486#endif
487 if (completion.complType() == Throw)
488 printf("Exception: %s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
489 else
490 printf("%s\n", completion.value().toString(globalObject->globalExec()).utf8().data());
491
492 globalObject->globalExec()->clearException();
493 }
494 printf("\n");
495}
496
497static NO_RETURN void printUsageStatement(JSGlobalData* globalData, bool help = false)
498{
499 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
500 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
501 fprintf(stderr, " -e Evaluate argument as script code\n");
502 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
503 fprintf(stderr, " -h|--help Prints this help message\n");
504 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
505#if HAVE(SIGNAL_H)
506 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
507#endif
508
509 cleanupGlobalData(globalData);
510 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
511}
512
513static void parseArguments(int argc, char** argv, Options& options, JSGlobalData* globalData)
514{
515 int i = 1;
516 for (; i < argc; ++i) {
517 const char* arg = argv[i];
518 if (!strcmp(arg, "-f")) {
519 if (++i == argc)
520 printUsageStatement(globalData);
521 options.scripts.append(Script(true, argv[i]));
522 continue;
523 }
524 if (!strcmp(arg, "-e")) {
525 if (++i == argc)
526 printUsageStatement(globalData);
527 options.scripts.append(Script(false, argv[i]));
528 continue;
529 }
530 if (!strcmp(arg, "-i")) {
531 options.interactive = true;
532 continue;
533 }
534 if (!strcmp(arg, "-d")) {
535 options.dump = true;
536 continue;
537 }
538 if (!strcmp(arg, "-s")) {
539#if HAVE(SIGNAL_H)
540 signal(SIGILL, _exit);
541 signal(SIGFPE, _exit);
542 signal(SIGBUS, _exit);
543 signal(SIGSEGV, _exit);
544#endif
545 continue;
546 }
547 if (!strcmp(arg, "--")) {
548 ++i;
549 break;
550 }
551 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
552 printUsageStatement(globalData, true);
553 options.scripts.append(Script(true, argv[i]));
554 }
555
556 if (options.scripts.isEmpty())
557 options.interactive = true;
558
559 for (; i < argc; ++i)
560 options.arguments.append(argv[i]);
561}
562
563int jscmain(int argc, char** argv, JSGlobalData* globalData)
564{
565 JSLock lock(SilenceAssertionsOnly);
566
567 Options options;
568 parseArguments(argc, argv, options, globalData);
569
570 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.arguments);
571 bool success = runWithScripts(globalObject, options.scripts, options.dump);
572 if (options.interactive && success)
573 runInteractive(globalObject);
574
575 return success ? 0 : 3;
576}
577
578static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
579{
580 FILE* f = fopen(fileName.utf8().data(), "r");
581 if (!f) {
582 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
583 return false;
584 }
585
586 size_t bufferSize = 0;
587 size_t bufferCapacity = 1024;
588
589 buffer.resize(bufferCapacity);
590
591 while (!feof(f) && !ferror(f)) {
592 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
593 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
594 bufferCapacity *= 2;
595 buffer.resize(bufferCapacity);
596 }
597 }
598 fclose(f);
599 buffer[bufferSize] = '\0';
600
601 if (buffer[0] == '#' && buffer[1] == '!')
602 buffer[0] = buffer[1] = '/';
603
604 return true;
605}
Note: See TracBrowser for help on using the repository browser.