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