Implement a faster Interpreter::getOpcodeID().
[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 #if ENABLE(JIT)
292     initializeHostCallReturnValue(); // This is needed to convince the linker not to drop host call return support.
293 #endif
294
295     heap.notifyIsSafeToCollect();
296     
297     LLInt::Data::performAssertions(*this);
298     
299     if (Options::useProfiler()) {
300         m_perBytecodeProfiler = std::make_unique<Profiler::Database>(*this);
301
302         StringPrintStream pathOut;
303         const char* profilerPath = getenv("JSC_PROFILER_PATH");
304         if (profilerPath)
305             pathOut.print(profilerPath, "/");
306         pathOut.print("JSCProfile-", getCurrentProcessID(), "-", m_perBytecodeProfiler->databaseID(), ".json");
307         m_perBytecodeProfiler->registerToSaveAtExit(pathOut.toCString().data());
308     }
309
310     callFrameForCatch = nullptr;
311
312     // Initialize this last, as a free way of asserting that VM initialization itself
313     // won't use this.
314     m_typedArrayController = adoptRef(new SimpleTypedArrayController());
315
316     m_bytecodeIntrinsicRegistry = std::make_unique<BytecodeIntrinsicRegistry>(*this);
317
318     if (Options::useTypeProfiler())
319         enableTypeProfiler();
320     if (Options::useControlFlowProfiler())
321         enableControlFlowProfiler();
322 #if ENABLE(SAMPLING_PROFILER)
323     if (Options::useSamplingProfiler()) {
324         setShouldBuildPCToCodeOriginMapping();
325         Ref<Stopwatch> stopwatch = Stopwatch::create();
326         stopwatch->start();
327         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
328         if (Options::samplingProfilerPath())
329             m_samplingProfiler->registerForReportAtExit();
330         m_samplingProfiler->start();
331     }
332 #endif // ENABLE(SAMPLING_PROFILER)
333
334     if (Options::alwaysGeneratePCToCodeOriginMap())
335         setShouldBuildPCToCodeOriginMapping();
336
337     if (Options::watchdog()) {
338         std::chrono::milliseconds timeoutMillis(Options::watchdog());
339         Watchdog& watchdog = ensureWatchdog();
340         watchdog.setTimeLimit(timeoutMillis);
341     }
342
343     VMInspector::instance().add(this);
344 }
345
346 VM::~VM()
347 {
348     promiseDeferredTimer->stopRunningTasks();
349 #if ENABLE(WEBASSEMBLY)
350     if (Wasm::existingWorklistOrNull())
351         Wasm::ensureWorklist().stopAllPlansForVM(*this);
352 #endif
353     if (UNLIKELY(m_watchdog))
354         m_watchdog->willDestroyVM(this);
355     m_traps.willDestroyVM();
356     VMInspector::instance().remove(this);
357
358     // Never GC, ever again.
359     heap.incrementDeferralDepth();
360
361 #if ENABLE(SAMPLING_PROFILER)
362     if (m_samplingProfiler) {
363         m_samplingProfiler->reportDataToOptionFile();
364         m_samplingProfiler->shutdown();
365     }
366 #endif // ENABLE(SAMPLING_PROFILER)
367     
368 #if ENABLE(JIT)
369     JITWorklist::instance()->completeAllForVM(*this);
370 #endif // ENABLE(JIT)
371
372 #if ENABLE(DFG_JIT)
373     // Make sure concurrent compilations are done, but don't install them, since there is
374     // no point to doing so.
375     for (unsigned i = DFG::numberOfWorklists(); i--;) {
376         if (DFG::Worklist* worklist = DFG::existingWorklistForIndexOrNull(i)) {
377             worklist->removeNonCompilingPlansForVM(*this);
378             worklist->waitUntilAllPlansForVMAreReady(*this);
379             worklist->removeAllReadyPlansForVM(*this);
380         }
381     }
382 #endif // ENABLE(DFG_JIT)
383     
384     waitForAsynchronousDisassembly();
385     
386     // Clear this first to ensure that nobody tries to remove themselves from it.
387     m_perBytecodeProfiler = nullptr;
388
389     ASSERT(currentThreadIsHoldingAPILock());
390     m_apiLock->willDestroyVM(this);
391     heap.lastChanceToFinalize();
392
393     delete interpreter;
394 #ifndef NDEBUG
395     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
396 #endif
397
398     delete emptyList;
399
400     delete propertyNames;
401     if (vmType != Default)
402         delete m_atomicStringTable;
403
404     delete clientData;
405     delete m_regExpCache;
406 #if ENABLE(REGEXP_TRACING)
407     delete m_rtTraceList;
408 #endif
409
410 #if ENABLE(DFG_JIT)
411     for (unsigned i = 0; i < scratchBuffers.size(); ++i)
412         fastFree(scratchBuffers[i]);
413 #endif
414 }
415
416 void VM::setLastStackTop(void* lastStackTop)
417
418     m_lastStackTop = lastStackTop;
419 }
420
421 Ref<VM> VM::createContextGroup(HeapType heapType)
422 {
423     return adoptRef(*new VM(APIContextGroup, heapType));
424 }
425
426 Ref<VM> VM::create(HeapType heapType)
427 {
428     return adoptRef(*new VM(Default, heapType));
429 }
430
431 Ref<VM> VM::createLeaked(HeapType heapType)
432 {
433     return create(heapType);
434 }
435
436 bool VM::sharedInstanceExists()
437 {
438     return sharedInstanceInternal();
439 }
440
441 VM& VM::sharedInstance()
442 {
443     GlobalJSLock globalLock;
444     VM*& instance = sharedInstanceInternal();
445     if (!instance)
446         instance = adoptRef(new VM(APIShared, SmallHeap)).leakRef();
447     return *instance;
448 }
449
450 VM*& VM::sharedInstanceInternal()
451 {
452     static VM* sharedInstance;
453     return sharedInstance;
454 }
455
456 Watchdog& VM::ensureWatchdog()
457 {
458     if (!m_watchdog)
459         m_watchdog = adoptRef(new Watchdog(this));
460     return *m_watchdog;
461 }
462
463 HeapProfiler& VM::ensureHeapProfiler()
464 {
465     if (!m_heapProfiler)
466         m_heapProfiler = std::make_unique<HeapProfiler>(*this);
467     return *m_heapProfiler;
468 }
469
470 #if ENABLE(SAMPLING_PROFILER)
471 SamplingProfiler& VM::ensureSamplingProfiler(RefPtr<Stopwatch>&& stopwatch)
472 {
473     if (!m_samplingProfiler)
474         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
475     return *m_samplingProfiler;
476 }
477 #endif // ENABLE(SAMPLING_PROFILER)
478
479 #if ENABLE(JIT)
480 static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
481 {
482     switch (intrinsic) {
483     case CharCodeAtIntrinsic:
484         return charCodeAtThunkGenerator;
485     case CharAtIntrinsic:
486         return charAtThunkGenerator;
487     case Clz32Intrinsic:
488         return clz32ThunkGenerator;
489     case FromCharCodeIntrinsic:
490         return fromCharCodeThunkGenerator;
491     case SqrtIntrinsic:
492         return sqrtThunkGenerator;
493     case AbsIntrinsic:
494         return absThunkGenerator;
495     case FloorIntrinsic:
496         return floorThunkGenerator;
497     case CeilIntrinsic:
498         return ceilThunkGenerator;
499     case TruncIntrinsic:
500         return truncThunkGenerator;
501     case RoundIntrinsic:
502         return roundThunkGenerator;
503     case ExpIntrinsic:
504         return expThunkGenerator;
505     case LogIntrinsic:
506         return logThunkGenerator;
507     case IMulIntrinsic:
508         return imulThunkGenerator;
509     case RandomIntrinsic:
510         return randomThunkGenerator;
511     case BoundThisNoArgsFunctionCallIntrinsic:
512         return boundThisNoArgsFunctionCallGenerator;
513     default:
514         return nullptr;
515     }
516 }
517
518 #endif // ENABLE(JIT)
519
520 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
521 {
522     return getHostFunction(function, NoIntrinsic, constructor, nullptr, name);
523 }
524
525 NativeExecutable* VM::getHostFunction(NativeFunction function, Intrinsic intrinsic, NativeFunction constructor, const DOMJIT::Signature* signature, const String& name)
526 {
527 #if ENABLE(JIT)
528     if (canUseJIT()) {
529         return jitStubs->hostFunctionStub(
530             this, function, constructor,
531             intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0,
532             intrinsic, signature, name);
533     }
534 #else // ENABLE(JIT)
535     UNUSED_PARAM(intrinsic);
536 #endif // ENABLE(JIT)
537     return NativeExecutable::create(*this,
538         adoptRef(*new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_call_trampoline), JITCode::HostCallThunk)), function,
539         adoptRef(*new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_construct_trampoline), JITCode::HostCallThunk)), constructor,
540         NoIntrinsic, signature, name);
541 }
542
543 VM::ClientData::~ClientData()
544 {
545 }
546
547 void VM::resetDateCache()
548 {
549     localTimeOffsetCache.reset();
550     cachedDateString = String();
551     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
552     dateInstanceCache.reset();
553 }
554
555 void VM::whenIdle(std::function<void()> callback)
556 {
557     if (!entryScope) {
558         callback();
559         return;
560     }
561
562     entryScope->addDidPopListener(callback);
563 }
564
565 void VM::deleteAllLinkedCode(DeleteAllCodeEffort effort)
566 {
567     whenIdle([=] () {
568         heap.deleteAllCodeBlocks(effort);
569     });
570 }
571
572 void VM::deleteAllCode(DeleteAllCodeEffort effort)
573 {
574     whenIdle([=] () {
575         m_codeCache->clear();
576         m_regExpCache->deleteAllCode();
577         heap.deleteAllCodeBlocks(effort);
578         heap.deleteAllUnlinkedCodeBlocks(effort);
579         heap.reportAbandonedObjectGraph();
580     });
581 }
582
583 SourceProviderCache* VM::addSourceProviderCache(SourceProvider* sourceProvider)
584 {
585     auto addResult = sourceProviderCacheMap.add(sourceProvider, nullptr);
586     if (addResult.isNewEntry)
587         addResult.iterator->value = adoptRef(new SourceProviderCache);
588     return addResult.iterator->value.get();
589 }
590
591 void VM::clearSourceProviderCaches()
592 {
593     sourceProviderCacheMap.clear();
594 }
595
596 void VM::throwException(ExecState* exec, Exception* exception)
597 {
598     if (Options::breakOnThrow()) {
599         CodeBlock* codeBlock = exec->codeBlock();
600         dataLog("Throwing exception in call frame ", RawPointer(exec), " for code block ", codeBlock, "\n");
601         CRASH();
602     }
603
604     ASSERT(exec == topCallFrame || exec == exec->lexicalGlobalObject()->globalExec() || exec == exec->vmEntryGlobalObject()->globalExec());
605
606     interpreter->notifyDebuggerOfExceptionToBeThrown(*this, exec, exception);
607
608     setException(exception);
609
610 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
611     m_nativeStackTraceOfLastThrow = std::unique_ptr<StackTrace>(StackTrace::captureStackTrace(Options::unexpectedExceptionStackTraceLimit()));
612     m_throwingThread = currentThread();
613 #endif
614 }
615
616 JSValue VM::throwException(ExecState* exec, JSValue thrownValue)
617 {
618     VM& vm = *this;
619     Exception* exception = jsDynamicCast<Exception*>(vm, thrownValue);
620     if (!exception)
621         exception = Exception::create(*this, thrownValue);
622
623     throwException(exec, exception);
624     return JSValue(exception);
625 }
626
627 JSObject* VM::throwException(ExecState* exec, JSObject* error)
628 {
629     return asObject(throwException(exec, JSValue(error)));
630 }
631
632 void VM::setStackPointerAtVMEntry(void* sp)
633 {
634     m_stackPointerAtVMEntry = sp;
635     updateStackLimits();
636 }
637
638 size_t VM::updateSoftReservedZoneSize(size_t softReservedZoneSize)
639 {
640     size_t oldSoftReservedZoneSize = m_currentSoftReservedZoneSize;
641     m_currentSoftReservedZoneSize = softReservedZoneSize;
642 #if !ENABLE(JIT)
643     interpreter->cloopStack().setSoftReservedZoneSize(softReservedZoneSize);
644 #endif
645
646     updateStackLimits();
647
648     return oldSoftReservedZoneSize;
649 }
650
651 #if OS(WINDOWS)
652 // On Windows the reserved stack space consists of committed memory, a guard page, and uncommitted memory,
653 // where the guard page is a barrier between committed and uncommitted memory.
654 // When data from the guard page is read or written, the guard page is moved, and memory is committed.
655 // This is how the system grows the stack.
656 // When using the C stack on Windows we need to precommit the needed stack space.
657 // Otherwise we might crash later if we access uncommitted stack memory.
658 // This can happen if we allocate stack space larger than the page guard size (4K).
659 // The system does not get the chance to move the guard page, and commit more memory,
660 // and we crash if uncommitted memory is accessed.
661 // The MSVC compiler fixes this by inserting a call to the _chkstk() function,
662 // when needed, see http://support.microsoft.com/kb/100775.
663 // By touching every page up to the stack limit with a dummy operation,
664 // we force the system to move the guard page, and commit memory.
665
666 static void preCommitStackMemory(void* stackLimit)
667 {
668     const int pageSize = 4096;
669     for (volatile char* p = reinterpret_cast<char*>(&stackLimit); p > stackLimit; p -= pageSize) {
670         char ch = *p;
671         *p = ch;
672     }
673 }
674 #endif
675
676 inline void VM::updateStackLimits()
677 {
678 #if OS(WINDOWS)
679     void* lastSoftStackLimit = m_softStackLimit;
680 #endif
681
682     size_t reservedZoneSize = Options::reservedZoneSize();
683     if (m_stackPointerAtVMEntry) {
684         ASSERT(wtfThreadData().stack().isGrowingDownward());
685         char* startOfStack = reinterpret_cast<char*>(m_stackPointerAtVMEntry);
686         m_softStackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_currentSoftReservedZoneSize);
687         m_stackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), reservedZoneSize);
688     } else {
689         m_softStackLimit = wtfThreadData().stack().recursionLimit(m_currentSoftReservedZoneSize);
690         m_stackLimit = wtfThreadData().stack().recursionLimit(reservedZoneSize);
691     }
692
693 #if OS(WINDOWS)
694     // We only need to precommit stack memory dictated by the VM::m_softStackLimit limit.
695     // This is because VM::m_softStackLimit applies to stack usage by LLINT asm or JIT
696     // generated code which can allocate stack space that the C++ compiler does not know
697     // about. As such, we have to precommit that stack memory manually.
698     //
699     // In contrast, we do not need to worry about VM::m_stackLimit because that limit is
700     // used exclusively by C++ code, and the C++ compiler will automatically commit the
701     // needed stack pages.
702     if (lastSoftStackLimit != m_softStackLimit)
703         preCommitStackMemory(m_softStackLimit);
704 #endif
705 }
706
707 #if ENABLE(DFG_JIT)
708 void VM::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
709 {
710     for (auto* scratchBuffer : scratchBuffers) {
711         if (scratchBuffer->activeLength()) {
712             void* bufferStart = scratchBuffer->dataBuffer();
713             conservativeRoots.add(bufferStart, static_cast<void*>(static_cast<char*>(bufferStart) + scratchBuffer->activeLength()));
714         }
715     }
716 }
717 #endif
718
719 void logSanitizeStack(VM* vm)
720 {
721     if (Options::verboseSanitizeStack() && vm->topCallFrame) {
722         int dummy;
723         dataLog(
724             "Sanitizing stack with top call frame at ", RawPointer(vm->topCallFrame),
725             ", current stack pointer at ", RawPointer(&dummy), ", in ",
726             pointerDump(vm->topCallFrame->codeBlock()), " and last code origin = ",
727             vm->topCallFrame->codeOrigin(), "\n");
728     }
729 }
730
731 #if ENABLE(REGEXP_TRACING)
732 void VM::addRegExpToTrace(RegExp* regExp)
733 {
734     gcProtect(regExp);
735     m_rtTraceList->add(regExp);
736 }
737
738 void VM::dumpRegExpTrace()
739 {
740     // The first RegExp object is ignored.  It is create by the RegExpPrototype ctor and not used.
741     RTTraceList::iterator iter = ++m_rtTraceList->begin();
742     
743     if (iter != m_rtTraceList->end()) {
744         dataLogF("\nRegExp Tracing\n");
745         dataLogF("Regular Expression                              8 Bit          16 Bit        match()    Matches    Average\n");
746         dataLogF(" <Match only / Match>                         JIT Addr      JIT Address       calls      found   String len\n");
747         dataLogF("----------------------------------------+----------------+----------------+----------+----------+-----------\n");
748     
749         unsigned reCount = 0;
750     
751         for (; iter != m_rtTraceList->end(); ++iter, ++reCount) {
752             (*iter)->printTraceData();
753             gcUnprotect(*iter);
754         }
755
756         dataLogF("%d Regular Expressions\n", reCount);
757     }
758     
759     m_rtTraceList->clear();
760 }
761 #else
762 void VM::dumpRegExpTrace()
763 {
764 }
765 #endif
766
767 WatchpointSet* VM::ensureWatchpointSetForImpureProperty(const Identifier& propertyName)
768 {
769     auto result = m_impurePropertyWatchpointSets.add(propertyName.string(), nullptr);
770     if (result.isNewEntry)
771         result.iterator->value = adoptRef(new WatchpointSet(IsWatched));
772     return result.iterator->value.get();
773 }
774
775 void VM::registerWatchpointForImpureProperty(const Identifier& propertyName, Watchpoint* watchpoint)
776 {
777     ensureWatchpointSetForImpureProperty(propertyName)->add(watchpoint);
778 }
779
780 void VM::addImpureProperty(const String& propertyName)
781 {
782     if (RefPtr<WatchpointSet> watchpointSet = m_impurePropertyWatchpointSets.take(propertyName))
783         watchpointSet->fireAll(*this, "Impure property added");
784 }
785
786 static bool enableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doEnableWork)
787 {
788     bool needsToRecompile = false;
789     if (!counter) {
790         doEnableWork();
791         needsToRecompile = true;
792     }
793     counter++;
794
795     return needsToRecompile;
796 }
797
798 static bool disableProfilerWithRespectToCount(unsigned& counter, std::function<void()> doDisableWork)
799 {
800     RELEASE_ASSERT(counter > 0);
801     bool needsToRecompile = false;
802     counter--;
803     if (!counter) {
804         doDisableWork();
805         needsToRecompile = true;
806     }
807
808     return needsToRecompile;
809 }
810
811 bool VM::enableTypeProfiler()
812 {
813     auto enableTypeProfiler = [this] () {
814         this->m_typeProfiler = std::make_unique<TypeProfiler>();
815         this->m_typeProfilerLog = std::make_unique<TypeProfilerLog>();
816     };
817
818     return enableProfilerWithRespectToCount(m_typeProfilerEnabledCount, enableTypeProfiler);
819 }
820
821 bool VM::disableTypeProfiler()
822 {
823     auto disableTypeProfiler = [this] () {
824         this->m_typeProfiler.reset(nullptr);
825         this->m_typeProfilerLog.reset(nullptr);
826     };
827
828     return disableProfilerWithRespectToCount(m_typeProfilerEnabledCount, disableTypeProfiler);
829 }
830
831 bool VM::enableControlFlowProfiler()
832 {
833     auto enableControlFlowProfiler = [this] () {
834         this->m_controlFlowProfiler = std::make_unique<ControlFlowProfiler>();
835     };
836
837     return enableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, enableControlFlowProfiler);
838 }
839
840 bool VM::disableControlFlowProfiler()
841 {
842     auto disableControlFlowProfiler = [this] () {
843         this->m_controlFlowProfiler.reset(nullptr);
844     };
845
846     return disableProfilerWithRespectToCount(m_controlFlowProfilerEnabledCount, disableControlFlowProfiler);
847 }
848
849 void VM::dumpTypeProfilerData()
850 {
851     if (!typeProfiler())
852         return;
853
854     typeProfilerLog()->processLogEntries(ASCIILiteral("VM Dump Types"));
855     typeProfiler()->dumpTypeProfilerData(*this);
856 }
857
858 void VM::queueMicrotask(JSGlobalObject& globalObject, Ref<Microtask>&& task)
859 {
860     m_microtaskQueue.append(std::make_unique<QueuedTask>(*this, &globalObject, WTFMove(task)));
861 }
862
863 void VM::drainMicrotasks()
864 {
865     while (!m_microtaskQueue.isEmpty())
866         m_microtaskQueue.takeFirst()->run();
867 }
868
869 void QueuedTask::run()
870 {
871     m_microtask->run(m_globalObject->globalExec());
872 }
873
874 void sanitizeStackForVM(VM* vm)
875 {
876     logSanitizeStack(vm);
877 #if !ENABLE(JIT)
878     vm->interpreter->cloopStack().sanitizeStack();
879 #else
880     sanitizeStackForVMImpl(vm);
881 #endif
882 }
883
884 size_t VM::committedStackByteCount()
885 {
886 #if ENABLE(JIT)
887     // When using the C stack, we don't know how many stack pages are actually
888     // committed. So, we use the current stack usage as an estimate.
889     ASSERT(wtfThreadData().stack().isGrowingDownward());
890     int8_t* current = reinterpret_cast<int8_t*>(&current);
891     int8_t* high = reinterpret_cast<int8_t*>(wtfThreadData().stack().origin());
892     return high - current;
893 #else
894     return CLoopStack::committedByteCount();
895 #endif
896 }
897
898 #if !ENABLE(JIT)
899 bool VM::ensureStackCapacityForCLoop(Register* newTopOfStack)
900 {
901     return interpreter->cloopStack().ensureCapacityFor(newTopOfStack);
902 }
903
904 bool VM::isSafeToRecurseSoftCLoop() const
905 {
906     return interpreter->cloopStack().isSafeToRecurse();
907 }
908 #endif // !ENABLE(JIT)
909
910 #if ENABLE(EXCEPTION_SCOPE_VERIFICATION)
911 void VM::verifyExceptionCheckNeedIsSatisfied(unsigned recursionDepth, ExceptionEventLocation& location)
912 {
913     if (!Options::validateExceptionChecks())
914         return;
915
916     if (UNLIKELY(m_needExceptionCheck)) {
917         auto throwDepth = m_simulatedThrowPointRecursionDepth;
918         auto& throwLocation = m_simulatedThrowPointLocation;
919
920         dataLog(
921             "ERROR: Unchecked JS exception:\n"
922             "    This scope can throw a JS exception: ", throwLocation, "\n"
923             "        (ExceptionScope::m_recursionDepth was ", throwDepth, ")\n"
924             "    But the exception was unchecked as of this scope: ", location, "\n"
925             "        (ExceptionScope::m_recursionDepth was ", recursionDepth, ")\n"
926             "\n");
927
928         RELEASE_ASSERT(!m_needExceptionCheck);
929     }
930 }
931 #endif
932
933 #if ENABLE(JIT)
934 RegisterAtOffsetList* VM::getAllCalleeSaveRegisterOffsets()
935 {
936     static RegisterAtOffsetList* result;
937
938     static std::once_flag calleeSavesFlag;
939     std::call_once(calleeSavesFlag, [] () {
940         result = new RegisterAtOffsetList(RegisterSet::vmCalleeSaveRegisters(), RegisterAtOffsetList::ZeroBased);
941     });
942
943     return result;
944 }
945 #endif // ENABLE(JIT)
946
947 } // namespace JSC