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(weakObjectRefSpace)
407 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(weakSetSpace)
408 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(weakMapSpace)
409#if ENABLE(WEBASSEMBLY)
410 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(webAssemblyCodeBlockSpace)
411 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(webAssemblyFunctionSpace)
412 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER(webAssemblyWrapperFunctionSpace)
413#endif
414
415#undef DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER
416
417 IsoCellSet executableToCodeBlockEdgesWithConstraints;
418 IsoCellSet executableToCodeBlockEdgesWithFinalizers;
419
420#define DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER(name) \
421 template<SubspaceAccess mode> \
422 IsoSubspace* name() \
423 { \
424 if (auto* spaceAndSet = m_##name.get()) \
425 return &spaceAndSet->space; \
426 if (mode == SubspaceAccess::Concurrently) \
427 return nullptr; \
428 return name##Slow(); \
429 } \
430 IsoSubspace* name##Slow(); \
431 std::unique_ptr<SpaceAndSet> m_##name;
432
433 struct SpaceAndSet {
434 WTF_MAKE_STRUCT_FAST_ALLOCATED;
435
436 IsoSubspace space;
437 IsoCellSet set;
438
439 template<typename... Arguments>
440 SpaceAndSet(Arguments&&... arguments)
441 : space(std::forward<Arguments>(arguments)...)
442 , set(space)
443 {
444 }
445
446 static IsoCellSet& setFor(Subspace& space)
447 {
448 return *bitwise_cast<IsoCellSet*>(
449 bitwise_cast<char*>(&space) -
450 OBJECT_OFFSETOF(SpaceAndSet, space) +
451 OBJECT_OFFSETOF(SpaceAndSet, set));
452 }
453 };
454
455 SpaceAndSet codeBlockSpace;
456
457 template<typename Func>
458 void forEachCodeBlockSpace(const Func& func)
459 {
460 // This should not include webAssemblyCodeBlockSpace because this is about subsclasses of
461 // JSC::CodeBlock.
462 func(codeBlockSpace);
463 }
464
465 DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER(evalExecutableSpace)
466 DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER(moduleProgramExecutableSpace)
467 SpaceAndSet functionExecutableSpace;
468 SpaceAndSet programExecutableSpace;
469
470 template<typename Func>
471 void forEachScriptExecutableSpace(const Func& func)
472 {
473 if (m_evalExecutableSpace)
474 func(*m_evalExecutableSpace);
475 func(functionExecutableSpace);
476 if (m_moduleProgramExecutableSpace)
477 func(*m_moduleProgramExecutableSpace);
478 func(programExecutableSpace);
479 }
480
481 SpaceAndSet unlinkedFunctionExecutableSpace;
482
483#undef DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER
484
485 VMType vmType;
486 ClientData* clientData;
487 EntryFrame* topEntryFrame;
488 // NOTE: When throwing an exception while rolling back the call frame, this may be equal to
489 // topEntryFrame.
490 // FIXME: This should be a void*, because it might not point to a CallFrame.
491 // https://bugs.webkit.org/show_bug.cgi?id=160441
492 ExecState* topCallFrame { nullptr };
493#if ENABLE(WEBASSEMBLY)
494 Wasm::Context wasmContext;
495#endif
496 Strong<Structure> structureStructure;
497 Strong<Structure> structureRareDataStructure;
498 Strong<Structure> terminatedExecutionErrorStructure;
499 Strong<Structure> stringStructure;
500 Strong<Structure> propertyNameEnumeratorStructure;
501 Strong<Structure> customGetterSetterStructure;
502 Strong<Structure> domAttributeGetterSetterStructure;
503 Strong<Structure> scopedArgumentsTableStructure;
504 Strong<Structure> apiWrapperStructure;
505 Strong<Structure> nativeExecutableStructure;
506 Strong<Structure> evalExecutableStructure;
507 Strong<Structure> programExecutableStructure;
508 Strong<Structure> functionExecutableStructure;
509#if ENABLE(WEBASSEMBLY)
510 Strong<Structure> webAssemblyCodeBlockStructure;
511#endif
512 Strong<Structure> moduleProgramExecutableStructure;
513 Strong<Structure> regExpStructure;
514 Strong<Structure> symbolStructure;
515 Strong<Structure> symbolTableStructure;
516 Strong<Structure> fixedArrayStructure;
517 Strong<Structure> immutableButterflyStructures[NumberOfCopyOnWriteIndexingModes];
518 Strong<Structure> sourceCodeStructure;
519 Strong<Structure> scriptFetcherStructure;
520 Strong<Structure> scriptFetchParametersStructure;
521 Strong<Structure> structureChainStructure;
522 Strong<Structure> sparseArrayValueMapStructure;
523 Strong<Structure> templateObjectDescriptorStructure;
524 Strong<Structure> arrayBufferNeuteringWatchpointStructure;
525 Strong<Structure> unlinkedFunctionExecutableStructure;
526 Strong<Structure> unlinkedProgramCodeBlockStructure;
527 Strong<Structure> unlinkedEvalCodeBlockStructure;
528 Strong<Structure> unlinkedFunctionCodeBlockStructure;
529 Strong<Structure> unlinkedModuleProgramCodeBlockStructure;
530 Strong<Structure> propertyTableStructure;
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 AtomStringTable* m_atomStringTable;
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 AtomStringTable* atomStringTable() const { return m_atomStringTable; }
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 bool isInMiniMode()
637 {
638 return !canUseJIT() || Options::forceMiniVMMode();
639 }
640
641 static bool useUnlinkedCodeBlockJettisoning()
642 {
643 return Options::useUnlinkedCodeBlockJettisoning() || isInMiniMode();
644 }
645
646 static void computeCanUseJIT();
647 ALWAYS_INLINE static bool canUseJIT()
648 {
649#if ENABLE(JIT)
650#if !ASSERT_DISABLED
651 RELEASE_ASSERT(s_canUseJITIsSet);
652#endif
653 return s_canUseJIT;
654#else
655 return false;
656#endif
657 }
658
659 SourceProviderCache* addSourceProviderCache(SourceProvider*);
660 void clearSourceProviderCaches();
661
662 StructureCache structureCache;
663
664 typedef HashMap<RefPtr<SourceProvider>, RefPtr<SourceProviderCache>> SourceProviderCacheMap;
665 SourceProviderCacheMap sourceProviderCacheMap;
666 Interpreter* interpreter;
667#if ENABLE(JIT)
668 std::unique_ptr<JITThunks> jitStubs;
669 MacroAssemblerCodeRef<JITThunkPtrTag> getCTIStub(ThunkGenerator generator)
670 {
671 return jitStubs->ctiStub(this, generator);
672 }
673
674#endif // ENABLE(JIT)
675#if ENABLE(FTL_JIT)
676 std::unique_ptr<FTL::Thunks> ftlThunks;
677#endif
678 NativeExecutable* getHostFunction(NativeFunction, NativeFunction constructor, const String& name);
679 NativeExecutable* getHostFunction(NativeFunction, Intrinsic, NativeFunction constructor, const DOMJIT::Signature*, const String& name);
680
681 MacroAssemblerCodePtr<JSEntryPtrTag> getCTIInternalFunctionTrampolineFor(CodeSpecializationKind);
682
683 static ptrdiff_t exceptionOffset()
684 {
685 return OBJECT_OFFSETOF(VM, m_exception);
686 }
687
688 static ptrdiff_t callFrameForCatchOffset()
689 {
690 return OBJECT_OFFSETOF(VM, callFrameForCatch);
691 }
692
693 static ptrdiff_t topEntryFrameOffset()
694 {
695 return OBJECT_OFFSETOF(VM, topEntryFrame);
696 }
697
698 static ptrdiff_t offsetOfHeapBarrierThreshold()
699 {
700 return OBJECT_OFFSETOF(VM, heap) + OBJECT_OFFSETOF(Heap, m_barrierThreshold);
701 }
702
703 static ptrdiff_t offsetOfHeapMutatorShouldBeFenced()
704 {
705 return OBJECT_OFFSETOF(VM, heap) + OBJECT_OFFSETOF(Heap, m_mutatorShouldBeFenced);
706 }
707
708 void restorePreviousException(Exception* exception) { setException(exception); }
709
710 void clearLastException() { m_lastException = nullptr; }
711
712 ExecState** addressOfCallFrameForCatch() { return &callFrameForCatch; }
713
714 JSCell** addressOfException() { return reinterpret_cast<JSCell**>(&m_exception); }
715
716 Exception* lastException() const { return m_lastException; }
717 JSCell** addressOfLastException() { return reinterpret_cast<JSCell**>(&m_lastException); }
718
719 // This should only be used for test or assertion code that wants to inspect
720 // the pending exception without interfering with Throw/CatchScopes.
721 Exception* exceptionForInspection() const { return m_exception; }
722
723 void setFailNextNewCodeBlock() { m_failNextNewCodeBlock = true; }
724 bool getAndClearFailNextNewCodeBlock()
725 {
726 bool result = m_failNextNewCodeBlock;
727 m_failNextNewCodeBlock = false;
728 return result;
729 }
730
731 ALWAYS_INLINE Structure* getStructure(StructureID id)
732 {
733 return heap.structureIDTable().get(decontaminate(id));
734 }
735
736 void* stackPointerAtVMEntry() const { return m_stackPointerAtVMEntry; }
737 void setStackPointerAtVMEntry(void*);
738
739 size_t softReservedZoneSize() const { return m_currentSoftReservedZoneSize; }
740 size_t updateSoftReservedZoneSize(size_t softReservedZoneSize);
741
742 static size_t committedStackByteCount();
743 inline bool ensureStackCapacityFor(Register* newTopOfStack);
744
745 void* stackLimit() { return m_stackLimit; }
746 void* softStackLimit() { return m_softStackLimit; }
747 void** addressOfSoftStackLimit() { return &m_softStackLimit; }
748#if ENABLE(C_LOOP)
749 void* cloopStackLimit() { return m_cloopStackLimit; }
750 void setCLoopStackLimit(void* limit) { m_cloopStackLimit = limit; }
751 JS_EXPORT_PRIVATE void* currentCLoopStackPointer() const;
752#endif
753
754 inline bool isSafeToRecurseSoft() const;
755 bool isSafeToRecurse() const
756 {
757 return isSafeToRecurse(m_stackLimit);
758 }
759
760 void** addressOfLastStackTop() { return &m_lastStackTop; }
761 void* lastStackTop() { return m_lastStackTop; }
762 void setLastStackTop(void*);
763
764 void firePrimitiveGigacageEnabledIfNecessary()
765 {
766 if (m_needToFirePrimitiveGigacageEnabled) {
767 m_needToFirePrimitiveGigacageEnabled = false;
768 m_primitiveGigacageEnabled.fireAll(*this, "Primitive gigacage disabled asynchronously");
769 }
770 }
771
772 JSValue hostCallReturnValue;
773 unsigned varargsLength;
774 ExecState* newCallFrameReturnValue;
775 ExecState* callFrameForCatch;
776 void* targetMachinePCForThrow;
777 const Instruction* targetInterpreterPCForThrow;
778 uint32_t osrExitIndex;
779 void* osrExitJumpDestination;
780 bool isExecutingInRegExpJIT { false };
781
782 // The threading protocol here is as follows:
783 // - You can call scratchBufferForSize from any thread.
784 // - You can only set the ScratchBuffer's activeLength from the main thread.
785 // - You can only write to entries in the ScratchBuffer from the main thread.
786 ScratchBuffer* scratchBufferForSize(size_t size);
787 void clearScratchBuffers();
788
789 EncodedJSValue* exceptionFuzzingBuffer(size_t size)
790 {
791 ASSERT(Options::useExceptionFuzz());
792 if (!m_exceptionFuzzBuffer)
793 m_exceptionFuzzBuffer = MallocPtr<EncodedJSValue>::malloc(size);
794 return m_exceptionFuzzBuffer.get();
795 }
796
797 void gatherScratchBufferRoots(ConservativeRoots&);
798
799 VMEntryScope* entryScope;
800
801 JSObject* stringRecursionCheckFirstObject { nullptr };
802 HashSet<JSObject*> stringRecursionCheckVisitedObjects;
803
804 LocalTimeOffsetCache localTimeOffsetCache;
805
806 String cachedDateString;
807 double cachedDateStringValue;
808
809 std::unique_ptr<Profiler::Database> m_perBytecodeProfiler;
810 RefPtr<TypedArrayController> m_typedArrayController;
811 RegExpCache* m_regExpCache;
812 BumpPointerAllocator m_regExpAllocator;
813 ConcurrentJSLock m_regExpAllocatorLock;
814
815#if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
816 static constexpr size_t patternContextBufferSize = 8192; // Space allocated to save nested parenthesis context
817 UniqueArray<char> m_regExpPatternContexBuffer;
818 Lock m_regExpPatternContextLock;
819 char* acquireRegExpPatternContexBuffer();
820 void releaseRegExpPatternContexBuffer();
821#else
822 static constexpr size_t patternContextBufferSize = 0; // Space allocated to save nested parenthesis context
823#endif
824
825 Ref<CompactVariableMap> m_compactVariableMap;
826
827 std::unique_ptr<HasOwnPropertyCache> m_hasOwnPropertyCache;
828 ALWAYS_INLINE HasOwnPropertyCache* hasOwnPropertyCache() { return m_hasOwnPropertyCache.get(); }
829 HasOwnPropertyCache* ensureHasOwnPropertyCache();
830
831#if ENABLE(REGEXP_TRACING)
832 typedef ListHashSet<RegExp*> RTTraceList;
833 RTTraceList* m_rtTraceList;
834#endif
835
836#if JSC_OBJC_API_ENABLED
837 void* m_apiWrapper { nullptr };
838#endif
839
840 JS_EXPORT_PRIVATE void resetDateCache();
841
842 RegExpCache* regExpCache() { return m_regExpCache; }
843#if ENABLE(REGEXP_TRACING)
844 void addRegExpToTrace(RegExp*);
845#endif
846 JS_EXPORT_PRIVATE void dumpRegExpTrace();
847
848 bool isCollectorBusyOnCurrentThread() { return heap.isCurrentThreadBusy(); }
849
850#if ENABLE(GC_VALIDATION)
851 bool isInitializingObject() const;
852 void setInitializingObjectClass(const ClassInfo*);
853#endif
854
855 bool currentThreadIsHoldingAPILock() const { return m_apiLock->currentThreadIsHoldingLock(); }
856
857 JSLock& apiLock() { return *m_apiLock; }
858 CodeCache* codeCache() { return m_codeCache.get(); }
859
860 JS_EXPORT_PRIVATE void whenIdle(Function<void()>&&);
861
862 JS_EXPORT_PRIVATE void deleteAllCode(DeleteAllCodeEffort);
863 JS_EXPORT_PRIVATE void deleteAllLinkedCode(DeleteAllCodeEffort);
864
865 void shrinkFootprintWhenIdle();
866
867 WatchpointSet* ensureWatchpointSetForImpureProperty(const Identifier&);
868 void registerWatchpointForImpureProperty(const Identifier&, Watchpoint*);
869
870 // FIXME: Use AtomString once it got merged with Identifier.
871 JS_EXPORT_PRIVATE void addImpureProperty(const String&);
872
873 InlineWatchpointSet& primitiveGigacageEnabled() { return m_primitiveGigacageEnabled; }
874
875 BuiltinExecutables* builtinExecutables() { return m_builtinExecutables.get(); }
876
877 bool enableTypeProfiler();
878 bool disableTypeProfiler();
879 TypeProfilerLog* typeProfilerLog() { return m_typeProfilerLog.get(); }
880 TypeProfiler* typeProfiler() { return m_typeProfiler.get(); }
881 JS_EXPORT_PRIVATE void dumpTypeProfilerData();
882
883 FunctionHasExecutedCache* functionHasExecutedCache() { return &m_functionHasExecutedCache; }
884
885 ControlFlowProfiler* controlFlowProfiler() { return m_controlFlowProfiler.get(); }
886 bool enableControlFlowProfiler();
887 bool disableControlFlowProfiler();
888
889 void queueMicrotask(JSGlobalObject&, Ref<Microtask>&&);
890 JS_EXPORT_PRIVATE void drainMicrotasks();
891 void setOnEachMicrotaskTick(WTF::Function<void(VM&)>&& func) { m_onEachMicrotaskTick = WTFMove(func); }
892 void finalizeSynchronousJSExecution() { ASSERT(currentThreadIsHoldingAPILock()); m_currentWeakRefVersion++; }
893 uintptr_t currentWeakRefVersion() const { return m_currentWeakRefVersion; }
894
895 void setGlobalConstRedeclarationShouldThrow(bool globalConstRedeclarationThrow) { m_globalConstRedeclarationShouldThrow = globalConstRedeclarationThrow; }
896 ALWAYS_INLINE bool globalConstRedeclarationShouldThrow() const { return m_globalConstRedeclarationShouldThrow; }
897
898 void setShouldBuildPCToCodeOriginMapping() { m_shouldBuildPCToCodeOriginMapping = true; }
899 bool shouldBuilderPCToCodeOriginMapping() const { return m_shouldBuildPCToCodeOriginMapping; }
900
901 BytecodeIntrinsicRegistry& bytecodeIntrinsicRegistry() { return *m_bytecodeIntrinsicRegistry; }
902
903 ShadowChicken* shadowChicken() { return m_shadowChicken.get(); }
904 void ensureShadowChicken();
905
906 template<typename Func>
907 void logEvent(CodeBlock*, const char* summary, const Func& func);
908
909 Optional<RefPtr<Thread>> ownerThread() const { return m_apiLock->ownerThread(); }
910
911 VMTraps& traps() { return m_traps; }
912
913 void handleTraps(ExecState* exec, VMTraps::Mask mask = VMTraps::Mask::allEventTypes()) { m_traps.handleTraps(exec, mask); }
914
915 bool needTrapHandling() { return m_traps.needTrapHandling(); }
916 bool needTrapHandling(VMTraps::Mask mask) { return m_traps.needTrapHandling(mask); }
917 void* needTrapHandlingAddress() { return m_traps.needTrapHandlingAddress(); }
918
919 void notifyNeedDebuggerBreak() { m_traps.fireTrap(VMTraps::NeedDebuggerBreak); }
920 void notifyNeedTermination() { m_traps.fireTrap(VMTraps::NeedTermination); }
921 void notifyNeedWatchdogCheck() { m_traps.fireTrap(VMTraps::NeedWatchdogCheck); }
922
923#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
924 StackTrace* nativeStackTraceOfLastThrow() const { return m_nativeStackTraceOfLastThrow.get(); }
925 Thread* throwingThread() const { return m_throwingThread.get(); }
926 bool needExceptionCheck() const { return m_needExceptionCheck; }
927#endif
928
929#if USE(CF)
930 CFRunLoopRef runLoop() const { return m_runLoop.get(); }
931 JS_EXPORT_PRIVATE void setRunLoop(CFRunLoopRef);
932#endif // USE(CF)
933
934 static void setCrashOnVMCreation(bool);
935
936 class DeferExceptionScope {
937 public:
938 DeferExceptionScope(VM& vm)
939 : m_savedException(vm.m_exception, nullptr)
940 , m_savedLastException(vm.m_lastException, nullptr)
941 {
942 }
943
944 private:
945 SetForScope<Exception*> m_savedException;
946 SetForScope<Exception*> m_savedLastException;
947 };
948
949private:
950 friend class LLIntOffsetsExtractor;
951
952 VM(VMType, HeapType);
953 static VM*& sharedInstanceInternal();
954 void createNativeThunk();
955
956 JS_EXPORT_PRIVATE Structure* setIteratorStructureSlow();
957 JS_EXPORT_PRIVATE Structure* mapIteratorStructureSlow();
958 JSCell* sentinelSetBucketSlow();
959 JSCell* sentinelMapBucketSlow();
960
961 void updateStackLimits();
962
963 bool isSafeToRecurse(void* stackLimit) const
964 {
965 ASSERT(Thread::current().stack().isGrowingDownward());
966 void* curr = currentStackPointer();
967 return curr >= stackLimit;
968 }
969
970 void setException(Exception* exception)
971 {
972 m_exception = exception;
973 m_lastException = exception;
974 }
975 Exception* exception() const
976 {
977#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
978 m_needExceptionCheck = false;
979#endif
980 return m_exception;
981 }
982 void clearException()
983 {
984#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
985 m_needExceptionCheck = false;
986 m_nativeStackTraceOfLastThrow = nullptr;
987 m_throwingThread = nullptr;
988#endif
989 m_exception = nullptr;
990 }
991
992#if ENABLE(C_LOOP)
993 bool ensureStackCapacityForCLoop(Register* newTopOfStack);
994 bool isSafeToRecurseSoftCLoop() const;
995#endif // ENABLE(C_LOOP)
996
997 JS_EXPORT_PRIVATE Exception* throwException(ExecState*, Exception*);
998 JS_EXPORT_PRIVATE Exception* throwException(ExecState*, JSValue);
999 JS_EXPORT_PRIVATE Exception* throwException(ExecState*, JSObject*);
1000
1001#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
1002 void verifyExceptionCheckNeedIsSatisfied(unsigned depth, ExceptionEventLocation&);
1003#endif
1004
1005 static void primitiveGigacageDisabledCallback(void*);
1006 void primitiveGigacageDisabled();
1007
1008#if ENABLE(GC_VALIDATION)
1009 const ClassInfo* m_initializingObjectClass;
1010#endif
1011
1012 void* m_stackPointerAtVMEntry;
1013 size_t m_currentSoftReservedZoneSize;
1014 void* m_stackLimit { nullptr };
1015 void* m_softStackLimit { nullptr };
1016#if ENABLE(C_LOOP)
1017 void* m_cloopStackLimit { nullptr };
1018#endif
1019 void* m_lastStackTop { nullptr };
1020
1021 Exception* m_exception { nullptr };
1022 Exception* m_lastException { nullptr };
1023#if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
1024 ExceptionScope* m_topExceptionScope { nullptr };
1025 ExceptionEventLocation m_simulatedThrowPointLocation;
1026 unsigned m_simulatedThrowPointRecursionDepth { 0 };
1027 mutable bool m_needExceptionCheck { false };
1028 std::unique_ptr<StackTrace> m_nativeStackTraceOfLastThrow;
1029 std::unique_ptr<StackTrace> m_nativeStackTraceOfLastSimulatedThrow;
1030 RefPtr<Thread> m_throwingThread;
1031#endif
1032
1033 bool m_failNextNewCodeBlock { false };
1034 DeletePropertyMode m_deletePropertyMode { DeletePropertyMode::Default };
1035 bool m_globalConstRedeclarationShouldThrow { true };
1036 bool m_shouldBuildPCToCodeOriginMapping { false };
1037 std::unique_ptr<CodeCache> m_codeCache;
1038 std::unique_ptr<BuiltinExecutables> m_builtinExecutables;
1039 HashMap<String, RefPtr<WatchpointSet>> m_impurePropertyWatchpointSets;
1040 std::unique_ptr<TypeProfiler> m_typeProfiler;
1041 std::unique_ptr<TypeProfilerLog> m_typeProfilerLog;
1042 unsigned m_typeProfilerEnabledCount;
1043 bool m_needToFirePrimitiveGigacageEnabled { false };
1044 Lock m_scratchBufferLock;
1045 Vector<ScratchBuffer*> m_scratchBuffers;
1046 size_t m_sizeOfLastScratchBuffer { 0 };
1047 InlineWatchpointSet m_primitiveGigacageEnabled;
1048 FunctionHasExecutedCache m_functionHasExecutedCache;
1049 std::unique_ptr<ControlFlowProfiler> m_controlFlowProfiler;
1050 unsigned m_controlFlowProfilerEnabledCount;
1051 Deque<std::unique_ptr<QueuedTask>> m_microtaskQueue;
1052 MallocPtr<EncodedJSValue> m_exceptionFuzzBuffer;
1053 VMTraps m_traps;
1054 RefPtr<Watchdog> m_watchdog;
1055 std::unique_ptr<HeapProfiler> m_heapProfiler;
1056#if ENABLE(SAMPLING_PROFILER)
1057 RefPtr<SamplingProfiler> m_samplingProfiler;
1058#endif
1059 std::unique_ptr<FuzzerAgent> m_fuzzerAgent;
1060 std::unique_ptr<ShadowChicken> m_shadowChicken;
1061 std::unique_ptr<BytecodeIntrinsicRegistry> m_bytecodeIntrinsicRegistry;
1062
1063 WTF::Function<void(VM&)> m_onEachMicrotaskTick;
1064 uintptr_t m_currentWeakRefVersion { 0 };
1065
1066#if ENABLE(JIT)
1067#if !ASSERT_DISABLED
1068 JS_EXPORT_PRIVATE static bool s_canUseJITIsSet;
1069#endif
1070 JS_EXPORT_PRIVATE static bool s_canUseJIT;
1071#endif
1072
1073 VM* m_prev; // Required by DoublyLinkedListNode.
1074 VM* m_next; // Required by DoublyLinkedListNode.
1075
1076 // Friends for exception checking purpose only.
1077 friend class Heap;
1078 friend class CatchScope;
1079 friend class ExceptionScope;
1080 friend class ThrowScope;
1081 friend class VMTraps;
1082 friend class WTF::DoublyLinkedListNode<VM>;
1083};
1084
1085#if ENABLE(GC_VALIDATION)
1086inline bool VM::isInitializingObject() const
1087{
1088 return !!m_initializingObjectClass;
1089}
1090
1091inline void VM::setInitializingObjectClass(const ClassInfo* initializingObjectClass)
1092{
1093 m_initializingObjectClass = initializingObjectClass;
1094}
1095#endif
1096
1097inline Heap* WeakSet::heap() const
1098{
1099 return &m_vm->heap;
1100}
1101
1102#if !ENABLE(C_LOOP)
1103extern "C" void sanitizeStackForVMImpl(VM*);
1104#endif
1105
1106JS_EXPORT_PRIVATE void sanitizeStackForVM(VM*);
1107void logSanitizeStack(VM*);
1108
1109} // namespace JSC
1110