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

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

Move allocation in constructors into separate constructorBody() methods
https://bugs.webkit.org/show_bug.cgi?id=66265

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

Source/JavaScriptCore:

Refactoring to put all allocations that need to be done after the object's
initialization list has executed but before the object is ready for use
into a separate constructorBody() method. This method is still called by the constructor,
so the patch doesn't resolve any potential issues, it's just to set up the code for further refactoring.

(GlobalObject::constructorBody):
(GlobalObject::GlobalObject):

  • runtime/ErrorInstance.cpp:

(JSC::ErrorInstance::ErrorInstance):

  • runtime/ErrorInstance.h:

(JSC::ErrorInstance::constructorBody):

  • runtime/ErrorPrototype.cpp:

(JSC::ErrorPrototype::ErrorPrototype):
(JSC::ErrorPrototype::constructorBody):

  • runtime/ErrorPrototype.h:
  • runtime/Executable.cpp:

(JSC::FunctionExecutable::FunctionExecutable):

  • runtime/Executable.h:

(JSC::FunctionExecutable::constructorBody):

  • runtime/InternalFunction.cpp:

(JSC::InternalFunction::InternalFunction):

  • runtime/InternalFunction.h:

(JSC::InternalFunction::constructorBody):

  • runtime/JSByteArray.cpp:

(JSC::JSByteArray::JSByteArray):

  • runtime/JSByteArray.h:

(JSC::JSByteArray::constructorBody):

  • runtime/JSFunction.cpp:

(JSC::JSFunction::JSFunction):
(JSC::JSFunction::constructorBody):

  • runtime/JSFunction.h:
  • runtime/JSGlobalObject.h:

(JSC::JSGlobalObject::JSGlobalObject):
(JSC::JSGlobalObject::constructorBody):

  • runtime/JSPropertyNameIterator.cpp:

(JSC::JSPropertyNameIterator::JSPropertyNameIterator):

  • runtime/JSPropertyNameIterator.h:

(JSC::JSPropertyNameIterator::constructorBody):

  • runtime/JSString.h:

(JSC::RopeBuilder::JSString):
(JSC::RopeBuilder::constructorBody):

  • runtime/NativeErrorConstructor.cpp:

(JSC::NativeErrorConstructor::NativeErrorConstructor):

  • runtime/NativeErrorConstructor.h:

(JSC::NativeErrorConstructor::constructorBody):

  • runtime/NativeErrorPrototype.cpp:

(JSC::NativeErrorPrototype::NativeErrorPrototype):
(JSC::NativeErrorPrototype::constructorBody):

  • runtime/NativeErrorPrototype.h:
  • runtime/StringObject.cpp:
  • runtime/StringObject.h:

(JSC::StringObject::create):

  • runtime/StringObjectThatMasqueradesAsUndefined.h:

(JSC::StringObjectThatMasqueradesAsUndefined::create):
(JSC::StringObjectThatMasqueradesAsUndefined::StringObjectThatMasqueradesAsUndefined):

  • runtime/StringPrototype.cpp:

(JSC::StringPrototype::StringPrototype):

  • runtime/StringPrototype.h:

(JSC::StringPrototype::create):

Source/WebCore:

No new tests.

Refactoring to put all allocations that need to be done after the object's
initialization list has executed but before the object is ready for use
into a separate constructorBody() method. This method is still called by the constructor,
so the patch doesn't resolve any potential issues, it's just to set up the code for further refactoring.

  • bridge/objc/ObjCRuntimeObject.h:

(JSC::Bindings::ObjCRuntimeObject::create):

  • bridge/objc/ObjCRuntimeObject.mm:
  • bridge/objc/objc_instance.mm:

(ObjCRuntimeMethod::create):
(ObjCRuntimeMethod::ObjCRuntimeMethod):

  • bridge/runtime_array.cpp:
  • bridge/runtime_array.h:

(JSC::RuntimeArray::create):

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