ThreadContext.cpp 157 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeBasePch.h"
  6. #include "ThreadServiceWrapper.h"
  7. #include "Types/TypePropertyCache.h"
  8. #ifdef ENABLE_SCRIPT_DEBUGGING
  9. #include "Debug/DebuggingFlags.h"
  10. #include "Debug/DiagProbe.h"
  11. #include "Debug/DebugManager.h"
  12. #endif
  13. #include "Chars.h"
  14. #include "CaseInsensitive.h"
  15. #include "CharSet.h"
  16. #include "CharMap.h"
  17. #include "StandardChars.h"
  18. #include "Base/ThreadContextTlsEntry.h"
  19. #include "Base/ThreadBoundThreadContextManager.h"
  20. #include "Language/SourceDynamicProfileManager.h"
  21. #include "Language/CodeGenRecyclableData.h"
  22. #include "Language/InterpreterStackFrame.h"
  23. #include "Language/JavascriptStackWalker.h"
  24. #include "Base/ScriptMemoryDumper.h"
  25. #if DBG
  26. #include "Memory/StressTest.h"
  27. #endif
  28. #ifdef DYNAMIC_PROFILE_MUTATOR
  29. #include "Language/DynamicProfileMutator.h"
  30. #endif
  31. #ifdef ENABLE_BASIC_TELEMETRY
  32. #include "Telemetry.h"
  33. #include "Recycler/RecyclerTelemetryTransmitter.h"
  34. #endif // ENABLE_BASIC_TELEMETRY
  35. const int TotalNumberOfBuiltInProperties = Js::PropertyIds::_countJSOnlyProperty;
  36. /*
  37. * When we aren't adding any additional properties
  38. */
  39. void DefaultInitializeAdditionalProperties(ThreadContext *threadContext)
  40. {
  41. }
  42. /*
  43. *
  44. */
  45. void (*InitializeAdditionalProperties)(ThreadContext *threadContext) = DefaultInitializeAdditionalProperties;
  46. CriticalSection ThreadContext::s_csThreadContext;
  47. size_t ThreadContext::processNativeCodeSize = 0;
  48. ThreadContext * ThreadContext::globalListFirst = nullptr;
  49. ThreadContext * ThreadContext::globalListLast = nullptr;
  50. THREAD_LOCAL uint ThreadContext::activeScriptSiteCount = 0;
  51. const Js::PropertyRecord * const ThreadContext::builtInPropertyRecords[] =
  52. {
  53. Js::BuiltInPropertyRecords::EMPTY,
  54. #define ENTRY_INTERNAL_SYMBOL(n) Js::BuiltInPropertyRecords::n,
  55. #define ENTRY_SYMBOL(n, d) Js::BuiltInPropertyRecords::n,
  56. #define ENTRY(n) Js::BuiltInPropertyRecords::n,
  57. #define ENTRY2(n, s) ENTRY(n)
  58. #include "Base/JnDirectFields.h"
  59. };
  60. ThreadContext::RecyclableData::RecyclableData(Recycler *const recycler) :
  61. pendingFinallyException(nullptr),
  62. soErrorObject(nullptr, nullptr, nullptr, true),
  63. oomErrorObject(nullptr, nullptr, nullptr, true),
  64. terminatedErrorObject(nullptr, nullptr, nullptr),
  65. typesWithProtoPropertyCache(recycler),
  66. #if ENABLE_NATIVE_CODEGEN
  67. propertyGuards(recycler, 128),
  68. #endif
  69. oldEntryPointInfo(nullptr),
  70. #ifdef ENABLE_SCRIPT_DEBUGGING
  71. returnedValueList(nullptr),
  72. #endif
  73. constructorCacheInvalidationCount(0)
  74. {
  75. }
  76. ThreadContext::ThreadContext(AllocationPolicyManager * allocationPolicyManager, JsUtil::ThreadService::ThreadServiceCallback threadServiceCallback, bool enableExperimentalFeatures) :
  77. currentThreadId(::GetCurrentThreadId()),
  78. stackLimitForCurrentThread(0),
  79. stackProber(nullptr),
  80. isThreadBound(false),
  81. hasThrownPendingException(false),
  82. hasBailedOutBitPtr(nullptr),
  83. noScriptScope(false),
  84. heapEnum(nullptr),
  85. threadContextFlags(ThreadContextFlagNoFlag),
  86. JsUtil::DoublyLinkedListElement<ThreadContext>(),
  87. allocationPolicyManager(allocationPolicyManager),
  88. threadService(threadServiceCallback),
  89. isOptimizedForManyInstances(Js::Configuration::Global.flags.OptimizeForManyInstances),
  90. bgJit(Js::Configuration::Global.flags.BgJit),
  91. pageAllocator(allocationPolicyManager, PageAllocatorType_Thread, Js::Configuration::Global.flags, 0, RecyclerHeuristic::Instance.DefaultMaxFreePageCount,
  92. false
  93. #if ENABLE_BACKGROUND_PAGE_FREEING
  94. , &backgroundPageQueue
  95. #endif
  96. ),
  97. recycler(nullptr),
  98. hasCollectionCallBack(false),
  99. callDispose(true),
  100. #if ENABLE_NATIVE_CODEGEN
  101. jobProcessor(nullptr),
  102. #endif
  103. interruptPoller(nullptr),
  104. expirableCollectModeGcCount(-1),
  105. expirableObjectList(nullptr),
  106. expirableObjectDisposeList(nullptr),
  107. numExpirableObjects(0),
  108. disableExpiration(false),
  109. callRootLevel(0),
  110. nextTypeId((Js::TypeId)Js::Constants::ReservedTypeIds),
  111. entryExitRecord(nullptr),
  112. leafInterpreterFrame(nullptr),
  113. threadServiceWrapper(nullptr),
  114. tryCatchFrameAddr(nullptr),
  115. temporaryArenaAllocatorCount(0),
  116. temporaryGuestArenaAllocatorCount(0),
  117. crefSContextForDiag(0),
  118. m_prereservedRegionAddr(0),
  119. scriptContextList(nullptr),
  120. scriptContextEverRegistered(false),
  121. #if DBG_DUMP || defined(PROFILE_EXEC)
  122. topLevelScriptSite(nullptr),
  123. #endif
  124. polymorphicCacheState(0),
  125. stackProbeCount(0),
  126. #ifdef BAILOUT_INJECTION
  127. bailOutByteCodeLocationCount(0),
  128. #endif
  129. sourceCodeSize(0),
  130. nativeCodeSize(0),
  131. threadAlloc(_u("TC"), GetPageAllocator(), Js::Throw::OutOfMemory),
  132. inlineCacheThreadInfoAllocator(_u("TC-InlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
  133. isInstInlineCacheThreadInfoAllocator(_u("TC-IsInstInlineCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
  134. equivalentTypeCacheInfoAllocator(_u("TC-EquivalentTypeCacheInfo"), GetPageAllocator(), Js::Throw::OutOfMemory),
  135. protoInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 521),
  136. storeFieldInlineCacheByPropId(&inlineCacheThreadInfoAllocator, 293),
  137. isInstInlineCacheByFunction(&isInstInlineCacheThreadInfoAllocator, 131),
  138. registeredInlineCacheCount(0),
  139. unregisteredInlineCacheCount(0),
  140. noSpecialPropertyRegistry(this->GetPageAllocator()),
  141. onlyWritablePropertyRegistry(this->GetPageAllocator()),
  142. standardUTF8Chars(0),
  143. standardUnicodeChars(0),
  144. hasUnhandledException(FALSE),
  145. hasCatchHandler(FALSE),
  146. disableImplicitFlags(DisableImplicitNoFlag),
  147. hasCatchHandlerToUserCode(false),
  148. caseInvariantPropertySet(nullptr),
  149. entryPointToBuiltInOperationIdCache(&threadAlloc, 0),
  150. #if ENABLE_NATIVE_CODEGEN
  151. preReservedVirtualAllocator(),
  152. #if !FLOATVAR
  153. codeGenNumberThreadAllocator(nullptr),
  154. xProcNumberPageSegmentManager(nullptr),
  155. #endif
  156. m_jitNumericProperties(nullptr),
  157. m_jitNeedsPropertyUpdate(false),
  158. #if DYNAMIC_INTERPRETER_THUNK || defined(ASMJS_PLAT)
  159. thunkPageAllocators(allocationPolicyManager, /* allocXData */ false, /* virtualAllocator */ nullptr, GetCurrentProcess()),
  160. #endif
  161. codePageAllocators(allocationPolicyManager, ALLOC_XDATA, GetPreReservedVirtualAllocator(), GetCurrentProcess()),
  162. #if defined(_CONTROL_FLOW_GUARD) && !defined(_M_ARM)
  163. jitThunkEmitter(this, &VirtualAllocWrapper::Instance , GetCurrentProcess()),
  164. #endif
  165. #endif
  166. dynamicObjectEnumeratorCacheMap(&HeapAllocator::Instance, 16),
  167. //threadContextFlags(ThreadContextFlagNoFlag),
  168. #ifdef NTBUILD
  169. telemetryBlock(&localTelemetryBlock),
  170. #endif
  171. configuration(enableExperimentalFeatures),
  172. jsrtRuntime(nullptr),
  173. propertyMap(nullptr),
  174. rootPendingClose(nullptr),
  175. exceptionCode(0),
  176. isProfilingUserCode(true),
  177. loopDepth(0),
  178. redeferralState(InitialRedeferralState),
  179. gcSinceLastRedeferral(0),
  180. gcSinceCallCountsCollected(0),
  181. tridentLoadAddress(nullptr),
  182. m_remoteThreadContextInfo(nullptr)
  183. #ifdef ENABLE_SCRIPT_DEBUGGING
  184. , debugManager(nullptr)
  185. #endif
  186. #if ENABLE_TTD
  187. , TTDContext(nullptr)
  188. , TTDExecutionInfo(nullptr)
  189. , TTDLog(nullptr)
  190. , TTDRootNestingCount(0)
  191. #endif
  192. #ifdef ENABLE_DIRECTCALL_TELEMETRY
  193. , directCallTelemetry(this)
  194. #endif
  195. #if ENABLE_JS_REENTRANCY_CHECK
  196. , noJsReentrancy(false)
  197. #endif
  198. , emptyStringPropertyRecord(nullptr)
  199. , recyclerTelemetryHostInterface(this)
  200. {
  201. pendingProjectionContextCloseList = JsUtil::List<IProjectionContext*, ArenaAllocator>::New(GetThreadAlloc());
  202. hostScriptContextStack = Anew(GetThreadAlloc(), JsUtil::Stack<HostScriptContext*>, GetThreadAlloc());
  203. functionCount = 0;
  204. sourceInfoCount = 0;
  205. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  206. scriptContextCount = 0;
  207. #endif
  208. isScriptActive = false;
  209. #ifdef ENABLE_CUSTOM_ENTROPY
  210. entropy.Initialize();
  211. #endif
  212. #if ENABLE_NATIVE_CODEGEN
  213. this->bailOutRegisterSaveSpace = AnewArrayZ(this->GetThreadAlloc(), Js::Var, GetBailOutRegisterSaveSlotCount());
  214. #endif
  215. #if DBG_DUMP
  216. scriptSiteCount = 0;
  217. pageAllocator.debugName = _u("Thread");
  218. #endif
  219. #ifdef DYNAMIC_PROFILE_MUTATOR
  220. this->dynamicProfileMutator = DynamicProfileMutator::GetMutator();
  221. #endif
  222. PERF_COUNTER_INC(Basic, ThreadContext);
  223. #ifdef LEAK_REPORT
  224. this->rootTrackerScriptContext = nullptr;
  225. this->threadId = ::GetCurrentThreadId();
  226. #endif
  227. #ifdef NTBUILD
  228. memset(&localTelemetryBlock, 0, sizeof(localTelemetryBlock));
  229. #endif
  230. AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
  231. ThreadContext::LinkToBeginning(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast);
  232. #if DBG
  233. // Since we created our page allocator while we were constructing this thread context
  234. // it will pick up the thread context id that is current on the thread. We need to update
  235. // that now.
  236. pageAllocator.UpdateThreadContextHandle((ThreadContextId)this);
  237. #endif
  238. #ifdef ENABLE_PROJECTION
  239. #if DBG_DUMP
  240. this->projectionMemoryInformation = nullptr;
  241. #endif
  242. #endif
  243. #if DBG
  244. arrayMutationSeed = (Js::Configuration::Global.flags.ArrayMutationTestSeed != 0) ? (uint)Js::Configuration::Global.flags.ArrayMutationTestSeed : (uint)time(NULL);
  245. srand(arrayMutationSeed);
  246. #endif
  247. this->InitAvailableCommit();
  248. }
  249. void ThreadContext::InitAvailableCommit()
  250. {
  251. // Once per process: get the available commit for the process from the OS and push it to the AutoSystemInfo.
  252. // (This must be done lazily, outside DllMain. And it must be done from the Runtime, since the common lib
  253. // doesn't have access to the DelayLoadLibrary stuff.)
  254. ULONG64 commit;
  255. BOOL success = AutoSystemInfo::Data.GetAvailableCommit(&commit);
  256. if (!success)
  257. {
  258. commit = (ULONG64)-1;
  259. #ifdef NTBUILD
  260. APP_MEMORY_INFORMATION AppMemInfo;
  261. success = GetWinCoreProcessThreads()->GetProcessInformation(
  262. GetCurrentProcess(),
  263. ProcessAppMemoryInfo,
  264. &AppMemInfo,
  265. sizeof(AppMemInfo));
  266. if (success)
  267. {
  268. commit = AppMemInfo.AvailableCommit;
  269. }
  270. #endif
  271. AutoSystemInfo::Data.SetAvailableCommit(commit);
  272. }
  273. }
  274. void ThreadContext::SetStackProber(StackProber * stackProber)
  275. {
  276. this->stackProber = stackProber;
  277. if (stackProber != NULL && this->stackLimitForCurrentThread != Js::Constants::StackLimitForScriptInterrupt)
  278. {
  279. this->stackLimitForCurrentThread = stackProber->GetScriptStackLimit();
  280. }
  281. }
  282. size_t ThreadContext::GetScriptStackLimit() const
  283. {
  284. return stackProber->GetScriptStackLimit();
  285. }
  286. HANDLE
  287. ThreadContext::GetProcessHandle() const
  288. {
  289. return GetCurrentProcess();
  290. }
  291. intptr_t
  292. ThreadContext::GetThreadStackLimitAddr() const
  293. {
  294. return (intptr_t)GetAddressOfStackLimitForCurrentThread();
  295. }
  296. #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_WASM_SIMD)
  297. intptr_t
  298. ThreadContext::GetSimdTempAreaAddr(uint8 tempIndex) const
  299. {
  300. return (intptr_t)&X86_TEMP_SIMD[tempIndex];
  301. }
  302. #endif
  303. intptr_t
  304. ThreadContext::GetDisableImplicitFlagsAddr() const
  305. {
  306. return (intptr_t)&disableImplicitFlags;
  307. }
  308. intptr_t
  309. ThreadContext::GetImplicitCallFlagsAddr() const
  310. {
  311. return (intptr_t)&implicitCallFlags;
  312. }
  313. ptrdiff_t
  314. ThreadContext::GetChakraBaseAddressDifference() const
  315. {
  316. return 0;
  317. }
  318. ptrdiff_t
  319. ThreadContext::GetCRTBaseAddressDifference() const
  320. {
  321. return 0;
  322. }
  323. IActiveScriptProfilerHeapEnum* ThreadContext::GetHeapEnum()
  324. {
  325. return heapEnum;
  326. }
  327. void ThreadContext::SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum)
  328. {
  329. Assert((newHeapEnum != nullptr && heapEnum == nullptr) || (newHeapEnum == nullptr && heapEnum != nullptr));
  330. heapEnum = newHeapEnum;
  331. }
  332. void ThreadContext::ClearHeapEnum()
  333. {
  334. Assert(heapEnum != nullptr);
  335. heapEnum = nullptr;
  336. }
  337. void ThreadContext::GlobalInitialize()
  338. {
  339. for (int i = 0; i < _countof(builtInPropertyRecords); i++)
  340. {
  341. builtInPropertyRecords[i]->SetHash(JsUtil::CharacterBuffer<WCHAR>::StaticGetHashCode(builtInPropertyRecords[i]->GetBuffer(), builtInPropertyRecords[i]->GetLength()));
  342. }
  343. }
  344. ThreadContext::~ThreadContext()
  345. {
  346. {
  347. AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
  348. ThreadContext::Unlink(this, &ThreadContext::globalListFirst, &ThreadContext::globalListLast);
  349. }
  350. #if ENABLE_TTD
  351. if(this->TTDContext != nullptr)
  352. {
  353. TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDContext);
  354. this->TTDContext = nullptr;
  355. }
  356. if(this->TTDExecutionInfo != nullptr)
  357. {
  358. TT_HEAP_DELETE(TTD::ThreadContextTTD, this->TTDExecutionInfo);
  359. this->TTDExecutionInfo = nullptr;
  360. }
  361. if(this->TTDLog != nullptr)
  362. {
  363. TT_HEAP_DELETE(TTD::EventLog, this->TTDLog);
  364. this->TTDLog = nullptr;
  365. }
  366. #endif
  367. #ifdef LEAK_REPORT
  368. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  369. {
  370. AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): %s (TID: %d)"), this,
  371. this->GetRecycler()->IsInDllCanUnloadNow()? _u("DllCanUnloadNow") :
  372. this->GetRecycler()->IsInDetachProcess()? _u("DetachProcess") : _u("Destructor"), this->threadId);
  373. LeakReport::DumpUrl(this->threadId);
  374. }
  375. #endif
  376. if (interruptPoller)
  377. {
  378. HeapDelete(interruptPoller);
  379. interruptPoller = nullptr;
  380. }
  381. #if DBG
  382. // ThreadContext dtor may be running on a different thread.
  383. // Recycler may call finalizer that free temp Arenas, which will free pages back to
  384. // the page Allocator, which will try to suspend idle on a different thread.
  385. // So we need to disable idle decommit asserts.
  386. pageAllocator.ShutdownIdleDecommit();
  387. #endif
  388. // Allocating memory during the shutdown codepath is not preferred
  389. // so we'll close the page allocator before we release the GC
  390. // If any dispose is allocating memory during shutdown, that is a bug
  391. pageAllocator.Close();
  392. // The recycler need to delete before the background code gen thread
  393. // because that might run finalizer which need access to the background code gen thread.
  394. if (recycler != nullptr)
  395. {
  396. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
  397. {
  398. if (!scriptContext->IsActuallyClosed())
  399. {
  400. // We close ScriptContext here because anyhow HeapDelete(recycler) when disposing the
  401. // JavaScriptLibrary will close ScriptContext. Explicit close gives us chance to clear
  402. // other things to which ScriptContext holds reference to
  403. AssertMsg(!IsInScript(), "Can we be in script here?");
  404. scriptContext->MarkForClose();
  405. }
  406. }
  407. // If all scriptContext's have been closed, then the sourceProfileManagersByUrl
  408. // should have been released
  409. AssertMsg(this->recyclableData->sourceProfileManagersByUrl == nullptr ||
  410. this->recyclableData->sourceProfileManagersByUrl->Count() == 0, "There seems to have been a refcounting imbalance.");
  411. this->recyclableData->sourceProfileManagersByUrl = nullptr;
  412. this->recyclableData->oldEntryPointInfo = nullptr;
  413. if (this->recyclableData->symbolRegistrationMap != nullptr)
  414. {
  415. this->recyclableData->symbolRegistrationMap->Clear();
  416. this->recyclableData->symbolRegistrationMap = nullptr;
  417. }
  418. #ifdef ENABLE_SCRIPT_DEBUGGING
  419. if (this->recyclableData->returnedValueList != nullptr)
  420. {
  421. this->recyclableData->returnedValueList->Clear();
  422. this->recyclableData->returnedValueList = nullptr;
  423. }
  424. #endif
  425. if (this->propertyMap != nullptr)
  426. {
  427. HeapDelete(this->propertyMap);
  428. this->propertyMap = nullptr;
  429. }
  430. #if ENABLE_NATIVE_CODEGEN
  431. if (this->m_jitNumericProperties != nullptr)
  432. {
  433. HeapDelete(this->m_jitNumericProperties);
  434. this->m_jitNumericProperties = nullptr;
  435. }
  436. #endif
  437. // Unpin the memory for leak report so we don't report this as a leak.
  438. recyclableData.Unroot(recycler);
  439. #if defined(LEAK_REPORT) || defined(CHECK_MEMORY_LEAK)
  440. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
  441. {
  442. scriptContext->ClearSourceContextInfoMaps();
  443. scriptContext->ShutdownClearSourceLists();
  444. }
  445. #ifdef LEAK_REPORT
  446. // heuristically figure out which one is the root tracker script engine
  447. // and force close on it
  448. if (this->rootTrackerScriptContext != nullptr)
  449. {
  450. this->rootTrackerScriptContext->Close(false);
  451. }
  452. #endif
  453. #endif
  454. #if ENABLE_NATIVE_CODEGEN
  455. #if !FLOATVAR
  456. if (this->codeGenNumberThreadAllocator)
  457. {
  458. HeapDelete(this->codeGenNumberThreadAllocator);
  459. this->codeGenNumberThreadAllocator = nullptr;
  460. }
  461. if (this->xProcNumberPageSegmentManager)
  462. {
  463. HeapDelete(this->xProcNumberPageSegmentManager);
  464. this->xProcNumberPageSegmentManager = nullptr;
  465. }
  466. #endif
  467. #endif
  468. #ifdef ENABLE_SCRIPT_DEBUGGING
  469. Assert(this->debugManager == nullptr);
  470. #endif
  471. HeapDelete(recycler);
  472. }
  473. #if ENABLE_NATIVE_CODEGEN
  474. if(jobProcessor)
  475. {
  476. if(this->bgJit)
  477. {
  478. HeapDelete(static_cast<JsUtil::BackgroundJobProcessor *>(jobProcessor));
  479. }
  480. else
  481. {
  482. HeapDelete(static_cast<JsUtil::ForegroundJobProcessor *>(jobProcessor));
  483. }
  484. jobProcessor = nullptr;
  485. }
  486. #endif
  487. // Do not require all GC callbacks to be revoked, because Trident may not revoke if there
  488. // is a leak, and we don't want the leak to be masked by an assert
  489. #ifdef ENABLE_PROJECTION
  490. externalWeakReferenceCacheList.Clear(&HeapAllocator::Instance);
  491. #endif
  492. this->collectCallBackList.Clear(&HeapAllocator::Instance);
  493. this->protoInlineCacheByPropId.Reset();
  494. this->storeFieldInlineCacheByPropId.Reset();
  495. this->isInstInlineCacheByFunction.Reset();
  496. this->equivalentTypeCacheEntryPoints.Reset();
  497. this->noSpecialPropertyRegistry.Reset();
  498. this->onlyWritablePropertyRegistry.Reset();
  499. this->registeredInlineCacheCount = 0;
  500. this->unregisteredInlineCacheCount = 0;
  501. AssertMsg(this->GetHeapEnum() == nullptr, "Heap enumeration should have been cleared/closed by the ScriptSite.");
  502. if (this->GetHeapEnum() != nullptr)
  503. {
  504. this->ClearHeapEnum();
  505. }
  506. #ifdef BAILOUT_INJECTION
  507. if (Js::Configuration::Global.flags.IsEnabled(Js::BailOutByteCodeFlag)
  508. && Js::Configuration::Global.flags.BailOutByteCode.Empty())
  509. {
  510. Output::Print(_u("Bail out byte code location count: %d"), this->bailOutByteCodeLocationCount);
  511. }
  512. #endif
  513. Assert(processNativeCodeSize >= nativeCodeSize);
  514. ::InterlockedExchangeSubtract(&processNativeCodeSize, nativeCodeSize);
  515. PERF_COUNTER_DEC(Basic, ThreadContext);
  516. #ifdef DYNAMIC_PROFILE_MUTATOR
  517. if (this->dynamicProfileMutator != nullptr)
  518. {
  519. this->dynamicProfileMutator->Delete();
  520. }
  521. #endif
  522. #ifdef ENABLE_PROJECTION
  523. #if DBG_DUMP
  524. if (this->projectionMemoryInformation)
  525. {
  526. this->projectionMemoryInformation->Release();
  527. this->projectionMemoryInformation = nullptr;
  528. }
  529. #endif
  530. #endif
  531. }
  532. void
  533. ThreadContext::SetJSRTRuntime(void* runtime)
  534. {
  535. Assert(jsrtRuntime == nullptr);
  536. jsrtRuntime = runtime;
  537. #ifdef ENABLE_BASIC_TELEMETRY
  538. Telemetry::EnsureInitializeForJSRT();
  539. #endif
  540. }
  541. void ThreadContext::CloseForJSRT()
  542. {
  543. // This is used for JSRT APIs only.
  544. Assert(this->jsrtRuntime);
  545. #ifdef ENABLE_BASIC_TELEMETRY
  546. // log any relevant telemetry before disposing the current thread for cases which are properly shutdown
  547. Telemetry::OnJSRTThreadContextClose();
  548. #endif
  549. ShutdownThreads();
  550. }
  551. ThreadContext* ThreadContext::GetContextForCurrentThread()
  552. {
  553. ThreadContextTLSEntry * tlsEntry = ThreadContextTLSEntry::GetEntryForCurrentThread();
  554. if (tlsEntry != nullptr)
  555. {
  556. return static_cast<ThreadContext *>(tlsEntry->GetThreadContext());
  557. }
  558. return nullptr;
  559. }
  560. void ThreadContext::ValidateThreadContext()
  561. {
  562. #if DBG
  563. // verify the runtime pointer is valid.
  564. {
  565. BOOL found = FALSE;
  566. AutoCriticalSection autocs(ThreadContext::GetCriticalSection());
  567. ThreadContext* currentThreadContext = GetThreadContextList();
  568. while (currentThreadContext)
  569. {
  570. if (currentThreadContext == this)
  571. {
  572. return;
  573. }
  574. currentThreadContext = currentThreadContext->Next();
  575. }
  576. AssertMsg(found, "invalid thread context");
  577. }
  578. #endif
  579. }
  580. class AutoRecyclerPtr : public AutoPtr<Recycler>
  581. {
  582. public:
  583. AutoRecyclerPtr(Recycler * ptr) : AutoPtr<Recycler>(ptr) {}
  584. ~AutoRecyclerPtr()
  585. {
  586. #if ENABLE_CONCURRENT_GC
  587. if (ptr != nullptr)
  588. {
  589. ptr->ShutdownThread();
  590. }
  591. #endif
  592. }
  593. };
  594. LPFILETIME ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetLastScriptExecutionEndTime() const
  595. {
  596. #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
  597. return &(tc->telemetryBlock->lastScriptEndTime);
  598. #else
  599. return nullptr;
  600. #endif
  601. }
  602. bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitTelemetry(RecyclerTelemetryInfo& rti)
  603. {
  604. #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
  605. return Js::TransmitRecyclerTelemetry(rti);
  606. #else
  607. return false;
  608. #endif
  609. }
  610. bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::TransmitTelemetryError(const RecyclerTelemetryInfo& rti, const char * msg)
  611. {
  612. #if defined(ENABLE_BASIC_TELEMETRY) && defined(NTBUILD)
  613. return Js::TransmitRecyclerTelemetryError(rti, msg);
  614. #else
  615. return false;
  616. #endif
  617. }
  618. bool ThreadContext::ThreadContextRecyclerTelemetryHostInterface::IsThreadBound() const
  619. {
  620. return this->tc->IsThreadBound();
  621. }
  622. DWORD ThreadContext::ThreadContextRecyclerTelemetryHostInterface::GetCurrentScriptThreadID() const
  623. {
  624. return this->tc->GetCurrentThreadId();
  625. }
  626. Recycler* ThreadContext::EnsureRecycler()
  627. {
  628. if (recycler == NULL)
  629. {
  630. AutoRecyclerPtr newRecycler(HeapNew(Recycler, GetAllocationPolicyManager(), &pageAllocator, Js::Throw::OutOfMemory, Js::Configuration::Global.flags, &recyclerTelemetryHostInterface));
  631. newRecycler->Initialize(isOptimizedForManyInstances, &threadService); // use in-thread GC when optimizing for many instances
  632. newRecycler->SetCollectionWrapper(this);
  633. #if ENABLE_NATIVE_CODEGEN
  634. // This may throw, so it needs to be after the recycler is initialized,
  635. // otherwise, the recycler dtor may encounter problems
  636. #if !FLOATVAR
  637. // TODO: we only need one of the following, one for OOP jit and one for in-proc BG JIT
  638. AutoPtr<CodeGenNumberThreadAllocator> localCodeGenNumberThreadAllocator(
  639. HeapNew(CodeGenNumberThreadAllocator, newRecycler));
  640. AutoPtr<XProcNumberPageSegmentManager> localXProcNumberPageSegmentManager(
  641. HeapNew(XProcNumberPageSegmentManager, newRecycler));
  642. #endif
  643. #endif
  644. this->recyclableData.Root(RecyclerNewZ(newRecycler, RecyclableData, newRecycler), newRecycler);
  645. if (this->IsThreadBound())
  646. {
  647. newRecycler->SetIsThreadBound();
  648. }
  649. // Assign the recycler to the ThreadContext after everything is initialized, because an OOM during initialization would
  650. // result in only partial initialization, so the 'recycler' member variable should remain null to cause full
  651. // reinitialization when requested later. Anything that happens after the Detach must have special cleanup code.
  652. this->recycler = newRecycler.Detach();
  653. try
  654. {
  655. #ifdef RECYCLER_WRITE_BARRIER
  656. #ifdef TARGET_64
  657. if (!RecyclerWriteBarrierManager::OnThreadInit())
  658. {
  659. Js::Throw::OutOfMemory();
  660. }
  661. #endif
  662. #endif
  663. this->expirableObjectList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc);
  664. this->expirableObjectDisposeList = Anew(&this->threadAlloc, ExpirableObjectList, &this->threadAlloc);
  665. InitializePropertyMaps(); // has many dependencies on the recycler and other members of the thread context
  666. #if ENABLE_NATIVE_CODEGEN
  667. #if !FLOATVAR
  668. this->codeGenNumberThreadAllocator = localCodeGenNumberThreadAllocator.Detach();
  669. this->xProcNumberPageSegmentManager = localXProcNumberPageSegmentManager.Detach();
  670. #endif
  671. #endif
  672. }
  673. catch(...)
  674. {
  675. // Initialization failed, undo what was done above. Callees that throw must clean up after themselves.
  676. if (this->recyclableData != nullptr)
  677. {
  678. this->recyclableData.Unroot(this->recycler);
  679. }
  680. {
  681. // AutoRecyclerPtr's destructor takes care of shutting down the background thread and deleting the recycler
  682. AutoRecyclerPtr recyclerToDelete(this->recycler);
  683. this->recycler = nullptr;
  684. }
  685. throw;
  686. }
  687. JS_ETW(EventWriteJSCRIPT_GC_INIT(this->recycler, this->GetHiResTimer()->Now()));
  688. }
  689. #if DBG
  690. if (CONFIG_FLAG(RecyclerTest))
  691. {
  692. StressTester test(recycler);
  693. test.Run();
  694. }
  695. #endif
  696. return recycler;
  697. }
  698. Js::PropertyRecord const *
  699. ThreadContext::GetPropertyName(Js::PropertyId propertyId)
  700. {
  701. // This API should only be use on the main thread
  702. Assert(GetCurrentThreadContextId() == (ThreadContextId)this);
  703. return this->GetPropertyNameImpl<false>(propertyId);
  704. }
  705. Js::PropertyRecord const *
  706. ThreadContext::GetPropertyNameLocked(Js::PropertyId propertyId)
  707. {
  708. return GetPropertyNameImpl<true>(propertyId);
  709. }
  710. template <bool locked>
  711. Js::PropertyRecord const *
  712. ThreadContext::GetPropertyNameImpl(Js::PropertyId propertyId)
  713. {
  714. //TODO: Remove this when completely transformed to use PropertyRecord*. Currently this is only partially done,
  715. // and there are calls to GetPropertyName with InternalPropertyId.
  716. if (propertyId >= 0 && Js::IsInternalPropertyId(propertyId))
  717. {
  718. return Js::InternalPropertyRecords::GetInternalPropertyName(propertyId);
  719. }
  720. int propertyIndex = propertyId - Js::PropertyIds::_none;
  721. if (propertyIndex < 0 || propertyIndex > propertyMap->GetLastIndex())
  722. {
  723. propertyIndex = 0;
  724. }
  725. const Js::PropertyRecord * propertyRecord = nullptr;
  726. if (locked) { propertyMap->LockResize(); }
  727. bool found = propertyMap->TryGetValueAt(propertyIndex, &propertyRecord);
  728. if (locked) { propertyMap->UnlockResize(); }
  729. AssertMsg(found && propertyRecord != nullptr, "using invalid propertyid");
  730. return propertyRecord;
  731. }
  732. void
  733. ThreadContext::FindPropertyRecord(Js::JavascriptString *pstName, Js::PropertyRecord const ** propertyRecord)
  734. {
  735. pstName->GetPropertyRecord(propertyRecord, true);
  736. if (*propertyRecord != nullptr)
  737. {
  738. return;
  739. }
  740. // GetString is not guaranteed to be null-terminated, but we explicitly pass length to the next step
  741. LPCWCH propertyName = pstName->GetString();
  742. FindPropertyRecord(propertyName, pstName->GetLength(), propertyRecord);
  743. if (*propertyRecord)
  744. {
  745. pstName->CachePropertyRecord(*propertyRecord);
  746. }
  747. }
  748. void
  749. ThreadContext::FindPropertyRecord(__in LPCWCH propertyName, __in int propertyNameLength, Js::PropertyRecord const ** propertyRecord)
  750. {
  751. EnterPinnedScope((volatile void **)propertyRecord);
  752. *propertyRecord = FindPropertyRecord(propertyName, propertyNameLength);
  753. LeavePinnedScope();
  754. }
  755. Js::PropertyRecord const *
  756. ThreadContext::GetPropertyRecord(Js::PropertyId propertyId)
  757. {
  758. return GetPropertyNameLocked(propertyId);
  759. }
  760. bool
  761. ThreadContext::IsNumericProperty(Js::PropertyId propertyId)
  762. {
  763. return GetPropertyRecord(propertyId)->IsNumeric();
  764. }
  765. const Js::PropertyRecord *
  766. ThreadContext::FindPropertyRecord(const char16 * propertyName, int propertyNameLength)
  767. {
  768. // IsDirectPropertyName == 1 char properties && GetEmptyStringPropertyRecord == 0 length
  769. if (propertyNameLength < 2)
  770. {
  771. if (propertyNameLength == 0)
  772. {
  773. return this->GetEmptyStringPropertyRecord();
  774. }
  775. if (IsDirectPropertyName(propertyName, propertyNameLength))
  776. {
  777. Js::PropertyRecord const * propertyRecord = propertyNamesDirect[propertyName[0]];
  778. Assert(propertyRecord == propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength)));
  779. return propertyRecord;
  780. }
  781. }
  782. return propertyMap->LookupWithKey(Js::HashedCharacterBuffer<char16>(propertyName, propertyNameLength));
  783. }
  784. Js::PropertyRecord const *
  785. ThreadContext::UncheckedAddPropertyId(__in LPCWSTR propertyName, __in int propertyNameLength, bool bind, bool isSymbol)
  786. {
  787. return UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), bind, isSymbol);
  788. }
  789. void ThreadContext::InitializePropertyMaps()
  790. {
  791. Assert(this->recycler != nullptr);
  792. Assert(this->recyclableData != nullptr);
  793. Assert(this->propertyMap == nullptr);
  794. Assert(this->caseInvariantPropertySet == nullptr);
  795. try
  796. {
  797. this->propertyMap = HeapNew(PropertyMap, &HeapAllocator::Instance, TotalNumberOfBuiltInProperties + 700);
  798. this->recyclableData->boundPropertyStrings = RecyclerNew(this->recycler, JsUtil::List<Js::PropertyRecord const*>, this->recycler);
  799. memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *));
  800. Js::JavascriptLibrary::InitializeProperties(this);
  801. InitializeAdditionalProperties(this);
  802. //Js::JavascriptLibrary::InitializeDOMProperties(this);
  803. }
  804. catch(...)
  805. {
  806. // Initialization failed, undo what was done above. Callees that throw must clean up after themselves. The recycler will
  807. // be trashed, so clear members that point to recyclable memory. Stuff in 'recyclableData' will be taken care of by the
  808. // recycler, and the 'recyclableData' instance will be trashed as well.
  809. if (this->propertyMap != nullptr)
  810. {
  811. HeapDelete(this->propertyMap);
  812. }
  813. this->propertyMap = nullptr;
  814. this->caseInvariantPropertySet = nullptr;
  815. memset(propertyNamesDirect, 0, 128*sizeof(Js::PropertyRecord *));
  816. throw;
  817. }
  818. }
  819. void ThreadContext::UncheckedAddBuiltInPropertyId()
  820. {
  821. for (int i = 0; i < _countof(builtInPropertyRecords); i++)
  822. {
  823. AddPropertyRecordInternal(builtInPropertyRecords[i]);
  824. }
  825. }
  826. bool
  827. ThreadContext::IsDirectPropertyName(const char16 * propertyName, int propertyNameLength)
  828. {
  829. return ((propertyNameLength == 1) && ((propertyName[0] & 0xFF80) == 0));
  830. }
  831. RecyclerWeakReference<const Js::PropertyRecord> *
  832. ThreadContext::CreatePropertyRecordWeakRef(const Js::PropertyRecord * propertyRecord)
  833. {
  834. RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef;
  835. if (propertyRecord->IsBound())
  836. {
  837. // Create a fake weak ref
  838. propertyRecordWeakRef = RecyclerNewLeaf(this->recycler, StaticPropertyRecordReference, propertyRecord);
  839. }
  840. else
  841. {
  842. propertyRecordWeakRef = recycler->CreateWeakReferenceHandle(propertyRecord);
  843. }
  844. return propertyRecordWeakRef;
  845. }
  846. Js::PropertyRecord const *
  847. ThreadContext::UncheckedAddPropertyId(JsUtil::CharacterBuffer<WCHAR> const& propertyName, bool bind, bool isSymbol)
  848. {
  849. #if ENABLE_TTD
  850. if(isSymbol & this->IsRuntimeInTTDMode())
  851. {
  852. if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformReplayAction())
  853. {
  854. //We reload all properties that occour in the trace so they only way we get here in TTD mode is:
  855. //(1) if the program is creating a new symbol (which always gets a fresh id) and we should recreate it or
  856. //(2) if it is forcing arguments in debug parse mode (instead of regular which we recorded in)
  857. Js::PropertyId propertyId = Js::Constants::NoProperty;
  858. this->TTDLog->ReplaySymbolCreationEvent(&propertyId);
  859. //Don't recreate the symbol below, instead return the known symbol by looking up on the pid
  860. const Js::PropertyRecord* res = this->GetPropertyName(propertyId);
  861. AssertMsg(res != nullptr, "This should never happen!!!");
  862. return res;
  863. }
  864. }
  865. #endif
  866. this->propertyMap->EnsureCapacity();
  867. // Automatically bind direct (single-character) property names, so that they can be
  868. // stored in the direct property table
  869. if (IsDirectPropertyName(propertyName.GetBuffer(), propertyName.GetLength()))
  870. {
  871. bind = true;
  872. }
  873. // Create the PropertyRecord
  874. int length = propertyName.GetLength();
  875. uint bytelength = sizeof(char16) * length;
  876. size_t allocLength = bytelength + sizeof(char16) + ( (!isSymbol && length <= 10 && length > 0) ? sizeof(uint32) : 0);
  877. // If it's bound, create it in the thread arena, along with a fake weak ref
  878. Js::PropertyRecord * propertyRecord;
  879. if (bind)
  880. {
  881. propertyRecord = AnewPlus(GetThreadAlloc(), allocLength, Js::PropertyRecord, propertyName.GetBuffer(), length, bytelength, isSymbol);
  882. propertyRecord->isBound = true;
  883. }
  884. else
  885. {
  886. propertyRecord = RecyclerNewFinalizedLeafPlus(recycler, allocLength, Js::PropertyRecord, propertyName.GetBuffer(), length, bytelength, isSymbol);
  887. }
  888. Js::PropertyId propertyId = this->GetNextPropertyId();
  889. #if ENABLE_TTD
  890. if(isSymbol & this->IsRuntimeInTTDMode())
  891. {
  892. if(this->TTDContext->GetActiveScriptContext() != nullptr && this->TTDContext->GetActiveScriptContext()->ShouldPerformRecordAction())
  893. {
  894. this->TTDLog->RecordSymbolCreationEvent(propertyId);
  895. }
  896. }
  897. #endif
  898. propertyRecord->pid = propertyId;
  899. AddPropertyRecordInternal(propertyRecord);
  900. return propertyRecord;
  901. }
  902. void
  903. ThreadContext::AddPropertyRecordInternal(const Js::PropertyRecord * propertyRecord)
  904. {
  905. // At this point the PropertyRecord is constructed but not added to the map.
  906. const char16 * propertyName = propertyRecord->GetBuffer();
  907. int propertyNameLength = propertyRecord->GetLength();
  908. Js::PropertyId propertyId = propertyRecord->GetPropertyId();
  909. Assert(propertyId == GetNextPropertyId());
  910. Assert(!IsActivePropertyId(propertyId));
  911. #if DBG
  912. // Only Assert we can't find the property if we are not adding a symbol.
  913. // For a symbol, the propertyName is not used and may collide with something in the map already.
  914. if (propertyNameLength > 0 && !propertyRecord->IsSymbol())
  915. {
  916. Assert(FindPropertyRecord(propertyName, propertyNameLength) == nullptr);
  917. }
  918. #endif
  919. #if ENABLE_TTD
  920. if(this->IsRuntimeInTTDMode())
  921. {
  922. this->TTDLog->AddPropertyRecord(propertyRecord);
  923. }
  924. #endif
  925. // Add to the map
  926. propertyMap->Add(propertyRecord);
  927. #if ENABLE_NATIVE_CODEGEN
  928. if (m_jitNumericProperties)
  929. {
  930. if (propertyRecord->IsNumeric())
  931. {
  932. m_jitNumericProperties->Set(propertyRecord->GetPropertyId());
  933. m_jitNeedsPropertyUpdate = true;
  934. }
  935. }
  936. #endif
  937. PropertyRecordTrace(_u("Added property '%s' at 0x%08x, pid = %d\n"), propertyName, propertyRecord, propertyId);
  938. // Do not store the pid for symbols in the direct property name table.
  939. // We don't want property ids for symbols to be searchable anyway.
  940. if (!propertyRecord->IsSymbol() && IsDirectPropertyName(propertyName, propertyNameLength))
  941. {
  942. // Store the pids for single character properties in the propertyNamesDirect array.
  943. // This property record should have been created as bound by the caller.
  944. Assert(propertyRecord->IsBound());
  945. Assert(propertyNamesDirect[propertyName[0]] == nullptr);
  946. propertyNamesDirect[propertyName[0]] = propertyRecord;
  947. }
  948. if (caseInvariantPropertySet)
  949. {
  950. AddCaseInvariantPropertyRecord(propertyRecord);
  951. }
  952. // Check that everything was added correctly
  953. #if DBG
  954. // Only Assert we can find the property if we are not adding a symbol.
  955. // For a symbol, the propertyName is not used and we won't be able to look the pid up via name.
  956. if (propertyNameLength && !propertyRecord->IsSymbol())
  957. {
  958. Assert(FindPropertyRecord(propertyName, propertyNameLength) == propertyRecord);
  959. }
  960. // We will still be able to lookup the symbol property by the property id, so go ahead and check that.
  961. Assert(GetPropertyName(propertyRecord->GetPropertyId()) == propertyRecord);
  962. #endif
  963. JS_ETW_INTERNAL(EventWriteJSCRIPT_HOSTING_PROPERTYID_LIST(propertyRecord, propertyRecord->GetBuffer()));
  964. }
  965. void
  966. ThreadContext::AddCaseInvariantPropertyRecord(const Js::PropertyRecord * propertyRecord)
  967. {
  968. Assert(this->caseInvariantPropertySet != nullptr);
  969. // Create a weak reference to the property record here (since we no longer use weak refs in the property map)
  970. RecyclerWeakReference<const Js::PropertyRecord> * propertyRecordWeakRef = CreatePropertyRecordWeakRef(propertyRecord);
  971. JsUtil::CharacterBuffer<WCHAR> newPropertyName(propertyRecord->GetBuffer(), propertyRecord->GetLength());
  972. Js::CaseInvariantPropertyListWithHashCode* list;
  973. if (!FindExistingPropertyRecord(newPropertyName, &list))
  974. {
  975. // This binds all the property string that is key in this map with no hope of reclaiming them
  976. // TODO: do better
  977. list = RecyclerNew(recycler, Js::CaseInvariantPropertyListWithHashCode, recycler, 1);
  978. // Do the add first so that the list is non-empty and we can calculate its hashcode correctly
  979. list->Add(propertyRecordWeakRef);
  980. // This will calculate the hashcode
  981. caseInvariantPropertySet->Add(list);
  982. }
  983. else
  984. {
  985. list->Add(propertyRecordWeakRef);
  986. }
  987. }
  988. void
  989. ThreadContext::BindPropertyRecord(const Js::PropertyRecord * propertyRecord)
  990. {
  991. if (!propertyRecord->IsBound())
  992. {
  993. Assert(!this->recyclableData->boundPropertyStrings->Contains(propertyRecord));
  994. this->recyclableData->boundPropertyStrings->Add(propertyRecord);
  995. // Cast around constness to set propertyRecord as bound
  996. const_cast<Js::PropertyRecord *>(propertyRecord)->isBound = true;
  997. }
  998. }
  999. void ThreadContext::GetOrAddPropertyId(_In_ LPCWSTR propertyName, _In_ int propertyNameLength, _Out_ Js::PropertyRecord const ** propertyRecord)
  1000. {
  1001. GetOrAddPropertyId(JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength), propertyRecord);
  1002. }
  1003. void ThreadContext::GetOrAddPropertyId(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, _Out_ Js::PropertyRecord const ** propRecord)
  1004. {
  1005. EnterPinnedScope((volatile void **)propRecord);
  1006. *propRecord = GetOrAddPropertyRecord(propertyName);
  1007. LeavePinnedScope();
  1008. }
  1009. const Js::PropertyRecord *
  1010. ThreadContext::GetOrAddPropertyRecordImpl(JsUtil::CharacterBuffer<char16> propertyName, bool bind)
  1011. {
  1012. // Make sure the recycler is around so that we can take weak references to the property strings
  1013. EnsureRecycler();
  1014. const Js::PropertyRecord * propertyRecord;
  1015. FindPropertyRecord(propertyName.GetBuffer(), propertyName.GetLength(), &propertyRecord);
  1016. if (propertyRecord == nullptr)
  1017. {
  1018. propertyRecord = UncheckedAddPropertyId(propertyName, bind);
  1019. }
  1020. else
  1021. {
  1022. // PropertyRecord exists, but may not be bound. Bind now if requested.
  1023. if (bind)
  1024. {
  1025. BindPropertyRecord(propertyRecord);
  1026. }
  1027. }
  1028. Assert(propertyRecord != nullptr);
  1029. Assert(!bind || propertyRecord->IsBound());
  1030. return propertyRecord;
  1031. }
  1032. void ThreadContext::AddBuiltInPropertyRecord(const Js::PropertyRecord *propertyRecord)
  1033. {
  1034. this->AddPropertyRecordInternal(propertyRecord);
  1035. }
  1036. BOOL ThreadContext::IsNumericPropertyId(Js::PropertyId propertyId, uint32* value)
  1037. {
  1038. if (Js::IsInternalPropertyId(propertyId))
  1039. {
  1040. return false;
  1041. }
  1042. Js::PropertyRecord const * propertyRecord = this->GetPropertyName(propertyId);
  1043. Assert(propertyRecord != nullptr);
  1044. if (propertyRecord == nullptr || !propertyRecord->IsNumeric())
  1045. {
  1046. return false;
  1047. }
  1048. *value = propertyRecord->GetNumericValue();
  1049. return true;
  1050. }
  1051. bool ThreadContext::IsActivePropertyId(Js::PropertyId pid)
  1052. {
  1053. Assert(pid != Js::Constants::NoProperty);
  1054. if (Js::IsInternalPropertyId(pid))
  1055. {
  1056. return true;
  1057. }
  1058. int propertyIndex = pid - Js::PropertyIds::_none;
  1059. const Js::PropertyRecord * propertyRecord;
  1060. if (propertyMap->TryGetValueAt(propertyIndex, &propertyRecord) && propertyRecord != nullptr)
  1061. {
  1062. return true;
  1063. }
  1064. return false;
  1065. }
  1066. void ThreadContext::InvalidatePropertyRecord(const Js::PropertyRecord * propertyRecord)
  1067. {
  1068. InternalInvalidateProtoTypePropertyCaches(propertyRecord->GetPropertyId()); // use the internal version so we don't check for active property id
  1069. #if ENABLE_NATIVE_CODEGEN
  1070. if (propertyRecord->IsNumeric() && m_jitNumericProperties)
  1071. {
  1072. m_jitNumericProperties->Clear(propertyRecord->GetPropertyId());
  1073. m_jitNeedsPropertyUpdate = true;
  1074. }
  1075. #endif
  1076. this->propertyMap->Remove(propertyRecord);
  1077. PropertyRecordTrace(_u("Reclaimed property '%s' at 0x%08x, pid = %d\n"),
  1078. propertyRecord->GetBuffer(), propertyRecord, propertyRecord->GetPropertyId());
  1079. }
  1080. Js::PropertyId ThreadContext::GetNextPropertyId()
  1081. {
  1082. return this->propertyMap->GetNextIndex() + Js::PropertyIds::_none;
  1083. }
  1084. Js::PropertyId ThreadContext::GetMaxPropertyId()
  1085. {
  1086. auto maxPropertyId = this->propertyMap->Count() + Js::InternalPropertyIds::Count;
  1087. return maxPropertyId;
  1088. }
  1089. void ThreadContext::CreateNoCasePropertyMap()
  1090. {
  1091. Assert(caseInvariantPropertySet == nullptr);
  1092. caseInvariantPropertySet = RecyclerNew(recycler, PropertyNoCaseSetType, recycler, 173);
  1093. // Prevent the set from being reclaimed
  1094. // Individual items in the set can be reclaimed though since they're lists of weak references
  1095. // The lists themselves can be reclaimed when all the weak references in them are cleared
  1096. this->recyclableData->caseInvariantPropertySet = caseInvariantPropertySet;
  1097. // Note that we are allocating from the recycler below, so we may cause a GC at any time, which
  1098. // could cause PropertyRecords to be collected and removed from the propertyMap.
  1099. // Thus, don't use BaseDictionary::Map here, as it cannot tolerate changes while mapping.
  1100. // Instead, walk the PropertyRecord entries in index order. This will work even if a GC occurs.
  1101. for (int propertyIndex = 0; propertyIndex <= this->propertyMap->GetLastIndex(); propertyIndex++)
  1102. {
  1103. const Js::PropertyRecord * propertyRecord;
  1104. if (this->propertyMap->TryGetValueAt(propertyIndex, &propertyRecord) && propertyRecord != nullptr)
  1105. {
  1106. AddCaseInvariantPropertyRecord(propertyRecord);
  1107. }
  1108. }
  1109. }
  1110. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>*
  1111. ThreadContext::FindPropertyIdNoCase(Js::ScriptContext * scriptContext, LPCWSTR propertyName, int propertyNameLength)
  1112. {
  1113. return ThreadContext::FindPropertyIdNoCase(scriptContext, JsUtil::CharacterBuffer<WCHAR>(propertyName, propertyNameLength));
  1114. }
  1115. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>*
  1116. ThreadContext::FindPropertyIdNoCase(Js::ScriptContext * scriptContext, JsUtil::CharacterBuffer<WCHAR> const& propertyName)
  1117. {
  1118. if (caseInvariantPropertySet == nullptr)
  1119. {
  1120. this->CreateNoCasePropertyMap();
  1121. }
  1122. Js::CaseInvariantPropertyListWithHashCode* list;
  1123. if (FindExistingPropertyRecord(propertyName, &list))
  1124. {
  1125. return list;
  1126. }
  1127. return nullptr;
  1128. }
  1129. bool
  1130. ThreadContext::FindExistingPropertyRecord(_In_ JsUtil::CharacterBuffer<WCHAR> const& propertyName, Js::CaseInvariantPropertyListWithHashCode** list)
  1131. {
  1132. Js::CaseInvariantPropertyListWithHashCode* l = this->caseInvariantPropertySet->LookupWithKey(propertyName);
  1133. (*list) = l;
  1134. return (l != nullptr);
  1135. }
  1136. void ThreadContext::CleanNoCasePropertyMap()
  1137. {
  1138. if (this->caseInvariantPropertySet != nullptr)
  1139. {
  1140. this->caseInvariantPropertySet->MapAndRemoveIf([](Js::CaseInvariantPropertyListWithHashCode* value) -> bool {
  1141. if (value && value->Count() == 0)
  1142. {
  1143. // Remove entry
  1144. return true;
  1145. }
  1146. // Keep entry
  1147. return false;
  1148. });
  1149. }
  1150. }
  1151. void
  1152. ThreadContext::ForceCleanPropertyMap()
  1153. {
  1154. // No-op now that we no longer use weak refs
  1155. }
  1156. #if ENABLE_NATIVE_CODEGEN
  1157. JsUtil::JobProcessor *
  1158. ThreadContext::GetJobProcessor()
  1159. {
  1160. if(bgJit && isOptimizedForManyInstances)
  1161. {
  1162. return ThreadBoundThreadContextManager::GetSharedJobProcessor();
  1163. }
  1164. if (!jobProcessor)
  1165. {
  1166. if(bgJit && !isOptimizedForManyInstances)
  1167. {
  1168. jobProcessor = HeapNew(JsUtil::BackgroundJobProcessor, GetAllocationPolicyManager(), &threadService, false /*disableParallelThreads*/);
  1169. }
  1170. else
  1171. {
  1172. jobProcessor = HeapNew(JsUtil::ForegroundJobProcessor);
  1173. }
  1174. }
  1175. return jobProcessor;
  1176. }
  1177. #endif
  1178. void
  1179. ThreadContext::RegisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData)
  1180. {
  1181. Assert(codeGenRecyclableData);
  1182. Assert(recyclableData);
  1183. // Linking must not be done concurrently with unlinking (caller must use lock)
  1184. recyclableData->codeGenRecyclableDatas.LinkToEnd(codeGenRecyclableData);
  1185. }
  1186. void
  1187. ThreadContext::UnregisterCodeGenRecyclableData(Js::CodeGenRecyclableData *const codeGenRecyclableData)
  1188. {
  1189. Assert(codeGenRecyclableData);
  1190. if(!recyclableData)
  1191. {
  1192. // The thread context's recyclable data may have already been released to the recycler if we're shutting down
  1193. return;
  1194. }
  1195. // Unlinking may be done from a background thread, but not concurrently with linking (caller must use lock). Partial unlink
  1196. // does not zero the previous and next links for the unlinked node so that the recycler can scan through the node from the
  1197. // main thread.
  1198. recyclableData->codeGenRecyclableDatas.UnlinkPartial(codeGenRecyclableData);
  1199. }
  1200. uint
  1201. ThreadContext::EnterScriptStart(Js::ScriptEntryExitRecord * record, bool doCleanup)
  1202. {
  1203. Recycler * recycler = this->GetRecycler();
  1204. Assert(recycler->IsReentrantState());
  1205. JS_ETW_INTERNAL(EventWriteJSCRIPT_RUN_START(this,0));
  1206. // Increment the callRootLevel early so that Dispose ran during FinishConcurrent will not close the current scriptContext
  1207. uint oldCallRootLevel = this->callRootLevel++;
  1208. if (oldCallRootLevel == 0)
  1209. {
  1210. Assert(!this->hasThrownPendingException);
  1211. RECORD_TIMESTAMP(lastScriptStartTime);
  1212. InterruptPoller *poller = this->interruptPoller;
  1213. if (poller)
  1214. {
  1215. poller->StartScript();
  1216. }
  1217. recycler->SetIsInScript(true);
  1218. if (doCleanup)
  1219. {
  1220. recycler->EnterIdleDecommit();
  1221. #if ENABLE_CONCURRENT_GC
  1222. recycler->FinishConcurrent<FinishConcurrentOnEnterScript>();
  1223. #endif
  1224. if (threadServiceWrapper == NULL)
  1225. {
  1226. // Reschedule the next collection at the start of the script.
  1227. recycler->ScheduleNextCollection();
  1228. }
  1229. }
  1230. }
  1231. this->PushEntryExitRecord(record);
  1232. AssertMsg(!this->IsScriptActive(),
  1233. "Missing EnterScriptEnd or LeaveScriptStart");
  1234. this->isScriptActive = true;
  1235. recycler->SetIsScriptActive(true);
  1236. #if DBG_DUMP
  1237. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1238. {
  1239. Output::Trace(Js::RunPhase, _u("%p> EnterScriptStart(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1240. Output::Flush();
  1241. }
  1242. #endif
  1243. return oldCallRootLevel;
  1244. }
  1245. void
  1246. ThreadContext::EnterScriptEnd(Js::ScriptEntryExitRecord * record, bool doCleanup)
  1247. {
  1248. #if DBG_DUMP
  1249. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1250. {
  1251. Output::Trace(Js::RunPhase, _u("%p> EnterScriptEnd (%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1252. Output::Flush();
  1253. }
  1254. #endif
  1255. this->PopEntryExitRecord(record);
  1256. AssertMsg(this->IsScriptActive(),
  1257. "Missing EnterScriptStart or LeaveScriptEnd");
  1258. this->isScriptActive = false;
  1259. this->GetRecycler()->SetIsScriptActive(false);
  1260. this->callRootLevel--;
  1261. #ifdef EXCEPTION_CHECK
  1262. ExceptionCheck::SetHandledExceptionType(record->handledExceptionType);
  1263. #endif
  1264. #ifdef RECYCLER_MEMORY_VERIFY
  1265. recycler->Verify(Js::RunPhase);
  1266. #endif
  1267. if (this->callRootLevel == 0)
  1268. {
  1269. RECORD_TIMESTAMP(lastScriptEndTime);
  1270. this->GetRecycler()->SetIsInScript(false);
  1271. InterruptPoller *poller = this->interruptPoller;
  1272. if (poller)
  1273. {
  1274. poller->EndScript();
  1275. }
  1276. ClosePendingProjectionContexts();
  1277. ClosePendingScriptContexts();
  1278. Assert(rootPendingClose == nullptr);
  1279. if (this->hasThrownPendingException)
  1280. {
  1281. // We have some cases where the thread instant of JavascriptExceptionObject
  1282. // are ignored and not clear. To avoid leaks, clear it here when
  1283. // we are not in script, where no one should be using these JavascriptExceptionObject
  1284. this->ClearPendingOOMError();
  1285. this->ClearPendingSOError();
  1286. this->hasThrownPendingException = false;
  1287. }
  1288. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1289. if (Js::Configuration::Global.flags.FreeRejittedCode)
  1290. #endif
  1291. {
  1292. // Since we're no longer in script, old entry points can now be collected
  1293. Js::FunctionEntryPointInfo* current = this->recyclableData->oldEntryPointInfo;
  1294. this->recyclableData->oldEntryPointInfo = nullptr;
  1295. // Clear out the next pointers so older entry points wont be held on
  1296. // as a false positive
  1297. while (current != nullptr)
  1298. {
  1299. Js::FunctionEntryPointInfo* next = current->nextEntryPoint;
  1300. current->nextEntryPoint = nullptr;
  1301. current = next;
  1302. }
  1303. }
  1304. if (doCleanup)
  1305. {
  1306. ThreadServiceWrapper* threadServiceWrapper = GetThreadServiceWrapper();
  1307. if (!threadServiceWrapper || !threadServiceWrapper->ScheduleNextCollectOnExit())
  1308. {
  1309. // Do the idle GC now if we fail schedule one.
  1310. recycler->CollectNow<CollectOnScriptExit>();
  1311. }
  1312. recycler->LeaveIdleDecommit();
  1313. }
  1314. }
  1315. if (doCleanup)
  1316. {
  1317. PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in EnterScriptEnd: %d\n"), this->recycler->NeedDispose());
  1318. if (this->recycler->NeedDispose())
  1319. {
  1320. this->recycler->FinishDisposeObjectsNow<FinishDispose>();
  1321. }
  1322. }
  1323. JS_ETW_INTERNAL(EventWriteJSCRIPT_RUN_STOP(this,0));
  1324. }
  1325. void
  1326. ThreadContext::SetForceOneIdleCollection()
  1327. {
  1328. ThreadServiceWrapper* threadServiceWrapper = GetThreadServiceWrapper();
  1329. if (threadServiceWrapper)
  1330. {
  1331. threadServiceWrapper->SetForceOneIdleCollection();
  1332. }
  1333. }
  1334. bool
  1335. ThreadContext::IsOnStack(void const *ptr)
  1336. {
  1337. if (IS_ASAN_FAKE_STACK_ADDR(ptr))
  1338. {
  1339. return true;
  1340. }
  1341. #if defined(_M_IX86) && defined(_MSC_VER)
  1342. return ptr < (void*)__readfsdword(0x4) && ptr >= (void*)__readfsdword(0xE0C);
  1343. #elif defined(_M_AMD64) && defined(_MSC_VER)
  1344. return ptr < (void*)__readgsqword(0x8) && ptr >= (void*)__readgsqword(0x1478);
  1345. #elif defined(_M_ARM)
  1346. ULONG lowLimit, highLimit;
  1347. ::GetCurrentThreadStackLimits(&lowLimit, &highLimit);
  1348. bool isOnStack = (void*)lowLimit <= ptr && ptr < (void*)highLimit;
  1349. return isOnStack;
  1350. #elif defined(_M_ARM64)
  1351. ULONG64 lowLimit, highLimit;
  1352. ::GetCurrentThreadStackLimits(&lowLimit, &highLimit);
  1353. bool isOnStack = (void*)lowLimit <= ptr && ptr < (void*)highLimit;
  1354. return isOnStack;
  1355. #elif !defined(_MSC_VER)
  1356. return ::IsAddressOnStack((ULONG_PTR) ptr);
  1357. #else
  1358. AssertMsg(FALSE, "IsOnStack -- not implemented yet case");
  1359. Js::Throw::NotImplemented();
  1360. return false;
  1361. #endif
  1362. }
  1363. size_t
  1364. ThreadContext::GetStackLimitForCurrentThread() const
  1365. {
  1366. FAULTINJECT_SCRIPT_TERMINATION;
  1367. size_t limit = this->stackLimitForCurrentThread;
  1368. Assert(limit == Js::Constants::StackLimitForScriptInterrupt
  1369. || !this->GetStackProber()
  1370. || limit == this->GetStackProber()->GetScriptStackLimit());
  1371. return limit;
  1372. }
  1373. void
  1374. ThreadContext::SetStackLimitForCurrentThread(size_t limit)
  1375. {
  1376. this->stackLimitForCurrentThread = limit;
  1377. }
  1378. _NOINLINE //Win8 947081: might use wrong _AddressOfReturnAddress() if this and caller are inlined
  1379. bool
  1380. ThreadContext::IsStackAvailable(size_t size, bool* isInterrupt)
  1381. {
  1382. size_t sp = (size_t)_AddressOfReturnAddress();
  1383. size_t stackLimit = this->GetStackLimitForCurrentThread();
  1384. bool stackAvailable = (sp > size && (sp - size) > stackLimit);
  1385. // Verify that JIT'd frames didn't mess up the ABI stack alignment
  1386. Assert(((uintptr_t)sp & (AutoSystemInfo::StackAlign - 1)) == (sizeof(void*) & (AutoSystemInfo::StackAlign - 1)));
  1387. #if DBG
  1388. this->GetStackProber()->AdjustKnownStackLimit(sp, size);
  1389. #endif
  1390. FAULTINJECT_STACK_PROBE
  1391. if (stackAvailable)
  1392. {
  1393. return true;
  1394. }
  1395. if (sp <= stackLimit)
  1396. {
  1397. if (stackLimit == Js::Constants::StackLimitForScriptInterrupt)
  1398. {
  1399. if (sp <= this->GetStackProber()->GetScriptStackLimit())
  1400. {
  1401. // Take down the process if we cant recover from the stack overflow
  1402. Js::Throw::FatalInternalError();
  1403. }
  1404. if (isInterrupt)
  1405. {
  1406. *isInterrupt = true; // when stack not available, indicate if due to script interrupt
  1407. }
  1408. }
  1409. }
  1410. return false;
  1411. }
  1412. _NOINLINE //Win8 947081: might use wrong _AddressOfReturnAddress() if this and caller are inlined
  1413. bool
  1414. ThreadContext::IsStackAvailableNoThrow(size_t size)
  1415. {
  1416. size_t sp = (size_t)_AddressOfReturnAddress();
  1417. size_t stackLimit = this->GetStackLimitForCurrentThread();
  1418. bool stackAvailable = (sp > stackLimit) && (sp > size) && ((sp - size) > stackLimit);
  1419. FAULTINJECT_STACK_PROBE
  1420. return stackAvailable;
  1421. }
  1422. /* static */ bool
  1423. ThreadContext::IsCurrentStackAvailable(size_t size)
  1424. {
  1425. ThreadContext *currentContext = GetContextForCurrentThread();
  1426. Assert(currentContext);
  1427. return currentContext->IsStackAvailable(size);
  1428. }
  1429. /*
  1430. returnAddress will be passed in the stackprobe call at the beginning of interpreter frame.
  1431. We need to probe the stack before we link up the InterpreterFrame structure in threadcontext,
  1432. and if we throw there, the stack walker might get confused when trying to identify a frame
  1433. is interpreter frame by comparing the current ebp in ebp chain with return address specified
  1434. in the last InterpreterFrame linked in threadcontext. We need to pass in the return address
  1435. of the probing frame to skip the right one (we need to skip first match in a->a->a recursion,
  1436. but not in a->b->a recursion).
  1437. */
  1438. void
  1439. ThreadContext::ProbeStackNoDispose(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress)
  1440. {
  1441. AssertCanHandleStackOverflow();
  1442. if (!this->IsStackAvailable(size))
  1443. {
  1444. if (this->IsExecutionDisabled())
  1445. {
  1446. // The probe failed because we hammered the stack limit to trigger script interrupt.
  1447. Assert(this->DoInterruptProbe());
  1448. throw Js::ScriptAbortException();
  1449. }
  1450. Js::Throw::StackOverflow(scriptContext, returnAddress);
  1451. }
  1452. #if defined(NTBUILD) || defined(__IOS__) || defined(__ANDROID__)
  1453. // Use every Nth stack probe as a QC trigger.
  1454. if (AutoSystemInfo::ShouldQCMoreFrequently() && this->HasInterruptPoller() && this->IsScriptActive())
  1455. {
  1456. ++(this->stackProbeCount);
  1457. if (this->stackProbeCount > ThreadContext::StackProbePollThreshold)
  1458. {
  1459. this->stackProbeCount = 0;
  1460. this->CheckInterruptPoll();
  1461. }
  1462. }
  1463. #endif
  1464. }
  1465. void
  1466. ThreadContext::ProbeStack(size_t size, Js::ScriptContext *scriptContext, PVOID returnAddress)
  1467. {
  1468. this->ProbeStackNoDispose(size, scriptContext, returnAddress);
  1469. #if PERFMAP_TRACE_ENABLED
  1470. if (PlatformAgnostic::PerfTrace::mapsRequested)
  1471. {
  1472. PlatformAgnostic::PerfTrace::WritePerfMap();
  1473. }
  1474. #endif
  1475. // BACKGROUND-GC TODO: If we're stuck purely in JITted code, we should have the
  1476. // background GC thread modify the threads stack limit to trigger the runtime stack probe
  1477. if (this->callDispose && this->recycler->NeedDispose())
  1478. {
  1479. PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in ProbeStack: %d\n"), this->recycler->NeedDispose());
  1480. this->recycler->FinishDisposeObjectsNow<FinishDisposeTimed>();
  1481. }
  1482. }
  1483. void
  1484. ThreadContext::ProbeStack(size_t size, Js::RecyclableObject * obj, Js::ScriptContext *scriptContext)
  1485. {
  1486. AssertCanHandleStackOverflowCall(obj->IsExternal() ||
  1487. (Js::JavascriptOperators::GetTypeId(obj) == Js::TypeIds_Function &&
  1488. Js::JavascriptFunction::FromVar(obj)->IsExternalFunction()));
  1489. if (!this->IsStackAvailable(size))
  1490. {
  1491. if (this->IsExecutionDisabled())
  1492. {
  1493. // The probe failed because we hammered the stack limit to trigger script interrupt.
  1494. Assert(this->DoInterruptProbe());
  1495. throw Js::ScriptAbortException();
  1496. }
  1497. if (obj->IsExternal() ||
  1498. (Js::JavascriptOperators::GetTypeId(obj) == Js::TypeIds_Function &&
  1499. Js::JavascriptFunction::FromVar(obj)->IsExternalFunction()))
  1500. {
  1501. Js::JavascriptError::ThrowStackOverflowError(scriptContext);
  1502. }
  1503. Js::Throw::StackOverflow(scriptContext, NULL);
  1504. }
  1505. }
  1506. void
  1507. ThreadContext::ProbeStack(size_t size)
  1508. {
  1509. Assert(this->IsScriptActive());
  1510. Js::ScriptEntryExitRecord *entryExitRecord = this->GetScriptEntryExit();
  1511. Assert(entryExitRecord);
  1512. Js::ScriptContext *scriptContext = entryExitRecord->scriptContext;
  1513. Assert(scriptContext);
  1514. this->ProbeStack(size, scriptContext);
  1515. }
  1516. /* static */ void
  1517. ThreadContext::ProbeCurrentStack(size_t size, Js::ScriptContext *scriptContext)
  1518. {
  1519. Assert(scriptContext != nullptr);
  1520. Assert(scriptContext->GetThreadContext() == GetContextForCurrentThread());
  1521. scriptContext->GetThreadContext()->ProbeStack(size, scriptContext);
  1522. }
  1523. /* static */ void
  1524. ThreadContext::ProbeCurrentStackNoDispose(size_t size, Js::ScriptContext *scriptContext)
  1525. {
  1526. Assert(scriptContext != nullptr);
  1527. Assert(scriptContext->GetThreadContext() == GetContextForCurrentThread());
  1528. scriptContext->GetThreadContext()->ProbeStackNoDispose(size, scriptContext);
  1529. }
  1530. template <bool leaveForHost>
  1531. void
  1532. ThreadContext::LeaveScriptStart(void * frameAddress)
  1533. {
  1534. Assert(this->IsScriptActive());
  1535. #if DBG_DUMP
  1536. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1537. {
  1538. Output::Trace(Js::RunPhase, _u("%p> LeaveScriptStart(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1539. Output::Flush();
  1540. }
  1541. #endif
  1542. Js::ScriptEntryExitRecord * entryExitRecord = this->GetScriptEntryExit();
  1543. AssertMsg(entryExitRecord && entryExitRecord->frameIdOfScriptExitFunction == nullptr,
  1544. "Missing LeaveScriptEnd or EnterScriptStart");
  1545. entryExitRecord->frameIdOfScriptExitFunction = frameAddress;
  1546. this->isScriptActive = false;
  1547. this->GetRecycler()->SetIsScriptActive(false);
  1548. AssertMsg(!(leaveForHost && this->IsDisableImplicitCall()),
  1549. "Disable implicit call should have been caught before leaving script for host");
  1550. // Save the implicit call flags
  1551. entryExitRecord->savedImplicitCallFlags = this->GetImplicitCallFlags();
  1552. // clear the hasReentered to detect if we have reentered into script
  1553. entryExitRecord->hasReentered = false;
  1554. #if DBG || defined(PROFILE_EXEC)
  1555. entryExitRecord->leaveForHost = leaveForHost;
  1556. #endif
  1557. #if DBG
  1558. entryExitRecord->leaveForAsyncHostOperation = false;
  1559. #endif
  1560. #ifdef PROFILE_EXEC
  1561. if (leaveForHost)
  1562. {
  1563. entryExitRecord->scriptContext->ProfileEnd(Js::RunPhase);
  1564. }
  1565. #endif
  1566. }
  1567. void ThreadContext::DisposeOnLeaveScript()
  1568. {
  1569. PHASE_PRINT_TRACE1(Js::DisposePhase, _u("[Dispose] NeedDispose in LeaveScriptStart: %d\n"), this->recycler->NeedDispose());
  1570. if (this->callDispose && this->recycler->NeedDispose()
  1571. && !recycler->IsCollectionDisabled())
  1572. {
  1573. this->recycler->FinishDisposeObjectsNow<FinishDispose>();
  1574. }
  1575. }
  1576. template <bool leaveForHost>
  1577. void
  1578. ThreadContext::LeaveScriptEnd(void * frameAddress)
  1579. {
  1580. Assert(!this->IsScriptActive());
  1581. #if DBG_DUMP
  1582. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::RunPhase))
  1583. {
  1584. Output::Trace(Js::RunPhase, _u("%p> LeaveScriptEnd(%p): Level %d\n"), ::GetCurrentThreadId(), this, this->callRootLevel);
  1585. Output::Flush();
  1586. }
  1587. #endif
  1588. Js::ScriptEntryExitRecord * entryExitRecord = this->GetScriptEntryExit();
  1589. AssertMsg(entryExitRecord && entryExitRecord->frameIdOfScriptExitFunction,
  1590. "LeaveScriptEnd without LeaveScriptStart");
  1591. AssertMsg(frameAddress == nullptr || frameAddress == entryExitRecord->frameIdOfScriptExitFunction,
  1592. "Mismatched script exit frames");
  1593. Assert(!!entryExitRecord->leaveForHost == leaveForHost);
  1594. entryExitRecord->frameIdOfScriptExitFunction = nullptr;
  1595. AssertMsg(!this->IsScriptActive(), "Missing LeaveScriptStart or LeaveScriptStart");
  1596. this->isScriptActive = true;
  1597. this->GetRecycler()->SetIsScriptActive(true);
  1598. Js::ImplicitCallFlags savedImplicitCallFlags = entryExitRecord->savedImplicitCallFlags;
  1599. if (leaveForHost)
  1600. {
  1601. savedImplicitCallFlags = (Js::ImplicitCallFlags)(savedImplicitCallFlags | Js::ImplicitCall_External);
  1602. }
  1603. else if (entryExitRecord->hasReentered)
  1604. {
  1605. savedImplicitCallFlags = (Js::ImplicitCallFlags)(savedImplicitCallFlags | Js::ImplicitCall_AsyncHostOperation);
  1606. }
  1607. // Restore the implicit call flags
  1608. this->SetImplicitCallFlags(savedImplicitCallFlags);
  1609. #ifdef PROFILE_EXEC
  1610. if (leaveForHost)
  1611. {
  1612. entryExitRecord->scriptContext->ProfileBegin(Js::RunPhase);
  1613. }
  1614. #endif
  1615. }
  1616. // explicit instantiations
  1617. template void ThreadContext::LeaveScriptStart<true>(void * frameAddress);
  1618. template void ThreadContext::LeaveScriptStart<false>(void * frameAddress);
  1619. template void ThreadContext::LeaveScriptEnd<true>(void * frameAddress);
  1620. template void ThreadContext::LeaveScriptEnd<false>(void * frameAddress);
  1621. void
  1622. ThreadContext::PushInterpreterFrame(Js::InterpreterStackFrame *interpreterFrame)
  1623. {
  1624. interpreterFrame->SetPreviousFrame(this->leafInterpreterFrame);
  1625. this->leafInterpreterFrame = interpreterFrame;
  1626. }
  1627. Js::InterpreterStackFrame *
  1628. ThreadContext::PopInterpreterFrame()
  1629. {
  1630. Js::InterpreterStackFrame *interpreterFrame = this->leafInterpreterFrame;
  1631. Assert(interpreterFrame);
  1632. this->leafInterpreterFrame = interpreterFrame->GetPreviousFrame();
  1633. return interpreterFrame;
  1634. }
  1635. BOOL
  1636. ThreadContext::ExecuteRecyclerCollectionFunctionCommon(Recycler * recycler, CollectionFunction function, CollectionFlags flags)
  1637. {
  1638. return __super::ExecuteRecyclerCollectionFunction(recycler, function, flags);
  1639. }
  1640. #if DBG
  1641. bool
  1642. ThreadContext::IsInAsyncHostOperation() const
  1643. {
  1644. if (!this->IsScriptActive())
  1645. {
  1646. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  1647. if (lastRecord != NULL)
  1648. {
  1649. return !!lastRecord->leaveForAsyncHostOperation;
  1650. }
  1651. }
  1652. return false;
  1653. }
  1654. #endif
  1655. #if ENABLE_NATIVE_CODEGEN
  1656. void
  1657. ThreadContext::SetJITConnectionInfo(HANDLE processHandle, void* serverSecurityDescriptor, UUID connectionId)
  1658. {
  1659. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  1660. if (!JITManager::GetJITManager()->IsConnected())
  1661. {
  1662. // TODO: return HRESULT
  1663. JITManager::GetJITManager()->ConnectRpcServer(processHandle, serverSecurityDescriptor, connectionId);
  1664. }
  1665. }
  1666. bool
  1667. ThreadContext::EnsureJITThreadContext(bool allowPrereserveAlloc)
  1668. {
  1669. #if ENABLE_OOP_NATIVE_CODEGEN
  1670. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  1671. if (!JITManager::GetJITManager()->IsConnected())
  1672. {
  1673. return false;
  1674. }
  1675. if (m_remoteThreadContextInfo)
  1676. {
  1677. return true;
  1678. }
  1679. ThreadContextDataIDL contextData;
  1680. contextData.threadStackLimitAddr = reinterpret_cast<intptr_t>(GetAddressOfStackLimitForCurrentThread());
  1681. contextData.bailOutRegisterSaveSpaceAddr = (intptr_t)bailOutRegisterSaveSpace;
  1682. contextData.disableImplicitFlagsAddr = (intptr_t)GetAddressOfDisableImplicitFlags();
  1683. contextData.implicitCallFlagsAddr = (intptr_t)GetAddressOfImplicitCallFlags();
  1684. contextData.scriptStackLimit = GetScriptStackLimit();
  1685. contextData.isThreadBound = IsThreadBound();
  1686. contextData.allowPrereserveAlloc = allowPrereserveAlloc;
  1687. #if defined(ENABLE_WASM_SIMD) && (_M_IX86 || _M_AMD64)
  1688. contextData.simdTempAreaBaseAddr = (intptr_t)GetSimdTempArea();
  1689. #endif
  1690. m_jitNumericProperties = HeapNew(BVSparse<HeapAllocator>, &HeapAllocator::Instance);
  1691. for (auto iter = propertyMap->GetIterator(); iter.IsValid(); iter.MoveNext())
  1692. {
  1693. if (iter.CurrentKey()->IsNumeric())
  1694. {
  1695. m_jitNumericProperties->Set(iter.CurrentKey()->GetPropertyId());
  1696. m_jitNeedsPropertyUpdate = true;
  1697. }
  1698. }
  1699. HRESULT hr = JITManager::GetJITManager()->InitializeThreadContext(
  1700. &contextData,
  1701. &m_remoteThreadContextInfo,
  1702. &m_prereservedRegionAddr,
  1703. &m_jitThunkStartAddr);
  1704. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1705. return m_remoteThreadContextInfo != nullptr;
  1706. #endif
  1707. }
  1708. #endif
  1709. #if ENABLE_TTD
  1710. void ThreadContext::InitTimeTravel(ThreadContext* threadContext, void* runtimeHandle, uint32 snapInterval, uint32 snapHistoryLength)
  1711. {
  1712. TTDAssert(!this->IsRuntimeInTTDMode(), "We should only init once.");
  1713. this->TTDContext = HeapNew(TTD::ThreadContextTTD, this, runtimeHandle, snapInterval, snapHistoryLength);
  1714. this->TTDLog = HeapNew(TTD::EventLog, this);
  1715. }
  1716. void ThreadContext::InitHostFunctionsAndTTData(bool record, bool replay, bool debug, size_t optTTUriLength, const char* optTTUri,
  1717. TTD::TTDOpenResourceStreamCallback openResourceStreamfp, TTD::TTDReadBytesFromStreamCallback readBytesFromStreamfp,
  1718. TTD::TTDWriteBytesToStreamCallback writeBytesToStreamfp, TTD::TTDFlushAndCloseStreamCallback flushAndCloseStreamfp,
  1719. TTD::TTDCreateExternalObjectCallback createExternalObjectfp,
  1720. TTD::TTDCreateJsRTContextCallback createJsRTContextCallbackfp, TTD::TTDReleaseJsRTContextCallback releaseJsRTContextCallbackfp, TTD::TTDSetActiveJsRTContext setActiveJsRTContextfp)
  1721. {
  1722. AssertMsg(this->IsRuntimeInTTDMode(), "Need to call init first.");
  1723. this->TTDContext->TTDataIOInfo = { openResourceStreamfp, readBytesFromStreamfp, writeBytesToStreamfp, flushAndCloseStreamfp, 0, nullptr };
  1724. this->TTDContext->TTDExternalObjectFunctions = { createExternalObjectfp, createJsRTContextCallbackfp, releaseJsRTContextCallbackfp, setActiveJsRTContextfp };
  1725. if(record)
  1726. {
  1727. TTDAssert(optTTUri == nullptr, "No URI is needed in record mode (the host explicitly provides it when writing.");
  1728. this->TTDLog->InitForTTDRecord(debug);
  1729. }
  1730. else
  1731. {
  1732. TTDAssert(optTTUri != nullptr, "We need a URI in replay mode so we can initialize the log from it");
  1733. this->TTDLog->InitForTTDReplay(this->TTDContext->TTDataIOInfo, optTTUri, optTTUriLength, debug);
  1734. this->sourceInfoCount = this->TTDLog->GetSourceInfoCount();
  1735. }
  1736. #if !ENABLE_TTD_DIAGNOSTICS_TRACING
  1737. if(debug)
  1738. {
  1739. #endif
  1740. TTD::TTInnerLoopLastStatementInfo lsi;
  1741. TTD::TTDebuggerSourceLocation dsl;
  1742. this->TTDLog->LoadLastSourceLineInfo(lsi, dsl);
  1743. this->TTDExecutionInfo = HeapNew(TTD::ExecutionInfoManager, lsi);
  1744. if(dsl.HasValue())
  1745. {
  1746. this->TTDExecutionInfo->SetPendingTTDToTarget(dsl);
  1747. }
  1748. #if !ENABLE_TTD_DIAGNOSTICS_TRACING
  1749. }
  1750. #endif
  1751. }
  1752. #endif
  1753. BOOL
  1754. ThreadContext::ExecuteRecyclerCollectionFunction(Recycler * recycler, CollectionFunction function, CollectionFlags flags)
  1755. {
  1756. // If the thread context doesn't have an associated Recycler set, don't do anything
  1757. if (this->recycler == nullptr)
  1758. {
  1759. return FALSE;
  1760. }
  1761. // Take etw rundown lock on this thread context. We can't collect entryPoints if we are in etw rundown.
  1762. AutoCriticalSection autocs(this->GetFunctionBodyLock());
  1763. // Disable calling dispose from leave script or the stack probe
  1764. // while we're executing the recycler wrapper
  1765. AutoRestoreValue<bool> callDispose(&this->callDispose, false);
  1766. BOOL ret = FALSE;
  1767. #if ENABLE_TTD
  1768. //
  1769. //TODO: We lose any events that happen in the callbacks (such as JsRelease) which may be a problem in the future.
  1770. // It may be possible to defer the collection of these objects to an explicit collection at the yield loop (same for weak set/map).
  1771. // We already indirectly do this for ScriptContext collection (but that is buggy so needs to be fixed too).
  1772. //
  1773. if(this->IsRuntimeInTTDMode())
  1774. {
  1775. this->TTDLog->PushMode(TTD::TTDMode::ExcludedExecutionTTAction);
  1776. }
  1777. #endif
  1778. if (!this->IsScriptActive())
  1779. {
  1780. Assert(!this->IsDisableImplicitCall() || this->IsInAsyncHostOperation());
  1781. ret = this->ExecuteRecyclerCollectionFunctionCommon(recycler, function, flags);
  1782. // Make sure that we finish a collect that is activated outside of script, since
  1783. // we won't have exit script to schedule it
  1784. if (!this->IsInScript() && recycler->CollectionInProgress()
  1785. && ((flags & CollectOverride_DisableIdleFinish) == 0) && threadServiceWrapper)
  1786. {
  1787. threadServiceWrapper->ScheduleFinishConcurrent();
  1788. }
  1789. }
  1790. else
  1791. {
  1792. void * frameAddr = nullptr;
  1793. GET_CURRENT_FRAME_ID(frameAddr);
  1794. // We may need stack to call out from Dispose or QC
  1795. if (!this->IsDisableImplicitCall()) // otherwise Dispose/QC disabled
  1796. {
  1797. // If we don't have stack space to call out from Dispose or QC,
  1798. // don't throw, simply return false. This gives SnailAlloc a better
  1799. // chance of allocating in low stack-space situations (like allocating
  1800. // a StackOverflowException object)
  1801. if (!this->IsStackAvailableNoThrow(Js::Constants::MinStackCallout))
  1802. {
  1803. return false;
  1804. }
  1805. }
  1806. this->LeaveScriptStart<false>(frameAddr);
  1807. ret = this->ExecuteRecyclerCollectionFunctionCommon(recycler, function, flags);
  1808. this->LeaveScriptEnd<false>(frameAddr);
  1809. if (this->callRootLevel != 0)
  1810. {
  1811. this->CheckScriptInterrupt();
  1812. }
  1813. }
  1814. #if ENABLE_TTD
  1815. if(this->IsRuntimeInTTDMode())
  1816. {
  1817. this->TTDLog->PopMode(TTD::TTDMode::ExcludedExecutionTTAction);
  1818. }
  1819. #endif
  1820. return ret;
  1821. }
  1822. void
  1823. ThreadContext::DisposeObjects(Recycler * recycler)
  1824. {
  1825. if (this->IsDisableImplicitCall())
  1826. {
  1827. // Don't dispose objects when implicit calls are disabled, since disposing may cause implicit calls. Objects will remain
  1828. // in the dispose queue and will be disposed later when implicit calls are not disabled.
  1829. return;
  1830. }
  1831. // We shouldn't DisposeObjects in NoScriptScope as this might lead to script execution.
  1832. // Callers of DisposeObjects should ensure !IsNoScriptScope() before calling DisposeObjects.
  1833. if (this->IsNoScriptScope())
  1834. {
  1835. FromDOM_NoScriptScope_unrecoverable_error();
  1836. }
  1837. if (!this->IsScriptActive())
  1838. {
  1839. __super::DisposeObjects(recycler);
  1840. }
  1841. else
  1842. {
  1843. void * frameAddr = nullptr;
  1844. GET_CURRENT_FRAME_ID(frameAddr);
  1845. // We may need stack to call out from Dispose
  1846. this->ProbeStack(Js::Constants::MinStackCallout);
  1847. this->LeaveScriptStart<false>(frameAddr);
  1848. __super::DisposeObjects(recycler);
  1849. this->LeaveScriptEnd<false>(frameAddr);
  1850. }
  1851. }
  1852. void
  1853. ThreadContext::PushEntryExitRecord(Js::ScriptEntryExitRecord * record)
  1854. {
  1855. AssertMsg(record, "Didn't provide a script entry record to push");
  1856. Assert(record->next == nullptr);
  1857. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  1858. if (lastRecord != nullptr)
  1859. {
  1860. // If we enter script again, we should have leave with leaveForHost or leave for dispose.
  1861. Assert(lastRecord->leaveForHost || lastRecord->leaveForAsyncHostOperation);
  1862. lastRecord->hasReentered = true;
  1863. record->next = lastRecord;
  1864. // these are on stack, which grows down. if this condition doesn't hold,
  1865. // then the list somehow got messed up
  1866. if (
  1867. #if defined(JSRT_VERIFY_RUNTIME_STATE) || defined(DEBUG)
  1868. !IsOnStack(lastRecord) ||
  1869. #endif
  1870. ((uintptr_t)record >= (uintptr_t)lastRecord
  1871. && !IS_ASAN_FAKE_STACK_ADDR(record)
  1872. && !IS_ASAN_FAKE_STACK_ADDR(lastRecord)))
  1873. {
  1874. EntryExitRecord_Corrupted_unrecoverable_error();
  1875. }
  1876. }
  1877. this->entryExitRecord = record;
  1878. }
  1879. void ThreadContext::PopEntryExitRecord(Js::ScriptEntryExitRecord * record)
  1880. {
  1881. AssertMsg(record && record == this->entryExitRecord, "Mismatch script entry/exit");
  1882. // these are on stack, which grows down. if this condition doesn't hold,
  1883. // then the list somehow got messed up
  1884. Js::ScriptEntryExitRecord * next = this->entryExitRecord->next;
  1885. if (next && (
  1886. #if defined(JSRT_VERIFY_RUNTIME_STATE) || defined(DEBUG)
  1887. !IsOnStack(next) ||
  1888. #endif
  1889. ((uintptr_t)this->entryExitRecord >= (uintptr_t)next
  1890. && !IS_ASAN_FAKE_STACK_ADDR(this->entryExitRecord)
  1891. && !IS_ASAN_FAKE_STACK_ADDR(next))))
  1892. {
  1893. EntryExitRecord_Corrupted_unrecoverable_error();
  1894. }
  1895. this->entryExitRecord = next;
  1896. }
  1897. BOOL ThreadContext::ReserveStaticTypeIds(__in int first, __in int last)
  1898. {
  1899. if ( nextTypeId <= first )
  1900. {
  1901. nextTypeId = (Js::TypeId) last;
  1902. return TRUE;
  1903. }
  1904. else
  1905. {
  1906. return FALSE;
  1907. }
  1908. }
  1909. Js::TypeId ThreadContext::ReserveTypeIds(int count)
  1910. {
  1911. Js::TypeId firstTypeId = nextTypeId;
  1912. nextTypeId = (Js::TypeId)(nextTypeId + count);
  1913. return firstTypeId;
  1914. }
  1915. Js::TypeId ThreadContext::CreateTypeId()
  1916. {
  1917. return nextTypeId = (Js::TypeId)(nextTypeId + 1);
  1918. }
  1919. void ThreadContext::SetWellKnownHostTypeId(WellKnownHostType wellKnownType, Js::TypeId typeId)
  1920. {
  1921. AssertMsg(wellKnownType <= WellKnownHostType_Last, "ThreadContext::SetWellKnownHostTypeId called on unknown type");
  1922. if (wellKnownType >= 0 && wellKnownType <= WellKnownHostType_Last)
  1923. {
  1924. this->wellKnownHostTypeIds[wellKnownType] = typeId;
  1925. #if ENABLE_NATIVE_CODEGEN
  1926. // The jit server really only needs to know about WellKnownHostType_HTMLAllCollection
  1927. if (this->m_remoteThreadContextInfo && wellKnownType == WellKnownHostType_HTMLAllCollection)
  1928. {
  1929. HRESULT hr = JITManager::GetJITManager()->SetWellKnownHostTypeId(this->m_remoteThreadContextInfo, (int)typeId);
  1930. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  1931. }
  1932. #endif
  1933. }
  1934. }
  1935. #ifdef ENABLE_SCRIPT_DEBUGGING
  1936. void ThreadContext::EnsureDebugManager()
  1937. {
  1938. if (this->debugManager == nullptr)
  1939. {
  1940. this->debugManager = HeapNew(Js::DebugManager, this, this->GetAllocationPolicyManager());
  1941. }
  1942. InterlockedIncrement(&crefSContextForDiag);
  1943. Assert(this->debugManager != nullptr);
  1944. }
  1945. void ThreadContext::ReleaseDebugManager()
  1946. {
  1947. Assert(crefSContextForDiag > 0);
  1948. Assert(this->debugManager != nullptr);
  1949. LONG lref = InterlockedDecrement(&crefSContextForDiag);
  1950. if (lref == 0)
  1951. {
  1952. if (this->recyclableData != nullptr)
  1953. {
  1954. this->recyclableData->returnedValueList = nullptr;
  1955. }
  1956. if (this->debugManager != nullptr)
  1957. {
  1958. this->debugManager->Close();
  1959. HeapDelete(this->debugManager);
  1960. this->debugManager = nullptr;
  1961. }
  1962. }
  1963. }
  1964. #endif
  1965. Js::TempArenaAllocatorObject *
  1966. ThreadContext::GetTemporaryAllocator(LPCWSTR name)
  1967. {
  1968. AssertCanHandleOutOfMemory();
  1969. if (temporaryArenaAllocatorCount != 0)
  1970. {
  1971. temporaryArenaAllocatorCount--;
  1972. Js::TempArenaAllocatorObject * allocator = recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount];
  1973. recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount] = nullptr;
  1974. return allocator;
  1975. }
  1976. return Js::TempArenaAllocatorObject::Create(this);
  1977. }
  1978. void
  1979. ThreadContext::ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject * tempAllocator)
  1980. {
  1981. if (temporaryArenaAllocatorCount < MaxTemporaryArenaAllocators)
  1982. {
  1983. tempAllocator->GetAllocator()->Reset();
  1984. recyclableData->temporaryArenaAllocators[temporaryArenaAllocatorCount] = tempAllocator;
  1985. temporaryArenaAllocatorCount++;
  1986. return;
  1987. }
  1988. tempAllocator->Dispose(false);
  1989. }
  1990. Js::TempGuestArenaAllocatorObject *
  1991. ThreadContext::GetTemporaryGuestAllocator(LPCWSTR name)
  1992. {
  1993. AssertCanHandleOutOfMemory();
  1994. if (temporaryGuestArenaAllocatorCount != 0)
  1995. {
  1996. temporaryGuestArenaAllocatorCount--;
  1997. Js::TempGuestArenaAllocatorObject * allocator = recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount];
  1998. allocator->AdviseInUse();
  1999. recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount] = nullptr;
  2000. return allocator;
  2001. }
  2002. return Js::TempGuestArenaAllocatorObject::Create(this);
  2003. }
  2004. void
  2005. ThreadContext::ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject * tempGuestAllocator)
  2006. {
  2007. if (temporaryGuestArenaAllocatorCount < MaxTemporaryArenaAllocators)
  2008. {
  2009. tempGuestAllocator->AdviseNotInUse();
  2010. recyclableData->temporaryGuestArenaAllocators[temporaryGuestArenaAllocatorCount] = tempGuestAllocator;
  2011. temporaryGuestArenaAllocatorCount++;
  2012. return;
  2013. }
  2014. tempGuestAllocator->Dispose(false);
  2015. }
  2016. void
  2017. ThreadContext::AddToPendingScriptContextCloseList(Js::ScriptContext * scriptContext)
  2018. {
  2019. Assert(scriptContext != nullptr);
  2020. if (rootPendingClose == nullptr)
  2021. {
  2022. rootPendingClose = scriptContext;
  2023. return;
  2024. }
  2025. // Prepend to the list.
  2026. scriptContext->SetNextPendingClose(rootPendingClose);
  2027. rootPendingClose = scriptContext;
  2028. }
  2029. void
  2030. ThreadContext::RemoveFromPendingClose(Js::ScriptContext * scriptContext)
  2031. {
  2032. Assert(scriptContext != nullptr);
  2033. if (rootPendingClose == nullptr)
  2034. {
  2035. // We already sent a close message, ignore the notification.
  2036. return;
  2037. }
  2038. // Base case: The root is being removed. Move the root along.
  2039. if (scriptContext == rootPendingClose)
  2040. {
  2041. rootPendingClose = rootPendingClose->GetNextPendingClose();
  2042. return;
  2043. }
  2044. Js::ScriptContext * currScriptContext = rootPendingClose;
  2045. Js::ScriptContext * nextScriptContext = nullptr;
  2046. while (currScriptContext)
  2047. {
  2048. nextScriptContext = currScriptContext->GetNextPendingClose();
  2049. if (!nextScriptContext)
  2050. {
  2051. break;
  2052. }
  2053. if (nextScriptContext == scriptContext) {
  2054. // The next pending close ScriptContext is the one to be removed - set prev->next to next->next
  2055. currScriptContext->SetNextPendingClose(nextScriptContext->GetNextPendingClose());
  2056. return;
  2057. }
  2058. currScriptContext = nextScriptContext;
  2059. }
  2060. // We expect to find scriptContext in the pending close list.
  2061. Assert(false);
  2062. }
  2063. void ThreadContext::ClosePendingScriptContexts()
  2064. {
  2065. Js::ScriptContext * scriptContext = rootPendingClose;
  2066. if (scriptContext == nullptr)
  2067. {
  2068. return;
  2069. }
  2070. Js::ScriptContext * nextScriptContext;
  2071. do
  2072. {
  2073. nextScriptContext = scriptContext->GetNextPendingClose();
  2074. scriptContext->Close(false);
  2075. scriptContext = nextScriptContext;
  2076. }
  2077. while (scriptContext);
  2078. rootPendingClose = nullptr;
  2079. }
  2080. void
  2081. ThreadContext::AddToPendingProjectionContextCloseList(IProjectionContext *projectionContext)
  2082. {
  2083. pendingProjectionContextCloseList->Add(projectionContext);
  2084. }
  2085. void
  2086. ThreadContext::RemoveFromPendingClose(IProjectionContext* projectionContext)
  2087. {
  2088. pendingProjectionContextCloseList->Remove(projectionContext);
  2089. }
  2090. void ThreadContext::ClosePendingProjectionContexts()
  2091. {
  2092. IProjectionContext* projectionContext;
  2093. for (int i = 0 ; i < pendingProjectionContextCloseList->Count(); i++)
  2094. {
  2095. projectionContext = pendingProjectionContextCloseList->Item(i);
  2096. projectionContext->Close();
  2097. }
  2098. pendingProjectionContextCloseList->Clear();
  2099. }
  2100. void
  2101. ThreadContext::RegisterScriptContext(Js::ScriptContext *scriptContext)
  2102. {
  2103. // NOTE: ETW rundown thread may be reading the scriptContextList concurrently. We don't need to
  2104. // lock access because we only insert to the front here.
  2105. scriptContext->next = this->scriptContextList;
  2106. if (this->scriptContextList)
  2107. {
  2108. Assert(this->scriptContextList->prev == NULL);
  2109. this->scriptContextList->prev = scriptContext;
  2110. }
  2111. scriptContext->prev = NULL;
  2112. this->scriptContextList = scriptContext;
  2113. if(NoJIT())
  2114. {
  2115. scriptContext->ForceNoNative();
  2116. }
  2117. if (NoDynamicThunks())
  2118. {
  2119. scriptContext->ForceNoDynamicThunks();
  2120. }
  2121. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  2122. scriptContextCount++;
  2123. #endif
  2124. scriptContextEverRegistered = true;
  2125. }
  2126. void
  2127. ThreadContext::UnregisterScriptContext(Js::ScriptContext *scriptContext)
  2128. {
  2129. // NOTE: ETW rundown thread may be reading the scriptContextList concurrently. Since this function
  2130. // is only called by ~ScriptContext() which already synchronized to ETW rundown, we are safe here.
  2131. if (scriptContext == this->scriptContextList)
  2132. {
  2133. Assert(scriptContext->prev == NULL);
  2134. this->scriptContextList = scriptContext->next;
  2135. }
  2136. else
  2137. {
  2138. scriptContext->prev->next = scriptContext->next;
  2139. }
  2140. if (scriptContext->next)
  2141. {
  2142. scriptContext->next->prev = scriptContext->prev;
  2143. }
  2144. scriptContext->prev = nullptr;
  2145. scriptContext->next = nullptr;
  2146. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  2147. scriptContextCount--;
  2148. #endif
  2149. }
  2150. ThreadContext::CollectCallBack *
  2151. ThreadContext::AddRecyclerCollectCallBack(RecyclerCollectCallBackFunction callback, void * context)
  2152. {
  2153. AutoCriticalSection autocs(&csCollectionCallBack);
  2154. CollectCallBack * collectCallBack = this->collectCallBackList.PrependNode(&HeapAllocator::Instance);
  2155. collectCallBack->callback = callback;
  2156. collectCallBack->context = context;
  2157. this->hasCollectionCallBack = true;
  2158. return collectCallBack;
  2159. }
  2160. void
  2161. ThreadContext::RemoveRecyclerCollectCallBack(ThreadContext::CollectCallBack * collectCallBack)
  2162. {
  2163. AutoCriticalSection autocs(&csCollectionCallBack);
  2164. this->collectCallBackList.RemoveElement(&HeapAllocator::Instance, collectCallBack);
  2165. this->hasCollectionCallBack = !this->collectCallBackList.Empty();
  2166. }
  2167. void
  2168. ThreadContext::PreCollectionCallBack(CollectionFlags flags)
  2169. {
  2170. #ifdef PERF_COUNTERS
  2171. PHASE_PRINT_TESTTRACE1(Js::DeferParsePhase, _u("TestTrace: deferparse - # of func: %d # deferparsed: %d\n"), PerfCounter::CodeCounterSet::GetTotalFunctionCounter().GetValue(), PerfCounter::CodeCounterSet::GetDeferredFunctionCounter().GetValue());
  2172. #endif
  2173. // This needs to be done before ClearInlineCaches since that method can empty the list of
  2174. // script contexts with inline caches
  2175. this->ClearScriptContextCaches();
  2176. // Clear up references to types to avoid keeping them alive
  2177. this->noSpecialPropertyRegistry.Clear();
  2178. this->onlyWritablePropertyRegistry.Clear();
  2179. // Clean up unused memory before we start collecting
  2180. this->CleanNoCasePropertyMap();
  2181. this->TryEnterExpirableCollectMode();
  2182. const BOOL concurrent = flags & CollectMode_Concurrent;
  2183. const BOOL partial = flags & CollectMode_Partial;
  2184. if (!partial)
  2185. {
  2186. // Integrate allocated pages from background JIT threads
  2187. #if ENABLE_NATIVE_CODEGEN
  2188. #if !FLOATVAR
  2189. if (codeGenNumberThreadAllocator)
  2190. {
  2191. codeGenNumberThreadAllocator->Integrate();
  2192. }
  2193. if (this->xProcNumberPageSegmentManager)
  2194. {
  2195. this->xProcNumberPageSegmentManager->Integrate();
  2196. }
  2197. #endif
  2198. #endif
  2199. }
  2200. RecyclerCollectCallBackFlags callBackFlags = (RecyclerCollectCallBackFlags)
  2201. ((concurrent ? Collect_Begin_Concurrent : Collect_Begin) | (partial? Collect_Begin_Partial : Collect_Begin));
  2202. CollectionCallBack(callBackFlags);
  2203. }
  2204. void
  2205. ThreadContext::PreSweepCallback()
  2206. {
  2207. #ifdef PERSISTENT_INLINE_CACHES
  2208. ClearInlineCachesWithDeadWeakRefs();
  2209. #else
  2210. ClearInlineCaches();
  2211. #endif
  2212. ClearIsInstInlineCaches();
  2213. ClearEquivalentTypeCaches();
  2214. ClearEnumeratorCaches();
  2215. this->dynamicObjectEnumeratorCacheMap.Clear();
  2216. }
  2217. void
  2218. ThreadContext::PreRescanMarkCallback()
  2219. {
  2220. // If this feature is turned off or if we're already in profile collection mode, do nothing
  2221. // We also do nothing if expiration is explicitly disabled by someone lower down the stack
  2222. if (!PHASE_OFF1(Js::ExpirableCollectPhase) && InExpirableCollectMode() && !this->disableExpiration)
  2223. {
  2224. this->DoExpirableCollectModeStackWalk();
  2225. }
  2226. }
  2227. void
  2228. ThreadContext::DoExpirableCollectModeStackWalk()
  2229. {
  2230. if (this->entryExitRecord != nullptr)
  2231. {
  2232. // If we're in script, we will do a stack walk, find the JavascriptFunction's on the stack
  2233. // and mark their entry points as being used so that we don't prematurely expire them
  2234. Js::ScriptContext* topScriptContext = this->entryExitRecord->scriptContext;
  2235. Js::JavascriptStackWalker walker(topScriptContext, TRUE);
  2236. Js::JavascriptFunction* javascriptFunction = nullptr;
  2237. while (walker.GetCallerWithoutInlinedFrames(&javascriptFunction))
  2238. {
  2239. if (javascriptFunction != nullptr && Js::ScriptFunction::Test(javascriptFunction))
  2240. {
  2241. Js::ScriptFunction* scriptFunction = (Js::ScriptFunction*) javascriptFunction;
  2242. Js::FunctionEntryPointInfo* entryPointInfo = scriptFunction->GetFunctionEntryPointInfo();
  2243. entryPointInfo->SetIsObjectUsed();
  2244. scriptFunction->GetFunctionBody()->MapEntryPoints([](int index, Js::FunctionEntryPointInfo* entryPoint){
  2245. entryPoint->SetIsObjectUsed();
  2246. });
  2247. }
  2248. }
  2249. }
  2250. }
  2251. void
  2252. ThreadContext::CollectionCallBack(RecyclerCollectCallBackFlags flags)
  2253. {
  2254. DListBase<CollectCallBack>::Iterator i(&this->collectCallBackList);
  2255. while (i.Next())
  2256. {
  2257. i.Data().callback(i.Data().context, flags);
  2258. }
  2259. }
  2260. void
  2261. ThreadContext::WaitCollectionCallBack()
  2262. {
  2263. // Avoid taking the lock if there are no call back
  2264. if (hasCollectionCallBack)
  2265. {
  2266. AutoCriticalSection autocs(&csCollectionCallBack);
  2267. CollectionCallBack(Collect_Wait);
  2268. }
  2269. }
  2270. void
  2271. ThreadContext::PostCollectionCallBack()
  2272. {
  2273. CollectionCallBack(Collect_End);
  2274. TryExitExpirableCollectMode();
  2275. // Recycler is null in the case where the ThreadContext is in the process of creating the recycler and
  2276. // we have a GC triggered (say because the -recyclerStress flag is passed in)
  2277. if (this->recycler != NULL)
  2278. {
  2279. if (this->recycler->InCacheCleanupCollection())
  2280. {
  2281. this->recycler->ClearCacheCleanupCollection();
  2282. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext; scriptContext = scriptContext->next)
  2283. {
  2284. scriptContext->CleanupWeakReferenceDictionaries();
  2285. }
  2286. }
  2287. }
  2288. }
  2289. void
  2290. ThreadContext::PostSweepRedeferralCallBack()
  2291. {
  2292. if (this->DoTryRedeferral())
  2293. {
  2294. HRESULT hr = S_OK;
  2295. BEGIN_TRANSLATE_OOM_TO_HRESULT
  2296. {
  2297. this->TryRedeferral();
  2298. }
  2299. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2300. }
  2301. this->UpdateRedeferralState();
  2302. }
  2303. bool
  2304. ThreadContext::DoTryRedeferral() const
  2305. {
  2306. if (PHASE_FORCE1(Js::RedeferralPhase) || PHASE_STRESS1(Js::RedeferralPhase))
  2307. {
  2308. return true;
  2309. }
  2310. if (PHASE_OFF1(Js::RedeferralPhase))
  2311. {
  2312. return false;
  2313. }
  2314. switch (this->redeferralState)
  2315. {
  2316. case InitialRedeferralState:
  2317. return false;
  2318. case StartupRedeferralState:
  2319. return gcSinceCallCountsCollected >= StartupRedeferralInactiveThreshold;
  2320. case MainRedeferralState:
  2321. return gcSinceCallCountsCollected >= MainRedeferralInactiveThreshold;
  2322. default:
  2323. Assert(0);
  2324. return false;
  2325. };
  2326. }
  2327. bool
  2328. ThreadContext::DoRedeferFunctionBodies() const
  2329. {
  2330. #if ENABLE_TTD
  2331. if (this->IsRuntimeInTTDMode())
  2332. {
  2333. return false;
  2334. }
  2335. #endif
  2336. if (PHASE_FORCE1(Js::RedeferralPhase) || PHASE_STRESS1(Js::RedeferralPhase))
  2337. {
  2338. return true;
  2339. }
  2340. if (PHASE_OFF1(Js::RedeferralPhase))
  2341. {
  2342. return false;
  2343. }
  2344. switch (this->redeferralState)
  2345. {
  2346. case InitialRedeferralState:
  2347. return false;
  2348. case StartupRedeferralState:
  2349. return gcSinceLastRedeferral >= StartupRedeferralCheckInterval;
  2350. case MainRedeferralState:
  2351. return gcSinceLastRedeferral >= MainRedeferralCheckInterval;
  2352. default:
  2353. Assert(0);
  2354. return false;
  2355. };
  2356. }
  2357. uint
  2358. ThreadContext::GetRedeferralCollectionInterval() const
  2359. {
  2360. switch(this->redeferralState)
  2361. {
  2362. case InitialRedeferralState:
  2363. return InitialRedeferralDelay;
  2364. case StartupRedeferralState:
  2365. return StartupRedeferralCheckInterval;
  2366. case MainRedeferralState:
  2367. return MainRedeferralCheckInterval;
  2368. default:
  2369. Assert(0);
  2370. return (uint)-1;
  2371. }
  2372. }
  2373. uint
  2374. ThreadContext::GetRedeferralInactiveThreshold() const
  2375. {
  2376. switch(this->redeferralState)
  2377. {
  2378. case InitialRedeferralState:
  2379. return InitialRedeferralDelay;
  2380. case StartupRedeferralState:
  2381. return StartupRedeferralInactiveThreshold;
  2382. case MainRedeferralState:
  2383. return MainRedeferralInactiveThreshold;
  2384. default:
  2385. Assert(0);
  2386. return (uint)-1;
  2387. }
  2388. }
  2389. void
  2390. ThreadContext::TryRedeferral()
  2391. {
  2392. bool doRedefer = this->DoRedeferFunctionBodies();
  2393. // Collect the set of active functions.
  2394. ActiveFunctionSet *pActiveFuncs = nullptr;
  2395. if (doRedefer)
  2396. {
  2397. pActiveFuncs = Anew(this->GetThreadAlloc(), ActiveFunctionSet, this->GetThreadAlloc());
  2398. this->GetActiveFunctions(pActiveFuncs);
  2399. #if DBG
  2400. this->redeferredFunctions = 0;
  2401. this->recoveredBytes = 0;
  2402. #endif
  2403. }
  2404. uint inactiveThreshold = this->GetRedeferralInactiveThreshold();
  2405. Js::ScriptContext *scriptContext;
  2406. for (scriptContext = GetScriptContextList(); scriptContext; scriptContext = scriptContext->next)
  2407. {
  2408. if (scriptContext->IsClosed())
  2409. {
  2410. continue;
  2411. }
  2412. scriptContext->RedeferFunctionBodies(pActiveFuncs, inactiveThreshold);
  2413. }
  2414. if (pActiveFuncs)
  2415. {
  2416. Adelete(this->GetThreadAlloc(), pActiveFuncs);
  2417. #if DBG
  2418. if (PHASE_STATS1(Js::RedeferralPhase) && this->redeferredFunctions)
  2419. {
  2420. Output::Print(_u("Redeferred: %d, Bytes: 0x%x\n"), this->redeferredFunctions, this->recoveredBytes);
  2421. }
  2422. #endif
  2423. }
  2424. }
  2425. void
  2426. ThreadContext::GetActiveFunctions(ActiveFunctionSet * pActiveFuncs)
  2427. {
  2428. if (!this->IsInScript() || this->entryExitRecord == nullptr)
  2429. {
  2430. return;
  2431. }
  2432. Js::JavascriptStackWalker walker(GetScriptContextList(), TRUE, NULL, true);
  2433. Js::JavascriptFunction *function = nullptr;
  2434. while (walker.GetCallerWithoutInlinedFrames(&function))
  2435. {
  2436. if (function->GetFunctionInfo()->HasBody())
  2437. {
  2438. Js::FunctionBody *body = function->GetFunctionInfo()->GetFunctionBody();
  2439. body->UpdateActiveFunctionSet(pActiveFuncs, nullptr);
  2440. }
  2441. }
  2442. }
  2443. void
  2444. ThreadContext::UpdateRedeferralState()
  2445. {
  2446. uint inactiveThreshold = this->GetRedeferralInactiveThreshold();
  2447. uint collectInterval = this->GetRedeferralCollectionInterval();
  2448. if (this->gcSinceCallCountsCollected >= inactiveThreshold)
  2449. {
  2450. this->gcSinceCallCountsCollected = 0;
  2451. if (this->gcSinceLastRedeferral >= collectInterval)
  2452. {
  2453. // Advance state
  2454. switch (this->redeferralState)
  2455. {
  2456. case InitialRedeferralState:
  2457. this->redeferralState = StartupRedeferralState;
  2458. break;
  2459. case StartupRedeferralState:
  2460. this->redeferralState = MainRedeferralState;
  2461. break;
  2462. case MainRedeferralState:
  2463. break;
  2464. default:
  2465. Assert(0);
  2466. break;
  2467. }
  2468. this->gcSinceLastRedeferral = 0;
  2469. }
  2470. }
  2471. else
  2472. {
  2473. this->gcSinceCallCountsCollected++;
  2474. this->gcSinceLastRedeferral++;
  2475. }
  2476. }
  2477. void
  2478. ThreadContext::PreDisposeObjectsCallBack()
  2479. {
  2480. this->expirableObjectDisposeList->Clear();
  2481. }
  2482. #ifdef FAULT_INJECTION
  2483. void
  2484. ThreadContext::DisposeScriptContextByFaultInjectionCallBack()
  2485. {
  2486. if (FAULTINJECT_SCRIPT_TERMINATION_ON_DISPOSE) {
  2487. int scriptContextToClose = -1;
  2488. /* inject only if we have more than 1 script context*/
  2489. uint totalScriptCount = GetScriptContextCount();
  2490. if (totalScriptCount > 1) {
  2491. if (Js::Configuration::Global.flags.FaultInjectionScriptContextToTerminateCount > 0)
  2492. {
  2493. scriptContextToClose = Js::Configuration::Global.flags.FaultInjectionScriptContextToTerminateCount % totalScriptCount;
  2494. for (Js::ScriptContext *scriptContext = GetScriptContextList(); scriptContext; scriptContext = scriptContext->next)
  2495. {
  2496. if (scriptContextToClose-- == 0)
  2497. {
  2498. scriptContext->DisposeScriptContextByFaultInjection();
  2499. break;
  2500. }
  2501. }
  2502. }
  2503. else
  2504. {
  2505. fwprintf(stderr, _u("***FI: FaultInjectionScriptContextToTerminateCount Failed, Value should be > 0. \n"));
  2506. }
  2507. }
  2508. }
  2509. }
  2510. #endif
  2511. #pragma region "Expirable Object Methods"
  2512. void
  2513. ThreadContext::TryExitExpirableCollectMode()
  2514. {
  2515. // If this feature is turned off or if we're already in profile collection mode, do nothing
  2516. // We also do nothing if expiration is explicitly disabled by someone lower down the stack
  2517. if (PHASE_OFF1(Js::ExpirableCollectPhase) || !InExpirableCollectMode() || this->disableExpiration)
  2518. {
  2519. return;
  2520. }
  2521. if (InExpirableCollectMode())
  2522. {
  2523. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Checking to see whether to complete Expirable Object Collection: GC Count is %d\n"), this->expirableCollectModeGcCount);
  2524. if (this->expirableCollectModeGcCount > 0)
  2525. {
  2526. this->expirableCollectModeGcCount--;
  2527. }
  2528. if (this->expirableCollectModeGcCount == 0 &&
  2529. (this->recycler->InCacheCleanupCollection() || CONFIG_FLAG(ForceExpireOnNonCacheCollect)))
  2530. {
  2531. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Completing Expirable Object Collection\n"));
  2532. ExpirableObjectList::Iterator expirableObjectIterator(this->expirableObjectList);
  2533. while (expirableObjectIterator.Next())
  2534. {
  2535. ExpirableObject* object = expirableObjectIterator.Data();
  2536. Assert(object);
  2537. if (!object->IsObjectUsed())
  2538. {
  2539. object->Expire();
  2540. }
  2541. }
  2542. // Leave expirable collection mode
  2543. expirableCollectModeGcCount = -1;
  2544. }
  2545. }
  2546. }
  2547. bool
  2548. ThreadContext::InExpirableCollectMode()
  2549. {
  2550. // We're in expirable collect if we have expirable objects registered,
  2551. // and expirableCollectModeGcCount is not negative
  2552. // and when debugger is attaching, it might have set the function to deferredParse.
  2553. return (expirableObjectList != nullptr &&
  2554. numExpirableObjects > 0 &&
  2555. expirableCollectModeGcCount >= 0
  2556. #ifdef ENABLE_SCRIPT_DEBUGGING
  2557. &&
  2558. (this->GetDebugManager() != nullptr &&
  2559. !this->GetDebugManager()->IsDebuggerAttaching())
  2560. #endif
  2561. );
  2562. }
  2563. void
  2564. ThreadContext::TryEnterExpirableCollectMode()
  2565. {
  2566. // If this feature is turned off or if we're already in profile collection mode, do nothing
  2567. if (PHASE_OFF1(Js::ExpirableCollectPhase) || InExpirableCollectMode())
  2568. {
  2569. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Not running Expirable Object Collection\n"));
  2570. return;
  2571. }
  2572. double entryPointCollectionThreshold = Js::Configuration::Global.flags.ExpirableCollectionTriggerThreshold / 100.0;
  2573. double currentThreadNativeCodeRatio = ((double) GetCodeSize()) / Js::Constants::MaxThreadJITCodeHeapSize;
  2574. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Current native code ratio: %f\n"), currentThreadNativeCodeRatio);
  2575. if (currentThreadNativeCodeRatio > entryPointCollectionThreshold)
  2576. {
  2577. OUTPUT_TRACE(Js::ExpirableCollectPhase, _u("Setting up Expirable Object Collection\n"));
  2578. this->expirableCollectModeGcCount = Js::Configuration::Global.flags.ExpirableCollectionGCCount;
  2579. ExpirableObjectList::Iterator expirableObjectIterator(this->expirableObjectList);
  2580. while (expirableObjectIterator.Next())
  2581. {
  2582. ExpirableObject* object = expirableObjectIterator.Data();
  2583. Assert(object);
  2584. object->EnterExpirableCollectMode();
  2585. }
  2586. }
  2587. }
  2588. void
  2589. ThreadContext::RegisterExpirableObject(ExpirableObject* object)
  2590. {
  2591. Assert(this->expirableObjectList);
  2592. Assert(object->GetRegistrationHandle() == nullptr);
  2593. ExpirableObject** registrationData = this->expirableObjectList->PrependNode();
  2594. (*registrationData) = object;
  2595. object->SetRegistrationHandle((void*) registrationData);
  2596. OUTPUT_VERBOSE_TRACE(Js::ExpirableCollectPhase, _u("Registered 0x%p\n"), object);
  2597. numExpirableObjects++;
  2598. }
  2599. void
  2600. ThreadContext::UnregisterExpirableObject(ExpirableObject* object)
  2601. {
  2602. Assert(this->expirableObjectList);
  2603. Assert(object->GetRegistrationHandle() != nullptr);
  2604. ExpirableObject** registrationData = (ExpirableObject**)PointerValue(object->GetRegistrationHandle());
  2605. Assert(*registrationData == object);
  2606. this->expirableObjectList->MoveElementTo(registrationData, this->expirableObjectDisposeList);
  2607. object->ClearRegistrationHandle();
  2608. OUTPUT_VERBOSE_TRACE(Js::ExpirableCollectPhase, _u("Unregistered 0x%p\n"), object);
  2609. numExpirableObjects--;
  2610. }
  2611. #pragma endregion
  2612. void
  2613. ThreadContext::ClearScriptContextCaches()
  2614. {
  2615. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext != nullptr; scriptContext = scriptContext->next)
  2616. {
  2617. scriptContext->ClearScriptContextCaches();
  2618. }
  2619. }
  2620. #ifdef PERSISTENT_INLINE_CACHES
  2621. void
  2622. ThreadContext::ClearInlineCachesWithDeadWeakRefs()
  2623. {
  2624. #if ENABLE_DEBUG_CONFIG_OPTIONS || defined(ENABLE_JS_ETW)
  2625. size_t allocatedSize = 0;
  2626. size_t preClearFreeListSize = 0;
  2627. size_t freeListSize = 0;
  2628. size_t polyInlineCacheSize = 0;
  2629. uint scriptContextCount = 0;
  2630. // Note: this event is not meaningful for MemGC, only Chakra
  2631. JS_ETW(EventWriteJSCRIPT_GC_CLEAR_INLINECACHE_START());
  2632. #endif
  2633. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext != nullptr; scriptContext = scriptContext->next)
  2634. {
  2635. #if ENABLE_DEBUG_CONFIG_OPTIONS || defined(ENABLE_JS_ETW)
  2636. scriptContextCount++;
  2637. allocatedSize += scriptContext->GetInlineCacheAllocator()->AllocatedSize();
  2638. preClearFreeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize();
  2639. #endif
  2640. scriptContext->ClearInlineCachesWithDeadWeakRefs();
  2641. #if ENABLE_DEBUG_CONFIG_OPTIONS || defined(ENABLE_JS_ETW)
  2642. freeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize();;
  2643. polyInlineCacheSize += scriptContext->GetInlineCacheAllocator()->GetPolyInlineCacheSize();
  2644. #endif
  2645. }
  2646. JS_ETW(EventWriteJSCRIPT_GC_CLEAR_INLINECACHE_STOP(this, scriptContextCount, (uint) allocatedSize, (uint) preClearFreeListSize, (uint) freeListSize, (uint) polyInlineCacheSize));
  2647. #if ENABLE_DEBUG_CONFIG_OPTIONS
  2648. if (PHASE_TRACE1(Js::InlineCachePhase))
  2649. {
  2650. Output::Print(_u("Inline cache arena: total = %5I64u KB, free list = %5I64u KB, poly caches = %5I64u KB, script contexts = %u\n"),
  2651. static_cast<uint64>(allocatedSize / 1024), static_cast<uint64>(freeListSize / 1024), static_cast<uint64>(polyInlineCacheSize / 1024), scriptContextCount);
  2652. }
  2653. #endif
  2654. }
  2655. #if ENABLE_NATIVE_CODEGEN
  2656. void
  2657. ThreadContext::ClearInvalidatedUniqueGuards()
  2658. {
  2659. // If a propertyGuard was invalidated, make sure to remove it's entry from unique property guard table of other property records.
  2660. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  2661. guards.Map([this](Js::PropertyRecord const * propertyRecord, PropertyGuardEntry* entry, const RecyclerWeakReference<const Js::PropertyRecord>* weakRef)
  2662. {
  2663. entry->uniqueGuards.MapAndRemoveIf([=](RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef)
  2664. {
  2665. Js::PropertyGuard* guard = guardWeakRef->Get();
  2666. bool shouldRemove = guard != nullptr && !guard->IsValid();
  2667. if (shouldRemove)
  2668. {
  2669. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  2670. {
  2671. Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"),
  2672. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue());
  2673. Output::Flush();
  2674. }
  2675. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  2676. {
  2677. Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"),
  2678. propertyRecord->GetBuffer(), guard->GetValue());
  2679. Output::Flush();
  2680. }
  2681. }
  2682. return shouldRemove;
  2683. });
  2684. });
  2685. }
  2686. #endif
  2687. void
  2688. ThreadContext::ClearInlineCaches()
  2689. {
  2690. if (PHASE_TRACE1(Js::InlineCachePhase))
  2691. {
  2692. size_t size = 0;
  2693. size_t freeListSize = 0;
  2694. size_t polyInlineCacheSize = 0;
  2695. uint scriptContextCount = 0;
  2696. for (Js::ScriptContext *scriptContext = scriptContextList;
  2697. scriptContext;
  2698. scriptContext = scriptContext->next)
  2699. {
  2700. scriptContextCount++;
  2701. size += scriptContext->GetInlineCacheAllocator()->AllocatedSize();
  2702. freeListSize += scriptContext->GetInlineCacheAllocator()->FreeListSize();
  2703. #ifdef POLY_INLINE_CACHE_SIZE_STATS
  2704. polyInlineCacheSize += scriptContext->GetInlineCacheAllocator()->GetPolyInlineCacheSize();
  2705. #endif
  2706. };
  2707. Output::Print(_u("Inline cache arena: total = %5I64u KB, free list = %5I64u KB, poly caches = %5I64u KB, script contexts = %u\n"),
  2708. static_cast<uint64>(size / 1024), static_cast<uint64>(freeListSize / 1024), static_cast<uint64>(polyInlineCacheSize / 1024), scriptContextCount);
  2709. }
  2710. Js::ScriptContext *scriptContext = this->scriptContextList;
  2711. while (scriptContext != nullptr)
  2712. {
  2713. scriptContext->ClearInlineCaches();
  2714. scriptContext = scriptContext->next;
  2715. }
  2716. inlineCacheThreadInfoAllocator.Reset();
  2717. protoInlineCacheByPropId.ResetNoDelete();
  2718. storeFieldInlineCacheByPropId.ResetNoDelete();
  2719. registeredInlineCacheCount = 0;
  2720. unregisteredInlineCacheCount = 0;
  2721. }
  2722. #endif //PERSISTENT_INLINE_CACHES
  2723. void
  2724. ThreadContext::ClearIsInstInlineCaches()
  2725. {
  2726. Js::ScriptContext *scriptContext = this->scriptContextList;
  2727. while (scriptContext != nullptr)
  2728. {
  2729. scriptContext->ClearIsInstInlineCaches();
  2730. scriptContext = scriptContext->next;
  2731. }
  2732. isInstInlineCacheThreadInfoAllocator.Reset();
  2733. isInstInlineCacheByFunction.ResetNoDelete();
  2734. }
  2735. void
  2736. ThreadContext::ClearEnumeratorCaches()
  2737. {
  2738. Js::ScriptContext *scriptContext = this->scriptContextList;
  2739. while (scriptContext != nullptr)
  2740. {
  2741. scriptContext->ClearEnumeratorCaches();
  2742. scriptContext = scriptContext->next;
  2743. }
  2744. }
  2745. void
  2746. ThreadContext::ClearEquivalentTypeCaches()
  2747. {
  2748. #if ENABLE_NATIVE_CODEGEN
  2749. // Called from PreSweepCallback to clear pointers to types that have no live object references left.
  2750. // The EquivalentTypeCache used to keep these types alive, but this caused memory growth in cases where
  2751. // entry points stayed around for a long time.
  2752. // In future we may want to pin the reference/guard type to the entry point, but that choice will depend
  2753. // on a use case where pinning the type helps us optimize. Lacking that, clearing the guard type is a
  2754. // simpler short-term solution.
  2755. // Note that clearing unmarked types from the cache and guard is needed for correctness if the cache doesn't keep
  2756. // the types alive.
  2757. FOREACH_DLISTBASE_ENTRY_EDITING(Js::EntryPointInfo *, entryPoint, &equivalentTypeCacheEntryPoints, iter)
  2758. {
  2759. bool isLive = entryPoint->ClearEquivalentTypeCaches();
  2760. if (!isLive)
  2761. {
  2762. iter.RemoveCurrent(&equivalentTypeCacheInfoAllocator);
  2763. }
  2764. }
  2765. NEXT_DLISTBASE_ENTRY_EDITING;
  2766. // Note: Don't reset the list, because we're only clearing the dead types from these caches.
  2767. // There may still be type references we need to keep an eye on.
  2768. #endif
  2769. }
  2770. Js::EntryPointInfo **
  2771. ThreadContext::RegisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo * entryPoint)
  2772. {
  2773. return equivalentTypeCacheEntryPoints.PrependNode(&equivalentTypeCacheInfoAllocator, entryPoint);
  2774. }
  2775. void
  2776. ThreadContext::UnregisterEquivalentTypeCacheEntryPoint(Js::EntryPointInfo ** entryPoint)
  2777. {
  2778. equivalentTypeCacheEntryPoints.RemoveElement(&equivalentTypeCacheInfoAllocator, entryPoint);
  2779. }
  2780. void
  2781. ThreadContext::RegisterProtoInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId)
  2782. {
  2783. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2784. {
  2785. Output::Print(_u("InlineCacheInvalidation: registering proto cache 0x%p for property %s(%u)\n"),
  2786. inlineCache, GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2787. Output::Flush();
  2788. }
  2789. RegisterInlineCache(protoInlineCacheByPropId, inlineCache, propertyId);
  2790. }
  2791. void
  2792. ThreadContext::RegisterStoreFieldInlineCache(Js::InlineCache * inlineCache, Js::PropertyId propertyId)
  2793. {
  2794. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2795. {
  2796. Output::Print(_u("InlineCacheInvalidation: registering store field cache 0x%p for property %s(%u)\n"),
  2797. inlineCache, GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2798. Output::Flush();
  2799. }
  2800. RegisterInlineCache(storeFieldInlineCacheByPropId, inlineCache, propertyId);
  2801. }
  2802. void
  2803. ThreadContext::RegisterInlineCache(InlineCacheListMapByPropertyId& inlineCacheMap, Js::InlineCache * inlineCache, Js::PropertyId propertyId)
  2804. {
  2805. InlineCacheList* inlineCacheList;
  2806. if (!inlineCacheMap.TryGetValue(propertyId, &inlineCacheList))
  2807. {
  2808. inlineCacheList = Anew(&this->inlineCacheThreadInfoAllocator, InlineCacheList, &this->inlineCacheThreadInfoAllocator);
  2809. inlineCacheMap.AddNew(propertyId, inlineCacheList);
  2810. }
  2811. Js::InlineCache** inlineCacheRef = inlineCacheList->PrependNode();
  2812. Assert(inlineCacheRef != nullptr);
  2813. *inlineCacheRef = inlineCache;
  2814. inlineCache->invalidationListSlotPtr = inlineCacheRef;
  2815. this->registeredInlineCacheCount++;
  2816. }
  2817. void ThreadContext::NotifyInlineCacheBatchUnregistered(uint count)
  2818. {
  2819. this->unregisteredInlineCacheCount += count;
  2820. // Negative or 0 InlineCacheInvalidationListCompactionThreshold forces compaction all the time.
  2821. if (CONFIG_FLAG(InlineCacheInvalidationListCompactionThreshold) <= 0 ||
  2822. this->registeredInlineCacheCount / this->unregisteredInlineCacheCount < (uint)CONFIG_FLAG(InlineCacheInvalidationListCompactionThreshold))
  2823. {
  2824. CompactInlineCacheInvalidationLists();
  2825. }
  2826. }
  2827. void
  2828. ThreadContext::InvalidateProtoInlineCaches(Js::PropertyId propertyId)
  2829. {
  2830. InlineCacheList* inlineCacheList;
  2831. if (protoInlineCacheByPropId.TryGetValueAndRemove(propertyId, &inlineCacheList))
  2832. {
  2833. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2834. {
  2835. Output::Print(_u("InlineCacheInvalidation: invalidating proto caches for property %s(%u)\n"),
  2836. GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2837. Output::Flush();
  2838. }
  2839. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  2840. }
  2841. }
  2842. void
  2843. ThreadContext::InvalidateStoreFieldInlineCaches(Js::PropertyId propertyId)
  2844. {
  2845. InlineCacheList* inlineCacheList;
  2846. if (storeFieldInlineCacheByPropId.TryGetValueAndRemove(propertyId, &inlineCacheList))
  2847. {
  2848. if (PHASE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2849. {
  2850. Output::Print(_u("InlineCacheInvalidation: invalidating store field caches for property %s(%u)\n"),
  2851. GetPropertyName(propertyId)->GetBuffer(), propertyId);
  2852. Output::Flush();
  2853. }
  2854. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  2855. }
  2856. }
  2857. void
  2858. ThreadContext::InvalidateAndDeleteInlineCacheList(InlineCacheList* inlineCacheList)
  2859. {
  2860. Assert(inlineCacheList != nullptr);
  2861. uint cacheCount = 0;
  2862. uint nullCacheCount = 0;
  2863. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList)
  2864. {
  2865. cacheCount++;
  2866. if (inlineCache != nullptr)
  2867. {
  2868. if (PHASE_VERBOSE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  2869. {
  2870. Output::Print(_u("InlineCacheInvalidation: invalidating cache 0x%p\n"), inlineCache);
  2871. Output::Flush();
  2872. }
  2873. memset(inlineCache, 0, sizeof(Js::InlineCache));
  2874. }
  2875. else
  2876. {
  2877. nullCacheCount++;
  2878. }
  2879. }
  2880. NEXT_SLISTBASE_ENTRY;
  2881. Adelete(&this->inlineCacheThreadInfoAllocator, inlineCacheList);
  2882. this->registeredInlineCacheCount = this->registeredInlineCacheCount > cacheCount ? this->registeredInlineCacheCount - cacheCount : 0;
  2883. this->unregisteredInlineCacheCount = this->unregisteredInlineCacheCount > nullCacheCount ? this->unregisteredInlineCacheCount - nullCacheCount : 0;
  2884. }
  2885. void
  2886. ThreadContext::CompactInlineCacheInvalidationLists()
  2887. {
  2888. #if DBG
  2889. uint countOfNodesToCompact = this->unregisteredInlineCacheCount;
  2890. this->totalUnregisteredCacheCount = 0;
  2891. #endif
  2892. Assert(this->unregisteredInlineCacheCount > 0);
  2893. CompactProtoInlineCaches();
  2894. if (this->unregisteredInlineCacheCount > 0)
  2895. {
  2896. CompactStoreFieldInlineCaches();
  2897. }
  2898. Assert(countOfNodesToCompact == this->totalUnregisteredCacheCount);
  2899. }
  2900. void
  2901. ThreadContext::CompactProtoInlineCaches()
  2902. {
  2903. protoInlineCacheByPropId.MapUntil([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  2904. {
  2905. CompactInlineCacheList(inlineCacheList);
  2906. return this->unregisteredInlineCacheCount == 0;
  2907. });
  2908. }
  2909. void
  2910. ThreadContext::CompactStoreFieldInlineCaches()
  2911. {
  2912. storeFieldInlineCacheByPropId.MapUntil([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  2913. {
  2914. CompactInlineCacheList(inlineCacheList);
  2915. return this->unregisteredInlineCacheCount == 0;
  2916. });
  2917. }
  2918. void
  2919. ThreadContext::CompactInlineCacheList(InlineCacheList* inlineCacheList)
  2920. {
  2921. Assert(inlineCacheList != nullptr);
  2922. uint cacheCount = 0;
  2923. FOREACH_SLISTBASE_ENTRY_EDITING(Js::InlineCache*, inlineCache, inlineCacheList, iterator)
  2924. {
  2925. if (inlineCache == nullptr)
  2926. {
  2927. iterator.RemoveCurrent();
  2928. cacheCount++;
  2929. }
  2930. }
  2931. NEXT_SLISTBASE_ENTRY_EDITING;
  2932. #if DBG
  2933. this->totalUnregisteredCacheCount += cacheCount;
  2934. #endif
  2935. if (cacheCount > 0)
  2936. {
  2937. AssertMsg(this->unregisteredInlineCacheCount >= cacheCount, "Some codepaths didn't unregistered the inlineCaches which might leak memory.");
  2938. this->unregisteredInlineCacheCount = this->unregisteredInlineCacheCount > cacheCount ?
  2939. this->unregisteredInlineCacheCount - cacheCount : 0;
  2940. AssertMsg(this->registeredInlineCacheCount >= cacheCount, "Some codepaths didn't registered the inlineCaches which might leak memory.");
  2941. this->registeredInlineCacheCount = this->registeredInlineCacheCount > cacheCount ?
  2942. this->registeredInlineCacheCount - cacheCount : 0;
  2943. }
  2944. }
  2945. #if DBG
  2946. bool
  2947. ThreadContext::IsProtoInlineCacheRegistered(const Js::InlineCache* inlineCache, Js::PropertyId propertyId)
  2948. {
  2949. return IsInlineCacheRegistered(protoInlineCacheByPropId, inlineCache, propertyId);
  2950. }
  2951. bool
  2952. ThreadContext::IsStoreFieldInlineCacheRegistered(const Js::InlineCache* inlineCache, Js::PropertyId propertyId)
  2953. {
  2954. return IsInlineCacheRegistered(storeFieldInlineCacheByPropId, inlineCache, propertyId);
  2955. }
  2956. bool
  2957. ThreadContext::IsInlineCacheRegistered(InlineCacheListMapByPropertyId& inlineCacheMap, const Js::InlineCache* inlineCache, Js::PropertyId propertyId)
  2958. {
  2959. InlineCacheList* inlineCacheList;
  2960. if (inlineCacheMap.TryGetValue(propertyId, &inlineCacheList))
  2961. {
  2962. return IsInlineCacheInList(inlineCache, inlineCacheList);
  2963. }
  2964. else
  2965. {
  2966. return false;
  2967. }
  2968. }
  2969. bool
  2970. ThreadContext::IsInlineCacheInList(const Js::InlineCache* inlineCache, const InlineCacheList* inlineCacheList)
  2971. {
  2972. Assert(inlineCache != nullptr);
  2973. Assert(inlineCacheList != nullptr);
  2974. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, curInlineCache, inlineCacheList)
  2975. {
  2976. if (curInlineCache == inlineCache)
  2977. {
  2978. return true;
  2979. }
  2980. }
  2981. NEXT_SLISTBASE_ENTRY;
  2982. return false;
  2983. }
  2984. #endif
  2985. #if ENABLE_NATIVE_CODEGEN
  2986. ThreadContext::PropertyGuardEntry*
  2987. ThreadContext::EnsurePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, bool& foundExistingEntry)
  2988. {
  2989. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  2990. PropertyGuardEntry* entry = nullptr;
  2991. foundExistingEntry = guards.TryGetValue(propertyRecord, &entry);
  2992. if (!foundExistingEntry)
  2993. {
  2994. entry = RecyclerNew(GetRecycler(), PropertyGuardEntry, GetRecycler());
  2995. guards.UncheckedAdd(CreatePropertyRecordWeakRef(propertyRecord), entry);
  2996. }
  2997. return entry;
  2998. }
  2999. Js::PropertyGuard*
  3000. ThreadContext::RegisterSharedPropertyGuard(Js::PropertyId propertyId)
  3001. {
  3002. Assert(IsActivePropertyId(propertyId));
  3003. const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId);
  3004. bool foundExistingGuard;
  3005. PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard);
  3006. if (entry->sharedGuard == nullptr)
  3007. {
  3008. entry->sharedGuard = Js::PropertyGuard::New(GetRecycler());
  3009. }
  3010. Js::PropertyGuard* guard = entry->sharedGuard;
  3011. PHASE_PRINT_VERBOSE_TRACE1(Js::FixedMethodsPhase, _u("FixedFields: registered shared guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p, %s\n"),
  3012. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue(), foundExistingGuard ? _u("existing") : _u("new"));
  3013. PHASE_PRINT_TESTTRACE1(Js::FixedMethodsPhase, _u("FixedFields: registered shared guard: name: %s, value: 0x%p, %s\n"),
  3014. propertyRecord->GetBuffer(), guard->GetValue(), foundExistingGuard ? _u("existing") : _u("new"));
  3015. return guard;
  3016. }
  3017. void
  3018. ThreadContext::RegisterLazyBailout(Js::PropertyId propertyId, Js::EntryPointInfo* entryPoint)
  3019. {
  3020. const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId);
  3021. bool foundExistingGuard;
  3022. PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard);
  3023. if (!entry->entryPoints)
  3024. {
  3025. entry->entryPoints = RecyclerNew(recycler, PropertyGuardEntry::EntryPointDictionary, recycler, /*capacity*/ 3);
  3026. }
  3027. entry->entryPoints->UncheckedAdd(entryPoint, NULL);
  3028. }
  3029. void
  3030. ThreadContext::RegisterUniquePropertyGuard(Js::PropertyId propertyId, Js::PropertyGuard* guard)
  3031. {
  3032. Assert(IsActivePropertyId(propertyId));
  3033. Assert(guard != nullptr);
  3034. RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef = this->recycler->CreateWeakReferenceHandle(guard);
  3035. RegisterUniquePropertyGuard(propertyId, guardWeakRef);
  3036. }
  3037. void
  3038. ThreadContext::RegisterUniquePropertyGuard(Js::PropertyId propertyId, RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef)
  3039. {
  3040. Assert(IsActivePropertyId(propertyId));
  3041. Assert(guardWeakRef != nullptr);
  3042. Js::PropertyGuard* guard = guardWeakRef->Get();
  3043. Assert(guard != nullptr);
  3044. const Js::PropertyRecord * propertyRecord = GetPropertyName(propertyId);
  3045. bool foundExistingGuard;
  3046. PropertyGuardEntry* entry = EnsurePropertyGuardEntry(propertyRecord, foundExistingGuard);
  3047. entry->uniqueGuards.Item(guardWeakRef);
  3048. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  3049. {
  3050. Output::Print(_u("FixedFields: registered unique guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p, %s entry\n"),
  3051. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue(), foundExistingGuard ? _u("existing") : _u("new"));
  3052. Output::Flush();
  3053. }
  3054. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  3055. {
  3056. Output::Print(_u("FixedFields: registered unique guard: name: %s, value: 0x%p, %s entry\n"),
  3057. propertyRecord->GetBuffer(), guard->GetValue(), foundExistingGuard ? _u("existing") : _u("new"));
  3058. Output::Flush();
  3059. }
  3060. }
  3061. void
  3062. ThreadContext::RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache)
  3063. {
  3064. Assert(Js::ConstructorCache::GetOffsetOfGuardValue() == Js::PropertyGuard::GetOffsetOfValue());
  3065. Assert(Js::ConstructorCache::GetSizeOfGuardValue() == Js::PropertyGuard::GetSizeOfValue());
  3066. RegisterUniquePropertyGuard(propertyId, reinterpret_cast<Js::PropertyGuard*>(cache));
  3067. }
  3068. void
  3069. ThreadContext::InvalidatePropertyGuardEntry(const Js::PropertyRecord* propertyRecord, PropertyGuardEntry* entry, bool isAllPropertyGuardsInvalidation)
  3070. {
  3071. Assert(entry != nullptr);
  3072. if (entry->sharedGuard != nullptr)
  3073. {
  3074. Js::PropertyGuard* guard = entry->sharedGuard;
  3075. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  3076. {
  3077. Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"),
  3078. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue());
  3079. Output::Flush();
  3080. }
  3081. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  3082. {
  3083. Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"), propertyRecord->GetBuffer(), guard->GetValue());
  3084. Output::Flush();
  3085. }
  3086. guard->Invalidate();
  3087. }
  3088. uint count = 0;
  3089. entry->uniqueGuards.Map([&count, propertyRecord](RecyclerWeakReference<Js::PropertyGuard>* guardWeakRef)
  3090. {
  3091. Js::PropertyGuard* guard = guardWeakRef->Get();
  3092. if (guard != nullptr)
  3093. {
  3094. if (PHASE_TRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TRACE1(Js::FixedMethodsPhase))
  3095. {
  3096. Output::Print(_u("FixedFields: invalidating guard: name: %s, address: 0x%p, value: 0x%p, value address: 0x%p\n"),
  3097. propertyRecord->GetBuffer(), guard, guard->GetValue(), guard->GetAddressOfValue());
  3098. Output::Flush();
  3099. }
  3100. if (PHASE_TESTTRACE1(Js::TracePropertyGuardsPhase) || PHASE_VERBOSE_TESTTRACE1(Js::FixedMethodsPhase))
  3101. {
  3102. Output::Print(_u("FixedFields: invalidating guard: name: %s, value: 0x%p\n"),
  3103. propertyRecord->GetBuffer(), guard->GetValue());
  3104. Output::Flush();
  3105. }
  3106. guard->Invalidate();
  3107. count++;
  3108. }
  3109. });
  3110. entry->uniqueGuards.Clear();
  3111. // Count no. of invalidations done so far. Exclude if this is all property guards invalidation in which case
  3112. // the unique Guards will be cleared anyway.
  3113. if (!isAllPropertyGuardsInvalidation)
  3114. {
  3115. this->recyclableData->constructorCacheInvalidationCount += count;
  3116. if (this->recyclableData->constructorCacheInvalidationCount > (uint)CONFIG_FLAG(ConstructorCacheInvalidationThreshold))
  3117. {
  3118. // TODO: In future, we should compact the uniqueGuards dictionary so this function can be called from PreCollectionCallback
  3119. // instead
  3120. this->ClearInvalidatedUniqueGuards();
  3121. this->recyclableData->constructorCacheInvalidationCount = 0;
  3122. }
  3123. }
  3124. if (entry->entryPoints && entry->entryPoints->Count() > 0)
  3125. {
  3126. Js::JavascriptStackWalker stackWalker(this->GetScriptContextList());
  3127. Js::JavascriptFunction* caller = nullptr;
  3128. while (stackWalker.GetCaller(&caller, /*includeInlineFrames*/ false))
  3129. {
  3130. // If the current frame is already from a bailout - we do not need to do on stack invalidation
  3131. if (caller != nullptr && Js::ScriptFunction::Test(caller) && !stackWalker.GetCurrentFrameFromBailout())
  3132. {
  3133. BYTE dummy;
  3134. Js::FunctionEntryPointInfo* functionEntryPoint = caller->GetFunctionBody()->GetDefaultFunctionEntryPointInfo();
  3135. if (functionEntryPoint->IsInNativeAddressRange((DWORD_PTR)stackWalker.GetInstructionPointer()))
  3136. {
  3137. if (entry->entryPoints->TryGetValue(functionEntryPoint, &dummy))
  3138. {
  3139. functionEntryPoint->DoLazyBailout(stackWalker.GetCurrentAddressOfInstructionPointer(),
  3140. caller->GetFunctionBody(), propertyRecord);
  3141. }
  3142. }
  3143. }
  3144. }
  3145. entry->entryPoints->Map([=](Js::EntryPointInfo* info, BYTE& dummy, const RecyclerWeakReference<Js::EntryPointInfo>* infoWeakRef)
  3146. {
  3147. OUTPUT_TRACE2(Js::LazyBailoutPhase, info->GetFunctionBody(), _u("Lazy bailout - Invalidation due to property: %s \n"), propertyRecord->GetBuffer());
  3148. info->Invalidate(true);
  3149. });
  3150. entry->entryPoints->Clear();
  3151. }
  3152. }
  3153. void
  3154. ThreadContext::InvalidatePropertyGuards(Js::PropertyId propertyId)
  3155. {
  3156. const Js::PropertyRecord* propertyRecord = GetPropertyName(propertyId);
  3157. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  3158. PropertyGuardEntry* entry = nullptr;
  3159. if (guards.TryGetValueAndRemove(propertyRecord, &entry))
  3160. {
  3161. InvalidatePropertyGuardEntry(propertyRecord, entry, false);
  3162. }
  3163. }
  3164. void
  3165. ThreadContext::InvalidateAllPropertyGuards()
  3166. {
  3167. PropertyGuardDictionary &guards = this->recyclableData->propertyGuards;
  3168. if (guards.Count() > 0)
  3169. {
  3170. guards.Map([this](Js::PropertyRecord const * propertyRecord, PropertyGuardEntry* entry, const RecyclerWeakReference<const Js::PropertyRecord>* weakRef)
  3171. {
  3172. InvalidatePropertyGuardEntry(propertyRecord, entry, true);
  3173. });
  3174. guards.Clear();
  3175. }
  3176. }
  3177. #endif
  3178. void
  3179. ThreadContext::InvalidateAllProtoInlineCaches()
  3180. {
  3181. protoInlineCacheByPropId.Map([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3182. {
  3183. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  3184. });
  3185. protoInlineCacheByPropId.Reset();
  3186. }
  3187. #if DBG
  3188. // Verifies if object is registered in any proto InlineCache
  3189. bool
  3190. ThreadContext::IsObjectRegisteredInProtoInlineCaches(Js::DynamicObject * object)
  3191. {
  3192. return protoInlineCacheByPropId.MapUntil([object](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3193. {
  3194. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList)
  3195. {
  3196. if (inlineCache != nullptr && !inlineCache->IsEmpty())
  3197. {
  3198. // Verify this object is not present in prototype chain of inlineCache's type
  3199. bool isObjectPresentOnPrototypeChain =
  3200. Js::JavascriptOperators::MapObjectAndPrototypesUntil<true>(inlineCache->GetType()->GetPrototype(), [=](Js::RecyclableObject* prototype)
  3201. {
  3202. return prototype == object;
  3203. });
  3204. if (isObjectPresentOnPrototypeChain) {
  3205. return true;
  3206. }
  3207. }
  3208. }
  3209. NEXT_SLISTBASE_ENTRY;
  3210. return false;
  3211. });
  3212. }
  3213. // Verifies if object is registered in any storeField InlineCache
  3214. bool
  3215. ThreadContext::IsObjectRegisteredInStoreFieldInlineCaches(Js::DynamicObject * object)
  3216. {
  3217. return storeFieldInlineCacheByPropId.MapUntil([object](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3218. {
  3219. FOREACH_SLISTBASE_ENTRY(Js::InlineCache*, inlineCache, inlineCacheList)
  3220. {
  3221. if (inlineCache != nullptr && !inlineCache->IsEmpty())
  3222. {
  3223. // Verify this object is not present in prototype chain of inlineCache's type
  3224. bool isObjectPresentOnPrototypeChain =
  3225. Js::JavascriptOperators::MapObjectAndPrototypesUntil<true>(inlineCache->GetType()->GetPrototype(), [=](Js::RecyclableObject* prototype)
  3226. {
  3227. return prototype == object;
  3228. });
  3229. if (isObjectPresentOnPrototypeChain) {
  3230. return true;
  3231. }
  3232. }
  3233. }
  3234. NEXT_SLISTBASE_ENTRY;
  3235. return false;
  3236. });
  3237. }
  3238. #endif
  3239. bool
  3240. ThreadContext::AreAllProtoInlineCachesInvalidated()
  3241. {
  3242. return protoInlineCacheByPropId.Count() == 0;
  3243. }
  3244. void
  3245. ThreadContext::InvalidateAllStoreFieldInlineCaches()
  3246. {
  3247. storeFieldInlineCacheByPropId.Map([this](Js::PropertyId propertyId, InlineCacheList* inlineCacheList)
  3248. {
  3249. InvalidateAndDeleteInlineCacheList(inlineCacheList);
  3250. });
  3251. storeFieldInlineCacheByPropId.Reset();
  3252. }
  3253. bool
  3254. ThreadContext::AreAllStoreFieldInlineCachesInvalidated()
  3255. {
  3256. return storeFieldInlineCacheByPropId.Count() == 0;
  3257. }
  3258. #if DBG
  3259. bool
  3260. ThreadContext::IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * inlineCache, Js::Var function)
  3261. {
  3262. Assert(inlineCache != nullptr);
  3263. Assert(function != nullptr);
  3264. Js::IsInstInlineCache* firstInlineCache;
  3265. if (this->isInstInlineCacheByFunction.TryGetValue(function, &firstInlineCache))
  3266. {
  3267. return IsIsInstInlineCacheInList(inlineCache, firstInlineCache);
  3268. }
  3269. else
  3270. {
  3271. return false;
  3272. }
  3273. }
  3274. #endif
  3275. void
  3276. ThreadContext::RegisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function)
  3277. {
  3278. Assert(function != nullptr);
  3279. Assert(inlineCache != nullptr);
  3280. // We should never cross-register or re-register a cache that is already on some invalidation list (for its function or some other function).
  3281. // Every cache must be first cleared and unregistered before being registered again.
  3282. AssertMsg(inlineCache->function == nullptr, "We should only register instance-of caches that have not yet been populated.");
  3283. Js::IsInstInlineCache** inlineCacheRef = nullptr;
  3284. if (this->isInstInlineCacheByFunction.TryGetReference(function, &inlineCacheRef))
  3285. {
  3286. AssertMsg(!IsIsInstInlineCacheInList(inlineCache, *inlineCacheRef), "Why are we registering a cache that is already registered?");
  3287. inlineCache->next = *inlineCacheRef;
  3288. *inlineCacheRef = inlineCache;
  3289. }
  3290. else
  3291. {
  3292. inlineCache->next = nullptr;
  3293. this->isInstInlineCacheByFunction.Add(function, inlineCache);
  3294. }
  3295. }
  3296. void
  3297. ThreadContext::UnregisterIsInstInlineCache(Js::IsInstInlineCache * inlineCache, Js::Var function)
  3298. {
  3299. Assert(inlineCache != nullptr);
  3300. Js::IsInstInlineCache** inlineCacheRef = nullptr;
  3301. if (this->isInstInlineCacheByFunction.TryGetReference(function, &inlineCacheRef))
  3302. {
  3303. Assert(*inlineCacheRef != nullptr);
  3304. if (inlineCache == *inlineCacheRef)
  3305. {
  3306. *inlineCacheRef = (*inlineCacheRef)->next;
  3307. if (*inlineCacheRef == nullptr)
  3308. {
  3309. this->isInstInlineCacheByFunction.Remove(function);
  3310. }
  3311. }
  3312. else
  3313. {
  3314. Js::IsInstInlineCache * prevInlineCache;
  3315. Js::IsInstInlineCache * curInlineCache;
  3316. for (prevInlineCache = *inlineCacheRef, curInlineCache = (*inlineCacheRef)->next; curInlineCache != nullptr;
  3317. prevInlineCache = curInlineCache, curInlineCache = curInlineCache->next)
  3318. {
  3319. if (curInlineCache == inlineCache)
  3320. {
  3321. prevInlineCache->next = curInlineCache->next;
  3322. return;
  3323. }
  3324. }
  3325. AssertMsg(false, "Why are we unregistering a cache that is not registered?");
  3326. }
  3327. }
  3328. }
  3329. void
  3330. ThreadContext::InvalidateIsInstInlineCacheList(Js::IsInstInlineCache* inlineCacheList)
  3331. {
  3332. Assert(inlineCacheList != nullptr);
  3333. Js::IsInstInlineCache* curInlineCache;
  3334. Js::IsInstInlineCache* nextInlineCache;
  3335. for (curInlineCache = inlineCacheList; curInlineCache != nullptr; curInlineCache = nextInlineCache)
  3336. {
  3337. if (PHASE_VERBOSE_TRACE1(Js::TraceInlineCacheInvalidationPhase))
  3338. {
  3339. Output::Print(_u("InlineCacheInvalidation: invalidating instanceof cache 0x%p\n"), curInlineCache);
  3340. Output::Flush();
  3341. }
  3342. // Stash away the next cache before we zero out the current one (including its next pointer).
  3343. nextInlineCache = curInlineCache->next;
  3344. // Clear the current cache to invalidate it.
  3345. memset(curInlineCache, 0, sizeof(Js::IsInstInlineCache));
  3346. }
  3347. }
  3348. void
  3349. ThreadContext::InvalidateIsInstInlineCachesForFunction(Js::Var function)
  3350. {
  3351. Js::IsInstInlineCache* inlineCacheList;
  3352. if (this->isInstInlineCacheByFunction.TryGetValueAndRemove(function, &inlineCacheList))
  3353. {
  3354. InvalidateIsInstInlineCacheList(inlineCacheList);
  3355. }
  3356. }
  3357. void
  3358. ThreadContext::InvalidateAllIsInstInlineCaches()
  3359. {
  3360. isInstInlineCacheByFunction.Map([this](const Js::Var function, Js::IsInstInlineCache* inlineCacheList)
  3361. {
  3362. InvalidateIsInstInlineCacheList(inlineCacheList);
  3363. });
  3364. isInstInlineCacheByFunction.Clear();
  3365. }
  3366. bool
  3367. ThreadContext::AreAllIsInstInlineCachesInvalidated() const
  3368. {
  3369. return isInstInlineCacheByFunction.Count() == 0;
  3370. }
  3371. #if DBG
  3372. bool
  3373. ThreadContext::IsIsInstInlineCacheInList(const Js::IsInstInlineCache* inlineCache, const Js::IsInstInlineCache* inlineCacheList)
  3374. {
  3375. Assert(inlineCache != nullptr);
  3376. Assert(inlineCacheList != nullptr);
  3377. for (const Js::IsInstInlineCache* curInlineCache = inlineCacheList; curInlineCache != nullptr; curInlineCache = curInlineCache->next)
  3378. {
  3379. if (curInlineCache == inlineCache)
  3380. {
  3381. return true;
  3382. }
  3383. }
  3384. return false;
  3385. }
  3386. #endif
  3387. void ThreadContext::RegisterTypeWithProtoPropertyCache(const Js::PropertyId propertyId, Js::Type *const type)
  3388. {
  3389. Assert(propertyId != Js::Constants::NoProperty);
  3390. Assert(IsActivePropertyId(propertyId));
  3391. Assert(type);
  3392. PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache;
  3393. TypeHashSet *typeHashSet = nullptr;
  3394. if(!typesWithProtoPropertyCache.TryGetValue(propertyId, &typeHashSet))
  3395. {
  3396. typeHashSet = RecyclerNew(recycler, TypeHashSet, recycler);
  3397. typesWithProtoPropertyCache.Add(propertyId, typeHashSet);
  3398. }
  3399. typeHashSet->Item(type, false);
  3400. }
  3401. void ThreadContext::InvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId)
  3402. {
  3403. Assert(propertyId != Js::Constants::NoProperty);
  3404. Assert(IsActivePropertyId(propertyId));
  3405. InternalInvalidateProtoTypePropertyCaches(propertyId);
  3406. }
  3407. void ThreadContext::InternalInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId)
  3408. {
  3409. // Get the hash set of registered types associated with the property ID, invalidate each type in the hash set, and
  3410. // remove the property ID and its hash set from the map
  3411. PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache;
  3412. TypeHashSet *typeHashSet = nullptr;
  3413. if(typesWithProtoPropertyCache.Count() != 0 && typesWithProtoPropertyCache.TryGetValueAndRemove(propertyId, &typeHashSet))
  3414. {
  3415. DoInvalidateProtoTypePropertyCaches(propertyId, typeHashSet);
  3416. }
  3417. }
  3418. void ThreadContext::InvalidateAllProtoTypePropertyCaches()
  3419. {
  3420. PropertyIdToTypeHashSetDictionary &typesWithProtoPropertyCache = recyclableData->typesWithProtoPropertyCache;
  3421. if (typesWithProtoPropertyCache.Count() > 0)
  3422. {
  3423. typesWithProtoPropertyCache.Map([this](Js::PropertyId propertyId, TypeHashSet * typeHashSet)
  3424. {
  3425. DoInvalidateProtoTypePropertyCaches(propertyId, typeHashSet);
  3426. });
  3427. typesWithProtoPropertyCache.Clear();
  3428. }
  3429. }
  3430. void ThreadContext::DoInvalidateProtoTypePropertyCaches(const Js::PropertyId propertyId, TypeHashSet *const typeHashSet)
  3431. {
  3432. Assert(propertyId != Js::Constants::NoProperty);
  3433. Assert(typeHashSet);
  3434. typeHashSet->Map(
  3435. [propertyId](Js::Type *const type, const bool unused, const RecyclerWeakReference<Js::Type>*)
  3436. {
  3437. type->GetPropertyCache()->ClearIfPropertyIsOnAPrototype(propertyId);
  3438. });
  3439. }
  3440. BOOL ThreadContext::HasPreviousHostScriptContext()
  3441. {
  3442. return hostScriptContextStack->Count() != 0;
  3443. }
  3444. HostScriptContext* ThreadContext::GetPreviousHostScriptContext()
  3445. {
  3446. return hostScriptContextStack->Peek();
  3447. }
  3448. void ThreadContext::PushHostScriptContext(HostScriptContext* topProvider)
  3449. {
  3450. // script engine can be created coming from GetDispID, so push/pop can be
  3451. // happening after the first round of enterscript as well. we might need to
  3452. // revisit the whole callRootLevel but probably not now.
  3453. // Assert(HasPreviousHostScriptContext() || callRootLevel == 0);
  3454. hostScriptContextStack->Push(topProvider);
  3455. }
  3456. HostScriptContext* ThreadContext::PopHostScriptContext()
  3457. {
  3458. return hostScriptContextStack->Pop();
  3459. // script engine can be created coming from GetDispID, so push/pop can be
  3460. // happening after the first round of enterscript as well. we might need to
  3461. // revisit the whole callRootLevel but probably not now.
  3462. // Assert(HasPreviousHostScriptContext() || callRootLevel == 0);
  3463. }
  3464. #if DBG || defined(PROFILE_EXEC)
  3465. bool
  3466. ThreadContext::AsyncHostOperationStart(void * suspendRecord)
  3467. {
  3468. bool wasInAsync = false;
  3469. Assert(!this->IsScriptActive());
  3470. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  3471. if (lastRecord != NULL)
  3472. {
  3473. if (!lastRecord->leaveForHost)
  3474. {
  3475. #if DBG
  3476. wasInAsync = !!lastRecord->leaveForAsyncHostOperation;
  3477. lastRecord->leaveForAsyncHostOperation = true;
  3478. #endif
  3479. #ifdef PROFILE_EXEC
  3480. lastRecord->scriptContext->ProfileSuspend(Js::RunPhase, (Js::Profiler::SuspendRecord *)suspendRecord);
  3481. #endif
  3482. }
  3483. else
  3484. {
  3485. Assert(!lastRecord->leaveForAsyncHostOperation);
  3486. }
  3487. }
  3488. return wasInAsync;
  3489. }
  3490. void
  3491. ThreadContext::AsyncHostOperationEnd(bool wasInAsync, void * suspendRecord)
  3492. {
  3493. Assert(!this->IsScriptActive());
  3494. Js::ScriptEntryExitRecord * lastRecord = this->entryExitRecord;
  3495. if (lastRecord != NULL)
  3496. {
  3497. if (!lastRecord->leaveForHost)
  3498. {
  3499. Assert(lastRecord->leaveForAsyncHostOperation);
  3500. #if DBG
  3501. lastRecord->leaveForAsyncHostOperation = wasInAsync;
  3502. #endif
  3503. #ifdef PROFILE_EXEC
  3504. lastRecord->scriptContext->ProfileResume((Js::Profiler::SuspendRecord *)suspendRecord);
  3505. #endif
  3506. }
  3507. else
  3508. {
  3509. Assert(!lastRecord->leaveForAsyncHostOperation);
  3510. Assert(!wasInAsync);
  3511. }
  3512. }
  3513. }
  3514. #endif
  3515. #ifdef RECYCLER_DUMP_OBJECT_GRAPH
  3516. void DumpRecyclerObjectGraph()
  3517. {
  3518. ThreadContext * threadContext = ThreadContext::GetContextForCurrentThread();
  3519. if (threadContext == nullptr)
  3520. {
  3521. Output::Print(_u("No thread context"));
  3522. }
  3523. threadContext->GetRecycler()->DumpObjectGraph();
  3524. }
  3525. #endif
  3526. #if ENABLE_NATIVE_CODEGEN
  3527. bool ThreadContext::IsNativeAddressHelper(void * pCodeAddr, Js::ScriptContext* currentScriptContext)
  3528. {
  3529. bool isNativeAddr = false;
  3530. if (currentScriptContext && currentScriptContext->GetJitFuncRangeCache() != nullptr)
  3531. {
  3532. isNativeAddr = currentScriptContext->GetJitFuncRangeCache()->IsNativeAddr(pCodeAddr);
  3533. }
  3534. for (Js::ScriptContext *scriptContext = scriptContextList; scriptContext && !isNativeAddr; scriptContext = scriptContext->next)
  3535. {
  3536. if (scriptContext == currentScriptContext || scriptContext->GetJitFuncRangeCache() == nullptr)
  3537. {
  3538. continue;
  3539. }
  3540. isNativeAddr = scriptContext->GetJitFuncRangeCache()->IsNativeAddr(pCodeAddr);
  3541. }
  3542. return isNativeAddr;
  3543. }
  3544. BOOL ThreadContext::IsNativeAddress(void * pCodeAddr, Js::ScriptContext* currentScriptContext)
  3545. {
  3546. #if ENABLE_OOP_NATIVE_CODEGEN
  3547. if (JITManager::GetJITManager()->IsOOPJITEnabled())
  3548. {
  3549. if (PreReservedVirtualAllocWrapper::IsInRange((void*)m_prereservedRegionAddr, pCodeAddr))
  3550. {
  3551. return true;
  3552. }
  3553. if (IsAllJITCodeInPreReservedRegion())
  3554. {
  3555. return false;
  3556. }
  3557. if (AutoSystemInfo::IsJscriptModulePointer(pCodeAddr))
  3558. {
  3559. return false;
  3560. }
  3561. #if DBG
  3562. boolean result;
  3563. HRESULT hr = JITManager::GetJITManager()->IsNativeAddr(this->m_remoteThreadContextInfo, (intptr_t)pCodeAddr, &result);
  3564. #endif
  3565. bool isNativeAddr = IsNativeAddressHelper(pCodeAddr, currentScriptContext);
  3566. #if DBG
  3567. Assert(FAILED(hr) || result == (isNativeAddr? TRUE:FALSE));
  3568. #endif
  3569. return isNativeAddr;
  3570. }
  3571. else
  3572. #endif
  3573. {
  3574. PreReservedVirtualAllocWrapper *preReservedVirtualAllocWrapper = this->GetPreReservedVirtualAllocator();
  3575. if (preReservedVirtualAllocWrapper->IsInRange(pCodeAddr))
  3576. {
  3577. return TRUE;
  3578. }
  3579. if (!this->IsAllJITCodeInPreReservedRegion())
  3580. {
  3581. #if DBG
  3582. AutoCriticalSection autoLock(&this->codePageAllocators.cs);
  3583. #endif
  3584. bool isNativeAddr = IsNativeAddressHelper(pCodeAddr, currentScriptContext);
  3585. #if DBG
  3586. Assert(this->codePageAllocators.IsInNonPreReservedPageAllocator(pCodeAddr) == isNativeAddr);
  3587. #endif
  3588. return isNativeAddr;
  3589. }
  3590. return FALSE;
  3591. }
  3592. }
  3593. #endif
  3594. #if ENABLE_PROFILE_INFO
  3595. void ThreadContext::EnsureSourceProfileManagersByUrlMap()
  3596. {
  3597. if(this->recyclableData->sourceProfileManagersByUrl == nullptr)
  3598. {
  3599. this->EnsureRecycler();
  3600. this->recyclableData->sourceProfileManagersByUrl = RecyclerNew(GetRecycler(), SourceProfileManagersByUrlMap, GetRecycler());
  3601. }
  3602. }
  3603. //
  3604. // Returns the cache profile manager for the URL and hash combination for a particular dynamic script. There is a ref count added for every script context
  3605. // that references the shared profile manager info.
  3606. //
  3607. Js::SourceDynamicProfileManager* ThreadContext::GetSourceDynamicProfileManager(_In_z_ const WCHAR* url, _In_ uint hash, _Inout_ bool* addRef)
  3608. {
  3609. EnsureSourceProfileManagersByUrlMap();
  3610. Js::SourceDynamicProfileManager* profileManager = nullptr;
  3611. SourceDynamicProfileManagerCache* managerCache = nullptr;
  3612. bool newCache = false;
  3613. if(!this->recyclableData->sourceProfileManagersByUrl->TryGetValue(url, &managerCache))
  3614. {
  3615. if(this->recyclableData->sourceProfileManagersByUrl->Count() >= INMEMORY_CACHE_MAX_URL)
  3616. {
  3617. return nullptr;
  3618. }
  3619. managerCache = RecyclerNewZ(this->GetRecycler(), SourceDynamicProfileManagerCache);
  3620. newCache = true;
  3621. }
  3622. bool createProfileManager = false;
  3623. if(!managerCache->sourceProfileManagerMap)
  3624. {
  3625. managerCache->sourceProfileManagerMap = RecyclerNew(this->GetRecycler(), SourceDynamicProfileManagerMap, this->GetRecycler());
  3626. createProfileManager = true;
  3627. }
  3628. else
  3629. {
  3630. createProfileManager = !managerCache->sourceProfileManagerMap->TryGetValue(hash, &profileManager);
  3631. }
  3632. if(createProfileManager)
  3633. {
  3634. if(managerCache->sourceProfileManagerMap->Count() < INMEMORY_CACHE_MAX_PROFILE_MANAGER)
  3635. {
  3636. profileManager = RecyclerNewZ(this->GetRecycler(), Js::SourceDynamicProfileManager, this->GetRecycler());
  3637. managerCache->sourceProfileManagerMap->Add(hash, profileManager);
  3638. }
  3639. }
  3640. else
  3641. {
  3642. profileManager->Reuse();
  3643. }
  3644. if(!*addRef)
  3645. {
  3646. managerCache->AddRef();
  3647. *addRef = true;
  3648. OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, _u("Addref dynamic source profile manger - Url: %s\n"), url);
  3649. }
  3650. if (newCache)
  3651. {
  3652. // Let's make a copy of the URL because there is no guarantee this URL will remain alive in the future.
  3653. size_t lengthInChars = wcslen(url) + 1;
  3654. WCHAR* urlCopy = RecyclerNewArrayLeaf(GetRecycler(), WCHAR, lengthInChars);
  3655. js_memcpy_s(urlCopy, lengthInChars * sizeof(WCHAR), url, lengthInChars * sizeof(WCHAR));
  3656. this->recyclableData->sourceProfileManagersByUrl->Add(urlCopy, managerCache);
  3657. }
  3658. return profileManager;
  3659. }
  3660. //
  3661. // Decrement the ref count for this URL and cleanup the corresponding record if there are no other references to it.
  3662. //
  3663. uint ThreadContext::ReleaseSourceDynamicProfileManagers(const WCHAR* url)
  3664. {
  3665. // If we've already freed the recyclable data, we're shutting down the thread context so skip clean up
  3666. if (this->recyclableData == nullptr) return 0;
  3667. SourceDynamicProfileManagerCache* managerCache = this->recyclableData->sourceProfileManagersByUrl->Lookup(url, nullptr);
  3668. uint refCount = 0;
  3669. if(managerCache) // manager cache may be null we exceeded -INMEMORY_CACHE_MAX_URL
  3670. {
  3671. refCount = managerCache->Release();
  3672. OUTPUT_VERBOSE_TRACE(Js::DynamicProfilePhase, _u("Release dynamic source profile manger %d Url: %s\n"), refCount, url);
  3673. Output::Flush();
  3674. if(refCount == 0)
  3675. {
  3676. this->recyclableData->sourceProfileManagersByUrl->Remove(url);
  3677. }
  3678. }
  3679. return refCount;
  3680. }
  3681. #endif
  3682. void ThreadContext::EnsureSymbolRegistrationMap()
  3683. {
  3684. if (this->recyclableData->symbolRegistrationMap == nullptr)
  3685. {
  3686. this->EnsureRecycler();
  3687. this->recyclableData->symbolRegistrationMap = RecyclerNew(GetRecycler(), SymbolRegistrationMap, GetRecycler());
  3688. }
  3689. }
  3690. const Js::PropertyRecord* ThreadContext::GetSymbolFromRegistrationMap(const char16* stringKey, charcount_t stringLength)
  3691. {
  3692. this->EnsureSymbolRegistrationMap();
  3693. Js::HashedCharacterBuffer<char16> propertyName = Js::HashedCharacterBuffer<char16>(stringKey, stringLength);
  3694. return this->recyclableData->symbolRegistrationMap->LookupWithKey(&propertyName, nullptr);
  3695. }
  3696. const Js::PropertyRecord* ThreadContext::AddSymbolToRegistrationMap(const char16* stringKey, charcount_t stringLength)
  3697. {
  3698. this->EnsureSymbolRegistrationMap();
  3699. const Js::PropertyRecord* propertyRecord = this->UncheckedAddPropertyId(stringKey, stringLength, /*bind*/false, /*isSymbol*/true);
  3700. Assert(propertyRecord);
  3701. // We need to support null characters in the Symbol names. For e.g. "A\0Z" is a valid symbol name and is different than "A\0Y".
  3702. // However, as the key contains a null character we need to hash the symbol name past the null character. The default implementation terminates
  3703. // at the null character, so we use the Js::HashedCharacterBuffer as key. We allocate the key in the recycler memory as it needs to be around
  3704. // for the lifetime of the map.
  3705. Js::HashedCharacterBuffer<char16> * propertyName = RecyclerNew(GetRecycler(), Js::HashedCharacterBuffer<char16>, propertyRecord->GetBuffer(), propertyRecord->GetLength());
  3706. this->recyclableData->symbolRegistrationMap->Add(propertyName, propertyRecord);
  3707. return propertyRecord;
  3708. }
  3709. #if ENABLE_TTD
  3710. JsUtil::BaseDictionary<Js::HashedCharacterBuffer<char16>*, const Js::PropertyRecord*, Recycler, PowerOf2SizePolicy, Js::PropertyRecordStringHashComparer>* ThreadContext::GetSymbolRegistrationMap_TTD()
  3711. {
  3712. //This adds a little memory but makes simplifies other logic -- maybe revise later
  3713. this->EnsureSymbolRegistrationMap();
  3714. return this->recyclableData->symbolRegistrationMap;
  3715. }
  3716. #endif
  3717. void ThreadContext::ClearImplicitCallFlags()
  3718. {
  3719. SetImplicitCallFlags(Js::ImplicitCall_None);
  3720. }
  3721. void ThreadContext::ClearImplicitCallFlags(Js::ImplicitCallFlags flags)
  3722. {
  3723. Assert((flags & Js::ImplicitCall_None) == 0);
  3724. SetImplicitCallFlags((Js::ImplicitCallFlags)(implicitCallFlags & ~flags));
  3725. }
  3726. void ThreadContext::CheckAndResetImplicitCallAccessorFlag()
  3727. {
  3728. Js::ImplicitCallFlags accessorCallFlag = (Js::ImplicitCallFlags)(Js::ImplicitCall_Accessor & ~Js::ImplicitCall_None);
  3729. if ((GetImplicitCallFlags() & accessorCallFlag) != 0)
  3730. {
  3731. ClearImplicitCallFlags(accessorCallFlag);
  3732. AddImplicitCallFlags(Js::ImplicitCall_NonProfiledAccessor);
  3733. }
  3734. }
  3735. bool ThreadContext::HasNoSideEffect(Js::RecyclableObject * function) const
  3736. {
  3737. Js::FunctionInfo::Attributes attributes = Js::FunctionInfo::GetAttributes(function);
  3738. return this->HasNoSideEffect(function, attributes);
  3739. }
  3740. bool ThreadContext::HasNoSideEffect(Js::RecyclableObject * function, Js::FunctionInfo::Attributes attributes) const
  3741. {
  3742. if (((attributes & Js::FunctionInfo::CanBeHoisted) != 0)
  3743. || ((attributes & Js::FunctionInfo::HasNoSideEffect) != 0 && !IsDisableImplicitException()))
  3744. {
  3745. Assert((attributes & Js::FunctionInfo::HasNoSideEffect) != 0);
  3746. return true;
  3747. }
  3748. return false;
  3749. }
  3750. bool
  3751. ThreadContext::RecordImplicitException()
  3752. {
  3753. // Record the exception in the implicit call flag
  3754. AddImplicitCallFlags(Js::ImplicitCall_Exception);
  3755. if (IsDisableImplicitException())
  3756. {
  3757. // Indicate that we shouldn't throw if ImplicitExceptions have been disabled
  3758. return false;
  3759. }
  3760. // Disabling implicit exception when disabling implicit calls can result in valid exceptions not being thrown.
  3761. // Instead we tell not to throw only if an implicit call happened and they are disabled. This is to cover the case
  3762. // of an exception being thrown because an implicit call not executed left the execution in a bad state.
  3763. // Since there is an implicit call, we expect to bailout and handle this operation in the interpreter instead.
  3764. bool hasImplicitCallHappened = IsDisableImplicitCall() && (GetImplicitCallFlags() & ~Js::ImplicitCall_Exception);
  3765. return !hasImplicitCallHappened;
  3766. }
  3767. void ThreadContext::SetThreadServiceWrapper(ThreadServiceWrapper* inThreadServiceWrapper)
  3768. {
  3769. AssertMsg(threadServiceWrapper == NULL || inThreadServiceWrapper == NULL, "double set ThreadServiceWrapper");
  3770. threadServiceWrapper = inThreadServiceWrapper;
  3771. }
  3772. ThreadServiceWrapper* ThreadContext::GetThreadServiceWrapper()
  3773. {
  3774. return threadServiceWrapper;
  3775. }
  3776. uint ThreadContext::GetRandomNumber()
  3777. {
  3778. #ifdef ENABLE_CUSTOM_ENTROPY
  3779. return (uint)GetEntropy().GetRand();
  3780. #else
  3781. uint randomNumber = 0;
  3782. errno_t e = rand_s(&randomNumber);
  3783. Assert(e == 0);
  3784. return randomNumber;
  3785. #endif
  3786. }
  3787. #if defined(ENABLE_JS_ETW) && defined(NTBUILD)
  3788. void ThreadContext::EtwLogPropertyIdList()
  3789. {
  3790. propertyMap->Map([&](const Js::PropertyRecord* propertyRecord){
  3791. EventWriteJSCRIPT_HOSTING_PROPERTYID_LIST(propertyRecord, propertyRecord->GetBuffer());
  3792. });
  3793. }
  3794. #endif
  3795. #ifdef ENABLE_PROJECTION
  3796. void ThreadContext::AddExternalWeakReferenceCache(ExternalWeakReferenceCache *externalWeakReferenceCache)
  3797. {
  3798. this->externalWeakReferenceCacheList.Prepend(&HeapAllocator::Instance, externalWeakReferenceCache);
  3799. }
  3800. void ThreadContext::RemoveExternalWeakReferenceCache(ExternalWeakReferenceCache *externalWeakReferenceCache)
  3801. {
  3802. Assert(!externalWeakReferenceCacheList.Empty());
  3803. this->externalWeakReferenceCacheList.Remove(&HeapAllocator::Instance, externalWeakReferenceCache);
  3804. }
  3805. void ThreadContext::MarkExternalWeakReferencedObjects(bool inPartialCollect)
  3806. {
  3807. SListBase<ExternalWeakReferenceCache *, HeapAllocator>::Iterator iteratorWeakRefCache(&this->externalWeakReferenceCacheList);
  3808. while (iteratorWeakRefCache.Next())
  3809. {
  3810. iteratorWeakRefCache.Data()->MarkNow(recycler, inPartialCollect);
  3811. }
  3812. }
  3813. void ThreadContext::ResolveExternalWeakReferencedObjects()
  3814. {
  3815. SListBase<ExternalWeakReferenceCache *, HeapAllocator>::Iterator iteratorWeakRefCache(&this->externalWeakReferenceCacheList);
  3816. while (iteratorWeakRefCache.Next())
  3817. {
  3818. iteratorWeakRefCache.Data()->ResolveNow(recycler);
  3819. }
  3820. }
  3821. #if DBG_DUMP
  3822. void ThreadContext::RegisterProjectionMemoryInformation(IProjectionContextMemoryInfo* projectionContextMemoryInfo)
  3823. {
  3824. Assert(this->projectionMemoryInformation == nullptr || this->projectionMemoryInformation == projectionContextMemoryInfo);
  3825. this->projectionMemoryInformation = projectionContextMemoryInfo;
  3826. }
  3827. void ThreadContext::DumpProjectionContextMemoryStats(LPCWSTR headerMsg, bool forceDetailed)
  3828. {
  3829. if (this->projectionMemoryInformation)
  3830. {
  3831. this->projectionMemoryInformation->DumpCurrentStats(headerMsg, forceDetailed);
  3832. }
  3833. }
  3834. IProjectionContextMemoryInfo* ThreadContext::GetProjectionContextMemoryInformation()
  3835. {
  3836. return this->projectionMemoryInformation;
  3837. }
  3838. #endif
  3839. #endif
  3840. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3841. Js::Var ThreadContext::GetMemoryStat(Js::ScriptContext* scriptContext)
  3842. {
  3843. ScriptMemoryDumper dumper(scriptContext);
  3844. return dumper.Dump();
  3845. }
  3846. void ThreadContext::SetAutoProxyName(LPCWSTR objectName)
  3847. {
  3848. recyclableData->autoProxyName = objectName;
  3849. }
  3850. #endif
  3851. //
  3852. // Regex helpers
  3853. //
  3854. UnifiedRegex::StandardChars<uint8>* ThreadContext::GetStandardChars(__inout_opt uint8* dummy)
  3855. {
  3856. if (standardUTF8Chars == 0)
  3857. {
  3858. ArenaAllocator* allocator = GetThreadAlloc();
  3859. standardUTF8Chars = Anew(allocator, UnifiedRegex::UTF8StandardChars, allocator);
  3860. }
  3861. return standardUTF8Chars;
  3862. }
  3863. UnifiedRegex::StandardChars<char16>* ThreadContext::GetStandardChars(__inout_opt char16* dummy)
  3864. {
  3865. if (standardUnicodeChars == 0)
  3866. {
  3867. ArenaAllocator* allocator = GetThreadAlloc();
  3868. standardUnicodeChars = Anew(allocator, UnifiedRegex::UnicodeStandardChars, allocator);
  3869. }
  3870. return standardUnicodeChars;
  3871. }
  3872. void ThreadContext::CheckScriptInterrupt()
  3873. {
  3874. if (TestThreadContextFlag(ThreadContextFlagCanDisableExecution))
  3875. {
  3876. if (this->IsExecutionDisabled())
  3877. {
  3878. Assert(this->DoInterruptProbe());
  3879. throw Js::ScriptAbortException();
  3880. }
  3881. }
  3882. else
  3883. {
  3884. this->CheckInterruptPoll();
  3885. }
  3886. }
  3887. void ThreadContext::CheckInterruptPoll()
  3888. {
  3889. // Disable QC when implicit calls are disabled since the host can do anything before returning back, like servicing the
  3890. // message loop, which may in turn cause script code to be executed and implicit calls to be made
  3891. if (!IsDisableImplicitCall())
  3892. {
  3893. InterruptPoller *poller = this->interruptPoller;
  3894. if (poller)
  3895. {
  3896. poller->CheckInterruptPoll();
  3897. }
  3898. }
  3899. }
  3900. void *
  3901. ThreadContext::GetDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType)
  3902. {
  3903. void * data = nullptr;
  3904. return this->dynamicObjectEnumeratorCacheMap.TryGetValue(dynamicType, &data)? data : nullptr;
  3905. }
  3906. void
  3907. ThreadContext::AddDynamicObjectEnumeratorCache(Js::DynamicType const * dynamicType, void * cache)
  3908. {
  3909. this->dynamicObjectEnumeratorCacheMap.Item(dynamicType, cache);
  3910. }
  3911. InterruptPoller::InterruptPoller(ThreadContext *tc) :
  3912. threadContext(tc),
  3913. lastPollTick(0),
  3914. lastResetTick(0),
  3915. isDisabled(FALSE)
  3916. {
  3917. tc->SetInterruptPoller(this);
  3918. }
  3919. void InterruptPoller::CheckInterruptPoll()
  3920. {
  3921. if (!isDisabled)
  3922. {
  3923. Js::ScriptEntryExitRecord *entryExitRecord = this->threadContext->GetScriptEntryExit();
  3924. if (entryExitRecord)
  3925. {
  3926. Js::ScriptContext *scriptContext = entryExitRecord->scriptContext;
  3927. if (scriptContext)
  3928. {
  3929. this->TryInterruptPoll(scriptContext);
  3930. }
  3931. }
  3932. }
  3933. }
  3934. void InterruptPoller::GetStatementCount(ULONG *pluHi, ULONG *pluLo)
  3935. {
  3936. DWORD resetTick = this->lastResetTick;
  3937. DWORD pollTick = this->lastPollTick;
  3938. DWORD elapsed;
  3939. elapsed = pollTick - resetTick;
  3940. ULONGLONG statements = (ULONGLONG)elapsed * InterruptPoller::TicksToStatements;
  3941. *pluLo = (ULONG)statements;
  3942. *pluHi = (ULONG)(statements >> 32);
  3943. }
  3944. void ThreadContext::DisableExecution()
  3945. {
  3946. Assert(TestThreadContextFlag(ThreadContextFlagCanDisableExecution));
  3947. // Hammer the stack limit with a value that will cause script abort on the next stack probe.
  3948. this->SetStackLimitForCurrentThread(Js::Constants::StackLimitForScriptInterrupt);
  3949. return;
  3950. }
  3951. void ThreadContext::EnableExecution()
  3952. {
  3953. Assert(this->GetStackProber());
  3954. // Restore the normal stack limit.
  3955. this->SetStackLimitForCurrentThread(this->GetStackProber()->GetScriptStackLimit());
  3956. // It's possible that the host disabled execution after the script threw an exception
  3957. // of it's own, so we shouldn't clear that. Only exceptions for script termination
  3958. // should be cleared.
  3959. if (GetRecordedException() == GetPendingTerminatedErrorObject())
  3960. {
  3961. SetRecordedException(NULL);
  3962. }
  3963. }
  3964. bool ThreadContext::TestThreadContextFlag(ThreadContextFlags contextFlag) const
  3965. {
  3966. return (this->threadContextFlags & contextFlag) != 0;
  3967. }
  3968. void ThreadContext::SetThreadContextFlag(ThreadContextFlags contextFlag)
  3969. {
  3970. this->threadContextFlags = (ThreadContextFlags)(this->threadContextFlags | contextFlag);
  3971. }
  3972. void ThreadContext::ClearThreadContextFlag(ThreadContextFlags contextFlag)
  3973. {
  3974. this->threadContextFlags = (ThreadContextFlags)(this->threadContextFlags & ~contextFlag);
  3975. }
  3976. #ifdef ENABLE_GLOBALIZATION
  3977. Js::DelayLoadWinRtString * ThreadContext::GetWinRTStringLibrary()
  3978. {
  3979. delayLoadWinRtString.EnsureFromSystemDirOnly();
  3980. return &delayLoadWinRtString;
  3981. }
  3982. #ifdef ENABLE_PROJECTION
  3983. Js::DelayLoadWinRtError * ThreadContext::GetWinRTErrorLibrary()
  3984. {
  3985. delayLoadWinRtError.EnsureFromSystemDirOnly();
  3986. return &delayLoadWinRtError;
  3987. }
  3988. Js::DelayLoadWinRtTypeResolution* ThreadContext::GetWinRTTypeResolutionLibrary()
  3989. {
  3990. delayLoadWinRtTypeResolution.EnsureFromSystemDirOnly();
  3991. return &delayLoadWinRtTypeResolution;
  3992. }
  3993. Js::DelayLoadWinRtRoParameterizedIID* ThreadContext::GetWinRTRoParameterizedIIDLibrary()
  3994. {
  3995. delayLoadWinRtRoParameterizedIID.EnsureFromSystemDirOnly();
  3996. return &delayLoadWinRtRoParameterizedIID;
  3997. }
  3998. #endif
  3999. #if defined(ENABLE_INTL_OBJECT) || defined(ENABLE_ES6_CHAR_CLASSIFIER)
  4000. #ifdef INTL_WINGLOB
  4001. Js::WindowsGlobalizationAdapter* ThreadContext::GetWindowsGlobalizationAdapter()
  4002. {
  4003. return &windowsGlobalizationAdapter;
  4004. }
  4005. Js::DelayLoadWindowsGlobalization* ThreadContext::GetWindowsGlobalizationLibrary()
  4006. {
  4007. delayLoadWindowsGlobalizationLibrary.Ensure(this->GetWinRTStringLibrary());
  4008. return &delayLoadWindowsGlobalizationLibrary;
  4009. }
  4010. #endif // INTL_WINGLOB
  4011. #endif
  4012. #ifdef ENABLE_FOUNDATION_OBJECT
  4013. Js::WindowsFoundationAdapter* ThreadContext::GetWindowsFoundationAdapter()
  4014. {
  4015. return &windowsFoundationAdapter;
  4016. }
  4017. Js::DelayLoadWinRtFoundation* ThreadContext::GetWinRtFoundationLibrary()
  4018. {
  4019. delayLoadWinRtFoundationLibrary.EnsureFromSystemDirOnly();
  4020. return &delayLoadWinRtFoundationLibrary;
  4021. }
  4022. #endif
  4023. #endif // ENABLE_GLOBALIZATION
  4024. // Despite the name, callers expect this to return the highest propid + 1.
  4025. uint ThreadContext::GetHighestPropertyNameIndex() const
  4026. {
  4027. return propertyMap->GetLastIndex() + 1 + Js::InternalPropertyIds::Count;
  4028. }
  4029. #if defined(CHECK_MEMORY_LEAK) || defined(LEAK_REPORT)
  4030. void ThreadContext::ReportAndCheckLeaksOnProcessDetach()
  4031. {
  4032. bool needReportOrCheck = false;
  4033. #ifdef LEAK_REPORT
  4034. needReportOrCheck = needReportOrCheck || Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag);
  4035. #endif
  4036. #ifdef CHECK_MEMORY_LEAK
  4037. needReportOrCheck = needReportOrCheck ||
  4038. (Js::Configuration::Global.flags.CheckMemoryLeak && MemoryLeakCheck::IsEnableOutput());
  4039. #endif
  4040. if (!needReportOrCheck)
  4041. {
  4042. return;
  4043. }
  4044. // Report leaks even if this is a force termination and we have not clean up the thread
  4045. // This is call during process detach. No one should be creating new thread context.
  4046. // So don't need to take the lock
  4047. ThreadContext * current = GetThreadContextList();
  4048. while (current)
  4049. {
  4050. #if DBG
  4051. current->pageAllocator.ClearConcurrentThreadId();
  4052. #endif
  4053. Recycler * recycler = current->GetRecycler();
  4054. #ifdef LEAK_REPORT
  4055. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  4056. {
  4057. AUTO_LEAK_REPORT_SECTION(Js::Configuration::Global.flags, _u("Thread Context (%p): Process Termination (TID: %d)"), current, current->threadId);
  4058. LeakReport::DumpUrl(current->threadId);
  4059. // Heuristically figure out which one is the root tracker script engine
  4060. // and force close on it
  4061. if (current->rootTrackerScriptContext != nullptr)
  4062. {
  4063. current->rootTrackerScriptContext->Close(false);
  4064. }
  4065. recycler->ReportLeaksOnProcessDetach();
  4066. }
  4067. #endif
  4068. #ifdef CHECK_MEMORY_LEAK
  4069. recycler->CheckLeaksOnProcessDetach(_u("Process Termination"));
  4070. #endif
  4071. current = current->Next();
  4072. }
  4073. }
  4074. #endif
  4075. #ifdef LEAK_REPORT
  4076. void
  4077. ThreadContext::SetRootTrackerScriptContext(Js::ScriptContext * scriptContext)
  4078. {
  4079. Assert(this->rootTrackerScriptContext == nullptr);
  4080. this->rootTrackerScriptContext = scriptContext;
  4081. scriptContext->isRootTrackerScriptContext = true;
  4082. }
  4083. void
  4084. ThreadContext::ClearRootTrackerScriptContext(Js::ScriptContext * scriptContext)
  4085. {
  4086. Assert(this->rootTrackerScriptContext == scriptContext);
  4087. this->rootTrackerScriptContext->isRootTrackerScriptContext = false;
  4088. this->rootTrackerScriptContext = nullptr;
  4089. }
  4090. #endif
  4091. AutoTagNativeLibraryEntry::AutoTagNativeLibraryEntry(Js::RecyclableObject* function, Js::CallInfo callInfo, PCWSTR name, void* addr)
  4092. {
  4093. // Save function/callInfo values (for StackWalker). Compiler may stackpack/optimize them for built-in native functions.
  4094. entry.function = function;
  4095. entry.callInfo = callInfo;
  4096. entry.name = name;
  4097. entry.addr = addr;
  4098. ThreadContext* threadContext = function->GetScriptContext()->GetThreadContext();
  4099. threadContext->PushNativeLibraryEntry(&entry);
  4100. }
  4101. AutoTagNativeLibraryEntry::~AutoTagNativeLibraryEntry()
  4102. {
  4103. ThreadContext* threadContext = entry.function->GetScriptContext()->GetThreadContext();
  4104. Assert(threadContext->PeekNativeLibraryEntry() == &entry);
  4105. threadContext->PopNativeLibraryEntry();
  4106. }
  4107. #if ENABLE_JS_REENTRANCY_CHECK
  4108. #if DBG
  4109. void JsReentLock::setObjectForMutation(Js::Var object)
  4110. {
  4111. m_arrayObject = nullptr;
  4112. if (object != nullptr && Js::DynamicObject::IsAnyArray(object))
  4113. {
  4114. m_arrayObject = object;
  4115. }
  4116. // Don't care about any other objects for now
  4117. }
  4118. void JsReentLock::setSecondObjectForMutation(Js::Var object)
  4119. {
  4120. m_arrayObject2 = nullptr;
  4121. if (object != nullptr && Js::DynamicObject::IsAnyArray(object))
  4122. {
  4123. m_arrayObject2 = object;
  4124. }
  4125. // Don't care about any other objects for now
  4126. }
  4127. void JsReentLock::MutateArrayObject(Js::Var arrayObject)
  4128. {
  4129. if (arrayObject)
  4130. {
  4131. Js::JavascriptArray *arr = Js::JavascriptArray::FromAnyArray(arrayObject);
  4132. uint32 random = static_cast<unsigned int>(rand());
  4133. if (random % 20 == 0)
  4134. {
  4135. arr->DoTypeMutation();
  4136. }
  4137. else if (random % 20 == 1)
  4138. {
  4139. // TODO : modify the length of the current array
  4140. // Or other opportunities
  4141. }
  4142. }
  4143. }
  4144. void JsReentLock::MutateArrayObject()
  4145. {
  4146. if (CONFIG_FLAG(EnableArrayTypeMutation))
  4147. {
  4148. JsReentLock::MutateArrayObject(m_arrayObject);
  4149. JsReentLock::MutateArrayObject(m_arrayObject2);
  4150. }
  4151. }
  4152. #endif
  4153. #endif