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