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