843db3a6031a67047afa2c66f6a8532a5b8264b6
[WebKit-https.git] / Source / JavaScriptCore / runtime / VM.h
1 /*
2  * Copyright (C) 2008, 2009, 2013 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 #ifndef VM_h
30 #define VM_h
31
32 #include "CachedTranscendentalFunction.h"
33 #include "DateInstanceCache.h"
34 #include "ExecutableAllocator.h"
35 #include "Heap.h"
36 #include "Intrinsic.h"
37 #include "JITThunks.h"
38 #include "JITThunks.h"
39 #include "JSCJSValue.h"
40 #include "JSLock.h"
41 #include "LLIntData.h"
42 #include "MacroAssemblerCodeRef.h"
43 #include "NumericStrings.h"
44 #include "ProfilerDatabase.h"
45 #include "PrivateName.h"
46 #include "PrototypeMap.h"
47 #include "SmallStrings.h"
48 #include "Strong.h"
49 #include "ThunkGenerators.h"
50 #include "TypedArrayController.h"
51 #include "Watchdog.h"
52 #include "WeakRandom.h"
53 #include <wtf/BumpPointerAllocator.h>
54 #include <wtf/DateMath.h>
55 #include <wtf/Forward.h>
56 #include <wtf/HashMap.h>
57 #include <wtf/RefCountedArray.h>
58 #include <wtf/SimpleStats.h>
59 #include <wtf/ThreadSafeRefCounted.h>
60 #include <wtf/ThreadSpecific.h>
61 #include <wtf/WTFThreadData.h>
62 #if ENABLE(REGEXP_TRACING)
63 #include <wtf/ListHashSet.h>
64 #endif
65
66 namespace JSC {
67
68     class CodeBlock;
69     class CodeCache;
70     class CommonIdentifiers;
71     class ExecState;
72     class HandleStack;
73     class IdentifierTable;
74     class Interpreter;
75     class JSGlobalObject;
76     class JSObject;
77     class Keywords;
78     class LLIntOffsetsExtractor;
79     class LegacyProfiler;
80     class NativeExecutable;
81     class ParserArena;
82     class RegExpCache;
83     class SourceProvider;
84     class SourceProviderCache;
85     struct StackFrame;
86     class Stringifier;
87     class Structure;
88 #if ENABLE(REGEXP_TRACING)
89     class RegExp;
90 #endif
91     class UnlinkedCodeBlock;
92     class UnlinkedEvalCodeBlock;
93     class UnlinkedFunctionExecutable;
94     class UnlinkedProgramCodeBlock;
95
96 #if ENABLE(DFG_JIT)
97     namespace DFG {
98     class LongLivedState;
99     class Worklist;
100     }
101 #endif // ENABLE(DFG_JIT)
102
103     struct HashTable;
104     struct Instruction;
105
106     struct LocalTimeOffsetCache {
107         LocalTimeOffsetCache()
108             : start(0.0)
109             , end(-1.0)
110             , increment(0.0)
111         {
112         }
113         
114         void reset()
115         {
116             offset = LocalTimeOffset();
117             start = 0.0;
118             end = -1.0;
119             increment = 0.0;
120         }
121
122         LocalTimeOffset offset;
123         double start;
124         double end;
125         double increment;
126     };
127
128 #if ENABLE(DFG_JIT)
129     class ConservativeRoots;
130
131 #if COMPILER(MSVC)
132 #pragma warning(push)
133 #pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
134 #endif
135     struct ScratchBuffer {
136         ScratchBuffer()
137         {
138             u.m_activeLength = 0;
139         }
140
141         static ScratchBuffer* create(size_t size)
142         {
143             ScratchBuffer* result = new (fastMalloc(ScratchBuffer::allocationSize(size))) ScratchBuffer;
144
145             return result;
146         }
147
148         static size_t allocationSize(size_t bufferSize) { return sizeof(ScratchBuffer) + bufferSize; }
149         void setActiveLength(size_t activeLength) { u.m_activeLength = activeLength; }
150         size_t activeLength() const { return u.m_activeLength; };
151         size_t* activeLengthPtr() { return &u.m_activeLength; };
152         void* dataBuffer() { return m_buffer; }
153
154         union {
155             size_t m_activeLength;
156             double pad; // Make sure m_buffer is double aligned.
157         } u;
158 #if CPU(MIPS) && (defined WTF_MIPS_ARCH_REV && WTF_MIPS_ARCH_REV == 2)
159         void* m_buffer[0] __attribute__((aligned(8)));
160 #else
161         void* m_buffer[0];
162 #endif
163     };
164 #if COMPILER(MSVC)
165 #pragma warning(pop)
166 #endif
167 #endif
168
169     class VM : public ThreadSafeRefCounted<VM> {
170     public:
171         // WebCore has a one-to-one mapping of threads to VMs;
172         // either create() or createLeaked() should only be called once
173         // on a thread, this is the 'default' VM (it uses the
174         // thread's default string uniquing table from wtfThreadData).
175         // API contexts created using the new context group aware interface
176         // create APIContextGroup objects which require less locking of JSC
177         // than the old singleton APIShared VM created for use by
178         // the original API.
179         enum VMType { Default, APIContextGroup, APIShared };
180         
181         struct ClientData {
182             JS_EXPORT_PRIVATE virtual ~ClientData() = 0;
183         };
184
185         bool isSharedInstance() { return vmType == APIShared; }
186         bool usingAPI() { return vmType != Default; }
187         static bool sharedInstanceExists();
188         JS_EXPORT_PRIVATE static VM& sharedInstance();
189
190         JS_EXPORT_PRIVATE static PassRefPtr<VM> create(HeapType = SmallHeap);
191         JS_EXPORT_PRIVATE static PassRefPtr<VM> createLeaked(HeapType = SmallHeap);
192         static PassRefPtr<VM> createContextGroup(HeapType = SmallHeap);
193         JS_EXPORT_PRIVATE ~VM();
194
195         void makeUsableFromMultipleThreads() { heap.machineThreads().makeUsableFromMultipleThreads(); }
196
197     private:
198         RefPtr<JSLock> m_apiLock;
199
200     public:
201 #if ENABLE(ASSEMBLER)
202         // executableAllocator should be destructed after the heap, as the heap can call executableAllocator
203         // in its destructor.
204         ExecutableAllocator executableAllocator;
205 #endif
206
207         // The heap should be just after executableAllocator and before other members to ensure that it's
208         // destructed after all the objects that reference it.
209         Heap heap;
210         
211 #if ENABLE(DFG_JIT)
212         OwnPtr<DFG::LongLivedState> dfgState;
213         RefPtr<DFG::Worklist> worklist;
214 #endif // ENABLE(DFG_JIT)
215
216         VMType vmType;
217         ClientData* clientData;
218         ExecState* topCallFrame;
219         Watchdog watchdog;
220
221         const HashTable* arrayConstructorTable;
222         const HashTable* arrayPrototypeTable;
223         const HashTable* booleanPrototypeTable;
224         const HashTable* dataViewTable;
225         const HashTable* dateTable;
226         const HashTable* dateConstructorTable;
227         const HashTable* errorPrototypeTable;
228         const HashTable* globalObjectTable;
229         const HashTable* jsonTable;
230         const HashTable* numberConstructorTable;
231         const HashTable* numberPrototypeTable;
232         const HashTable* objectConstructorTable;
233         const HashTable* privateNamePrototypeTable;
234         const HashTable* regExpTable;
235         const HashTable* regExpConstructorTable;
236         const HashTable* regExpPrototypeTable;
237         const HashTable* stringConstructorTable;
238         const HashTable* promisePrototypeTable;
239         const HashTable* promiseConstructorTable;
240         const HashTable* promiseResolverPrototypeTable;
241         
242         Strong<Structure> structureStructure;
243         Strong<Structure> structureRareDataStructure;
244         Strong<Structure> debuggerActivationStructure;
245         Strong<Structure> terminatedExecutionErrorStructure;
246         Strong<Structure> stringStructure;
247         Strong<Structure> notAnObjectStructure;
248         Strong<Structure> propertyNameIteratorStructure;
249         Strong<Structure> getterSetterStructure;
250         Strong<Structure> apiWrapperStructure;
251         Strong<Structure> JSScopeStructure;
252         Strong<Structure> executableStructure;
253         Strong<Structure> nativeExecutableStructure;
254         Strong<Structure> evalExecutableStructure;
255         Strong<Structure> programExecutableStructure;
256         Strong<Structure> functionExecutableStructure;
257         Strong<Structure> regExpStructure;
258         Strong<Structure> sharedSymbolTableStructure;
259         Strong<Structure> structureChainStructure;
260         Strong<Structure> sparseArrayValueMapStructure;
261         Strong<Structure> withScopeStructure;
262         Strong<Structure> unlinkedFunctionExecutableStructure;
263         Strong<Structure> unlinkedProgramCodeBlockStructure;
264         Strong<Structure> unlinkedEvalCodeBlockStructure;
265         Strong<Structure> unlinkedFunctionCodeBlockStructure;
266         Strong<Structure> propertyTableStructure;
267
268         IdentifierTable* identifierTable;
269         CommonIdentifiers* propertyNames;
270         const MarkedArgumentBuffer* emptyList; // Lists are supposed to be allocated on the stack to have their elements properly marked, which is not the case here - but this list has nothing to mark.
271         SmallStrings smallStrings;
272         NumericStrings numericStrings;
273         DateInstanceCache dateInstanceCache;
274         WTF::SimpleStats machineCodeBytesPerBytecodeWordForBaselineJIT;
275         Vector<CodeBlock*> codeBlocksBeingCompiled;
276         void startedCompiling(CodeBlock* codeBlock)
277         {
278             codeBlocksBeingCompiled.append(codeBlock);
279         }
280
281         void finishedCompiling(CodeBlock* codeBlock)
282         {
283             ASSERT_UNUSED(codeBlock, codeBlock == codeBlocksBeingCompiled.last());
284             codeBlocksBeingCompiled.removeLast();
285         }
286
287         void setInDefineOwnProperty(bool inDefineOwnProperty)
288         {
289             m_inDefineOwnProperty = inDefineOwnProperty;
290         }
291
292         bool isInDefineOwnProperty()
293         {
294             return m_inDefineOwnProperty;
295         }
296
297         LegacyProfiler* enabledProfiler()
298         {
299             return m_enabledProfiler;
300         }
301
302 #if ENABLE(JIT) && ENABLE(LLINT)
303         bool canUseJIT() { return m_canUseJIT; }
304 #elif ENABLE(JIT)
305         bool canUseJIT() { return true; } // jit only
306 #else
307         bool canUseJIT() { return false; } // interpreter only
308 #endif
309
310 #if ENABLE(YARR_JIT)
311         bool canUseRegExpJIT() { return m_canUseRegExpJIT; }
312 #else
313         bool canUseRegExpJIT() { return false; } // interpreter only
314 #endif
315
316         SourceProviderCache* addSourceProviderCache(SourceProvider*);
317         void clearSourceProviderCaches();
318
319         PrototypeMap prototypeMap;
320
321         OwnPtr<ParserArena> parserArena;
322         typedef HashMap<RefPtr<SourceProvider>, RefPtr<SourceProviderCache> > SourceProviderCacheMap;
323         SourceProviderCacheMap sourceProviderCacheMap;
324         OwnPtr<Keywords> keywords;
325         Interpreter* interpreter;
326 #if ENABLE(JIT)
327         OwnPtr<JITThunks> jitStubs;
328         MacroAssemblerCodeRef getCTIStub(ThunkGenerator generator)
329         {
330             return jitStubs->ctiStub(this, generator);
331         }
332         NativeExecutable* getHostFunction(NativeFunction, Intrinsic);
333 #endif
334         NativeExecutable* getHostFunction(NativeFunction, NativeFunction constructor);
335
336         JSValue exception;
337         JS_EXPORT_PRIVATE void clearExceptionStack();
338         RefCountedArray<StackFrame>& exceptionStack() { return m_exceptionStack; }
339
340         const ClassInfo* const jsArrayClassInfo;
341         const ClassInfo* const jsFinalObjectClassInfo;
342
343         ReturnAddressPtr exceptionLocation;
344         JSValue hostCallReturnValue;
345         ExecState* callFrameForThrow;
346         void* targetMachinePCForThrow;
347         Instruction* targetInterpreterPCForThrow;
348 #if ENABLE(DFG_JIT)
349         uint32_t osrExitIndex;
350         void* osrExitJumpDestination;
351         Vector<ScratchBuffer*> scratchBuffers;
352         size_t sizeOfLastScratchBuffer;
353         
354         ScratchBuffer* scratchBufferForSize(size_t size)
355         {
356             if (!size)
357                 return 0;
358             
359             if (size > sizeOfLastScratchBuffer) {
360                 // Protect against a N^2 memory usage pathology by ensuring
361                 // that at worst, we get a geometric series, meaning that the
362                 // total memory usage is somewhere around
363                 // max(scratch buffer size) * 4.
364                 sizeOfLastScratchBuffer = size * 2;
365
366                 scratchBuffers.append(ScratchBuffer::create(sizeOfLastScratchBuffer));
367             }
368
369             ScratchBuffer* result = scratchBuffers.last();
370             result->setActiveLength(0);
371             return result;
372         }
373
374         void gatherConservativeRoots(ConservativeRoots&);
375 #endif
376
377         JSGlobalObject* dynamicGlobalObject;
378
379         HashSet<JSObject*> stringRecursionCheckVisitedObjects;
380
381         LocalTimeOffsetCache localTimeOffsetCache;
382         
383         String cachedDateString;
384         double cachedDateStringValue;
385
386         LegacyProfiler* m_enabledProfiler;
387         OwnPtr<Profiler::Database> m_perBytecodeProfiler;
388         RefPtr<TypedArrayController> m_typedArrayController;
389         RegExpCache* m_regExpCache;
390         BumpPointerAllocator m_regExpAllocator;
391
392 #if ENABLE(REGEXP_TRACING)
393         typedef ListHashSet<RefPtr<RegExp> > RTTraceList;
394         RTTraceList* m_rtTraceList;
395 #endif
396
397         ThreadIdentifier exclusiveThread;
398
399         CachedTranscendentalFunction<std::sin> cachedSin;
400
401         JS_EXPORT_PRIVATE void resetDateCache();
402
403         JS_EXPORT_PRIVATE void startSampling();
404         JS_EXPORT_PRIVATE void stopSampling();
405         JS_EXPORT_PRIVATE void dumpSampleData(ExecState* exec);
406         RegExpCache* regExpCache() { return m_regExpCache; }
407 #if ENABLE(REGEXP_TRACING)
408         void addRegExpToTrace(PassRefPtr<RegExp> regExp);
409 #endif
410         JS_EXPORT_PRIVATE void dumpRegExpTrace();
411
412         bool isCollectorBusy() { return heap.isBusy(); }
413         JS_EXPORT_PRIVATE void releaseExecutableMemory();
414
415 #if ENABLE(GC_VALIDATION)
416         bool isInitializingObject() const; 
417         void setInitializingObjectClass(const ClassInfo*);
418 #endif
419
420         unsigned m_newStringsSinceLastHashCons;
421
422         static const unsigned s_minNumberOfNewStringsToHashCons = 100;
423
424         bool haveEnoughNewStringsToHashCons() { return m_newStringsSinceLastHashCons > s_minNumberOfNewStringsToHashCons; }
425         void resetNewStringsSinceLastHashCons() { m_newStringsSinceLastHashCons = 0; }
426
427         bool currentThreadIsHoldingAPILock() const
428         {
429             return m_apiLock->currentThreadIsHoldingLock() || exclusiveThread == currentThread();
430         }
431
432         JSLock& apiLock() { return *m_apiLock; }
433         CodeCache* codeCache() { return m_codeCache.get(); }
434
435         void prepareToDiscardCode();
436         
437         JS_EXPORT_PRIVATE void discardAllCode();
438
439     private:
440         friend class LLIntOffsetsExtractor;
441         
442         VM(VMType, HeapType);
443         static VM*& sharedInstanceInternal();
444         void createNativeThunk();
445 #if ENABLE(ASSEMBLER)
446         bool m_canUseAssembler;
447 #endif
448 #if ENABLE(JIT)
449         bool m_canUseJIT;
450 #endif
451 #if ENABLE(YARR_JIT)
452         bool m_canUseRegExpJIT;
453 #endif
454 #if ENABLE(GC_VALIDATION)
455         const ClassInfo* m_initializingObjectClass;
456 #endif
457         bool m_inDefineOwnProperty;
458         OwnPtr<CodeCache> m_codeCache;
459         RefCountedArray<StackFrame> m_exceptionStack;
460     };
461
462 #if ENABLE(GC_VALIDATION)
463     inline bool VM::isInitializingObject() const
464     {
465         return !!m_initializingObjectClass;
466     }
467
468     inline void VM::setInitializingObjectClass(const ClassInfo* initializingObjectClass)
469     {
470         m_initializingObjectClass = initializingObjectClass;
471     }
472 #endif
473
474     inline Heap* WeakSet::heap() const
475     {
476         return &m_vm->heap;
477     }
478
479 } // namespace JSC
480
481 #endif // VM_h