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