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