One file per class for CodeBlock.h/.cpp
[WebKit-https.git] / Source / JavaScriptCore / runtime / VM.cpp
1 /*
2  * Copyright (C) 2008, 2011, 2013-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "VM.h"
31
32 #include "ArgList.h"
33 #include "ArrayBufferNeuteringWatchpoint.h"
34 #include "BuiltinExecutables.h"
35 #include "BytecodeIntrinsicRegistry.h"
36 #include "CodeBlock.h"
37 #include "CodeCache.h"
38 #include "CommonIdentifiers.h"
39 #include "CommonSlowPaths.h"
40 #include "CustomGetterSetter.h"
41 #include "DFGLongLivedState.h"
42 #include "DFGWorklist.h"
43 #include "Disassembler.h"
44 #include "ErrorInstance.h"
45 #include "EvalCodeBlock.h"
46 #include "Exception.h"
47 #include "FTLThunks.h"
48 #include "FunctionCodeBlock.h"
49 #include "FunctionConstructor.h"
50 #include "GCActivityCallback.h"
51 #include "GetterSetter.h"
52 #include "HasOwnPropertyCache.h"
53 #include "Heap.h"
54 #include "HeapIterationScope.h"
55 #include "HeapProfiler.h"
56 #include "HostCallReturnValue.h"
57 #include "Identifier.h"
58 #include "IncrementalSweeper.h"
59 #include "InferredTypeTable.h"
60 #include "Interpreter.h"
61 #include "JITCode.h"
62 #include "JITWorklist.h"
63 #include "JSAPIValueWrapper.h"
64 #include "JSArray.h"
65 #include "JSCInlines.h"
66 #include "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 "JSTemplateRegistryKey.h"
74 #include "JSWithScope.h"
75 #include "LLIntData.h"
76 #include "Lexer.h"
77 #include "Lookup.h"
78 #include "ModuleProgramCodeBlock.h"
79 #include "NativeStdFunctionCell.h"
80 #include "Nodes.h"
81 #include "Parser.h"
82 #include "ProfilerDatabase.h"
83 #include "ProgramCodeBlock.h"
84 #include "PropertyMapHashTable.h"
85 #include "RegExpCache.h"
86 #include "RegExpObject.h"
87 #include "RegisterAtOffsetList.h"
88 #include "RuntimeType.h"
89 #include "SamplingProfiler.h"
90 #include "ShadowChicken.h"
91 #include "SimpleTypedArrayController.h"
92 #include "SourceProviderCache.h"
93 #include "StackVisitor.h"
94 #include "StrictEvalActivation.h"
95 #include "StrongInlines.h"
96 #include "StructureInlines.h"
97 #include "TypeProfiler.h"
98 #include "TypeProfilerLog.h"
99 #include "UnlinkedCodeBlock.h"
100 #include "VMEntryScope.h"
101 #include "Watchdog.h"
102 #include "WeakGCMapInlines.h"
103 #include "WeakMapData.h"
104 #include "WebAssemblyCodeBlock.h"
105 #include <wtf/CurrentTime.h>
106 #include <wtf/ProcessID.h>
107 #include <wtf/SimpleStats.h>
108 #include <wtf/StringPrintStream.h>
109 #include <wtf/Threading.h>
110 #include <wtf/WTFThreadData.h>
111 #include <wtf/text/AtomicStringTable.h>
112 #include <wtf/text/SymbolRegistry.h>
113
114 #if !ENABLE(JIT)
115 #include "CLoopStack.h"
116 #include "CLoopStackInlines.h"
117 #endif
118
119 #if ENABLE(DFG_JIT)
120 #include "ConservativeRoots.h"
121 #endif
122
123 #if ENABLE(REGEXP_TRACING)
124 #include "RegExp.h"
125 #endif
126
127 #if USE(CF)
128 #include <CoreFoundation/CoreFoundation.h>
129 #endif
130
131 using namespace WTF;
132
133 namespace JSC {
134
135 // Note: Platform.h will enforce that ENABLE(ASSEMBLER) is true if either
136 // ENABLE(JIT) or ENABLE(YARR_JIT) or both are enabled. The code below
137 // just checks for ENABLE(JIT) or ENABLE(YARR_JIT) with this premise in mind.
138
139 #if ENABLE(ASSEMBLER)
140 static bool enableAssembler(ExecutableAllocator& executableAllocator)
141 {
142     if (!Options::useJIT() && !Options::useRegExpJIT())
143         return false;
144
145     if (!executableAllocator.isValid()) {
146         if (Options::crashIfCantAllocateJITMemory())
147             CRASH();
148         return false;
149     }
150
151 #if USE(CF) || OS(UNIX)
152     char* canUseJITString = getenv("JavaScriptCoreUseJIT");
153     return !canUseJITString || atoi(canUseJITString);
154 #else
155     return true;
156 #endif
157 }
158 #endif // ENABLE(!ASSEMBLER)
159
160 VM::VM(VMType vmType, HeapType heapType)
161     : m_apiLock(adoptRef(new JSLock(this)))
162 #if ENABLE(ASSEMBLER)
163     , executableAllocator(*this)
164 #endif
165     , heap(this, heapType)
166     , vmType(vmType)
167     , clientData(0)
168     , topVMEntryFrame(nullptr)
169     , topCallFrame(CallFrame::noCaller())
170     , m_atomicStringTable(vmType == Default ? wtfThreadData().atomicStringTable() : new AtomicStringTable)
171     , propertyNames(nullptr)
172     , emptyList(new MarkedArgumentBuffer)
173     , machineCodeBytesPerBytecodeWordForBaselineJIT(std::make_unique<SimpleStats>())
174     , customGetterSetterFunctionMap(*this)
175     , stringCache(*this)
176     , symbolImplToSymbolMap(*this)
177     , prototypeMap(*this)
178     , interpreter(0)
179     , jsArrayClassInfo(JSArray::info())
180     , jsFinalObjectClassInfo(JSFinalObject::info())
181     , sizeOfLastScratchBuffer(0)
182     , entryScope(0)
183     , m_regExpCache(new RegExpCache(this))
184 #if ENABLE(REGEXP_TRACING)
185     , m_rtTraceList(new RTTraceList())
186 #endif
187 #if ENABLE(ASSEMBLER)
188     , m_canUseAssembler(enableAssembler(executableAllocator))
189 #endif
190 #if ENABLE(JIT)
191     , m_canUseJIT(m_canUseAssembler && Options::useJIT())
192 #endif
193 #if ENABLE(YARR_JIT)
194     , m_canUseRegExpJIT(m_canUseAssembler && Options::useRegExpJIT())
195 #endif
196 #if ENABLE(GC_VALIDATION)
197     , m_initializingObjectClass(0)
198 #endif
199     , m_stackPointerAtVMEntry(0)
200     , m_codeCache(std::make_unique<CodeCache>())
201     , m_builtinExecutables(std::make_unique<BuiltinExecutables>(*this))
202     , m_typeProfilerEnabledCount(0)
203     , m_controlFlowProfilerEnabledCount(0)
204     , m_shadowChicken(std::make_unique<ShadowChicken>())
205 {
206     interpreter = new Interpreter(*this);
207     StackBounds stack = wtfThreadData().stack();
208     updateSoftReservedZoneSize(Options::softReservedZoneSize());
209     setLastStackTop(stack.origin());
210
211     // Need to be careful to keep everything consistent here
212     JSLockHolder lock(this);
213     AtomicStringTable* existingEntryAtomicStringTable = wtfThreadData().setCurrentAtomicStringTable(m_atomicStringTable);
214     propertyNames = new CommonIdentifiers(this);
215     structureStructure.set(*this, Structure::createStructure(*this));
216     structureRareDataStructure.set(*this, StructureRareData::createStructure(*this, 0, jsNull()));
217     terminatedExecutionErrorStructure.set(*this, TerminatedExecutionError::createStructure(*this, 0, jsNull()));
218     stringStructure.set(*this, JSString::createStructure(*this, 0, jsNull()));
219     propertyNameEnumeratorStructure.set(*this, JSPropertyNameEnumerator::createStructure(*this, 0, jsNull()));
220     customGetterSetterStructure.set(*this, CustomGetterSetter::createStructure(*this, 0, jsNull()));
221     scopedArgumentsTableStructure.set(*this, ScopedArgumentsTable::createStructure(*this, 0, jsNull()));
222     apiWrapperStructure.set(*this, JSAPIValueWrapper::createStructure(*this, 0, jsNull()));
223     JSScopeStructure.set(*this, JSScope::createStructure(*this, 0, jsNull()));
224     executableStructure.set(*this, ExecutableBase::createStructure(*this, 0, jsNull()));
225     nativeExecutableStructure.set(*this, NativeExecutable::createStructure(*this, 0, jsNull()));
226     evalExecutableStructure.set(*this, EvalExecutable::createStructure(*this, 0, jsNull()));
227     programExecutableStructure.set(*this, ProgramExecutable::createStructure(*this, 0, jsNull()));
228     functionExecutableStructure.set(*this, FunctionExecutable::createStructure(*this, 0, jsNull()));
229 #if ENABLE(WEBASSEMBLY)
230     webAssemblyExecutableStructure.set(*this, WebAssemblyExecutable::createStructure(*this, 0, jsNull()));
231 #endif
232     moduleProgramExecutableStructure.set(*this, ModuleProgramExecutable::createStructure(*this, 0, jsNull()));
233     regExpStructure.set(*this, RegExp::createStructure(*this, 0, jsNull()));
234     symbolStructure.set(*this, Symbol::createStructure(*this, 0, jsNull()));
235     symbolTableStructure.set(*this, SymbolTable::createStructure(*this, 0, jsNull()));
236     structureChainStructure.set(*this, StructureChain::createStructure(*this, 0, jsNull()));
237     sparseArrayValueMapStructure.set(*this, SparseArrayValueMap::createStructure(*this, 0, jsNull()));
238     templateRegistryKeyStructure.set(*this, JSTemplateRegistryKey::createStructure(*this, 0, jsNull()));
239     arrayBufferNeuteringWatchpointStructure.set(*this, ArrayBufferNeuteringWatchpoint::createStructure(*this));
240     unlinkedFunctionExecutableStructure.set(*this, UnlinkedFunctionExecutable::createStructure(*this, 0, jsNull()));
241     unlinkedProgramCodeBlockStructure.set(*this, UnlinkedProgramCodeBlock::createStructure(*this, 0, jsNull()));
242     unlinkedEvalCodeBlockStructure.set(*this, UnlinkedEvalCodeBlock::createStructure(*this, 0, jsNull()));
243     unlinkedFunctionCodeBlockStructure.set(*this, UnlinkedFunctionCodeBlock::createStructure(*this, 0, jsNull()));
244     unlinkedModuleProgramCodeBlockStructure.set(*this, UnlinkedModuleProgramCodeBlock::createStructure(*this, 0, jsNull()));
245     propertyTableStructure.set(*this, PropertyTable::createStructure(*this, 0, jsNull()));
246     weakMapDataStructure.set(*this, WeakMapData::createStructure(*this, 0, jsNull()));
247     inferredValueStructure.set(*this, InferredValue::createStructure(*this, 0, jsNull()));
248     inferredTypeStructure.set(*this, InferredType::createStructure(*this, 0, jsNull()));
249     inferredTypeTableStructure.set(*this, InferredTypeTable::createStructure(*this, 0, jsNull()));
250     functionRareDataStructure.set(*this, FunctionRareData::createStructure(*this, 0, jsNull()));
251     exceptionStructure.set(*this, Exception::createStructure(*this, 0, jsNull()));
252     promiseDeferredStructure.set(*this, JSPromiseDeferred::createStructure(*this, 0, jsNull()));
253     internalPromiseDeferredStructure.set(*this, JSInternalPromiseDeferred::createStructure(*this, 0, jsNull()));
254     programCodeBlockStructure.set(*this, ProgramCodeBlock::createStructure(*this, 0, jsNull()));
255     moduleProgramCodeBlockStructure.set(*this, ModuleProgramCodeBlock::createStructure(*this, 0, jsNull()));
256     evalCodeBlockStructure.set(*this, EvalCodeBlock::createStructure(*this, 0, jsNull()));
257     functionCodeBlockStructure.set(*this, FunctionCodeBlock::createStructure(*this, 0, jsNull()));
258 #if ENABLE(WEBASSEMBLY)
259     webAssemblyCodeBlockStructure.set(*this, WebAssemblyCodeBlock::createStructure(*this, 0, jsNull()));
260 #endif
261     hashMapBucketSetStructure.set(*this, HashMapBucket<HashMapBucketDataKey>::createStructure(*this, 0, jsNull()));
262     hashMapBucketMapStructure.set(*this, HashMapBucket<HashMapBucketDataKeyValue>::createStructure(*this, 0, jsNull()));
263     hashMapImplSetStructure.set(*this, HashMapImpl<HashMapBucket<HashMapBucketDataKey>>::createStructure(*this, 0, jsNull()));
264     hashMapImplMapStructure.set(*this, HashMapImpl<HashMapBucket<HashMapBucketDataKeyValue>>::createStructure(*this, 0, jsNull()));
265
266     iterationTerminator.set(*this, JSFinalObject::create(*this, JSFinalObject::createStructure(*this, 0, jsNull(), 1)));
267     nativeStdFunctionCellStructure.set(*this, NativeStdFunctionCell::createStructure(*this, 0, jsNull()));
268     smallStrings.initializeCommonStrings(*this);
269
270     wtfThreadData().setCurrentAtomicStringTable(existingEntryAtomicStringTable);
271
272 #if ENABLE(JIT)
273     jitStubs = std::make_unique<JITThunks>();
274     allCalleeSaveRegisterOffsets = std::make_unique<RegisterAtOffsetList>(RegisterSet::vmCalleeSaveRegisters(), RegisterAtOffsetList::ZeroBased);
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     interpreter->initialize();
283     
284 #if ENABLE(JIT)
285     initializeHostCallReturnValue(); // This is needed to convince the linker not to drop host call return support.
286 #endif
287
288     heap.notifyIsSafeToCollect();
289     
290     LLInt::Data::performAssertions(*this);
291     
292     if (Options::useProfiler()) {
293         m_perBytecodeProfiler = std::make_unique<Profiler::Database>(*this);
294
295         StringPrintStream pathOut;
296         const char* profilerPath = getenv("JSC_PROFILER_PATH");
297         if (profilerPath)
298             pathOut.print(profilerPath, "/");
299         pathOut.print("JSCProfile-", getCurrentProcessID(), "-", m_perBytecodeProfiler->databaseID(), ".json");
300         m_perBytecodeProfiler->registerToSaveAtExit(pathOut.toCString().data());
301     }
302
303     callFrameForCatch = nullptr;
304
305 #if ENABLE(DFG_JIT)
306     if (canUseJIT())
307         dfgState = std::make_unique<DFG::LongLivedState>();
308 #endif
309     
310     // Initialize this last, as a free way of asserting that VM initialization itself
311     // won't use this.
312     m_typedArrayController = adoptRef(new SimpleTypedArrayController());
313
314     m_bytecodeIntrinsicRegistry = std::make_unique<BytecodeIntrinsicRegistry>(*this);
315
316     if (Options::useTypeProfiler())
317         enableTypeProfiler();
318     if (Options::useControlFlowProfiler())
319         enableControlFlowProfiler();
320 #if ENABLE(SAMPLING_PROFILER)
321     if (Options::useSamplingProfiler()) {
322         setShouldBuildPCToCodeOriginMapping();
323         Ref<Stopwatch> stopwatch = Stopwatch::create();
324         stopwatch->start();
325         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
326         if (Options::samplingProfilerPath())
327             m_samplingProfiler->registerForReportAtExit();
328         m_samplingProfiler->start();
329     }
330 #endif // ENABLE(SAMPLING_PROFILER)
331
332     if (Options::alwaysGeneratePCToCodeOriginMap())
333         setShouldBuildPCToCodeOriginMapping();
334
335     if (Options::watchdog()) {
336         std::chrono::milliseconds timeoutMillis(Options::watchdog());
337         Watchdog& watchdog = ensureWatchdog();
338         watchdog.setTimeLimit(timeoutMillis);
339     }
340 }
341
342 VM::~VM()
343 {
344     // Never GC, ever again.
345     heap.incrementDeferralDepth();
346
347 #if ENABLE(SAMPLING_PROFILER)
348     if (m_samplingProfiler) {
349         m_samplingProfiler->reportDataToOptionFile();
350         m_samplingProfiler->shutdown();
351     }
352 #endif // ENABLE(SAMPLING_PROFILER)
353     
354 #if ENABLE(JIT)
355     JITWorklist::instance()->completeAllForVM(*this);
356 #endif // ENABLE(JIT)
357
358 #if ENABLE(DFG_JIT)
359     // Make sure concurrent compilations are done, but don't install them, since there is
360     // no point to doing so.
361     for (unsigned i = DFG::numberOfWorklists(); i--;) {
362         if (DFG::Worklist* worklist = DFG::existingWorklistForIndexOrNull(i)) {
363             worklist->removeNonCompilingPlansForVM(*this);
364             worklist->waitUntilAllPlansForVMAreReady(*this);
365             worklist->removeAllReadyPlansForVM(*this);
366         }
367     }
368 #endif // ENABLE(DFG_JIT)
369     
370     waitForAsynchronousDisassembly();
371     
372     // Clear this first to ensure that nobody tries to remove themselves from it.
373     m_perBytecodeProfiler = nullptr;
374
375     ASSERT(m_apiLock->currentThreadIsHoldingLock());
376     m_apiLock->willDestroyVM(this);
377     heap.lastChanceToFinalize();
378
379     delete interpreter;
380 #ifndef NDEBUG
381     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);
382 #endif
383
384     delete emptyList;
385
386     delete propertyNames;
387     if (vmType != Default)
388         delete m_atomicStringTable;
389
390     delete clientData;
391     delete m_regExpCache;
392 #if ENABLE(REGEXP_TRACING)
393     delete m_rtTraceList;
394 #endif
395
396 #if ENABLE(DFG_JIT)
397     for (unsigned i = 0; i < scratchBuffers.size(); ++i)
398         fastFree(scratchBuffers[i]);
399 #endif
400 }
401
402 void VM::setLastStackTop(void* lastStackTop)
403
404     m_lastStackTop = lastStackTop;
405 }
406
407 Ref<VM> VM::createContextGroup(HeapType heapType)
408 {
409     return adoptRef(*new VM(APIContextGroup, heapType));
410 }
411
412 Ref<VM> VM::create(HeapType heapType)
413 {
414     return adoptRef(*new VM(Default, heapType));
415 }
416
417 Ref<VM> VM::createLeaked(HeapType heapType)
418 {
419     return create(heapType);
420 }
421
422 bool VM::sharedInstanceExists()
423 {
424     return sharedInstanceInternal();
425 }
426
427 VM& VM::sharedInstance()
428 {
429     GlobalJSLock globalLock;
430     VM*& instance = sharedInstanceInternal();
431     if (!instance)
432         instance = adoptRef(new VM(APIShared, SmallHeap)).leakRef();
433     return *instance;
434 }
435
436 VM*& VM::sharedInstanceInternal()
437 {
438     static VM* sharedInstance;
439     return sharedInstance;
440 }
441
442 Watchdog& VM::ensureWatchdog()
443 {
444     if (!m_watchdog) {
445         m_watchdog = adoptRef(new Watchdog());
446         
447         // The LLINT peeks into the Watchdog object directly. In order to do that,
448         // the LLINT assumes that the internal shape of a std::unique_ptr is the
449         // same as a plain C++ pointer, and loads the address of Watchdog from it.
450         RELEASE_ASSERT(*reinterpret_cast<Watchdog**>(&m_watchdog) == m_watchdog.get());
451
452         // And if we've previously compiled any functions, we need to revert
453         // them because they don't have the needed polling checks for the watchdog
454         // yet.
455         deleteAllCode();
456     }
457     return *m_watchdog;
458 }
459
460 HeapProfiler& VM::ensureHeapProfiler()
461 {
462     if (!m_heapProfiler)
463         m_heapProfiler = std::make_unique<HeapProfiler>(*this);
464     return *m_heapProfiler;
465 }
466
467 #if ENABLE(SAMPLING_PROFILER)
468 SamplingProfiler& VM::ensureSamplingProfiler(RefPtr<Stopwatch>&& stopwatch)
469 {
470     if (!m_samplingProfiler)
471         m_samplingProfiler = adoptRef(new SamplingProfiler(*this, WTFMove(stopwatch)));
472     return *m_samplingProfiler;
473 }
474 #endif // ENABLE(SAMPLING_PROFILER)
475
476 #if ENABLE(JIT)
477 static ThunkGenerator thunkGeneratorForIntrinsic(Intrinsic intrinsic)
478 {
479     switch (intrinsic) {
480     case CharCodeAtIntrinsic:
481         return charCodeAtThunkGenerator;
482     case CharAtIntrinsic:
483         return charAtThunkGenerator;
484     case Clz32Intrinsic:
485         return clz32ThunkGenerator;
486     case FromCharCodeIntrinsic:
487         return fromCharCodeThunkGenerator;
488     case SqrtIntrinsic:
489         return sqrtThunkGenerator;
490     case AbsIntrinsic:
491         return absThunkGenerator;
492     case FloorIntrinsic:
493         return floorThunkGenerator;
494     case CeilIntrinsic:
495         return ceilThunkGenerator;
496     case TruncIntrinsic:
497         return truncThunkGenerator;
498     case RoundIntrinsic:
499         return roundThunkGenerator;
500     case ExpIntrinsic:
501         return expThunkGenerator;
502     case LogIntrinsic:
503         return logThunkGenerator;
504     case IMulIntrinsic:
505         return imulThunkGenerator;
506     case RandomIntrinsic:
507         return randomThunkGenerator;
508     case BoundThisNoArgsFunctionCallIntrinsic:
509         return boundThisNoArgsFunctionCallGenerator;
510     default:
511         return nullptr;
512     }
513 }
514
515 #endif // ENABLE(JIT)
516
517 NativeExecutable* VM::getHostFunction(NativeFunction function, NativeFunction constructor, const String& name)
518 {
519     return getHostFunction(function, NoIntrinsic, constructor, name);
520 }
521
522 NativeExecutable* VM::getHostFunction(NativeFunction function, Intrinsic intrinsic, NativeFunction constructor, const String& name)
523 {
524 #if ENABLE(JIT)
525     if (canUseJIT()) {
526         return jitStubs->hostFunctionStub(
527             this, function, constructor,
528             intrinsic != NoIntrinsic ? thunkGeneratorForIntrinsic(intrinsic) : 0,
529             intrinsic, name);
530     }
531 #else // ENABLE(JIT)
532     UNUSED_PARAM(intrinsic);
533 #endif // ENABLE(JIT)
534     return NativeExecutable::create(*this,
535         adoptRef(new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_call_trampoline), JITCode::HostCallThunk)), function,
536         adoptRef(new NativeJITCode(MacroAssemblerCodeRef::createLLIntCodeRef(llint_native_construct_trampoline), JITCode::HostCallThunk)), constructor,
537         NoIntrinsic, name);
538 }
539
540 VM::ClientData::~ClientData()
541 {
542 }
543
544 void VM::resetDateCache()
545 {
546     localTimeOffsetCache.reset();
547     cachedDateString = String();
548     cachedDateStringValue = std::numeric_limits<double>::quiet_NaN();
549     dateInstanceCache.reset();
550 }
551
552 void VM::whenIdle(std::function<void()> callback)
553 {
554     if (!entryScope) {
555         callback();
556         return;
557     }
558
559     entryScope->addDidPopListener(callback);
560 }
561
562 void VM::deleteAllLinkedCode()
563 {
564     whenIdle([this]() {
565         heap.deleteAllCodeBlocks();
566     });
567 }
568
569 void VM::deleteAllCode()
570 {
571     whenIdle([this]() {
572         m_codeCache->clear();
573         m_regExpCache->deleteAllCode();
574         heap.deleteAllCodeBlocks();
575         heap.deleteAllUnlinkedCodeBlocks();
576         heap.reportAbandonedObjectGraph();
577     });
578 }
579
580 SourceProviderCache* VM::addSourceProviderCache(SourceProvider* sourceProvider)
581 {
582     auto addResult = sourceProviderCacheMap.add(sourceProvider, nullptr);
583     if (addResult.isNewEntry)
584         addResult.iterator->value = adoptRef(new SourceProviderCache);
585     return addResult.iterator->value.get();
586 }
587
588 void VM::clearSourceProviderCaches()
589 {
590     sourceProviderCacheMap.clear();
591 }
592
593 void VM::throwException(ExecState* exec, Exception* exception)
594 {
595     if (Options::breakOnThrow()) {
596         dataLog("In call frame ", RawPointer(exec), " for code block ", *exec->codeBlock(), "\n");
597         CRASH();
598     }
599
600     ASSERT(exec == topCallFrame || exec == exec->lexicalGlobalObject()->globalExec() || exec == exec->vmEntryGlobalObject()->globalExec());
601
602     interpreter->notifyDebuggerOfExceptionToBeThrown(exec, exception);
603
604     setException(exception);
605 }
606
607 JSValue VM::throwException(ExecState* exec, JSValue thrownValue)
608 {
609     Exception* exception = jsDynamicCast<Exception*>(thrownValue);
610     if (!exception)
611         exception = Exception::create(*this, thrownValue);
612
613     throwException(exec, exception);
614     return JSValue(exception);
615 }
616
617 JSObject* VM::throwException(ExecState* exec, JSObject* error)
618 {
619     return asObject(throwException(exec, JSValue(error)));
620 }
621
622 void VM::setStackPointerAtVMEntry(void* sp)
623 {
624     m_stackPointerAtVMEntry = sp;
625     updateStackLimits();
626 }
627
628 size_t VM::updateSoftReservedZoneSize(size_t softReservedZoneSize)
629 {
630     size_t oldSoftReservedZoneSize = m_currentSoftReservedZoneSize;
631     m_currentSoftReservedZoneSize = softReservedZoneSize;
632 #if !ENABLE(JIT)
633     interpreter->cloopStack().setSoftReservedZoneSize(softReservedZoneSize);
634 #endif
635
636     updateStackLimits();
637
638     return oldSoftReservedZoneSize;
639 }
640
641 #if PLATFORM(WIN)
642 // On Windows the reserved stack space consists of committed memory, a guard page, and uncommitted memory,
643 // where the guard page is a barrier between committed and uncommitted memory.
644 // When data from the guard page is read or written, the guard page is moved, and memory is committed.
645 // This is how the system grows the stack.
646 // When using the C stack on Windows we need to precommit the needed stack space.
647 // Otherwise we might crash later if we access uncommitted stack memory.
648 // This can happen if we allocate stack space larger than the page guard size (4K).
649 // The system does not get the chance to move the guard page, and commit more memory,
650 // and we crash if uncommitted memory is accessed.
651 // The MSVC compiler fixes this by inserting a call to the _chkstk() function,
652 // when needed, see http://support.microsoft.com/kb/100775.
653 // By touching every page up to the stack limit with a dummy operation,
654 // we force the system to move the guard page, and commit memory.
655
656 static void preCommitStackMemory(void* stackLimit)
657 {
658     const int pageSize = 4096;
659     for (volatile char* p = reinterpret_cast<char*>(&stackLimit); p > stackLimit; p -= pageSize) {
660         char ch = *p;
661         *p = ch;
662     }
663 }
664 #endif
665
666 inline void VM::updateStackLimits()
667 {
668 #if PLATFORM(WIN)
669     void* lastSoftStackLimit = m_softStackLimit;
670 #endif
671
672     size_t reservedZoneSize = Options::reservedZoneSize();
673     if (m_stackPointerAtVMEntry) {
674         ASSERT(wtfThreadData().stack().isGrowingDownward());
675         char* startOfStack = reinterpret_cast<char*>(m_stackPointerAtVMEntry);
676         m_softStackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), m_currentSoftReservedZoneSize);
677         m_stackLimit = wtfThreadData().stack().recursionLimit(startOfStack, Options::maxPerThreadStackUsage(), reservedZoneSize);
678     } else {
679         m_softStackLimit = wtfThreadData().stack().recursionLimit(m_currentSoftReservedZoneSize);
680         m_stackLimit = wtfThreadData().stack().recursionLimit(reservedZoneSize);
681     }
682
683 #if PLATFORM(WIN)
684     // We only need to precommit stack memory dictated by the VM::m_softStackLimit limit.
685     // This is because VM::m_softStackLimit applies to stack usage by LLINT asm or JIT
686     // generated code which can allocate stack space that the C++ compiler does not know
687     // about. As such, we have to precommit that stack memory manually.
688     //
689     // In contrast, we do not need to worry about VM::m_stackLimit because that limit is
690     // used exclusively by C++ code, and the C++ compiler will automatically commit the
691     // needed stack pages.
692     if (lastSoftStackLimit != m_softStackLimit)
693         preCommitStackMemory(m_softStackLimit);
694 #endif
695 }
696
697 #if ENABLE(DFG_JIT)
698 void VM::gatherConservativeRoots(ConservativeRoots& conservativeRoots)
699 {
700     for (size_t i = 0; i < scratchBuffers.size(); i++) {
701         ScratchBuffer* scratchBuffer = scratchBuffers[i];
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, PassRefPtr<Microtask> task)
850 {
851     m_microtaskQueue.append(std::make_unique<QueuedTask>(*this, globalObject, 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 } // namespace JSC