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