Add ability to generate a Heap Snapshot
[WebKit.git] / Source / JavaScriptCore / runtime / VM.cpp
1 /*
2  * Copyright (C) 2008, 2011, 2013-2016 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 "DFGLongLivedState.h"
42 #include "DFGWorklist.h"
43 #include "Disassembler.h"
44 #include "ErrorInstance.h"
45 #include "Exception.h"
46 #include "FTLThunks.h"
47 #include "FunctionConstructor.h"
48 #include "GCActivityCallback.h"
49 #include "GeneratorFrame.h"
50 #include "GetterSetter.h"
51 #include "Heap.h"
52 #include "HeapIterationScope.h"
53 #include "HeapProfiler.h"
54 #include "HostCallReturnValue.h"
55 #include "Identifier.h"
56 #include "IncrementalSweeper.h"
57 #include "InferredTypeTable.h"
58 #include "Interpreter.h"
59 #include "JITCode.h"
60 #include "JSAPIValueWrapper.h"
61 #include "JSArray.h"
62 #include "JSCInlines.h"
63 #include "JSFunction.h"
64 #include "JSGlobalObjectFunctions.h"
65 #include "JSInternalPromiseDeferred.h"
66 #include "JSLexicalEnvironment.h"
67 #include "JSLock.h"
68 #include "JSNotAnObject.h"
69 #include "JSPromiseDeferred.h"
70 #include "JSPropertyNameEnumerator.h"
71 #include "JSTemplateRegistryKey.h"
72 #include "JSWithScope.h"
73 #include "Lexer.h"
74 #include "Lookup.h"
75 #include "MapData.h"
76 #include "NativeStdFunctionCell.h"
77 #include "Nodes.h"
78 #include "Parser.h"
79 #include "ProfilerDatabase.h"
80 #include "PropertyMapHashTable.h"
81 #include "RegExpCache.h"
82 #include "RegExpObject.h"
83 #include "RegisterAtOffsetList.h"
84 #include "RuntimeType.h"
85 #include "SamplingProfiler.h"
86 #include "SimpleTypedArrayController.h"
87 #include "SourceProviderCache.h"
88 #include "StackVisitor.h"
89 #include "StrictEvalActivation.h"
90 #include "StrongInlines.h"
91 #include "StructureInlines.h"
92 #include "TypeProfiler.h"
93 #include "TypeProfilerLog.h"
94 #include "UnlinkedCodeBlock.h"
95 #include "VMEntryScope.h"
96 #include "Watchdog.h"
97 #include "WeakGCMapInlines.h"
98 #include "WeakMapData.h"
99 #include <wtf/CurrentTime.h>
100 #include <wtf/ProcessID.h>
101 #include <wtf/RetainPtr.h>
102 #include <wtf/StringPrintStream.h>
103 #include <wtf/Threading.h>
104 #include <wtf/WTFThreadData.h>
105 #include <wtf/text/AtomicStringTable.h>
106 #include <wtf/text/SymbolRegistry.h>
107
108 #if ENABLE(DFG_JIT)
109 #include "ConservativeRoots.h"
110 #endif
111
112 #if ENABLE(REGEXP_TRACING)
113 #include "RegExp.h"
114 #endif
115
116 #if USE(CF)
117 #include <CoreFoundation/CoreFoundation.h>
118 #endif
119
120 using namespace WTF;
121
122 namespace JSC {
123
124 // Note: Platform.h will enforce that ENABLE(ASSEMBLER) is true if either
125 // ENABLE(JIT) or ENABLE(YARR_JIT) or both are enabled. The code below
126 // just checks for ENABLE(JIT) or ENABLE(YARR_JIT) with this premise in mind.
127
128 #if ENABLE(ASSEMBLER)
129 static bool enableAssembler(ExecutableAllocator& executableAllocator)
130 {
131     if (!Options::useJIT() && !Options::useRegExpJIT())
132         return false;
133
134     if (!executableAllocator.isValid()) {
135         if (Options::crashIfCantAllocateJITMemory())
136             CRASH();
137         return false;
138     }
139
140 #if USE(CF) || OS(UNIX)
141     char* canUseJITString = getenv("JavaScriptCoreUseJIT");
142     return !canUseJITString || atoi(canUseJITString);
143 #else
144     return true;
145 #endif
146 }
147 #endif // ENABLE(!ASSEMBLER)
148
149 VM::VM(VMType vmType, HeapType heapType)
150     : m_apiLock(adoptRef(new JSLock(this)))
151 #if ENABLE(ASSEMBLER)
152     , executableAllocator(*this)
153 #endif
154     , heap(this, heapType)
155     , vmType(vmType)
156     , clientData(0)
157     , topVMEntryFrame(nullptr)
158     , topCallFrame(CallFrame::noCaller())
159     , m_atomicStringTable(vmType == Default ? wtfThreadData().atomicStringTable() : new AtomicStringTable)
160     , propertyNames(nullptr)
161     , emptyList(new MarkedArgumentBuffer)
162     , customGetterSetterFunctionMap(*this)
163     , stringCache(*this)
164     , prototypeMap(*this)
165     , interpreter(0)
166     , jsArrayClassInfo(JSArray::info())
167     , jsFinalObjectClassInfo(JSFinalObject::info())
168     , sizeOfLastScratchBuffer(0)
169     , entryScope(0)
170     , m_regExpCache(new RegExpCache(this))
171 #if ENABLE(REGEXP_TRACING)
172     , m_rtTraceList(new RTTraceList())
173 #endif
174 #if ENABLE(ASSEMBLER)
175     , m_canUseAssembler(enableAssembler(executableAllocator))
176 #endif
177 #if ENABLE(JIT)
178     , m_canUseJIT(m_canUseAssembler && Options::useJIT())
179 #endif
180 #if ENABLE(YARR_JIT)
181     , m_canUseRegExpJIT(m_canUseAssembler && Options::useRegExpJIT())
182 #endif
183 #if ENABLE(GC_VALIDATION)
184     , m_initializingObjectClass(0)
185 #endif
186     , m_stackPointerAtVMEntry(0)
187     , m_stackLimit(0)
188 #if !ENABLE(JIT)
189     , m_jsStackLimit(0)
190 #endif
191 #if ENABLE(FTL_JIT)
192     , m_ftlStackLimit(0)
193     , m_largestFTLStackSize(0)
194 #endif
195     , m_inDefineOwnProperty(false)
196     , m_codeCache(std::make_unique<CodeCache>())
197     , m_enabledProfiler(nullptr)
198     , m_builtinExecutables(std::make_unique<BuiltinExecutables>(*this))
199     , m_typeProfilerEnabledCount(0)
200     , m_controlFlowProfilerEnabledCount(0)
201 {
202     interpreter = new Interpreter(*this);
203     StackBounds stack = wtfThreadData().stack();
204     updateReservedZoneSize(Options::reservedZoneSize());
205 #if !ENABLE(JIT)
206     interpreter->stack().setReservedZoneSize(Options::reservedZoneSize());
207 #endif
208     setLastStackTop(stack.origin());
209
210     // Need to be careful to keep everything consistent here
211     JSLockHolder lock(this);
212     AtomicStringTable* existingEntryAtomicStringTable = wtfThreadData().setCurrentAtomicStringTable(m_atomicStringTable);
213     propertyNames = new CommonIdentifiers(this);
214     structureStructure.set(*this, Structure::createStructure(*this));
215     structureRareDataStructure.set(*this, StructureRareData::createStructure(*this, 0, jsNull()));
216     terminatedExecutionErrorStructure.set(*this, TerminatedExecutionError::createStructure(*this, 0, jsNull()));
217     stringStructure.set(*this, JSString::createStructure(*this, 0, jsNull()));
218     notAnObjectStructure.set(*this, JSNotAnObject::createStructure(*this, 0, jsNull()));
219     propertyNameEnumeratorStructure.set(*this, JSPropertyNameEnumerator::createStructure(*this, 0, jsNull()));
220     getterSetterStructure.set(*this, GetterSetter::createStructure(*this, 0, jsNull()));
221     customGetterSetterStructure.set(*this, CustomGetterSetter::createStructure(*this, 0, jsNull()));
222     scopedArgumentsTableStructure.set(*this, ScopedArgumentsTable::createStructure(*this, 0, jsNull()));
223     apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, 0, jsNull()));
224     JSScopeStructure.set(*this, JSScope::createStructure(*this, 0, jsNull()));
225     executableStructure.set(*this, ExecutableBase::createStructure(*this, 0, jsNull()));
226     nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, 0, jsNull()));
227     evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, 0, jsNull()));
228     programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, 0, jsNull()));
229     functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, 0, jsNull()));
230 #if ENABLE(WEBASSEMBLY)
231     webAssemblyExecutableStructure.set(*this, WebAssemblyExecutable::createStructure(*this, 0, jsNull()));
232 #endif
233     moduleProgramExecutableStructure.set(*this, ModuleProgramExecutable::createStructure(*this, 0, jsNull()));
234     regExpStructure.set(*this, RegExp::createStructure(*this, 0, jsNull()));
235     symbolStructure.set(*this, Symbol::createStructure(*this, 0, jsNull()));
236     symbolTableStructure.set(*this, SymbolTable::createStructure(*this, 0, jsNull()));
237     structureChainStructure.set(*this, StructureChain::createStructure(*this, 0, jsNull()));
238     sparseArrayValueMapStructure.set(*this, SparseArrayValueMap::createStructure(*this, 0, jsNull()));
239     templateRegistryKeyStructure.set(*this, JSTemplateRegistryKey::createStructure(*this, 0, jsNull()));
240     arrayBufferNeuteringWatchpointStructure.set(*this, ArrayBufferNeuteringWatchpoint::createStructure(*this));
241     unlinkedFunctionExecutableStructure.set(*this, UnlinkedFunctionExecutable::createStructure(*this, 0, jsNull()));
242     unlinkedProgramCodeBlockStructure.set(*this, UnlinkedProgramCodeBlock::createStructure(*this, 0, jsNull()));
243     unlinkedEvalCodeBlockStructure.set(*this, UnlinkedEvalCodeBlock::createStructure(*this, 0, jsNull()));
244     unlinkedFunctionCodeBlockStructure.set(*this, UnlinkedFunctionCodeBlock::createStructure(*this, 0, jsNull()));
245     unlinkedModuleProgramCodeBlockStructure.set(*this, UnlinkedModuleProgramCodeBlock::createStructure(*this, 0, jsNull()));
246     propertyTableStructure.set(*this, PropertyTable::createStructure(*this, 0, jsNull()));
247     weakMapDataStructure.set(*this, WeakMapData::createStructure(*this, 0, jsNull()));
248     inferredValueStructure.set(*this, InferredValue::createStructure(*this, 0, jsNull()));
249     inferredTypeStructure.set(*this, InferredType::createStructure(*this, 0, jsNull()));
250     inferredTypeTableStructure.set(*this, InferredTypeTable::createStructure(*this, 0, jsNull()));
251     functionRareDataStructure.set(*this, FunctionRareData::createStructure(*this, 0, jsNull()));
252     generatorFrameStructure.set(*this, GeneratorFrame::createStructure(*this, 0, jsNull()));
253     exceptionStructure.set(*this, Exception::createStructure(*this, 0, jsNull()));
254     promiseDeferredStructure.set(*this, JSPromiseDeferred::createStructure(*this, 0, jsNull()));
255     internalPromiseDeferredStructure.set(*this, JSInternalPromiseDeferred::createStructure(*this, 0, jsNull()));
256     programCodeBlockStructure.set(*this, ProgramCodeBlock::createStructure(*this, 0, jsNull()));
257     moduleProgramCodeBlockStructure.set(*this, ModuleProgramCodeBlock::createStructure(*this, 0, jsNull()));
258     evalCodeBlockStructure.set(*this, EvalCodeBlock::createStructure(*this, 0, jsNull()));
259     functionCodeBlockStructure.set(*this, FunctionCodeBlock::createStructure(*this, 0, jsNull()));
260 #if ENABLE(WEBASSEMBLY)
261     webAssemblyCodeBlockStructure.set(*this, WebAssemblyCodeBlock::createStructure(*this, 0, jsNull()));
262 #endif
263
264     iterationTerminator.set(*this, JSFinalObject::create(*this, JSFinalObject::createStructure(*this, 0, jsNull(), 1)));
265     nativeStdFunctionCellStructure.set(*this, NativeStdFunctionCell::createStructure(*this, 0, jsNull()));
266     smallStrings.initializeCommonStrings(*this);
267
268     wtfThreadData().setCurrentAtomicStringTable(existingEntryAtomicStringTable);
269
270 #if ENABLE(JIT)
271     jitStubs = std::make_unique<JITThunks>();
272     allCalleeSaveRegisterOffsets = std::make_unique<RegisterAtOffsetList>(RegisterSet::vmCalleeSaveRegisters(), RegisterAtOffsetList::ZeroBased);
273 #endif
274     arityCheckData = std::make_unique<CommonSlowPaths::ArityCheckData>();
275
276 #if ENABLE(FTL_JIT)
277     ftlThunks = std::make_unique<FTL::Thunks>();
278 #endif // ENABLE(FTL_JIT)
279     
280     interpreter->initialize();
281     
282 #if ENABLE(JIT)
283     initializeHostCallReturnValue(); // This is needed to convince the linker not to drop host call return support.
284 #endif
285
286     heap.notifyIsSafeToCollect();
287     
288     LLInt::Data::performAssertions(*this);
289     
290     if (Options::useProfiler()) {
291         m_perBytecodeProfiler = std::make_unique<Profiler::Database>(*this);
292
293         StringPrintStream pathOut;
294         const char* profilerPath = getenv("JSC_PROFILER_PATH");
295         if (profilerPath)
296             pathOut.print(profilerPath, "/");
297         pathOut.print("JSCProfile-", getCurrentProcessID(), "-", m_perBytecodeProfiler->databaseID(), ".json");
298         m_perBytecodeProfiler->registerToSaveAtExit(pathOut.toCString().data());
299     }
300
301     callFrameForCatch = nullptr;
302
303 #if ENABLE(DFG_JIT)
304     if (canUseJIT())
305         dfgState = std::make_unique<DFG::LongLivedState>();
306 #endif
307     
308     // Initialize this last, as a free way of asserting that VM initialization itself
309     // won't use this.
310     m_typedArrayController = adoptRef(new SimpleTypedArrayController());
311
312     m_bytecodeIntrinsicRegistry = std::make_unique<BytecodeIntrinsicRegistry>(*this);
313
314     if (Options::useTypeProfiler())
315         enableTypeProfiler();
316     if (Options::useControlFlowProfiler())
317         enableControlFlowProfiler();
318 #if ENABLE(SAMPLING_PROFILER)
319     if (Options::useSamplingProfiler()) {
320         setShouldBuildPCToCodeOriginMapping();
321         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, Stopwatch::create()));
322         m_samplingProfiler->start();
323     }
324 #endif // ENABLE(SAMPLING_PROFILER)
325
326     if (Options::alwaysGeneratePCToCodeOriginMap())
327         setShouldBuildPCToCodeOriginMapping();
328
329     if (Options::watchdog()) {
330         std::chrono::milliseconds timeoutMillis(Options::watchdog());
331         Watchdog& watchdog = ensureWatchdog();
332         watchdog.setTimeLimit(timeoutMillis);
333     }
334 }
335
336 VM::~VM()
337 {
338     // Never GC, ever again.
339     heap.incrementDeferralDepth();
340
341 #if ENABLE(SAMPLING_PROFILER)
342     if (m_samplingProfiler)
343         m_samplingProfiler->shutdown();
344 #endif // ENABLE(SAMPLING_PROFILER)
345     
346 #if ENABLE(DFG_JIT)
347     // Make sure concurrent compilations are done, but don't install them, since there is
348     // no point to doing so.
349     for (unsigned i = DFG::numberOfWorklists(); i--;) {
350         if (DFG::Worklist* worklist = DFG::worklistForIndexOrNull(i)) {
351             worklist->waitUntilAllPlansForVMAreReady(*this);
352             worklist->removeAllReadyPlansForVM(*this);
353         }
354     }
355 #endif // ENABLE(DFG_JIT)
356     
357     waitForAsynchronousDisassembly();
358     
359     // Clear this first to ensure that nobody tries to remove themselves from it.
360     m_perBytecodeProfiler = nullptr;
361
362     ASSERT(m_apiLock->currentThreadIsHoldingLock());
363     m_apiLock->willDestroyVM(this);
364     heap.lastChanceToFinalize();
365
366     delete interpreter;
367 #ifndef NDEBUG
368     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
369 #endif
370
371     delete emptyList;
372
373     delete propertyNames;
374     if (vmType != Default)
375         delete m_atomicStringTable;
376
377     delete clientData;
378     delete m_regExpCache;
379 #if ENABLE(REGEXP_TRACING)
380     delete m_rtTraceList;
381 #endif
382
383 #if ENABLE(DFG_JIT)
384     for (unsigned i = 0; i < scratchBuffers.size(); ++i)
385         fastFree(scratchBuffers[i]);
386 #endif
387 }
388
389 void VM::setLastStackTop(void* lastStackTop)
390
391     m_lastStackTop = lastStackTop;
392 }
393
394 Ref<VM> VM::createContextGroup(HeapType heapType)
395 {
396     return adoptRef(*new VM(APIContextGroup, heapType));
397 }
398
399 Ref<VM> VM::create(HeapType heapType)
400 {
401     return adoptRef(*new VM(Default, heapType));
402 }
403
404 Ref<VM> VM::createLeaked(HeapType heapType)
405 {
406     return create(heapType);
407 }
408
409 bool VM::sharedInstanceExists()
410 {
411     return sharedInstanceInternal();
412 }
413
414 VM& VM::sharedInstance()
415 {
416     GlobalJSLock globalLock;
417     VM*& instance = sharedInstanceInternal();
418     if (!instance)
419         instance = adoptRef(new VM(APIShared, SmallHeap)).leakRef();
420     return *instance;
421 }
422
423 VM*& VM::sharedInstanceInternal()
424 {
425     static VM* sharedInstance;
426     return sharedInstance;
427 }
428
429 Watchdog& VM::ensureWatchdog()
430 {
431     if (!m_watchdog) {
432         m_watchdog = adoptRef(new Watchdog());
433         
434         // The LLINT peeks into the Watchdog object directly. In order to do that,
435         // the LLINT assumes that the internal shape of a std::unique_ptr is the
436         // same as a plain C++ pointer, and loads the address of Watchdog from it.
437         RELEASE_ASSERT(*reinterpret_cast<Watchdog**>(&m_watchdog) == m_watchdog.get());
438
439         // And if we've previously compiled any functions, we need to revert
440         // them because they don't have the needed polling checks for the watchdog
441         // yet.
442         deleteAllCode();
443     }
444     return *m_watchdog;
445 }
446
447 HeapProfiler& VM::ensureHeapProfiler()
448 {
449     if (!m_heapProfiler)
450         m_heapProfiler = std::make_unique<HeapProfiler>(*this);
451     return *m_heapProfiler;
452 }
453
454 #if ENABLE(SAMPLING_PROFILER)
455 void VM::ensureSamplingProfiler(RefPtr<Stopwatch>&& stopwatch)
456 {
457     if (!m_samplingProfiler)
458         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
459 }
460 #endif // ENABLE(SAMPLING_PROFILER)
461
462 #if ENABLE(JIT)
463 static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
464 {
465     switch (intrinsic) {
466     case CharCodeAtIntrinsic:
467         return charCodeAtThunkGenerator;
468     case CharAtIntrinsic:
469         return charAtThunkGenerator;
470     case Clz32Intrinsic:
471         return clz32ThunkGenerator;
472     case FromCharCodeIntrinsic:
473         return fromCharCodeThunkGenerator;
474     case SqrtIntrinsic:
475         return sqrtThunkGenerator;
476     case PowIntrinsic:
477         return powThunkGenerator;
478     case AbsIntrinsic:
479         return absThunkGenerator;
480     case FloorIntrinsic:
481         return floorThunkGenerator;
482     case CeilIntrinsic:
483         return ceilThunkGenerator;
484     case RoundIntrinsic:
485         return roundThunkGenerator;
486     case ExpIntrinsic:
487         return expThunkGenerator;
488     case LogIntrinsic:
489         return logThunkGenerator;
490     case IMulIntrinsic:
491         return imulThunkGenerator;
492     case RandomIntrinsic:
493         return randomThunkGenerator;
494     default:
495         return 0;
496     }
497 }
498
499 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
500 {
501     return jitStubs->hostFunctionStub(this, function, constructor, name);
502 }
503 NativeExecutable* VM::getHostFunction(NativeFunction function, Intrinsic intrinsic, const String& name)
504 {
505     ASSERT(canUseJIT());
506     return jitStubs->hostFunctionStub(this, function, intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0, intrinsic, name);
507 }
508
509 #else // !ENABLE(JIT)
510
511 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
512 {
513     return NativeExecutable::create(*this,
514         adoptRef(new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_call_trampoline), JITCode::HostCallThunk)), function,
515         adoptRef(new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_construct_trampoline), JITCode::HostCallThunk)), constructor,
516         NoIntrinsic, name);
517 }
518
519 #endif // !ENABLE(JIT)
520
521 VM::ClientData::~ClientData()
522 {
523 }
524
525 void VM::resetDateCache()
526 {
527     localTimeOffsetCache.reset();
528     cachedDateString = String();
529     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
530     dateInstanceCache.reset();
531 }
532
533 void VM::startSampling()
534 {
535     interpreter->startSampling();
536 }
537
538 void VM::stopSampling()
539 {
540     interpreter->stopSampling();
541 }
542
543 void VM::whenIdle(std::function<void()> callback)
544 {
545     if (!entryScope) {
546         callback();
547         return;
548     }
549
550     entryScope->addDidPopListener(callback);
551 }
552
553 void VM::deleteAllLinkedCode()
554 {
555     whenIdle([this]() {
556         heap.deleteAllCodeBlocks();
557         heap.reportAbandonedObjectGraph();
558     });
559 }
560
561 void VM::deleteAllCode()
562 {
563     whenIdle([this]() {
564         m_codeCache->clear();
565         m_regExpCache->deleteAllCode();
566         heap.deleteAllCodeBlocks();
567         heap.deleteAllUnlinkedCodeBlocks();
568         heap.reportAbandonedObjectGraph();
569     });
570 }
571
572 void VM::dumpSampleData(ExecState* exec)
573 {
574     interpreter->dumpSampleData(exec);
575 #if ENABLE(ASSEMBLER)
576     ExecutableAllocator::dumpProfile();
577 #endif
578 }
579
580 SourceProviderCache* VM::addSourceProviderCache(SourceProvider* sourceProvider)
581 {
582     auto addResult = sourceProviderCacheMap.add(sourceProvider, nullptr);
583     if (addResult.isNewEntry)
584         addResult.iterator->value = adoptRef(new SourceProviderCache);
585     return addResult.iterator->value.get();
586 }
587
588 void VM::clearSourceProviderCaches()
589 {
590     sourceProviderCacheMap.clear();
591 }
592
593 void VM::throwException(ExecState* exec, Exception* exception)
594 {
595     if (Options::breakOnThrow()) {
596         dataLog("In call frame ", RawPointer(exec), " for code block ", *exec->codeBlock(), "\n");
597         CRASH();
598     }
599
600     ASSERT(exec == topCallFrame || exec == exec->lexicalGlobalObject()->globalExec() || exec == exec->vmEntryGlobalObject()->globalExec());
601
602     interpreter->notifyDebuggerOfExceptionToBeThrown(exec, exception);
603
604     setException(exception);
605 }
606
607 JSValue VM::throwException(ExecState* exec, JSValue thrownValue)
608 {
609     Exception* exception = jsDynamicCast<Exception*>(thrownValue);
610     if (!exception)
611         exception = Exception::create(*this, thrownValue);
612
613     throwException(exec, exception);
614     return JSValue(exception);
615 }
616
617 JSObject* VM::throwException(ExecState* exec, JSObject* error)
618 {
619     return asObject(throwException(exec, JSValue(error)));
620 }
621
622 void VM::setStackPointerAtVMEntry(void* sp)
623 {
624     m_stackPointerAtVMEntry = sp;
625     updateStackLimit();
626 }
627
628 size_t VM::updateReservedZoneSize(size_t reservedZoneSize)
629 {
630     size_t oldReservedZoneSize = m_reservedZoneSize;
631     m_reservedZoneSize = reservedZoneSize;
632
633     updateStackLimit();
634
635     return oldReservedZoneSize;
636 }
637
638 #if PLATFORM(WIN)
639 // On Windows the reserved stack space consists of committed memory, a guard page, and uncommitted memory,
640 // where the guard page is a barrier between committed and uncommitted memory.
641 // When data from the guard page is read or written, the guard page is moved, and memory is committed.
642 // This is how the system grows the stack.
643 // When using the C stack on Windows we need to precommit the needed stack space.
644 // Otherwise we might crash later if we access uncommitted stack memory.
645 // This can happen if we allocate stack space larger than the page guard size (4K).
646 // The system does not get the chance to move the guard page, and commit more memory,
647 // and we crash if uncommitted memory is accessed.
648 // The MSVC compiler fixes this by inserting a call to the _chkstk() function,
649 // when needed, see http://support.microsoft.com/kb/100775.
650 // By touching every page up to the stack limit with a dummy operation,
651 // we force the system to move the guard page, and commit memory.
652
653 static void preCommitStackMemory(void* stackLimit)
654 {
655     const int pageSize = 4096;
656     for (volatile char* p = reinterpret_cast<char*>(&stackLimit); p > stackLimit; p -= pageSize) {
657         char ch = *p;
658         *p = ch;
659     }
660 }
661 #endif
662
663 inline void VM::updateStackLimit()
664 {
665 #if PLATFORM(WIN)
666     void* lastStackLimit = m_stackLimit;
667 #endif
668
669     if (m_stackPointerAtVMEntry) {
670         ASSERT(wtfThreadData().stack().isGrowingDownward());
671         char* startOfStack = reinterpret_cast<char*>(m_stackPointerAtVMEntry);
672 #if ENABLE(FTL_JIT)
673         m_stackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_reservedZoneSize + m_largestFTLStackSize);
674         m_ftlStackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_reservedZoneSize + 2 * m_largestFTLStackSize);
675 #else
676         m_stackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_reservedZoneSize);
677 #endif
678     } else {
679 #if ENABLE(FTL_JIT)
680         m_stackLimit = wtfThreadData().stack().recursionLimit(m_reservedZoneSize + m_largestFTLStackSize);
681         m_ftlStackLimit = wtfThreadData().stack().recursionLimit(m_reservedZoneSize + 2 * m_largestFTLStackSize);
682 #else
683         m_stackLimit = wtfThreadData().stack().recursionLimit(m_reservedZoneSize);
684 #endif
685     }
686
687 #if PLATFORM(WIN)
688     if (lastStackLimit != m_stackLimit)
689         preCommitStackMemory(m_stackLimit);
690 #endif
691 }
692
693 #if ENABLE(FTL_JIT)
694 void VM::updateFTLLargestStackSize(size_t stackSize)
695 {
696     if (stackSize > m_largestFTLStackSize) {
697         m_largestFTLStackSize = stackSize;
698         updateStackLimit();
699     }
700 }
701 #endif
702
703 #if ENABLE(DFG_JIT)
704 void VM::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
705 {
706     for (size_t i = 0; i < scratchBuffers.size(); i++) {
707         ScratchBuffer* scratchBuffer = scratchBuffers[i];
708         if (scratchBuffer->activeLength()) {
709             void* bufferStart = scratchBuffer->dataBuffer();
710             conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
711         }
712     }
713 }
714 #endif
715
716 void logSanitizeStack(VM* vm)
717 {
718     if (Options::verboseSanitizeStack() && vm->topCallFrame) {
719         int dummy;
720         dataLog(
721             "Sanitizing stack with top call frame at ", RawPointer(vm->topCallFrame),
722             ", current stack pointer at ", RawPointer(&dummy), ", in ",
723             pointerDump(vm->topCallFrame->codeBlock()), " and last code origin = ",
724             vm->topCallFrame->codeOrigin(), "\n");
725     }
726 }
727
728 #if ENABLE(REGEXP_TRACING)
729 void VM::addRegExpToTrace(RegExp* regExp)
730 {
731     gcProtect(regExp);
732     m_rtTraceList->add(regExp);
733 }
734
735 void VM::dumpRegExpTrace()
736 {
737     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
738     RTTraceList::iterator iter = ++m_rtTraceList->begin();
739     
740     if (iter != m_rtTraceList->end()) {
741         dataLogF("\nRegExp Tracing\n");
742         dataLogF("Regular Expression                              8 Bit          16 Bit        match()    Matches    Average\n");
743         dataLogF(" <Match only / Match>                         JIT Addr      JIT Address       calls      found   String len\n");
744         dataLogF("----------------------------------------+----------------+----------------+----------+----------+-----------\n");
745     
746         unsigned reCount = 0;
747     
748         for (; iter != m_rtTraceList->end(); ++iter, ++reCount) {
749             (*iter)->printTraceData();
750             gcUnprotect(*iter);
751         }
752
753         dataLogF("%d Regular Expressions\n", reCount);
754     }
755     
756     m_rtTraceList->clear();
757 }
758 #else
759 void VM::dumpRegExpTrace()
760 {
761 }
762 #endif
763
764 void VM::registerWatchpointForImpureProperty(const Identifier& propertyName, Watchpoint* watchpoint)
765 {
766     auto result = m_impurePropertyWatchpointSets.add(propertyName.string(), nullptr);
767     if (result.isNewEntry)
768         result.iterator->value = adoptRef(new WatchpointSet(IsWatched));
769     result.iterator->value->add(watchpoint);
770 }
771
772 void VM::addImpureProperty(const String& propertyName)
773 {
774     if (RefPtr<WatchpointSet> watchpointSet = m_impurePropertyWatchpointSets.take(propertyName))
775         watchpointSet->fireAll("Impure property added");
776 }
777
778 class SetEnabledProfilerFunctor {
779 public:
780     bool operator()(CodeBlock* codeBlock)
781     {
782         if (JITCode::isOptimizingJIT(codeBlock->jitType()))
783             codeBlock->jettison(Profiler::JettisonDueToLegacyProfiler);
784         return false;
785     }
786 };
787
788 void VM::setEnabledProfiler(LegacyProfiler* profiler)
789 {
790     m_enabledProfiler = profiler;
791     if (m_enabledProfiler) {
792         SetEnabledProfilerFunctor functor;
793         heap.forEachCodeBlock(functor);
794     }
795 }
796
797 static bool enableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doEnableWork)
798 {
799     bool needsToRecompile = false;
800     if (!counter) {
801         doEnableWork();
802         needsToRecompile = true;
803     }
804     counter++;
805
806     return needsToRecompile;
807 }
808
809 static bool disableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doDisableWork)
810 {
811     RELEASE_ASSERT(counter > 0);
812     bool needsToRecompile = false;
813     counter--;
814     if (!counter) {
815         doDisableWork();
816         needsToRecompile = true;
817     }
818
819     return needsToRecompile;
820 }
821
822 bool VM::enableTypeProfiler()
823 {
824     auto enableTypeProfiler = [this] () {
825         this->m_typeProfiler = std::make_unique<TypeProfiler>();
826         this->m_typeProfilerLog = std::make_unique<TypeProfilerLog>();
827     };
828
829     return enableProfilerWithRespectToCount(m_typeProfilerEnabledCount, enableTypeProfiler);
830 }
831
832 bool VM::disableTypeProfiler()
833 {
834     auto disableTypeProfiler = [this] () {
835         this->m_typeProfiler.reset(nullptr);
836         this->m_typeProfilerLog.reset(nullptr);
837     };
838
839     return disableProfilerWithRespectToCount(m_typeProfilerEnabledCount, disableTypeProfiler);
840 }
841
842 bool VM::enableControlFlowProfiler()
843 {
844     auto enableControlFlowProfiler = [this] () {
845         this->m_controlFlowProfiler = std::make_unique<ControlFlowProfiler>();
846     };
847
848     return enableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, enableControlFlowProfiler);
849 }
850
851 bool VM::disableControlFlowProfiler()
852 {
853     auto disableControlFlowProfiler = [this] () {
854         this->m_controlFlowProfiler.reset(nullptr);
855     };
856
857     return disableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, disableControlFlowProfiler);
858 }
859
860 void VM::dumpTypeProfilerData()
861 {
862     if (!typeProfiler())
863         return;
864
865     typeProfilerLog()->processLogEntries(ASCIILiteral("VM Dump Types"));
866     typeProfiler()->dumpTypeProfilerData(*this);
867 }
868
869 void VM::queueMicrotask(JSGlobalObject* globalObject, PassRefPtr<Microtask> task)
870 {
871     m_microtaskQueue.append(std::make_unique<QueuedTask>(*this, globalObject, task));
872 }
873
874 void VM::drainMicrotasks()
875 {
876     while (!m_microtaskQueue.isEmpty())
877         m_microtaskQueue.takeFirst()->run();
878 }
879
880 void QueuedTask::run()
881 {
882     m_microtask->run(m_globalObject->globalExec());
883 }
884
885 void sanitizeStackForVM(VM* vm)
886 {
887     logSanitizeStack(vm);
888 #if !ENABLE(JIT)
889     vm->interpreter->stack().sanitizeStack();
890 #else
891     sanitizeStackForVMImpl(vm);
892 #endif
893 }
894
895 } // namespace JSC