2 * Copyright (C) 2008, 2011 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
30 #include "JSGlobalData.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"
42 #include "JSByteArray.h"
43 #include "JSClassRef.h"
44 #include "JSFunction.h"
46 #include "JSNotAnObject.h"
47 #include "JSPropertyNameIterator.h"
48 #include "JSStaticScopeObject.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>
60 #if ENABLE(REGEXP_TRACING)
65 #include <CoreFoundation/CoreFoundation.h>
74 class Recompiler : public MarkedBlock::VoidFunctor {
76 void operator()(JSCell*);
79 inline void Recompiler::operator()(JSCell* cell)
81 if (!cell->inherits(&JSFunction::s_info))
83 JSFunction* function = asFunction(cell);
84 if (!function->executable() || function->executable()->isHostFunction())
86 function->jsExecutable()->discardCode();
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;
112 void* JSGlobalData::jsFinalObjectVPtr;
113 void* JSGlobalData::jsArrayVPtr;
114 void* JSGlobalData::jsByteArrayVPtr;
115 void* JSGlobalData::jsStringVPtr;
116 void* JSGlobalData::jsFunctionVPtr;
119 // Work around for gcc trying to coalesce our reads of the various cell vptrs
120 #define CLOBBER_MEMORY() do { \
121 asm volatile ("" : : : "memory"); \
124 #define CLOBBER_MEMORY() do { } while (false)
127 void JSGlobalData::storeVPtrs()
129 // Enough storage to fit a JSArray, JSByteArray, JSString, or JSFunction.
130 // COMPILE_ASSERTS below check that this is true.
133 COMPILE_ASSERT(sizeof(JSFinalObject) <= sizeof(storage), sizeof_JSFinalObject_must_be_less_than_storage);
134 JSCell* jsFinalObject = new (storage) JSFinalObject(JSFinalObject::VPtrStealingHack);
136 JSGlobalData::jsFinalObjectVPtr = jsFinalObject->vptr();
138 COMPILE_ASSERT(sizeof(JSArray) <= sizeof(storage), sizeof_JSArray_must_be_less_than_storage);
139 JSCell* jsArray = new (storage) JSArray(JSArray::VPtrStealingHack);
141 JSGlobalData::jsArrayVPtr = jsArray->vptr();
143 COMPILE_ASSERT(sizeof(JSByteArray) <= sizeof(storage), sizeof_JSByteArray_must_be_less_than_storage);
144 JSCell* jsByteArray = new (storage) JSByteArray(JSByteArray::VPtrStealingHack);
146 JSGlobalData::jsByteArrayVPtr = jsByteArray->vptr();
148 COMPILE_ASSERT(sizeof(JSString) <= sizeof(storage), sizeof_JSString_must_be_less_than_storage);
149 JSCell* jsString = new (storage) JSString(JSString::VPtrStealingHack);
151 JSGlobalData::jsStringVPtr = jsString->vptr();
153 COMPILE_ASSERT(sizeof(JSFunction) <= sizeof(storage), sizeof_JSFunction_must_be_less_than_storage);
154 JSCell* jsFunction = new (storage) JSFunction(JSCell::VPtrStealingHack);
156 JSGlobalData::jsFunctionVPtr = jsFunction->vptr();
159 JSGlobalData::JSGlobalData(GlobalDataType globalDataType, ThreadStackType threadStackType, HeapSize heapSize)
160 : globalDataType(globalDataType)
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)
187 , parserArena(adoptPtr(new ParserArena))
188 , keywords(adoptPtr(new Keywords(this)))
190 , heap(this, heapSize)
192 , sizeOfLastScratchBuffer(0)
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())
204 #if CPU(X86) && ENABLE(JIT)
205 , m_timeoutCount(512)
207 #if ENABLE(GC_VALIDATION)
208 , m_isInitializingObject(false)
210 #if ENABLE(TIZEN_JS_EXT_API)
211 , m_executionState(0)
214 interpreter = new Interpreter;
215 if (globalDataType == Default)
216 m_stack = wtfThreadData().stack();
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()));
242 wtfThreadData().setCurrentIdentifierTable(existingEntryIdentifierTable);
244 #if ENABLE(JIT) && ENABLE(INTERPRETER)
246 CFStringRef canUseJITKey = CFStringCreateWithCString(0 , "JavaScriptCoreUseJIT", kCFStringEncodingMacRoman);
247 CFBooleanRef canUseJIT = (CFBooleanRef)CFPreferencesCopyAppValue(canUseJITKey, kCFPreferencesCurrentApplication);
249 m_canUseJIT = kCFBooleanTrue == canUseJIT;
250 CFRelease(canUseJIT);
252 char* canUseJITString = getenv("JavaScriptCoreUseJIT");
253 m_canUseJIT = !canUseJITString || atoi(canUseJITString);
255 CFRelease(canUseJITKey);
257 char* canUseJITString = getenv("JavaScriptCoreUseJIT");
258 m_canUseJIT = !canUseJITString || atoi(canUseJITString);
264 #if ENABLE(INTERPRETER)
266 m_canUseJIT = executableAllocator.isValid();
268 jitStubs = adoptPtr(new JITThunks(this));
271 heap.notifyIsSafeToCollect();
274 void JSGlobalData::clearBuiltinStructures()
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();
298 JSGlobalData::~JSGlobalData()
300 // By the time this is destroyed, heap.destroy() must already have been called.
304 // Zeroing out to make the behavior more predictable when someone attempts to use a deleted instance.
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();
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));
346 deleteAllValues(opaqueJSClassData);
350 delete propertyNames;
351 if (globalDataType != Default)
352 deleteIdentifierTable(identifierTable);
355 delete m_regExpCache;
356 #if ENABLE(REGEXP_TRACING)
357 delete m_rtTraceList;
361 for (unsigned i = 0; i < scratchBuffers.size(); ++i)
362 fastFree(scratchBuffers[i]);
366 PassRefPtr<JSGlobalData> JSGlobalData::createContextGroup(ThreadStackType type, HeapSize heapSize)
368 return adoptRef(new JSGlobalData(APIContextGroup, type, heapSize));
371 PassRefPtr<JSGlobalData> JSGlobalData::create(ThreadStackType type, HeapSize heapSize)
373 return adoptRef(new JSGlobalData(Default, type, heapSize));
376 PassRefPtr<JSGlobalData> JSGlobalData::createLeaked(ThreadStackType type, HeapSize heapSize)
378 return create(type, heapSize);
381 bool JSGlobalData::sharedInstanceExists()
383 return sharedInstanceInternal();
386 JSGlobalData& JSGlobalData::sharedInstance()
388 JSGlobalData*& instance = sharedInstanceInternal();
390 instance = adoptRef(new JSGlobalData(APIShared, ThreadStackTypeSmall, SmallHeap)).leakRef();
391 instance->makeUsableFromMultipleThreads();
396 JSGlobalData*& JSGlobalData::sharedInstanceInternal()
398 ASSERT(JSLock::currentThreadIsHoldingLock());
399 static JSGlobalData* sharedInstance;
400 return sharedInstance;
404 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
406 return jitStubs->hostFunctionStub(this, function, constructor);
408 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, ThunkGenerator generator, DFG::Intrinsic intrinsic)
410 return jitStubs->hostFunctionStub(this, function, generator, intrinsic);
413 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, NativeFunction constructor)
415 return NativeExecutable::create(*this, function, constructor);
419 JSGlobalData::ClientData::~ClientData()
423 void JSGlobalData::resetDateCache()
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();
432 void JSGlobalData::startSampling()
434 interpreter->startSampling();
437 void JSGlobalData::stopSampling()
439 interpreter->stopSampling();
442 void JSGlobalData::dumpSampleData(ExecState* exec)
444 interpreter->dumpSampleData(exec);
445 #if ENABLE(ASSEMBLER)
446 ExecutableAllocator::dumpProfile();
450 void JSGlobalData::recompileAllJSFunctions()
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);
456 heap.objectSpace().forEachCell<Recompiler>();
459 struct StackPreservingRecompiler : public MarkedBlock::VoidFunctor {
460 HashSet<FunctionExecutable*> currentlyExecutingFunctions;
461 void operator()(JSCell* cell)
463 if (!cell->inherits(&FunctionExecutable::s_info))
465 FunctionExecutable* executable = jsCast<FunctionExecutable*>(cell);
466 if (currentlyExecutingFunctions.contains(executable))
468 executable->discardCode();
472 void JSGlobalData::releaseExecutableMemory()
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;
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())
488 executable = function->jsExecutable();
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));
497 heap.objectSpace().forEachCell<StackPreservingRecompiler>(recompiler);
499 m_regExpCache->invalidateCode();
500 heap.collectAllGarbage();
503 void releaseExecutableMemory(JSGlobalData& globalData)
505 globalData.releaseExecutableMemory();
508 #if ENABLE(REGEXP_TRACING)
509 void JSGlobalData::addRegExpToTrace(RegExp* regExp)
511 m_rtTraceList->add(regExp);
514 void JSGlobalData::dumpRegExpTrace()
516 // The first RegExp object is ignored. It is create by the RegExpPrototype ctor and not used.
517 RTTraceList::iterator iter = ++m_rtTraceList->begin();
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");
525 unsigned reCount = 0;
527 for (; iter != m_rtTraceList->end(); ++iter, ++reCount)
528 (*iter)->printTraceData();
530 printf("%d Regular Expressions\n", reCount);
533 m_rtTraceList->clear();
536 void JSGlobalData::dumpRegExpTrace()