tizen beta release
[framework/web/webkit-efl.git] / Source / JavaScriptCore / runtime / JSGlobalData.cpp
1 /*
2  * Copyright (C) 2008, 2011 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "JSGlobalData.h"
31
32 #include "ArgList.h"
33 #include "Heap.h"
34 #include "CommonIdentifiers.h"
35 #include "DebuggerActivation.h"
36 #include "FunctionConstructor.h"
37 #include "GetterSetter.h"
38 #include "Interpreter.h"
39 #include "JSActivation.h"
40 #include "JSAPIValueWrapper.h"
41 #include "JSArray.h"
42 #include "JSByteArray.h"
43 #include "JSClassRef.h"
44 #include "JSFunction.h"
45 #include "JSLock.h"
46 #include "JSNotAnObject.h"
47 #include "JSPropertyNameIterator.h"
48 #include "JSStaticScopeObject.h"
49 #include "Lexer.h"
50 #include "Lookup.h"
51 #include "Nodes.h"
52 #include "ParserArena.h"
53 #include "RegExpCache.h"
54 #include "RegExpObject.h"
55 #include "StrictEvalActivation.h"
56 #include "StrongInlines.h"
57 #include <wtf/Threading.h>
58 #include <wtf/WTFThreadData.h>
59
60 #if ENABLE(REGEXP_TRACING)
61 #include "RegExp.h"
62 #endif
63
64 #if PLATFORM(MAC)
65 #include <CoreFoundation/CoreFoundation.h>
66 #endif
67
68 using namespace WTF;
69
70 namespace {
71
72 using namespace JSC;
73
74 class Recompiler : public MarkedBlock::VoidFunctor {
75 public:
76     void operator()(JSCell*);
77 };
78
79 inline void Recompiler::operator()(JSCell* cell)
80 {
81     if (!cell->inherits(&JSFunction::s_info))
82         return;
83     JSFunction* function = asFunction(cell);
84     if (!function->executable() || function->executable()->isHostFunction())
85         return;
86     function->jsExecutable()->discardCode();
87 }
88
89 } // namespace
90
91 namespace JSC {
92
93 extern const HashTable arrayConstructorTable;
94 extern const HashTable arrayPrototypeTable;
95 extern const HashTable booleanPrototypeTable;
96 extern const HashTable jsonTable;
97 extern const HashTable dateTable;
98 extern const HashTable dateConstructorTable;
99 extern const HashTable errorPrototypeTable;
100 extern const HashTable globalObjectTable;
101 extern const HashTable mathTable;
102 extern const HashTable numberConstructorTable;
103 extern const HashTable numberPrototypeTable;
104 extern const HashTable objectConstructorTable;
105 extern const HashTable objectPrototypeTable;
106 extern const HashTable regExpTable;
107 extern const HashTable regExpConstructorTable;
108 extern const HashTable regExpPrototypeTable;
109 extern const HashTable stringTable;
110 extern const HashTable stringConstructorTable;
111
112 void* JSGlobalData::jsFinalObjectVPtr;
113 void* JSGlobalData::jsArrayVPtr;
114 void* JSGlobalData::jsByteArrayVPtr;
115 void* JSGlobalData::jsStringVPtr;
116 void* JSGlobalData::jsFunctionVPtr;
117
118 #if COMPILER(GCC)
119 // Work around for gcc trying to coalesce our reads of the various cell vptrs
120 #define CLOBBER_MEMORY() do { \
121     asm volatile ("" : : : "memory"); \
122 } while (false)
123 #else
124 #define CLOBBER_MEMORY() do { } while (false)
125 #endif
126
127 void JSGlobalData::storeVPtrs()
128 {
129     // Enough storage to fit a JSArray, JSByteArray, JSString, or JSFunction.
130     // COMPILE_ASSERTS below check that this is true.
131     char storage[64];
132
133     COMPILE_ASSERT(sizeof(JSFinalObject) <= sizeof(storage), sizeof_JSFinalObject_must_be_less_than_storage);
134     JSCell* jsFinalObject = new (storage) JSFinalObject(JSFinalObject::VPtrStealingHack);
135     CLOBBER_MEMORY();
136     JSGlobalData::jsFinalObjectVPtr = jsFinalObject->vptr();
137
138     COMPILE_ASSERT(sizeof(JSArray) <= sizeof(storage), sizeof_JSArray_must_be_less_than_storage);
139     JSCell* jsArray = new (storage) JSArray(JSArray::VPtrStealingHack);
140     CLOBBER_MEMORY();
141     JSGlobalData::jsArrayVPtr = jsArray->vptr();
142
143     COMPILE_ASSERT(sizeof(JSByteArray) <= sizeof(storage), sizeof_JSByteArray_must_be_less_than_storage);
144     JSCell* jsByteArray = new (storage) JSByteArray(JSByteArray::VPtrStealingHack);
145     CLOBBER_MEMORY();
146     JSGlobalData::jsByteArrayVPtr = jsByteArray->vptr();
147
148     COMPILE_ASSERT(sizeof(JSString) <= sizeof(storage), sizeof_JSString_must_be_less_than_storage);
149     JSCell* jsString = new (storage) JSString(JSString::VPtrStealingHack);
150     CLOBBER_MEMORY();
151     JSGlobalData::jsStringVPtr = jsString->vptr();
152
153     COMPILE_ASSERT(sizeof(JSFunction) <= sizeof(storage), sizeof_JSFunction_must_be_less_than_storage);
154     JSCell* jsFunction = new (storage) JSFunction(JSCell::VPtrStealingHack);
155     CLOBBER_MEMORY();
156     JSGlobalData::jsFunctionVPtr = jsFunction->vptr();
157 }
158
159 JSGlobalData::JSGlobalData(GlobalDataType globalDataType, ThreadStackType threadStackType, HeapSize heapSize)
160     : globalDataType(globalDataType)
161     , clientData(0)
162     , topCallFrame(CallFrame::noCaller())
163     , arrayConstructorTable(fastNew<HashTable>(JSC::arrayConstructorTable))
164     , arrayPrototypeTable(fastNew<HashTable>(JSC::arrayPrototypeTable))
165     , booleanPrototypeTable(fastNew<HashTable>(JSC::booleanPrototypeTable))
166     , dateTable(fastNew<HashTable>(JSC::dateTable))
167     , dateConstructorTable(fastNew<HashTable>(JSC::dateConstructorTable))
168     , errorPrototypeTable(fastNew<HashTable>(JSC::errorPrototypeTable))
169     , globalObjectTable(fastNew<HashTable>(JSC::globalObjectTable))
170     , jsonTable(fastNew<HashTable>(JSC::jsonTable))
171     , mathTable(fastNew<HashTable>(JSC::mathTable))
172     , numberConstructorTable(fastNew<HashTable>(JSC::numberConstructorTable))
173     , numberPrototypeTable(fastNew<HashTable>(JSC::numberPrototypeTable))
174     , objectConstructorTable(fastNew<HashTable>(JSC::objectConstructorTable))
175     , objectPrototypeTable(fastNew<HashTable>(JSC::objectPrototypeTable))
176     , regExpTable(fastNew<HashTable>(JSC::regExpTable))
177     , regExpConstructorTable(fastNew<HashTable>(JSC::regExpConstructorTable))
178     , regExpPrototypeTable(fastNew<HashTable>(JSC::regExpPrototypeTable))
179     , stringTable(fastNew<HashTable>(JSC::stringTable))
180     , stringConstructorTable(fastNew<HashTable>(JSC::stringConstructorTable))
181     , identifierTable(globalDataType == Default ? wtfThreadData().currentIdentifierTable() : createIdentifierTable())
182     , propertyNames(new CommonIdentifiers(this))
183     , emptyList(new MarkedArgumentBuffer)
184 #if ENABLE(ASSEMBLER)
185     , executableAllocator(*this)
186 #endif
187     , parserArena(adoptPtr(new ParserArena))
188     , keywords(adoptPtr(new Keywords(this)))
189     , interpreter(0)
190     , heap(this, heapSize)
191 #if ENABLE(DFG_JIT)
192     , sizeOfLastScratchBuffer(0)
193 #endif
194     , dynamicGlobalObject(0)
195     , cachedUTCOffset(std::numeric_limits<double>::quiet_NaN())
196     , maxReentryDepth(threadStackType == ThreadStackTypeSmall ? MaxSmallThreadReentryDepth : MaxLargeThreadReentryDepth)
197     , m_regExpCache(new RegExpCache(this))
198 #if ENABLE(REGEXP_TRACING)
199     , m_rtTraceList(new RTTraceList())
200 #endif
201 #ifndef NDEBUG
202     , exclusiveThread(0)
203 #endif
204 #if CPU(X86) && ENABLE(JIT)
205     , m_timeoutCount(512)
206 #endif
207 #if ENABLE(GC_VALIDATION)
208     , m_isInitializingObject(false)
209 #endif
210 #if ENABLE(TIZEN_JS_EXT_API)
211     , m_executionState(0)
212 #endif
213 {
214     interpreter = new Interpreter;
215     if (globalDataType == Default)
216         m_stack = wtfThreadData().stack();
217
218     // Need to be careful to keep everything consistent here
219     IdentifierTable* existingEntryIdentifierTable = wtfThreadData().setCurrentIdentifierTable(identifierTable);
220     JSLock lock(SilenceAssertionsOnly);
221     structureStructure.set(*this, Structure::createStructure(*this));
222     debuggerActivationStructure.set(*this, DebuggerActivation::createStructure(*this, 0, jsNull()));
223     activationStructure.set(*this, JSActivation::createStructure(*this, 0, jsNull()));
224     interruptedExecutionErrorStructure.set(*this, InterruptedExecutionError::createStructure(*this, 0, jsNull()));
225     terminatedExecutionErrorStructure.set(*this, TerminatedExecutionError::createStructure(*this, 0, jsNull()));
226     staticScopeStructure.set(*this, JSStaticScopeObject::createStructure(*this, 0, jsNull()));
227     strictEvalActivationStructure.set(*this, StrictEvalActivation::createStructure(*this, 0, jsNull()));
228     stringStructure.set(*this, JSString::createStructure(*this, 0, jsNull()));
229     notAnObjectStructure.set(*this, JSNotAnObject::createStructure(*this, 0, jsNull()));
230     propertyNameIteratorStructure.set(*this, JSPropertyNameIterator::createStructure(*this, 0, jsNull()));
231     getterSetterStructure.set(*this, GetterSetter::createStructure(*this, 0, jsNull()));
232     apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, 0, jsNull()));
233     scopeChainNodeStructure.set(*this, ScopeChainNode::createStructure(*this, 0, jsNull()));
234     executableStructure.set(*this, ExecutableBase::createStructure(*this, 0, jsNull()));
235     nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, 0, jsNull()));
236     evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, 0, jsNull()));
237     programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, 0, jsNull()));
238     functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, 0, jsNull()));
239     regExpStructure.set(*this, RegExp::createStructure(*this, 0, jsNull()));
240     structureChainStructure.set(*this, StructureChain::createStructure(*this, 0, jsNull()));
241
242     wtfThreadData().setCurrentIdentifierTable(existingEntryIdentifierTable);
243
244 #if ENABLE(JIT) && ENABLE(INTERPRETER)
245 #if USE(CF)
246     CFStringRef canUseJITKey = CFStringCreateWithCString(0 , "JavaScriptCoreUseJIT", kCFStringEncodingMacRoman);
247     CFBooleanRef canUseJIT = (CFBooleanRef)CFPreferencesCopyAppValue(canUseJITKey, kCFPreferencesCurrentApplication);
248     if (canUseJIT) {
249         m_canUseJIT = kCFBooleanTrue == canUseJIT;
250         CFRelease(canUseJIT);
251     } else {
252       char* canUseJITString = getenv("JavaScriptCoreUseJIT");
253       m_canUseJIT = !canUseJITString || atoi(canUseJITString);
254     }
255     CFRelease(canUseJITKey);
256 #elif OS(UNIX)
257     char* canUseJITString = getenv("JavaScriptCoreUseJIT");
258     m_canUseJIT = !canUseJITString || atoi(canUseJITString);
259 #else
260     m_canUseJIT = true;
261 #endif
262 #endif
263 #if ENABLE(JIT)
264 #if ENABLE(INTERPRETER)
265     if (m_canUseJIT)
266         m_canUseJIT = executableAllocator.isValid();
267 #endif
268     jitStubs = adoptPtr(new JITThunks(this));
269 #endif
270
271     heap.notifyIsSafeToCollect();
272 }
273
274 void JSGlobalData::clearBuiltinStructures()
275 {
276     structureStructure.clear();
277     debuggerActivationStructure.clear();
278     activationStructure.clear();
279     interruptedExecutionErrorStructure.clear();
280     terminatedExecutionErrorStructure.clear();
281     staticScopeStructure.clear();
282     strictEvalActivationStructure.clear();
283     stringStructure.clear();
284     notAnObjectStructure.clear();
285     propertyNameIteratorStructure.clear();
286     getterSetterStructure.clear();
287     apiWrapperStructure.clear();
288     scopeChainNodeStructure.clear();
289     executableStructure.clear();
290     nativeExecutableStructure.clear();
291     evalExecutableStructure.clear();
292     programExecutableStructure.clear();
293     functionExecutableStructure.clear();
294     regExpStructure.clear();
295     structureChainStructure.clear();
296 }
297
298 JSGlobalData::~JSGlobalData()
299 {
300     // By the time this is destroyed, heap.destroy() must already have been called.
301
302     delete interpreter;
303 #ifndef NDEBUG
304     // Zeroing out to make the behavior more predictable when someone attempts to use a deleted instance.
305     interpreter = 0;
306 #endif
307
308     arrayPrototypeTable->deleteTable();
309     arrayConstructorTable->deleteTable();
310     booleanPrototypeTable->deleteTable();
311     dateTable->deleteTable();
312     dateConstructorTable->deleteTable();
313     errorPrototypeTable->deleteTable();
314     globalObjectTable->deleteTable();
315     jsonTable->deleteTable();
316     mathTable->deleteTable();
317     numberConstructorTable->deleteTable();
318     numberPrototypeTable->deleteTable();
319     objectConstructorTable->deleteTable();
320     objectPrototypeTable->deleteTable();
321     regExpTable->deleteTable();
322     regExpConstructorTable->deleteTable();
323     regExpPrototypeTable->deleteTable();
324     stringTable->deleteTable();
325     stringConstructorTable->deleteTable();
326
327     fastDelete(const_cast<HashTable*>(arrayConstructorTable));
328     fastDelete(const_cast<HashTable*>(arrayPrototypeTable));
329     fastDelete(const_cast<HashTable*>(booleanPrototypeTable));
330     fastDelete(const_cast<HashTable*>(dateTable));
331     fastDelete(const_cast<HashTable*>(dateConstructorTable));
332     fastDelete(const_cast<HashTable*>(errorPrototypeTable));
333     fastDelete(const_cast<HashTable*>(globalObjectTable));
334     fastDelete(const_cast<HashTable*>(jsonTable));
335     fastDelete(const_cast<HashTable*>(mathTable));
336     fastDelete(const_cast<HashTable*>(numberConstructorTable));
337     fastDelete(const_cast<HashTable*>(numberPrototypeTable));
338     fastDelete(const_cast<HashTable*>(objectConstructorTable));
339     fastDelete(const_cast<HashTable*>(objectPrototypeTable));
340     fastDelete(const_cast<HashTable*>(regExpTable));
341     fastDelete(const_cast<HashTable*>(regExpConstructorTable));
342     fastDelete(const_cast<HashTable*>(regExpPrototypeTable));
343     fastDelete(const_cast<HashTable*>(stringTable));
344     fastDelete(const_cast<HashTable*>(stringConstructorTable));
345
346     deleteAllValues(opaqueJSClassData);
347
348     delete emptyList;
349
350     delete propertyNames;
351     if (globalDataType != Default)
352         deleteIdentifierTable(identifierTable);
353
354     delete clientData;
355     delete m_regExpCache;
356 #if ENABLE(REGEXP_TRACING)
357     delete m_rtTraceList;
358 #endif
359
360 #if ENABLE(DFG_JIT)
361     for (unsigned i = 0; i < scratchBuffers.size(); ++i)
362         fastFree(scratchBuffers[i]);
363 #endif
364 }
365
366 PassRefPtr<JSGlobalData> JSGlobalData::createContextGroup(ThreadStackType type, HeapSize heapSize)
367 {
368     return adoptRef(new JSGlobalData(APIContextGroup, type, heapSize));
369 }
370
371 PassRefPtr<JSGlobalData> JSGlobalData::create(ThreadStackType type, HeapSize heapSize)
372 {
373     return adoptRef(new JSGlobalData(Default, type, heapSize));
374 }
375
376 PassRefPtr<JSGlobalData> JSGlobalData::createLeaked(ThreadStackType type, HeapSize heapSize)
377 {
378     return create(type, heapSize);
379 }
380
381 bool JSGlobalData::sharedInstanceExists()
382 {
383     return sharedInstanceInternal();
384 }
385
386 JSGlobalData& JSGlobalData::sharedInstance()
387 {
388     JSGlobalData*& instance = sharedInstanceInternal();
389     if (!instance) {
390         instance = adoptRef(new JSGlobalData(APIShared, ThreadStackTypeSmall, SmallHeap)).leakRef();
391         instance->makeUsableFromMultipleThreads();
392     }
393     return *instance;
394 }
395
396 JSGlobalData*& JSGlobalData::sharedInstanceInternal()
397 {
398     ASSERT(JSLock::currentThreadIsHoldingLock());
399     static JSGlobalData* sharedInstance;
400     return sharedInstance;
401 }
402
403 #if ENABLE(JIT)
404 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
405 {
406     return jitStubs->hostFunctionStub(this, function, constructor);
407 }
408 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, ThunkGenerator generator, DFG::Intrinsic intrinsic)
409 {
410     return jitStubs->hostFunctionStub(this, function, generator, intrinsic);
411 }
412 #else
413 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
414 {
415     return NativeExecutable::create(*this, function, constructor);
416 }
417 #endif
418
419 JSGlobalData::ClientData::~ClientData()
420 {
421 }
422
423 void JSGlobalData::resetDateCache()
424 {
425     cachedUTCOffset = std::numeric_limits<double>::quiet_NaN();
426     dstOffsetCache.reset();
427     cachedDateString = UString();
428     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
429     dateInstanceCache.reset();
430 }
431
432 void JSGlobalData::startSampling()
433 {
434     interpreter->startSampling();
435 }
436
437 void JSGlobalData::stopSampling()
438 {
439     interpreter->stopSampling();
440 }
441
442 void JSGlobalData::dumpSampleData(ExecState* exec)
443 {
444     interpreter->dumpSampleData(exec);
445 #if ENABLE(ASSEMBLER)
446     ExecutableAllocator::dumpProfile();
447 #endif
448 }
449
450 void JSGlobalData::recompileAllJSFunctions()
451 {
452     // If JavaScript is running, it's not safe to recompile, since we'll end
453     // up throwing away code that is live on the stack.
454     ASSERT(!dynamicGlobalObject);
455     
456     heap.objectSpace().forEachCell<Recompiler>();
457 }
458
459 struct StackPreservingRecompiler : public MarkedBlock::VoidFunctor {
460     HashSet<FunctionExecutable*> currentlyExecutingFunctions;
461     void operator()(JSCell* cell)
462     {
463         if (!cell->inherits(&FunctionExecutable::s_info))
464             return;
465         FunctionExecutable* executable = jsCast<FunctionExecutable*>(cell);
466         if (currentlyExecutingFunctions.contains(executable))
467             return;
468         executable->discardCode();
469     }
470 };
471
472 void JSGlobalData::releaseExecutableMemory()
473 {
474     if (dynamicGlobalObject) {
475         StackPreservingRecompiler recompiler;
476         HashSet<JSCell*> roots;
477         heap.getConservativeRegisterRoots(roots);
478         HashSet<JSCell*>::iterator end = roots.end();
479         for (HashSet<JSCell*>::iterator ptr = roots.begin(); ptr != end; ++ptr) {
480             ScriptExecutable* executable = 0;
481             JSCell* cell = *ptr;
482             if (cell->inherits(&ScriptExecutable::s_info))
483                 executable = static_cast<ScriptExecutable*>(*ptr);
484             else if (cell->inherits(&JSFunction::s_info)) {
485                 JSFunction* function = asFunction(*ptr);
486                 if (function->isHostFunction())
487                     continue;
488                 executable = function->jsExecutable();
489             } else
490                 continue;
491             ASSERT(executable->inherits(&ScriptExecutable::s_info));
492             executable->unlinkCalls();
493             if (executable->inherits(&FunctionExecutable::s_info))
494                 recompiler.currentlyExecutingFunctions.add(static_cast<FunctionExecutable*>(executable));
495                 
496         }
497         heap.objectSpace().forEachCell<StackPreservingRecompiler>(recompiler);
498     }
499     m_regExpCache->invalidateCode();
500     heap.collectAllGarbage();
501 }
502     
503 void releaseExecutableMemory(JSGlobalData& globalData)
504 {
505     globalData.releaseExecutableMemory();
506 }
507
508 #if ENABLE(REGEXP_TRACING)
509 void JSGlobalData::addRegExpToTrace(RegExp* regExp)
510 {
511     m_rtTraceList->add(regExp);
512 }
513
514 void JSGlobalData::dumpRegExpTrace()
515 {
516     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
517     RTTraceList::iterator iter = ++m_rtTraceList->begin();
518     
519     if (iter != m_rtTraceList->end()) {
520         printf("\nRegExp Tracing\n");
521         printf("                                                            match()    matches\n");
522         printf("Regular Expression                          JIT Address      calls      found\n");
523         printf("----------------------------------------+----------------+----------+----------\n");
524     
525         unsigned reCount = 0;
526     
527         for (; iter != m_rtTraceList->end(); ++iter, ++reCount)
528             (*iter)->printTraceData();
529
530         printf("%d Regular Expressions\n", reCount);
531     }
532     
533     m_rtTraceList->clear();
534 }
535 #else
536 void JSGlobalData::dumpRegExpTrace()
537 {
538 }
539 #endif
540
541 } // namespace JSC