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