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