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

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

jsc command line should support typed arrays by default
https://bugs.webkit.org/show_bug.cgi?id=84298

Rubber stamped by Gavin Barraclough.

  • JSCTypedArrayStubs.h:

(JSC):

  • jsc.cpp:

(GlobalObject::finishCreation):

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