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

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

Fix the uses of String::operator+=() for Mac
https://bugs.webkit.org/show_bug.cgi?id=95818

Patch by Benjamin Poulain <[email protected]> on 2012-09-05
Reviewed by Dan Bernstein.

Source/JavaScriptCore:

  • jsc.cpp:

(functionJSCStack): Use StringBuilder to create the stack dump, it is faster
and avoid String::operator+=().

  • parser/Parser.h:

(JSC::Parser::updateErrorMessageSpecialCase):
(JSC::Parser::updateErrorMessage):
(JSC::Parser::updateErrorWithNameAndMessage):
Use the String operators (and makeString) to concatenate the strings.

Source/WebCore:

  • bindings/js/JSCSSStyleDeclarationCustom.cpp:

(WebCore::JSCSSStyleDeclaration::putDelegate):
This is a legitimate use of String::append(), it is the only
concatenation in this function.

  • loader/appcache/ManifestParser.cpp:

(WebCore::parseManifest): Ditto.

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