Exception is a JSCell, not a JSObject.
[WebKit-https.git] / Source / JavaScriptCore / runtime / VM.cpp
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 #include "config.h"
30 #include "VM.h"
31
32 #include "ArgList.h"
33 #include "ArrayBufferNeuteringWatchpoint.h"
34 #include "BuiltinExecutables.h"
35 #include "BytecodeIntrinsicRegistry.h"
36 #include "CodeBlock.h"
37 #include "CodeCache.h"
38 #include "CommonIdentifiers.h"
39 #include "CommonSlowPaths.h"
40 #include "CustomGetterSetter.h"
41 #include "DFGWorklist.h"
42 #include "DirectEvalExecutable.h"
43 #include "Disassembler.h"
44 #include "Error.h"
45 #include "ErrorConstructor.h"
46 #include "ErrorInstance.h"
47 #include "EvalCodeBlock.h"
48 #include "Exception.h"
49 #include "ExecutableToCodeBlockEdge.h"
50 #include "FTLThunks.h"
51 #include "FastMallocAlignedMemoryAllocator.h"
52 #include "FunctionCodeBlock.h"
53 #include "FunctionConstructor.h"
54 #include "FunctionExecutable.h"
55 #include "GCActivityCallback.h"
56 #include "GetterSetter.h"
57 #include "GigacageAlignedMemoryAllocator.h"
58 #include "HasOwnPropertyCache.h"
59 #include "Heap.h"
60 #include "HeapIterationScope.h"
61 #include "HeapProfiler.h"
62 #include "HostCallReturnValue.h"
63 #include "Identifier.h"
64 #include "IncrementalSweeper.h"
65 #include "IndirectEvalExecutable.h"
66 #include "InferredValue.h"
67 #include "Interpreter.h"
68 #include "IntlCollatorConstructor.h"
69 #include "IntlDateTimeFormatConstructor.h"
70 #include "IntlNumberFormatConstructor.h"
71 #include "IntlPluralRulesConstructor.h"
72 #include "JITCode.h"
73 #include "JITWorklist.h"
74 #include "JSAPIValueWrapper.h"
75 #include "JSArray.h"
76 #include "JSArrayBufferConstructor.h"
77 #include "JSAsyncFunction.h"
78 #include "JSBigInt.h"
79 #include "JSBoundFunction.h"
80 #include "JSCInlines.h"
81 #include "JSCallbackFunction.h"
82 #include "JSCustomGetterSetterFunction.h"
83 #include "JSDestructibleObjectHeapCellType.h"
84 #include "JSFixedArray.h"
85 #include "JSFunction.h"
86 #include "JSGlobalObjectFunctions.h"
87 #include "JSImmutableButterfly.h"
88 #include "JSInternalPromiseDeferred.h"
89 #include "JSLock.h"
90 #include "JSMap.h"
91 #include "JSMapIterator.h"
92 #include "JSPromiseDeferred.h"
93 #include "JSPropertyNameEnumerator.h"
94 #include "JSSegmentedVariableObjectHeapCellType.h"
95 #include "JSScriptFetchParameters.h"
96 #include "JSScriptFetcher.h"
97 #include "JSSet.h"
98 #include "JSSetIterator.h"
99 #include "JSSourceCode.h"
100 #include "JSStringHeapCellType.h"
101 #include "JSTemplateObjectDescriptor.h"
102 #include "JSWeakMap.h"
103 #include "JSWeakSet.h"
104 #include "JSWebAssembly.h"
105 #include "JSWebAssemblyCodeBlock.h"
106 #include "JSWebAssemblyCodeBlockHeapCellType.h"
107 #include "JSWithScope.h"
108 #include "LLIntData.h"
109 #include "Lexer.h"
110 #include "Lookup.h"
111 #include "MinimumReservedZoneSize.h"
112 #include "ModuleProgramCodeBlock.h"
113 #include "ModuleProgramExecutable.h"
114 #include "NativeErrorConstructor.h"
115 #include "NativeExecutable.h"
116 #include "NativeStdFunctionCell.h"
117 #include "Nodes.h"
118 #include "ObjCCallbackFunction.h"
119 #include "Parser.h"
120 #include "ProfilerDatabase.h"
121 #include "ProgramCodeBlock.h"
122 #include "ProgramExecutable.h"
123 #include "PromiseDeferredTimer.h"
124 #include "PropertyMapHashTable.h"
125 #include "ProxyRevoke.h"
126 #include "RegExpCache.h"
127 #include "RegExpObject.h"
128 #include "RegisterAtOffsetList.h"
129 #include "RuntimeType.h"
130 #include "SamplingProfiler.h"
131 #include "ShadowChicken.h"
132 #include "SimpleTypedArrayController.h"
133 #include "SourceProviderCache.h"
134 #include "StackVisitor.h"
135 #include "StrictEvalActivation.h"
136 #include "StrongInlines.h"
137 #include "StructureInlines.h"
138 #include "TestRunnerUtils.h"
139 #include "ThunkGenerators.h"
140 #include "TypeProfiler.h"
141 #include "TypeProfilerLog.h"
142 #include "UnlinkedCodeBlock.h"
143 #include "VMEntryScope.h"
144 #include "VMInlines.h"
145 #include "VMInspector.h"
146 #include "VariableEnvironment.h"
147 #include "WasmWorklist.h"
148 #include "Watchdog.h"
149 #include "WeakGCMapInlines.h"
150 #include "WebAssemblyFunction.h"
151 #include "WebAssemblyWrapperFunction.h"
152 #include <wtf/ProcessID.h>
153 #include <wtf/ReadWriteLock.h>
154 #include <wtf/SimpleStats.h>
155 #include <wtf/StringPrintStream.h>
156 #include <wtf/Threading.h>
157 #include <wtf/text/AtomicStringTable.h>
158 #include <wtf/text/SymbolRegistry.h>
159
160 #if ENABLE(C_LOOP)
161 #include "CLoopStack.h"
162 #include "CLoopStackInlines.h"
163 #endif
164
165 #if ENABLE(DFG_JIT)
166 #include "ConservativeRoots.h"
167 #endif
168
169 #if ENABLE(REGEXP_TRACING)
170 #include "RegExp.h"
171 #endif
172
173 namespace JSC {
174
175 #if ENABLE(JIT)
176 #if !ASSERT_DISABLED
177 bool VM::s_canUseJITIsSet = false;
178 #endif
179 bool VM::s_canUseJIT = false;
180 #endif
181
182 Atomic<unsigned> VM::s_numberOfIDs;
183
184 // Note: Platform.h will enforce that ENABLE(ASSEMBLER) is true if either
185 // ENABLE(JIT) or ENABLE(YARR_JIT) or both are enabled. The code below
186 // just checks for ENABLE(JIT) or ENABLE(YARR_JIT) with this premise in mind.
187
188 #if ENABLE(ASSEMBLER)
189 static bool enableAssembler(ExecutableAllocator& executableAllocator)
190 {
191     if (!Options::useJIT() && !Options::useRegExpJIT())
192         return false;
193
194     if (!executableAllocator.isValid()) {
195         if (Options::crashIfCantAllocateJITMemory())
196             CRASH();
197         return false;
198     }
199
200     char* canUseJITString = getenv("JavaScriptCoreUseJIT");
201     return !canUseJITString || atoi(canUseJITString);
202 }
203 #endif // ENABLE(!ASSEMBLER)
204
205 bool VM::canUseAssembler()
206 {
207 #if ENABLE(ASSEMBLER)
208     static std::once_flag onceKey;
209     static bool enabled = false;
210     std::call_once(onceKey, [] {
211         enabled = enableAssembler(ExecutableAllocator::singleton());
212     });
213     return enabled;
214 #else
215     return false; // interpreter only
216 #endif
217 }
218
219 void VM::computeCanUseJIT()
220 {
221 #if ENABLE(JIT)
222 #if !ASSERT_DISABLED
223     RELEASE_ASSERT(!s_canUseJITIsSet);
224     s_canUseJITIsSet = true;
225 #endif
226     s_canUseJIT = VM::canUseAssembler() && Options::useJIT();
227 #endif
228 }
229
230 bool VM::canUseRegExpJIT()
231 {
232 #if ENABLE(YARR_JIT)
233     static std::once_flag onceKey;
234     static bool enabled = false;
235     std::call_once(onceKey, [] {
236         enabled = VM::canUseAssembler() && Options::useRegExpJIT();
237     });
238     return enabled;
239 #else
240     return false; // interpreter only
241 #endif
242 }
243
244 bool VM::isInMiniMode()
245 {
246     return !canUseJIT() || Options::forceMiniVMMode();
247 }
248
249 inline unsigned VM::nextID()
250 {
251     for (;;) {
252         unsigned currentNumberOfIDs = s_numberOfIDs.load();
253         unsigned newID = currentNumberOfIDs + 1;
254         if (s_numberOfIDs.compareExchangeWeak(currentNumberOfIDs, newID))
255             return newID;
256     }
257 }
258
259 static bool vmCreationShouldCrash = false;
260
261 VM::VM(VMType vmType, HeapType heapType)
262     : m_id(nextID())
263     , m_apiLock(adoptRef(new JSLock(this)))
264 #if USE(CF)
265     , m_runLoop(CFRunLoopGetCurrent())
266 #endif // USE(CF)
267     , heap(this, heapType)
268     , fastMallocAllocator(std::make_unique<FastMallocAlignedMemoryAllocator>())
269     , primitiveGigacageAllocator(std::make_unique<GigacageAlignedMemoryAllocator>(Gigacage::Primitive))
270     , jsValueGigacageAllocator(std::make_unique<GigacageAlignedMemoryAllocator>(Gigacage::JSValue))
271     , auxiliaryHeapCellType(std::make_unique<HeapCellType>(CellAttributes(DoesNotNeedDestruction, HeapCell::Auxiliary)))
272     , immutableButterflyHeapCellType(std::make_unique<HeapCellType>(CellAttributes(DoesNotNeedDestruction, HeapCell::JSCellWithInteriorPointers)))
273     , cellHeapCellType(std::make_unique<HeapCellType>(CellAttributes(DoesNotNeedDestruction, HeapCell::JSCell)))
274     , destructibleCellHeapCellType(std::make_unique<HeapCellType>(CellAttributes(NeedsDestruction, HeapCell::JSCell)))
275     , stringHeapCellType(std::make_unique<JSStringHeapCellType>())
276     , destructibleObjectHeapCellType(std::make_unique<JSDestructibleObjectHeapCellType>())
277     , segmentedVariableObjectHeapCellType(std::make_unique<JSSegmentedVariableObjectHeapCellType>())
278 #if ENABLE(WEBASSEMBLY)
279     , webAssemblyCodeBlockHeapCellType(std::make_unique<JSWebAssemblyCodeBlockHeapCellType>())
280 #endif
281     , primitiveGigacageAuxiliarySpace("Primitive Gigacage Auxiliary", heap, auxiliaryHeapCellType.get(), primitiveGigacageAllocator.get())
282     , jsValueGigacageAuxiliarySpace("JSValue Gigacage Auxiliary", heap, auxiliaryHeapCellType.get(), jsValueGigacageAllocator.get())
283     , immutableButterflyJSValueGigacageAuxiliarySpace("ImmutableButterfly Gigacage JSCellWithInteriorPointers", heap, immutableButterflyHeapCellType.get(), jsValueGigacageAllocator.get())
284     , cellSpace("JSCell", heap, cellHeapCellType.get(), fastMallocAllocator.get())
285     , jsValueGigacageCellSpace("JSValue Gigacage JSCell", heap, cellHeapCellType.get(), jsValueGigacageAllocator.get())
286     , destructibleCellSpace("Destructible JSCell", heap, destructibleCellHeapCellType.get(), fastMallocAllocator.get())
287     , stringSpace("JSString", heap, stringHeapCellType.get(), fastMallocAllocator.get())
288     , destructibleObjectSpace("JSDestructibleObject", heap, destructibleObjectHeapCellType.get(), fastMallocAllocator.get())
289     , eagerlySweptDestructibleObjectSpace("Eagerly Swept JSDestructibleObject", heap, destructibleObjectHeapCellType.get(), fastMallocAllocator.get())
290     , segmentedVariableObjectSpace("JSSegmentedVariableObjectSpace", heap, segmentedVariableObjectHeapCellType.get(), fastMallocAllocator.get())
291     , executableToCodeBlockEdgeSpace ISO_SUBSPACE_INIT(heap, cellHeapCellType.get(), ExecutableToCodeBlockEdge)
292     , functionSpace ISO_SUBSPACE_INIT(heap, cellHeapCellType.get(), JSFunction)
293     , internalFunctionSpace ISO_SUBSPACE_INIT(heap, destructibleObjectHeapCellType.get(), InternalFunction)
294     , nativeExecutableSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), NativeExecutable)
295     , propertyTableSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), PropertyTable)
296     , structureRareDataSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), StructureRareData)
297     , structureSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), Structure)
298     , executableToCodeBlockEdgesWithConstraints(executableToCodeBlockEdgeSpace)
299     , executableToCodeBlockEdgesWithFinalizers(executableToCodeBlockEdgeSpace)
300     , codeBlockSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), CodeBlock)
301     , functionExecutableSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), FunctionExecutable)
302     , programExecutableSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), ProgramExecutable)
303     , unlinkedFunctionExecutableSpace ISO_SUBSPACE_INIT(heap, destructibleCellHeapCellType.get(), UnlinkedFunctionExecutable)
304     , vmType(vmType)
305     , clientData(0)
306     , topEntryFrame(nullptr)
307     , topCallFrame(CallFrame::noCaller())
308     , promiseDeferredTimer(std::make_unique<PromiseDeferredTimer>(*this))
309     , m_atomicStringTable(vmType == Default ? Thread::current().atomicStringTable() : new AtomicStringTable)
310     , propertyNames(nullptr)
311     , emptyList(new ArgList)
312     , machineCodeBytesPerBytecodeWordForBaselineJIT(std::make_unique<SimpleStats>())
313     , customGetterSetterFunctionMap(*this)
314     , stringCache(*this)
315     , symbolImplToSymbolMap(*this)
316     , structureCache(*this)
317     , interpreter(0)
318     , entryScope(0)
319     , m_regExpCache(new RegExpCache(this))
320     , m_compactVariableMap(adoptRef(*(new CompactVariableMap)))
321 #if ENABLE(REGEXP_TRACING)
322     , m_rtTraceList(new RTTraceList())
323 #endif
324 #if ENABLE(GC_VALIDATION)
325     , m_initializingObjectClass(0)
326 #endif
327     , m_stackPointerAtVMEntry(0)
328     , m_codeCache(std::make_unique<CodeCache>())
329     , m_builtinExecutables(std::make_unique<BuiltinExecutables>(*this))
330     , m_typeProfilerEnabledCount(0)
331     , m_primitiveGigacageEnabled(IsWatched)
332     , m_controlFlowProfilerEnabledCount(0)
333 {
334     if (UNLIKELY(vmCreationShouldCrash))
335         CRASH_WITH_INFO(0x4242424220202020, 0xbadbeef0badbeef, 0x1234123412341234, 0x1337133713371337);
336
337     interpreter = new Interpreter(*this);
338     StackBounds stack = Thread::current().stack();
339     updateSoftReservedZoneSize(Options::softReservedZoneSize());
340     setLastStackTop(stack.origin());
341
342     JSRunLoopTimer::Manager::shared().registerVM(*this);
343
344     // Need to be careful to keep everything consistent here
345     JSLockHolder lock(this);
346     AtomicStringTable* existingEntryAtomicStringTable = Thread::current().setCurrentAtomicStringTable(m_atomicStringTable);
347     structureStructure.set(*this, Structure::createStructure(*this));
348     structureRareDataStructure.set(*this, StructureRareData::createStructure(*this, 0, jsNull()));
349     stringStructure.set(*this, JSString::createStructure(*this, 0, jsNull()));
350
351     smallStrings.initializeCommonStrings(*this);
352
353     propertyNames = new CommonIdentifiers(this);
354     terminatedExecutionErrorStructure.set(*this, TerminatedExecutionError::createStructure(*this, 0, jsNull()));
355     propertyNameEnumeratorStructure.set(*this, JSPropertyNameEnumerator::createStructure(*this, 0, jsNull()));
356     customGetterSetterStructure.set(*this, CustomGetterSetter::createStructure(*this, 0, jsNull()));
357     domAttributeGetterSetterStructure.set(*this, DOMAttributeGetterSetter::createStructure(*this, 0, jsNull()));
358     scopedArgumentsTableStructure.set(*this, ScopedArgumentsTable::createStructure(*this, 0, jsNull()));
359     apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, 0, jsNull()));
360     nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, 0, jsNull()));
361     evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, 0, jsNull()));
362     programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, 0, jsNull()));
363     functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, 0, jsNull()));
364 #if ENABLE(WEBASSEMBLY)
365     webAssemblyCodeBlockStructure.set(*this, JSWebAssemblyCodeBlock::createStructure(*this, 0, jsNull()));
366 #endif
367     moduleProgramExecutableStructure.set(*this, ModuleProgramExecutable::createStructure(*this, 0, jsNull()));
368     regExpStructure.set(*this, RegExp::createStructure(*this, 0, jsNull()));
369     symbolStructure.set(*this, Symbol::createStructure(*this, 0, jsNull()));
370     symbolTableStructure.set(*this, SymbolTable::createStructure(*this, 0, jsNull()));
371     fixedArrayStructure.set(*this, JSFixedArray::createStructure(*this, 0, jsNull()));
372
373     immutableButterflyStructures[arrayIndexFromIndexingType(CopyOnWriteArrayWithInt32) - NumberOfIndexingShapes].set(*this, JSImmutableButterfly::createStructure(*this, 0, jsNull(), CopyOnWriteArrayWithInt32));
374     immutableButterflyStructures[arrayIndexFromIndexingType(CopyOnWriteArrayWithDouble) - NumberOfIndexingShapes].set(*this, JSImmutableButterfly::createStructure(*this, 0, jsNull(), CopyOnWriteArrayWithDouble));
375     immutableButterflyStructures[arrayIndexFromIndexingType(CopyOnWriteArrayWithContiguous) - NumberOfIndexingShapes].set(*this, JSImmutableButterfly::createStructure(*this, 0, jsNull(), CopyOnWriteArrayWithContiguous));
376
377     sourceCodeStructure.set(*this, JSSourceCode::createStructure(*this, 0, jsNull()));
378     scriptFetcherStructure.set(*this, JSScriptFetcher::createStructure(*this, 0, jsNull()));
379     scriptFetchParametersStructure.set(*this, JSScriptFetchParameters::createStructure(*this, 0, jsNull()));
380     structureChainStructure.set(*this, StructureChain::createStructure(*this, 0, jsNull()));
381     sparseArrayValueMapStructure.set(*this, SparseArrayValueMap::createStructure(*this, 0, jsNull()));
382     templateObjectDescriptorStructure.set(*this, JSTemplateObjectDescriptor::createStructure(*this, 0, jsNull()));
383     arrayBufferNeuteringWatchpointStructure.set(*this, ArrayBufferNeuteringWatchpoint::createStructure(*this));
384     unlinkedFunctionExecutableStructure.set(*this, UnlinkedFunctionExecutable::createStructure(*this, 0, jsNull()));
385     unlinkedProgramCodeBlockStructure.set(*this, UnlinkedProgramCodeBlock::createStructure(*this, 0, jsNull()));
386     unlinkedEvalCodeBlockStructure.set(*this, UnlinkedEvalCodeBlock::createStructure(*this, 0, jsNull()));
387     unlinkedFunctionCodeBlockStructure.set(*this, UnlinkedFunctionCodeBlock::createStructure(*this, 0, jsNull()));
388     unlinkedModuleProgramCodeBlockStructure.set(*this, UnlinkedModuleProgramCodeBlock::createStructure(*this, 0, jsNull()));
389     propertyTableStructure.set(*this, PropertyTable::createStructure(*this, 0, jsNull()));
390     if (VM::canUseJIT())
391         inferredValueStructure.set(*this, InferredValue::createStructure(*this, 0, jsNull()));
392     functionRareDataStructure.set(*this, FunctionRareData::createStructure(*this, 0, jsNull()));
393     exceptionStructure.set(*this, Exception::createStructure(*this, 0, jsNull()));
394     promiseDeferredStructure.set(*this, JSPromiseDeferred::createStructure(*this, 0, jsNull()));
395     internalPromiseDeferredStructure.set(*this, JSInternalPromiseDeferred::createStructure(*this, 0, jsNull()));
396     nativeStdFunctionCellStructure.set(*this, NativeStdFunctionCell::createStructure(*this, 0, jsNull()));
397     programCodeBlockStructure.set(*this, ProgramCodeBlock::createStructure(*this, 0, jsNull()));
398     moduleProgramCodeBlockStructure.set(*this, ModuleProgramCodeBlock::createStructure(*this, 0, jsNull()));
399     evalCodeBlockStructure.set(*this, EvalCodeBlock::createStructure(*this, 0, jsNull()));
400     functionCodeBlockStructure.set(*this, FunctionCodeBlock::createStructure(*this, 0, jsNull()));
401     hashMapBucketSetStructure.set(*this, HashMapBucket<HashMapBucketDataKey>::createStructure(*this, 0, jsNull()));
402     hashMapBucketMapStructure.set(*this, HashMapBucket<HashMapBucketDataKeyValue>::createStructure(*this, 0, jsNull()));
403     setIteratorStructure.set(*this, JSSetIterator::createStructure(*this, 0, jsNull()));
404     mapIteratorStructure.set(*this, JSMapIterator::createStructure(*this, 0, jsNull()));
405     bigIntStructure.set(*this, JSBigInt::createStructure(*this, 0, jsNull()));
406     executableToCodeBlockEdgeStructure.set(*this, ExecutableToCodeBlockEdge::createStructure(*this, nullptr, jsNull()));
407
408     // Eagerly initialize constant cells since the concurrent compiler can access them.
409     if (canUseJIT()) {
410         sentinelMapBucket();
411         sentinelSetBucket();
412     }
413
414     Thread::current().setCurrentAtomicStringTable(existingEntryAtomicStringTable);
415
416 #if ENABLE(JIT)
417     jitStubs = std::make_unique<JITThunks>();
418 #endif
419
420 #if ENABLE(FTL_JIT)
421     ftlThunks = std::make_unique<FTL::Thunks>();
422 #endif // ENABLE(FTL_JIT)
423     
424 #if !ENABLE(C_LOOP)
425     initializeHostCallReturnValue(); // This is needed to convince the linker not to drop host call return support.
426 #endif
427     
428     Gigacage::addPrimitiveDisableCallback(primitiveGigacageDisabledCallback, this);
429
430     heap.notifyIsSafeToCollect();
431     
432     LLInt::Data::performAssertions(*this);
433     
434     if (UNLIKELY(Options::useProfiler())) {
435         m_perBytecodeProfiler = std::make_unique<Profiler::Database>(*this);
436
437         StringPrintStream pathOut;
438         const char* profilerPath = getenv("JSC_PROFILER_PATH");
439         if (profilerPath)
440             pathOut.print(profilerPath, "/");
441         pathOut.print("JSCProfile-", getCurrentProcessID(), "-", m_perBytecodeProfiler->databaseID(), ".json");
442         m_perBytecodeProfiler->registerToSaveAtExit(pathOut.toCString().data());
443     }
444
445     callFrameForCatch = nullptr;
446
447     // Initialize this last, as a free way of asserting that VM initialization itself
448     // won't use this.
449     m_typedArrayController = adoptRef(new SimpleTypedArrayController());
450
451     m_bytecodeIntrinsicRegistry = std::make_unique<BytecodeIntrinsicRegistry>(*this);
452
453     if (Options::useTypeProfiler())
454         enableTypeProfiler();
455     if (Options::useControlFlowProfiler())
456         enableControlFlowProfiler();
457 #if ENABLE(SAMPLING_PROFILER)
458     if (Options::useSamplingProfiler()) {
459         setShouldBuildPCToCodeOriginMapping();
460         Ref<Stopwatch> stopwatch = Stopwatch::create();
461         stopwatch->start();
462         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
463         if (Options::samplingProfilerPath())
464             m_samplingProfiler->registerForReportAtExit();
465         m_samplingProfiler->start();
466     }
467 #endif // ENABLE(SAMPLING_PROFILER)
468
469     if (Options::alwaysGeneratePCToCodeOriginMap())
470         setShouldBuildPCToCodeOriginMapping();
471
472     if (Options::watchdog()) {
473         Watchdog& watchdog = ensureWatchdog();
474         watchdog.setTimeLimit(Seconds::fromMilliseconds(Options::watchdog()));
475     }
476
477 #if ENABLE(JIT)
478     // Make sure that any stubs that the JIT is going to use are initialized in non-compilation threads.
479     if (canUseJIT()) {
480         getCTIInternalFunctionTrampolineFor(CodeForCall);
481         getCTIInternalFunctionTrampolineFor(CodeForConstruct);
482     }
483 #endif
484
485     if (!canUseJIT())
486         noJITValueProfileSingleton = std::make_unique<ValueProfile>(0);
487
488     if (Options::forceDebuggerBytecodeGeneration() || Options::alwaysUseShadowChicken())
489         ensureShadowChicken();
490
491     VMInspector::instance().add(this);
492 }
493
494 static ReadWriteLock s_destructionLock;
495
496 void waitForVMDestruction()
497 {
498     auto locker = holdLock(s_destructionLock.write());
499 }
500
501 VM::~VM()
502 {
503     auto destructionLocker = holdLock(s_destructionLock.read());
504     
505     Gigacage::removePrimitiveDisableCallback(primitiveGigacageDisabledCallback, this);
506     promiseDeferredTimer->stopRunningTasks();
507 #if ENABLE(WEBASSEMBLY)
508     if (Wasm::Worklist* worklist = Wasm::existingWorklistOrNull())
509         worklist->stopAllPlansForContext(wasmContext);
510 #endif
511     if (UNLIKELY(m_watchdog))
512         m_watchdog->willDestroyVM(this);
513     m_traps.willDestroyVM();
514     VMInspector::instance().remove(this);
515
516     // Never GC, ever again.
517     heap.incrementDeferralDepth();
518
519 #if ENABLE(SAMPLING_PROFILER)
520     if (m_samplingProfiler) {
521         m_samplingProfiler->reportDataToOptionFile();
522         m_samplingProfiler->shutdown();
523     }
524 #endif // ENABLE(SAMPLING_PROFILER)
525     
526 #if ENABLE(JIT)
527     if (JITWorklist* worklist = JITWorklist::existingGlobalWorklistOrNull())
528         worklist->completeAllForVM(*this);
529 #endif // ENABLE(JIT)
530
531 #if ENABLE(DFG_JIT)
532     // Make sure concurrent compilations are done, but don't install them, since there is
533     // no point to doing so.
534     for (unsigned i = DFG::numberOfWorklists(); i--;) {
535         if (DFG::Worklist* worklist = DFG::existingWorklistForIndexOrNull(i)) {
536             worklist->removeNonCompilingPlansForVM(*this);
537             worklist->waitUntilAllPlansForVMAreReady(*this);
538             worklist->removeAllReadyPlansForVM(*this);
539         }
540     }
541 #endif // ENABLE(DFG_JIT)
542     
543     waitForAsynchronousDisassembly();
544     
545     // Clear this first to ensure that nobody tries to remove themselves from it.
546     m_perBytecodeProfiler = nullptr;
547
548     ASSERT(currentThreadIsHoldingAPILock());
549     m_apiLock->willDestroyVM(this);
550     smallStrings.setIsInitialized(false);
551     heap.lastChanceToFinalize();
552
553     JSRunLoopTimer::Manager::shared().unregisterVM(*this);
554     
555     delete interpreter;
556 #ifndef NDEBUG
557     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
558 #endif
559
560     delete emptyList;
561
562     delete propertyNames;
563     if (vmType != Default)
564         delete m_atomicStringTable;
565
566     delete clientData;
567     delete m_regExpCache;
568
569 #if ENABLE(REGEXP_TRACING)
570     delete m_rtTraceList;
571 #endif
572
573 #if ENABLE(DFG_JIT)
574     for (unsigned i = 0; i < m_scratchBuffers.size(); ++i)
575         fastFree(m_scratchBuffers[i]);
576 #endif
577 }
578
579 void VM::primitiveGigacageDisabledCallback(void* argument)
580 {
581     static_cast<VM*>(argument)->primitiveGigacageDisabled();
582 }
583
584 void VM::primitiveGigacageDisabled()
585 {
586     if (m_apiLock->currentThreadIsHoldingLock()) {
587         m_primitiveGigacageEnabled.fireAll(*this, "Primitive gigacage disabled");
588         return;
589     }
590  
591     // This is totally racy, and that's OK. The point is, it's up to the user to ensure that they pass the
592     // uncaged buffer in a nicely synchronized manner.
593     m_needToFirePrimitiveGigacageEnabled = true;
594 }
595
596 void VM::setLastStackTop(void* lastStackTop)
597
598     m_lastStackTop = lastStackTop;
599 }
600
601 Ref<VM> VM::createContextGroup(HeapType heapType)
602 {
603     return adoptRef(*new VM(APIContextGroup, heapType));
604 }
605
606 Ref<VM> VM::create(HeapType heapType)
607 {
608     return adoptRef(*new VM(Default, heapType));
609 }
610
611 bool VM::sharedInstanceExists()
612 {
613     return sharedInstanceInternal();
614 }
615
616 VM& VM::sharedInstance()
617 {
618     GlobalJSLock globalLock;
619     VM*& instance = sharedInstanceInternal();
620     if (!instance)
621         instance = adoptRef(new VM(APIShared, SmallHeap)).leakRef();
622     return *instance;
623 }
624
625 VM*& VM::sharedInstanceInternal()
626 {
627     static VM* sharedInstance;
628     return sharedInstance;
629 }
630
631 Watchdog& VM::ensureWatchdog()
632 {
633     if (!m_watchdog)
634         m_watchdog = adoptRef(new Watchdog(this));
635     return *m_watchdog;
636 }
637
638 HeapProfiler& VM::ensureHeapProfiler()
639 {
640     if (!m_heapProfiler)
641         m_heapProfiler = std::make_unique<HeapProfiler>(*this);
642     return *m_heapProfiler;
643 }
644
645 #if ENABLE(SAMPLING_PROFILER)
646 SamplingProfiler& VM::ensureSamplingProfiler(RefPtr<Stopwatch>&& stopwatch)
647 {
648     if (!m_samplingProfiler)
649         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
650     return *m_samplingProfiler;
651 }
652 #endif // ENABLE(SAMPLING_PROFILER)
653
654 #if ENABLE(JIT)
655 static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
656 {
657     switch (intrinsic) {
658     case CharCodeAtIntrinsic:
659         return charCodeAtThunkGenerator;
660     case CharAtIntrinsic:
661         return charAtThunkGenerator;
662     case Clz32Intrinsic:
663         return clz32ThunkGenerator;
664     case FromCharCodeIntrinsic:
665         return fromCharCodeThunkGenerator;
666     case SqrtIntrinsic:
667         return sqrtThunkGenerator;
668     case AbsIntrinsic:
669         return absThunkGenerator;
670     case FloorIntrinsic:
671         return floorThunkGenerator;
672     case CeilIntrinsic:
673         return ceilThunkGenerator;
674     case TruncIntrinsic:
675         return truncThunkGenerator;
676     case RoundIntrinsic:
677         return roundThunkGenerator;
678     case ExpIntrinsic:
679         return expThunkGenerator;
680     case LogIntrinsic:
681         return logThunkGenerator;
682     case IMulIntrinsic:
683         return imulThunkGenerator;
684     case RandomIntrinsic:
685         return randomThunkGenerator;
686     case BoundThisNoArgsFunctionCallIntrinsic:
687         return boundThisNoArgsFunctionCallGenerator;
688     default:
689         return nullptr;
690     }
691 }
692
693 #endif // ENABLE(JIT)
694
695 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
696 {
697     return getHostFunction(function, NoIntrinsic, constructor, nullptr, name);
698 }
699
700 static Ref<NativeJITCode> jitCodeForCallTrampoline()
701 {
702     static NativeJITCode* result;
703     static std::once_flag onceKey;
704     std::call_once(onceKey, [&] {
705         result = new NativeJITCode(LLInt::getCodeRef<JSEntryPtrTag>(llint_native_call_trampoline), JITCode::HostCallThunk, NoIntrinsic);
706     });
707     return makeRef(*result);
708 }
709
710 static Ref<NativeJITCode> jitCodeForConstructTrampoline()
711 {
712     static NativeJITCode* result;
713     static std::once_flag onceKey;
714     std::call_once(onceKey, [&] {
715         result = new NativeJITCode(LLInt::getCodeRef<JSEntryPtrTag>(llint_native_construct_trampoline), JITCode::HostCallThunk, NoIntrinsic);
716     });
717     return makeRef(*result);
718 }
719
720 NativeExecutable* VM::getHostFunction(NativeFunction function, Intrinsic intrinsic, NativeFunction constructor, const DOMJIT::Signature* signature, const String& name)
721 {
722 #if ENABLE(JIT)
723     if (canUseJIT()) {
724         return jitStubs->hostFunctionStub(
725             this, function, constructor,
726             intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0,
727             intrinsic, signature, name);
728     }
729 #endif // ENABLE(JIT)
730     UNUSED_PARAM(intrinsic);
731     UNUSED_PARAM(signature);
732     return NativeExecutable::create(*this, jitCodeForCallTrampoline(), function, jitCodeForConstructTrampoline(), constructor, name);
733 }
734
735 MacroAssemblerCodePtr<JSEntryPtrTag> VM::getCTIInternalFunctionTrampolineFor(CodeSpecializationKind kind)
736 {
737 #if ENABLE(JIT)
738     if (canUseJIT()) {
739         if (kind == CodeForCall)
740             return jitStubs->ctiInternalFunctionCall(this).retagged<JSEntryPtrTag>();
741         return jitStubs->ctiInternalFunctionConstruct(this).retagged<JSEntryPtrTag>();
742     }
743 #endif
744     if (kind == CodeForCall)
745         return LLInt::getCodePtr<JSEntryPtrTag>(llint_internal_function_call_trampoline);
746     return LLInt::getCodePtr<JSEntryPtrTag>(llint_internal_function_construct_trampoline);
747 }
748
749 VM::ClientData::~ClientData()
750 {
751 }
752
753 void VM::resetDateCache()
754 {
755     localTimeOffsetCache.reset();
756     cachedDateString = String();
757     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
758     dateInstanceCache.reset();
759 }
760
761 void VM::whenIdle(Function<void()>&& callback)
762 {
763     if (!entryScope) {
764         callback();
765         return;
766     }
767
768     entryScope->addDidPopListener(WTFMove(callback));
769 }
770
771 void VM::deleteAllLinkedCode(DeleteAllCodeEffort effort)
772 {
773     whenIdle([=] () {
774         heap.deleteAllCodeBlocks(effort);
775     });
776 }
777
778 void VM::deleteAllCode(DeleteAllCodeEffort effort)
779 {
780     whenIdle([=] () {
781         m_codeCache->clear();
782         m_regExpCache->deleteAllCode();
783         heap.deleteAllCodeBlocks(effort);
784         heap.deleteAllUnlinkedCodeBlocks(effort);
785         heap.reportAbandonedObjectGraph();
786     });
787 }
788
789 void VM::shrinkFootprintWhenIdle()
790 {
791     whenIdle([=] () {
792         sanitizeStackForVM(this);
793         deleteAllCode(DeleteAllCodeIfNotCollecting);
794         heap.collectNow(Synchronousness::Sync, CollectionScope::Full);
795         // FIXME: Consider stopping various automatic threads here.
796         // https://bugs.webkit.org/show_bug.cgi?id=185447
797         WTF::releaseFastMallocFreeMemory();
798     });
799 }
800
801 SourceProviderCache* VM::addSourceProviderCache(SourceProvider* sourceProvider)
802 {
803     auto addResult = sourceProviderCacheMap.add(sourceProvider, nullptr);
804     if (addResult.isNewEntry)
805         addResult.iterator->value = adoptRef(new SourceProviderCache);
806     return addResult.iterator->value.get();
807 }
808
809 void VM::clearSourceProviderCaches()
810 {
811     sourceProviderCacheMap.clear();
812 }
813
814 Exception* VM::throwException(ExecState* exec, Exception* exception)
815 {
816     ASSERT(exec == topCallFrame || exec->isGlobalExec() || exec == exec->lexicalGlobalObject()->callFrameAtDebuggerEntry());
817     CallFrame* throwOriginFrame = exec->isGlobalExec() ? exec : topJSCallFrame();
818
819     if (Options::breakOnThrow()) {
820         CodeBlock* codeBlock = throwOriginFrame ? throwOriginFrame->codeBlock() : nullptr;
821         dataLog("Throwing exception in call frame ", RawPointer(throwOriginFrame), " for code block ", codeBlock, "\n");
822         CRASH();
823     }
824
825     interpreter->notifyDebuggerOfExceptionToBeThrown(*this, throwOriginFrame, exception);
826
827     setException(exception);
828
829 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
830     m_nativeStackTraceOfLastThrow = StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit());
831     m_throwingThread = &Thread::current();
832 #endif
833     return exception;
834 }
835
836 Exception* VM::throwException(ExecState* exec, JSValue thrownValue)
837 {
838     VM& vm = *this;
839     Exception* exception = jsDynamicCast<Exception*>(vm, thrownValue);
840     if (!exception)
841         exception = Exception::create(*this, thrownValue);
842
843     return throwException(exec, exception);
844 }
845
846 Exception* VM::throwException(ExecState* exec, JSObject* error)
847 {
848     return throwException(exec, JSValue(error));
849 }
850
851 void VM::setStackPointerAtVMEntry(void* sp)
852 {
853     m_stackPointerAtVMEntry = sp;
854     updateStackLimits();
855 }
856
857 size_t VM::updateSoftReservedZoneSize(size_t softReservedZoneSize)
858 {
859     size_t oldSoftReservedZoneSize = m_currentSoftReservedZoneSize;
860     m_currentSoftReservedZoneSize = softReservedZoneSize;
861 #if ENABLE(C_LOOP)
862     interpreter->cloopStack().setSoftReservedZoneSize(softReservedZoneSize);
863 #endif
864
865     updateStackLimits();
866
867     return oldSoftReservedZoneSize;
868 }
869
870 #if OS(WINDOWS)
871 // On Windows the reserved stack space consists of committed memory, a guard page, and uncommitted memory,
872 // where the guard page is a barrier between committed and uncommitted memory.
873 // When data from the guard page is read or written, the guard page is moved, and memory is committed.
874 // This is how the system grows the stack.
875 // When using the C stack on Windows we need to precommit the needed stack space.
876 // Otherwise we might crash later if we access uncommitted stack memory.
877 // This can happen if we allocate stack space larger than the page guard size (4K).
878 // The system does not get the chance to move the guard page, and commit more memory,
879 // and we crash if uncommitted memory is accessed.
880 // The MSVC compiler fixes this by inserting a call to the _chkstk() function,
881 // when needed, see http://support.microsoft.com/kb/100775.
882 // By touching every page up to the stack limit with a dummy operation,
883 // we force the system to move the guard page, and commit memory.
884
885 static void preCommitStackMemory(void* stackLimit)
886 {
887     const int pageSize = 4096;
888     for (volatile char* p = reinterpret_cast<char*>(&stackLimit); p > stackLimit; p -= pageSize) {
889         char ch = *p;
890         *p = ch;
891     }
892 }
893 #endif
894
895 inline void VM::updateStackLimits()
896 {
897 #if OS(WINDOWS)
898     void* lastSoftStackLimit = m_softStackLimit;
899 #endif
900
901     const StackBounds& stack = Thread::current().stack();
902     size_t reservedZoneSize = Options::reservedZoneSize();
903     // We should have already ensured that Options::reservedZoneSize() >= minimumReserveZoneSize at
904     // options initialization time, and the option value should not have been changed thereafter.
905     // We don't have the ability to assert here that it hasn't changed, but we can at least assert
906     // that the value is sane.
907     RELEASE_ASSERT(reservedZoneSize >= minimumReservedZoneSize);
908
909     if (m_stackPointerAtVMEntry) {
910         ASSERT(stack.isGrowingDownward());
911         char* startOfStack = reinterpret_cast<char*>(m_stackPointerAtVMEntry);
912         m_softStackLimit = stack.recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_currentSoftReservedZoneSize);
913         m_stackLimit = stack.recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), reservedZoneSize);
914     } else {
915         m_softStackLimit = stack.recursionLimit(m_currentSoftReservedZoneSize);
916         m_stackLimit = stack.recursionLimit(reservedZoneSize);
917     }
918
919 #if OS(WINDOWS)
920     // We only need to precommit stack memory dictated by the VM::m_softStackLimit limit.
921     // This is because VM::m_softStackLimit applies to stack usage by LLINT asm or JIT
922     // generated code which can allocate stack space that the C++ compiler does not know
923     // about. As such, we have to precommit that stack memory manually.
924     //
925     // In contrast, we do not need to worry about VM::m_stackLimit because that limit is
926     // used exclusively by C++ code, and the C++ compiler will automatically commit the
927     // needed stack pages.
928     if (lastSoftStackLimit != m_softStackLimit)
929         preCommitStackMemory(m_softStackLimit);
930 #endif
931 }
932
933 #if ENABLE(DFG_JIT)
934 void VM::gatherScratchBufferRoots(ConservativeRoots& conservativeRoots)
935 {
936     auto lock = holdLock(m_scratchBufferLock);
937     for (auto* scratchBuffer : m_scratchBuffers) {
938         if (scratchBuffer->activeLength()) {
939             void* bufferStart = scratchBuffer->dataBuffer();
940             conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
941         }
942     }
943 }
944 #endif
945
946 void logSanitizeStack(VM* vm)
947 {
948     if (Options::verboseSanitizeStack() && vm->topCallFrame) {
949         int dummy;
950         auto& stackBounds = Thread::current().stack();
951         dataLog(
952             "Sanitizing stack for VM = ", RawPointer(vm), " with top call frame at ", RawPointer(vm->topCallFrame),
953             ", current stack pointer at ", RawPointer(&dummy), ", in ",
954             pointerDump(vm->topCallFrame->codeBlock()), ", last code origin = ",
955             vm->topCallFrame->codeOrigin(), ", last stack top = ", RawPointer(vm->lastStackTop()), ", in stack range [", RawPointer(stackBounds.origin()), ", ", RawPointer(stackBounds.end()), "]\n");
956     }
957 }
958
959 #if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
960 char* VM::acquireRegExpPatternContexBuffer()
961 {
962     m_regExpPatternContextLock.lock();
963     ASSERT(m_regExpPatternContextLock.isLocked());
964     if (!m_regExpPatternContexBuffer)
965         m_regExpPatternContexBuffer = makeUniqueArray<char>(VM::patternContextBufferSize);
966     return m_regExpPatternContexBuffer.get();
967 }
968
969 void VM::releaseRegExpPatternContexBuffer()
970 {
971     ASSERT(m_regExpPatternContextLock.isLocked());
972
973     m_regExpPatternContextLock.unlock();
974 }
975 #endif
976
977 #if ENABLE(REGEXP_TRACING)
978 void VM::addRegExpToTrace(RegExp* regExp)
979 {
980     gcProtect(regExp);
981     m_rtTraceList->add(regExp);
982 }
983
984 void VM::dumpRegExpTrace()
985 {
986     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
987     RTTraceList::iterator iter = ++m_rtTraceList->begin();
988     
989     if (iter != m_rtTraceList->end()) {
990         dataLogF("\nRegExp Tracing\n");
991         dataLogF("Regular Expression                              8 Bit          16 Bit        match()    Matches    Average\n");
992         dataLogF(" <Match only / Match>                         JIT Addr      JIT Address       calls      found   String len\n");
993         dataLogF("----------------------------------------+----------------+----------------+----------+----------+-----------\n");
994     
995         unsigned reCount = 0;
996     
997         for (; iter != m_rtTraceList->end(); ++iter, ++reCount) {
998             (*iter)->printTraceData();
999             gcUnprotect(*iter);
1000         }
1001
1002         dataLogF("%d Regular Expressions\n", reCount);
1003     }
1004     
1005     m_rtTraceList->clear();
1006 }
1007 #else
1008 void VM::dumpRegExpTrace()
1009 {
1010 }
1011 #endif
1012
1013 WatchpointSet* VM::ensureWatchpointSetForImpureProperty(const Identifier& propertyName)
1014 {
1015     auto result = m_impurePropertyWatchpointSets.add(propertyName.string(), nullptr);
1016     if (result.isNewEntry)
1017         result.iterator->value = adoptRef(new WatchpointSet(IsWatched));
1018     return result.iterator->value.get();
1019 }
1020
1021 void VM::registerWatchpointForImpureProperty(const Identifier& propertyName, Watchpoint* watchpoint)
1022 {
1023     ensureWatchpointSetForImpureProperty(propertyName)->add(watchpoint);
1024 }
1025
1026 void VM::addImpureProperty(const String& propertyName)
1027 {
1028     if (RefPtr<WatchpointSet> watchpointSet = m_impurePropertyWatchpointSets.take(propertyName))
1029         watchpointSet->fireAll(*this, "Impure property added");
1030 }
1031
1032 template<typename Func>
1033 static bool enableProfilerWithRespectToCount(unsigned& counter, const Func& doEnableWork)
1034 {
1035     bool needsToRecompile = false;
1036     if (!counter) {
1037         doEnableWork();
1038         needsToRecompile = true;
1039     }
1040     counter++;
1041
1042     return needsToRecompile;
1043 }
1044
1045 template<typename Func>
1046 static bool disableProfilerWithRespectToCount(unsigned& counter, const Func& doDisableWork)
1047 {
1048     RELEASE_ASSERT(counter > 0);
1049     bool needsToRecompile = false;
1050     counter--;
1051     if (!counter) {
1052         doDisableWork();
1053         needsToRecompile = true;
1054     }
1055
1056     return needsToRecompile;
1057 }
1058
1059 bool VM::enableTypeProfiler()
1060 {
1061     auto enableTypeProfiler = [this] () {
1062         this->m_typeProfiler = std::make_unique<TypeProfiler>();
1063         this->m_typeProfilerLog = std::make_unique<TypeProfilerLog>(*this);
1064     };
1065
1066     return enableProfilerWithRespectToCount(m_typeProfilerEnabledCount, enableTypeProfiler);
1067 }
1068
1069 bool VM::disableTypeProfiler()
1070 {
1071     auto disableTypeProfiler = [this] () {
1072         this->m_typeProfiler.reset(nullptr);
1073         this->m_typeProfilerLog.reset(nullptr);
1074     };
1075
1076     return disableProfilerWithRespectToCount(m_typeProfilerEnabledCount, disableTypeProfiler);
1077 }
1078
1079 bool VM::enableControlFlowProfiler()
1080 {
1081     auto enableControlFlowProfiler = [this] () {
1082         this->m_controlFlowProfiler = std::make_unique<ControlFlowProfiler>();
1083     };
1084
1085     return enableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, enableControlFlowProfiler);
1086 }
1087
1088 bool VM::disableControlFlowProfiler()
1089 {
1090     auto disableControlFlowProfiler = [this] () {
1091         this->m_controlFlowProfiler.reset(nullptr);
1092     };
1093
1094     return disableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, disableControlFlowProfiler);
1095 }
1096
1097 void VM::dumpTypeProfilerData()
1098 {
1099     if (!typeProfiler())
1100         return;
1101
1102     typeProfilerLog()->processLogEntries(*this, "VM Dump Types"_s);
1103     typeProfiler()->dumpTypeProfilerData(*this);
1104 }
1105
1106 void VM::queueMicrotask(JSGlobalObject& globalObject, Ref<Microtask>&& task)
1107 {
1108     m_microtaskQueue.append(std::make_unique<QueuedTask>(*this, &globalObject, WTFMove(task)));
1109 }
1110
1111 void VM::drainMicrotasks()
1112 {
1113     while (!m_microtaskQueue.isEmpty()) {
1114         m_microtaskQueue.takeFirst()->run();
1115         if (m_onEachMicrotaskTick)
1116             m_onEachMicrotaskTick(*this);
1117     }
1118 }
1119
1120 void QueuedTask::run()
1121 {
1122     m_microtask->run(m_globalObject->globalExec());
1123 }
1124
1125 void sanitizeStackForVM(VM* vm)
1126 {
1127     logSanitizeStack(vm);
1128     if (vm->topCallFrame) {
1129         auto& stackBounds = Thread::current().stack();
1130         ASSERT(vm->currentThreadIsHoldingAPILock());
1131         ASSERT_UNUSED(stackBounds, stackBounds.contains(vm->lastStackTop()));
1132     }
1133 #if ENABLE(C_LOOP)
1134     vm->interpreter->cloopStack().sanitizeStack();
1135 #else
1136     sanitizeStackForVMImpl(vm);
1137 #endif
1138 }
1139
1140 size_t VM::committedStackByteCount()
1141 {
1142 #if !ENABLE(C_LOOP)
1143     // When using the C stack, we don't know how many stack pages are actually
1144     // committed. So, we use the current stack usage as an estimate.
1145     ASSERT(Thread::current().stack().isGrowingDownward());
1146     uint8_t* current = bitwise_cast<uint8_t*>(currentStackPointer());
1147     uint8_t* high = bitwise_cast<uint8_t*>(Thread::current().stack().origin());
1148     return high - current;
1149 #else
1150     return CLoopStack::committedByteCount();
1151 #endif
1152 }
1153
1154 #if ENABLE(C_LOOP)
1155 bool VM::ensureStackCapacityForCLoop(Register* newTopOfStack)
1156 {
1157     return interpreter->cloopStack().ensureCapacityFor(newTopOfStack);
1158 }
1159
1160 bool VM::isSafeToRecurseSoftCLoop() const
1161 {
1162     return interpreter->cloopStack().isSafeToRecurse();
1163 }
1164 #endif // ENABLE(C_LOOP)
1165
1166 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
1167 void VM::verifyExceptionCheckNeedIsSatisfied(unsigned recursionDepth, ExceptionEventLocation& location)
1168 {
1169     if (!Options::validateExceptionChecks())
1170         return;
1171
1172     if (UNLIKELY(m_needExceptionCheck)) {
1173         auto throwDepth = m_simulatedThrowPointRecursionDepth;
1174         auto& throwLocation = m_simulatedThrowPointLocation;
1175
1176         dataLog(
1177             "ERROR: Unchecked JS exception:\n"
1178             "    This scope can throw a JS exception: ", throwLocation, "\n"
1179             "        (ExceptionScope::m_recursionDepth was ", throwDepth, ")\n"
1180             "    But the exception was unchecked as of this scope: ", location, "\n"
1181             "        (ExceptionScope::m_recursionDepth was ", recursionDepth, ")\n"
1182             "\n");
1183
1184         StringPrintStream out;
1185         std::unique_ptr<StackTrace> currentTrace = StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit());
1186
1187         if (Options::dumpSimulatedThrows()) {
1188             out.println("The simulated exception was thrown at:");
1189             m_nativeStackTraceOfLastSimulatedThrow->dump(out, "    ");
1190             out.println();
1191         }
1192         out.println("Unchecked exception detected at:");
1193         currentTrace->dump(out, "    ");
1194         out.println();
1195
1196         dataLog(out.toCString());
1197         RELEASE_ASSERT(!m_needExceptionCheck);
1198     }
1199 }
1200 #endif
1201
1202 #if USE(CF)
1203 void VM::setRunLoop(CFRunLoopRef runLoop)
1204 {
1205     ASSERT(runLoop);
1206     m_runLoop = runLoop;
1207     JSRunLoopTimer::Manager::shared().didChangeRunLoop(*this, runLoop);
1208 }
1209 #endif // USE(CF)
1210
1211 ScratchBuffer* VM::scratchBufferForSize(size_t size)
1212 {
1213     if (!size)
1214         return nullptr;
1215
1216     auto locker = holdLock(m_scratchBufferLock);
1217
1218     if (size > m_sizeOfLastScratchBuffer) {
1219         // Protect against a N^2 memory usage pathology by ensuring
1220         // that at worst, we get a geometric series, meaning that the
1221         // total memory usage is somewhere around
1222         // max(scratch buffer size) * 4.
1223         m_sizeOfLastScratchBuffer = size * 2;
1224
1225         ScratchBuffer* newBuffer = ScratchBuffer::create(m_sizeOfLastScratchBuffer);
1226         RELEASE_ASSERT(newBuffer);
1227         m_scratchBuffers.append(newBuffer);
1228     }
1229
1230     ScratchBuffer* result = m_scratchBuffers.last();
1231     return result;
1232 }
1233
1234 void VM::clearScratchBuffers()
1235 {
1236     auto lock = holdLock(m_scratchBufferLock);
1237     for (auto* scratchBuffer : m_scratchBuffers)
1238         scratchBuffer->setActiveLength(0);
1239 }
1240
1241 void VM::ensureShadowChicken()
1242 {
1243     if (m_shadowChicken)
1244         return;
1245     m_shadowChicken = std::make_unique<ShadowChicken>();
1246 }
1247
1248 #define DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(name, heapCellType, type) \
1249     IsoSubspace* VM::name##Slow() \
1250     { \
1251         ASSERT(!m_##name); \
1252         auto space = std::make_unique<IsoSubspace> ISO_SUBSPACE_INIT(heap, heapCellType, type); \
1253         WTF::storeStoreFence(); \
1254         m_##name = WTFMove(space); \
1255         return m_##name.get(); \
1256     }
1257
1258
1259 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(boundFunctionSpace, cellHeapCellType.get(), JSBoundFunction)
1260 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(callbackFunctionSpace, destructibleObjectHeapCellType.get(), JSCallbackFunction)
1261 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(customGetterSetterFunctionSpace, cellHeapCellType.get(), JSCustomGetterSetterFunction)
1262 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(errorInstanceSpace, destructibleObjectHeapCellType.get(), ErrorInstance)
1263 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(nativeStdFunctionSpace, cellHeapCellType.get(), JSNativeStdFunction)
1264 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(proxyRevokeSpace, destructibleObjectHeapCellType.get(), ProxyRevoke)
1265 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(weakMapSpace, destructibleObjectHeapCellType.get(), JSWeakMap)
1266 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(weakSetSpace, destructibleObjectHeapCellType.get(), JSWeakSet)
1267 #if JSC_OBJC_API_ENABLED
1268 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(objCCallbackFunctionSpace, destructibleObjectHeapCellType.get(), ObjCCallbackFunction)
1269 #endif
1270 #if ENABLE(WEBASSEMBLY)
1271 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(webAssemblyCodeBlockSpace, webAssemblyCodeBlockHeapCellType.get(), JSWebAssemblyCodeBlock)
1272 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(webAssemblyFunctionSpace, cellHeapCellType.get(), WebAssemblyFunction)
1273 DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW(webAssemblyWrapperFunctionSpace, cellHeapCellType.get(), WebAssemblyWrapperFunction)
1274 #endif
1275
1276 #undef DYNAMIC_ISO_SUBSPACE_DEFINE_MEMBER_SLOW
1277
1278 #define DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER_SLOW(name, heapCellType, type) \
1279     IsoSubspace* VM::name##Slow() \
1280     { \
1281         ASSERT(!m_##name); \
1282         auto space = std::make_unique<SpaceAndSet> ISO_SUBSPACE_INIT(heap, heapCellType, type); \
1283         WTF::storeStoreFence(); \
1284         m_##name = WTFMove(space); \
1285         return &m_##name->space; \
1286     }
1287
1288 DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER_SLOW(inferredValueSpace, destructibleCellHeapCellType.get(), InferredValue)
1289 DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER_SLOW(evalExecutableSpace, destructibleCellHeapCellType.get(), EvalExecutable)
1290 DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER_SLOW(moduleProgramExecutableSpace, destructibleCellHeapCellType.get(), ModuleProgramExecutable)
1291
1292 #undef DYNAMIC_SPACE_AND_SET_DEFINE_MEMBER_SLOW
1293
1294
1295 JSCell* VM::sentinelSetBucketSlow()
1296 {
1297     ASSERT(!m_sentinelSetBucket);
1298     auto* sentinel = JSSet::BucketType::createSentinel(*this);
1299     m_sentinelSetBucket.set(*this, sentinel);
1300     return sentinel;
1301 }
1302
1303 JSCell* VM::sentinelMapBucketSlow()
1304 {
1305     ASSERT(!m_sentinelMapBucket);
1306     auto* sentinel = JSMap::BucketType::createSentinel(*this);
1307     m_sentinelMapBucket.set(*this, sentinel);
1308     return sentinel;
1309 }
1310
1311 JSGlobalObject* VM::vmEntryGlobalObject(const CallFrame* callFrame) const
1312 {
1313     if (callFrame && callFrame->isGlobalExec()) {
1314         ASSERT(callFrame->callee().isCell() && callFrame->callee().asCell()->isObject());
1315         ASSERT(callFrame == callFrame->lexicalGlobalObject()->globalExec());
1316         return callFrame->lexicalGlobalObject();
1317     }
1318     ASSERT(entryScope);
1319     return entryScope->globalObject();
1320 }
1321
1322 void VM::setCrashOnVMCreation(bool shouldCrash)
1323 {
1324     vmCreationShouldCrash = shouldCrash;
1325 }
1326
1327 } // namespace JSC