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