[JSC] Check TypeInfo first before calling getCallData when we would like to check...
[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     if (!canUseJIT())
494         noJITValueProfileSingleton = std::make_unique<ValueProfile>(0);
495
496     VMInspector::instance().add(this);
497 }
498
499 static ReadWriteLock s_destructionLock;
500
501 void waitForVMDestruction()
502 {
503     auto locker = holdLock(s_destructionLock.write());
504 }
505
506 VM::~VM()
507 {
508     auto destructionLocker = holdLock(s_destructionLock.read());
509     
510     Gigacage::removePrimitiveDisableCallback(primitiveGigacageDisabledCallback, this);
511     promiseDeferredTimer->stopRunningTasks();
512 #if ENABLE(WEBASSEMBLY)
513     if (Wasm::existingWorklistOrNull())
514         Wasm::ensureWorklist().stopAllPlansForContext(wasmContext);
515 #endif
516     if (UNLIKELY(m_watchdog))
517         m_watchdog->willDestroyVM(this);
518     m_traps.willDestroyVM();
519     VMInspector::instance().remove(this);
520
521     // Never GC, ever again.
522     heap.incrementDeferralDepth();
523
524 #if ENABLE(SAMPLING_PROFILER)
525     if (m_samplingProfiler) {
526         m_samplingProfiler->reportDataToOptionFile();
527         m_samplingProfiler->shutdown();
528     }
529 #endif // ENABLE(SAMPLING_PROFILER)
530     
531 #if ENABLE(JIT)
532     JITWorklist::instance()->completeAllForVM(*this);
533 #endif // ENABLE(JIT)
534
535 #if ENABLE(DFG_JIT)
536     // Make sure concurrent compilations are done, but don't install them, since there is
537     // no point to doing so.
538     for (unsigned i = DFG::numberOfWorklists(); i--;) {
539         if (DFG::Worklist* worklist = DFG::existingWorklistForIndexOrNull(i)) {
540             worklist->removeNonCompilingPlansForVM(*this);
541             worklist->waitUntilAllPlansForVMAreReady(*this);
542             worklist->removeAllReadyPlansForVM(*this);
543         }
544     }
545 #endif // ENABLE(DFG_JIT)
546     
547     waitForAsynchronousDisassembly();
548     
549     // Clear this first to ensure that nobody tries to remove themselves from it.
550     m_perBytecodeProfiler = nullptr;
551
552     ASSERT(currentThreadIsHoldingAPILock());
553     m_apiLock->willDestroyVM(this);
554     heap.lastChanceToFinalize();
555     
556 #if !USE(FAST_TLS_FOR_TLC)
557     ThreadLocalCache::destructor(threadLocalCacheData);
558 #endif
559
560     delete interpreter;
561 #ifndef NDEBUG
562     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
563 #endif
564
565     delete emptyList;
566
567     delete propertyNames;
568     if (vmType != Default)
569         delete m_atomicStringTable;
570
571     delete clientData;
572     delete m_regExpCache;
573
574 #if ENABLE(REGEXP_TRACING)
575     delete m_rtTraceList;
576 #endif
577
578 #if ENABLE(DFG_JIT)
579     for (unsigned i = 0; i < m_scratchBuffers.size(); ++i)
580         fastFree(m_scratchBuffers[i]);
581 #endif
582 }
583
584 void VM::primitiveGigacageDisabledCallback(void* argument)
585 {
586     static_cast<VM*>(argument)->primitiveGigacageDisabled();
587 }
588
589 void VM::primitiveGigacageDisabled()
590 {
591     if (m_apiLock->currentThreadIsHoldingLock()) {
592         m_primitiveGigacageEnabled.fireAll(*this, "Primitive gigacage disabled");
593         return;
594     }
595  
596     // This is totally racy, and that's OK. The point is, it's up to the user to ensure that they pass the
597     // uncaged buffer in a nicely synchronized manner.
598     m_needToFirePrimitiveGigacageEnabled = true;
599 }
600
601 void VM::setLastStackTop(void* lastStackTop)
602
603     m_lastStackTop = lastStackTop;
604 }
605
606 Ref<VM> VM::createContextGroup(HeapType heapType)
607 {
608     return adoptRef(*new VM(APIContextGroup, heapType));
609 }
610
611 Ref<VM> VM::create(HeapType heapType)
612 {
613     return adoptRef(*new VM(Default, heapType));
614 }
615
616 bool VM::sharedInstanceExists()
617 {
618     return sharedInstanceInternal();
619 }
620
621 VM& VM::sharedInstance()
622 {
623     GlobalJSLock globalLock;
624     VM*& instance = sharedInstanceInternal();
625     if (!instance)
626         instance = adoptRef(new VM(APIShared, SmallHeap)).leakRef();
627     return *instance;
628 }
629
630 VM*& VM::sharedInstanceInternal()
631 {
632     static VM* sharedInstance;
633     return sharedInstance;
634 }
635
636 Watchdog& VM::ensureWatchdog()
637 {
638     if (!m_watchdog)
639         m_watchdog = adoptRef(new Watchdog(this));
640     return *m_watchdog;
641 }
642
643 HeapProfiler& VM::ensureHeapProfiler()
644 {
645     if (!m_heapProfiler)
646         m_heapProfiler = std::make_unique<HeapProfiler>(*this);
647     return *m_heapProfiler;
648 }
649
650 #if ENABLE(SAMPLING_PROFILER)
651 SamplingProfiler& VM::ensureSamplingProfiler(RefPtr<Stopwatch>&& stopwatch)
652 {
653     if (!m_samplingProfiler)
654         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
655     return *m_samplingProfiler;
656 }
657 #endif // ENABLE(SAMPLING_PROFILER)
658
659 #if ENABLE(JIT)
660 static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
661 {
662     switch (intrinsic) {
663     case CharCodeAtIntrinsic:
664         return charCodeAtThunkGenerator;
665     case CharAtIntrinsic:
666         return charAtThunkGenerator;
667     case Clz32Intrinsic:
668         return clz32ThunkGenerator;
669     case FromCharCodeIntrinsic:
670         return fromCharCodeThunkGenerator;
671     case SqrtIntrinsic:
672         return sqrtThunkGenerator;
673     case AbsIntrinsic:
674         return absThunkGenerator;
675     case FloorIntrinsic:
676         return floorThunkGenerator;
677     case CeilIntrinsic:
678         return ceilThunkGenerator;
679     case TruncIntrinsic:
680         return truncThunkGenerator;
681     case RoundIntrinsic:
682         return roundThunkGenerator;
683     case ExpIntrinsic:
684         return expThunkGenerator;
685     case LogIntrinsic:
686         return logThunkGenerator;
687     case IMulIntrinsic:
688         return imulThunkGenerator;
689     case RandomIntrinsic:
690         return randomThunkGenerator;
691     case BoundThisNoArgsFunctionCallIntrinsic:
692         return boundThisNoArgsFunctionCallGenerator;
693     default:
694         return nullptr;
695     }
696 }
697
698 #endif // ENABLE(JIT)
699
700 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
701 {
702     return getHostFunction(function, NoIntrinsic, constructor, nullptr, name);
703 }
704
705 NativeExecutable* VM::getHostFunction(NativeFunction function, Intrinsic intrinsic, NativeFunction constructor, const DOMJIT::Signature* signature, const String& name)
706 {
707 #if ENABLE(JIT)
708     if (canUseJIT()) {
709         return jitStubs->hostFunctionStub(
710             this, function, constructor,
711             intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0,
712             intrinsic, signature, name);
713     }
714 #else // ENABLE(JIT)
715     UNUSED_PARAM(intrinsic);
716 #endif // ENABLE(JIT)
717     return NativeExecutable::create(*this,
718         adoptRef(*new NativeJITCode(LLInt::getCodeRef<JSEntryPtrTag>(llint_native_call_trampoline), JITCode::HostCallThunk)), function,
719         adoptRef(*new NativeJITCode(LLInt::getCodeRef<JSEntryPtrTag>(llint_native_construct_trampoline), JITCode::HostCallThunk)), constructor,
720         NoIntrinsic, signature, name);
721 }
722
723 MacroAssemblerCodePtr<JSEntryPtrTag> VM::getCTIInternalFunctionTrampolineFor(CodeSpecializationKind kind)
724 {
725 #if ENABLE(JIT)
726     if (canUseJIT()) {
727         if (kind == CodeForCall)
728             return jitStubs->ctiInternalFunctionCall(this).retagged<JSEntryPtrTag>();
729         return jitStubs->ctiInternalFunctionConstruct(this).retagged<JSEntryPtrTag>();
730     }
731 #endif
732     if (kind == CodeForCall)
733         return LLInt::getCodePtr<JSEntryPtrTag>(llint_internal_function_call_trampoline);
734     return LLInt::getCodePtr<JSEntryPtrTag>(llint_internal_function_construct_trampoline);
735 }
736
737 VM::ClientData::~ClientData()
738 {
739 }
740
741 void VM::resetDateCache()
742 {
743     localTimeOffsetCache.reset();
744     cachedDateString = String();
745     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
746     dateInstanceCache.reset();
747 }
748
749 void VM::whenIdle(std::function<void()> callback)
750 {
751     if (!entryScope) {
752         callback();
753         return;
754     }
755
756     entryScope->addDidPopListener(callback);
757 }
758
759 void VM::deleteAllLinkedCode(DeleteAllCodeEffort effort)
760 {
761     whenIdle([=] () {
762         heap.deleteAllCodeBlocks(effort);
763     });
764 }
765
766 void VM::deleteAllCode(DeleteAllCodeEffort effort)
767 {
768     whenIdle([=] () {
769         m_codeCache->clear();
770         m_regExpCache->deleteAllCode();
771         heap.deleteAllCodeBlocks(effort);
772         heap.deleteAllUnlinkedCodeBlocks(effort);
773         heap.reportAbandonedObjectGraph();
774     });
775 }
776
777 void VM::shrinkFootprint()
778 {
779     sanitizeStackForVM(this);
780     deleteAllCode(DeleteAllCodeIfNotCollecting);
781     heap.collectSync();
782     WTF::releaseFastMallocFreeMemory();
783     // FIXME: Consider stopping various automatic threads here.
784     // https://bugs.webkit.org/show_bug.cgi?id=185447
785 }
786
787 SourceProviderCache* VM::addSourceProviderCache(SourceProvider* sourceProvider)
788 {
789     auto addResult = sourceProviderCacheMap.add(sourceProvider, nullptr);
790     if (addResult.isNewEntry)
791         addResult.iterator->value = adoptRef(new SourceProviderCache);
792     return addResult.iterator->value.get();
793 }
794
795 void VM::clearSourceProviderCaches()
796 {
797     sourceProviderCacheMap.clear();
798 }
799
800 void VM::throwException(ExecState* exec, Exception* exception)
801 {
802     if (Options::breakOnThrow()) {
803         CodeBlock* codeBlock = exec->codeBlock();
804         dataLog("Throwing exception in call frame ", RawPointer(exec), " for code block ", codeBlock, "\n");
805         CRASH();
806     }
807
808     ASSERT(exec == topCallFrame || exec == exec->lexicalGlobalObject()->globalExec() || exec == exec->vmEntryGlobalObject()->globalExec());
809
810     interpreter->notifyDebuggerOfExceptionToBeThrown(*this, exec, exception);
811
812     setException(exception);
813
814 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
815     m_nativeStackTraceOfLastThrow = StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit());
816     m_throwingThread = &Thread::current();
817 #endif
818 }
819
820 JSValue VM::throwException(ExecState* exec, JSValue thrownValue)
821 {
822     VM& vm = *this;
823     Exception* exception = jsDynamicCast<Exception*>(vm, thrownValue);
824     if (!exception)
825         exception = Exception::create(*this, thrownValue);
826
827     throwException(exec, exception);
828     return JSValue(exception);
829 }
830
831 JSObject* VM::throwException(ExecState* exec, JSObject* error)
832 {
833     return asObject(throwException(exec, JSValue(error)));
834 }
835
836 void VM::setStackPointerAtVMEntry(void* sp)
837 {
838     m_stackPointerAtVMEntry = sp;
839     updateStackLimits();
840 }
841
842 size_t VM::updateSoftReservedZoneSize(size_t softReservedZoneSize)
843 {
844     size_t oldSoftReservedZoneSize = m_currentSoftReservedZoneSize;
845     m_currentSoftReservedZoneSize = softReservedZoneSize;
846 #if !ENABLE(JIT)
847     interpreter->cloopStack().setSoftReservedZoneSize(softReservedZoneSize);
848 #endif
849
850     updateStackLimits();
851
852     return oldSoftReservedZoneSize;
853 }
854
855 #if OS(WINDOWS)
856 // On Windows the reserved stack space consists of committed memory, a guard page, and uncommitted memory,
857 // where the guard page is a barrier between committed and uncommitted memory.
858 // When data from the guard page is read or written, the guard page is moved, and memory is committed.
859 // This is how the system grows the stack.
860 // When using the C stack on Windows we need to precommit the needed stack space.
861 // Otherwise we might crash later if we access uncommitted stack memory.
862 // This can happen if we allocate stack space larger than the page guard size (4K).
863 // The system does not get the chance to move the guard page, and commit more memory,
864 // and we crash if uncommitted memory is accessed.
865 // The MSVC compiler fixes this by inserting a call to the _chkstk() function,
866 // when needed, see http://support.microsoft.com/kb/100775.
867 // By touching every page up to the stack limit with a dummy operation,
868 // we force the system to move the guard page, and commit memory.
869
870 static void preCommitStackMemory(void* stackLimit)
871 {
872     const int pageSize = 4096;
873     for (volatile char* p = reinterpret_cast<char*>(&stackLimit); p > stackLimit; p -= pageSize) {
874         char ch = *p;
875         *p = ch;
876     }
877 }
878 #endif
879
880 inline void VM::updateStackLimits()
881 {
882 #if OS(WINDOWS)
883     void* lastSoftStackLimit = m_softStackLimit;
884 #endif
885
886     const StackBounds& stack = Thread::current().stack();
887     size_t reservedZoneSize = Options::reservedZoneSize();
888     // We should have already ensured that Options::reservedZoneSize() >= minimumReserveZoneSize at
889     // options initialization time, and the option value should not have been changed thereafter.
890     // We don't have the ability to assert here that it hasn't changed, but we can at least assert
891     // that the value is sane.
892     RELEASE_ASSERT(reservedZoneSize >= minimumReservedZoneSize);
893
894     if (m_stackPointerAtVMEntry) {
895         ASSERT(stack.isGrowingDownward());
896         char* startOfStack = reinterpret_cast<char*>(m_stackPointerAtVMEntry);
897         m_softStackLimit = stack.recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_currentSoftReservedZoneSize);
898         m_stackLimit = stack.recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), reservedZoneSize);
899     } else {
900         m_softStackLimit = stack.recursionLimit(m_currentSoftReservedZoneSize);
901         m_stackLimit = stack.recursionLimit(reservedZoneSize);
902     }
903
904 #if OS(WINDOWS)
905     // We only need to precommit stack memory dictated by the VM::m_softStackLimit limit.
906     // This is because VM::m_softStackLimit applies to stack usage by LLINT asm or JIT
907     // generated code which can allocate stack space that the C++ compiler does not know
908     // about. As such, we have to precommit that stack memory manually.
909     //
910     // In contrast, we do not need to worry about VM::m_stackLimit because that limit is
911     // used exclusively by C++ code, and the C++ compiler will automatically commit the
912     // needed stack pages.
913     if (lastSoftStackLimit != m_softStackLimit)
914         preCommitStackMemory(m_softStackLimit);
915 #endif
916 }
917
918 #if ENABLE(DFG_JIT)
919 void VM::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
920 {
921     auto lock = holdLock(m_scratchBufferLock);
922     for (auto* scratchBuffer : m_scratchBuffers) {
923         if (scratchBuffer->activeLength()) {
924             void* bufferStart = scratchBuffer->dataBuffer();
925             conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
926         }
927     }
928 }
929 #endif
930
931 void logSanitizeStack(VM* vm)
932 {
933     if (Options::verboseSanitizeStack() && vm->topCallFrame) {
934         int dummy;
935         auto& stackBounds = Thread::current().stack();
936         dataLog(
937             "Sanitizing stack for VM = ", RawPointer(vm), " with top call frame at ", RawPointer(vm->topCallFrame),
938             ", current stack pointer at ", RawPointer(&dummy), ", in ",
939             pointerDump(vm->topCallFrame->codeBlock()), ", last code origin = ",
940             vm->topCallFrame->codeOrigin(), ", last stack top = ", RawPointer(vm->lastStackTop()), ", in stack range [", RawPointer(stackBounds.origin()), ", ", RawPointer(stackBounds.end()), "]\n");
941     }
942 }
943
944 #if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
945 char* VM::acquireRegExpPatternContexBuffer()
946 {
947     m_regExpPatternContextLock.lock();
948     ASSERT(m_regExpPatternContextLock.isLocked());
949     if (!m_regExpPatternContexBuffer)
950         m_regExpPatternContexBuffer = makeUniqueArray<char>(VM::patternContextBufferSize);
951     return m_regExpPatternContexBuffer.get();
952 }
953
954 void VM::releaseRegExpPatternContexBuffer()
955 {
956     ASSERT(m_regExpPatternContextLock.isLocked());
957
958     m_regExpPatternContextLock.unlock();
959 }
960 #endif
961
962 #if ENABLE(REGEXP_TRACING)
963 void VM::addRegExpToTrace(RegExp* regExp)
964 {
965     gcProtect(regExp);
966     m_rtTraceList->add(regExp);
967 }
968
969 void VM::dumpRegExpTrace()
970 {
971     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
972     RTTraceList::iterator iter = ++m_rtTraceList->begin();
973     
974     if (iter != m_rtTraceList->end()) {
975         dataLogF("\nRegExp Tracing\n");
976         dataLogF("Regular Expression                              8 Bit          16 Bit        match()    Matches    Average\n");
977         dataLogF(" <Match only / Match>                         JIT Addr      JIT Address       calls      found   String len\n");
978         dataLogF("----------------------------------------+----------------+----------------+----------+----------+-----------\n");
979     
980         unsigned reCount = 0;
981     
982         for (; iter != m_rtTraceList->end(); ++iter, ++reCount) {
983             (*iter)->printTraceData();
984             gcUnprotect(*iter);
985         }
986
987         dataLogF("%d Regular Expressions\n", reCount);
988     }
989     
990     m_rtTraceList->clear();
991 }
992 #else
993 void VM::dumpRegExpTrace()
994 {
995 }
996 #endif
997
998 WatchpointSet* VM::ensureWatchpointSetForImpureProperty(const Identifier& propertyName)
999 {
1000     auto result = m_impurePropertyWatchpointSets.add(propertyName.string(), nullptr);
1001     if (result.isNewEntry)
1002         result.iterator->value = adoptRef(new WatchpointSet(IsWatched));
1003     return result.iterator->value.get();
1004 }
1005
1006 void VM::registerWatchpointForImpureProperty(const Identifier& propertyName, Watchpoint* watchpoint)
1007 {
1008     ensureWatchpointSetForImpureProperty(propertyName)->add(watchpoint);
1009 }
1010
1011 void VM::addImpureProperty(const String& propertyName)
1012 {
1013     if (RefPtr<WatchpointSet> watchpointSet = m_impurePropertyWatchpointSets.take(propertyName))
1014         watchpointSet->fireAll(*this, "Impure property added");
1015 }
1016
1017 static bool enableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doEnableWork)
1018 {
1019     bool needsToRecompile = false;
1020     if (!counter) {
1021         doEnableWork();
1022         needsToRecompile = true;
1023     }
1024     counter++;
1025
1026     return needsToRecompile;
1027 }
1028
1029 static bool disableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doDisableWork)
1030 {
1031     RELEASE_ASSERT(counter > 0);
1032     bool needsToRecompile = false;
1033     counter--;
1034     if (!counter) {
1035         doDisableWork();
1036         needsToRecompile = true;
1037     }
1038
1039     return needsToRecompile;
1040 }
1041
1042 bool VM::enableTypeProfiler()
1043 {
1044     auto enableTypeProfiler = [this] () {
1045         this->m_typeProfiler = std::make_unique<TypeProfiler>();
1046         this->m_typeProfilerLog = std::make_unique<TypeProfilerLog>(*this);
1047     };
1048
1049     return enableProfilerWithRespectToCount(m_typeProfilerEnabledCount, enableTypeProfiler);
1050 }
1051
1052 bool VM::disableTypeProfiler()
1053 {
1054     auto disableTypeProfiler = [this] () {
1055         this->m_typeProfiler.reset(nullptr);
1056         this->m_typeProfilerLog.reset(nullptr);
1057     };
1058
1059     return disableProfilerWithRespectToCount(m_typeProfilerEnabledCount, disableTypeProfiler);
1060 }
1061
1062 bool VM::enableControlFlowProfiler()
1063 {
1064     auto enableControlFlowProfiler = [this] () {
1065         this->m_controlFlowProfiler = std::make_unique<ControlFlowProfiler>();
1066     };
1067
1068     return enableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, enableControlFlowProfiler);
1069 }
1070
1071 bool VM::disableControlFlowProfiler()
1072 {
1073     auto disableControlFlowProfiler = [this] () {
1074         this->m_controlFlowProfiler.reset(nullptr);
1075     };
1076
1077     return disableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, disableControlFlowProfiler);
1078 }
1079
1080 void VM::dumpTypeProfilerData()
1081 {
1082     if (!typeProfiler())
1083         return;
1084
1085     typeProfilerLog()->processLogEntries(ASCIILiteral("VM Dump Types"));
1086     typeProfiler()->dumpTypeProfilerData(*this);
1087 }
1088
1089 void VM::queueMicrotask(JSGlobalObject& globalObject, Ref<Microtask>&& task)
1090 {
1091     m_microtaskQueue.append(std::make_unique<QueuedTask>(*this, &globalObject, WTFMove(task)));
1092 }
1093
1094 void VM::drainMicrotasks()
1095 {
1096     while (!m_microtaskQueue.isEmpty())
1097         m_microtaskQueue.takeFirst()->run();
1098 }
1099
1100 void QueuedTask::run()
1101 {
1102     m_microtask->run(m_globalObject->globalExec());
1103 }
1104
1105 void sanitizeStackForVM(VM* vm)
1106 {
1107     logSanitizeStack(vm);
1108     if (vm->topCallFrame) {
1109         auto& stackBounds = Thread::current().stack();
1110         ASSERT(vm->currentThreadIsHoldingAPILock());
1111         ASSERT_UNUSED(stackBounds, stackBounds.contains(vm->lastStackTop()));
1112     }
1113 #if !ENABLE(JIT)
1114     vm->interpreter->cloopStack().sanitizeStack();
1115 #else
1116     sanitizeStackForVMImpl(vm);
1117 #endif
1118 }
1119
1120 size_t VM::committedStackByteCount()
1121 {
1122 #if ENABLE(JIT)
1123     // When using the C stack, we don't know how many stack pages are actually
1124     // committed. So, we use the current stack usage as an estimate.
1125     ASSERT(Thread::current().stack().isGrowingDownward());
1126     int8_t* current = reinterpret_cast<int8_t*>(&current);
1127     int8_t* high = reinterpret_cast<int8_t*>(Thread::current().stack().origin());
1128     return high - current;
1129 #else
1130     return CLoopStack::committedByteCount();
1131 #endif
1132 }
1133
1134 #if !ENABLE(JIT)
1135 bool VM::ensureStackCapacityForCLoop(Register* newTopOfStack)
1136 {
1137     return interpreter->cloopStack().ensureCapacityFor(newTopOfStack);
1138 }
1139
1140 bool VM::isSafeToRecurseSoftCLoop() const
1141 {
1142     return interpreter->cloopStack().isSafeToRecurse();
1143 }
1144 #endif // !ENABLE(JIT)
1145
1146 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
1147 void VM::verifyExceptionCheckNeedIsSatisfied(unsigned recursionDepth, ExceptionEventLocation& location)
1148 {
1149     if (!Options::validateExceptionChecks())
1150         return;
1151
1152     if (UNLIKELY(m_needExceptionCheck)) {
1153         auto throwDepth = m_simulatedThrowPointRecursionDepth;
1154         auto& throwLocation = m_simulatedThrowPointLocation;
1155
1156         dataLog(
1157             "ERROR: Unchecked JS exception:\n"
1158             "    This scope can throw a JS exception: ", throwLocation, "\n"
1159             "        (ExceptionScope::m_recursionDepth was ", throwDepth, ")\n"
1160             "    But the exception was unchecked as of this scope: ", location, "\n"
1161             "        (ExceptionScope::m_recursionDepth was ", recursionDepth, ")\n"
1162             "\n");
1163
1164         StringPrintStream out;
1165         std::unique_ptr<StackTrace> currentTrace = StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit());
1166
1167         if (Options::dumpSimulatedThrows()) {
1168             out.println("The simulated exception was thrown at:");
1169             m_nativeStackTraceOfLastSimulatedThrow->dump(out, "    ");
1170             out.println();
1171         }
1172         out.println("Unchecked exception detected at:");
1173         currentTrace->dump(out, "    ");
1174         out.println();
1175
1176         dataLog(out.toCString());
1177         RELEASE_ASSERT(!m_needExceptionCheck);
1178     }
1179 }
1180 #endif
1181
1182 #if USE(CF)
1183 void VM::registerRunLoopTimer(JSRunLoopTimer* timer)
1184 {
1185     ASSERT(runLoop());
1186     ASSERT(!m_runLoopTimers.contains(timer));
1187     m_runLoopTimers.add(timer);
1188     timer->setRunLoop(runLoop());
1189 }
1190
1191 void VM::unregisterRunLoopTimer(JSRunLoopTimer* timer)
1192 {
1193     ASSERT(m_runLoopTimers.contains(timer));
1194     m_runLoopTimers.remove(timer);
1195     timer->setRunLoop(nullptr);
1196 }
1197
1198 void VM::setRunLoop(CFRunLoopRef runLoop)
1199 {
1200     ASSERT(runLoop);
1201     m_runLoop = runLoop;
1202     for (auto timer : m_runLoopTimers)
1203         timer->setRunLoop(runLoop);
1204 }
1205 #endif // USE(CF)
1206
1207 ScratchBuffer* VM::scratchBufferForSize(size_t size)
1208 {
1209     if (!size)
1210         return nullptr;
1211
1212     auto locker = holdLock(m_scratchBufferLock);
1213
1214     if (size > m_sizeOfLastScratchBuffer) {
1215         // Protect against a N^2 memory usage pathology by ensuring
1216         // that at worst, we get a geometric series, meaning that the
1217         // total memory usage is somewhere around
1218         // max(scratch buffer size) * 4.
1219         m_sizeOfLastScratchBuffer = size * 2;
1220
1221         ScratchBuffer* newBuffer = ScratchBuffer::create(m_sizeOfLastScratchBuffer);
1222         RELEASE_ASSERT(newBuffer);
1223         m_scratchBuffers.append(newBuffer);
1224     }
1225
1226     ScratchBuffer* result = m_scratchBuffers.last();
1227     return result;
1228 }
1229
1230 } // namespace JSC