178a3e2ba88faede959ca30e38be0792adad8928
[WebKit.git] / Source / JavaScriptCore / runtime / VM.h
1 /*
2  * Copyright (C) 2008-2017 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 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 #pragma once
30
31 #include "CallData.h"
32 #include "ConcurrentJSLock.h"
33 #include "ControlFlowProfiler.h"
34 #include "DateInstanceCache.h"
35 #include "DeleteAllCodeEffort.h"
36 #include "ExceptionEventLocation.h"
37 #include "ExecutableAllocator.h"
38 #include "FunctionHasExecutedCache.h"
39 #include "Heap.h"
40 #include "Intrinsic.h"
41 #include "JITThunks.h"
42 #include "JSCJSValue.h"
43 #include "JSDestructibleObjectSubspace.h"
44 #include "JSLock.h"
45 #include "JSSegmentedVariableObjectSubspace.h"
46 #include "JSStringSubspace.h"
47 #include "JSWebAssemblyCodeBlockSubspace.h"
48 #include "MacroAssemblerCodeRef.h"
49 #include "Microtask.h"
50 #include "NumericStrings.h"
51 #include "PrivateName.h"
52 #include "PrototypeMap.h"
53 #include "SmallStrings.h"
54 #include "SourceCode.h"
55 #include "Strong.h"
56 #include "Subspace.h"
57 #include "TemplateRegistryKeyTable.h"
58 #include "ThunkGenerators.h"
59 #include "VMEntryRecord.h"
60 #include "VMTraps.h"
61 #include "Watchpoint.h"
62 #include <wtf/Bag.h>
63 #include <wtf/BumpPointerAllocator.h>
64 #include <wtf/CheckedArithmetic.h>
65 #include <wtf/DateMath.h>
66 #include <wtf/Deque.h>
67 #include <wtf/DoublyLinkedList.h>
68 #include <wtf/Forward.h>
69 #include <wtf/HashMap.h>
70 #include <wtf/HashSet.h>
71 #include <wtf/StackBounds.h>
72 #include <wtf/Stopwatch.h>
73 #include <wtf/ThreadSafeRefCounted.h>
74 #include <wtf/ThreadSpecific.h>
75 #include <wtf/WTFThreadData.h>
76 #include <wtf/text/SymbolRegistry.h>
77 #include <wtf/text/WTFString.h>
78 #if ENABLE(REGEXP_TRACING)
79 #include <wtf/ListHashSet.h>
80 #endif
81
82 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
83 #include <wtf/StackTrace.h>
84 #endif
85
86 namespace WTF {
87 class SimpleStats;
88 } // namespace WTF
89 using WTF::SimpleStats;
90
91 namespace JSC {
92
93 class BuiltinExecutables;
94 class BytecodeIntrinsicRegistry;
95 class CodeBlock;
96 class CodeCache;
97 class CommonIdentifiers;
98 class CustomGetterSetter;
99 class ExecState;
100 class Exception;
101 class ExceptionScope;
102 class HandleStack;
103 class TypeProfiler;
104 class TypeProfilerLog;
105 class HasOwnPropertyCache;
106 class HeapProfiler;
107 class Identifier;
108 class Interpreter;
109 class JSCustomGetterSetterFunction;
110 class JSGlobalObject;
111 class JSObject;
112 class JSWebAssemblyInstance;
113 class LLIntOffsetsExtractor;
114 class NativeExecutable;
115 class PromiseDeferredTimer;
116 class RegExpCache;
117 class Register;
118 class RegisterAtOffsetList;
119 #if ENABLE(SAMPLING_PROFILER)
120 class SamplingProfiler;
121 #endif
122 class ShadowChicken;
123 class ScriptExecutable;
124 class SourceProvider;
125 class SourceProviderCache;
126 class StackFrame;
127 class Structure;
128 #if ENABLE(REGEXP_TRACING)
129 class RegExp;
130 #endif
131 class Symbol;
132 class TypedArrayController;
133 class UnlinkedCodeBlock;
134 class UnlinkedEvalCodeBlock;
135 class UnlinkedFunctionExecutable;
136 class UnlinkedProgramCodeBlock;
137 class UnlinkedModuleProgramCodeBlock;
138 class VirtualRegister;
139 class VMEntryScope;
140 class Watchdog;
141 class Watchpoint;
142 class WatchpointSet;
143
144 #if ENABLE(DFG_JIT)
145 namespace DFG {
146 class LongLivedState;
147 }
148 #endif // ENABLE(DFG_JIT)
149 #if ENABLE(FTL_JIT)
150 namespace FTL {
151 class Thunks;
152 }
153 #endif // ENABLE(FTL_JIT)
154 namespace CommonSlowPaths {
155 struct ArityCheckData;
156 }
157 namespace Profiler {
158 class Database;
159 }
160 namespace DOMJIT {
161 class Signature;
162 }
163
164 struct HashTable;
165 struct Instruction;
166
167 struct LocalTimeOffsetCache {
168     LocalTimeOffsetCache()
169         : start(0.0)
170         , end(-1.0)
171         , increment(0.0)
172         , timeType(WTF::UTCTime)
173     {
174     }
175
176     void reset()
177     {
178         offset = LocalTimeOffset();
179         start = 0.0;
180         end = -1.0;
181         increment = 0.0;
182         timeType = WTF::UTCTime;
183     }
184
185     LocalTimeOffset offset;
186     double start;
187     double end;
188     double increment;
189     WTF::TimeType timeType;
190 };
191
192 class QueuedTask {
193     WTF_MAKE_NONCOPYABLE(QueuedTask);
194     WTF_MAKE_FAST_ALLOCATED;
195 public:
196     void run();
197
198     QueuedTask(VM& vm, JSGlobalObject* globalObject, Ref<Microtask>&& microtask)
199         : m_globalObject(vm, globalObject)
200         , m_microtask(WTFMove(microtask))
201     {
202     }
203
204 private:
205     Strong<JSGlobalObject> m_globalObject;
206     Ref<Microtask> m_microtask;
207 };
208
209 class ConservativeRoots;
210
211 #if COMPILER(MSVC)
212 #pragma warning(push)
213 #pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
214 #endif
215 struct ScratchBuffer {
216     ScratchBuffer()
217     {
218         u.m_activeLength = 0;
219     }
220
221     static ScratchBuffer* create(size_t size)
222     {
223         ScratchBuffer* result = new (fastMalloc(ScratchBuffer::allocationSize(size))) ScratchBuffer;
224
225         return result;
226     }
227
228     static size_t allocationSize(Checked<size_t> bufferSize) { return (sizeof(ScratchBuffer) + bufferSize).unsafeGet(); }
229     void setActiveLength(size_t activeLength) { u.m_activeLength = activeLength; }
230     size_t activeLength() const { return u.m_activeLength; };
231     size_t* activeLengthPtr() { return &u.m_activeLength; };
232     void* dataBuffer() { return m_buffer; }
233
234     union {
235         size_t m_activeLength;
236         double pad; // Make sure m_buffer is double aligned.
237     } u;
238 #if CPU(MIPS) && (defined WTF_MIPS_ARCH_REV && WTF_MIPS_ARCH_REV == 2)
239     void* m_buffer[0] __attribute__((aligned(8)));
240 #else
241     void* m_buffer[0];
242 #endif
243 };
244 #if COMPILER(MSVC)
245 #pragma warning(pop)
246 #endif
247
248 class VM : public ThreadSafeRefCounted<VM>, public DoublyLinkedListNode<VM> {
249 public:
250     // WebCore has a one-to-one mapping of threads to VMs;
251     // either create() or createLeaked() should only be called once
252     // on a thread, this is the 'default' VM (it uses the
253     // thread's default string uniquing table from wtfThreadData).
254     // API contexts created using the new context group aware interface
255     // create APIContextGroup objects which require less locking of JSC
256     // than the old singleton APIShared VM created for use by
257     // the original API.
258     enum VMType { Default, APIContextGroup, APIShared };
259
260     struct ClientData {
261         JS_EXPORT_PRIVATE virtual ~ClientData() = 0;
262     };
263
264     bool isSharedInstance() { return vmType == APIShared; }
265     bool usingAPI() { return vmType != Default; }
266     JS_EXPORT_PRIVATE static bool sharedInstanceExists();
267     JS_EXPORT_PRIVATE static VM& sharedInstance();
268
269     JS_EXPORT_PRIVATE static Ref<VM> create(HeapType = SmallHeap);
270     JS_EXPORT_PRIVATE static Ref<VM> createLeaked(HeapType = SmallHeap);
271     static Ref<VM> createContextGroup(HeapType = SmallHeap);
272     JS_EXPORT_PRIVATE ~VM();
273
274     Watchdog& ensureWatchdog();
275     Watchdog* watchdog() { return m_watchdog.get(); }
276
277     HeapProfiler* heapProfiler() const { return m_heapProfiler.get(); }
278     JS_EXPORT_PRIVATE HeapProfiler& ensureHeapProfiler();
279
280 #if ENABLE(SAMPLING_PROFILER)
281     SamplingProfiler* samplingProfiler() { return m_samplingProfiler.get(); }
282     JS_EXPORT_PRIVATE SamplingProfiler& ensureSamplingProfiler(RefPtr<Stopwatch>&&);
283 #endif
284
285 private:
286     RefPtr<JSLock> m_apiLock;
287
288 public:
289     Heap heap;
290     
291     Subspace auxiliarySpace;
292     
293     // Whenever possible, use subspaceFor<CellType>(vm) to get one of these subspaces.
294     Subspace cellSpace;
295     Subspace destructibleCellSpace;
296     JSStringSubspace stringSpace;
297     JSDestructibleObjectSubspace destructibleObjectSpace;
298     JSSegmentedVariableObjectSubspace segmentedVariableObjectSpace;
299 #if ENABLE(WEBASSEMBLY)
300     JSWebAssemblyCodeBlockSubspace webAssemblyCodeBlockSpace;
301 #endif
302
303 #if ENABLE(DFG_JIT)
304     std::unique_ptr<DFG::LongLivedState> dfgState;
305 #endif // ENABLE(DFG_JIT)
306
307     VMType vmType;
308     ClientData* clientData;
309     VMEntryFrame* topVMEntryFrame;
310     // NOTE: When throwing an exception while rolling back the call frame, this may be equal to
311     // topVMEntryFrame.
312     // FIXME: This should be a void*, because it might not point to a CallFrame.
313     // https://bugs.webkit.org/show_bug.cgi?id=160441
314     ExecState* topCallFrame { nullptr };
315     // FIXME: Save this state elsewhere to allow PIC. https://bugs.webkit.org/show_bug.cgi?id=169773
316     JSWebAssemblyInstance* wasmContext { nullptr };
317     Strong<Structure> structureStructure;
318     Strong<Structure> structureRareDataStructure;
319     Strong<Structure> terminatedExecutionErrorStructure;
320     Strong<Structure> stringStructure;
321     Strong<Structure> propertyNameIteratorStructure;
322     Strong<Structure> propertyNameEnumeratorStructure;
323     Strong<Structure> customGetterSetterStructure;
324     Strong<Structure> scopedArgumentsTableStructure;
325     Strong<Structure> apiWrapperStructure;
326     Strong<Structure> JSScopeStructure;
327     Strong<Structure> executableStructure;
328     Strong<Structure> nativeExecutableStructure;
329     Strong<Structure> evalExecutableStructure;
330     Strong<Structure> programExecutableStructure;
331     Strong<Structure> functionExecutableStructure;
332 #if ENABLE(WEBASSEMBLY)
333     Strong<Structure> webAssemblyToJSCalleeStructure;
334     Strong<Structure> webAssemblyCodeBlockStructure;
335 #endif
336     Strong<Structure> moduleProgramExecutableStructure;
337     Strong<Structure> regExpStructure;
338     Strong<Structure> symbolStructure;
339     Strong<Structure> symbolTableStructure;
340     Strong<Structure> fixedArrayStructure;
341     Strong<Structure> sourceCodeStructure;
342     Strong<Structure> scriptFetcherStructure;
343     Strong<Structure> structureChainStructure;
344     Strong<Structure> sparseArrayValueMapStructure;
345     Strong<Structure> templateRegistryKeyStructure;
346     Strong<Structure> arrayBufferNeuteringWatchpointStructure;
347     Strong<Structure> unlinkedFunctionExecutableStructure;
348     Strong<Structure> unlinkedProgramCodeBlockStructure;
349     Strong<Structure> unlinkedEvalCodeBlockStructure;
350     Strong<Structure> unlinkedFunctionCodeBlockStructure;
351     Strong<Structure> unlinkedModuleProgramCodeBlockStructure;
352     Strong<Structure> propertyTableStructure;
353     Strong<Structure> weakMapDataStructure;
354     Strong<Structure> inferredValueStructure;
355     Strong<Structure> inferredTypeStructure;
356     Strong<Structure> inferredTypeTableStructure;
357     Strong<Structure> functionRareDataStructure;
358     Strong<Structure> exceptionStructure;
359     Strong<Structure> promiseDeferredStructure;
360     Strong<Structure> internalPromiseDeferredStructure;
361     Strong<Structure> nativeStdFunctionCellStructure;
362     Strong<Structure> programCodeBlockStructure;
363     Strong<Structure> moduleProgramCodeBlockStructure;
364     Strong<Structure> evalCodeBlockStructure;
365     Strong<Structure> functionCodeBlockStructure;
366     Strong<Structure> hashMapBucketSetStructure;
367     Strong<Structure> hashMapBucketMapStructure;
368     Strong<Structure> hashMapImplSetStructure;
369     Strong<Structure> hashMapImplMapStructure;
370
371     Strong<JSCell> iterationTerminator;
372     Strong<JSCell> emptyPropertyNameEnumerator;
373
374     std::unique_ptr<PromiseDeferredTimer> promiseDeferredTimer;
375     
376     JSCell* currentlyDestructingCallbackObject;
377     const ClassInfo* currentlyDestructingCallbackObjectClassInfo;
378
379     AtomicStringTable* m_atomicStringTable;
380     WTF::SymbolRegistry m_symbolRegistry;
381     TemplateRegistryKeyTable m_templateRegistryKeytable;
382     CommonIdentifiers* propertyNames;
383     const ArgList* emptyList;
384     SmallStrings smallStrings;
385     NumericStrings numericStrings;
386     DateInstanceCache dateInstanceCache;
387     std::unique_ptr<SimpleStats> machineCodeBytesPerBytecodeWordForBaselineJIT;
388     WeakGCMap<std::pair<CustomGetterSetter*, int>, JSCustomGetterSetterFunction> customGetterSetterFunctionMap;
389     WeakGCMap<StringImpl*, JSString, PtrHash<StringImpl*>> stringCache;
390     Strong<JSString> lastCachedString;
391
392     AtomicStringTable* atomicStringTable() const { return m_atomicStringTable; }
393     WTF::SymbolRegistry& symbolRegistry() { return m_symbolRegistry; }
394
395     TemplateRegistryKeyTable& templateRegistryKeyTable() { return m_templateRegistryKeytable; }
396
397     WeakGCMap<SymbolImpl*, Symbol, PtrHash<SymbolImpl*>> symbolImplToSymbolMap;
398
399     enum class DeletePropertyMode {
400         // Default behaviour of deleteProperty, matching the spec.
401         Default,
402         // This setting causes deleteProperty to force deletion of all
403         // properties including those that are non-configurable (DontDelete).
404         IgnoreConfigurable
405     };
406
407     DeletePropertyMode deletePropertyMode()
408     {
409         return m_deletePropertyMode;
410     }
411
412     class DeletePropertyModeScope {
413     public:
414         DeletePropertyModeScope(VM& vm, DeletePropertyMode mode)
415             : m_vm(vm)
416             , m_previousMode(vm.m_deletePropertyMode)
417         {
418             m_vm.m_deletePropertyMode = mode;
419         }
420
421         ~DeletePropertyModeScope()
422         {
423             m_vm.m_deletePropertyMode = m_previousMode;
424         }
425
426     private:
427         VM& m_vm;
428         DeletePropertyMode m_previousMode;
429     };
430
431 #if ENABLE(JIT)
432     bool canUseJIT() { return m_canUseJIT; }
433 #else
434     bool canUseJIT() { return false; } // interpreter only
435 #endif
436
437 #if ENABLE(YARR_JIT)
438     bool canUseRegExpJIT() { return m_canUseRegExpJIT; }
439 #else
440     bool canUseRegExpJIT() { return false; } // interpreter only
441 #endif
442
443     SourceProviderCache* addSourceProviderCache(SourceProvider*);
444     void clearSourceProviderCaches();
445
446     PrototypeMap prototypeMap;
447
448     typedef HashMap<RefPtr<SourceProvider>, RefPtr<SourceProviderCache>> SourceProviderCacheMap;
449     SourceProviderCacheMap sourceProviderCacheMap;
450     Interpreter* interpreter;
451 #if ENABLE(JIT)
452     std::unique_ptr<JITThunks> jitStubs;
453     MacroAssemblerCodeRef getCTIStub(ThunkGenerator generator)
454     {
455         return jitStubs->ctiStub(this, generator);
456     }
457     
458     static RegisterAtOffsetList* getAllCalleeSaveRegisterOffsets();
459
460 #endif // ENABLE(JIT)
461     std::unique_ptr<CommonSlowPaths::ArityCheckData> arityCheckData;
462 #if ENABLE(FTL_JIT)
463     std::unique_ptr<FTL::Thunks> ftlThunks;
464 #endif
465     NativeExecutable* getHostFunction(NativeFunction, NativeFunction constructor, const String& name);
466     NativeExecutable* getHostFunction(NativeFunction, Intrinsic, NativeFunction constructor, const DOMJIT::Signature*, const String& name);
467
468     static ptrdiff_t exceptionOffset()
469     {
470         return OBJECT_OFFSETOF(VM, m_exception);
471     }
472
473     static ptrdiff_t callFrameForCatchOffset()
474     {
475         return OBJECT_OFFSETOF(VM, callFrameForCatch);
476     }
477
478     static ptrdiff_t targetMachinePCForThrowOffset()
479     {
480         return OBJECT_OFFSETOF(VM, targetMachinePCForThrow);
481     }
482
483     static ptrdiff_t topVMEntryFrameOffset()
484     {
485         return OBJECT_OFFSETOF(VM, topVMEntryFrame);
486     }
487
488     void restorePreviousException(Exception* exception) { setException(exception); }
489
490     void clearLastException() { m_lastException = nullptr; }
491
492     ExecState** addressOfCallFrameForCatch() { return &callFrameForCatch; }
493
494     JSCell** addressOfException() { return reinterpret_cast<JSCell**>(&m_exception); }
495
496     Exception* lastException() const { return m_lastException; }
497     JSCell** addressOfLastException() { return reinterpret_cast<JSCell**>(&m_lastException); }
498
499     void setFailNextNewCodeBlock() { m_failNextNewCodeBlock = true; }
500     bool getAndClearFailNextNewCodeBlock()
501     {
502         bool result = m_failNextNewCodeBlock;
503         m_failNextNewCodeBlock = false;
504         return result;
505     }
506     
507     ALWAYS_INLINE Structure* getStructure(StructureID id)
508     {
509         return heap.structureIDTable().get(decontaminate(id));
510     }
511     
512     void* stackPointerAtVMEntry() const { return m_stackPointerAtVMEntry; }
513     void setStackPointerAtVMEntry(void*);
514
515     size_t softReservedZoneSize() const { return m_currentSoftReservedZoneSize; }
516     size_t updateSoftReservedZoneSize(size_t softReservedZoneSize);
517     
518     static size_t committedStackByteCount();
519     inline bool ensureStackCapacityFor(Register* newTopOfStack);
520
521     void* stackLimit() { return m_stackLimit; }
522     void* softStackLimit() { return m_softStackLimit; }
523     void** addressOfSoftStackLimit() { return &m_softStackLimit; }
524 #if !ENABLE(JIT)
525     void* cloopStackLimit() { return m_cloopStackLimit; }
526     void setCLoopStackLimit(void* limit) { m_cloopStackLimit = limit; }
527 #endif
528
529     inline bool isSafeToRecurseSoft() const;
530     bool isSafeToRecurse() const
531     {
532         return isSafeToRecurse(m_stackLimit);
533     }
534
535     void* lastStackTop() { return m_lastStackTop; }
536     void setLastStackTop(void*);
537
538     const ClassInfo* const jsArrayClassInfo;
539     const ClassInfo* const jsFinalObjectClassInfo;
540
541     JSValue hostCallReturnValue;
542     unsigned varargsLength;
543     ExecState* newCallFrameReturnValue;
544     ExecState* callFrameForCatch;
545     void* targetMachinePCForThrow;
546     Instruction* targetInterpreterPCForThrow;
547     uint32_t osrExitIndex;
548     void* osrExitJumpDestination;
549     Vector<ScratchBuffer*> scratchBuffers;
550     size_t sizeOfLastScratchBuffer;
551
552     bool isExecutingInRegExpJIT { false };
553
554     ScratchBuffer* scratchBufferForSize(size_t size)
555     {
556         if (!size)
557             return 0;
558
559         if (size > sizeOfLastScratchBuffer) {
560             // Protect against a N^2 memory usage pathology by ensuring
561             // that at worst, we get a geometric series, meaning that the
562             // total memory usage is somewhere around
563             // max(scratch buffer size) * 4.
564             sizeOfLastScratchBuffer = size * 2;
565
566             ScratchBuffer* newBuffer = ScratchBuffer::create(sizeOfLastScratchBuffer);
567             RELEASE_ASSERT(newBuffer);
568             scratchBuffers.append(newBuffer);
569         }
570
571         ScratchBuffer* result = scratchBuffers.last();
572         result->setActiveLength(0);
573         return result;
574     }
575
576     EncodedJSValue* exceptionFuzzingBuffer(size_t size)
577     {
578         ASSERT(Options::useExceptionFuzz());
579         if (!m_exceptionFuzzBuffer)
580             m_exceptionFuzzBuffer = MallocPtr<EncodedJSValue>::malloc(size);
581         return m_exceptionFuzzBuffer.get();
582     }
583
584     void gatherConservativeRoots(ConservativeRoots&);
585
586     VMEntryScope* entryScope;
587
588     JSObject* stringRecursionCheckFirstObject { nullptr };
589     HashSet<JSObject*> stringRecursionCheckVisitedObjects;
590
591     LocalTimeOffsetCache localTimeOffsetCache;
592
593     String cachedDateString;
594     double cachedDateStringValue;
595
596     std::unique_ptr<Profiler::Database> m_perBytecodeProfiler;
597     RefPtr<TypedArrayController> m_typedArrayController;
598     RegExpCache* m_regExpCache;
599     BumpPointerAllocator m_regExpAllocator;
600     ConcurrentJSLock m_regExpAllocatorLock;
601
602     std::unique_ptr<HasOwnPropertyCache> m_hasOwnPropertyCache;
603     ALWAYS_INLINE HasOwnPropertyCache* hasOwnPropertyCache() { return m_hasOwnPropertyCache.get(); }
604     HasOwnPropertyCache* ensureHasOwnPropertyCache();
605
606 #if ENABLE(REGEXP_TRACING)
607     typedef ListHashSet<RegExp*> RTTraceList;
608     RTTraceList* m_rtTraceList;
609 #endif
610
611     JS_EXPORT_PRIVATE void resetDateCache();
612
613     RegExpCache* regExpCache() { return m_regExpCache; }
614 #if ENABLE(REGEXP_TRACING)
615     void addRegExpToTrace(RegExp*);
616 #endif
617     JS_EXPORT_PRIVATE void dumpRegExpTrace();
618
619     bool isCollectorBusyOnCurrentThread() { return heap.isCurrentThreadBusy(); }
620
621 #if ENABLE(GC_VALIDATION)
622     bool isInitializingObject() const; 
623     void setInitializingObjectClass(const ClassInfo*);
624 #endif
625
626     bool currentThreadIsHoldingAPILock() const { return m_apiLock->currentThreadIsHoldingLock(); }
627
628     JSLock& apiLock() { return *m_apiLock; }
629     CodeCache* codeCache() { return m_codeCache.get(); }
630
631     JS_EXPORT_PRIVATE void whenIdle(std::function<void()>);
632
633     JS_EXPORT_PRIVATE void deleteAllCode(DeleteAllCodeEffort);
634     JS_EXPORT_PRIVATE void deleteAllLinkedCode(DeleteAllCodeEffort);
635
636     WatchpointSet* ensureWatchpointSetForImpureProperty(const Identifier&);
637     void registerWatchpointForImpureProperty(const Identifier&, Watchpoint*);
638     
639     // FIXME: Use AtomicString once it got merged with Identifier.
640     JS_EXPORT_PRIVATE void addImpureProperty(const String&);
641
642     BuiltinExecutables* builtinExecutables() { return m_builtinExecutables.get(); }
643
644     bool enableTypeProfiler();
645     bool disableTypeProfiler();
646     TypeProfilerLog* typeProfilerLog() { return m_typeProfilerLog.get(); }
647     TypeProfiler* typeProfiler() { return m_typeProfiler.get(); }
648     JS_EXPORT_PRIVATE void dumpTypeProfilerData();
649
650     FunctionHasExecutedCache* functionHasExecutedCache() { return &m_functionHasExecutedCache; }
651
652     ControlFlowProfiler* controlFlowProfiler() { return m_controlFlowProfiler.get(); }
653     bool enableControlFlowProfiler();
654     bool disableControlFlowProfiler();
655
656     JS_EXPORT_PRIVATE void queueMicrotask(JSGlobalObject*, Ref<Microtask>&&);
657     JS_EXPORT_PRIVATE void drainMicrotasks();
658     void setGlobalConstRedeclarationShouldThrow(bool globalConstRedeclarationThrow) { m_globalConstRedeclarationShouldThrow = globalConstRedeclarationThrow; }
659     ALWAYS_INLINE bool globalConstRedeclarationShouldThrow() const { return m_globalConstRedeclarationShouldThrow; }
660
661     void setShouldBuildPCToCodeOriginMapping() { m_shouldBuildPCToCodeOriginMapping = true; }
662     bool shouldBuilderPCToCodeOriginMapping() const { return m_shouldBuildPCToCodeOriginMapping; }
663
664     BytecodeIntrinsicRegistry& bytecodeIntrinsicRegistry() { return *m_bytecodeIntrinsicRegistry; }
665     
666     ShadowChicken& shadowChicken() { return *m_shadowChicken; }
667     
668     template<typename Func>
669     void logEvent(CodeBlock*, const char* summary, const Func& func);
670
671     std::optional<RefPtr<Thread>> ownerThread() const { return m_apiLock->ownerThread(); }
672
673     VMTraps& traps() { return m_traps; }
674
675     void handleTraps(ExecState* exec, VMTraps::Mask mask = VMTraps::Mask::allEventTypes()) { m_traps.handleTraps(exec, mask); }
676
677     bool needTrapHandling() { return m_traps.needTrapHandling(); }
678     bool needTrapHandling(VMTraps::Mask mask) { return m_traps.needTrapHandling(mask); }
679     void* needTrapHandlingAddress() { return m_traps.needTrapHandlingAddress(); }
680
681     void notifyNeedDebuggerBreak() { m_traps.fireTrap(VMTraps::NeedDebuggerBreak); }
682     void notifyNeedTermination() { m_traps.fireTrap(VMTraps::NeedTermination); }
683     void notifyNeedWatchdogCheck() { m_traps.fireTrap(VMTraps::NeedWatchdogCheck); }
684
685 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
686     StackTrace* nativeStackTraceOfLastThrow() const { return m_nativeStackTraceOfLastThrow.get(); }
687 #endif
688
689 private:
690     friend class LLIntOffsetsExtractor;
691
692     VM(VMType, HeapType);
693     static VM*& sharedInstanceInternal();
694     void createNativeThunk();
695
696     void updateStackLimits();
697
698     bool isSafeToRecurse(void* stackLimit) const
699     {
700         ASSERT(wtfThreadData().stack().isGrowingDownward());
701         void* curr = reinterpret_cast<void*>(&curr);
702         return curr >= stackLimit;
703     }
704
705     void setException(Exception* exception)
706     {
707         m_exception = exception;
708         m_lastException = exception;
709     }
710     Exception* exception() const
711     {
712 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
713         m_needExceptionCheck = false;
714 #endif
715         return m_exception;
716     }
717     void clearException()
718     {
719 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
720         m_needExceptionCheck = false;
721         m_nativeStackTraceOfLastThrow = nullptr;
722 #endif
723         m_exception = nullptr;
724     }
725
726 #if !ENABLE(JIT)    
727     bool ensureStackCapacityForCLoop(Register* newTopOfStack);
728     bool isSafeToRecurseSoftCLoop() const;
729 #endif // !ENABLE(JIT)
730
731     JS_EXPORT_PRIVATE void throwException(ExecState*, Exception*);
732     JS_EXPORT_PRIVATE JSValue throwException(ExecState*, JSValue);
733     JS_EXPORT_PRIVATE JSObject* throwException(ExecState*, JSObject*);
734
735 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
736     void verifyExceptionCheckNeedIsSatisfied(unsigned depth, ExceptionEventLocation&);
737 #endif
738
739 #if ENABLE(ASSEMBLER)
740     bool m_canUseAssembler;
741 #endif
742 #if ENABLE(JIT)
743     bool m_canUseJIT;
744 #endif
745 #if ENABLE(YARR_JIT)
746     bool m_canUseRegExpJIT;
747 #endif
748 #if ENABLE(GC_VALIDATION)
749     const ClassInfo* m_initializingObjectClass;
750 #endif
751
752     void* m_stackPointerAtVMEntry;
753     size_t m_currentSoftReservedZoneSize;
754     void* m_stackLimit { nullptr };
755     void* m_softStackLimit { nullptr };
756 #if !ENABLE(JIT)
757     void* m_cloopStackLimit { nullptr };
758 #endif
759     void* m_lastStackTop;
760
761     Exception* m_exception { nullptr };
762     Exception* m_lastException { nullptr };
763 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
764     ExceptionScope* m_topExceptionScope { nullptr };
765     ExceptionEventLocation m_simulatedThrowPointLocation;
766     unsigned m_simulatedThrowPointRecursionDepth { 0 };
767     mutable bool m_needExceptionCheck { false };
768     std::unique_ptr<StackTrace> m_nativeStackTraceOfLastThrow;
769 #endif
770
771     bool m_failNextNewCodeBlock { false };
772     DeletePropertyMode m_deletePropertyMode { DeletePropertyMode::Default };
773     bool m_globalConstRedeclarationShouldThrow { true };
774     bool m_shouldBuildPCToCodeOriginMapping { false };
775     std::unique_ptr<CodeCache> m_codeCache;
776     std::unique_ptr<BuiltinExecutables> m_builtinExecutables;
777     HashMap<String, RefPtr<WatchpointSet>> m_impurePropertyWatchpointSets;
778     std::unique_ptr<TypeProfiler> m_typeProfiler;
779     std::unique_ptr<TypeProfilerLog> m_typeProfilerLog;
780     unsigned m_typeProfilerEnabledCount;
781     FunctionHasExecutedCache m_functionHasExecutedCache;
782     std::unique_ptr<ControlFlowProfiler> m_controlFlowProfiler;
783     unsigned m_controlFlowProfilerEnabledCount;
784     Deque<std::unique_ptr<QueuedTask>> m_microtaskQueue;
785     MallocPtr<EncodedJSValue> m_exceptionFuzzBuffer;
786     VMTraps m_traps;
787     RefPtr<Watchdog> m_watchdog;
788     std::unique_ptr<HeapProfiler> m_heapProfiler;
789 #if ENABLE(SAMPLING_PROFILER)
790     RefPtr<SamplingProfiler> m_samplingProfiler;
791 #endif
792     std::unique_ptr<ShadowChicken> m_shadowChicken;
793     std::unique_ptr<BytecodeIntrinsicRegistry> m_bytecodeIntrinsicRegistry;
794
795     VM* m_prev; // Required by DoublyLinkedListNode.
796     VM* m_next; // Required by DoublyLinkedListNode.
797
798     // Friends for exception checking purpose only.
799     friend class Heap;
800     friend class CatchScope;
801     friend class ExceptionScope;
802     friend class ThrowScope;
803     friend class VMTraps;
804     friend class WTF::DoublyLinkedListNode<VM>;
805 };
806
807 #if ENABLE(GC_VALIDATION)
808 inline bool VM::isInitializingObject() const
809 {
810     return !!m_initializingObjectClass;
811 }
812
813 inline void VM::setInitializingObjectClass(const ClassInfo* initializingObjectClass)
814 {
815     m_initializingObjectClass = initializingObjectClass;
816 }
817 #endif
818
819 inline Heap* WeakSet::heap() const
820 {
821     return &m_vm->heap;
822 }
823
824 #if ENABLE(JIT)
825 extern "C" void sanitizeStackForVMImpl(VM*);
826 #endif
827
828 void sanitizeStackForVM(VM*);
829 void logSanitizeStack(VM*);
830
831 } // namespace JSC