ThreadContext.cpp 159 KB

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