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

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

Rationalize JSObject::putDirect* methods
https://bugs.webkit.org/show_bug.cgi?id=68274

Reviewed by Sam Weinig.

Delete the *Function variants. These are overall inefficient,
in the way they get the name back from the function rather
than just passing it in.

(GlobalObject::finishCreation):
(GlobalObject::addFunction):

  • runtime/FunctionPrototype.cpp:

(JSC::FunctionPrototype::addFunctionProperties):

  • runtime/JSGlobalObject.cpp:

(JSC::JSGlobalObject::reset):

  • runtime/JSObject.cpp:

(JSC::JSObject::put):
(JSC::JSObject::putWithAttributes):
(JSC::JSObject::defineGetter):
(JSC::JSObject::defineSetter):

  • runtime/JSObject.h:

(JSC::JSObject::putDirect):
(JSC::JSObject::putDirectWithoutTransition):

  • runtime/Lookup.cpp:

(JSC::setUpStaticFunctionSlot):

  • runtime/Lookup.h:

(JSC::lookupPut):

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