ThreadContext.cpp 158 KB

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