ThreadContext.cpp 151 KB

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