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