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