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