cf49a66385088af52ff203ac5576f203efb7f7e1
[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 #if ENABLE(PROMISES)
239         const HashTable* promisePrototypeTable;
240         const HashTable* promiseConstructorTable;
241         const HashTable* promiseResolverPrototypeTable;
242 #endif
243
244         Strong<Structure> structureStructure;
245         Strong<Structure> structureRareDataStructure;
246         Strong<Structure> debuggerActivationStructure;
247         Strong<Structure> terminatedExecutionErrorStructure;
248         Strong<Structure> stringStructure;
249         Strong<Structure> notAnObjectStructure;
250         Strong<Structure> propertyNameIteratorStructure;
251         Strong<Structure> getterSetterStructure;
252         Strong<Structure> apiWrapperStructure;
253         Strong<Structure> JSScopeStructure;
254         Strong<Structure> executableStructure;
255         Strong<Structure> nativeExecutableStructure;
256         Strong<Structure> evalExecutableStructure;
257         Strong<Structure> programExecutableStructure;
258         Strong<Structure> functionExecutableStructure;
259         Strong<Structure> regExpStructure;
260         Strong<Structure> sharedSymbolTableStructure;
261         Strong<Structure> structureChainStructure;
262         Strong<Structure> sparseArrayValueMapStructure;
263         Strong<Structure> withScopeStructure;
264         Strong<Structure> unlinkedFunctionExecutableStructure;
265         Strong<Structure> unlinkedProgramCodeBlockStructure;
266         Strong<Structure> unlinkedEvalCodeBlockStructure;
267         Strong<Structure> unlinkedFunctionCodeBlockStructure;
268         Strong<Structure> propertyTableStructure;
269
270         IdentifierTable* identifierTable;
271         CommonIdentifiers* propertyNames;
272         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.
273         SmallStrings smallStrings;
274         NumericStrings numericStrings;
275         DateInstanceCache dateInstanceCache;
276         WTF::SimpleStats machineCodeBytesPerBytecodeWordForBaselineJIT;
277
278         void setInDefineOwnProperty(bool inDefineOwnProperty)
279         {
280             m_inDefineOwnProperty = inDefineOwnProperty;
281         }
282
283         bool isInDefineOwnProperty()
284         {
285             return m_inDefineOwnProperty;
286         }
287
288         LegacyProfiler* enabledProfiler()
289         {
290             return m_enabledProfiler;
291         }
292
293 #if ENABLE(JIT) && ENABLE(LLINT)
294         bool canUseJIT() { return m_canUseJIT; }
295 #elif ENABLE(JIT)
296         bool canUseJIT() { return true; } // jit only
297 #else
298         bool canUseJIT() { return false; } // interpreter only
299 #endif
300
301 #if ENABLE(YARR_JIT)
302         bool canUseRegExpJIT() { return m_canUseRegExpJIT; }
303 #else
304         bool canUseRegExpJIT() { return false; } // interpreter only
305 #endif
306
307         SourceProviderCache* addSourceProviderCache(SourceProvider*);
308         void clearSourceProviderCaches();
309
310         PrototypeMap prototypeMap;
311
312         OwnPtr<ParserArena> parserArena;
313         typedef HashMap<RefPtr<SourceProvider>, RefPtr<SourceProviderCache> > SourceProviderCacheMap;
314         SourceProviderCacheMap sourceProviderCacheMap;
315         OwnPtr<Keywords> keywords;
316         Interpreter* interpreter;
317 #if ENABLE(JIT)
318         OwnPtr<JITThunks> jitStubs;
319         MacroAssemblerCodeRef getCTIStub(ThunkGenerator generator)
320         {
321             return jitStubs->ctiStub(this, generator);
322         }
323         NativeExecutable* getHostFunction(NativeFunction, Intrinsic);
324 #endif
325         NativeExecutable* getHostFunction(NativeFunction, NativeFunction constructor);
326
327         static ptrdiff_t exceptionOffset()
328         {
329             return OBJECT_OFFSETOF(VM, m_exception);
330         }
331         
332         JS_EXPORT_PRIVATE void clearException();
333         JS_EXPORT_PRIVATE void clearExceptionStack();
334         void getExceptionInfo(JSValue& exception, RefCountedArray<StackFrame>& exceptionStack);
335         void setExceptionInfo(JSValue& exception, RefCountedArray<StackFrame>& exceptionStack);
336         JSValue exception() const { return m_exception; }
337         JSValue* addressOfException() { return &m_exception; }
338         const RefCountedArray<StackFrame>& exceptionStack() const { return m_exceptionStack; }
339
340         JS_EXPORT_PRIVATE JSValue throwException(ExecState*, JSValue);
341         JS_EXPORT_PRIVATE JSObject* throwException(ExecState*, JSObject*);
342         
343         const ClassInfo* const jsArrayClassInfo;
344         const ClassInfo* const jsFinalObjectClassInfo;
345
346         ReturnAddressPtr exceptionLocation;
347         JSValue hostCallReturnValue;
348         ExecState* callFrameForThrow;
349         void* targetMachinePCForThrow;
350         Instruction* targetInterpreterPCForThrow;
351 #if ENABLE(DFG_JIT)
352         uint32_t osrExitIndex;
353         void* osrExitJumpDestination;
354         Vector<ScratchBuffer*> scratchBuffers;
355         size_t sizeOfLastScratchBuffer;
356         
357         ScratchBuffer* scratchBufferForSize(size_t size)
358         {
359             if (!size)
360                 return 0;
361             
362             if (size > sizeOfLastScratchBuffer) {
363                 // Protect against a N^2 memory usage pathology by ensuring
364                 // that at worst, we get a geometric series, meaning that the
365                 // total memory usage is somewhere around
366                 // max(scratch buffer size) * 4.
367                 sizeOfLastScratchBuffer = size * 2;
368
369                 scratchBuffers.append(ScratchBuffer::create(sizeOfLastScratchBuffer));
370             }
371
372             ScratchBuffer* result = scratchBuffers.last();
373             result->setActiveLength(0);
374             return result;
375         }
376
377         void gatherConservativeRoots(ConservativeRoots&);
378 #endif
379
380         JSGlobalObject* dynamicGlobalObject;
381
382         HashSet<JSObject*> stringRecursionCheckVisitedObjects;
383
384         LocalTimeOffsetCache localTimeOffsetCache;
385         
386         String cachedDateString;
387         double cachedDateStringValue;
388
389         LegacyProfiler* m_enabledProfiler;
390         OwnPtr<Profiler::Database> m_perBytecodeProfiler;
391         RefPtr<TypedArrayController> m_typedArrayController;
392         RegExpCache* m_regExpCache;
393         BumpPointerAllocator m_regExpAllocator;
394
395 #if ENABLE(REGEXP_TRACING)
396         typedef ListHashSet<RefPtr<RegExp> > RTTraceList;
397         RTTraceList* m_rtTraceList;
398 #endif
399
400         ThreadIdentifier exclusiveThread;
401
402         CachedTranscendentalFunction<std::sin> cachedSin;
403
404         JS_EXPORT_PRIVATE void resetDateCache();
405
406         JS_EXPORT_PRIVATE void startSampling();
407         JS_EXPORT_PRIVATE void stopSampling();
408         JS_EXPORT_PRIVATE void dumpSampleData(ExecState* exec);
409         RegExpCache* regExpCache() { return m_regExpCache; }
410 #if ENABLE(REGEXP_TRACING)
411         void addRegExpToTrace(PassRefPtr<RegExp> regExp);
412 #endif
413         JS_EXPORT_PRIVATE void dumpRegExpTrace();
414
415         bool isCollectorBusy() { return heap.isBusy(); }
416         JS_EXPORT_PRIVATE void releaseExecutableMemory();
417
418 #if ENABLE(GC_VALIDATION)
419         bool isInitializingObject() const; 
420         void setInitializingObjectClass(const ClassInfo*);
421 #endif
422
423         unsigned m_newStringsSinceLastHashCons;
424
425         static const unsigned s_minNumberOfNewStringsToHashCons = 100;
426
427         bool haveEnoughNewStringsToHashCons() { return m_newStringsSinceLastHashCons > s_minNumberOfNewStringsToHashCons; }
428         void resetNewStringsSinceLastHashCons() { m_newStringsSinceLastHashCons = 0; }
429
430         bool currentThreadIsHoldingAPILock() const
431         {
432             return m_apiLock->currentThreadIsHoldingLock() || exclusiveThread == currentThread();
433         }
434
435         JSLock& apiLock() { return *m_apiLock; }
436         CodeCache* codeCache() { return m_codeCache.get(); }
437
438         void prepareToDiscardCode();
439         
440         JS_EXPORT_PRIVATE void discardAllCode();
441
442     private:
443         friend class LLIntOffsetsExtractor;
444         friend class ClearExceptionScope;
445         
446         VM(VMType, HeapType);
447         static VM*& sharedInstanceInternal();
448         void createNativeThunk();
449 #if ENABLE(ASSEMBLER)
450         bool m_canUseAssembler;
451 #endif
452 #if ENABLE(JIT)
453         bool m_canUseJIT;
454 #endif
455 #if ENABLE(YARR_JIT)
456         bool m_canUseRegExpJIT;
457 #endif
458 #if ENABLE(GC_VALIDATION)
459         const ClassInfo* m_initializingObjectClass;
460 #endif
461         JSValue m_exception;
462         bool m_inDefineOwnProperty;
463         OwnPtr<CodeCache> m_codeCache;
464         RefCountedArray<StackFrame> m_exceptionStack;
465     };
466
467 #if ENABLE(GC_VALIDATION)
468     inline bool VM::isInitializingObject() const
469     {
470         return !!m_initializingObjectClass;
471     }
472
473     inline void VM::setInitializingObjectClass(const ClassInfo* initializingObjectClass)
474     {
475         m_initializingObjectClass = initializingObjectClass;
476     }
477 #endif
478
479     inline Heap* WeakSet::heap() const
480     {
481         return &m_vm->heap;
482     }
483
484 } // namespace JSC
485
486 #endif // VM_h