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