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