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