50ad5581f90e8b20b47a4089713c536437b10a53
[WebKit-https.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 "JSZombie.h"
50 #include "Lexer.h"
51 #include "Lookup.h"
52 #include "Nodes.h"
53 #include "Parser.h"
54 #include "RegExpCache.h"
55 #include "RegExpObject.h"
56 #include "StrictEvalActivation.h"
57 #include <wtf/WTFThreadData.h>
58 #if ENABLE(REGEXP_TRACING)
59 #include "RegExp.h"
60 #endif
61
62
63 #if ENABLE(JSC_MULTIPLE_THREADS)
64 #include <wtf/Threading.h>
65 #endif
66
67 #if PLATFORM(MAC)
68 #include "ProfilerServer.h"
69 #include <CoreFoundation/CoreFoundation.h>
70 #endif
71
72 using namespace WTF;
73
74 namespace {
75
76 using namespace JSC;
77
78 class Recompiler {
79 public:
80     void operator()(JSCell*);
81 };
82
83 inline void Recompiler::operator()(JSCell* cell)
84 {
85     if (!cell->inherits(&JSFunction::s_info))
86         return;
87     JSFunction* function = asFunction(cell);
88     if (function->executable()->isHostFunction())
89         return;
90     function->jsExecutable()->discardCode();
91 }
92
93 } // namespace
94
95 namespace JSC {
96
97 extern JSC_CONST_HASHTABLE HashTable arrayConstructorTable;
98 extern JSC_CONST_HASHTABLE HashTable arrayPrototypeTable;
99 extern JSC_CONST_HASHTABLE HashTable booleanPrototypeTable;
100 extern JSC_CONST_HASHTABLE HashTable jsonTable;
101 extern JSC_CONST_HASHTABLE HashTable dateTable;
102 extern JSC_CONST_HASHTABLE HashTable dateConstructorTable;
103 extern JSC_CONST_HASHTABLE HashTable errorPrototypeTable;
104 extern JSC_CONST_HASHTABLE HashTable globalObjectTable;
105 extern JSC_CONST_HASHTABLE HashTable mathTable;
106 extern JSC_CONST_HASHTABLE HashTable numberConstructorTable;
107 extern JSC_CONST_HASHTABLE HashTable numberPrototypeTable;
108 extern JSC_CONST_HASHTABLE HashTable objectConstructorTable;
109 extern JSC_CONST_HASHTABLE HashTable objectPrototypeTable;
110 extern JSC_CONST_HASHTABLE HashTable regExpTable;
111 extern JSC_CONST_HASHTABLE HashTable regExpConstructorTable;
112 extern JSC_CONST_HASHTABLE HashTable regExpPrototypeTable;
113 extern JSC_CONST_HASHTABLE HashTable stringTable;
114 extern JSC_CONST_HASHTABLE HashTable stringConstructorTable;
115
116 void* JSGlobalData::jsArrayVPtr;
117 void* JSGlobalData::jsByteArrayVPtr;
118 void* JSGlobalData::jsStringVPtr;
119 void* JSGlobalData::jsFunctionVPtr;
120
121 #if COMPILER(GCC)
122 // Work around for gcc trying to coalesce our reads of the various cell vptrs
123 #define CLOBBER_MEMORY() do { \
124     asm volatile ("" : : : "memory"); \
125 } while (false)
126 #else
127 #define CLOBBER_MEMORY() do { } while (false)
128 #endif
129
130 void JSGlobalData::storeVPtrs()
131 {
132     // Enough storage to fit a JSArray, JSByteArray, JSString, or JSFunction.
133     // COMPILE_ASSERTS below check that this is true.
134     char storage[64];
135
136     COMPILE_ASSERT(sizeof(JSArray) <= sizeof(storage), sizeof_JSArray_must_be_less_than_storage);
137     JSCell* jsArray = new (storage) JSArray(JSArray::VPtrStealingHack);
138     CLOBBER_MEMORY();
139     JSGlobalData::jsArrayVPtr = jsArray->vptr();
140
141     COMPILE_ASSERT(sizeof(JSByteArray) <= sizeof(storage), sizeof_JSByteArray_must_be_less_than_storage);
142     JSCell* jsByteArray = new (storage) JSByteArray(JSByteArray::VPtrStealingHack);
143     CLOBBER_MEMORY();
144     JSGlobalData::jsByteArrayVPtr = jsByteArray->vptr();
145
146     COMPILE_ASSERT(sizeof(JSString) <= sizeof(storage), sizeof_JSString_must_be_less_than_storage);
147     JSCell* jsString = new (storage) JSString(JSString::VPtrStealingHack);
148     CLOBBER_MEMORY();
149     JSGlobalData::jsStringVPtr = jsString->vptr();
150
151     COMPILE_ASSERT(sizeof(JSFunction) <= sizeof(storage), sizeof_JSFunction_must_be_less_than_storage);
152     JSCell* jsFunction = new (storage) JSFunction(JSCell::VPtrStealingHack);
153     CLOBBER_MEMORY();
154     JSGlobalData::jsFunctionVPtr = jsFunction->vptr();
155 }
156
157 JSGlobalData::JSGlobalData(GlobalDataType globalDataType, ThreadStackType threadStackType)
158     : globalDataType(globalDataType)
159     , clientData(0)
160     , arrayConstructorTable(fastNew<HashTable>(JSC::arrayConstructorTable))
161     , arrayPrototypeTable(fastNew<HashTable>(JSC::arrayPrototypeTable))
162     , booleanPrototypeTable(fastNew<HashTable>(JSC::booleanPrototypeTable))
163     , dateTable(fastNew<HashTable>(JSC::dateTable))
164     , dateConstructorTable(fastNew<HashTable>(JSC::dateConstructorTable))
165     , errorPrototypeTable(fastNew<HashTable>(JSC::errorPrototypeTable))
166     , globalObjectTable(fastNew<HashTable>(JSC::globalObjectTable))
167     , jsonTable(fastNew<HashTable>(JSC::jsonTable))
168     , mathTable(fastNew<HashTable>(JSC::mathTable))
169     , numberConstructorTable(fastNew<HashTable>(JSC::numberConstructorTable))
170     , numberPrototypeTable(fastNew<HashTable>(JSC::numberPrototypeTable))
171     , objectConstructorTable(fastNew<HashTable>(JSC::objectConstructorTable))
172     , objectPrototypeTable(fastNew<HashTable>(JSC::objectPrototypeTable))
173     , regExpTable(fastNew<HashTable>(JSC::regExpTable))
174     , regExpConstructorTable(fastNew<HashTable>(JSC::regExpConstructorTable))
175     , regExpPrototypeTable(fastNew<HashTable>(JSC::regExpPrototypeTable))
176     , stringTable(fastNew<HashTable>(JSC::stringTable))
177     , stringConstructorTable(fastNew<HashTable>(JSC::stringConstructorTable))
178     , identifierTable(globalDataType == Default ? wtfThreadData().currentIdentifierTable() : createIdentifierTable())
179     , propertyNames(new CommonIdentifiers(this))
180     , emptyList(new MarkedArgumentBuffer)
181     , lexer(new Lexer(this))
182     , parser(new Parser)
183     , interpreter(0)
184     , heap(this)
185     , globalObjectCount(0)
186     , dynamicGlobalObject(0)
187     , cachedUTCOffset(NaN)
188     , maxReentryDepth(threadStackType == ThreadStackTypeSmall ? MaxSmallThreadReentryDepth : MaxLargeThreadReentryDepth)
189     , m_regExpCache(new RegExpCache(this))
190 #if ENABLE(REGEXP_TRACING)
191     , m_rtTraceList(new RTTraceList())
192 #endif
193 #ifndef NDEBUG
194     , exclusiveThread(0)
195 #endif
196 {
197     interpreter = new Interpreter(*this);
198     if (globalDataType == Default)
199         m_stack = wtfThreadData().stack();
200
201     // Need to be careful to keep everything consistent here
202     IdentifierTable* existingEntryIdentifierTable = wtfThreadData().setCurrentIdentifierTable(identifierTable);
203     JSLock lock(SilenceAssertionsOnly);
204     structureStructure.set(*this, Structure::createStructure(*this));
205     debuggerActivationStructure.set(*this, DebuggerActivation::createStructure(*this, jsNull()));
206     activationStructure.set(*this, JSActivation::createStructure(*this, jsNull()));
207     interruptedExecutionErrorStructure.set(*this, JSNonFinalObject::createStructure(*this, jsNull()));
208     terminatedExecutionErrorStructure.set(*this, JSNonFinalObject::createStructure(*this, jsNull()));
209     staticScopeStructure.set(*this, JSStaticScopeObject::createStructure(*this, jsNull()));
210     strictEvalActivationStructure.set(*this, StrictEvalActivation::createStructure(*this, jsNull()));
211     stringStructure.set(*this, JSString::createStructure(*this, jsNull()));
212     notAnObjectStructure.set(*this, JSNotAnObject::createStructure(*this, jsNull()));
213     propertyNameIteratorStructure.set(*this, JSPropertyNameIterator::createStructure(*this, jsNull()));
214     getterSetterStructure.set(*this, GetterSetter::createStructure(*this, jsNull()));
215     apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, jsNull()));
216     scopeChainNodeStructure.set(*this, ScopeChainNode::createStructure(*this, jsNull()));
217     executableStructure.set(*this, ExecutableBase::createStructure(*this, jsNull()));
218     nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, jsNull()));
219     evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, jsNull()));
220     programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, jsNull()));
221     functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, jsNull()));
222     dummyMarkableCellStructure.set(*this, JSCell::createDummyStructure(*this));
223     regExpStructure.set(*this, RegExp::createStructure(*this, jsNull()));
224     structureChainStructure.set(*this, StructureChain::createStructure(*this, jsNull()));
225
226 #if ENABLE(JSC_ZOMBIES)
227     zombieStructure.set(*this, JSZombie::createStructure(*this, jsNull()));
228 #endif
229
230     wtfThreadData().setCurrentIdentifierTable(existingEntryIdentifierTable);
231
232 #if PLATFORM(MAC)
233     startProfilerServerIfNeeded();
234 #endif
235 #if ENABLE(JIT) && ENABLE(INTERPRETER)
236 #if USE(CF)
237     CFStringRef canUseJITKey = CFStringCreateWithCString(0 , "JavaScriptCoreUseJIT", kCFStringEncodingMacRoman);
238     CFBooleanRef canUseJIT = (CFBooleanRef)CFPreferencesCopyAppValue(canUseJITKey, kCFPreferencesCurrentApplication);
239     if (canUseJIT) {
240         m_canUseJIT = kCFBooleanTrue == canUseJIT;
241         CFRelease(canUseJIT);
242     } else {
243       char* canUseJITString = getenv("JavaScriptCoreUseJIT");
244       m_canUseJIT = !canUseJITString || atoi(canUseJITString);
245     }
246     CFRelease(canUseJITKey);
247 #elif OS(UNIX)
248     char* canUseJITString = getenv("JavaScriptCoreUseJIT");
249     m_canUseJIT = !canUseJITString || atoi(canUseJITString);
250 #else
251     m_canUseJIT = true;
252 #endif
253 #endif
254 #if ENABLE(JIT)
255 #if ENABLE(INTERPRETER)
256     if (m_canUseJIT)
257         m_canUseJIT = executableAllocator.isValid();
258 #endif
259     jitStubs = adoptPtr(new JITThunks(this));
260 #endif
261 }
262
263 void JSGlobalData::clearBuiltinStructures()
264 {
265     structureStructure.clear();
266     debuggerActivationStructure.clear();
267     activationStructure.clear();
268     interruptedExecutionErrorStructure.clear();
269     terminatedExecutionErrorStructure.clear();
270     staticScopeStructure.clear();
271     strictEvalActivationStructure.clear();
272     stringStructure.clear();
273     notAnObjectStructure.clear();
274     propertyNameIteratorStructure.clear();
275     getterSetterStructure.clear();
276     apiWrapperStructure.clear();
277     scopeChainNodeStructure.clear();
278     executableStructure.clear();
279     nativeExecutableStructure.clear();
280     evalExecutableStructure.clear();
281     programExecutableStructure.clear();
282     functionExecutableStructure.clear();
283     dummyMarkableCellStructure.clear();
284     regExpStructure.clear();
285     structureChainStructure.clear();
286
287 #if ENABLE(JSC_ZOMBIES)
288     zombieStructure.clear();
289 #endif
290 }
291
292 JSGlobalData::~JSGlobalData()
293 {
294     // By the time this is destroyed, heap.destroy() must already have been called.
295
296     delete interpreter;
297 #ifndef NDEBUG
298     // Zeroing out to make the behavior more predictable when someone attempts to use a deleted instance.
299     interpreter = 0;
300 #endif
301
302     arrayPrototypeTable->deleteTable();
303     arrayConstructorTable->deleteTable();
304     booleanPrototypeTable->deleteTable();
305     dateTable->deleteTable();
306     dateConstructorTable->deleteTable();
307     errorPrototypeTable->deleteTable();
308     globalObjectTable->deleteTable();
309     jsonTable->deleteTable();
310     mathTable->deleteTable();
311     numberConstructorTable->deleteTable();
312     numberPrototypeTable->deleteTable();
313     objectConstructorTable->deleteTable();
314     objectPrototypeTable->deleteTable();
315     regExpTable->deleteTable();
316     regExpConstructorTable->deleteTable();
317     regExpPrototypeTable->deleteTable();
318     stringTable->deleteTable();
319     stringConstructorTable->deleteTable();
320
321     fastDelete(const_cast<HashTable*>(arrayConstructorTable));
322     fastDelete(const_cast<HashTable*>(arrayPrototypeTable));
323     fastDelete(const_cast<HashTable*>(booleanPrototypeTable));
324     fastDelete(const_cast<HashTable*>(dateTable));
325     fastDelete(const_cast<HashTable*>(dateConstructorTable));
326     fastDelete(const_cast<HashTable*>(errorPrototypeTable));
327     fastDelete(const_cast<HashTable*>(globalObjectTable));
328     fastDelete(const_cast<HashTable*>(jsonTable));
329     fastDelete(const_cast<HashTable*>(mathTable));
330     fastDelete(const_cast<HashTable*>(numberConstructorTable));
331     fastDelete(const_cast<HashTable*>(numberPrototypeTable));
332     fastDelete(const_cast<HashTable*>(objectConstructorTable));
333     fastDelete(const_cast<HashTable*>(objectPrototypeTable));
334     fastDelete(const_cast<HashTable*>(regExpTable));
335     fastDelete(const_cast<HashTable*>(regExpConstructorTable));
336     fastDelete(const_cast<HashTable*>(regExpPrototypeTable));
337     fastDelete(const_cast<HashTable*>(stringTable));
338     fastDelete(const_cast<HashTable*>(stringConstructorTable));
339
340     delete parser;
341     delete lexer;
342
343     deleteAllValues(opaqueJSClassData);
344
345     delete emptyList;
346
347     delete propertyNames;
348     if (globalDataType != Default)
349         deleteIdentifierTable(identifierTable);
350
351     delete clientData;
352     delete m_regExpCache;
353 #if ENABLE(REGEXP_TRACING)
354     delete m_rtTraceList;
355 #endif
356 }
357
358 PassRefPtr<JSGlobalData> JSGlobalData::createContextGroup(ThreadStackType type)
359 {
360     return adoptRef(new JSGlobalData(APIContextGroup, type));
361 }
362
363 PassRefPtr<JSGlobalData> JSGlobalData::create(ThreadStackType type)
364 {
365     return adoptRef(new JSGlobalData(Default, type));
366 }
367
368 PassRefPtr<JSGlobalData> JSGlobalData::createLeaked(ThreadStackType type)
369 {
370     return create(type);
371 }
372
373 bool JSGlobalData::sharedInstanceExists()
374 {
375     return sharedInstanceInternal();
376 }
377
378 JSGlobalData& JSGlobalData::sharedInstance()
379 {
380     JSGlobalData*& instance = sharedInstanceInternal();
381     if (!instance) {
382         instance = adoptRef(new JSGlobalData(APIShared, ThreadStackTypeSmall)).leakRef();
383 #if ENABLE(JSC_MULTIPLE_THREADS)
384         instance->makeUsableFromMultipleThreads();
385 #endif
386     }
387     return *instance;
388 }
389
390 JSGlobalData*& JSGlobalData::sharedInstanceInternal()
391 {
392     ASSERT(JSLock::currentThreadIsHoldingLock());
393     static JSGlobalData* sharedInstance;
394     return sharedInstance;
395 }
396
397 #if ENABLE(JIT)
398 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function)
399 {
400     return jitStubs->hostFunctionStub(this, function);
401 }
402 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function, ThunkGenerator generator)
403 {
404     return jitStubs->hostFunctionStub(this, function, generator);
405 }
406 #else
407 NativeExecutable* JSGlobalData::getHostFunction(NativeFunction function)
408 {
409     return NativeExecutable::create(*this, function, callHostFunctionAsConstructor);
410 }
411 #endif
412
413 JSGlobalData::ClientData::~ClientData()
414 {
415 }
416
417 void JSGlobalData::resetDateCache()
418 {
419     cachedUTCOffset = NaN;
420     dstOffsetCache.reset();
421     cachedDateString = UString();
422     cachedDateStringValue = NaN;
423     dateInstanceCache.reset();
424 }
425
426 void JSGlobalData::startSampling()
427 {
428     interpreter->startSampling();
429 }
430
431 void JSGlobalData::stopSampling()
432 {
433     interpreter->stopSampling();
434 }
435
436 void JSGlobalData::dumpSampleData(ExecState* exec)
437 {
438     interpreter->dumpSampleData(exec);
439 }
440
441 void JSGlobalData::recompileAllJSFunctions()
442 {
443     // If JavaScript is running, it's not safe to recompile, since we'll end
444     // up throwing away code that is live on the stack.
445     ASSERT(!dynamicGlobalObject);
446     
447     Recompiler recompiler;
448     heap.forEach(recompiler);
449 }
450
451 #if ENABLE(REGEXP_TRACING)
452 void JSGlobalData::addRegExpToTrace(RegExp* regExp)
453 {
454     m_rtTraceList->add(regExp);
455 }
456
457 void JSGlobalData::dumpRegExpTrace()
458 {
459     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
460     RTTraceList::iterator iter = ++m_rtTraceList->begin();
461     
462     if (iter != m_rtTraceList->end()) {
463         printf("\nRegExp Tracing\n");
464         printf("                                                            match()    matches\n");
465         printf("Regular Expression                          JIT Address      calls      found\n");
466         printf("----------------------------------------+----------------+----------+----------\n");
467     
468         unsigned reCount = 0;
469     
470         for (; iter != m_rtTraceList->end(); ++iter, ++reCount)
471             (*iter)->printTraceData();
472
473         printf("%d Regular Expressions\n", reCount);
474     }
475     
476     m_rtTraceList->clear();
477 }
478 #else
479 void JSGlobalData::dumpRegExpTrace()
480 {
481 }
482 #endif
483
484 } // namespace JSC