Source/JavaScriptCore: https://bugs.webkit.org/show_bug.cgi?id=119548
[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         static ptrdiff_t exceptionOffset()
337         {
338             return OBJECT_OFFSETOF(VM, m_exception);
339         }
340         
341         JS_EXPORT_PRIVATE void clearException();
342         JS_EXPORT_PRIVATE void clearExceptionStack();
343         void getExceptionInfo(JSValue& exception, RefCountedArray<StackFrame>& exceptionStack);
344         void setExceptionInfo(JSValue& exception, RefCountedArray<StackFrame>& exceptionStack);
345         JSValue exception() const { return m_exception; }
346         JSValue* addressOfException() { return &m_exception; }
347         const RefCountedArray<StackFrame>& exceptionStack() const { return m_exceptionStack; }
348
349         JS_EXPORT_PRIVATE JSValue throwException(ExecState*, JSValue);
350         JS_EXPORT_PRIVATE JSObject* throwException(ExecState*, JSObject*);
351         
352         const ClassInfo* const jsArrayClassInfo;
353         const ClassInfo* const jsFinalObjectClassInfo;
354
355         ReturnAddressPtr exceptionLocation;
356         JSValue hostCallReturnValue;
357         ExecState* callFrameForThrow;
358         void* targetMachinePCForThrow;
359         Instruction* targetInterpreterPCForThrow;
360 #if ENABLE(DFG_JIT)
361         uint32_t osrExitIndex;
362         void* osrExitJumpDestination;
363         Vector<ScratchBuffer*> scratchBuffers;
364         size_t sizeOfLastScratchBuffer;
365         
366         ScratchBuffer* scratchBufferForSize(size_t size)
367         {
368             if (!size)
369                 return 0;
370             
371             if (size > sizeOfLastScratchBuffer) {
372                 // Protect against a N^2 memory usage pathology by ensuring
373                 // that at worst, we get a geometric series, meaning that the
374                 // total memory usage is somewhere around
375                 // max(scratch buffer size) * 4.
376                 sizeOfLastScratchBuffer = size * 2;
377
378                 scratchBuffers.append(ScratchBuffer::create(sizeOfLastScratchBuffer));
379             }
380
381             ScratchBuffer* result = scratchBuffers.last();
382             result->setActiveLength(0);
383             return result;
384         }
385
386         void gatherConservativeRoots(ConservativeRoots&);
387 #endif
388
389         JSGlobalObject* dynamicGlobalObject;
390
391         HashSet<JSObject*> stringRecursionCheckVisitedObjects;
392
393         LocalTimeOffsetCache localTimeOffsetCache;
394         
395         String cachedDateString;
396         double cachedDateStringValue;
397
398         LegacyProfiler* m_enabledProfiler;
399         OwnPtr<Profiler::Database> m_perBytecodeProfiler;
400         RefPtr<TypedArrayController> m_typedArrayController;
401         RegExpCache* m_regExpCache;
402         BumpPointerAllocator m_regExpAllocator;
403
404 #if ENABLE(REGEXP_TRACING)
405         typedef ListHashSet<RefPtr<RegExp> > RTTraceList;
406         RTTraceList* m_rtTraceList;
407 #endif
408
409         ThreadIdentifier exclusiveThread;
410
411         CachedTranscendentalFunction<std::sin> cachedSin;
412
413         JS_EXPORT_PRIVATE void resetDateCache();
414
415         JS_EXPORT_PRIVATE void startSampling();
416         JS_EXPORT_PRIVATE void stopSampling();
417         JS_EXPORT_PRIVATE void dumpSampleData(ExecState* exec);
418         RegExpCache* regExpCache() { return m_regExpCache; }
419 #if ENABLE(REGEXP_TRACING)
420         void addRegExpToTrace(PassRefPtr<RegExp> regExp);
421 #endif
422         JS_EXPORT_PRIVATE void dumpRegExpTrace();
423
424         bool isCollectorBusy() { return heap.isBusy(); }
425         JS_EXPORT_PRIVATE void releaseExecutableMemory();
426
427 #if ENABLE(GC_VALIDATION)
428         bool isInitializingObject() const; 
429         void setInitializingObjectClass(const ClassInfo*);
430 #endif
431
432         unsigned m_newStringsSinceLastHashCons;
433
434         static const unsigned s_minNumberOfNewStringsToHashCons = 100;
435
436         bool haveEnoughNewStringsToHashCons() { return m_newStringsSinceLastHashCons > s_minNumberOfNewStringsToHashCons; }
437         void resetNewStringsSinceLastHashCons() { m_newStringsSinceLastHashCons = 0; }
438
439         bool currentThreadIsHoldingAPILock() const
440         {
441             return m_apiLock->currentThreadIsHoldingLock() || exclusiveThread == currentThread();
442         }
443
444         JSLock& apiLock() { return *m_apiLock; }
445         CodeCache* codeCache() { return m_codeCache.get(); }
446
447         void prepareToDiscardCode();
448         
449         JS_EXPORT_PRIVATE void discardAllCode();
450
451     private:
452         friend class LLIntOffsetsExtractor;
453         friend class ClearExceptionScope;
454         
455         VM(VMType, HeapType);
456         static VM*& sharedInstanceInternal();
457         void createNativeThunk();
458 #if ENABLE(ASSEMBLER)
459         bool m_canUseAssembler;
460 #endif
461 #if ENABLE(JIT)
462         bool m_canUseJIT;
463 #endif
464 #if ENABLE(YARR_JIT)
465         bool m_canUseRegExpJIT;
466 #endif
467 #if ENABLE(GC_VALIDATION)
468         const ClassInfo* m_initializingObjectClass;
469 #endif
470         JSValue m_exception;
471         bool m_inDefineOwnProperty;
472         OwnPtr<CodeCache> m_codeCache;
473         RefCountedArray<StackFrame> m_exceptionStack;
474     };
475
476 #if ENABLE(GC_VALIDATION)
477     inline bool VM::isInitializingObject() const
478     {
479         return !!m_initializingObjectClass;
480     }
481
482     inline void VM::setInitializingObjectClass(const ClassInfo* initializingObjectClass)
483     {
484         m_initializingObjectClass = initializingObjectClass;
485     }
486 #endif
487
488     inline Heap* WeakSet::heap() const
489     {
490         return &m_vm->heap;
491     }
492
493 } // namespace JSC
494
495 #endif // VM_h