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