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

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

Unreviewed, rolling out r164812.
http://trac.webkit.org/changeset/164812
https://bugs.webkit.org/show_bug.cgi?id=129699

it made things run slower (Requested by pizlo on #webkit).

  • interpreter/Interpreter.cpp:

(JSC::Interpreter::execute):

  • jsc.cpp:

(GlobalObject::finishCreation):

  • runtime/BatchedTransitionOptimizer.h:

(JSC::BatchedTransitionOptimizer::BatchedTransitionOptimizer):
(JSC::BatchedTransitionOptimizer::~BatchedTransitionOptimizer):

  • Property svn:eol-style set to native
File size: 36.2 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2012, 2013 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 "APIShims.h"
26#include "ButterflyInlines.h"
27#include "BytecodeGenerator.h"
28#include "Completion.h"
29#include "CopiedSpaceInlines.h"
30#include "ExceptionHelpers.h"
31#include "HeapStatistics.h"
32#include "InitializeThreading.h"
33#include "Interpreter.h"
34#include "JSArray.h"
35#include "JSArrayBuffer.h"
36#include "JSCInlines.h"
37#include "JSFunction.h"
38#include "JSLock.h"
39#include "JSProxy.h"
40#include "JSString.h"
41#include "SamplingTool.h"
42#include "StackVisitor.h"
43#include "StructureRareDataInlines.h"
44#include "TestRunnerUtils.h"
45#include <math.h>
46#include <stdio.h>
47#include <stdlib.h>
48#include <string.h>
49#include <thread>
50#include <wtf/CurrentTime.h>
51#include <wtf/MainThread.h>
52#include <wtf/StringPrintStream.h>
53#include <wtf/text/StringBuilder.h>
54
55#if !OS(WINDOWS)
56#include <unistd.h>
57#endif
58
59#if HAVE(READLINE)
60// readline/history.h has a Function typedef which conflicts with the WTF::Function template from WTF/Forward.h
61// We #define it to something else to avoid this conflict.
62#define Function ReadlineFunction
63#include <readline/history.h>
64#include <readline/readline.h>
65#undef Function
66#endif
67
68#if HAVE(SYS_TIME_H)
69#include <sys/time.h>
70#endif
71
72#if HAVE(SIGNAL_H)
73#include <signal.h>
74#endif
75
76#if COMPILER(MSVC) && !OS(WINCE)
77#include <crtdbg.h>
78#include <mmsystem.h>
79#include <windows.h>
80#endif
81
82#if PLATFORM(IOS) && CPU(ARM_THUMB2)
83#include <fenv.h>
84#include <arm/arch.h>
85#endif
86
87#if PLATFORM(EFL)
88#include <Ecore.h>
89#endif
90
91using namespace JSC;
92using namespace WTF;
93
94namespace {
95
96class Element;
97class ElementHandleOwner;
98class Root;
99
100class Element : public JSNonFinalObject {
101public:
102 Element(VM& vm, Structure* structure, Root* root)
103 : Base(vm, structure)
104 , m_root(root)
105 {
106 }
107
108 typedef JSNonFinalObject Base;
109 static const bool needsDestruction = false;
110
111 Root* root() const { return m_root; }
112 void setRoot(Root* root) { m_root = root; }
113
114 static Element* create(VM& vm, JSGlobalObject* globalObject, Root* root)
115 {
116 Structure* structure = createStructure(vm, globalObject, jsNull());
117 Element* element = new (NotNull, allocateCell<Element>(vm.heap, sizeof(Element))) Element(vm, structure, root);
118 element->finishCreation(vm);
119 return element;
120 }
121
122 void finishCreation(VM&);
123
124 static ElementHandleOwner* handleOwner();
125
126 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
127 {
128 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
129 }
130
131 DECLARE_INFO;
132
133private:
134 Root* m_root;
135};
136
137class ElementHandleOwner : public WeakHandleOwner {
138public:
139 virtual bool isReachableFromOpaqueRoots(Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)
140 {
141 Element* element = jsCast<Element*>(handle.slot()->asCell());
142 return visitor.containsOpaqueRoot(element->root());
143 }
144};
145
146class Root : public JSDestructibleObject {
147public:
148 Root(VM& vm, Structure* structure)
149 : Base(vm, structure)
150 {
151 }
152
153 Element* element()
154 {
155 return m_element.get();
156 }
157
158 void setElement(Element* element)
159 {
160 Weak<Element> newElement(element, Element::handleOwner());
161 m_element.swap(newElement);
162 }
163
164 static Root* create(VM& vm, JSGlobalObject* globalObject)
165 {
166 Structure* structure = createStructure(vm, globalObject, jsNull());
167 Root* root = new (NotNull, allocateCell<Root>(vm.heap, sizeof(Root))) Root(vm, structure);
168 root->finishCreation(vm);
169 return root;
170 }
171
172 typedef JSDestructibleObject Base;
173
174 DECLARE_INFO;
175 static const bool needsDestruction = true;
176
177 static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
178 {
179 return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
180 }
181
182 static void visitChildren(JSCell* thisObject, SlotVisitor& visitor)
183 {
184 Base::visitChildren(thisObject, visitor);
185 visitor.addOpaqueRoot(thisObject);
186 }
187
188private:
189 Weak<Element> m_element;
190};
191
192const ClassInfo Element::s_info = { "Element", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(Element) };
193const ClassInfo Root::s_info = { "Root", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(Root) };
194
195ElementHandleOwner* Element::handleOwner()
196{
197 static ElementHandleOwner* owner = 0;
198 if (!owner)
199 owner = new ElementHandleOwner();
200 return owner;
201}
202
203void Element::finishCreation(VM& vm)
204{
205 Base::finishCreation(vm);
206 m_root->setElement(this);
207}
208
209}
210
211static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer);
212
213static EncodedJSValue JSC_HOST_CALL functionSetElementRoot(ExecState*);
214static EncodedJSValue JSC_HOST_CALL functionCreateRoot(ExecState*);
215static EncodedJSValue JSC_HOST_CALL functionCreateElement(ExecState*);
216static EncodedJSValue JSC_HOST_CALL functionGetElement(ExecState*);
217static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
218static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
219static EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState*);
220static EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState*);
221static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
222static EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState*);
223static EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState*);
224static EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState*);
225#ifndef NDEBUG
226static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
227static EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState*);
228#endif
229static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
230static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
231static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
232static EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState*);
233static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
234static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
235static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
236static EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState*);
237static EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState*);
238static EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState*);
239static EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState*);
240static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
241static EncodedJSValue JSC_HOST_CALL functionFalse(ExecState*);
242static EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*);
243
244#if ENABLE(SAMPLING_FLAGS)
245static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
246static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
247#endif
248
249struct Script {
250 bool isFile;
251 char* argument;
252
253 Script(bool isFile, char *argument)
254 : isFile(isFile)
255 , argument(argument)
256 {
257 }
258};
259
260class CommandLine {
261public:
262 CommandLine(int argc, char** argv)
263 : m_interactive(false)
264 , m_dump(false)
265 , m_exitCode(false)
266 , m_profile(false)
267 {
268 parseArguments(argc, argv);
269 }
270
271 bool m_interactive;
272 bool m_dump;
273 bool m_exitCode;
274 Vector<Script> m_scripts;
275 Vector<String> m_arguments;
276 bool m_profile;
277 String m_profilerOutput;
278
279 void parseArguments(int, char**);
280};
281
282static const char interactivePrompt[] = ">>> ";
283
284class StopWatch {
285public:
286 void start();
287 void stop();
288 long getElapsedMS(); // call stop() first
289
290private:
291 double m_startTime;
292 double m_stopTime;
293};
294
295void StopWatch::start()
296{
297 m_startTime = monotonicallyIncreasingTime();
298}
299
300void StopWatch::stop()
301{
302 m_stopTime = monotonicallyIncreasingTime();
303}
304
305long StopWatch::getElapsedMS()
306{
307 return static_cast<long>((m_stopTime - m_startTime) * 1000);
308}
309
310class GlobalObject : public JSGlobalObject {
311private:
312 GlobalObject(VM&, Structure*);
313
314public:
315 typedef JSGlobalObject Base;
316
317 static GlobalObject* create(VM& vm, Structure* structure, const Vector<String>& arguments)
318 {
319 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(vm.heap)) GlobalObject(vm, structure);
320 object->finishCreation(vm, arguments);
321 vm.heap.addFinalizer(object, destroy);
322 object->setGlobalThis(vm, JSProxy::create(vm, JSProxy::createStructure(vm, object, object->prototype()), object));
323 return object;
324 }
325
326 static const bool needsDestruction = false;
327
328 DECLARE_INFO;
329 static const GlobalObjectMethodTable s_globalObjectMethodTable;
330
331 static Structure* createStructure(VM& vm, JSValue prototype)
332 {
333 return Structure::create(vm, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), info());
334 }
335
336 static bool javaScriptExperimentsEnabled(const JSGlobalObject*) { return true; }
337
338protected:
339 void finishCreation(VM& vm, const Vector<String>& arguments)
340 {
341 Base::finishCreation(vm);
342
343 addFunction(vm, "debug", functionDebug, 1);
344 addFunction(vm, "describe", functionDescribe, 1);
345 addFunction(vm, "describeArray", functionDescribeArray, 1);
346 addFunction(vm, "print", functionPrint, 1);
347 addFunction(vm, "quit", functionQuit, 0);
348 addFunction(vm, "gc", functionGCAndSweep, 0);
349 addFunction(vm, "fullGC", functionFullGC, 0);
350 addFunction(vm, "edenGC", functionEdenGC, 0);
351#ifndef NDEBUG
352 addFunction(vm, "dumpCallFrame", functionDumpCallFrame, 0);
353 addFunction(vm, "releaseExecutableMemory", functionReleaseExecutableMemory, 0);
354#endif
355 addFunction(vm, "version", functionVersion, 1);
356 addFunction(vm, "run", functionRun, 1);
357 addFunction(vm, "load", functionLoad, 1);
358 addFunction(vm, "readFile", functionReadFile, 1);
359 addFunction(vm, "checkSyntax", functionCheckSyntax, 1);
360 addFunction(vm, "jscStack", functionJSCStack, 1);
361 addFunction(vm, "readline", functionReadline, 0);
362 addFunction(vm, "preciseTime", functionPreciseTime, 0);
363 addFunction(vm, "neverInlineFunction", functionNeverInlineFunction, 1);
364 addFunction(vm, "noInline", functionNeverInlineFunction, 1);
365 addFunction(vm, "numberOfDFGCompiles", functionNumberOfDFGCompiles, 1);
366 addFunction(vm, "reoptimizationRetryCount", functionReoptimizationRetryCount, 1);
367 addFunction(vm, "transferArrayBuffer", functionTransferArrayBuffer, 1);
368#if ENABLE(SAMPLING_FLAGS)
369 addFunction(vm, "setSamplingFlags", functionSetSamplingFlags, 1);
370 addFunction(vm, "clearSamplingFlags", functionClearSamplingFlags, 1);
371#endif
372 addConstructableFunction(vm, "Root", functionCreateRoot, 0);
373 addConstructableFunction(vm, "Element", functionCreateElement, 1);
374 addFunction(vm, "getElement", functionGetElement, 1);
375 addFunction(vm, "setElementRoot", functionSetElementRoot, 2);
376
377 putDirectNativeFunction(vm, this, Identifier(&vm, "DFGTrue"), 0, functionFalse, DFGTrue, DontEnum | JSC::Function);
378
379 addFunction(vm, "effectful42", functionEffectful42, 0);
380
381 JSArray* array = constructEmptyArray(globalExec(), 0);
382 for (size_t i = 0; i < arguments.size(); ++i)
383 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]));
384 putDirect(vm, Identifier(globalExec(), "arguments"), array);
385 }
386
387 void addFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
388 {
389 Identifier identifier(&vm, name);
390 putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function));
391 }
392
393 void addConstructableFunction(VM& vm, const char* name, NativeFunction function, unsigned arguments)
394 {
395 Identifier identifier(&vm, name);
396 putDirect(vm, identifier, JSFunction::create(vm, this, arguments, identifier.string(), function, NoIntrinsic, function));
397 }
398};
399
400const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, 0, ExecState::globalObjectTable, CREATE_METHOD_TABLE(GlobalObject) };
401const GlobalObjectMethodTable GlobalObject::s_globalObjectMethodTable = { &allowsAccessFrom, &supportsProfiling, &supportsRichSourceInfo, &shouldInterruptScript, &javaScriptExperimentsEnabled, 0, &shouldInterruptScriptBeforeTimeout };
402
403
404GlobalObject::GlobalObject(VM& vm, Structure* structure)
405 : JSGlobalObject(vm, structure, &s_globalObjectMethodTable)
406{
407}
408
409static inline String stringFromUTF(const char* utf8)
410{
411 // Find the the first non-ascii character, or nul.
412 const char* pos = utf8;
413 while (*pos > 0)
414 pos++;
415 size_t asciiLength = pos - utf8;
416
417 // Fast case - string is all ascii.
418 if (!*pos)
419 return String(utf8, asciiLength);
420
421 // Slow case - contains non-ascii characters, use fromUTF8WithLatin1Fallback.
422 ASSERT(*pos < 0);
423 ASSERT(strlen(utf8) == asciiLength + strlen(pos));
424 return String::fromUTF8WithLatin1Fallback(utf8, asciiLength + strlen(pos));
425}
426
427static inline SourceCode jscSource(const char* utf8, const String& filename)
428{
429 String str = stringFromUTF(utf8);
430 return makeSource(str, filename);
431}
432
433EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
434{
435 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
436 if (i)
437 putchar(' ');
438
439 printf("%s", exec->uncheckedArgument(i).toString(exec)->value(exec).utf8().data());
440 }
441
442 putchar('\n');
443 fflush(stdout);
444 return JSValue::encode(jsUndefined());
445}
446
447#ifndef NDEBUG
448EncodedJSValue JSC_HOST_CALL functionDumpCallFrame(ExecState* exec)
449{
450 if (!exec->callerFrame()->isVMEntrySentinel())
451 exec->vm().interpreter->dumpCallFrame(exec->callerFrame());
452 return JSValue::encode(jsUndefined());
453}
454#endif
455
456EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
457{
458 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec)->value(exec).utf8().data());
459 return JSValue::encode(jsUndefined());
460}
461
462EncodedJSValue JSC_HOST_CALL functionDescribe(ExecState* exec)
463{
464 if (exec->argumentCount() < 1)
465 return JSValue::encode(jsUndefined());
466 return JSValue::encode(jsString(exec, toString(exec->argument(0))));
467}
468
469EncodedJSValue JSC_HOST_CALL functionDescribeArray(ExecState* exec)
470{
471 if (exec->argumentCount() < 1)
472 return JSValue::encode(jsUndefined());
473 JSObject* object = jsDynamicCast<JSObject*>(exec->argument(0));
474 if (!object)
475 return JSValue::encode(jsString(exec, "<not object>"));
476 return JSValue::encode(jsString(exec, toString("<Public length: ", object->getArrayLength(), "; vector length: ", object->getVectorLength(), ">")));
477}
478
479class FunctionJSCStackFunctor {
480public:
481 FunctionJSCStackFunctor(StringBuilder& trace)
482 : m_trace(trace)
483 {
484 }
485
486 StackVisitor::Status operator()(StackVisitor& visitor)
487 {
488 m_trace.append(String::format(" %zu %s\n", visitor->index(), visitor->toString().utf8().data()));
489 return StackVisitor::Continue;
490 }
491
492private:
493 StringBuilder& m_trace;
494};
495
496EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
497{
498 StringBuilder trace;
499 trace.appendLiteral("--> Stack trace:\n");
500
501 FunctionJSCStackFunctor functor(trace);
502 exec->iterate(functor);
503 fprintf(stderr, "%s", trace.toString().utf8().data());
504 return JSValue::encode(jsUndefined());
505}
506
507EncodedJSValue JSC_HOST_CALL functionCreateRoot(ExecState* exec)
508{
509 JSLockHolder lock(exec);
510 return JSValue::encode(Root::create(exec->vm(), exec->lexicalGlobalObject()));
511}
512
513EncodedJSValue JSC_HOST_CALL functionCreateElement(ExecState* exec)
514{
515 JSLockHolder lock(exec);
516 JSValue arg = exec->argument(0);
517 return JSValue::encode(Element::create(exec->vm(), exec->lexicalGlobalObject(), arg.isNull() ? nullptr : jsCast<Root*>(exec->argument(0))));
518}
519
520EncodedJSValue JSC_HOST_CALL functionGetElement(ExecState* exec)
521{
522 JSLockHolder lock(exec);
523 Element* result = jsCast<Root*>(exec->argument(0).asCell())->element();
524 return JSValue::encode(result ? result : jsUndefined());
525}
526
527EncodedJSValue JSC_HOST_CALL functionSetElementRoot(ExecState* exec)
528{
529 JSLockHolder lock(exec);
530 Element* element = jsCast<Element*>(exec->argument(0));
531 Root* root = jsCast<Root*>(exec->argument(1));
532 element->setRoot(root);
533 return JSValue::encode(jsUndefined());
534}
535
536EncodedJSValue JSC_HOST_CALL functionGCAndSweep(ExecState* exec)
537{
538 JSLockHolder lock(exec);
539 exec->heap()->collectAllGarbage();
540 return JSValue::encode(jsUndefined());
541}
542
543EncodedJSValue JSC_HOST_CALL functionFullGC(ExecState* exec)
544{
545 JSLockHolder lock(exec);
546 Heap* heap = exec->heap();
547 heap->setShouldDoFullCollection(true);
548 exec->heap()->collect();
549 return JSValue::encode(jsUndefined());
550}
551
552EncodedJSValue JSC_HOST_CALL functionEdenGC(ExecState* exec)
553{
554 JSLockHolder lock(exec);
555 Heap* heap = exec->heap();
556 heap->setShouldDoFullCollection(false);
557 heap->collect();
558 return JSValue::encode(jsUndefined());
559}
560
561#ifndef NDEBUG
562EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
563{
564 JSLockHolder lock(exec);
565 exec->vm().releaseExecutableMemory();
566 return JSValue::encode(jsUndefined());
567}
568#endif
569
570EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
571{
572 // We need this function for compatibility with the Mozilla JS tests but for now
573 // we don't actually do any version-specific handling
574 return JSValue::encode(jsUndefined());
575}
576
577EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
578{
579 String fileName = exec->argument(0).toString(exec)->value(exec);
580 Vector<char> script;
581 if (!fillBufferWithContentsOfFile(fileName, script))
582 return JSValue::encode(exec->vm().throwException(exec, createError(exec, "Could not open file.")));
583
584 GlobalObject* globalObject = GlobalObject::create(exec->vm(), GlobalObject::createStructure(exec->vm(), jsNull()), Vector<String>());
585
586 JSArray* array = constructEmptyArray(globalObject->globalExec(), 0);
587 for (unsigned i = 1; i < exec->argumentCount(); ++i)
588 array->putDirectIndex(globalObject->globalExec(), i - 1, exec->uncheckedArgument(i));
589 globalObject->putDirect(
590 exec->vm(), Identifier(globalObject->globalExec(), "arguments"), array);
591
592 JSValue exception;
593 StopWatch stopWatch;
594 stopWatch.start();
595 evaluate(globalObject->globalExec(), jscSource(script.data(), fileName), JSValue(), &exception);
596 stopWatch.stop();
597
598 if (!!exception) {
599 exec->vm().throwException(globalObject->globalExec(), exception);
600 return JSValue::encode(jsUndefined());
601 }
602
603 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
604}
605
606EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
607{
608 String fileName = exec->argument(0).toString(exec)->value(exec);
609 Vector<char> script;
610 if (!fillBufferWithContentsOfFile(fileName, script))
611 return JSValue::encode(exec->vm().throwException(exec, createError(exec, "Could not open file.")));
612
613 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
614
615 JSValue evaluationException;
616 JSValue result = evaluate(globalObject->globalExec(), jscSource(script.data(), fileName), JSValue(), &evaluationException);
617 if (evaluationException)
618 exec->vm().throwException(exec, evaluationException);
619 return JSValue::encode(result);
620}
621
622EncodedJSValue JSC_HOST_CALL functionReadFile(ExecState* exec)
623{
624 String fileName = exec->argument(0).toString(exec)->value(exec);
625 Vector<char> script;
626 if (!fillBufferWithContentsOfFile(fileName, script))
627 return JSValue::encode(exec->vm().throwException(exec, createError(exec, "Could not open file.")));
628
629 return JSValue::encode(jsString(exec, stringFromUTF(script.data())));
630}
631
632EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
633{
634 String fileName = exec->argument(0).toString(exec)->value(exec);
635 Vector<char> script;
636 if (!fillBufferWithContentsOfFile(fileName, script))
637 return JSValue::encode(exec->vm().throwException(exec, createError(exec, "Could not open file.")));
638
639 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
640
641 StopWatch stopWatch;
642 stopWatch.start();
643
644 JSValue syntaxException;
645 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script.data(), fileName), &syntaxException);
646 stopWatch.stop();
647
648 if (!validSyntax)
649 exec->vm().throwException(exec, syntaxException);
650 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
651}
652
653#if ENABLE(SAMPLING_FLAGS)
654EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
655{
656 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
657 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
658 if ((flag >= 1) && (flag <= 32))
659 SamplingFlags::setFlag(flag);
660 }
661 return JSValue::encode(jsNull());
662}
663
664EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
665{
666 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
667 unsigned flag = static_cast<unsigned>(exec->uncheckedArgument(i).toNumber(exec));
668 if ((flag >= 1) && (flag <= 32))
669 SamplingFlags::clearFlag(flag);
670 }
671 return JSValue::encode(jsNull());
672}
673#endif
674
675EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
676{
677 Vector<char, 256> line;
678 int c;
679 while ((c = getchar()) != EOF) {
680 // FIXME: Should we also break on \r?
681 if (c == '\n')
682 break;
683 line.append(c);
684 }
685 line.append('\0');
686 return JSValue::encode(jsString(exec, line.data()));
687}
688
689EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
690{
691 return JSValue::encode(jsNumber(currentTime()));
692}
693
694EncodedJSValue JSC_HOST_CALL functionNeverInlineFunction(ExecState* exec)
695{
696 return JSValue::encode(setNeverInline(exec));
697}
698
699EncodedJSValue JSC_HOST_CALL functionNumberOfDFGCompiles(ExecState* exec)
700{
701 return JSValue::encode(numberOfDFGCompiles(exec));
702}
703
704EncodedJSValue JSC_HOST_CALL functionReoptimizationRetryCount(ExecState* exec)
705{
706 if (exec->argumentCount() < 1)
707 return JSValue::encode(jsUndefined());
708
709 CodeBlock* block = getSomeBaselineCodeBlockForFunction(exec->argument(0));
710 if (!block)
711 return JSValue::encode(jsNumber(0));
712
713 return JSValue::encode(jsNumber(block->reoptimizationRetryCounter()));
714}
715
716EncodedJSValue JSC_HOST_CALL functionTransferArrayBuffer(ExecState* exec)
717{
718 if (exec->argumentCount() < 1)
719 return JSValue::encode(exec->vm().throwException(exec, createError(exec, "Not enough arguments")));
720
721 JSArrayBuffer* buffer = jsDynamicCast<JSArrayBuffer*>(exec->argument(0));
722 if (!buffer)
723 return JSValue::encode(exec->vm().throwException(exec, createError(exec, "Expected an array buffer")));
724
725 ArrayBufferContents dummyContents;
726 buffer->impl()->transfer(dummyContents);
727
728 return JSValue::encode(jsUndefined());
729}
730
731EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*)
732{
733 exit(EXIT_SUCCESS);
734
735#if COMPILER(MSVC) && OS(WINCE)
736 // Without this, Visual Studio will complain that this method does not return a value.
737 return JSValue::encode(jsUndefined());
738#endif
739}
740
741EncodedJSValue JSC_HOST_CALL functionFalse(ExecState*)
742{
743 return JSValue::encode(jsBoolean(false));
744}
745
746EncodedJSValue JSC_HOST_CALL functionEffectful42(ExecState*)
747{
748 return JSValue::encode(jsNumber(42));
749}
750
751// Use SEH for Release builds only to get rid of the crash report dialog
752// (luckily the same tests fail in Release and Debug builds so far). Need to
753// be in a separate main function because the jscmain function requires object
754// unwinding.
755
756#if COMPILER(MSVC) && !defined(_DEBUG) && !OS(WINCE)
757#define TRY __try {
758#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
759#else
760#define TRY
761#define EXCEPT(x)
762#endif
763
764int jscmain(int argc, char** argv);
765
766static double s_desiredTimeout;
767
768static NO_RETURN_DUE_TO_CRASH void timeoutThreadMain(void*)
769{
770 auto timeout = std::chrono::microseconds(static_cast<std::chrono::microseconds::rep>(s_desiredTimeout * 1000000));
771 std::this_thread::sleep_for(timeout);
772
773 dataLog("Timed out after ", s_desiredTimeout, " seconds!\n");
774 CRASH();
775}
776
777int main(int argc, char** argv)
778{
779#if PLATFORM(IOS) && CPU(ARM_THUMB2)
780 // Enabled IEEE754 denormal support.
781 fenv_t env;
782 fegetenv( &env );
783 env.__fpscr &= ~0x01000000u;
784 fesetenv( &env );
785#endif
786
787#if OS(WINDOWS)
788#if !OS(WINCE)
789 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
790 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
791 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
792 ::SetErrorMode(0);
793
794#if defined(_DEBUG)
795 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
796 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
797 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
798 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
799 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
800 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
801#endif
802#endif
803
804 timeBeginPeriod(1);
805#endif
806
807#if PLATFORM(EFL)
808 ecore_init();
809#endif
810
811 // Initialize JSC before getting VM.
812#if ENABLE(SAMPLING_REGIONS)
813 WTF::initializeMainThread();
814#endif
815 JSC::initializeThreading();
816
817#if !OS(WINCE)
818 if (char* timeoutString = getenv("JSC_timeout")) {
819 if (sscanf(timeoutString, "%lf", &s_desiredTimeout) != 1) {
820 dataLog(
821 "WARNING: timeout string is malformed, got ", timeoutString,
822 " but expected a number. Not using a timeout.\n");
823 } else
824 createThread(timeoutThreadMain, 0, "jsc Timeout Thread");
825 }
826#endif
827
828#if PLATFORM(IOS)
829 Options::crashIfCantAllocateJITMemory() = true;
830#endif
831
832 // We can't use destructors in the following code because it uses Windows
833 // Structured Exception Handling
834 int res = 0;
835 TRY
836 res = jscmain(argc, argv);
837 EXCEPT(res = 3)
838 if (Options::logHeapStatisticsAtExit())
839 HeapStatistics::reportSuccess();
840
841#if PLATFORM(EFL)
842 ecore_shutdown();
843#endif
844
845 return res;
846}
847
848static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
849{
850 const char* script;
851 String fileName;
852 Vector<char> scriptBuffer;
853
854 if (dump)
855 JSC::Options::dumpGeneratedBytecodes() = true;
856
857 VM& vm = globalObject->vm();
858
859#if ENABLE(SAMPLING_FLAGS)
860 SamplingFlags::start();
861#endif
862
863 bool success = true;
864 for (size_t i = 0; i < scripts.size(); i++) {
865 if (scripts[i].isFile) {
866 fileName = scripts[i].argument;
867 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
868 return false; // fail early so we can catch missing files
869 script = scriptBuffer.data();
870 } else {
871 script = scripts[i].argument;
872 fileName = "[Command Line]";
873 }
874
875 vm.startSampling();
876
877 JSValue evaluationException;
878 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(script, fileName), JSValue(), &evaluationException);
879 success = success && !evaluationException;
880 if (dump && !evaluationException)
881 printf("End: %s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
882 if (evaluationException) {
883 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
884 Identifier stackID(globalObject->globalExec(), "stack");
885 JSValue stackValue = evaluationException.get(globalObject->globalExec(), stackID);
886 if (!stackValue.isUndefinedOrNull())
887 printf("%s\n", stackValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
888 }
889
890 vm.stopSampling();
891 globalObject->globalExec()->clearException();
892 }
893
894#if ENABLE(SAMPLING_FLAGS)
895 SamplingFlags::stop();
896#endif
897#if ENABLE(SAMPLING_REGIONS)
898 SamplingRegion::dump();
899#endif
900 vm.dumpSampleData(globalObject->globalExec());
901#if ENABLE(SAMPLING_COUNTERS)
902 AbstractSamplingCounter::dump();
903#endif
904#if ENABLE(REGEXP_TRACING)
905 vm.dumpRegExpTrace();
906#endif
907 return success;
908}
909
910#define RUNNING_FROM_XCODE 0
911
912static void runInteractive(GlobalObject* globalObject)
913{
914 String interpreterName("Interpreter");
915
916 bool shouldQuit = false;
917 while (!shouldQuit) {
918#if HAVE(READLINE) && !RUNNING_FROM_XCODE
919 ParserError error;
920 String source;
921 do {
922 error = ParserError();
923 char* line = readline(source.isEmpty() ? interactivePrompt : "... ");
924 shouldQuit = !line;
925 if (!line)
926 break;
927 source = source + line;
928 source = source + '\n';
929 checkSyntax(globalObject->vm(), makeSource(source, interpreterName), error);
930 if (!line[0])
931 break;
932 add_history(line);
933 } while (error.m_syntaxErrorType == ParserError::SyntaxErrorRecoverable);
934
935 if (error.m_type != ParserError::ErrorNone) {
936 printf("%s:%d\n", error.m_message.utf8().data(), error.m_line);
937 continue;
938 }
939
940
941 JSValue evaluationException;
942 JSValue returnValue = evaluate(globalObject->globalExec(), makeSource(source, interpreterName), JSValue(), &evaluationException);
943#else
944 printf("%s", interactivePrompt);
945 Vector<char, 256> line;
946 int c;
947 while ((c = getchar()) != EOF) {
948 // FIXME: Should we also break on \r?
949 if (c == '\n')
950 break;
951 line.append(c);
952 }
953 if (line.isEmpty())
954 break;
955 line.append('\0');
956
957 JSValue evaluationException;
958 JSValue returnValue = evaluate(globalObject->globalExec(), jscSource(line.data(), interpreterName), JSValue(), &evaluationException);
959#endif
960 if (evaluationException)
961 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
962 else
963 printf("%s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
964
965 globalObject->globalExec()->clearException();
966 }
967 printf("\n");
968}
969
970static NO_RETURN void printUsageStatement(bool help = false)
971{
972 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
973 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
974 fprintf(stderr, " -e Evaluate argument as script code\n");
975 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
976 fprintf(stderr, " -h|--help Prints this help message\n");
977 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
978#if HAVE(SIGNAL_H)
979 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
980#endif
981 fprintf(stderr, " -p <file> Outputs profiling data to a file\n");
982 fprintf(stderr, " -x Output exit code before terminating\n");
983 fprintf(stderr, "\n");
984 fprintf(stderr, " --options Dumps all JSC VM options and exits\n");
985 fprintf(stderr, " --dumpOptions Dumps all JSC VM options before continuing\n");
986 fprintf(stderr, " --<jsc VM option>=<value> Sets the specified JSC VM option\n");
987 fprintf(stderr, "\n");
988
989 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
990}
991
992void CommandLine::parseArguments(int argc, char** argv)
993{
994 int i = 1;
995 bool needToDumpOptions = false;
996 bool needToExit = false;
997
998 for (; i < argc; ++i) {
999 const char* arg = argv[i];
1000 if (!strcmp(arg, "-f")) {
1001 if (++i == argc)
1002 printUsageStatement();
1003 m_scripts.append(Script(true, argv[i]));
1004 continue;
1005 }
1006 if (!strcmp(arg, "-e")) {
1007 if (++i == argc)
1008 printUsageStatement();
1009 m_scripts.append(Script(false, argv[i]));
1010 continue;
1011 }
1012 if (!strcmp(arg, "-i")) {
1013 m_interactive = true;
1014 continue;
1015 }
1016 if (!strcmp(arg, "-d")) {
1017 m_dump = true;
1018 continue;
1019 }
1020 if (!strcmp(arg, "-p")) {
1021 if (++i == argc)
1022 printUsageStatement();
1023 m_profile = true;
1024 m_profilerOutput = argv[i];
1025 continue;
1026 }
1027 if (!strcmp(arg, "-s")) {
1028#if HAVE(SIGNAL_H)
1029 signal(SIGILL, _exit);
1030 signal(SIGFPE, _exit);
1031 signal(SIGBUS, _exit);
1032 signal(SIGSEGV, _exit);
1033#endif
1034 continue;
1035 }
1036 if (!strcmp(arg, "-x")) {
1037 m_exitCode = true;
1038 continue;
1039 }
1040 if (!strcmp(arg, "--")) {
1041 ++i;
1042 break;
1043 }
1044 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
1045 printUsageStatement(true);
1046
1047 if (!strcmp(arg, "--options")) {
1048 needToDumpOptions = true;
1049 needToExit = true;
1050 continue;
1051 }
1052 if (!strcmp(arg, "--dumpOptions")) {
1053 needToDumpOptions = true;
1054 continue;
1055 }
1056
1057 // See if the -- option is a JSC VM option.
1058 // NOTE: At this point, we know that the arg starts with "--". Skip it.
1059 if (JSC::Options::setOption(&arg[2])) {
1060 // The arg was recognized as a VM option and has been parsed.
1061 continue; // Just continue with the next arg.
1062 }
1063
1064 // This arg is not recognized by the VM nor by jsc. Pass it on to the
1065 // script.
1066 m_scripts.append(Script(true, argv[i]));
1067 }
1068
1069 if (m_scripts.isEmpty())
1070 m_interactive = true;
1071
1072 for (; i < argc; ++i)
1073 m_arguments.append(argv[i]);
1074
1075 if (needToDumpOptions)
1076 JSC::Options::dumpAllOptions(stderr);
1077 if (needToExit)
1078 exit(EXIT_SUCCESS);
1079}
1080
1081int jscmain(int argc, char** argv)
1082{
1083 // Note that the options parsing can affect VM creation, and thus
1084 // comes first.
1085 CommandLine options(argc, argv);
1086 VM* vm = VM::create(LargeHeap).leakRef();
1087 int result;
1088 {
1089 APIEntryShim shim(vm);
1090
1091 if (options.m_profile && !vm->m_perBytecodeProfiler)
1092 vm->m_perBytecodeProfiler = adoptPtr(new Profiler::Database(*vm));
1093
1094 GlobalObject* globalObject = GlobalObject::create(*vm, GlobalObject::createStructure(*vm, jsNull()), options.m_arguments);
1095 bool success = runWithScripts(globalObject, options.m_scripts, options.m_dump);
1096 if (options.m_interactive && success)
1097 runInteractive(globalObject);
1098
1099 result = success ? 0 : 3;
1100
1101 if (options.m_exitCode)
1102 printf("jsc exiting %d\n", result);
1103
1104 if (options.m_profile) {
1105 if (!vm->m_perBytecodeProfiler->save(options.m_profilerOutput.utf8().data()))
1106 fprintf(stderr, "could not save profiler output.\n");
1107 }
1108 }
1109
1110 return result;
1111}
1112
1113static bool fillBufferWithContentsOfFile(const String& fileName, Vector<char>& buffer)
1114{
1115 FILE* f = fopen(fileName.utf8().data(), "r");
1116 if (!f) {
1117 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
1118 return false;
1119 }
1120
1121 size_t bufferSize = 0;
1122 size_t bufferCapacity = 1024;
1123
1124 buffer.resize(bufferCapacity);
1125
1126 while (!feof(f) && !ferror(f)) {
1127 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
1128 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
1129 bufferCapacity *= 2;
1130 buffer.resize(bufferCapacity);
1131 }
1132 }
1133 fclose(f);
1134 buffer[bufferSize] = '\0';
1135
1136 if (buffer[0] == '#' && buffer[1] == '!')
1137 buffer[0] = buffer[1] = '/';
1138
1139 return true;
1140}
Note: See TracBrowser for help on using the repository browser.