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