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