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
384#define DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(name) \
385 template<SubspaceAccess mode> \
386 IsoSubspace* name() \
387 { \
388 if (m_##name || mode == SubspaceAccess::Concurrently) \
389 return m_##name.get(); \
390 return name##Slow(); \
391 } \
392 IsoSubspace* name##Slow(); \
393 std::unique_ptr<IsoSubspace> m_##name;
394
395
396#if JSC_OBJC_API_ENABLED
397 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(objCCallbackFunctionSpace)
398#endif
399 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(boundFunctionSpace)
400 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(callbackFunctionSpace)
401 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(customGetterSetterFunctionSpace)
402 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(errorInstanceSpace)
403 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(nativeStdFunctionSpace)
404 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(proxyRevokeSpace)
405 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(weakSetSpace)
406 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(weakMapSpace)
407#if ENABLE(WEBASSEMBLY)
408 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(webAssemblyCodeBlockSpace)
409 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(webAssemblyFunctionSpace)
410 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(webAssemblyWrapperFunctionSpace)
411#endif
412
413#undef DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER
414
415 IsoCellSet executableToCodeBlockEdgesWithConstraints;
416 IsoCellSet executableToCodeBlockEdgesWithFinalizers;
417
418#define DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER(name) \
419 template<SubspaceAccess mode> \
420 IsoSubspace* name() \
421 { \
422 if (auto* spaceAndSet = m_##name.get()) \
423 return &spaceAndSet->space; \
424 if (mode == SubspaceAccess::Concurrently) \
425 return nullptr; \
426 return name##Slow(); \
427 } \
428 IsoSubspace* name##Slow(); \
429 std::unique_ptr<SpaceAndSet> m_##name;
430
431 struct SpaceAndSet {
432 WTF_MAKE_STRUCT_FAST_ALLOCATED;
433
434 IsoSubspace space;
435 IsoCellSet set;
436
437 template<typename... Arguments>
438 SpaceAndSet(Arguments&&... arguments)
439 : space(std::forward<Arguments>(arguments)...)
440 , set(space)
441 {
442 }
443
444 static IsoCellSet& setFor(Subspace& space)
445 {
446 return *bitwise_cast<IsoCellSet*>(
447 bitwise_cast<char*>(&space) -
448 OBJECT_OFFSETOF(SpaceAndSet, space) +
449 OBJECT_OFFSETOF(SpaceAndSet, set));
450 }
451 };
452
453 SpaceAndSet codeBlockSpace;
454 DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER(inferredValueSpace)
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> inferredValueStructure;
531 Strong<Structure> functionRareDataStructure;
532 Strong<Structure> exceptionStructure;
533 Strong<Structure> promiseDeferredStructure;
534 Strong<Structure> internalPromiseDeferredStructure;
535 Strong<Structure> nativeStdFunctionCellStructure;
536 Strong<Structure> programCodeBlockStructure;
537 Strong<Structure> moduleProgramCodeBlockStructure;
538 Strong<Structure> evalCodeBlockStructure;
539 Strong<Structure> functionCodeBlockStructure;
540 Strong<Structure> hashMapBucketSetStructure;
541 Strong<Structure> hashMapBucketMapStructure;
542 Strong<Structure> bigIntStructure;
543 Strong<Structure> executableToCodeBlockEdgeStructure;
544
545 Strong<Structure> m_setIteratorStructure;
546 Strong<Structure> m_mapIteratorStructure;
547
548 Strong<JSCell> emptyPropertyNameEnumerator;
549
550 Strong<JSCell> m_sentinelSetBucket;
551 Strong<JSCell> m_sentinelMapBucket;
552
553 std::unique_ptr<PromiseDeferredTimer> promiseDeferredTimer;
554
555 JSCell* currentlyDestructingCallbackObject;
556 const ClassInfo* currentlyDestructingCallbackObjectClassInfo { nullptr };
557
558 AtomicStringTable* m_atomicStringTable;
559 WTF::SymbolRegistry m_symbolRegistry;
560 CommonIdentifiers* propertyNames;
561 const ArgList* emptyList;
562 SmallStrings smallStrings;
563 NumericStrings numericStrings;
564 DateInstanceCache dateInstanceCache;
565 std::unique_ptr<SimpleStats> machineCodeBytesPerBytecodeWordForBaselineJIT;
566 WeakGCMap<std::pair<CustomGetterSetter*, int>, JSCustomGetterSetterFunction> customGetterSetterFunctionMap;
567 WeakGCMap<StringImpl*, JSString, PtrHash<StringImpl*>> stringCache;
568 Strong<JSString> lastCachedString;
569
570 AtomicStringTable* atomicStringTable() const { return m_atomicStringTable; }
571 WTF::SymbolRegistry& symbolRegistry() { return m_symbolRegistry; }
572
573 Structure* setIteratorStructure()
574 {
575 if (LIKELY(m_setIteratorStructure))
576 return m_setIteratorStructure.get();
577 return setIteratorStructureSlow();
578 }
579
580 Structure* mapIteratorStructure()
581 {
582 if (LIKELY(m_mapIteratorStructure))
583 return m_mapIteratorStructure.get();
584 return mapIteratorStructureSlow();
585 }
586
587 JSCell* sentinelSetBucket()
588 {
589 if (LIKELY(m_sentinelSetBucket))
590 return m_sentinelSetBucket.get();
591 return sentinelSetBucketSlow();
592 }
593
594 JSCell* sentinelMapBucket()
595 {
596 if (LIKELY(m_sentinelMapBucket))
597 return m_sentinelMapBucket.get();
598 return sentinelMapBucketSlow();
599 }
600
601 WeakGCMap<SymbolImpl*, Symbol, PtrHash<SymbolImpl*>> symbolImplToSymbolMap;
602
603 enum class DeletePropertyMode {
604 // Default behaviour of deleteProperty, matching the spec.
605 Default,
606 // This setting causes deleteProperty to force deletion of all
607 // properties including those that are non-configurable (DontDelete).
608 IgnoreConfigurable
609 };
610
611 DeletePropertyMode deletePropertyMode()
612 {
613 return m_deletePropertyMode;
614 }
615
616 class DeletePropertyModeScope {
617 public:
618 DeletePropertyModeScope(VM& vm, DeletePropertyMode mode)
619 : m_vm(vm)
620 , m_previousMode(vm.m_deletePropertyMode)
621 {
622 m_vm.m_deletePropertyMode = mode;
623 }
624
625 ~DeletePropertyModeScope()
626 {
627 m_vm.m_deletePropertyMode = m_previousMode;
628 }
629
630 private:
631 VM& m_vm;
632 DeletePropertyMode m_previousMode;
633 };
634
635 static JS_EXPORT_PRIVATE bool canUseAssembler();
636 static JS_EXPORT_PRIVATE bool isInMiniMode();
637
638 static void computeCanUseJIT();
639 ALWAYS_INLINE static bool canUseJIT()
640 {
641#if ENABLE(JIT)
642#if !ASSERT_DISABLED
643 RELEASE_ASSERT(s_canUseJITIsSet);
644#endif
645 return s_canUseJIT;
646#else
647 return false;
648#endif
649 }
650
651 SourceProviderCache* addSourceProviderCache(SourceProvider*);
652 void clearSourceProviderCaches();
653
654 StructureCache structureCache;
655
656 typedef HashMap<RefPtr<SourceProvider>, RefPtr<SourceProviderCache>> SourceProviderCacheMap;
657 SourceProviderCacheMap sourceProviderCacheMap;
658 Interpreter* interpreter;
659#if ENABLE(JIT)
660 std::unique_ptr<JITThunks> jitStubs;
661 MacroAssemblerCodeRef<JITThunkPtrTag> getCTIStub(ThunkGenerator generator)
662 {
663 return jitStubs->ctiStub(this, generator);
664 }
665
666#endif // ENABLE(JIT)
667#if ENABLE(FTL_JIT)
668 std::unique_ptr<FTL::Thunks> ftlThunks;
669#endif
670 NativeExecutable* getHostFunction(NativeFunction, NativeFunction constructor, const String& name);
671 NativeExecutable* getHostFunction(NativeFunction, Intrinsic, NativeFunction constructor, const DOMJIT::Signature*, const String& name);
672
673 MacroAssemblerCodePtr<JSEntryPtrTag> getCTIInternalFunctionTrampolineFor(CodeSpecializationKind);
674
675 static ptrdiff_t exceptionOffset()
676 {
677 return OBJECT_OFFSETOF(VM, m_exception);
678 }
679
680 static ptrdiff_t callFrameForCatchOffset()
681 {
682 return OBJECT_OFFSETOF(VM, callFrameForCatch);
683 }
684
685 static ptrdiff_t topEntryFrameOffset()
686 {
687 return OBJECT_OFFSETOF(VM, topEntryFrame);
688 }
689
690 void restorePreviousException(Exception* exception) { setException(exception); }
691
692 void clearLastException() { m_lastException = nullptr; }
693
694 ExecState** addressOfCallFrameForCatch() { return &callFrameForCatch; }
695
696 JSCell** addressOfException() { return reinterpret_cast<JSCell**>(&m_exception); }
697
698 Exception* lastException() const { return m_lastException; }
699 JSCell** addressOfLastException() { return reinterpret_cast<JSCell**>(&m_lastException); }
700
701 // This should only be used for test or assertion code that wants to inspect
702 // the pending exception without interfering with Throw/CatchScopes.
703 Exception* exceptionForInspection() const { return m_exception; }
704
705 void setFailNextNewCodeBlock() { m_failNextNewCodeBlock = true; }
706 bool getAndClearFailNextNewCodeBlock()
707 {
708 bool result = m_failNextNewCodeBlock;
709 m_failNextNewCodeBlock = false;
710 return result;
711 }
712
713 ALWAYS_INLINE Structure* getStructure(StructureID id)
714 {
715 return heap.structureIDTable().get(decontaminate(id));
716 }
717
718 void* stackPointerAtVMEntry() const { return m_stackPointerAtVMEntry; }
719 void setStackPointerAtVMEntry(void*);
720
721 size_t softReservedZoneSize() const { return m_currentSoftReservedZoneSize; }
722 size_t updateSoftReservedZoneSize(size_t softReservedZoneSize);
723
724 static size_t committedStackByteCount();
725 inline bool ensureStackCapacityFor(Register* newTopOfStack);
726
727 void* stackLimit() { return m_stackLimit; }
728 void* softStackLimit() { return m_softStackLimit; }
729 void** addressOfSoftStackLimit() { return &m_softStackLimit; }
730#if ENABLE(C_LOOP)
731 void* cloopStackLimit() { return m_cloopStackLimit; }
732 void setCLoopStackLimit(void* limit) { m_cloopStackLimit = limit; }
733#endif
734
735 inline bool isSafeToRecurseSoft() const;
736 bool isSafeToRecurse() const
737 {
738 return isSafeToRecurse(m_stackLimit);
739 }
740
741 void** addressOfLastStackTop() { return &m_lastStackTop; }
742 void* lastStackTop() { return m_lastStackTop; }
743 void setLastStackTop(void*);
744
745 void firePrimitiveGigacageEnabledIfNecessary()
746 {
747 if (m_needToFirePrimitiveGigacageEnabled) {
748 m_needToFirePrimitiveGigacageEnabled = false;
749 m_primitiveGigacageEnabled.fireAll(*this, "Primitive gigacage disabled asynchronously");
750 }
751 }
752
753 JSValue hostCallReturnValue;
754 unsigned varargsLength;
755 ExecState* newCallFrameReturnValue;
756 ExecState* callFrameForCatch;
757 void* targetMachinePCForThrow;
758 const Instruction* targetInterpreterPCForThrow;
759 uint32_t osrExitIndex;
760 void* osrExitJumpDestination;
761 bool isExecutingInRegExpJIT { false };
762
763 // The threading protocol here is as follows:
764 // - You can call scratchBufferForSize from any thread.
765 // - You can only set the ScratchBuffer's activeLength from the main thread.
766 // - You can only write to entries in the ScratchBuffer from the main thread.
767 ScratchBuffer* scratchBufferForSize(size_t size);
768 void clearScratchBuffers();
769
770 EncodedJSValue* exceptionFuzzingBuffer(size_t size)
771 {
772 ASSERT(Options::useExceptionFuzz());
773 if (!m_exceptionFuzzBuffer)
774 m_exceptionFuzzBuffer = MallocPtr<EncodedJSValue>::malloc(size);
775 return m_exceptionFuzzBuffer.get();
776 }
777
778 void gatherScratchBufferRoots(ConservativeRoots&);
779
780 VMEntryScope* entryScope;
781
782 JSObject* stringRecursionCheckFirstObject { nullptr };
783 HashSet<JSObject*> stringRecursionCheckVisitedObjects;
784
785 LocalTimeOffsetCache localTimeOffsetCache;
786
787 String cachedDateString;
788 double cachedDateStringValue;
789
790 std::unique_ptr<Profiler::Database> m_perBytecodeProfiler;
791 RefPtr<TypedArrayController> m_typedArrayController;
792 RegExpCache* m_regExpCache;
793 BumpPointerAllocator m_regExpAllocator;
794 ConcurrentJSLock m_regExpAllocatorLock;
795
796#if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
797 static constexpr size_t patternContextBufferSize = 8192; // Space allocated to save nested parenthesis context
798 UniqueArray<char> m_regExpPatternContexBuffer;
799 Lock m_regExpPatternContextLock;
800 char* acquireRegExpPatternContexBuffer();
801 void releaseRegExpPatternContexBuffer();
802#endif
803
804 Ref<CompactVariableMap> m_compactVariableMap;
805
806 std::unique_ptr<HasOwnPropertyCache> m_hasOwnPropertyCache;
807 ALWAYS_INLINE HasOwnPropertyCache* hasOwnPropertyCache() { return m_hasOwnPropertyCache.get(); }
808 HasOwnPropertyCache* ensureHasOwnPropertyCache();
809
810#if ENABLE(REGEXP_TRACING)
811 typedef ListHashSet<RegExp*> RTTraceList;
812 RTTraceList* m_rtTraceList;
813#endif
814
815#if JSC_OBJC_API_ENABLED
816 void* m_apiWrapper { nullptr };
817#endif
818
819 JS_EXPORT_PRIVATE void resetDateCache();
820
821 RegExpCache* regExpCache() { return m_regExpCache; }
822#if ENABLE(REGEXP_TRACING)
823 void addRegExpToTrace(RegExp*);
824#endif
825 JS_EXPORT_PRIVATE void dumpRegExpTrace();
826
827 bool isCollectorBusyOnCurrentThread() { return heap.isCurrentThreadBusy(); }
828
829#if ENABLE(GC_VALIDATION)
830 bool isInitializingObject() const;
831 void setInitializingObjectClass(const ClassInfo*);
832#endif
833
834 bool currentThreadIsHoldingAPILock() const { return m_apiLock->currentThreadIsHoldingLock(); }
835
836 JSLock& apiLock() { return *m_apiLock; }
837 CodeCache* codeCache() { return m_codeCache.get(); }
838
839 JS_EXPORT_PRIVATE void whenIdle(Function<void()>&&);
840
841 JS_EXPORT_PRIVATE void deleteAllCode(DeleteAllCodeEffort);
842 JS_EXPORT_PRIVATE void deleteAllLinkedCode(DeleteAllCodeEffort);
843
844 void shrinkFootprintWhenIdle();
845
846 WatchpointSet* ensureWatchpointSetForImpureProperty(const Identifier&);
847 void registerWatchpointForImpureProperty(const Identifier&, Watchpoint*);
848
849 // FIXME: Use AtomicString once it got merged with Identifier.
850 JS_EXPORT_PRIVATE void addImpureProperty(const String&);
851
852 InlineWatchpointSet& primitiveGigacageEnabled() { return m_primitiveGigacageEnabled; }
853
854 BuiltinExecutables* builtinExecutables() { return m_builtinExecutables.get(); }
855
856 bool enableTypeProfiler();
857 bool disableTypeProfiler();
858 TypeProfilerLog* typeProfilerLog() { return m_typeProfilerLog.get(); }
859 TypeProfiler* typeProfiler() { return m_typeProfiler.get(); }
860 JS_EXPORT_PRIVATE void dumpTypeProfilerData();
861
862 FunctionHasExecutedCache* functionHasExecutedCache() { return &m_functionHasExecutedCache; }
863
864 ControlFlowProfiler* controlFlowProfiler() { return m_controlFlowProfiler.get(); }
865 bool enableControlFlowProfiler();
866 bool disableControlFlowProfiler();
867
868 void queueMicrotask(JSGlobalObject&, Ref<Microtask>&&);
869 JS_EXPORT_PRIVATE void drainMicrotasks();
870 ALWAYS_INLINE void setOnEachMicrotaskTick(WTF::Function<void(VM&)>&& func) { m_onEachMicrotaskTick = WTFMove(func); }
871 void setGlobalConstRedeclarationShouldThrow(bool globalConstRedeclarationThrow) { m_globalConstRedeclarationShouldThrow = globalConstRedeclarationThrow; }
872 ALWAYS_INLINE bool globalConstRedeclarationShouldThrow() const { return m_globalConstRedeclarationShouldThrow; }
873
874 void setShouldBuildPCToCodeOriginMapping() { m_shouldBuildPCToCodeOriginMapping = true; }
875 bool shouldBuilderPCToCodeOriginMapping() const { return m_shouldBuildPCToCodeOriginMapping; }
876
877 BytecodeIntrinsicRegistry& bytecodeIntrinsicRegistry() { return *m_bytecodeIntrinsicRegistry; }
878
879 ShadowChicken* shadowChicken() { return m_shadowChicken.get(); }
880 void ensureShadowChicken();
881
882 template<typename Func>
883 void logEvent(CodeBlock*, const char* summary, const Func& func);
884
885 Optional<RefPtr<Thread>> ownerThread() const { return m_apiLock->ownerThread(); }
886
887 VMTraps& traps() { return m_traps; }
888
889 void handleTraps(ExecState* exec, VMTraps::Mask mask = VMTraps::Mask::allEventTypes()) { m_traps.handleTraps(exec, mask); }
890
891 bool needTrapHandling() { return m_traps.needTrapHandling(); }
892 bool needTrapHandling(VMTraps::Mask mask) { return m_traps.needTrapHandling(mask); }
893 void* needTrapHandlingAddress() { return m_traps.needTrapHandlingAddress(); }
894
895 void notifyNeedDebuggerBreak() { m_traps.fireTrap(VMTraps::NeedDebuggerBreak); }
896 void notifyNeedTermination() { m_traps.fireTrap(VMTraps::NeedTermination); }
897 void notifyNeedWatchdogCheck() { m_traps.fireTrap(VMTraps::NeedWatchdogCheck); }
898
899#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
900 StackTrace* nativeStackTraceOfLastThrow() const { return m_nativeStackTraceOfLastThrow.get(); }
901 Thread* throwingThread() const { return m_throwingThread.get(); }
902 bool needExceptionCheck() const { return m_needExceptionCheck; }
903#endif
904
905#if USE(CF)
906 CFRunLoopRef runLoop() const { return m_runLoop.get(); }
907 JS_EXPORT_PRIVATE void setRunLoop(CFRunLoopRef);
908#endif // USE(CF)
909
910 static void setCrashOnVMCreation(bool);
911
912 class DeferExceptionScope {
913 public:
914 DeferExceptionScope(VM& vm)
915 : m_savedException(vm.m_exception, nullptr)
916 , m_savedLastException(vm.m_lastException, nullptr)
917 {
918 }
919
920 private:
921 SetForScope<Exception*> m_savedException;
922 SetForScope<Exception*> m_savedLastException;
923 };
924
925private:
926 friend class LLIntOffsetsExtractor;
927
928 VM(VMType, HeapType);
929 static VM*& sharedInstanceInternal();
930 void createNativeThunk();
931
932 JS_EXPORT_PRIVATE Structure* setIteratorStructureSlow();
933 JS_EXPORT_PRIVATE Structure* mapIteratorStructureSlow();
934 JSCell* sentinelSetBucketSlow();
935 JSCell* sentinelMapBucketSlow();
936
937 void updateStackLimits();
938
939 bool isSafeToRecurse(void* stackLimit) const
940 {
941 ASSERT(Thread::current().stack().isGrowingDownward());
942 void* curr = currentStackPointer();
943 return curr >= stackLimit;
944 }
945
946 void setException(Exception* exception)
947 {
948 m_exception = exception;
949 m_lastException = exception;
950 }
951 Exception* exception() const
952 {
953#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
954 m_needExceptionCheck = false;
955#endif
956 return m_exception;
957 }
958 void clearException()
959 {
960#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
961 m_needExceptionCheck = false;
962 m_nativeStackTraceOfLastThrow = nullptr;
963 m_throwingThread = nullptr;
964#endif
965 m_exception = nullptr;
966 }
967
968#if ENABLE(C_LOOP)
969 bool ensureStackCapacityForCLoop(Register* newTopOfStack);
970 bool isSafeToRecurseSoftCLoop() const;
971#endif // ENABLE(C_LOOP)
972
973 JS_EXPORT_PRIVATE Exception* throwException(ExecState*, Exception*);
974 JS_EXPORT_PRIVATE Exception* throwException(ExecState*, JSValue);
975 JS_EXPORT_PRIVATE Exception* throwException(ExecState*, JSObject*);
976
977#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
978 void verifyExceptionCheckNeedIsSatisfied(unsigned depth, ExceptionEventLocation&);
979#endif
980
981 static void primitiveGigacageDisabledCallback(void*);
982 void primitiveGigacageDisabled();
983
984#if ENABLE(GC_VALIDATION)
985 const ClassInfo* m_initializingObjectClass;
986#endif
987
988 void* m_stackPointerAtVMEntry;
989 size_t m_currentSoftReservedZoneSize;
990 void* m_stackLimit { nullptr };
991 void* m_softStackLimit { nullptr };
992#if ENABLE(C_LOOP)
993 void* m_cloopStackLimit { nullptr };
994#endif
995 void* m_lastStackTop { nullptr };
996
997 Exception* m_exception { nullptr };
998 Exception* m_lastException { nullptr };
999#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
1000 ExceptionScope* m_topExceptionScope { nullptr };
1001 ExceptionEventLocation m_simulatedThrowPointLocation;
1002 unsigned m_simulatedThrowPointRecursionDepth { 0 };
1003 mutable bool m_needExceptionCheck { false };
1004 std::unique_ptr<StackTrace> m_nativeStackTraceOfLastThrow;
1005 std::unique_ptr<StackTrace> m_nativeStackTraceOfLastSimulatedThrow;
1006 RefPtr<Thread> m_throwingThread;
1007#endif
1008
1009 bool m_failNextNewCodeBlock { false };
1010 DeletePropertyMode m_deletePropertyMode { DeletePropertyMode::Default };
1011 bool m_globalConstRedeclarationShouldThrow { true };
1012 bool m_shouldBuildPCToCodeOriginMapping { false };
1013 std::unique_ptr<CodeCache> m_codeCache;
1014 std::unique_ptr<BuiltinExecutables> m_builtinExecutables;
1015 HashMap<String, RefPtr<WatchpointSet>> m_impurePropertyWatchpointSets;
1016 std::unique_ptr<TypeProfiler> m_typeProfiler;
1017 std::unique_ptr<TypeProfilerLog> m_typeProfilerLog;
1018 unsigned m_typeProfilerEnabledCount;
1019 bool m_needToFirePrimitiveGigacageEnabled { false };
1020 Lock m_scratchBufferLock;
1021 Vector<ScratchBuffer*> m_scratchBuffers;
1022 size_t m_sizeOfLastScratchBuffer { 0 };
1023 InlineWatchpointSet m_primitiveGigacageEnabled;
1024 FunctionHasExecutedCache m_functionHasExecutedCache;
1025 std::unique_ptr<ControlFlowProfiler> m_controlFlowProfiler;
1026 unsigned m_controlFlowProfilerEnabledCount;
1027 Deque<std::unique_ptr<QueuedTask>> m_microtaskQueue;
1028 MallocPtr<EncodedJSValue> m_exceptionFuzzBuffer;
1029 VMTraps m_traps;
1030 RefPtr<Watchdog> m_watchdog;
1031 std::unique_ptr<HeapProfiler> m_heapProfiler;
1032#if ENABLE(SAMPLING_PROFILER)
1033 RefPtr<SamplingProfiler> m_samplingProfiler;
1034#endif
1035 std::unique_ptr<FuzzerAgent> m_fuzzerAgent;
1036 std::unique_ptr<ShadowChicken> m_shadowChicken;
1037 std::unique_ptr<BytecodeIntrinsicRegistry> m_bytecodeIntrinsicRegistry;
1038
1039 WTF::Function<void(VM&)> m_onEachMicrotaskTick;
1040
1041#if ENABLE(JIT)
1042#if !ASSERT_DISABLED
1043 JS_EXPORT_PRIVATE static bool s_canUseJITIsSet;
1044#endif
1045 JS_EXPORT_PRIVATE static bool s_canUseJIT;
1046#endif
1047
1048 VM* m_prev; // Required by DoublyLinkedListNode.
1049 VM* m_next; // Required by DoublyLinkedListNode.
1050
1051 // Friends for exception checking purpose only.
1052 friend class Heap;
1053 friend class CatchScope;
1054 friend class ExceptionScope;
1055 friend class ThrowScope;
1056 friend class VMTraps;
1057 friend class WTF::DoublyLinkedListNode<VM>;
1058};
1059
1060#if ENABLE(GC_VALIDATION)
1061inline bool VM::isInitializingObject() const
1062{
1063 return !!m_initializingObjectClass;
1064}
1065
1066inline void VM::setInitializingObjectClass(const ClassInfo* initializingObjectClass)
1067{
1068 m_initializingObjectClass = initializingObjectClass;
1069}
1070#endif
1071
1072inline Heap* WeakSet::heap() const
1073{
1074 return &m_vm->heap;
1075}
1076
1077#if !ENABLE(C_LOOP)
1078extern "C" void sanitizeStackForVMImpl(VM*);
1079#endif
1080
1081JS_EXPORT_PRIVATE void sanitizeStackForVM(VM*);
1082void logSanitizeStack(VM*);
1083
1084} // namespace JSC
1085