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