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