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