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