[JSC] Use IsoSpace for JSWeakMap and JSWeakSet to use finalizeUnconditionally
[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         std::chrono::milliseconds timeoutMillis(Options::watchdog());
422         Watchdog& watchdog = ensureWatchdog();
423         watchdog.setTimeLimit(timeoutMillis);
424     }
425
426     // Make sure that any stubs that the JIT is going to use are initialized in non-compilation threads.
427     getCTIInternalFunctionTrampolineFor(CodeForCall);
428     getCTIInternalFunctionTrampolineFor(CodeForConstruct);
429
430     VMInspector::instance().add(this);
431 }
432
433 static StaticReadWriteLock s_destructionLock;
434
435 void waitForVMDestruction()
436 {
437     auto locker = holdLock(s_destructionLock.write());
438 }
439
440 VM::~VM()
441 {
442     auto destructionLocker = holdLock(s_destructionLock.read());
443     
444     Gigacage::removePrimitiveDisableCallback(primitiveGigacageDisabledCallback, this);
445     promiseDeferredTimer->stopRunningTasks();
446 #if ENABLE(WEBASSEMBLY)
447     if (Wasm::existingWorklistOrNull())
448         Wasm::ensureWorklist().stopAllPlansForContext(wasmContext);
449 #endif
450     if (UNLIKELY(m_watchdog))
451         m_watchdog->willDestroyVM(this);
452     m_traps.willDestroyVM();
453     VMInspector::instance().remove(this);
454
455     // Never GC, ever again.
456     heap.incrementDeferralDepth();
457
458 #if ENABLE(SAMPLING_PROFILER)
459     if (m_samplingProfiler) {
460         m_samplingProfiler->reportDataToOptionFile();
461         m_samplingProfiler->shutdown();
462     }
463 #endif // ENABLE(SAMPLING_PROFILER)
464     
465 #if ENABLE(JIT)
466     JITWorklist::instance()->completeAllForVM(*this);
467 #endif // ENABLE(JIT)
468
469 #if ENABLE(DFG_JIT)
470     // Make sure concurrent compilations are done, but don't install them, since there is
471     // no point to doing so.
472     for (unsigned i = DFG::numberOfWorklists(); i--;) {
473         if (DFG::Worklist* worklist = DFG::existingWorklistForIndexOrNull(i)) {
474             worklist->removeNonCompilingPlansForVM(*this);
475             worklist->waitUntilAllPlansForVMAreReady(*this);
476             worklist->removeAllReadyPlansForVM(*this);
477         }
478     }
479 #endif // ENABLE(DFG_JIT)
480     
481     waitForAsynchronousDisassembly();
482     
483     // Clear this first to ensure that nobody tries to remove themselves from it.
484     m_perBytecodeProfiler = nullptr;
485
486     ASSERT(currentThreadIsHoldingAPILock());
487     m_apiLock->willDestroyVM(this);
488     heap.lastChanceToFinalize();
489
490     delete interpreter;
491 #ifndef NDEBUG
492     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
493 #endif
494
495     delete emptyList;
496
497     delete propertyNames;
498     if (vmType != Default)
499         delete m_atomicStringTable;
500
501     delete clientData;
502     delete m_regExpCache;
503 #if ENABLE(REGEXP_TRACING)
504     delete m_rtTraceList;
505 #endif
506
507 #if ENABLE(DFG_JIT)
508     for (unsigned i = 0; i < m_scratchBuffers.size(); ++i)
509         fastFree(m_scratchBuffers[i]);
510 #endif
511 }
512
513 void VM::primitiveGigacageDisabledCallback(void* argument)
514 {
515     static_cast<VM*>(argument)->primitiveGigacageDisabled();
516 }
517
518 void VM::primitiveGigacageDisabled()
519 {
520     if (m_apiLock->currentThreadIsHoldingLock()) {
521         m_primitiveGigacageEnabled.fireAll(*this, "Primitive gigacage disabled");
522         return;
523     }
524  
525     // This is totally racy, and that's OK. The point is, it's up to the user to ensure that they pass the
526     // uncaged buffer in a nicely synchronized manner.
527     m_needToFirePrimitiveGigacageEnabled = true;
528 }
529
530 void VM::setLastStackTop(void* lastStackTop)
531
532     m_lastStackTop = lastStackTop;
533 }
534
535 Ref<VM> VM::createContextGroup(HeapType heapType)
536 {
537     return adoptRef(*new VM(APIContextGroup, heapType));
538 }
539
540 Ref<VM> VM::create(HeapType heapType)
541 {
542     return adoptRef(*new VM(Default, heapType));
543 }
544
545 Ref<VM> VM::createLeaked(HeapType heapType)
546 {
547     return create(heapType);
548 }
549
550 bool VM::sharedInstanceExists()
551 {
552     return sharedInstanceInternal();
553 }
554
555 VM& VM::sharedInstance()
556 {
557     GlobalJSLock globalLock;
558     VM*& instance = sharedInstanceInternal();
559     if (!instance)
560         instance = adoptRef(new VM(APIShared, SmallHeap)).leakRef();
561     return *instance;
562 }
563
564 VM*& VM::sharedInstanceInternal()
565 {
566     static VM* sharedInstance;
567     return sharedInstance;
568 }
569
570 Watchdog& VM::ensureWatchdog()
571 {
572     if (!m_watchdog)
573         m_watchdog = adoptRef(new Watchdog(this));
574     return *m_watchdog;
575 }
576
577 HeapProfiler& VM::ensureHeapProfiler()
578 {
579     if (!m_heapProfiler)
580         m_heapProfiler = std::make_unique<HeapProfiler>(*this);
581     return *m_heapProfiler;
582 }
583
584 #if ENABLE(SAMPLING_PROFILER)
585 SamplingProfiler& VM::ensureSamplingProfiler(RefPtr<Stopwatch>&& stopwatch)
586 {
587     if (!m_samplingProfiler)
588         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
589     return *m_samplingProfiler;
590 }
591 #endif // ENABLE(SAMPLING_PROFILER)
592
593 #if ENABLE(JIT)
594 static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
595 {
596     switch (intrinsic) {
597     case CharCodeAtIntrinsic:
598         return charCodeAtThunkGenerator;
599     case CharAtIntrinsic:
600         return charAtThunkGenerator;
601     case Clz32Intrinsic:
602         return clz32ThunkGenerator;
603     case FromCharCodeIntrinsic:
604         return fromCharCodeThunkGenerator;
605     case SqrtIntrinsic:
606         return sqrtThunkGenerator;
607     case AbsIntrinsic:
608         return absThunkGenerator;
609     case FloorIntrinsic:
610         return floorThunkGenerator;
611     case CeilIntrinsic:
612         return ceilThunkGenerator;
613     case TruncIntrinsic:
614         return truncThunkGenerator;
615     case RoundIntrinsic:
616         return roundThunkGenerator;
617     case ExpIntrinsic:
618         return expThunkGenerator;
619     case LogIntrinsic:
620         return logThunkGenerator;
621     case IMulIntrinsic:
622         return imulThunkGenerator;
623     case RandomIntrinsic:
624         return randomThunkGenerator;
625     case BoundThisNoArgsFunctionCallIntrinsic:
626         return boundThisNoArgsFunctionCallGenerator;
627     default:
628         return nullptr;
629     }
630 }
631
632 #endif // ENABLE(JIT)
633
634 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
635 {
636     return getHostFunction(function, NoIntrinsic, constructor, nullptr, name);
637 }
638
639 NativeExecutable* VM::getHostFunction(NativeFunction function, Intrinsic intrinsic, NativeFunction constructor, const DOMJIT::Signature* signature, const String& name)
640 {
641 #if ENABLE(JIT)
642     if (canUseJIT()) {
643         return jitStubs->hostFunctionStub(
644             this, function, constructor,
645             intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0,
646             intrinsic, signature, name);
647     }
648 #else // ENABLE(JIT)
649     UNUSED_PARAM(intrinsic);
650 #endif // ENABLE(JIT)
651     return NativeExecutable::create(*this,
652         adoptRef(*new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_call_trampoline), JITCode::HostCallThunk)), function,
653         adoptRef(*new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_construct_trampoline), JITCode::HostCallThunk)), constructor,
654         NoIntrinsic, signature, name);
655 }
656
657 MacroAssemblerCodePtr VM::getCTIInternalFunctionTrampolineFor(CodeSpecializationKind kind)
658 {
659 #if ENABLE(JIT)
660     if (kind == CodeForCall)
661         return jitStubs->ctiInternalFunctionCall(this);
662     return jitStubs->ctiInternalFunctionConstruct(this);
663 #else
664     if (kind == CodeForCall)
665         return MacroAssemblerCodePtr::createLLIntCodePtr(llint_internal_function_call_trampoline);
666     return MacroAssemblerCodePtr::createLLIntCodePtr(llint_internal_function_construct_trampoline);
667 #endif
668 }
669
670 VM::ClientData::~ClientData()
671 {
672 }
673
674 void VM::resetDateCache()
675 {
676     localTimeOffsetCache.reset();
677     cachedDateString = String();
678     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
679     dateInstanceCache.reset();
680 }
681
682 void VM::whenIdle(std::function<void()> callback)
683 {
684     if (!entryScope) {
685         callback();
686         return;
687     }
688
689     entryScope->addDidPopListener(callback);
690 }
691
692 void VM::deleteAllLinkedCode(DeleteAllCodeEffort effort)
693 {
694     whenIdle([=] () {
695         heap.deleteAllCodeBlocks(effort);
696     });
697 }
698
699 void VM::deleteAllCode(DeleteAllCodeEffort effort)
700 {
701     whenIdle([=] () {
702         m_codeCache->clear();
703         m_regExpCache->deleteAllCode();
704         heap.deleteAllCodeBlocks(effort);
705         heap.deleteAllUnlinkedCodeBlocks(effort);
706         heap.reportAbandonedObjectGraph();
707     });
708 }
709
710 SourceProviderCache* VM::addSourceProviderCache(SourceProvider* sourceProvider)
711 {
712     auto addResult = sourceProviderCacheMap.add(sourceProvider, nullptr);
713     if (addResult.isNewEntry)
714         addResult.iterator->value = adoptRef(new SourceProviderCache);
715     return addResult.iterator->value.get();
716 }
717
718 void VM::clearSourceProviderCaches()
719 {
720     sourceProviderCacheMap.clear();
721 }
722
723 void VM::throwException(ExecState* exec, Exception* exception)
724 {
725     if (Options::breakOnThrow()) {
726         CodeBlock* codeBlock = exec->codeBlock();
727         dataLog("Throwing exception in call frame ", RawPointer(exec), " for code block ", codeBlock, "\n");
728         CRASH();
729     }
730
731     ASSERT(exec == topCallFrame || exec == exec->lexicalGlobalObject()->globalExec() || exec == exec->vmEntryGlobalObject()->globalExec());
732
733     interpreter->notifyDebuggerOfExceptionToBeThrown(*this, exec, exception);
734
735     setException(exception);
736
737 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
738     m_nativeStackTraceOfLastThrow = StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit());
739     m_throwingThread = &Thread::current();
740 #endif
741 }
742
743 JSValue VM::throwException(ExecState* exec, JSValue thrownValue)
744 {
745     VM& vm = *this;
746     Exception* exception = jsDynamicCast<Exception*>(vm, thrownValue);
747     if (!exception)
748         exception = Exception::create(*this, thrownValue);
749
750     throwException(exec, exception);
751     return JSValue(exception);
752 }
753
754 JSObject* VM::throwException(ExecState* exec, JSObject* error)
755 {
756     return asObject(throwException(exec, JSValue(error)));
757 }
758
759 void VM::setStackPointerAtVMEntry(void* sp)
760 {
761     m_stackPointerAtVMEntry = sp;
762     updateStackLimits();
763 }
764
765 size_t VM::updateSoftReservedZoneSize(size_t softReservedZoneSize)
766 {
767     size_t oldSoftReservedZoneSize = m_currentSoftReservedZoneSize;
768     m_currentSoftReservedZoneSize = softReservedZoneSize;
769 #if !ENABLE(JIT)
770     interpreter->cloopStack().setSoftReservedZoneSize(softReservedZoneSize);
771 #endif
772
773     updateStackLimits();
774
775     return oldSoftReservedZoneSize;
776 }
777
778 #if OS(WINDOWS)
779 // On Windows the reserved stack space consists of committed memory, a guard page, and uncommitted memory,
780 // where the guard page is a barrier between committed and uncommitted memory.
781 // When data from the guard page is read or written, the guard page is moved, and memory is committed.
782 // This is how the system grows the stack.
783 // When using the C stack on Windows we need to precommit the needed stack space.
784 // Otherwise we might crash later if we access uncommitted stack memory.
785 // This can happen if we allocate stack space larger than the page guard size (4K).
786 // The system does not get the chance to move the guard page, and commit more memory,
787 // and we crash if uncommitted memory is accessed.
788 // The MSVC compiler fixes this by inserting a call to the _chkstk() function,
789 // when needed, see http://support.microsoft.com/kb/100775.
790 // By touching every page up to the stack limit with a dummy operation,
791 // we force the system to move the guard page, and commit memory.
792
793 static void preCommitStackMemory(void* stackLimit)
794 {
795     const int pageSize = 4096;
796     for (volatile char* p = reinterpret_cast<char*>(&stackLimit); p > stackLimit; p -= pageSize) {
797         char ch = *p;
798         *p = ch;
799     }
800 }
801 #endif
802
803 inline void VM::updateStackLimits()
804 {
805 #if OS(WINDOWS)
806     void* lastSoftStackLimit = m_softStackLimit;
807 #endif
808
809     const StackBounds& stack = Thread::current().stack();
810     size_t reservedZoneSize = Options::reservedZoneSize();
811     // We should have already ensured that Options::reservedZoneSize() >= minimumReserveZoneSize at
812     // options initialization time, and the option value should not have been changed thereafter.
813     // We don't have the ability to assert here that it hasn't changed, but we can at least assert
814     // that the value is sane.
815     RELEASE_ASSERT(reservedZoneSize >= minimumReservedZoneSize);
816
817     if (m_stackPointerAtVMEntry) {
818         ASSERT(stack.isGrowingDownward());
819         char* startOfStack = reinterpret_cast<char*>(m_stackPointerAtVMEntry);
820         m_softStackLimit = stack.recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_currentSoftReservedZoneSize);
821         m_stackLimit = stack.recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), reservedZoneSize);
822     } else {
823         m_softStackLimit = stack.recursionLimit(m_currentSoftReservedZoneSize);
824         m_stackLimit = stack.recursionLimit(reservedZoneSize);
825     }
826
827 #if OS(WINDOWS)
828     // We only need to precommit stack memory dictated by the VM::m_softStackLimit limit.
829     // This is because VM::m_softStackLimit applies to stack usage by LLINT asm or JIT
830     // generated code which can allocate stack space that the C++ compiler does not know
831     // about. As such, we have to precommit that stack memory manually.
832     //
833     // In contrast, we do not need to worry about VM::m_stackLimit because that limit is
834     // used exclusively by C++ code, and the C++ compiler will automatically commit the
835     // needed stack pages.
836     if (lastSoftStackLimit != m_softStackLimit)
837         preCommitStackMemory(m_softStackLimit);
838 #endif
839 }
840
841 #if ENABLE(DFG_JIT)
842 void VM::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
843 {
844     auto lock = holdLock(m_scratchBufferLock);
845     for (auto* scratchBuffer : m_scratchBuffers) {
846         if (scratchBuffer->activeLength()) {
847             void* bufferStart = scratchBuffer->dataBuffer();
848             conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
849         }
850     }
851 }
852 #endif
853
854 void logSanitizeStack(VM* vm)
855 {
856     if (Options::verboseSanitizeStack() && vm->topCallFrame) {
857         int dummy;
858         auto& stackBounds = Thread::current().stack();
859         dataLog(
860             "Sanitizing stack for VM = ", RawPointer(vm), " with top call frame at ", RawPointer(vm->topCallFrame),
861             ", current stack pointer at ", RawPointer(&dummy), ", in ",
862             pointerDump(vm->topCallFrame->codeBlock()), ", last code origin = ",
863             vm->topCallFrame->codeOrigin(), ", last stack top = ", RawPointer(vm->lastStackTop()), ", in stack range [", RawPointer(stackBounds.origin()), ", ", RawPointer(stackBounds.end()), "]\n");
864     }
865 }
866
867 #if ENABLE(REGEXP_TRACING)
868 void VM::addRegExpToTrace(RegExp* regExp)
869 {
870     gcProtect(regExp);
871     m_rtTraceList->add(regExp);
872 }
873
874 void VM::dumpRegExpTrace()
875 {
876     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
877     RTTraceList::iterator iter = ++m_rtTraceList->begin();
878     
879     if (iter != m_rtTraceList->end()) {
880         dataLogF("\nRegExp Tracing\n");
881         dataLogF("Regular Expression                              8 Bit          16 Bit        match()    Matches    Average\n");
882         dataLogF(" <Match only / Match>                         JIT Addr      JIT Address       calls      found   String len\n");
883         dataLogF("----------------------------------------+----------------+----------------+----------+----------+-----------\n");
884     
885         unsigned reCount = 0;
886     
887         for (; iter != m_rtTraceList->end(); ++iter, ++reCount) {
888             (*iter)->printTraceData();
889             gcUnprotect(*iter);
890         }
891
892         dataLogF("%d Regular Expressions\n", reCount);
893     }
894     
895     m_rtTraceList->clear();
896 }
897 #else
898 void VM::dumpRegExpTrace()
899 {
900 }
901 #endif
902
903 WatchpointSet* VM::ensureWatchpointSetForImpureProperty(const Identifier& propertyName)
904 {
905     auto result = m_impurePropertyWatchpointSets.add(propertyName.string(), nullptr);
906     if (result.isNewEntry)
907         result.iterator->value = adoptRef(new WatchpointSet(IsWatched));
908     return result.iterator->value.get();
909 }
910
911 void VM::registerWatchpointForImpureProperty(const Identifier& propertyName, Watchpoint* watchpoint)
912 {
913     ensureWatchpointSetForImpureProperty(propertyName)->add(watchpoint);
914 }
915
916 void VM::addImpureProperty(const String& propertyName)
917 {
918     if (RefPtr<WatchpointSet> watchpointSet = m_impurePropertyWatchpointSets.take(propertyName))
919         watchpointSet->fireAll(*this, "Impure property added");
920 }
921
922 static bool enableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doEnableWork)
923 {
924     bool needsToRecompile = false;
925     if (!counter) {
926         doEnableWork();
927         needsToRecompile = true;
928     }
929     counter++;
930
931     return needsToRecompile;
932 }
933
934 static bool disableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doDisableWork)
935 {
936     RELEASE_ASSERT(counter > 0);
937     bool needsToRecompile = false;
938     counter--;
939     if (!counter) {
940         doDisableWork();
941         needsToRecompile = true;
942     }
943
944     return needsToRecompile;
945 }
946
947 bool VM::enableTypeProfiler()
948 {
949     auto enableTypeProfiler = [this] () {
950         this->m_typeProfiler = std::make_unique<TypeProfiler>();
951         this->m_typeProfilerLog = std::make_unique<TypeProfilerLog>();
952     };
953
954     return enableProfilerWithRespectToCount(m_typeProfilerEnabledCount, enableTypeProfiler);
955 }
956
957 bool VM::disableTypeProfiler()
958 {
959     auto disableTypeProfiler = [this] () {
960         this->m_typeProfiler.reset(nullptr);
961         this->m_typeProfilerLog.reset(nullptr);
962     };
963
964     return disableProfilerWithRespectToCount(m_typeProfilerEnabledCount, disableTypeProfiler);
965 }
966
967 bool VM::enableControlFlowProfiler()
968 {
969     auto enableControlFlowProfiler = [this] () {
970         this->m_controlFlowProfiler = std::make_unique<ControlFlowProfiler>();
971     };
972
973     return enableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, enableControlFlowProfiler);
974 }
975
976 bool VM::disableControlFlowProfiler()
977 {
978     auto disableControlFlowProfiler = [this] () {
979         this->m_controlFlowProfiler.reset(nullptr);
980     };
981
982     return disableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, disableControlFlowProfiler);
983 }
984
985 void VM::dumpTypeProfilerData()
986 {
987     if (!typeProfiler())
988         return;
989
990     typeProfilerLog()->processLogEntries(ASCIILiteral("VM Dump Types"));
991     typeProfiler()->dumpTypeProfilerData(*this);
992 }
993
994 void VM::queueMicrotask(JSGlobalObject& globalObject, Ref<Microtask>&& task)
995 {
996     m_microtaskQueue.append(std::make_unique<QueuedTask>(*this, &globalObject, WTFMove(task)));
997 }
998
999 void VM::drainMicrotasks()
1000 {
1001     while (!m_microtaskQueue.isEmpty())
1002         m_microtaskQueue.takeFirst()->run();
1003 }
1004
1005 void QueuedTask::run()
1006 {
1007     m_microtask->run(m_globalObject->globalExec());
1008 }
1009
1010 void sanitizeStackForVM(VM* vm)
1011 {
1012     logSanitizeStack(vm);
1013     if (vm->topCallFrame) {
1014         auto& stackBounds = Thread::current().stack();
1015         ASSERT(vm->currentThreadIsHoldingAPILock());
1016         ASSERT_UNUSED(stackBounds, stackBounds.contains(vm->lastStackTop()));
1017     }
1018 #if !ENABLE(JIT)
1019     vm->interpreter->cloopStack().sanitizeStack();
1020 #else
1021     sanitizeStackForVMImpl(vm);
1022 #endif
1023 }
1024
1025 size_t VM::committedStackByteCount()
1026 {
1027 #if ENABLE(JIT)
1028     // When using the C stack, we don't know how many stack pages are actually
1029     // committed. So, we use the current stack usage as an estimate.
1030     ASSERT(Thread::current().stack().isGrowingDownward());
1031     int8_t* current = reinterpret_cast<int8_t*>(&current);
1032     int8_t* high = reinterpret_cast<int8_t*>(Thread::current().stack().origin());
1033     return high - current;
1034 #else
1035     return CLoopStack::committedByteCount();
1036 #endif
1037 }
1038
1039 #if !ENABLE(JIT)
1040 bool VM::ensureStackCapacityForCLoop(Register* newTopOfStack)
1041 {
1042     return interpreter->cloopStack().ensureCapacityFor(newTopOfStack);
1043 }
1044
1045 bool VM::isSafeToRecurseSoftCLoop() const
1046 {
1047     return interpreter->cloopStack().isSafeToRecurse();
1048 }
1049 #endif // !ENABLE(JIT)
1050
1051 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
1052 void VM::verifyExceptionCheckNeedIsSatisfied(unsigned recursionDepth, ExceptionEventLocation& location)
1053 {
1054     if (!Options::validateExceptionChecks())
1055         return;
1056
1057     if (UNLIKELY(m_needExceptionCheck)) {
1058         auto throwDepth = m_simulatedThrowPointRecursionDepth;
1059         auto& throwLocation = m_simulatedThrowPointLocation;
1060
1061         dataLog(
1062             "ERROR: Unchecked JS exception:\n"
1063             "    This scope can throw a JS exception: ", throwLocation, "\n"
1064             "        (ExceptionScope::m_recursionDepth was ", throwDepth, ")\n"
1065             "    But the exception was unchecked as of this scope: ", location, "\n"
1066             "        (ExceptionScope::m_recursionDepth was ", recursionDepth, ")\n"
1067             "\n");
1068
1069         StringPrintStream out;
1070         std::unique_ptr<StackTrace> currentTrace = StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit());
1071
1072         if (Options::dumpSimulatedThrows()) {
1073             out.println("The simulated exception was thrown at:");
1074             m_nativeStackTraceOfLastSimulatedThrow->dump(out, "    ");
1075             out.println();
1076         }
1077         out.println("Unchecked exception detected at:");
1078         currentTrace->dump(out, "    ");
1079         out.println();
1080
1081         dataLog(out.toCString());
1082         RELEASE_ASSERT(!m_needExceptionCheck);
1083     }
1084 }
1085 #endif
1086
1087 #if USE(CF)
1088 void VM::registerRunLoopTimer(JSRunLoopTimer* timer)
1089 {
1090     ASSERT(runLoop());
1091     ASSERT(!m_runLoopTimers.contains(timer));
1092     m_runLoopTimers.add(timer);
1093     timer->setRunLoop(runLoop());
1094 }
1095
1096 void VM::unregisterRunLoopTimer(JSRunLoopTimer* timer)
1097 {
1098     ASSERT(m_runLoopTimers.contains(timer));
1099     m_runLoopTimers.remove(timer);
1100     timer->setRunLoop(nullptr);
1101 }
1102
1103 void VM::setRunLoop(CFRunLoopRef runLoop)
1104 {
1105     ASSERT(runLoop);
1106     m_runLoop = runLoop;
1107     for (auto timer : m_runLoopTimers)
1108         timer->setRunLoop(runLoop);
1109 }
1110 #endif // USE(CF)
1111
1112 ScratchBuffer* VM::scratchBufferForSize(size_t size)
1113 {
1114     if (!size)
1115         return nullptr;
1116
1117     auto locker = holdLock(m_scratchBufferLock);
1118
1119     if (size > m_sizeOfLastScratchBuffer) {
1120         // Protect against a N^2 memory usage pathology by ensuring
1121         // that at worst, we get a geometric series, meaning that the
1122         // total memory usage is somewhere around
1123         // max(scratch buffer size) * 4.
1124         m_sizeOfLastScratchBuffer = size * 2;
1125
1126         ScratchBuffer* newBuffer = ScratchBuffer::create(m_sizeOfLastScratchBuffer);
1127         RELEASE_ASSERT(newBuffer);
1128         m_scratchBuffers.append(newBuffer);
1129     }
1130
1131     ScratchBuffer* result = m_scratchBuffers.last();
1132     return result;
1133 }
1134
1135 } // namespace JSC