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

Last change on this file since 79707 was 79707, checked in by Patrick Gansterer, 14 years ago

2011-02-25 Patrick Gansterer <Patrick Gansterer>

Unreviewed WinCE build fix for r79695.

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