ScriptContext.cpp 238 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. 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. // Parser Includes
  7. #include "RegexCommon.h"
  8. #include "DebugWriter.h"
  9. #include "RegexStats.h"
  10. #include "ByteCode/ByteCodeApi.h"
  11. #include "Library/ProfileString.h"
  12. #ifdef ENABLE_SCRIPT_DEBUGGING
  13. #include "Debug/DiagHelperMethodWrapper.h"
  14. #endif
  15. #if PROFILE_DICTIONARY
  16. #include "DictionaryStats.h"
  17. #endif
  18. #include "Base/ScriptContextProfiler.h"
  19. #include "Base/EtwTrace.h"
  20. #include "Language/InterpreterStackFrame.h"
  21. #include "Language/SourceDynamicProfileManager.h"
  22. #include "Language/JavascriptStackWalker.h"
  23. #include "Language/AsmJsTypes.h"
  24. #include "Language/AsmJsModule.h"
  25. #ifdef ASMJS_PLAT
  26. #include "Language/AsmJsEncoder.h"
  27. #include "Language/AsmJsCodeGenerator.h"
  28. #include "Language/AsmJsUtils.h"
  29. #endif
  30. #ifdef ENABLE_BASIC_TELEMETRY
  31. #include "ScriptContextTelemetry.h"
  32. #endif
  33. namespace Js
  34. {
  35. ScriptContext * ScriptContext::New(ThreadContext * threadContext)
  36. {
  37. AutoPtr<ScriptContext> scriptContext(HeapNew(ScriptContext, threadContext));
  38. scriptContext->InitializeAllocations();
  39. return scriptContext.Detach();
  40. }
  41. #if ENABLE_NATIVE_CODEGEN
  42. CriticalSection JITPageAddrToFuncRangeCache::cs;
  43. #endif
  44. ScriptContext::ScriptContext(ThreadContext* threadContext) :
  45. ScriptContextBase(),
  46. prev(nullptr),
  47. next(nullptr),
  48. interpreterArena(nullptr),
  49. moduleSrcInfoCount(0),
  50. // Regex globals
  51. #if ENABLE_REGEX_CONFIG_OPTIONS
  52. regexStatsDatabase(0),
  53. regexDebugWriter(0),
  54. #endif
  55. trigramAlphabet(nullptr),
  56. regexStacks(nullptr),
  57. config(threadContext->GetConfig(), threadContext->IsOptimizedForManyInstances()),
  58. #if ENABLE_BACKGROUND_PARSING
  59. backgroundParser(nullptr),
  60. #endif
  61. #if ENABLE_NATIVE_CODEGEN
  62. nativeCodeGen(nullptr),
  63. m_domFastPathHelperMap(nullptr),
  64. m_remoteScriptContextAddr(nullptr),
  65. jitFuncRangeCache(nullptr),
  66. #endif
  67. threadContext(threadContext),
  68. scriptStartEventHandler(nullptr),
  69. scriptEndEventHandler(nullptr),
  70. #ifdef FAULT_INJECTION
  71. disposeScriptByFaultInjectionEventHandler(nullptr),
  72. #endif
  73. guestArena(nullptr),
  74. #ifdef ENABLE_SCRIPT_DEBUGGING
  75. diagnosticArena(nullptr),
  76. raiseMessageToDebuggerFunctionType(nullptr),
  77. transitionToDebugModeIfFirstSourceFn(nullptr),
  78. debugContext(nullptr),
  79. isDebugContextInitialized(false),
  80. isEnumeratingRecyclerObjects(false),
  81. #endif
  82. sourceSize(0),
  83. deferredBody(false),
  84. isScriptContextActuallyClosed(false),
  85. isFinalized(false),
  86. isEvalRestricted(false),
  87. isInvalidatedForHostObjects(false),
  88. fastDOMenabled(false),
  89. directHostTypeId(TypeIds_GlobalObject),
  90. isPerformingNonreentrantWork(false),
  91. isDiagnosticsScriptContext(false),
  92. m_enumerateNonUserFunctionsOnly(false),
  93. recycler(threadContext->EnsureRecycler()),
  94. CurrentThunk(DefaultEntryThunk),
  95. CurrentCrossSiteThunk(CrossSite::DefaultThunk),
  96. DeferredParsingThunk(DefaultDeferredParsingThunk),
  97. DeferredDeserializationThunk(DefaultDeferredDeserializeThunk),
  98. DispatchDefaultInvoke(nullptr),
  99. DispatchProfileInvoke(nullptr),
  100. m_pBuiltinFunctionIdMap(nullptr),
  101. hostScriptContext(nullptr),
  102. scriptEngineHaltCallback(nullptr),
  103. #if DYNAMIC_INTERPRETER_THUNK
  104. interpreterThunkEmitter(nullptr),
  105. #endif
  106. #ifdef ASMJS_PLAT
  107. asmJsInterpreterThunkEmitter(nullptr),
  108. asmJsCodeGenerator(nullptr),
  109. #endif
  110. generalAllocator(_u("SC-General"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  111. #ifdef ENABLE_BASIC_TELEMETRY
  112. telemetryAllocator(_u("SC-Telemetry"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  113. #endif
  114. dynamicProfileInfoAllocator(_u("SC-DynProfileInfo"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  115. #ifdef SEPARATE_ARENA
  116. sourceCodeAllocator(_u("SC-Code"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  117. regexAllocator(_u("SC-Regex"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  118. #endif
  119. #ifdef NEED_MISC_ALLOCATOR
  120. miscAllocator(_u("GC-Misc"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  121. #endif
  122. inlineCacheAllocator(_u("SC-InlineCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  123. isInstInlineCacheAllocator(_u("SC-IsInstInlineCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  124. forInCacheAllocator(_u("SC-ForInCache"), threadContext->GetPageAllocator(), Throw::OutOfMemory),
  125. hasUsedInlineCache(false),
  126. hasProtoOrStoreFieldInlineCache(false),
  127. hasIsInstInlineCache(false),
  128. registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(nullptr),
  129. firstInterpreterFrameReturnAddress(nullptr),
  130. builtInLibraryFunctions(nullptr),
  131. isWeakReferenceDictionaryListCleared(false)
  132. #if ENABLE_PROFILE_INFO
  133. , referencesSharedDynamicSourceContextInfo(false)
  134. #endif
  135. #if DBG
  136. , isInitialized(false)
  137. , isCloningGlobal(false)
  138. , bindRef(MiscAllocator())
  139. #endif
  140. #if ENABLE_TTD
  141. , TTDHostCallbackFunctor()
  142. , ScriptContextLogTag(TTD_INVALID_LOG_PTR_ID)
  143. , TTDWellKnownInfo(nullptr)
  144. , TTDContextInfo(nullptr)
  145. , TTDSnapshotOrInflateInProgress(false)
  146. , TTDRecordOrReplayModeEnabled(false)
  147. , TTDRecordModeEnabled(false)
  148. , TTDReplayModeEnabled(false)
  149. , TTDShouldPerformRecordOrReplayAction(false)
  150. , TTDShouldPerformRecordAction(false)
  151. , TTDShouldPerformReplayAction(false)
  152. , TTDShouldPerformDebuggerAction(false)
  153. , TTDShouldSuppressGetterInvocationForDebuggerEvaluation(false)
  154. #endif
  155. #ifdef REJIT_STATS
  156. , rejitStatsMap(nullptr)
  157. , bailoutReasonCounts(nullptr)
  158. , bailoutReasonCountsCap(nullptr)
  159. , rejitReasonCounts(nullptr)
  160. , rejitReasonCountsCap(nullptr)
  161. #endif
  162. #ifdef ENABLE_BASIC_TELEMETRY
  163. , telemetry(nullptr)
  164. #endif
  165. #ifdef INLINE_CACHE_STATS
  166. , cacheDataMap(nullptr)
  167. #endif
  168. #ifdef FIELD_ACCESS_STATS
  169. , fieldAccessStatsByFunctionNumber(nullptr)
  170. #endif
  171. , webWorkerId(Js::Constants::NonWebWorkerContextId)
  172. , url(_u(""))
  173. , startupComplete(false)
  174. #ifdef EDIT_AND_CONTINUE
  175. , activeScriptEditQuery(nullptr)
  176. #endif
  177. #ifdef RECYCLER_PERF_COUNTERS
  178. , bindReferenceCount(0)
  179. #endif
  180. , nextPendingClose(nullptr)
  181. #ifdef ENABLE_SCRIPT_PROFILING
  182. , heapEnum(nullptr)
  183. , m_fTraceDomCall(FALSE)
  184. #endif
  185. , intConstPropsOnGlobalObject(nullptr)
  186. , intConstPropsOnGlobalUserObject(nullptr)
  187. #ifdef PROFILE_STRINGS
  188. , stringProfiler(nullptr)
  189. #endif
  190. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  191. , codeSize(0)
  192. , bailOutRecordBytes(0)
  193. , bailOutOffsetBytes(0)
  194. #endif
  195. , emptyStringPropertyId(Js::PropertyIds::_none)
  196. , debugContext(nullptr)
  197. , jitFuncRangeCache(nullptr)
  198. {
  199. #ifdef ENABLE_SCRIPT_DEBUGGING
  200. // This may allocate memory and cause exception, but it is ok, as we all we have done so far
  201. // are field init and those dtor will be called if exception occurs
  202. threadContext->EnsureDebugManager();
  203. #endif
  204. // Don't use throwing memory allocation in ctor, as exception in ctor doesn't cause the dtor to be called
  205. // potentially causing memory leaks
  206. BEGIN_NO_EXCEPTION;
  207. #ifdef RUNTIME_DATA_COLLECTION
  208. createTime = time(nullptr);
  209. #endif
  210. #ifdef BGJIT_STATS
  211. interpretedCount = maxFuncInterpret = funcJITCount = bytecodeJITCount = interpretedCallsHighPri = jitCodeUsed = funcJitCodeUsed = loopJITCount = speculativeJitCount = 0;
  212. #endif
  213. #ifdef PROFILE_TYPES
  214. convertNullToSimpleCount = 0;
  215. convertNullToSimpleDictionaryCount = 0;
  216. convertNullToDictionaryCount = 0;
  217. convertDeferredToDictionaryCount = 0;
  218. convertDeferredToSimpleDictionaryCount = 0;
  219. convertSimpleToDictionaryCount = 0;
  220. convertSimpleToSimpleDictionaryCount = 0;
  221. convertPathToDictionaryCount1 = 0;
  222. convertPathToDictionaryCount2 = 0;
  223. convertPathToDictionaryCount3 = 0;
  224. convertPathToDictionaryCount4 = 0;
  225. convertPathToSimpleDictionaryCount = 0;
  226. convertSimplePathToPathCount = 0;
  227. convertSimpleDictionaryToDictionaryCount = 0;
  228. convertSimpleSharedDictionaryToNonSharedCount = 0;
  229. convertSimpleSharedToNonSharedCount = 0;
  230. simplePathTypeHandlerCount = 0;
  231. pathTypeHandlerCount = 0;
  232. promoteCount = 0;
  233. cacheCount = 0;
  234. branchCount = 0;
  235. maxPathLength = 0;
  236. memset(typeCount, 0, sizeof(typeCount));
  237. memset(instanceCount, 0, sizeof(instanceCount));
  238. #endif
  239. #ifdef PROFILE_OBJECT_LITERALS
  240. objectLiteralInstanceCount = 0;
  241. objectLiteralPathCount = 0;
  242. memset(objectLiteralCount, 0, sizeof(objectLiteralCount));
  243. objectLiteralSimpleDictionaryCount = 0;
  244. objectLiteralMaxLength = 0;
  245. objectLiteralPromoteCount = 0;
  246. objectLiteralCacheCount = 0;
  247. objectLiteralBranchCount = 0;
  248. #endif
  249. #if DBG_DUMP
  250. byteCodeDataSize = 0;
  251. byteCodeAuxiliaryDataSize = 0;
  252. byteCodeAuxiliaryContextDataSize = 0;
  253. memset(byteCodeHistogram, 0, sizeof(byteCodeHistogram));
  254. #endif
  255. #if DBG || defined(RUNTIME_DATA_COLLECTION)
  256. this->allocId = threadContext->GetScriptContextCount();
  257. #endif
  258. #if DBG
  259. this->hadProfiled = false;
  260. #endif
  261. #if DBG_DUMP
  262. forinCache = 0;
  263. forinNoCache = 0;
  264. #endif
  265. callCount = 0;
  266. threadContext->GetHiResTimer()->Reset();
  267. #ifdef PROFILE_EXEC
  268. profiler = nullptr;
  269. isProfilerCreated = false;
  270. disableProfiler = false;
  271. ensureParentInfo = false;
  272. #endif
  273. #ifdef PROFILE_MEM
  274. profileMemoryDump = true;
  275. #endif
  276. #ifdef ENABLE_SCRIPT_PROFILING
  277. m_pProfileCallback = nullptr;
  278. m_pProfileCallback2 = nullptr;
  279. m_inProfileCallback = FALSE;
  280. CleanupDocumentContext = nullptr;
  281. #endif
  282. // Do this after all operations that may cause potential exceptions. Note: InitialAllocations may still throw!
  283. numberAllocator.Initialize(this->GetRecycler());
  284. #if DEBUG
  285. m_iProfileSession = -1;
  286. #endif
  287. #ifdef LEAK_REPORT
  288. this->urlRecord = nullptr;
  289. this->isRootTrackerScriptContext = false;
  290. #endif
  291. PERF_COUNTER_INC(Basic, ScriptContext);
  292. PERF_COUNTER_INC(Basic, ScriptContextActive);
  293. END_NO_EXCEPTION;
  294. }
  295. void ScriptContext::InitializeAllocations()
  296. {
  297. this->charClassifier = Anew(GeneralAllocator(), CharClassifier, this);
  298. this->valueOfInlineCache = AllocatorNewZ(InlineCacheAllocator, GetInlineCacheAllocator(), InlineCache);
  299. this->toStringInlineCache = AllocatorNewZ(InlineCacheAllocator, GetInlineCacheAllocator(), InlineCache);
  300. #ifdef REJIT_STATS
  301. rejitReasonCounts = AnewArrayZ(GeneralAllocator(), uint, NumRejitReasons);
  302. rejitReasonCountsCap = AnewArrayZ(GeneralAllocator(), uint, NumRejitReasons);
  303. bailoutReasonCounts = Anew(GeneralAllocator(), BailoutStatsMap, GeneralAllocator());
  304. bailoutReasonCountsCap = Anew(GeneralAllocator(), BailoutStatsMap, GeneralAllocator());
  305. #endif
  306. #ifdef ENABLE_BASIC_TELEMETRY
  307. this->telemetry = Anew(this->TelemetryAllocator(), ScriptContextTelemetry, *this);
  308. #endif
  309. #ifdef PROFILE_STRINGS
  310. if (Js::Configuration::Global.flags.ProfileStrings)
  311. {
  312. stringProfiler = Anew(MiscAllocator(), StringProfiler, threadContext->GetPageAllocator());
  313. }
  314. #endif
  315. intConstPropsOnGlobalObject = Anew(GeneralAllocator(), PropIdSetForConstProp, GeneralAllocator());
  316. intConstPropsOnGlobalUserObject = Anew(GeneralAllocator(), PropIdSetForConstProp, GeneralAllocator());
  317. #if ENABLE_NATIVE_CODEGEN
  318. m_domFastPathHelperMap = HeapNew(JITDOMFastPathHelperMap, &HeapAllocator::Instance, 17);
  319. #endif
  320. #ifdef ENABLE_SCRIPT_DEBUGGING
  321. this->debugContext = HeapNew(DebugContext, this);
  322. #endif
  323. }
  324. #ifdef ENABLE_SCRIPT_DEBUGGING
  325. void ScriptContext::EnsureClearDebugDocument()
  326. {
  327. if (this->sourceList)
  328. {
  329. this->sourceList->Map([=](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef) {
  330. Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  331. if (sourceInfo)
  332. {
  333. sourceInfo->ClearDebugDocument();
  334. }
  335. });
  336. }
  337. }
  338. #endif
  339. void ScriptContext::ShutdownClearSourceLists()
  340. {
  341. if (this->sourceList)
  342. {
  343. // In the unclean shutdown case, we might not have destroyed the script context when
  344. // this is called- in which case, skip doing this work and simply release the source list
  345. // so that it doesn't show up as a leak. Since we're doing unclean shutdown, it's ok to
  346. // skip cleanup here for expediency.
  347. if (this->isClosed)
  348. {
  349. this->MapFunction([this](Js::FunctionBody* functionBody) {
  350. Assert(functionBody->GetScriptContext() == this);
  351. functionBody->CleanupSourceInfo(true);
  352. });
  353. }
  354. #ifdef ENABLE_SCRIPT_DEBUGGING
  355. EnsureClearDebugDocument();
  356. #endif
  357. // Don't need the source list any more so ok to release
  358. this->sourceList.Unroot(this->GetRecycler());
  359. }
  360. if (this->calleeUtf8SourceInfoList)
  361. {
  362. this->calleeUtf8SourceInfoList.Unroot(this->GetRecycler());
  363. }
  364. }
  365. ScriptContext::~ScriptContext()
  366. {
  367. // Take etw rundown lock on this thread context. We are going to change/destroy this scriptContext.
  368. AutoCriticalSection autocs(GetThreadContext()->GetFunctionBodyLock());
  369. #if ENABLE_NATIVE_CODEGEN
  370. if (m_domFastPathHelperMap != nullptr)
  371. {
  372. HeapDelete(m_domFastPathHelperMap);
  373. }
  374. #endif
  375. // TODO: Can we move this on Close()?
  376. ClearHostScriptContext();
  377. if (this->hasProtoOrStoreFieldInlineCache)
  378. {
  379. // TODO (PersistentInlineCaches): It really isn't necessary to clear inline caches in all script contexts.
  380. // Since this script context is being destroyed, the inline cache arena will also go away and release its
  381. // memory back to the page allocator. Thus, we cannot leave this script context's inline caches on the
  382. // thread context's invalidation lists. However, it should suffice to remove this script context's caches
  383. // without touching other script contexts' caches. We could call some form of RemoveInlineCachesFromInvalidationLists()
  384. // on the inline cache allocator, which would walk all inline caches and zap values pointed to by strongRef.
  385. // clear out all inline caches to remove our proto inline caches from the thread context
  386. threadContext->ClearInlineCaches();
  387. ClearInlineCaches();
  388. Assert(!this->hasProtoOrStoreFieldInlineCache);
  389. }
  390. if (this->hasIsInstInlineCache)
  391. {
  392. // clear out all inline caches to remove our proto inline caches from the thread context
  393. threadContext->ClearIsInstInlineCaches();
  394. ClearIsInstInlineCaches();
  395. Assert(!this->hasIsInstInlineCache);
  396. }
  397. // Only call RemoveFromPendingClose if we are in a pending close state.
  398. if (isClosed && !isScriptContextActuallyClosed)
  399. {
  400. threadContext->RemoveFromPendingClose(this);
  401. }
  402. SetIsClosed();
  403. bool closed = Close(true);
  404. // JIT may access number allocator. Need to close the script context first,
  405. // which will close the native code generator and abort any current job on this generator.
  406. numberAllocator.Uninitialize();
  407. ShutdownClearSourceLists();
  408. if (regexStacks)
  409. {
  410. Adelete(RegexAllocator(), regexStacks);
  411. regexStacks = nullptr;
  412. }
  413. if (javascriptLibrary != nullptr)
  414. {
  415. javascriptLibrary->scriptContext = nullptr;
  416. javascriptLibrary = nullptr;
  417. if (closed)
  418. {
  419. // if we just closed, we haven't unpin the object yet.
  420. // We need to null out the script context in the global object first
  421. // before we unpin the global object so that script context dtor doesn't get called twice
  422. #if ENABLE_NATIVE_CODEGEN
  423. Assert(this->IsClosedNativeCodeGenerator());
  424. #endif
  425. if (!GetThreadContext()->IsJSRT())
  426. {
  427. this->recycler->RootRelease(globalObject);
  428. }
  429. }
  430. }
  431. // Normally the JavascriptLibraryBase will unregister the scriptContext from the threadContext.
  432. // In cases where we don't finish initialization e.g. OOM, manually unregister the scriptContext.
  433. if (this->IsRegistered())
  434. {
  435. threadContext->UnregisterScriptContext(this);
  436. }
  437. #if ENABLE_BACKGROUND_PARSING
  438. if (this->backgroundParser != nullptr)
  439. {
  440. BackgroundParser::Delete(this->backgroundParser);
  441. this->backgroundParser = nullptr;
  442. }
  443. #endif
  444. #ifdef ENABLE_SCRIPT_DEBUGGING
  445. if (this->debugContext != nullptr)
  446. {
  447. Assert(this->debugContext->IsClosed());
  448. HeapDelete(this->debugContext);
  449. this->debugContext = nullptr;
  450. }
  451. #endif
  452. #if ENABLE_NATIVE_CODEGEN
  453. if (this->nativeCodeGen != nullptr)
  454. {
  455. DeleteNativeCodeGenerator(this->nativeCodeGen);
  456. nativeCodeGen = NULL;
  457. }
  458. if (jitFuncRangeCache != nullptr)
  459. {
  460. HeapDelete(jitFuncRangeCache);
  461. jitFuncRangeCache = nullptr;
  462. }
  463. #endif
  464. #if DYNAMIC_INTERPRETER_THUNK
  465. if (this->interpreterThunkEmitter != nullptr)
  466. {
  467. HeapDelete(interpreterThunkEmitter);
  468. this->interpreterThunkEmitter = NULL;
  469. }
  470. #endif
  471. #ifdef ASMJS_PLAT
  472. if (this->asmJsInterpreterThunkEmitter != nullptr)
  473. {
  474. HeapDelete(asmJsInterpreterThunkEmitter);
  475. this->asmJsInterpreterThunkEmitter = nullptr;
  476. }
  477. if (this->asmJsCodeGenerator != nullptr)
  478. {
  479. HeapDelete(asmJsCodeGenerator);
  480. this->asmJsCodeGenerator = NULL;
  481. }
  482. #endif
  483. // In case there is something added to the list between close and dtor, just reset the list again
  484. this->weakReferenceDictionaryList.Reset();
  485. #if ENABLE_NATIVE_CODEGEN
  486. if (m_remoteScriptContextAddr)
  487. {
  488. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  489. if (JITManager::GetJITManager()->CleanupScriptContext(&m_remoteScriptContextAddr) == S_OK)
  490. {
  491. Assert(m_remoteScriptContextAddr == nullptr);
  492. }
  493. m_remoteScriptContextAddr = nullptr;
  494. }
  495. #endif
  496. PERF_COUNTER_DEC(Basic, ScriptContext);
  497. }
  498. void ScriptContext::SetUrl(BSTR bstrUrl)
  499. {
  500. // Assumption: this method is never called multiple times
  501. Assert(this->url != nullptr && wcslen(this->url) == 0);
  502. charcount_t length = SysStringLen(bstrUrl) + 1; // Add 1 for the NULL.
  503. char16* urlCopy = AnewArray(this->GeneralAllocator(), char16, length);
  504. js_memcpy_s(urlCopy, (length - 1) * sizeof(char16), bstrUrl, (length - 1) * sizeof(char16));
  505. urlCopy[length - 1] = _u('\0');
  506. this->url = urlCopy;
  507. #ifdef LEAK_REPORT
  508. if (Js::Configuration::Global.flags.IsEnabled(Js::LeakReportFlag))
  509. {
  510. this->urlRecord = LeakReport::LogUrl(urlCopy, this->globalObject);
  511. }
  512. #endif
  513. }
  514. uint ScriptContext::GetNextSourceContextId()
  515. {
  516. Assert(this->Cache()->sourceContextInfoMap ||
  517. this->Cache()->dynamicSourceContextInfoMap);
  518. uint nextSourceContextId = 0;
  519. if (this->Cache()->sourceContextInfoMap)
  520. {
  521. nextSourceContextId = this->Cache()->sourceContextInfoMap->Count();
  522. }
  523. if (this->Cache()->dynamicSourceContextInfoMap)
  524. {
  525. nextSourceContextId += this->Cache()->dynamicSourceContextInfoMap->Count();
  526. }
  527. return nextSourceContextId + 1;
  528. }
  529. // Do most of the Close() work except the final release which could delete the scriptContext.
  530. void ScriptContext::InternalClose()
  531. {
  532. isScriptContextActuallyClosed = true;
  533. PERF_COUNTER_DEC(Basic, ScriptContextActive);
  534. #if DBG_DUMP
  535. if (Js::Configuration::Global.flags.TraceWin8Allocations)
  536. {
  537. Output::Print(_u("MemoryTrace: ScriptContext Close\n"));
  538. Output::Flush();
  539. }
  540. #endif
  541. JS_ETW_INTERNAL(EventWriteJSCRIPT_HOST_SCRIPT_CONTEXT_CLOSE(this));
  542. #if ENABLE_TTD
  543. if(this->TTDWellKnownInfo != nullptr)
  544. {
  545. TT_HEAP_DELETE(TTD::RuntimeContextInfo, this->TTDWellKnownInfo);
  546. this->TTDWellKnownInfo = nullptr;
  547. }
  548. if(this->TTDContextInfo != nullptr)
  549. {
  550. TT_HEAP_DELETE(TTD::ScriptContextTTD, this->TTDContextInfo);
  551. this->TTDContextInfo = nullptr;
  552. }
  553. #endif
  554. #if ENABLE_NATIVE_CODEGEN
  555. if (nativeCodeGen != nullptr)
  556. {
  557. Assert(!isInitialized || this->globalObject != nullptr);
  558. CloseNativeCodeGenerator(this->nativeCodeGen);
  559. }
  560. #endif
  561. {
  562. // Take lock on the function bodies to sync with the etw source rundown if any.
  563. AutoCriticalSection autocs(GetThreadContext()->GetFunctionBodyLock());
  564. if (this->sourceList)
  565. {
  566. bool hasFunctions = false;
  567. this->sourceList->MapUntil([&hasFunctions](int, RecyclerWeakReference<Utf8SourceInfo>* sourceInfoWeakRef) -> bool
  568. {
  569. Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  570. if (sourceInfo)
  571. {
  572. hasFunctions = sourceInfo->HasFunctions();
  573. }
  574. return hasFunctions;
  575. });
  576. if (hasFunctions)
  577. {
  578. // We still need to walk through all the function bodies and call cleanup
  579. // because otherwise ETW events might not get fired if a GC doesn't happen
  580. // and the thread context isn't shut down cleanly (process detach case)
  581. this->MapFunction([this](Js::FunctionBody* functionBody) {
  582. Assert(functionBody->GetScriptContext() == nullptr || functionBody->GetScriptContext() == this);
  583. functionBody->Cleanup(/* isScriptContextClosing */ true);
  584. });
  585. }
  586. }
  587. }
  588. this->GetThreadContext()->SubSourceSize(this->GetSourceSize());
  589. #if DYNAMIC_INTERPRETER_THUNK
  590. if (this->interpreterThunkEmitter != nullptr)
  591. {
  592. this->interpreterThunkEmitter->Close();
  593. }
  594. #endif
  595. #ifdef ASMJS_PLAT
  596. if (this->asmJsInterpreterThunkEmitter != nullptr)
  597. {
  598. this->asmJsInterpreterThunkEmitter->Close();
  599. }
  600. #endif
  601. #ifdef ENABLE_SCRIPT_PROFILING
  602. // Stop profiling if present
  603. DeRegisterProfileProbe(S_OK, nullptr);
  604. #endif
  605. #ifdef ENABLE_SCRIPT_DEBUGGING
  606. this->EnsureClearDebugDocument();
  607. if (this->debugContext != nullptr)
  608. {
  609. if (this->debugContext->GetProbeContainer() != nullptr)
  610. {
  611. this->debugContext->GetProbeContainer()->UninstallInlineBreakpointProbe(nullptr);
  612. this->debugContext->GetProbeContainer()->UninstallDebuggerScriptOptionCallback();
  613. }
  614. // Guard the closing DebugContext as in meantime PDM might call OnBreakFlagChange
  615. AutoCriticalSection autoDebugContextCloseCS(&debugContextCloseCS);
  616. this->debugContext->Close();
  617. // Not deleting debugContext here as Close above will clear all memory debugContext allocated.
  618. // Actual deletion of debugContext will happen in ScriptContext destructor
  619. }
  620. if (this->diagnosticArena != nullptr)
  621. {
  622. HeapDelete(this->diagnosticArena);
  623. this->diagnosticArena = nullptr;
  624. }
  625. #endif
  626. // Need to print this out before the native code gen is deleted
  627. // which will delete the codegenProfiler
  628. #ifdef PROFILE_EXEC
  629. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  630. {
  631. if (isProfilerCreated)
  632. {
  633. this->ProfilePrint();
  634. }
  635. if (profiler != nullptr)
  636. {
  637. profiler->Release();
  638. profiler = nullptr;
  639. }
  640. }
  641. #endif
  642. #if ENABLE_PROFILE_INFO
  643. // Release this only after native code gen is shut down, as there may be
  644. // profile info allocated from the SourceDynamicProfileManager arena.
  645. // The first condition might not be true if the dynamic functions have already been freed by the time
  646. // ScriptContext closes
  647. if (referencesSharedDynamicSourceContextInfo)
  648. {
  649. // For the host provided dynamic code, we may not have added any dynamic context to the dynamicSourceContextInfoMap
  650. Assert(this->GetDynamicSourceContextInfoMap() != nullptr);
  651. this->GetThreadContext()->ReleaseSourceDynamicProfileManagers(this->GetUrl());
  652. }
  653. #endif
  654. RECYCLER_PERF_COUNTER_SUB(BindReference, bindReferenceCount);
  655. if (this->interpreterArena)
  656. {
  657. ReleaseInterpreterArena();
  658. interpreterArena = nullptr;
  659. }
  660. if (this->guestArena)
  661. {
  662. ReleaseGuestArena();
  663. guestArena = nullptr;
  664. }
  665. builtInLibraryFunctions = nullptr;
  666. pActiveScriptDirect = nullptr;
  667. isWeakReferenceDictionaryListCleared = true;
  668. this->weakReferenceDictionaryList.Clear(this->GeneralAllocator());
  669. if (registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext != nullptr)
  670. {
  671. // UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext may throw, set up the correct state first
  672. ScriptContext ** registeredScriptContext = registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext;
  673. ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches();
  674. Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr);
  675. threadContext->UnregisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(registeredScriptContext);
  676. }
  677. #ifdef ENABLE_SCRIPT_DEBUGGING
  678. threadContext->ReleaseDebugManager();
  679. #endif
  680. // This can be null if the script context initialization threw
  681. // and InternalClose gets called in the destructor code path
  682. if (javascriptLibrary != nullptr)
  683. {
  684. javascriptLibrary->CleanupForClose();
  685. javascriptLibrary->Uninitialize();
  686. this->ClearScriptContextCaches();
  687. }
  688. }
  689. bool ScriptContext::Close(bool inDestructor)
  690. {
  691. if (isScriptContextActuallyClosed)
  692. return false;
  693. InternalClose();
  694. if (!inDestructor && globalObject != nullptr)
  695. {
  696. //A side effect of releasing globalObject that this script context could be deleted, so the release call here
  697. //must be the last thing in close.
  698. #if ENABLE_NATIVE_CODEGEN
  699. Assert(this->IsClosedNativeCodeGenerator());
  700. #endif
  701. if (!GetThreadContext()->IsJSRT())
  702. {
  703. GetRecycler()->RootRelease(globalObject);
  704. }
  705. globalObject = nullptr;
  706. }
  707. // A script context closing is a signal to the thread context that it
  708. // needs to do an idle GC independent of what the heuristics are
  709. this->threadContext->SetForceOneIdleCollection();
  710. return true;
  711. }
  712. PropertyString* ScriptContext::GetPropertyString2(char16 ch1, char16 ch2)
  713. {
  714. if (ch1 < '0' || ch1 > 'z' || ch2 < '0' || ch2 > 'z')
  715. {
  716. return NULL;
  717. }
  718. const uint i = PropertyStringMap::PStrMapIndex(ch1);
  719. if (this->Cache()->propertyStrings[i] == NULL)
  720. {
  721. return NULL;
  722. }
  723. const uint j = PropertyStringMap::PStrMapIndex(ch2);
  724. return this->Cache()->propertyStrings[i]->strLen2[j];
  725. }
  726. void ScriptContext::FindPropertyRecord(JavascriptString *pstName, PropertyRecord const ** propertyRecord)
  727. {
  728. threadContext->FindPropertyRecord(pstName, propertyRecord);
  729. }
  730. void ScriptContext::FindPropertyRecord(__in LPCWSTR propertyName, __in int propertyNameLength, PropertyRecord const ** propertyRecord)
  731. {
  732. threadContext->FindPropertyRecord(propertyName, propertyNameLength, propertyRecord);
  733. }
  734. JsUtil::List<const RecyclerWeakReference<Js::PropertyRecord const>*>* ScriptContext::FindPropertyIdNoCase(__in LPCWSTR propertyName, __in int propertyNameLength)
  735. {
  736. return threadContext->FindPropertyIdNoCase(this, propertyName, propertyNameLength);
  737. }
  738. PropertyId ScriptContext::GetOrAddPropertyIdTracked(JsUtil::CharacterBuffer<WCHAR> const& propName)
  739. {
  740. Js::PropertyRecord const * propertyRecord = nullptr;
  741. threadContext->GetOrAddPropertyId(propName, &propertyRecord);
  742. this->TrackPid(propertyRecord);
  743. return propertyRecord->GetPropertyId();
  744. }
  745. void ScriptContext::GetOrAddPropertyRecord(JsUtil::CharacterBuffer<WCHAR> const& propertyName, PropertyRecord const ** propertyRecord)
  746. {
  747. threadContext->GetOrAddPropertyId(propertyName, propertyRecord);
  748. }
  749. PropertyId ScriptContext::GetOrAddPropertyIdTracked(__in_ecount(propertyNameLength) LPCWSTR propertyName, __in int propertyNameLength)
  750. {
  751. Js::PropertyRecord const * propertyRecord = nullptr;
  752. threadContext->GetOrAddPropertyId(propertyName, propertyNameLength, &propertyRecord);
  753. if (propertyNameLength == 2)
  754. {
  755. CachePropertyString2(propertyRecord);
  756. }
  757. this->TrackPid(propertyRecord);
  758. return propertyRecord->GetPropertyId();
  759. }
  760. void ScriptContext::GetOrAddPropertyRecord(__in_ecount(propertyNameLength) LPCWSTR propertyName, __in int propertyNameLength, PropertyRecord const ** propertyRecord)
  761. {
  762. threadContext->GetOrAddPropertyId(propertyName, propertyNameLength, propertyRecord);
  763. if (propertyNameLength == 2)
  764. {
  765. CachePropertyString2(*propertyRecord);
  766. }
  767. }
  768. BOOL ScriptContext::IsNumericPropertyId(PropertyId propertyId, uint32* value)
  769. {
  770. BOOL isNumericPropertyId = threadContext->IsNumericPropertyId(propertyId, value);
  771. #if DEBUG
  772. PropertyRecord const * name = this->GetPropertyName(propertyId);
  773. if (name != nullptr)
  774. {
  775. // Symbol properties are not numeric - description should not be used.
  776. if (name->IsSymbol())
  777. {
  778. return false;
  779. }
  780. uint32 index;
  781. BOOL isIndex = JavascriptArray::GetIndex(name->GetBuffer(), &index);
  782. if (isNumericPropertyId != isIndex)
  783. {
  784. // WOOB 1137798: JavascriptArray::GetIndex does not handle embedded NULLs. So if we have a property
  785. // name "1234\0", JavascriptArray::GetIndex would incorrectly accepts it as an array index property
  786. // name.
  787. Assert((size_t)(name->GetLength()) != wcslen(name->GetBuffer()));
  788. }
  789. else if (isNumericPropertyId)
  790. {
  791. Assert((uint32)*value == index);
  792. }
  793. }
  794. #endif
  795. return isNumericPropertyId;
  796. }
  797. void ScriptContext::RegisterWeakReferenceDictionary(JsUtil::IWeakReferenceDictionary* weakReferenceDictionary)
  798. {
  799. this->weakReferenceDictionaryList.Prepend(this->GeneralAllocator(), weakReferenceDictionary);
  800. }
  801. RecyclableObject *ScriptContext::GetMissingPropertyResult()
  802. {
  803. return GetLibrary()->GetUndefined();
  804. }
  805. RecyclableObject *ScriptContext::GetMissingItemResult()
  806. {
  807. return GetLibrary()->GetUndefined();
  808. }
  809. SRCINFO *ScriptContext::AddHostSrcInfo(SRCINFO const *pSrcInfo)
  810. {
  811. Assert(pSrcInfo != nullptr);
  812. return RecyclerNewZ(this->GetRecycler(), SRCINFO, *pSrcInfo);
  813. }
  814. #ifdef PROFILE_TYPES
  815. void ScriptContext::ProfileTypes()
  816. {
  817. Output::Print(_u("===============================================================================\n"));
  818. Output::Print(_u("Types Profile %s\n"), this->url);
  819. Output::Print(_u("-------------------------------------------------------------------------------\n"));
  820. Output::Print(_u("Dynamic Type Conversions:\n"));
  821. Output::Print(_u(" Null to Simple %8d\n"), convertNullToSimpleCount);
  822. Output::Print(_u(" Deferred to SimpleMap %8d\n"), convertDeferredToSimpleDictionaryCount);
  823. Output::Print(_u(" Simple to Map %8d\n"), convertSimpleToDictionaryCount);
  824. Output::Print(_u(" Simple to SimpleMap %8d\n"), convertSimpleToSimpleDictionaryCount);
  825. Output::Print(_u(" Path to SimpleMap (set) %8d\n"), convertPathToDictionaryCount1);
  826. Output::Print(_u(" Path to SimpleMap (delete) %8d\n"), convertPathToDictionaryCount2);
  827. Output::Print(_u(" Path to SimpleMap (attribute) %8d\n"), convertPathToDictionaryCount3);
  828. Output::Print(_u(" Path to SimpleMap %8d\n"), convertPathToSimpleDictionaryCount);
  829. Output::Print(_u(" SimplePath to Path %8d\n"), convertSimplePathToPathCount);
  830. Output::Print(_u(" Shared SimpleMap to non-shared %8d\n"), convertSimpleSharedDictionaryToNonSharedCount);
  831. Output::Print(_u(" Deferred to Map %8d\n"), convertDeferredToDictionaryCount);
  832. Output::Print(_u(" Path to Map (accessor) %8d\n"), convertPathToDictionaryCount4);
  833. Output::Print(_u(" SimpleMap to Map %8d\n"), convertSimpleDictionaryToDictionaryCount);
  834. Output::Print(_u(" Path Cache Hits %8d\n"), cacheCount);
  835. Output::Print(_u(" Path Branches %8d\n"), branchCount);
  836. Output::Print(_u(" Path Promotions %8d\n"), promoteCount);
  837. Output::Print(_u(" Path Length (max) %8d\n"), maxPathLength);
  838. Output::Print(_u(" SimplePathTypeHandlers %8d\n"), simplePathTypeHandlerCount);
  839. Output::Print(_u(" PathTypeHandlers %8d\n"), pathTypeHandlerCount);
  840. Output::Print(_u("\n"));
  841. Output::Print(_u("Type Statistics: %8s %8s\n"), _u("Types"), _u("Instances"));
  842. Output::Print(_u(" Undefined %8d %8d\n"), typeCount[TypeIds_Undefined], instanceCount[TypeIds_Undefined]);
  843. Output::Print(_u(" Null %8d %8d\n"), typeCount[TypeIds_Null], instanceCount[TypeIds_Null]);
  844. Output::Print(_u(" Boolean %8d %8d\n"), typeCount[TypeIds_Boolean], instanceCount[TypeIds_Boolean]);
  845. Output::Print(_u(" Integer %8d %8d\n"), typeCount[TypeIds_Integer], instanceCount[TypeIds_Integer]);
  846. Output::Print(_u(" Number %8d %8d\n"), typeCount[TypeIds_Number], instanceCount[TypeIds_Number]);
  847. Output::Print(_u(" String %8d %8d\n"), typeCount[TypeIds_String], instanceCount[TypeIds_String]);
  848. Output::Print(_u(" Object %8d %8d\n"), typeCount[TypeIds_Object], instanceCount[TypeIds_Object]);
  849. Output::Print(_u(" Function %8d %8d\n"), typeCount[TypeIds_Function], instanceCount[TypeIds_Function]);
  850. Output::Print(_u(" Array %8d %8d\n"), typeCount[TypeIds_Array], instanceCount[TypeIds_Array]);
  851. Output::Print(_u(" Date %8d %8d\n"), typeCount[TypeIds_Date], instanceCount[TypeIds_Date] + instanceCount[TypeIds_WinRTDate]);
  852. Output::Print(_u(" Symbol %8d %8d\n"), typeCount[TypeIds_Symbol], instanceCount[TypeIds_Symbol]);
  853. Output::Print(_u(" RegEx %8d %8d\n"), typeCount[TypeIds_RegEx], instanceCount[TypeIds_RegEx]);
  854. Output::Print(_u(" Error %8d %8d\n"), typeCount[TypeIds_Error], instanceCount[TypeIds_Error]);
  855. Output::Print(_u(" Proxy %8d %8d\n"), typeCount[TypeIds_Proxy], instanceCount[TypeIds_Proxy]);
  856. Output::Print(_u(" BooleanObject %8d %8d\n"), typeCount[TypeIds_BooleanObject], instanceCount[TypeIds_BooleanObject]);
  857. Output::Print(_u(" NumberObject %8d %8d\n"), typeCount[TypeIds_NumberObject], instanceCount[TypeIds_NumberObject]);
  858. Output::Print(_u(" StringObject %8d %8d\n"), typeCount[TypeIds_StringObject], instanceCount[TypeIds_StringObject]);
  859. Output::Print(_u(" SymbolObject %8d %8d\n"), typeCount[TypeIds_SymbolObject], instanceCount[TypeIds_SymbolObject]);
  860. Output::Print(_u(" GlobalObject %8d %8d\n"), typeCount[TypeIds_GlobalObject], instanceCount[TypeIds_GlobalObject]);
  861. Output::Print(_u(" Enumerator %8d %8d\n"), typeCount[TypeIds_Enumerator], instanceCount[TypeIds_Enumerator]);
  862. Output::Print(_u(" Int8Array %8d %8d\n"), typeCount[TypeIds_Int8Array], instanceCount[TypeIds_Int8Array]);
  863. Output::Print(_u(" Uint8Array %8d %8d\n"), typeCount[TypeIds_Uint8Array], instanceCount[TypeIds_Uint8Array]);
  864. Output::Print(_u(" Uint8ClampedArray %8d %8d\n"), typeCount[TypeIds_Uint8ClampedArray], instanceCount[TypeIds_Uint8ClampedArray]);
  865. Output::Print(_u(" Int16Array %8d %8d\n"), typeCount[TypeIds_Int16Array], instanceCount[TypeIds_Int16Array]);
  866. Output::Print(_u(" Int16Array %8d %8d\n"), typeCount[TypeIds_Uint16Array], instanceCount[TypeIds_Uint16Array]);
  867. Output::Print(_u(" Int32Array %8d %8d\n"), typeCount[TypeIds_Int32Array], instanceCount[TypeIds_Int32Array]);
  868. Output::Print(_u(" Uint32Array %8d %8d\n"), typeCount[TypeIds_Uint32Array], instanceCount[TypeIds_Uint32Array]);
  869. Output::Print(_u(" Float32Array %8d %8d\n"), typeCount[TypeIds_Float32Array], instanceCount[TypeIds_Float32Array]);
  870. Output::Print(_u(" Float64Array %8d %8d\n"), typeCount[TypeIds_Float64Array], instanceCount[TypeIds_Float64Array]);
  871. Output::Print(_u(" DataView %8d %8d\n"), typeCount[TypeIds_DataView], instanceCount[TypeIds_DataView]);
  872. Output::Print(_u(" ModuleRoot %8d %8d\n"), typeCount[TypeIds_ModuleRoot], instanceCount[TypeIds_ModuleRoot]);
  873. Output::Print(_u(" HostObject %8d %8d\n"), typeCount[TypeIds_HostObject], instanceCount[TypeIds_HostObject]);
  874. Output::Print(_u(" VariantDate %8d %8d\n"), typeCount[TypeIds_VariantDate], instanceCount[TypeIds_VariantDate]);
  875. Output::Print(_u(" HostDispatch %8d %8d\n"), typeCount[TypeIds_HostDispatch], instanceCount[TypeIds_HostDispatch]);
  876. Output::Print(_u(" Arguments %8d %8d\n"), typeCount[TypeIds_Arguments], instanceCount[TypeIds_Arguments]);
  877. Output::Print(_u(" ActivationObject %8d %8d\n"), typeCount[TypeIds_ActivationObject], instanceCount[TypeIds_ActivationObject]);
  878. Output::Print(_u(" Map %8d %8d\n"), typeCount[TypeIds_Map], instanceCount[TypeIds_Map]);
  879. Output::Print(_u(" Set %8d %8d\n"), typeCount[TypeIds_Set], instanceCount[TypeIds_Set]);
  880. Output::Print(_u(" WeakMap %8d %8d\n"), typeCount[TypeIds_WeakMap], instanceCount[TypeIds_WeakMap]);
  881. Output::Print(_u(" WeakSet %8d %8d\n"), typeCount[TypeIds_WeakSet], instanceCount[TypeIds_WeakSet]);
  882. Output::Print(_u(" ArrayIterator %8d %8d\n"), typeCount[TypeIds_ArrayIterator], instanceCount[TypeIds_ArrayIterator]);
  883. Output::Print(_u(" MapIterator %8d %8d\n"), typeCount[TypeIds_MapIterator], instanceCount[TypeIds_MapIterator]);
  884. Output::Print(_u(" SetIterator %8d %8d\n"), typeCount[TypeIds_SetIterator], instanceCount[TypeIds_SetIterator]);
  885. Output::Print(_u(" StringIterator %8d %8d\n"), typeCount[TypeIds_StringIterator], instanceCount[TypeIds_StringIterator]);
  886. Output::Print(_u(" Generator %8d %8d\n"), typeCount[TypeIds_Generator], instanceCount[TypeIds_Generator]);
  887. #if !DBG
  888. Output::Print(_u(" ** Instance statistics only available on debug builds...\n"));
  889. #endif
  890. Output::Flush();
  891. }
  892. #endif
  893. #ifdef PROFILE_OBJECT_LITERALS
  894. void ScriptContext::ProfileObjectLiteral()
  895. {
  896. Output::Print(_u("===============================================================================\n"));
  897. Output::Print(_u(" Object Lit Instances created.. %d\n"), objectLiteralInstanceCount);
  898. Output::Print(_u(" Object Lit Path Types......... %d\n"), objectLiteralPathCount);
  899. Output::Print(_u(" Object Lit Simple Map......... %d\n"), objectLiteralSimpleDictionaryCount);
  900. Output::Print(_u(" Object Lit Max # of properties %d\n"), objectLiteralMaxLength);
  901. Output::Print(_u(" Object Lit Promote count...... %d\n"), objectLiteralPromoteCount);
  902. Output::Print(_u(" Object Lit Cache Hits......... %d\n"), objectLiteralCacheCount);
  903. Output::Print(_u(" Object Lit Branch count....... %d\n"), objectLiteralBranchCount);
  904. for (int i = 0; i < TypePath::MaxPathTypeHandlerLength; i++)
  905. {
  906. if (objectLiteralCount[i] != 0)
  907. {
  908. Output::Print(_u(" Object Lit properties [ %2d] .. %d\n"), i, objectLiteralCount[i]);
  909. }
  910. }
  911. Output::Flush();
  912. }
  913. #endif
  914. //
  915. // Regex helpers
  916. //
  917. #if ENABLE_REGEX_CONFIG_OPTIONS
  918. UnifiedRegex::RegexStatsDatabase* ScriptContext::GetRegexStatsDatabase()
  919. {
  920. if (regexStatsDatabase == 0)
  921. {
  922. ArenaAllocator* allocator = MiscAllocator();
  923. regexStatsDatabase = Anew(allocator, UnifiedRegex::RegexStatsDatabase, allocator);
  924. }
  925. return regexStatsDatabase;
  926. }
  927. UnifiedRegex::DebugWriter* ScriptContext::GetRegexDebugWriter()
  928. {
  929. if (regexDebugWriter == 0)
  930. {
  931. ArenaAllocator* allocator = MiscAllocator();
  932. regexDebugWriter = Anew(allocator, UnifiedRegex::DebugWriter);
  933. }
  934. return regexDebugWriter;
  935. }
  936. #endif
  937. void ScriptContext::RedeferFunctionBodies(ActiveFunctionSet *pActiveFuncs, uint inactiveThreshold)
  938. {
  939. Assert(!this->IsClosed());
  940. if (!this->IsScriptContextInNonDebugMode())
  941. {
  942. return;
  943. }
  944. // For each active function, collect call counts, update inactive counts, and redefer if appropriate.
  945. // In the redeferral case, we require 2 passes over the set of FunctionBody's.
  946. // This is because a function inlined in a non-redeferred function cannot itself be redeferred.
  947. // So we first need to close over the set of non-redeferrable functions, then go back and redefer
  948. // the eligible candidates.
  949. auto fn = [&](FunctionBody *functionBody) {
  950. bool exec = functionBody->InterpretedSinceCallCountCollection();
  951. functionBody->CollectInterpretedCounts();
  952. functionBody->MapEntryPoints([&](int index, FunctionEntryPointInfo *entryPointInfo) {
  953. if (!entryPointInfo->IsCleanedUp() && entryPointInfo->ExecutedSinceCallCountCollection())
  954. {
  955. exec = true;
  956. }
  957. entryPointInfo->CollectCallCounts();
  958. });
  959. if (exec)
  960. {
  961. functionBody->SetInactiveCount(0);
  962. }
  963. else
  964. {
  965. functionBody->IncrInactiveCount(inactiveThreshold);
  966. }
  967. if (pActiveFuncs)
  968. {
  969. Assert(this->GetThreadContext()->DoRedeferFunctionBodies());
  970. bool doRedefer = functionBody->DoRedeferFunction(inactiveThreshold);
  971. if (!doRedefer)
  972. {
  973. functionBody->UpdateActiveFunctionSet(pActiveFuncs, nullptr);
  974. }
  975. }
  976. };
  977. this->MapFunction(fn);
  978. if (!pActiveFuncs)
  979. {
  980. return;
  981. }
  982. auto fnRedefer = [&](FunctionBody * functionBody) {
  983. Assert(pActiveFuncs);
  984. if (!functionBody->IsActiveFunction(pActiveFuncs))
  985. {
  986. Assert(functionBody->DoRedeferFunction(inactiveThreshold));
  987. functionBody->RedeferFunction();
  988. }
  989. else
  990. {
  991. functionBody->ResetRedeferralAttributes();
  992. }
  993. };
  994. this->MapFunction(fnRedefer);
  995. }
  996. bool ScriptContext::DoUndeferGlobalFunctions() const
  997. {
  998. return CONFIG_FLAG(DeferTopLevelTillFirstCall) && !AutoSystemInfo::Data.IsLowMemoryProcess();
  999. }
  1000. RegexPatternMruMap* ScriptContext::GetDynamicRegexMap() const
  1001. {
  1002. Assert(!isScriptContextActuallyClosed);
  1003. Assert(Cache()->dynamicRegexMap);
  1004. return Cache()->dynamicRegexMap;
  1005. }
  1006. void ScriptContext::SetTrigramAlphabet(UnifiedRegex::TrigramAlphabet * trigramAlphabet)
  1007. {
  1008. this->trigramAlphabet = trigramAlphabet;
  1009. }
  1010. UnifiedRegex::RegexStacks *ScriptContext::RegexStacks()
  1011. {
  1012. UnifiedRegex::RegexStacks * stacks = regexStacks;
  1013. if (stacks)
  1014. {
  1015. return stacks;
  1016. }
  1017. return AllocRegexStacks();
  1018. }
  1019. UnifiedRegex::RegexStacks * ScriptContext::AllocRegexStacks()
  1020. {
  1021. Assert(this->regexStacks == nullptr);
  1022. UnifiedRegex::RegexStacks * stacks = Anew(RegexAllocator(), UnifiedRegex::RegexStacks, threadContext->GetPageAllocator());
  1023. this->regexStacks = stacks;
  1024. return stacks;
  1025. }
  1026. UnifiedRegex::RegexStacks *ScriptContext::SaveRegexStacks()
  1027. {
  1028. Assert(regexStacks);
  1029. const auto saved = regexStacks;
  1030. regexStacks = nullptr;
  1031. return saved;
  1032. }
  1033. void ScriptContext::RestoreRegexStacks(UnifiedRegex::RegexStacks *const stacks)
  1034. {
  1035. Assert(stacks);
  1036. Assert(stacks != regexStacks);
  1037. if (regexStacks)
  1038. {
  1039. Adelete(RegexAllocator(), regexStacks);
  1040. }
  1041. regexStacks = stacks;
  1042. }
  1043. Js::TempArenaAllocatorObject* ScriptContext::GetTemporaryAllocator(LPCWSTR name)
  1044. {
  1045. return this->threadContext->GetTemporaryAllocator(name);
  1046. }
  1047. void ScriptContext::ReleaseTemporaryAllocator(Js::TempArenaAllocatorObject* tempAllocator)
  1048. {
  1049. AssertMsg(tempAllocator != nullptr, "tempAllocator should not be null");
  1050. this->threadContext->ReleaseTemporaryAllocator(tempAllocator);
  1051. }
  1052. Js::TempGuestArenaAllocatorObject* ScriptContext::GetTemporaryGuestAllocator(LPCWSTR name)
  1053. {
  1054. return this->threadContext->GetTemporaryGuestAllocator(name);
  1055. }
  1056. void ScriptContext::ReleaseTemporaryGuestAllocator(Js::TempGuestArenaAllocatorObject* tempGuestAllocator)
  1057. {
  1058. AssertMsg(tempGuestAllocator != nullptr, "tempAllocator should not be null");
  1059. this->threadContext->ReleaseTemporaryGuestAllocator(tempGuestAllocator);
  1060. }
  1061. void ScriptContext::InitializeCache()
  1062. {
  1063. #if ENABLE_PROFILE_INFO
  1064. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  1065. if (DynamicProfileInfo::NeedProfileInfoList())
  1066. {
  1067. this->Cache()->profileInfoList = RecyclerNew(this->GetRecycler(), DynamicProfileInfoList);
  1068. }
  1069. #endif
  1070. #endif
  1071. ClearArray(this->Cache()->propertyStrings, 80);
  1072. this->Cache()->dynamicRegexMap =
  1073. RegexPatternMruMap::New(
  1074. recycler,
  1075. REGEX_CONFIG_FLAG(DynamicRegexMruListSize) <= 0 ? 16 : REGEX_CONFIG_FLAG(DynamicRegexMruListSize));
  1076. SourceContextInfo* sourceContextInfo = RecyclerNewStructZ(this->GetRecycler(), SourceContextInfo);
  1077. sourceContextInfo->dwHostSourceContext = Js::Constants::NoHostSourceContext;
  1078. sourceContextInfo->isHostDynamicDocument = false;
  1079. sourceContextInfo->sourceContextId = Js::Constants::NoSourceContext;
  1080. this->Cache()->noContextSourceContextInfo = sourceContextInfo;
  1081. SRCINFO* srcInfo = RecyclerNewStructZ(this->GetRecycler(), SRCINFO);
  1082. srcInfo->sourceContextInfo = this->Cache()->noContextSourceContextInfo;
  1083. srcInfo->moduleID = kmodGlobal;
  1084. this->Cache()->noContextGlobalSourceInfo = srcInfo;
  1085. }
  1086. void ScriptContext::InitializePreGlobal()
  1087. {
  1088. this->guestArena = this->GetRecycler()->CreateGuestArena(_u("Guest"), Throw::OutOfMemory);
  1089. #if ENABLE_BACKGROUND_PARSING
  1090. if (PHASE_ON1(Js::ParallelParsePhase))
  1091. {
  1092. this->backgroundParser = BackgroundParser::New(this);
  1093. }
  1094. #endif
  1095. #if ENABLE_NATIVE_CODEGEN
  1096. // Create the native code gen before the profiler
  1097. this->nativeCodeGen = NewNativeCodeGenerator(this);
  1098. this->jitFuncRangeCache = HeapNew(JITPageAddrToFuncRangeCache);
  1099. #endif
  1100. #ifdef PROFILE_EXEC
  1101. this->CreateProfiler();
  1102. #endif
  1103. this->operationStack = Anew(GeneralAllocator(), JsUtil::Stack<Var>, GeneralAllocator());
  1104. Tick::InitType();
  1105. }
  1106. void ScriptContext::Initialize()
  1107. {
  1108. SmartFPUControl defaultControl;
  1109. InitializePreGlobal();
  1110. InitializeGlobalObject();
  1111. InitializePostGlobal();
  1112. }
  1113. void ScriptContext::InitializePostGlobal()
  1114. {
  1115. #ifdef ENABLE_SCRIPT_DEBUGGING
  1116. this->GetDebugContext()->Initialize();
  1117. this->GetDebugContext()->GetProbeContainer()->Initialize(this);
  1118. isDebugContextInitialized = true;
  1119. #endif
  1120. #if defined(_M_ARM32_OR_ARM64)
  1121. // We need to ensure that the above write to the isDebugContextInitialized is visible to the debugger thread.
  1122. MemoryBarrier();
  1123. #endif
  1124. AssertMsg(this->CurrentThunk == DefaultEntryThunk, "Creating non default thunk while initializing");
  1125. AssertMsg(this->DeferredParsingThunk == DefaultDeferredParsingThunk, "Creating non default thunk while initializing");
  1126. AssertMsg(this->DeferredDeserializationThunk == DefaultDeferredDeserializeThunk, "Creating non default thunk while initializing");
  1127. #ifdef FIELD_ACCESS_STATS
  1128. this->fieldAccessStatsByFunctionNumber = RecyclerNew(this->recycler, FieldAccessStatsByFunctionNumberMap, recycler);
  1129. BindReference(this->fieldAccessStatsByFunctionNumber);
  1130. #endif
  1131. if (!sourceList)
  1132. {
  1133. AutoCriticalSection critSec(threadContext->GetFunctionBodyLock());
  1134. sourceList.Root(RecyclerNew(this->GetRecycler(), SourceList, this->GetRecycler()), this->GetRecycler());
  1135. }
  1136. #if DYNAMIC_INTERPRETER_THUNK
  1137. interpreterThunkEmitter = HeapNew(InterpreterThunkEmitter, this, SourceCodeAllocator(), this->GetThreadContext()->GetThunkPageAllocators());
  1138. #endif
  1139. #ifdef ASMJS_PLAT
  1140. asmJsInterpreterThunkEmitter = HeapNew(InterpreterThunkEmitter, this, SourceCodeAllocator(), this->GetThreadContext()->GetThunkPageAllocators(),
  1141. true);
  1142. #endif
  1143. JS_ETW(EtwTrace::LogScriptContextLoadEvent(this));
  1144. JS_ETW_INTERNAL(EventWriteJSCRIPT_HOST_SCRIPT_CONTEXT_START(this));
  1145. #ifdef PROFILE_EXEC
  1146. if (profiler != nullptr)
  1147. {
  1148. this->threadContext->GetRecycler()->SetProfiler(profiler->GetProfiler(), profiler->GetBackgroundRecyclerProfiler());
  1149. }
  1150. #endif
  1151. #if DBG
  1152. this->javascriptLibrary->DumpLibraryByteCode();
  1153. isInitialized = TRUE;
  1154. #endif
  1155. }
  1156. #ifdef ASMJS_PLAT
  1157. AsmJsCodeGenerator* ScriptContext::InitAsmJsCodeGenerator()
  1158. {
  1159. if( !asmJsCodeGenerator )
  1160. {
  1161. asmJsCodeGenerator = HeapNew( AsmJsCodeGenerator, this );
  1162. }
  1163. return asmJsCodeGenerator;
  1164. }
  1165. #endif
  1166. void ScriptContext::MarkForClose()
  1167. {
  1168. if (IsClosed())
  1169. {
  1170. return;
  1171. }
  1172. SaveStartupProfileAndRelease(true);
  1173. SetIsClosed();
  1174. #ifdef LEAK_REPORT
  1175. if (this->isRootTrackerScriptContext)
  1176. {
  1177. this->GetThreadContext()->ClearRootTrackerScriptContext(this);
  1178. }
  1179. #endif
  1180. if (!threadContext->IsInScript())
  1181. {
  1182. Close(FALSE);
  1183. }
  1184. else
  1185. {
  1186. threadContext->AddToPendingScriptContextCloseList(this);
  1187. }
  1188. }
  1189. void ScriptContext::SetIsClosed()
  1190. {
  1191. if (!this->isClosed)
  1192. {
  1193. this->isClosed = true;
  1194. if (this->javascriptLibrary)
  1195. {
  1196. JS_ETW(EtwTrace::LogSourceUnloadEvents(this));
  1197. #if ENABLE_PROFILE_INFO
  1198. #if DBG_DUMP
  1199. DynamicProfileInfo::DumpScriptContext(this);
  1200. #endif
  1201. #ifdef RUNTIME_DATA_COLLECTION
  1202. DynamicProfileInfo::DumpScriptContextToFile(this);
  1203. #endif
  1204. #endif
  1205. #if ENABLE_PROFILE_INFO
  1206. #ifdef DYNAMIC_PROFILE_STORAGE
  1207. HRESULT hr = S_OK;
  1208. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  1209. {
  1210. DynamicProfileInfo::Save(this);
  1211. }
  1212. END_TRANSLATE_OOM_TO_HRESULT(hr);
  1213. if (this->Cache()->sourceContextInfoMap)
  1214. {
  1215. this->Cache()->sourceContextInfoMap->Map([&](DWORD_PTR dwHostSourceContext, SourceContextInfo * sourceContextInfo)
  1216. {
  1217. if (sourceContextInfo->sourceDynamicProfileManager)
  1218. {
  1219. sourceContextInfo->sourceDynamicProfileManager->ClearSavingData();
  1220. }
  1221. });
  1222. }
  1223. #endif
  1224. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  1225. this->ClearDynamicProfileList();
  1226. #endif
  1227. #endif
  1228. }
  1229. #if ENABLE_NATIVE_CODEGEN
  1230. if (m_remoteScriptContextAddr)
  1231. {
  1232. JITManager::GetJITManager()->CloseScriptContext(m_remoteScriptContextAddr);
  1233. }
  1234. #endif
  1235. this->PrintStats();
  1236. }
  1237. }
  1238. void ScriptContext::InitializeGlobalObject()
  1239. {
  1240. GlobalObject * localGlobalObject = GlobalObject::New(this);
  1241. GetRecycler()->RootAddRef(localGlobalObject);
  1242. // Assigned the global Object after we have successfully AddRef (in case of OOM)
  1243. globalObject = localGlobalObject;
  1244. globalObject->Initialize(this);
  1245. this->GetThreadContext()->RegisterScriptContext(this);
  1246. }
  1247. #ifdef ENABLE_SCRIPT_DEBUGGING
  1248. ArenaAllocator* ScriptContext::AllocatorForDiagnostics()
  1249. {
  1250. if (this->diagnosticArena == nullptr)
  1251. {
  1252. this->diagnosticArena = HeapNew(ArenaAllocator, _u("Diagnostic"), this->GetThreadContext()->GetDebugManager()->GetDiagnosticPageAllocator(), Throw::OutOfMemory);
  1253. }
  1254. Assert(this->diagnosticArena != nullptr);
  1255. return this->diagnosticArena;
  1256. }
  1257. #endif
  1258. void ScriptContext::PushObject(Var object)
  1259. {
  1260. operationStack->Push(object);
  1261. }
  1262. Var ScriptContext::PopObject()
  1263. {
  1264. return operationStack->Pop();
  1265. }
  1266. BOOL ScriptContext::CheckObject(Var object)
  1267. {
  1268. return operationStack->Contains(object);
  1269. }
  1270. void ScriptContext::SetHostScriptContext(HostScriptContext * hostScriptContext)
  1271. {
  1272. Assert(this->hostScriptContext == nullptr);
  1273. this->hostScriptContext = hostScriptContext;
  1274. #ifdef PROFILE_EXEC
  1275. this->ensureParentInfo = true;
  1276. #endif
  1277. }
  1278. //
  1279. // Enables chakradiag to get the HaltCallBack pointer that is implemented by
  1280. // the ScriptEngine.
  1281. //
  1282. void ScriptContext::SetScriptEngineHaltCallback(HaltCallback* scriptEngine)
  1283. {
  1284. Assert(this->scriptEngineHaltCallback == NULL);
  1285. Assert(scriptEngine != NULL);
  1286. this->scriptEngineHaltCallback = scriptEngine;
  1287. }
  1288. void ScriptContext::ClearHostScriptContext()
  1289. {
  1290. if (this->hostScriptContext != nullptr)
  1291. {
  1292. this->hostScriptContext->Delete();
  1293. #ifdef PROFILE_EXEC
  1294. this->ensureParentInfo = false;
  1295. #endif
  1296. }
  1297. }
  1298. IActiveScriptProfilerHeapEnum* ScriptContext::GetHeapEnum()
  1299. {
  1300. Assert(this->GetThreadContext());
  1301. return this->GetThreadContext()->GetHeapEnum();
  1302. }
  1303. void ScriptContext::SetHeapEnum(IActiveScriptProfilerHeapEnum* newHeapEnum)
  1304. {
  1305. Assert(this->GetThreadContext());
  1306. this->GetThreadContext()->SetHeapEnum(newHeapEnum);
  1307. }
  1308. void ScriptContext::ClearHeapEnum()
  1309. {
  1310. Assert(this->GetThreadContext());
  1311. this->GetThreadContext()->ClearHeapEnum();
  1312. }
  1313. BOOL ScriptContext::VerifyAlive(BOOL isJSFunction, ScriptContext* requestScriptContext)
  1314. {
  1315. if (isClosed)
  1316. {
  1317. if (!requestScriptContext)
  1318. {
  1319. requestScriptContext = this;
  1320. }
  1321. #if ENABLE_PROFILE_INFO
  1322. if (!GetThreadContext()->RecordImplicitException())
  1323. {
  1324. return FALSE;
  1325. }
  1326. #endif
  1327. if (isJSFunction)
  1328. {
  1329. Js::JavascriptError::MapAndThrowError(requestScriptContext, JSERR_CantExecute);
  1330. }
  1331. else
  1332. {
  1333. Js::JavascriptError::MapAndThrowError(requestScriptContext, E_ACCESSDENIED);
  1334. }
  1335. }
  1336. return TRUE;
  1337. }
  1338. void ScriptContext::VerifyAliveWithHostContext(BOOL isJSFunction, HostScriptContext* requestHostScriptContext)
  1339. {
  1340. if (requestHostScriptContext)
  1341. {
  1342. VerifyAlive(isJSFunction, requestHostScriptContext->GetScriptContext());
  1343. }
  1344. else
  1345. {
  1346. Assert(GetThreadContext()->IsJSRT() || !GetHostScriptContext()->HasCaller());
  1347. VerifyAlive(isJSFunction, NULL);
  1348. }
  1349. }
  1350. PropertyRecord const * ScriptContext::GetPropertyName(PropertyId propertyId)
  1351. {
  1352. return threadContext->GetPropertyName(propertyId);
  1353. }
  1354. PropertyRecord const * ScriptContext::GetPropertyNameLocked(PropertyId propertyId)
  1355. {
  1356. return threadContext->GetPropertyNameLocked(propertyId);
  1357. }
  1358. void ScriptContext::InitPropertyStringMap(int i)
  1359. {
  1360. this->Cache()->propertyStrings[i] = RecyclerNewStruct(GetRecycler(), PropertyStringMap);
  1361. ClearArray(this->Cache()->propertyStrings[i]->strLen2, 80);
  1362. }
  1363. void ScriptContext::TrackPid(const PropertyRecord* propertyRecord)
  1364. {
  1365. if (IsBuiltInPropertyId(propertyRecord->GetPropertyId()) || propertyRecord->IsBound())
  1366. {
  1367. return;
  1368. }
  1369. if (-1 != this->GetLibrary()->EnsureReferencedPropertyRecordList()->AddNew(propertyRecord))
  1370. {
  1371. RECYCLER_PERF_COUNTER_INC(PropertyRecordBindReference);
  1372. }
  1373. }
  1374. void ScriptContext::TrackPid(PropertyId propertyId)
  1375. {
  1376. if (IsBuiltInPropertyId(propertyId))
  1377. {
  1378. return;
  1379. }
  1380. const PropertyRecord* propertyRecord = this->GetPropertyName(propertyId);
  1381. Assert(propertyRecord != nullptr);
  1382. this->TrackPid(propertyRecord);
  1383. }
  1384. bool ScriptContext::IsTrackedPropertyId(Js::PropertyId propertyId)
  1385. {
  1386. if (IsBuiltInPropertyId(propertyId))
  1387. {
  1388. return true;
  1389. }
  1390. const PropertyRecord* propertyRecord = this->GetPropertyName(propertyId);
  1391. Assert(propertyRecord != nullptr);
  1392. if (propertyRecord->IsBound())
  1393. {
  1394. return true;
  1395. }
  1396. JavascriptLibrary::ReferencedPropertyRecordHashSet * referencedPropertyRecords
  1397. = this->GetLibrary()->GetReferencedPropertyRecordList();
  1398. return referencedPropertyRecords && referencedPropertyRecords->Contains(propertyRecord);
  1399. }
  1400. PropertyString* ScriptContext::AddPropertyString2(const Js::PropertyRecord* propString)
  1401. {
  1402. const char16* buf = propString->GetBuffer();
  1403. const uint i = PropertyStringMap::PStrMapIndex(buf[0]);
  1404. if (this->Cache()->propertyStrings[i] == NULL)
  1405. {
  1406. InitPropertyStringMap(i);
  1407. }
  1408. const uint j = PropertyStringMap::PStrMapIndex(buf[1]);
  1409. if (this->Cache()->propertyStrings[i]->strLen2[j] == NULL && !isClosed)
  1410. {
  1411. this->Cache()->propertyStrings[i]->strLen2[j] = GetLibrary()->CreatePropertyString(propString);
  1412. this->TrackPid(propString);
  1413. }
  1414. return this->Cache()->propertyStrings[i]->strLen2[j];
  1415. }
  1416. PropertyString* ScriptContext::CachePropertyString2(const PropertyRecord* propString)
  1417. {
  1418. Assert(propString->GetLength() == 2);
  1419. const char16* propertyName = propString->GetBuffer();
  1420. if ((propertyName[0] <= 'z') && (propertyName[1] <= 'z') && (propertyName[0] >= '0') && (propertyName[1] >= '0') && ((propertyName[0] > '9') || (propertyName[1] > '9')))
  1421. {
  1422. return AddPropertyString2(propString);
  1423. }
  1424. return NULL;
  1425. }
  1426. PropertyString* ScriptContext::TryGetPropertyString(PropertyId propertyId)
  1427. {
  1428. PropertyStringCacheMap* propertyStringMap = this->GetLibrary()->EnsurePropertyStringMap();
  1429. RecyclerWeakReference<PropertyString>* stringReference = nullptr;
  1430. if (propertyStringMap->TryGetValue(propertyId, &stringReference))
  1431. {
  1432. PropertyString *string = stringReference->Get();
  1433. if (string != nullptr)
  1434. {
  1435. return string;
  1436. }
  1437. }
  1438. return nullptr;
  1439. }
  1440. PropertyString* ScriptContext::GetPropertyString(PropertyId propertyId)
  1441. {
  1442. PropertyString *string = TryGetPropertyString(propertyId);
  1443. if (string != nullptr)
  1444. {
  1445. return string;
  1446. }
  1447. PropertyStringCacheMap* propertyStringMap = this->GetLibrary()->EnsurePropertyStringMap();
  1448. const Js::PropertyRecord* propertyName = this->GetPropertyName(propertyId);
  1449. string = this->GetLibrary()->CreatePropertyString(propertyName);
  1450. propertyStringMap->Item(propertyId, recycler->CreateWeakReferenceHandle(string));
  1451. return string;
  1452. }
  1453. void ScriptContext::InvalidatePropertyStringCache(PropertyId propertyId, Type* type)
  1454. {
  1455. Assert(!isFinalized);
  1456. PropertyStringCacheMap* propertyStringMap = this->javascriptLibrary->GetPropertyStringMap();
  1457. if (propertyStringMap != nullptr)
  1458. {
  1459. PropertyString *string = nullptr;
  1460. RecyclerWeakReference<PropertyString>* stringReference = nullptr;
  1461. if (propertyStringMap->TryGetValue(propertyId, &stringReference))
  1462. {
  1463. string = stringReference->Get();
  1464. }
  1465. if (string)
  1466. {
  1467. PolymorphicInlineCache * cache = string->GetLdElemInlineCache();
  1468. PropertyCacheOperationInfo info;
  1469. if (cache->PretendTryGetProperty(type, &info))
  1470. {
  1471. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1472. if (PHASE_TRACE1(PropertyStringCachePhase))
  1473. {
  1474. Output::Print(_u("PropertyString '%s' : Invalidating LdElem cache for type %p\n"), string->GetString(), type);
  1475. }
  1476. #endif
  1477. cache->GetInlineCaches()[cache->GetInlineCacheIndexForType(type)].RemoveFromInvalidationListAndClear(this->GetThreadContext());
  1478. }
  1479. cache = string->GetStElemInlineCache();
  1480. if (cache->PretendTrySetProperty(type, type, &info))
  1481. {
  1482. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1483. if (PHASE_TRACE1(PropertyStringCachePhase))
  1484. {
  1485. Output::Print(_u("PropertyString '%s' : Invalidating StElem cache for type %p\n"), string->GetString(), type);
  1486. }
  1487. #endif
  1488. cache->GetInlineCaches()[cache->GetInlineCacheIndexForType(type)].RemoveFromInvalidationListAndClear(this->GetThreadContext());
  1489. }
  1490. }
  1491. }
  1492. }
  1493. void ScriptContext::CleanupWeakReferenceDictionaries()
  1494. {
  1495. if (!isWeakReferenceDictionaryListCleared)
  1496. {
  1497. SListBase<JsUtil::IWeakReferenceDictionary*>::Iterator iter(&this->weakReferenceDictionaryList);
  1498. while (iter.Next())
  1499. {
  1500. JsUtil::IWeakReferenceDictionary* weakReferenceDictionary = iter.Data();
  1501. weakReferenceDictionary->Cleanup();
  1502. }
  1503. }
  1504. }
  1505. JavascriptString* ScriptContext::GetIntegerString(Var aValue)
  1506. {
  1507. return this->GetIntegerString(TaggedInt::ToInt32(aValue));
  1508. }
  1509. JavascriptString* ScriptContext::GetIntegerString(uint value)
  1510. {
  1511. if (value <= INT_MAX)
  1512. {
  1513. return this->GetIntegerString((int)value);
  1514. }
  1515. return TaggedInt::ToString(value, this);
  1516. }
  1517. JavascriptString* ScriptContext::GetIntegerString(int value)
  1518. {
  1519. // Optimize for 0-9
  1520. if (0 <= value && value <= 9)
  1521. {
  1522. return GetLibrary()->GetCharStringCache().GetStringForCharA('0' + static_cast<char>(value));
  1523. }
  1524. JavascriptString *string;
  1525. // TODO: (obastemur) Could this be dynamic instead of compile time?
  1526. #ifndef CC_LOW_MEMORY_TARGET // we don't need this on a target with low memory
  1527. if (this->Cache()->integerStringMap == nullptr)
  1528. {
  1529. this->Cache()->integerStringMap = RecyclerNew(GetRecycler(), StringMap, GetRecycler());
  1530. }
  1531. StringMap * integerStringMap = this->Cache()->integerStringMap;
  1532. if (!integerStringMap->TryGetValue(value, &string))
  1533. {
  1534. // Add the string to hash table cache
  1535. // Don't add if table is getting too full. We'll be holding on to
  1536. // too many strings, and table lookup will become too slow.
  1537. // TODO: Long term running app, this cache doesn't provide much value?
  1538. // i.e. what is the importance of first 512 number to string calls?
  1539. // a solution; count the number of times we couldn't use cache
  1540. // after cache is full. If it's bigger than X ?? the discard the
  1541. // previous cache?
  1542. if (integerStringMap->Count() > 512)
  1543. {
  1544. #endif
  1545. // Use recycler memory
  1546. string = TaggedInt::ToString(value, this);
  1547. #ifndef CC_LOW_MEMORY_TARGET
  1548. }
  1549. else
  1550. {
  1551. char16 stringBuffer[22];
  1552. int pos = TaggedInt::ToBuffer(value, stringBuffer, _countof(stringBuffer));
  1553. string = JavascriptString::NewCopyBuffer(stringBuffer + pos, (_countof(stringBuffer) - 1) - pos, this);
  1554. integerStringMap->AddNew(value, string);
  1555. }
  1556. }
  1557. #endif
  1558. return string;
  1559. }
  1560. void ScriptContext::CheckEvalRestriction()
  1561. {
  1562. HRESULT hr = S_OK;
  1563. Var domError = nullptr;
  1564. HostScriptContext* hostScriptContext = this->GetHostScriptContext();
  1565. BEGIN_LEAVE_SCRIPT(this)
  1566. {
  1567. if (!FAILED(hr = hostScriptContext->CheckEvalRestriction()))
  1568. {
  1569. return;
  1570. }
  1571. hr = hostScriptContext->HostExceptionFromHRESULT(hr, &domError);
  1572. }
  1573. END_LEAVE_SCRIPT(this);
  1574. if (FAILED(hr))
  1575. {
  1576. Js::JavascriptError::MapAndThrowError(this, hr);
  1577. }
  1578. if (domError != nullptr)
  1579. {
  1580. JavascriptExceptionOperators::Throw(domError, this);
  1581. }
  1582. AssertMsg(false, "We should have thrown by now.");
  1583. Js::JavascriptError::MapAndThrowError(this, E_FAIL);
  1584. }
  1585. ParseNode* ScriptContext::ParseScript(Parser* parser,
  1586. const byte* script,
  1587. size_t cb,
  1588. SRCINFO const * pSrcInfo,
  1589. CompileScriptException * pse,
  1590. Utf8SourceInfo** ppSourceInfo,
  1591. const char16 *rootDisplayName,
  1592. LoadScriptFlag loadScriptFlag,
  1593. uint* sourceIndex,
  1594. Js::Var scriptSource)
  1595. {
  1596. if (pSrcInfo == nullptr)
  1597. {
  1598. pSrcInfo = this->Cache()->noContextGlobalSourceInfo;
  1599. }
  1600. LPUTF8 utf8Script = nullptr;
  1601. size_t length = cb;
  1602. size_t cbNeeded = 0;
  1603. bool isLibraryCode = ((loadScriptFlag & LoadScriptFlag_LibraryCode) == LoadScriptFlag_LibraryCode);
  1604. if ((loadScriptFlag & LoadScriptFlag_Utf8Source) != LoadScriptFlag_Utf8Source)
  1605. {
  1606. // Convert to UTF8 and then load that
  1607. length = cb / sizeof(char16);
  1608. if (!IsValidCharCount(length))
  1609. {
  1610. Js::Throw::OutOfMemory();
  1611. }
  1612. Assert(length < MAXLONG);
  1613. // Allocate memory for the UTF8 output buffer.
  1614. // We need at most 3 bytes for each Unicode code point.
  1615. // The + 1 is to include the terminating NUL.
  1616. // Nit: Technically, we know that the NUL only needs 1 byte instead of
  1617. // 3, but that's difficult to express in a SAL annotation for "EncodeInto".
  1618. size_t cbUtf8Buffer = AllocSizeMath::Mul(AllocSizeMath::Add(length, 1), 3);
  1619. utf8Script = RecyclerNewArrayLeafTrace(this->GetRecycler(), utf8char_t, cbUtf8Buffer);
  1620. cbNeeded = utf8::EncodeIntoAndNullTerminate(utf8Script, (const char16*)script, static_cast<charcount_t>(length));
  1621. #if DBG_DUMP && defined(PROFILE_MEM)
  1622. if(Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::ParsePhase) && Configuration::Global.flags.Verbose)
  1623. {
  1624. Output::Print(_u("Loading script.\n")
  1625. _u(" Unicode (in bytes) %u\n")
  1626. _u(" UTF-8 size (in bytes) %u\n")
  1627. _u(" Expected savings %d\n"), length * sizeof(char16), cbNeeded, length * sizeof(char16) - cbNeeded);
  1628. }
  1629. #endif
  1630. // Free unused bytes
  1631. Assert(cbNeeded + 1 <= cbUtf8Buffer);
  1632. *ppSourceInfo = Utf8SourceInfo::New(this, utf8Script, (int)length,
  1633. cbNeeded, pSrcInfo, isLibraryCode);
  1634. }
  1635. else
  1636. {
  1637. // We do not own the memory passed into DefaultLoadScriptUtf8. We need to save it so we copy the memory.
  1638. if(*ppSourceInfo == nullptr)
  1639. {
  1640. #ifndef NTBUILD
  1641. if (loadScriptFlag & LoadScriptFlag_ExternalArrayBuffer)
  1642. {
  1643. *ppSourceInfo = Utf8SourceInfo::NewWithNoCopy(this,
  1644. script, (int)length, cb, pSrcInfo, isLibraryCode,
  1645. scriptSource);
  1646. }
  1647. else
  1648. #endif
  1649. {
  1650. // the 'length' here is not correct - we will get the length from the parser - however parser hasn't done yet.
  1651. // Once the parser is done we will update the utf8sourceinfo's lenght correctly with parser's
  1652. *ppSourceInfo = Utf8SourceInfo::New(this, script,
  1653. (int)length, cb, pSrcInfo, isLibraryCode);
  1654. }
  1655. }
  1656. }
  1657. //
  1658. // Parse and the JavaScript code
  1659. //
  1660. HRESULT hr;
  1661. SourceContextInfo * sourceContextInfo = pSrcInfo->sourceContextInfo;
  1662. // Invoke the parser, passing in the global function name, which we will then run to execute
  1663. // the script.
  1664. // TODO: yongqu handle non-global code.
  1665. ULONG grfscr = fscrGlobalCode | ((loadScriptFlag & LoadScriptFlag_Expression) == LoadScriptFlag_Expression ? fscrReturnExpression : 0);
  1666. if(((loadScriptFlag & LoadScriptFlag_disableDeferredParse) != LoadScriptFlag_disableDeferredParse) &&
  1667. (length > Parser::GetDeferralThreshold(sourceContextInfo->IsSourceProfileLoaded())))
  1668. {
  1669. grfscr |= fscrDeferFncParse;
  1670. }
  1671. if((loadScriptFlag & LoadScriptFlag_disableAsmJs) == LoadScriptFlag_disableAsmJs)
  1672. {
  1673. grfscr |= fscrNoAsmJs;
  1674. }
  1675. if(PHASE_FORCE1(Js::EvalCompilePhase))
  1676. {
  1677. // pretend it is eval
  1678. grfscr |= (fscrEval | fscrEvalCode);
  1679. }
  1680. if((loadScriptFlag & LoadScriptFlag_isByteCodeBufferForLibrary) == LoadScriptFlag_isByteCodeBufferForLibrary)
  1681. {
  1682. grfscr |= fscrNoPreJit;
  1683. }
  1684. if(((loadScriptFlag & LoadScriptFlag_Module) == LoadScriptFlag_Module) &&
  1685. GetConfig()->IsES6ModuleEnabled())
  1686. {
  1687. grfscr |= fscrIsModuleCode;
  1688. }
  1689. if (isLibraryCode)
  1690. {
  1691. grfscr |= fscrIsLibraryCode;
  1692. }
  1693. ParseNodePtr parseTree;
  1694. if((loadScriptFlag & LoadScriptFlag_Utf8Source) == LoadScriptFlag_Utf8Source)
  1695. {
  1696. hr = parser->ParseUtf8Source(&parseTree, script, cb, grfscr, pse,
  1697. &sourceContextInfo->nextLocalFunctionId, sourceContextInfo);
  1698. }
  1699. else
  1700. {
  1701. hr = parser->ParseCesu8Source(&parseTree, utf8Script, cbNeeded, grfscr,
  1702. pse, &sourceContextInfo->nextLocalFunctionId, sourceContextInfo);
  1703. }
  1704. if(FAILED(hr) || parseTree == nullptr)
  1705. {
  1706. return nullptr;
  1707. }
  1708. (*ppSourceInfo)->SetParseFlags(grfscr);
  1709. //Make sure we have the body and text information available
  1710. if ((loadScriptFlag & LoadScriptFlag_Utf8Source) != LoadScriptFlag_Utf8Source)
  1711. {
  1712. *sourceIndex = this->SaveSourceNoCopy(*ppSourceInfo, static_cast<charcount_t>((*ppSourceInfo)->GetCchLength()), /*isCesu8*/ true);
  1713. }
  1714. else
  1715. {
  1716. // Update the length.
  1717. (*ppSourceInfo)->SetCchLength(parser->GetSourceIchLim());
  1718. *sourceIndex = this->SaveSourceNoCopy(*ppSourceInfo, parser->GetSourceIchLim(), /* isCesu8*/ false);
  1719. }
  1720. return parseTree;
  1721. }
  1722. JavascriptFunction* ScriptContext::LoadScript(const byte* script, size_t cb,
  1723. SRCINFO const * pSrcInfo, CompileScriptException * pse, Utf8SourceInfo** ppSourceInfo,
  1724. const char16 *rootDisplayName, LoadScriptFlag loadScriptFlag, Js::Var scriptSource)
  1725. {
  1726. Assert(!this->threadContext->IsScriptActive());
  1727. Assert(pse != nullptr);
  1728. HRESULT hr = NOERROR;
  1729. try
  1730. {
  1731. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_StackOverflow));
  1732. Js::AutoDynamicCodeReference dynamicFunctionReference(this);
  1733. Parser parser(this);
  1734. uint sourceIndex;
  1735. JavascriptFunction * pFunction = nullptr;
  1736. ParseNodePtr parseTree = ParseScript(&parser, script, cb, pSrcInfo,
  1737. pse, ppSourceInfo, rootDisplayName, loadScriptFlag,
  1738. &sourceIndex, scriptSource);
  1739. if (parseTree != nullptr)
  1740. {
  1741. pFunction = GenerateRootFunction(parseTree, sourceIndex, &parser, (*ppSourceInfo)->GetParseFlags(), pse, rootDisplayName);
  1742. }
  1743. if (pse->ei.scode == JSERR_AsmJsCompileError)
  1744. {
  1745. Assert((loadScriptFlag & LoadScriptFlag_disableAsmJs) != LoadScriptFlag_disableAsmJs);
  1746. pse->Free();
  1747. loadScriptFlag = (LoadScriptFlag)(loadScriptFlag | LoadScriptFlag_disableAsmJs);
  1748. return LoadScript(script, cb, pSrcInfo, pse, ppSourceInfo,
  1749. rootDisplayName, loadScriptFlag, scriptSource);
  1750. }
  1751. #ifdef ENABLE_SCRIPT_PROFILING
  1752. if (pFunction != nullptr && this->IsProfiling())
  1753. {
  1754. RegisterScript(pFunction->GetFunctionProxy());
  1755. }
  1756. #else
  1757. Assert(!this->IsProfiling());
  1758. #endif
  1759. return pFunction;
  1760. }
  1761. catch (Js::OutOfMemoryException)
  1762. {
  1763. hr = E_OUTOFMEMORY;
  1764. }
  1765. catch (Js::StackOverflowException)
  1766. {
  1767. hr = VBSERR_OutOfStack;
  1768. }
  1769. pse->ProcessError(nullptr, hr, nullptr);
  1770. return nullptr;
  1771. }
  1772. JavascriptFunction* ScriptContext::GenerateRootFunction(ParseNodePtr parseTree, uint sourceIndex, Parser* parser, uint32 grfscr, CompileScriptException * pse, const char16 *rootDisplayName)
  1773. {
  1774. HRESULT hr;
  1775. // Get the source code to keep it alive during the bytecode generation process
  1776. LPCUTF8 source = this->GetSource(sourceIndex)->GetSource(_u("ScriptContext::GenerateRootFunction"));
  1777. Assert(source != nullptr); // Source should not have been reclaimed by now
  1778. // Generate bytecode and native code
  1779. ParseableFunctionInfo* body = NULL;
  1780. hr = GenerateByteCode(parseTree, grfscr, this, &body, sourceIndex, false, parser, pse);
  1781. this->GetSource(sourceIndex)->SetByteCodeGenerationFlags(grfscr);
  1782. if(FAILED(hr))
  1783. {
  1784. return nullptr;
  1785. }
  1786. body->SetDisplayName(rootDisplayName);
  1787. body->SetIsTopLevel(true);
  1788. JavascriptFunction* rootFunction = javascriptLibrary->CreateScriptFunction(body);
  1789. return rootFunction;
  1790. }
  1791. BOOL ScriptContext::ReserveStaticTypeIds(__in int first, __in int last)
  1792. {
  1793. return threadContext->ReserveStaticTypeIds(first, last);
  1794. }
  1795. TypeId ScriptContext::ReserveTypeIds(int count)
  1796. {
  1797. return threadContext->ReserveTypeIds(count);
  1798. }
  1799. TypeId ScriptContext::CreateTypeId()
  1800. {
  1801. return threadContext->CreateTypeId();
  1802. }
  1803. void ScriptContext::OnScriptStart(bool isRoot, bool isScript)
  1804. {
  1805. const bool isForcedEnter =
  1806. #ifdef ENABLE_SCRIPT_DEBUGGING
  1807. this->GetDebugContext() != nullptr ? this->GetDebugContext()->GetProbeContainer()->isForcedToEnterScriptStart :
  1808. #endif
  1809. false;
  1810. if (this->scriptStartEventHandler != nullptr && ((isRoot && threadContext->GetCallRootLevel() == 1) || isForcedEnter))
  1811. {
  1812. #ifdef ENABLE_SCRIPT_DEBUGGING
  1813. if (this->GetDebugContext() != nullptr)
  1814. {
  1815. this->GetDebugContext()->GetProbeContainer()->isForcedToEnterScriptStart = false;
  1816. }
  1817. #endif
  1818. this->scriptStartEventHandler(this);
  1819. }
  1820. #if ENABLE_NATIVE_CODEGEN
  1821. //Blue 5491: Only start codegen if isScript. Avoid it if we are not really starting script and called from risky region such as catch handler.
  1822. if (isScript)
  1823. {
  1824. NativeCodeGenEnterScriptStart(this->GetNativeCodeGenerator());
  1825. }
  1826. #endif
  1827. }
  1828. void ScriptContext::OnScriptEnd(bool isRoot, bool isForcedEnd)
  1829. {
  1830. if ((isRoot && threadContext->GetCallRootLevel() == 1) || isForcedEnd)
  1831. {
  1832. if (this->scriptEndEventHandler != nullptr)
  1833. {
  1834. this->scriptEndEventHandler(this);
  1835. }
  1836. }
  1837. }
  1838. #ifdef FAULT_INJECTION
  1839. void ScriptContext::DisposeScriptContextByFaultInjection() {
  1840. if (this->disposeScriptByFaultInjectionEventHandler != nullptr)
  1841. {
  1842. this->disposeScriptByFaultInjectionEventHandler(this);
  1843. }
  1844. }
  1845. #endif
  1846. template <bool stackProbe, bool leaveForHost>
  1847. bool ScriptContext::LeaveScriptStart(void * frameAddress)
  1848. {
  1849. ThreadContext * threadContext = this->threadContext;
  1850. if (!threadContext->IsScriptActive())
  1851. {
  1852. // we should have enter always.
  1853. AssertMsg(FALSE, "Leaving ScriptStart while script is not active.");
  1854. return false;
  1855. }
  1856. // Make sure the host function will have at least 32k of stack available.
  1857. if (stackProbe)
  1858. {
  1859. threadContext->ProbeStack(Js::Constants::MinStackCallout, this);
  1860. }
  1861. else
  1862. {
  1863. AssertMsg(ExceptionCheck::HasStackProbe(), "missing stack probe");
  1864. }
  1865. threadContext->LeaveScriptStart<leaveForHost>(frameAddress);
  1866. return true;
  1867. }
  1868. template <bool leaveForHost>
  1869. void ScriptContext::LeaveScriptEnd(void * frameAddress)
  1870. {
  1871. this->threadContext->LeaveScriptEnd<leaveForHost>(frameAddress);
  1872. }
  1873. // explicit instantiations
  1874. template bool ScriptContext::LeaveScriptStart<true, true>(void * frameAddress);
  1875. template bool ScriptContext::LeaveScriptStart<true, false>(void * frameAddress);
  1876. template bool ScriptContext::LeaveScriptStart<false, true>(void * frameAddress);
  1877. template void ScriptContext::LeaveScriptEnd<true>(void * frameAddress);
  1878. template void ScriptContext::LeaveScriptEnd<false>(void * frameAddress);
  1879. bool ScriptContext::EnsureInterpreterArena(ArenaAllocator **ppAlloc)
  1880. {
  1881. bool fNew = false;
  1882. if (this->interpreterArena == nullptr)
  1883. {
  1884. this->interpreterArena = this->GetRecycler()->CreateGuestArena(_u("Interpreter"), Throw::OutOfMemory);
  1885. fNew = true;
  1886. }
  1887. *ppAlloc = this->interpreterArena;
  1888. return fNew;
  1889. }
  1890. void ScriptContext::ReleaseInterpreterArena()
  1891. {
  1892. AssertMsg(this->interpreterArena, "No interpreter arena to release");
  1893. if (this->interpreterArena)
  1894. {
  1895. this->GetRecycler()->DeleteGuestArena(this->interpreterArena);
  1896. this->interpreterArena = nullptr;
  1897. }
  1898. }
  1899. void ScriptContext::ReleaseGuestArena()
  1900. {
  1901. AssertMsg(this->guestArena, "No guest arena to release");
  1902. if (this->guestArena)
  1903. {
  1904. this->GetRecycler()->DeleteGuestArena(this->guestArena);
  1905. this->guestArena = nullptr;
  1906. }
  1907. }
  1908. void ScriptContext::SetScriptStartEventHandler(ScriptContext::EventHandler eventHandler)
  1909. {
  1910. AssertMsg(this->scriptStartEventHandler == nullptr, "Do not support multi-cast yet");
  1911. this->scriptStartEventHandler = eventHandler;
  1912. }
  1913. void ScriptContext::SetScriptEndEventHandler(ScriptContext::EventHandler eventHandler)
  1914. {
  1915. AssertMsg(this->scriptEndEventHandler == nullptr, "Do not support multi-cast yet");
  1916. this->scriptEndEventHandler = eventHandler;
  1917. }
  1918. #ifdef FAULT_INJECTION
  1919. void ScriptContext::SetDisposeDisposeByFaultInjectionEventHandler(ScriptContext::EventHandler eventHandler)
  1920. {
  1921. AssertMsg(this->disposeScriptByFaultInjectionEventHandler == nullptr, "Do not support multi-cast yet");
  1922. this->disposeScriptByFaultInjectionEventHandler = eventHandler;
  1923. }
  1924. #endif
  1925. bool ScriptContext::SaveSourceCopy(Utf8SourceInfo* const sourceInfo, int cchLength, bool isCesu8, uint * index)
  1926. {
  1927. HRESULT hr = S_OK;
  1928. BEGIN_TRANSLATE_OOM_TO_HRESULT
  1929. {
  1930. *index = this->SaveSourceCopy(sourceInfo, cchLength, isCesu8);
  1931. }
  1932. END_TRANSLATE_OOM_TO_HRESULT(hr);
  1933. return hr == S_OK;
  1934. }
  1935. uint ScriptContext::SaveSourceCopy(Utf8SourceInfo* sourceInfo, int cchLength, bool isCesu8)
  1936. {
  1937. Utf8SourceInfo* newSource = Utf8SourceInfo::Clone(this, sourceInfo);
  1938. return SaveSourceNoCopy(newSource, cchLength, isCesu8);
  1939. }
  1940. uint ScriptContext::SaveSourceNoCopy(Utf8SourceInfo* sourceInfo, int cchLength, bool isCesu8)
  1941. {
  1942. Assert(sourceInfo->GetScriptContext() == this);
  1943. #ifdef ENABLE_SCRIPT_DEBUGGING
  1944. if (this->IsScriptContextInDebugMode() && !sourceInfo->GetIsLibraryCode() && !sourceInfo->IsInDebugMode())
  1945. {
  1946. sourceInfo->SetInDebugMode(true);
  1947. }
  1948. #endif
  1949. RecyclerWeakReference<Utf8SourceInfo>* sourceWeakRef = this->GetRecycler()->CreateWeakReferenceHandle<Utf8SourceInfo>(sourceInfo);
  1950. sourceInfo->SetIsCesu8(isCesu8);
  1951. {
  1952. // We can be compiling new source code while rundown thread is reading from the list, causing AV on the reader thread
  1953. // lock the list during write as well.
  1954. AutoCriticalSection autocs(GetThreadContext()->GetFunctionBodyLock());
  1955. return sourceList->SetAtFirstFreeSpot(sourceWeakRef);
  1956. }
  1957. }
  1958. void ScriptContext::CloneSources(ScriptContext* sourceContext)
  1959. {
  1960. sourceContext->sourceList->Map([=](int index, RecyclerWeakReference<Utf8SourceInfo>* sourceInfo)
  1961. {
  1962. Utf8SourceInfo* info = sourceInfo->Get();
  1963. if (info)
  1964. {
  1965. CloneSource(info);
  1966. }
  1967. });
  1968. }
  1969. uint ScriptContext::CloneSource(Utf8SourceInfo* info)
  1970. {
  1971. return this->SaveSourceCopy(info, info->GetCchLength(), info->GetIsCesu8());
  1972. }
  1973. Utf8SourceInfo* ScriptContext::GetSource(uint index)
  1974. {
  1975. Assert(this->sourceList->IsItemValid(index)); // This assert should be a subset of info != null- if info was null, in the last collect, we'd have invalidated the item
  1976. Utf8SourceInfo* info = this->sourceList->Item(index)->Get();
  1977. Assert(info != nullptr); // Should still be alive if this method is being called
  1978. return info;
  1979. }
  1980. bool ScriptContext::IsItemValidInSourceList(int index)
  1981. {
  1982. return (index < this->sourceList->Count()) && this->sourceList->IsItemValid(index);
  1983. }
  1984. void ScriptContext::RecordException(JavascriptExceptionObject * exceptionObject, bool propagateToDebugger)
  1985. {
  1986. Assert(this->threadContext->GetRecordedException() == nullptr || GetThreadContext()->HasUnhandledException());
  1987. this->threadContext->SetRecordedException(exceptionObject, propagateToDebugger);
  1988. #if DBG && ENABLE_DEBUG_STACK_BACK_TRACE
  1989. exceptionObject->FillStackBackTrace();
  1990. #endif
  1991. }
  1992. void ScriptContext::RethrowRecordedException(JavascriptExceptionObject::HostWrapperCreateFuncType hostWrapperCreateFunc)
  1993. {
  1994. bool considerPassingToDebugger = false;
  1995. JavascriptExceptionObject * exceptionObject = this->GetAndClearRecordedException(&considerPassingToDebugger);
  1996. if (hostWrapperCreateFunc)
  1997. {
  1998. exceptionObject->SetHostWrapperCreateFunc(exceptionObject->GetScriptContext() != this ? hostWrapperCreateFunc : nullptr);
  1999. }
  2000. JavascriptExceptionOperators::RethrowExceptionObject(exceptionObject, this, considerPassingToDebugger);
  2001. }
  2002. Js::JavascriptExceptionObject * ScriptContext::GetAndClearRecordedException(bool *considerPassingToDebugger)
  2003. {
  2004. JavascriptExceptionObject * exceptionObject = this->threadContext->GetRecordedException();
  2005. Assert(exceptionObject != nullptr);
  2006. if (considerPassingToDebugger)
  2007. {
  2008. *considerPassingToDebugger = this->threadContext->GetPropagateException();
  2009. }
  2010. exceptionObject = exceptionObject->CloneIfStaticExceptionObject(this);
  2011. this->threadContext->SetRecordedException(nullptr);
  2012. return exceptionObject;
  2013. }
  2014. bool ScriptContext::IsInEvalMap(FastEvalMapString const& key, BOOL isIndirect, ScriptFunction **ppFuncScript)
  2015. {
  2016. EvalCacheDictionary *dict = isIndirect ? this->Cache()->indirectEvalCacheDictionary : this->Cache()->evalCacheDictionary;
  2017. if (dict == nullptr)
  2018. {
  2019. return false;
  2020. }
  2021. #ifdef PROFILE_EVALMAP
  2022. if (Configuration::Global.flags.ProfileEvalMap)
  2023. {
  2024. charcount_t len = key.str.GetLength();
  2025. if (dict->TryGetValue(key, ppFuncScript))
  2026. {
  2027. Output::Print(_u("EvalMap cache hit:\t source size = %d\n"), len);
  2028. }
  2029. else
  2030. {
  2031. Output::Print(_u("EvalMap cache miss:\t source size = %d\n"), len);
  2032. }
  2033. }
  2034. #endif
  2035. // If eval map cleanup is false, to preserve existing behavior, add it to the eval map MRU list
  2036. bool success = dict->TryGetValue(key, ppFuncScript);
  2037. if (success)
  2038. {
  2039. dict->NotifyAdd(key);
  2040. #ifdef VERBOSE_EVAL_MAP
  2041. #if DBG
  2042. dict->DumpKeepAlives();
  2043. #endif
  2044. #endif
  2045. }
  2046. return success;
  2047. }
  2048. void ScriptContext::AddToEvalMap(FastEvalMapString const& key, BOOL isIndirect, ScriptFunction *pfuncScript)
  2049. {
  2050. Assert(!pfuncScript->GetFunctionInfo()->IsGenerator());
  2051. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  2052. Js::Utf8SourceInfo* utf8SourceInfo = pfuncScript->GetFunctionBody()->GetUtf8SourceInfo();
  2053. if (this->IsScriptContextInDebugMode() && !utf8SourceInfo->GetIsLibraryCode() && !utf8SourceInfo->IsInDebugMode())
  2054. {
  2055. // Identifying if any non library function escaped for not being in debug mode.
  2056. Throw::FatalInternalError();
  2057. }
  2058. #endif
  2059. #if ENABLE_TTD
  2060. if(!this->IsTTDRecordOrReplayModeEnabled())
  2061. {
  2062. this->AddToEvalMapHelper(key, isIndirect, pfuncScript);
  2063. }
  2064. #else
  2065. this->AddToEvalMapHelper(key, isIndirect, pfuncScript);
  2066. #endif
  2067. }
  2068. void ScriptContext::AddToEvalMapHelper(FastEvalMapString const& key, BOOL isIndirect, ScriptFunction *pFuncScript)
  2069. {
  2070. EvalCacheDictionary *dict = isIndirect ? this->Cache()->indirectEvalCacheDictionary : this->Cache()->evalCacheDictionary;
  2071. if (dict == nullptr)
  2072. {
  2073. EvalCacheTopLevelDictionary* evalTopDictionary = RecyclerNew(this->recycler, EvalCacheTopLevelDictionary, this->recycler);
  2074. dict = RecyclerNew(this->recycler, EvalCacheDictionary, evalTopDictionary, recycler);
  2075. if (isIndirect)
  2076. {
  2077. this->Cache()->indirectEvalCacheDictionary = dict;
  2078. }
  2079. else
  2080. {
  2081. this->Cache()->evalCacheDictionary = dict;
  2082. }
  2083. }
  2084. dict->Add(key, pFuncScript);
  2085. }
  2086. bool ScriptContext::IsInNewFunctionMap(EvalMapString const& key, FunctionInfo **ppFuncInfo)
  2087. {
  2088. if (this->Cache()->newFunctionCache == nullptr)
  2089. {
  2090. return false;
  2091. }
  2092. // If eval map cleanup is false, to preserve existing behavior, add it to the eval map MRU list
  2093. bool success = this->Cache()->newFunctionCache->TryGetValue(key, ppFuncInfo);
  2094. if (success)
  2095. {
  2096. this->Cache()->newFunctionCache->NotifyAdd(key);
  2097. #ifdef VERBOSE_EVAL_MAP
  2098. #if DBG
  2099. this->Cache()->newFunctionCache->DumpKeepAlives();
  2100. #endif
  2101. #endif
  2102. }
  2103. return success;
  2104. }
  2105. void ScriptContext::AddToNewFunctionMap(EvalMapString const& key, FunctionInfo *pFuncInfo)
  2106. {
  2107. if (this->Cache()->newFunctionCache == nullptr)
  2108. {
  2109. this->Cache()->newFunctionCache = RecyclerNew(this->recycler, NewFunctionCache, this->recycler);
  2110. }
  2111. this->Cache()->newFunctionCache->Add(key, pFuncInfo);
  2112. }
  2113. void ScriptContext::EnsureSourceContextInfoMap()
  2114. {
  2115. if (this->Cache()->sourceContextInfoMap == nullptr)
  2116. {
  2117. this->Cache()->sourceContextInfoMap = RecyclerNew(this->GetRecycler(), SourceContextInfoMap, this->GetRecycler());
  2118. }
  2119. }
  2120. void ScriptContext::EnsureDynamicSourceContextInfoMap()
  2121. {
  2122. if (this->Cache()->dynamicSourceContextInfoMap == nullptr)
  2123. {
  2124. this->Cache()->dynamicSourceContextInfoMap = RecyclerNew(this->GetRecycler(), DynamicSourceContextInfoMap, this->GetRecycler());
  2125. }
  2126. }
  2127. SourceContextInfo* ScriptContext::GetSourceContextInfo(uint hash)
  2128. {
  2129. SourceContextInfo * sourceContextInfo = nullptr;
  2130. if (this->Cache()->dynamicSourceContextInfoMap && this->Cache()->dynamicSourceContextInfoMap->TryGetValue(hash, &sourceContextInfo))
  2131. {
  2132. return sourceContextInfo;
  2133. }
  2134. return nullptr;
  2135. }
  2136. SourceContextInfo* ScriptContext::CreateSourceContextInfo(uint hash, DWORD_PTR hostSourceContext)
  2137. {
  2138. EnsureDynamicSourceContextInfoMap();
  2139. if (this->GetSourceContextInfo(hash) != nullptr)
  2140. {
  2141. return this->Cache()->noContextSourceContextInfo;
  2142. }
  2143. if (this->Cache()->dynamicSourceContextInfoMap->Count() > INMEMORY_CACHE_MAX_PROFILE_MANAGER)
  2144. {
  2145. OUTPUT_TRACE(Js::DynamicProfilePhase, _u("Max of dynamic script profile info reached.\n"));
  2146. return this->Cache()->noContextSourceContextInfo;
  2147. }
  2148. // This is capped so we can continue allocating in the arena
  2149. SourceContextInfo * sourceContextInfo = RecyclerNewStructZ(this->GetRecycler(), SourceContextInfo);
  2150. sourceContextInfo->sourceContextId = this->GetNextSourceContextId();
  2151. sourceContextInfo->dwHostSourceContext = hostSourceContext;
  2152. sourceContextInfo->isHostDynamicDocument = true;
  2153. sourceContextInfo->hash = hash;
  2154. #if ENABLE_PROFILE_INFO
  2155. sourceContextInfo->sourceDynamicProfileManager = this->threadContext->GetSourceDynamicProfileManager(this->GetUrl(), hash, &referencesSharedDynamicSourceContextInfo);
  2156. #endif
  2157. // For the host provided dynamic code (if hostSourceContext is not NoHostSourceContext), do not add to dynamicSourceContextInfoMap
  2158. if (hostSourceContext == Js::Constants::NoHostSourceContext)
  2159. {
  2160. this->Cache()->dynamicSourceContextInfoMap->Add(hash, sourceContextInfo);
  2161. }
  2162. return sourceContextInfo;
  2163. }
  2164. //
  2165. // Makes a copy of the URL to be stored in the map.
  2166. //
  2167. SourceContextInfo * ScriptContext::CreateSourceContextInfo(DWORD_PTR sourceContext, char16 const * url, size_t len,
  2168. IActiveScriptDataCache* profileDataCache, char16 const * sourceMapUrl /*= NULL*/, size_t sourceMapUrlLen /*= 0*/)
  2169. {
  2170. // Take etw rundown lock on this thread context. We are going to init/add to sourceContextInfoMap.
  2171. AutoCriticalSection autocs(GetThreadContext()->GetFunctionBodyLock());
  2172. EnsureSourceContextInfoMap();
  2173. Assert(this->GetSourceContextInfo(sourceContext, profileDataCache) == nullptr);
  2174. SourceContextInfo * sourceContextInfo = RecyclerNewStructZ(this->GetRecycler(), SourceContextInfo);
  2175. sourceContextInfo->sourceContextId = this->GetNextSourceContextId();
  2176. sourceContextInfo->dwHostSourceContext = sourceContext;
  2177. sourceContextInfo->isHostDynamicDocument = false;
  2178. #if ENABLE_PROFILE_INFO
  2179. sourceContextInfo->sourceDynamicProfileManager = nullptr;
  2180. #endif
  2181. if (url != nullptr)
  2182. {
  2183. sourceContextInfo->url = CopyString(url, len, this->SourceCodeAllocator());
  2184. JS_ETW(EtwTrace::LogSourceModuleLoadEvent(this, sourceContext, url));
  2185. }
  2186. if (sourceMapUrl != nullptr && sourceMapUrlLen != 0)
  2187. {
  2188. sourceContextInfo->sourceMapUrl = CopyString(sourceMapUrl, sourceMapUrlLen, this->SourceCodeAllocator());
  2189. }
  2190. #if ENABLE_PROFILE_INFO
  2191. if (!this->startupComplete)
  2192. {
  2193. sourceContextInfo->sourceDynamicProfileManager = SourceDynamicProfileManager::LoadFromDynamicProfileStorage(sourceContextInfo, this, profileDataCache);
  2194. Assert(sourceContextInfo->sourceDynamicProfileManager != NULL);
  2195. }
  2196. this->Cache()->sourceContextInfoMap->Add(sourceContext, sourceContextInfo);
  2197. #endif
  2198. return sourceContextInfo;
  2199. }
  2200. // static
  2201. const char16* ScriptContext::CopyString(const char16* str, size_t charCount, ArenaAllocator* alloc)
  2202. {
  2203. size_t length = charCount + 1; // Add 1 for the NULL.
  2204. char16* copy = AnewArray(alloc, char16, length);
  2205. js_wmemcpy_s(copy, length, str, charCount);
  2206. copy[length - 1] = _u('\0');
  2207. return copy;
  2208. }
  2209. SourceContextInfo * ScriptContext::GetSourceContextInfo(DWORD_PTR sourceContext, IActiveScriptDataCache* profileDataCache)
  2210. {
  2211. if (sourceContext == Js::Constants::NoHostSourceContext)
  2212. {
  2213. return this->Cache()->noContextSourceContextInfo;
  2214. }
  2215. // We only init sourceContextInfoMap, don't need to lock.
  2216. EnsureSourceContextInfoMap();
  2217. SourceContextInfo * sourceContextInfo = nullptr;
  2218. if (this->Cache()->sourceContextInfoMap->TryGetValue(sourceContext, &sourceContextInfo))
  2219. {
  2220. #if ENABLE_PROFILE_INFO
  2221. if (profileDataCache &&
  2222. sourceContextInfo->sourceDynamicProfileManager != nullptr &&
  2223. !sourceContextInfo->sourceDynamicProfileManager->IsProfileLoadedFromWinInet() &&
  2224. !this->startupComplete)
  2225. {
  2226. bool profileLoaded = sourceContextInfo->sourceDynamicProfileManager->LoadFromProfileCache(profileDataCache, sourceContextInfo->url);
  2227. if (profileLoaded)
  2228. {
  2229. JS_ETW(EventWriteJSCRIPT_PROFILE_LOAD(sourceContextInfo->dwHostSourceContext, this));
  2230. }
  2231. }
  2232. #endif
  2233. return sourceContextInfo;
  2234. }
  2235. return nullptr;
  2236. }
  2237. SRCINFO const *
  2238. ScriptContext::GetModuleSrcInfo(Js::ModuleID moduleID)
  2239. {
  2240. if (moduleSrcInfoCount <= moduleID)
  2241. {
  2242. uint newCount = moduleID + 4; // Preallocate 4 more slots, moduleID don't usually grow much
  2243. Field(SRCINFO const *)* newModuleSrcInfo = RecyclerNewArrayZ(this->GetRecycler(), Field(SRCINFO const*), newCount);
  2244. CopyArray(newModuleSrcInfo, newCount, Cache()->moduleSrcInfo, moduleSrcInfoCount);
  2245. Cache()->moduleSrcInfo = newModuleSrcInfo;
  2246. moduleSrcInfoCount = newCount;
  2247. Cache()->moduleSrcInfo[0] = this->Cache()->noContextGlobalSourceInfo;
  2248. }
  2249. SRCINFO const * si = Cache()->moduleSrcInfo[moduleID];
  2250. if (si == nullptr)
  2251. {
  2252. SRCINFO * newSrcInfo = RecyclerNewStructZ(this->GetRecycler(), SRCINFO);
  2253. newSrcInfo->sourceContextInfo = this->Cache()->noContextSourceContextInfo;
  2254. newSrcInfo->moduleID = moduleID;
  2255. Cache()->moduleSrcInfo[moduleID] = newSrcInfo;
  2256. si = newSrcInfo;
  2257. }
  2258. return si;
  2259. }
  2260. #if ENABLE_TTD
  2261. void ScriptContext::InitializeCoreImage_TTD()
  2262. {
  2263. TTDAssert(this->TTDWellKnownInfo == nullptr, "This should only happen once!!!");
  2264. this->TTDContextInfo = TT_HEAP_NEW(TTD::ScriptContextTTD, this);
  2265. this->TTDWellKnownInfo = TT_HEAP_NEW(TTD::RuntimeContextInfo);
  2266. BEGIN_ENTER_SCRIPT(this, true, true, true)
  2267. {
  2268. this->TTDWellKnownInfo->GatherKnownObjectToPathMap(this);
  2269. }
  2270. END_ENTER_SCRIPT
  2271. }
  2272. #endif
  2273. #ifdef PROFILE_EXEC
  2274. void
  2275. ScriptContext::DisableProfiler()
  2276. {
  2277. disableProfiler = true;
  2278. }
  2279. Profiler *
  2280. ScriptContext::CreateProfiler()
  2281. {
  2282. Assert(profiler == nullptr);
  2283. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  2284. {
  2285. this->profiler = NoCheckHeapNew(ScriptContextProfiler);
  2286. this->profiler->Initialize(GetThreadContext()->GetPageAllocator(), threadContext->GetRecycler());
  2287. #if ENABLE_NATIVE_CODEGEN
  2288. CreateProfilerNativeCodeGen(this->nativeCodeGen, this->profiler);
  2289. #endif
  2290. this->isProfilerCreated = true;
  2291. Profiler * oldProfiler = this->threadContext->GetRecycler()->GetProfiler();
  2292. this->threadContext->GetRecycler()->SetProfiler(this->profiler->GetProfiler(), this->profiler->GetBackgroundRecyclerProfiler());
  2293. return oldProfiler;
  2294. }
  2295. return nullptr;
  2296. }
  2297. void
  2298. ScriptContext::SetRecyclerProfiler()
  2299. {
  2300. Assert(Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag));
  2301. AssertMsg(this->profiler != nullptr, "Profiler tag is supplied but the profiler pointer is NULL");
  2302. if (this->ensureParentInfo)
  2303. {
  2304. this->hostScriptContext->EnsureParentInfo();
  2305. this->ensureParentInfo = false;
  2306. }
  2307. this->GetRecycler()->SetProfiler(this->profiler->GetProfiler(), this->profiler->GetBackgroundRecyclerProfiler());
  2308. }
  2309. void
  2310. ScriptContext::SetProfilerFromScriptContext(ScriptContext * scriptContext)
  2311. {
  2312. // this function needs to be called before any code gen happens so
  2313. // that access to codegenProfiler won't have concurrency issues
  2314. if (Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag))
  2315. {
  2316. Assert(this->profiler != nullptr);
  2317. Assert(this->isProfilerCreated);
  2318. Assert(scriptContext->profiler != nullptr);
  2319. Assert(scriptContext->isProfilerCreated);
  2320. scriptContext->profiler->ProfileMerge(this->profiler);
  2321. this->profiler->Release();
  2322. this->profiler = scriptContext->profiler;
  2323. this->profiler->AddRef();
  2324. this->isProfilerCreated = false;
  2325. #if ENABLE_NATIVE_CODEGEN
  2326. SetProfilerFromNativeCodeGen(this->nativeCodeGen, scriptContext->GetNativeCodeGenerator());
  2327. #endif
  2328. this->threadContext->GetRecycler()->SetProfiler(this->profiler->GetProfiler(), this->profiler->GetBackgroundRecyclerProfiler());
  2329. }
  2330. }
  2331. void
  2332. ScriptContext::ProfileBegin(Js::Phase phase)
  2333. {
  2334. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2335. "Profiler tag is supplied but the profiler pointer is NULL");
  2336. if (this->profiler)
  2337. {
  2338. if (this->ensureParentInfo)
  2339. {
  2340. this->hostScriptContext->EnsureParentInfo();
  2341. this->ensureParentInfo = false;
  2342. }
  2343. this->profiler->ProfileBegin(phase);
  2344. }
  2345. }
  2346. void
  2347. ScriptContext::ProfileEnd(Js::Phase phase)
  2348. {
  2349. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2350. "Profiler tag is supplied but the profiler pointer is NULL");
  2351. if (this->profiler)
  2352. {
  2353. this->profiler->ProfileEnd(phase);
  2354. }
  2355. }
  2356. void
  2357. ScriptContext::ProfileSuspend(Js::Phase phase, Js::Profiler::SuspendRecord * suspendRecord)
  2358. {
  2359. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2360. "Profiler tag is supplied but the profiler pointer is NULL");
  2361. if (this->profiler)
  2362. {
  2363. this->profiler->ProfileSuspend(phase, suspendRecord);
  2364. }
  2365. }
  2366. void
  2367. ScriptContext::ProfileResume(Js::Profiler::SuspendRecord * suspendRecord)
  2368. {
  2369. AssertMsg((this->profiler != nullptr) == Js::Configuration::Global.flags.IsEnabled(Js::ProfileFlag),
  2370. "Profiler tag is supplied but the profiler pointer is NULL");
  2371. if (this->profiler)
  2372. {
  2373. this->profiler->ProfileResume(suspendRecord);
  2374. }
  2375. }
  2376. void
  2377. ScriptContext::ProfilePrint()
  2378. {
  2379. if (disableProfiler)
  2380. {
  2381. return;
  2382. }
  2383. Assert(profiler != nullptr);
  2384. recycler->EnsureNotCollecting();
  2385. profiler->ProfilePrint(Js::Configuration::Global.flags.Profile.GetFirstPhase());
  2386. #if ENABLE_NATIVE_CODEGEN
  2387. ProfilePrintNativeCodeGen(this->nativeCodeGen);
  2388. #endif
  2389. }
  2390. #endif
  2391. #ifdef ENABLE_SCRIPT_PROFILING
  2392. inline void ScriptContext::CoreSetProfileEventMask(DWORD dwEventMask)
  2393. {
  2394. AssertMsg(m_pProfileCallback != NULL, "Assigning the event mask when there is no callback");
  2395. m_dwEventMask = dwEventMask;
  2396. m_fTraceFunctionCall = (dwEventMask & PROFILER_EVENT_MASK_TRACE_SCRIPT_FUNCTION_CALL);
  2397. m_fTraceNativeFunctionCall = (dwEventMask & PROFILER_EVENT_MASK_TRACE_NATIVE_FUNCTION_CALL);
  2398. m_fTraceDomCall = (dwEventMask & PROFILER_EVENT_MASK_TRACE_DOM_FUNCTION_CALL);
  2399. }
  2400. HRESULT ScriptContext::RegisterProfileProbe(IActiveScriptProfilerCallback *pProfileCallback, DWORD dwEventMask, DWORD dwContext, RegisterExternalLibraryType RegisterExternalLibrary, JavascriptMethod dispatchInvoke)
  2401. {
  2402. if (m_pProfileCallback != NULL)
  2403. {
  2404. return ACTIVPROF_E_PROFILER_PRESENT;
  2405. }
  2406. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterProfileProbe\n"));
  2407. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("Info\nThunks Address :\n"));
  2408. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("DefaultEntryThunk : 0x%08X, CrossSite::DefaultThunk : 0x%08X, DefaultDeferredParsingThunk : 0x%08X\n"), DefaultEntryThunk, CrossSite::DefaultThunk, DefaultDeferredParsingThunk);
  2409. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ProfileEntryThunk : 0x%08X, CrossSite::ProfileThunk : 0x%08X, ProfileDeferredParsingThunk : 0x%08X, ProfileDeferredDeserializeThunk : 0x%08X,\n"), ProfileEntryThunk, CrossSite::ProfileThunk, ProfileDeferredParsingThunk, ProfileDeferredDeserializeThunk);
  2410. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptType :\n"));
  2411. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("PROFILER_SCRIPT_TYPE_USER : 0, PROFILER_SCRIPT_TYPE_DYNAMIC : 1, PROFILER_SCRIPT_TYPE_NATIVE : 2, PROFILER_SCRIPT_TYPE_DOM : 3\n"));
  2412. HRESULT hr = pProfileCallback->Initialize(dwContext);
  2413. if (SUCCEEDED(hr))
  2414. {
  2415. m_pProfileCallback = pProfileCallback;
  2416. pProfileCallback->AddRef();
  2417. CoreSetProfileEventMask(dwEventMask);
  2418. if (m_fTraceDomCall)
  2419. {
  2420. if (FAILED(pProfileCallback->QueryInterface(&m_pProfileCallback2)))
  2421. {
  2422. m_fTraceDomCall = FALSE;
  2423. }
  2424. }
  2425. if (webWorkerId != Js::Constants::NonWebWorkerContextId)
  2426. {
  2427. IActiveScriptProfilerCallback3 * pProfilerCallback3;
  2428. if (SUCCEEDED(pProfileCallback->QueryInterface(&pProfilerCallback3)))
  2429. {
  2430. pProfilerCallback3->SetWebWorkerId(webWorkerId);
  2431. pProfilerCallback3->Release();
  2432. // Omitting the HRESULT since it is up to the callback to make use of the webWorker information.
  2433. }
  2434. }
  2435. #if DEBUG
  2436. StartNewProfileSession();
  2437. #endif
  2438. #if ENABLE_NATIVE_CODEGEN
  2439. NativeCodeGenerator *pNativeCodeGen = this->GetNativeCodeGenerator();
  2440. AutoOptionalCriticalSection autoAcquireCodeGenQueue(GetNativeCodeGenCriticalSection(pNativeCodeGen));
  2441. #endif
  2442. this->SetProfileMode(TRUE);
  2443. #if ENABLE_NATIVE_CODEGEN
  2444. SetProfileModeNativeCodeGen(pNativeCodeGen, TRUE);
  2445. #endif
  2446. // Register builtin functions
  2447. if (m_fTraceNativeFunctionCall)
  2448. {
  2449. hr = this->RegisterBuiltinFunctions(RegisterExternalLibrary);
  2450. if (FAILED(hr))
  2451. {
  2452. return hr;
  2453. }
  2454. }
  2455. this->RegisterAllScripts();
  2456. // Set the dispatch profiler:
  2457. this->SetDispatchProfile(TRUE, dispatchInvoke);
  2458. // Update the function objects currently present in there.
  2459. this->SetFunctionInRecyclerToProfileMode();
  2460. }
  2461. return hr;
  2462. }
  2463. HRESULT ScriptContext::SetProfileEventMask(DWORD dwEventMask)
  2464. {
  2465. if (m_pProfileCallback == NULL)
  2466. {
  2467. return ACTIVPROF_E_PROFILER_ABSENT;
  2468. }
  2469. return ACTIVPROF_E_UNABLE_TO_APPLY_ACTION;
  2470. }
  2471. HRESULT ScriptContext::DeRegisterProfileProbe(HRESULT hrReason, JavascriptMethod dispatchInvoke)
  2472. {
  2473. if (m_pProfileCallback == NULL)
  2474. {
  2475. return ACTIVPROF_E_PROFILER_ABSENT;
  2476. }
  2477. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::DeRegisterProfileProbe\n"));
  2478. #if ENABLE_NATIVE_CODEGEN
  2479. // Acquire the code gen working queue - we are going to change the thunks
  2480. NativeCodeGenerator *pNativeCodeGen = this->GetNativeCodeGenerator();
  2481. Assert(pNativeCodeGen);
  2482. {
  2483. AutoOptionalCriticalSection lock(GetNativeCodeGenCriticalSection(pNativeCodeGen));
  2484. this->SetProfileMode(FALSE);
  2485. SetProfileModeNativeCodeGen(pNativeCodeGen, FALSE);
  2486. // DisableJIT-TODO: Does need to happen even with JIT disabled?
  2487. // Unset the dispatch profiler:
  2488. if (dispatchInvoke != nullptr)
  2489. {
  2490. this->SetDispatchProfile(FALSE, dispatchInvoke);
  2491. }
  2492. }
  2493. #endif
  2494. m_inProfileCallback = TRUE;
  2495. HRESULT hr = m_pProfileCallback->Shutdown(hrReason);
  2496. m_inProfileCallback = FALSE;
  2497. m_pProfileCallback->Release();
  2498. m_pProfileCallback = NULL;
  2499. if (m_pProfileCallback2 != NULL)
  2500. {
  2501. m_pProfileCallback2->Release();
  2502. m_pProfileCallback2 = NULL;
  2503. }
  2504. #if DEBUG
  2505. StopProfileSession();
  2506. #endif
  2507. return hr;
  2508. }
  2509. void ScriptContext::SetProfileMode(BOOL fSet)
  2510. {
  2511. #ifdef ENABLE_SCRIPT_PROFILING
  2512. if (fSet)
  2513. {
  2514. AssertMsg(m_pProfileCallback != NULL, "In profile mode when there is no call back");
  2515. this->CurrentThunk = ProfileEntryThunk;
  2516. this->CurrentCrossSiteThunk = CrossSite::ProfileThunk;
  2517. this->DeferredParsingThunk = ProfileDeferredParsingThunk;
  2518. this->DeferredDeserializationThunk = ProfileDeferredDeserializeThunk;
  2519. this->globalObject->EvalHelper = &Js::GlobalObject::ProfileModeEvalHelper;
  2520. #if DBG
  2521. this->hadProfiled = true;
  2522. #endif
  2523. }
  2524. else
  2525. #endif
  2526. {
  2527. Assert(!fSet);
  2528. this->CurrentThunk = DefaultEntryThunk;
  2529. this->CurrentCrossSiteThunk = CrossSite::DefaultThunk;
  2530. this->DeferredParsingThunk = DefaultDeferredParsingThunk;
  2531. this->globalObject->EvalHelper = &Js::GlobalObject::DefaultEvalHelper;
  2532. // In Debug mode/Fast F12 library is still needed for built-in wrappers.
  2533. if (!(this->IsScriptContextInDebugMode() && this->IsExceptionWrapperForBuiltInsEnabled()))
  2534. {
  2535. this->javascriptLibrary->SetProfileMode(FALSE);
  2536. }
  2537. }
  2538. }
  2539. HRESULT ScriptContext::RegisterScript(Js::FunctionProxy * proxy, BOOL fRegisterScript /*default TRUE*/)
  2540. {
  2541. if (m_pProfileCallback == nullptr)
  2542. {
  2543. return ACTIVPROF_E_PROFILER_ABSENT;
  2544. }
  2545. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterScript, fRegisterScript : %s, IsFunctionDefer : %s\n"), IsTrueOrFalse(fRegisterScript), IsTrueOrFalse(proxy->IsDeferred()));
  2546. AssertMsg(proxy != nullptr, "Function body cannot be null when calling reporting");
  2547. AssertMsg(proxy->GetScriptContext() == this, "wrong script context while reporting the function?");
  2548. if (fRegisterScript)
  2549. {
  2550. // Register the script to the callback.
  2551. // REVIEW: do we really need to undefer everything?
  2552. HRESULT hr = proxy->EnsureDeserialized()->Parse()->ReportScriptCompiled();
  2553. if (FAILED(hr))
  2554. {
  2555. return hr;
  2556. }
  2557. }
  2558. return !proxy->IsDeferred() ? proxy->GetFunctionBody()->RegisterFunction(false) : S_OK;
  2559. }
  2560. HRESULT ScriptContext::RegisterAllScripts()
  2561. {
  2562. AssertMsg(m_pProfileCallback != nullptr, "Called register scripts when we don't have profile callback");
  2563. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterAllScripts started\n"));
  2564. // Future Work: Once Utf8SourceInfo can generate the debug document text without requiring a function body,
  2565. // this code can be considerably simplified to doing the following:
  2566. // - scriptContext->MapScript() : Fire script compiled for each script
  2567. // - scriptContext->MapFunction(): Fire function compiled for each function
  2568. this->MapScript([](Utf8SourceInfo* sourceInfo)
  2569. {
  2570. FunctionBody* functionBody = sourceInfo->GetAnyParsedFunction();
  2571. if (functionBody)
  2572. {
  2573. functionBody->ReportScriptCompiled();
  2574. }
  2575. });
  2576. // FunctionCompiled events for all functions.
  2577. this->MapFunction([](Js::FunctionBody* pFuncBody)
  2578. {
  2579. if (!pFuncBody->GetIsTopLevel() && pFuncBody->GetIsGlobalFunc())
  2580. {
  2581. // This must be the dummy function, generated due to the deferred parsing.
  2582. return;
  2583. }
  2584. pFuncBody->RegisterFunction(TRUE, TRUE); // Ignore potential failure (worst case is not profiling).
  2585. });
  2586. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterAllScripts ended\n"));
  2587. return S_OK;
  2588. }
  2589. #endif // ENABLE_SCRIPT_PROFILING
  2590. // Shuts down and recreates the native code generator. This is used when
  2591. // attaching and detaching the debugger in order to clear the list of work
  2592. // items that are pending in the JIT job queue.
  2593. // Alloc first and then free so that the native code generator is at a different address
  2594. #if ENABLE_NATIVE_CODEGEN
  2595. HRESULT ScriptContext::RecreateNativeCodeGenerator()
  2596. {
  2597. NativeCodeGenerator* oldCodeGen = this->nativeCodeGen;
  2598. HRESULT hr = S_OK;
  2599. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2600. this->nativeCodeGen = NewNativeCodeGenerator(this);
  2601. SetProfileModeNativeCodeGen(this->GetNativeCodeGenerator(), this->IsProfiling());
  2602. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2603. // Delete the native code generator and recreate so that all jobs get cleared properly
  2604. // and re-jitted.
  2605. CloseNativeCodeGenerator(oldCodeGen);
  2606. DeleteNativeCodeGenerator(oldCodeGen);
  2607. return hr;
  2608. }
  2609. #endif
  2610. #ifdef ENABLE_SCRIPT_DEBUGGING
  2611. HRESULT ScriptContext::OnDebuggerAttached()
  2612. {
  2613. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerAttached: start 0x%p\n"), this);
  2614. Js::StepController* stepController = &this->GetThreadContext()->GetDebugManager()->stepController;
  2615. if (stepController->IsActive())
  2616. {
  2617. AssertMsg(stepController->GetActivatedContext() == nullptr, "StepController should not be active when we attach.");
  2618. stepController->Deactivate(); // Defense in depth
  2619. }
  2620. bool shouldPerformSourceRundown = false;
  2621. if (this->IsScriptContextInNonDebugMode())
  2622. {
  2623. // Today we do source rundown as a part of attach to support VS attaching without
  2624. // first calling PerformSourceRundown. PerformSourceRundown will be called once
  2625. // by debugger host prior to attaching.
  2626. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::SourceRundown);
  2627. // Need to perform rundown only once.
  2628. shouldPerformSourceRundown = true;
  2629. }
  2630. // Rundown on all existing functions and change their thunks so that they will go to debug mode once they are called.
  2631. HRESULT hr = OnDebuggerAttachedDetached(/*attach*/ true);
  2632. // Debugger attach/detach failure is catastrophic, take down the process
  2633. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2634. // Disable QC while functions are re-parsed as this can be time consuming
  2635. AutoDisableInterrupt autoDisableInterrupt(this->threadContext, false /* explicitCompletion */);
  2636. hr = this->GetDebugContext()->RundownSourcesAndReparse(shouldPerformSourceRundown, /*shouldReparseFunctions*/ true);
  2637. if (this->IsClosed())
  2638. {
  2639. return hr;
  2640. }
  2641. // Debugger attach/detach failure is catastrophic, take down the process
  2642. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2643. HRESULT hrEntryPointUpdate = S_OK;
  2644. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2645. #ifdef ASMJS_PLAT
  2646. TempArenaAllocatorObject* tmpAlloc = GetTemporaryAllocator(_u("DebuggerTransition"));
  2647. debugTransitionAlloc = tmpAlloc->GetAllocator();
  2648. asmJsEnvironmentMap = Anew(debugTransitionAlloc, AsmFunctionMap, debugTransitionAlloc);
  2649. #endif
  2650. // Still do the pass on the function's entrypoint to reflect its state with the functionbody's entrypoint.
  2651. this->UpdateRecyclerFunctionEntryPointsForDebugger();
  2652. #ifdef ASMJS_PLAT
  2653. auto asmEnvIter = asmJsEnvironmentMap->GetIterator();
  2654. while (asmEnvIter.IsValid())
  2655. {
  2656. // we are attaching, change frame setup for asm.js frame to javascript frame
  2657. SList<AsmJsScriptFunction *> * funcList = asmEnvIter.CurrentValue();
  2658. Assert(!funcList->Empty());
  2659. void* newEnv = AsmJsModuleInfo::ConvertFrameForJavascript(asmEnvIter.CurrentKey(), funcList->Head());
  2660. funcList->Iterate([&](AsmJsScriptFunction * func)
  2661. {
  2662. func->SetEnvironment(RecyclerNewPlus(this->GetRecycler(), sizeof(void*), FrameDisplay, 1));
  2663. func->GetEnvironment()->SetItem(0, newEnv);
  2664. });
  2665. asmEnvIter.MoveNext();
  2666. }
  2667. // walk through and clean up the asm.js fields as a discrete step, because module might be multiply linked
  2668. auto asmCleanupIter = asmJsEnvironmentMap->GetIterator();
  2669. while (asmCleanupIter.IsValid())
  2670. {
  2671. SList<AsmJsScriptFunction *> * funcList = asmCleanupIter.CurrentValue();
  2672. Assert(!funcList->Empty());
  2673. funcList->Iterate([](AsmJsScriptFunction * func)
  2674. {
  2675. func->SetModuleEnvironment(nullptr);
  2676. func->GetFunctionBody()->ResetAsmJsInfo();
  2677. });
  2678. asmCleanupIter.MoveNext();
  2679. }
  2680. ReleaseTemporaryAllocator(tmpAlloc);
  2681. #endif
  2682. END_TRANSLATE_OOM_TO_HRESULT(hrEntryPointUpdate);
  2683. if (hrEntryPointUpdate != S_OK)
  2684. {
  2685. // should only be here for OOM
  2686. Assert(hrEntryPointUpdate == E_OUTOFMEMORY);
  2687. return hrEntryPointUpdate;
  2688. }
  2689. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerAttached: done 0x%p, hr = 0x%X\n"), this, hr);
  2690. return hr;
  2691. }
  2692. // Reverts the script context state back to the state before debugging began.
  2693. HRESULT ScriptContext::OnDebuggerDetached()
  2694. {
  2695. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerDetached: start 0x%p\n"), this);
  2696. Js::StepController* stepController = &this->GetThreadContext()->GetDebugManager()->stepController;
  2697. if (stepController->IsActive())
  2698. {
  2699. // Normally step controller is deactivated on start of dispatch (step, async break, exception, etc),
  2700. // and in the beginning of interpreter loop we check for step complete (can cause check whether current bytecode belong to stmt).
  2701. // But since it holds to functionBody/statementMaps, we have to deactivate it as func bodies are going away/reparsed.
  2702. stepController->Deactivate();
  2703. }
  2704. // Go through all existing functions and change their thunks back to using non-debug mode versions when called
  2705. // and notify the script context that the debugger has detached to allow it to revert the runtime to the proper
  2706. // state (JIT enabled).
  2707. HRESULT hr = OnDebuggerAttachedDetached(/*attach*/ false);
  2708. // Debugger attach/detach failure is catastrophic, take down the process
  2709. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2710. // Move the debugger into source rundown mode.
  2711. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::SourceRundown);
  2712. // Disable QC while functions are re-parsed as this can be time consuming
  2713. AutoDisableInterrupt autoDisableInterrupt(this->threadContext, false /* explicitCompletion */);
  2714. // Force a reparse so that indirect function caches are updated.
  2715. hr = this->GetDebugContext()->RundownSourcesAndReparse(/*shouldPerformSourceRundown*/ false, /*shouldReparseFunctions*/ true);
  2716. if (this->IsClosed())
  2717. {
  2718. return hr;
  2719. }
  2720. // Debugger attach/detach failure is catastrophic, take down the process
  2721. DEBUGGER_ATTACHDETACH_FATAL_ERROR_IF_FAILED(hr);
  2722. // Still do the pass on the function's entrypoint to reflect its state with the functionbody's entrypoint.
  2723. this->UpdateRecyclerFunctionEntryPointsForDebugger();
  2724. OUTPUT_TRACE(Js::DebuggerPhase, _u("ScriptContext::OnDebuggerDetached: done 0x%p, hr = 0x%X\n"), this, hr);
  2725. return hr;
  2726. }
  2727. HRESULT ScriptContext::OnDebuggerAttachedDetached(bool attach)
  2728. {
  2729. // notify threadContext that debugger is attaching so do not do expire
  2730. struct AutoRestore
  2731. {
  2732. AutoRestore(ThreadContext* threadContext)
  2733. :threadContext(threadContext)
  2734. {
  2735. this->threadContext->GetDebugManager()->SetDebuggerAttaching(true);
  2736. }
  2737. ~AutoRestore()
  2738. {
  2739. this->threadContext->GetDebugManager()->SetDebuggerAttaching(false);
  2740. }
  2741. private:
  2742. ThreadContext* threadContext;
  2743. } autoRestore(this->GetThreadContext());
  2744. // xplat-todo: (obastemur) Enable JIT on Debug mode
  2745. // CodeGen entrypoint can be deleted before we are able to unregister
  2746. // due to how we handle xdata on xplat, resetting the entrypoints below might affect CodeGen process.
  2747. // it is safer (on xplat) to turn JIT off during Debug for now.
  2748. #ifdef _WIN32
  2749. if (!Js::Configuration::Global.EnableJitInDebugMode())
  2750. #endif
  2751. {
  2752. if (attach)
  2753. {
  2754. // Now force nonative, so the job will not be put in jit queue.
  2755. ForceNoNative();
  2756. }
  2757. else
  2758. {
  2759. // Take the runtime out of interpreted mode so the JIT
  2760. // queue can be exercised.
  2761. this->ForceNative();
  2762. }
  2763. }
  2764. // Invalidate all the caches.
  2765. this->threadContext->InvalidateAllProtoInlineCaches();
  2766. this->threadContext->InvalidateAllStoreFieldInlineCaches();
  2767. this->threadContext->InvalidateAllIsInstInlineCaches();
  2768. if (!attach)
  2769. {
  2770. this->UnRegisterDebugThunk();
  2771. // Remove all breakpoint probes
  2772. this->GetDebugContext()->GetProbeContainer()->RemoveAllProbes();
  2773. }
  2774. HRESULT hr = S_OK;
  2775. #ifndef _WIN32
  2776. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2777. {
  2778. // xplat eh_frame handling is a bit different than Windows
  2779. // RecreateNativeCodeGenerator call below will be cleaning up
  2780. // XDataAllocation and we won't be able to __DEREGISTER_FRAME
  2781. // xplat-todo: make eh_frame handling better
  2782. this->sourceList->Map([=](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef) {
  2783. Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  2784. if (sourceInfo != nullptr)
  2785. {
  2786. sourceInfo->MapFunction([](Js::FunctionBody* functionBody) {
  2787. functionBody->ResetEntryPoint();
  2788. });
  2789. }
  2790. });
  2791. }
  2792. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2793. if (FAILED(hr))
  2794. {
  2795. return hr;
  2796. }
  2797. #endif
  2798. if (!CONFIG_FLAG(ForceDiagnosticsMode))
  2799. {
  2800. #if ENABLE_NATIVE_CODEGEN
  2801. // Recreate the native code generator so that all pending
  2802. // JIT work items will be cleared.
  2803. hr = RecreateNativeCodeGenerator();
  2804. if (FAILED(hr))
  2805. {
  2806. return hr;
  2807. }
  2808. #endif
  2809. if (attach)
  2810. {
  2811. // We need to transition to debug mode after the NativeCodeGenerator is cleared/closed. Since the NativeCodeGenerator will be working on a different thread - it may
  2812. // be checking on the DebuggerState (from ScriptContext) while emitting code.
  2813. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::Debugging);
  2814. #if ENABLE_NATIVE_CODEGEN
  2815. UpdateNativeCodeGeneratorForDebugMode(this->nativeCodeGen);
  2816. #endif
  2817. }
  2818. }
  2819. else if (attach)
  2820. {
  2821. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::Debugging);
  2822. }
  2823. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  2824. {
  2825. // Remap all the function entry point thunks.
  2826. this->sourceList->Map([=](uint i, RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef) {
  2827. Js::Utf8SourceInfo* sourceInfo = sourceInfoWeakRef->Get();
  2828. if (sourceInfo != nullptr)
  2829. {
  2830. if (!sourceInfo->GetIsLibraryCode())
  2831. {
  2832. sourceInfo->SetInDebugMode(attach);
  2833. sourceInfo->MapFunction([](Js::FunctionBody* functionBody) {
  2834. functionBody->SetEntryToDeferParseForDebugger();
  2835. });
  2836. }
  2837. #ifdef _WIN32
  2838. else
  2839. {
  2840. sourceInfo->MapFunction([](Js::FunctionBody* functionBody) {
  2841. functionBody->ResetEntryPoint();
  2842. });
  2843. }
  2844. #endif
  2845. }
  2846. });
  2847. }
  2848. END_TRANSLATE_OOM_TO_HRESULT(hr);
  2849. if (FAILED(hr))
  2850. {
  2851. return hr;
  2852. }
  2853. if (attach)
  2854. {
  2855. this->RegisterDebugThunk();
  2856. }
  2857. #if ENABLE_PROFILE_INFO
  2858. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  2859. // Reset the dynamic profile list
  2860. if (this->Cache()->profileInfoList)
  2861. {
  2862. this->Cache()->profileInfoList->Reset();
  2863. }
  2864. #endif
  2865. #endif
  2866. return hr;
  2867. }
  2868. #endif
  2869. #if defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  2870. // We use ProfileThunk under debugger.
  2871. void ScriptContext::RegisterDebugThunk(bool calledDuringAttach /*= true*/)
  2872. {
  2873. if (this->IsExceptionWrapperForBuiltInsEnabled())
  2874. {
  2875. this->CurrentThunk = ProfileEntryThunk;
  2876. this->CurrentCrossSiteThunk = CrossSite::ProfileThunk;
  2877. #if ENABLE_NATIVE_CODEGEN
  2878. SetProfileModeNativeCodeGen(this->GetNativeCodeGenerator(), TRUE);
  2879. #endif
  2880. // Set library to profile mode so that for built-ins all new instances of functions
  2881. // are created with entry point set to the ProfileThunk.
  2882. this->javascriptLibrary->SetProfileMode(true);
  2883. this->javascriptLibrary->SetDispatchProfile(true, DispatchProfileInvoke);
  2884. if (!calledDuringAttach)
  2885. {
  2886. #ifdef ENABLE_SCRIPT_PROFILING
  2887. m_fTraceDomCall = TRUE; // This flag is always needed in DebugMode to wrap external functions with DebugProfileThunk
  2888. #endif
  2889. // Update the function objects currently present in there.
  2890. this->SetFunctionInRecyclerToProfileMode(true/*enumerateNonUserFunctionsOnly*/);
  2891. }
  2892. }
  2893. }
  2894. void ScriptContext::UnRegisterDebugThunk()
  2895. {
  2896. if (!this->IsProfiling() && this->IsExceptionWrapperForBuiltInsEnabled())
  2897. {
  2898. this->CurrentThunk = DefaultEntryThunk;
  2899. this->CurrentCrossSiteThunk = CrossSite::DefaultThunk;
  2900. #if ENABLE_NATIVE_CODEGEN
  2901. SetProfileModeNativeCodeGen(this->GetNativeCodeGenerator(), FALSE);
  2902. #endif
  2903. if (!this->IsProfiling())
  2904. {
  2905. this->javascriptLibrary->SetProfileMode(false);
  2906. this->javascriptLibrary->SetDispatchProfile(false, DispatchDefaultInvoke);
  2907. }
  2908. }
  2909. }
  2910. #endif // defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  2911. #ifdef ENABLE_SCRIPT_PROFILING
  2912. HRESULT ScriptContext::RegisterBuiltinFunctions(RegisterExternalLibraryType RegisterExternalLibrary)
  2913. {
  2914. Assert(m_pProfileCallback != NULL);
  2915. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RegisterBuiltinFunctions\n"));
  2916. HRESULT hr = S_OK;
  2917. // Consider creating ProfileArena allocator instead of General allocator
  2918. if (m_pBuiltinFunctionIdMap == NULL)
  2919. {
  2920. // Anew throws if it OOMs, so the caller into this function needs to handle that exception
  2921. m_pBuiltinFunctionIdMap = Anew(GeneralAllocator(), BuiltinFunctionIdDictionary,
  2922. GeneralAllocator(), 17);
  2923. }
  2924. this->javascriptLibrary->SetProfileMode(TRUE);
  2925. if (FAILED(hr = OnScriptCompiled(BuiltInFunctionsScriptId, PROFILER_SCRIPT_TYPE_NATIVE, NULL)))
  2926. {
  2927. return hr;
  2928. }
  2929. if (FAILED(hr = this->javascriptLibrary->ProfilerRegisterBuiltIns()))
  2930. {
  2931. return hr;
  2932. }
  2933. // External Library
  2934. if (RegisterExternalLibrary != NULL)
  2935. {
  2936. (*RegisterExternalLibrary)(this);
  2937. }
  2938. return hr;
  2939. }
  2940. #endif // ENABLE_SCRIPT_PROFILING
  2941. #ifdef ENABLE_SCRIPT_DEBUGGING
  2942. void ScriptContext::SetFunctionInRecyclerToProfileMode(bool enumerateNonUserFunctionsOnly/* = false*/)
  2943. {
  2944. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::SetFunctionInRecyclerToProfileMode started (m_fTraceDomCall : %s)\n"), IsTrueOrFalse(IsTraceDomCall()));
  2945. // Mark this script context isEnumeratingRecyclerObjects
  2946. AutoEnumeratingRecyclerObjects enumeratingRecyclerObjects(this);
  2947. m_enumerateNonUserFunctionsOnly = enumerateNonUserFunctionsOnly;
  2948. this->recycler->EnumerateObjects(JavascriptLibrary::EnumFunctionClass, &ScriptContext::RecyclerEnumClassEnumeratorCallback);
  2949. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::SetFunctionInRecyclerToProfileMode ended\n"));
  2950. }
  2951. void ScriptContext::UpdateRecyclerFunctionEntryPointsForDebugger()
  2952. {
  2953. // Mark this script context isEnumeratingRecyclerObjects
  2954. AutoEnumeratingRecyclerObjects enumeratingRecyclerObjects(this);
  2955. this->recycler->EnumerateObjects(JavascriptLibrary::EnumFunctionClass, &ScriptContext::RecyclerFunctionCallbackForDebugger);
  2956. }
  2957. #ifdef ASMJS_PLAT
  2958. void ScriptContext::TransitionEnvironmentForDebugger(ScriptFunction * scriptFunction)
  2959. {
  2960. FunctionBody* functionBody = scriptFunction->GetFunctionBody();
  2961. #ifdef ENABLE_WASM
  2962. // Wasm functions will not get reparsed, but the jitted code will be lost
  2963. // Reset the entry point
  2964. if (functionBody->IsWasmFunction())
  2965. {
  2966. // In case we are in debugger mode, make sure we use the non profiling thunk for this new entry point
  2967. JavascriptMethod realThunk = CurrentThunk;
  2968. CurrentThunk = AsmJsDefaultEntryThunk;
  2969. functionBody->ResetEntryPoint();
  2970. CurrentThunk = realThunk;
  2971. bool isDeferred = functionBody->GetAsmJsFunctionInfo()->IsWasmDeferredParse();
  2972. // Make sure the function and the function body are using the same entry point
  2973. scriptFunction->ChangeEntryPoint(functionBody->GetDefaultEntryPointInfo(), AsmJsDefaultEntryThunk);
  2974. WasmLibrary::SetWasmEntryPointToInterpreter(scriptFunction, isDeferred);
  2975. // Reset jit status for this function
  2976. functionBody->SetIsAsmJsFullJitScheduled(false);
  2977. Assert(functionBody->HasValidEntryPoint());
  2978. }
  2979. else
  2980. #endif
  2981. if (scriptFunction->GetScriptContext()->IsScriptContextInDebugMode())
  2982. {
  2983. if (functionBody->IsInDebugMode() &&
  2984. scriptFunction->GetFunctionBody()->GetAsmJsFunctionInfo() != nullptr &&
  2985. scriptFunction->GetFunctionBody()->GetAsmJsFunctionInfo()->GetModuleFunctionBody() != nullptr)
  2986. {
  2987. AsmJsScriptFunction* asmFunc = AsmJsScriptFunction::FromVar(scriptFunction);
  2988. void* env = (void*)asmFunc->GetModuleEnvironment();
  2989. SList<AsmJsScriptFunction*> * funcList = nullptr;
  2990. if (asmJsEnvironmentMap->TryGetValue(env, &funcList))
  2991. {
  2992. funcList->Push(asmFunc);
  2993. }
  2994. else
  2995. {
  2996. SList<AsmJsScriptFunction*> * newList = Anew(debugTransitionAlloc, SList<AsmJsScriptFunction*>, debugTransitionAlloc);
  2997. asmJsEnvironmentMap->AddNew(env, newList);
  2998. newList->Push(asmFunc);
  2999. }
  3000. }
  3001. }
  3002. }
  3003. #endif
  3004. /*static*/
  3005. void ScriptContext::RecyclerFunctionCallbackForDebugger(void *address, size_t size)
  3006. {
  3007. JavascriptFunction *pFunction = (JavascriptFunction *)address;
  3008. ScriptContext* scriptContext = pFunction->GetScriptContext();
  3009. if (scriptContext == nullptr || scriptContext->IsClosed())
  3010. {
  3011. // Can't enumerate from closed scriptcontext
  3012. return;
  3013. }
  3014. if (!scriptContext->IsEnumeratingRecyclerObjects())
  3015. {
  3016. return; // function not from enumerating script context
  3017. }
  3018. // Wrapped function are not allocated with the EnumClass bit
  3019. Assert(pFunction->GetFunctionInfo() != &JavascriptExternalFunction::EntryInfo::WrappedFunctionThunk);
  3020. JavascriptMethod entryPoint = pFunction->GetEntryPoint();
  3021. FunctionInfo * info = pFunction->GetFunctionInfo();
  3022. FunctionProxy * proxy = info->GetFunctionProxy();
  3023. if (proxy == nullptr)
  3024. {
  3025. // Not a user defined function, we need to wrap them with try-catch for "continue after exception"
  3026. if (!pFunction->IsScriptFunction() && IsExceptionWrapperForBuiltInsEnabled(scriptContext))
  3027. {
  3028. #if defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  3029. if (scriptContext->IsScriptContextInDebugMode())
  3030. {
  3031. // We are attaching.
  3032. // For built-ins, WinRT and DOM functions which are already in recycler, change entry points to route to debug/profile thunk.
  3033. ScriptContext::SetEntryPointToProfileThunk(pFunction);
  3034. }
  3035. else
  3036. {
  3037. // We are detaching.
  3038. // For built-ins, WinRT and DOM functions which are already in recycler, restore entry points to original.
  3039. if (!scriptContext->IsProfiling())
  3040. {
  3041. ScriptContext::RestoreEntryPointFromProfileThunk(pFunction);
  3042. }
  3043. // If we are profiling, don't change anything.
  3044. }
  3045. #else
  3046. AssertMsg(false, "Debugging/Profiling needs to be enabled to change thunks");
  3047. #endif
  3048. }
  3049. return;
  3050. }
  3051. Assert(proxy->GetFunctionInfo() == info);
  3052. if (!proxy->IsFunctionBody())
  3053. {
  3054. // REVIEW: why we still have function that is still deferred?
  3055. return;
  3056. }
  3057. Assert(pFunction->IsScriptFunction());
  3058. // Excluding the internal library code, which is not debuggable already
  3059. if (!proxy->GetUtf8SourceInfo()->GetIsLibraryCode())
  3060. {
  3061. // Reset the constructor cache to default, so that it will not pick up the cached type, created before debugging.
  3062. // Look bug: 301517
  3063. pFunction->ResetConstructorCacheToDefault();
  3064. }
  3065. if (ScriptFunctionWithInlineCache::Is(pFunction))
  3066. {
  3067. ScriptFunctionWithInlineCache::FromVar(pFunction)->ClearInlineCacheOnFunctionObject();
  3068. }
  3069. // We should have force parsed the function, and have a function body
  3070. FunctionBody * pBody = proxy->GetFunctionBody();
  3071. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3072. if (scriptContext->IsScriptContextInDebugMode() &&
  3073. !proxy->GetUtf8SourceInfo()->GetIsLibraryCode() &&
  3074. #ifdef ENABLE_WASM
  3075. !pBody->IsWasmFunction() &&
  3076. #endif
  3077. !pBody->IsInDebugMode())
  3078. {
  3079. // Identifying if any function escaped for not being in debug mode. (This can be removed as a part of TFS : 935011)
  3080. Throw::FatalInternalError();
  3081. }
  3082. #endif
  3083. ScriptFunction * scriptFunction = ScriptFunction::FromVar(pFunction);
  3084. #ifdef ASMJS_PLAT
  3085. scriptContext->TransitionEnvironmentForDebugger(scriptFunction);
  3086. #endif
  3087. JavascriptMethod newEntryPoint;
  3088. if (CrossSite::IsThunk(entryPoint))
  3089. {
  3090. // Can't change from cross-site to non-cross-site, but still need to update the e.p.info on ScriptFunctionType.
  3091. newEntryPoint = entryPoint;
  3092. }
  3093. else
  3094. {
  3095. newEntryPoint = pBody->GetDirectEntryPoint(pBody->GetDefaultFunctionEntryPointInfo());
  3096. }
  3097. scriptFunction->ChangeEntryPoint(pBody->GetDefaultFunctionEntryPointInfo(), newEntryPoint);
  3098. }
  3099. #endif
  3100. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  3101. void ScriptContext::RecyclerEnumClassEnumeratorCallback(void *address, size_t size)
  3102. {
  3103. // TODO: we are assuming its function because for now we are enumerating only on functions
  3104. // In future if the RecyclerNewEnumClass is used of Recyclable objects or Dynamic object, we would need a check if it is function
  3105. JavascriptFunction *pFunction = (JavascriptFunction *)address;
  3106. ScriptContext* scriptContext = pFunction->GetScriptContext();
  3107. if (scriptContext == nullptr || scriptContext->IsClosed())
  3108. {
  3109. // Can't enumerate from closed scriptcontext
  3110. return;
  3111. }
  3112. if (!scriptContext->IsEnumeratingRecyclerObjects())
  3113. {
  3114. return; // function not from enumerating script context
  3115. }
  3116. if (!scriptContext->IsTraceDomCall() && (pFunction->IsExternalFunction() || pFunction->IsWinRTFunction()))
  3117. {
  3118. return;
  3119. }
  3120. if (scriptContext->IsEnumerateNonUserFunctionsOnly() && pFunction->IsScriptFunction())
  3121. {
  3122. return;
  3123. }
  3124. // Wrapped function are not allocated with the EnumClass bit
  3125. Assert(pFunction->GetFunctionInfo() != &JavascriptExternalFunction::EntryInfo::WrappedFunctionThunk);
  3126. JavascriptMethod entryPoint = pFunction->GetEntryPoint();
  3127. FunctionProxy *proxy = pFunction->GetFunctionProxy();
  3128. if (proxy != NULL)
  3129. {
  3130. #if defined(ENABLE_SCRIPT_PROFILING)
  3131. #if ENABLE_DEBUG_CONFIG_OPTIONS
  3132. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3133. #endif
  3134. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::RecyclerEnumClassEnumeratorCallback\n"));
  3135. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\tFunctionProxy : 0x%08X, FunctionNumber : %s, DeferredParseAttributes : %d, EntryPoint : 0x%08X"),
  3136. (DWORD_PTR)proxy, proxy->GetDebugNumberSet(debugStringBuffer), proxy->GetAttributes(), (DWORD_PTR)entryPoint);
  3137. #if ENABLE_NATIVE_CODEGEN
  3138. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u(" (IsIntermediateCodeGenThunk : %s, isNative : %s)\n"),
  3139. IsTrueOrFalse(IsIntermediateCodeGenThunk(entryPoint)), IsTrueOrFalse(scriptContext->IsNativeAddress(entryPoint)));
  3140. #endif
  3141. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\n"));
  3142. #endif
  3143. #if ENABLE_NATIVE_CODEGEN
  3144. if (!IsIntermediateCodeGenThunk(entryPoint) && entryPoint != DynamicProfileInfo::EnsureDynamicProfileInfoThunk)
  3145. #endif
  3146. {
  3147. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\t\tJs::ScriptContext::GetProfileModeThunk : 0x%08X\n"), (DWORD_PTR)Js::ScriptContext::GetProfileModeThunk(entryPoint));
  3148. ScriptFunction * scriptFunction = ScriptFunction::FromVar(pFunction);
  3149. scriptFunction->ChangeEntryPoint(proxy->GetDefaultEntryPointInfo(), Js::ScriptContext::GetProfileModeThunk(entryPoint));
  3150. #if ENABLE_NATIVE_CODEGEN && defined(ENABLE_SCRIPT_PROFILING)
  3151. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\tUpdated entrypoint : 0x%08X (isNative : %s)\n"), (DWORD_PTR)pFunction->GetEntryPoint(), IsTrueOrFalse(scriptContext->IsNativeAddress(entryPoint)));
  3152. #endif
  3153. }
  3154. }
  3155. else
  3156. {
  3157. ScriptContext::SetEntryPointToProfileThunk(pFunction);
  3158. }
  3159. }
  3160. // static
  3161. void ScriptContext::SetEntryPointToProfileThunk(JavascriptFunction* function)
  3162. {
  3163. JavascriptMethod entryPoint = function->GetEntryPoint();
  3164. if (entryPoint == Js::CrossSite::DefaultThunk)
  3165. {
  3166. function->SetEntryPoint(Js::CrossSite::ProfileThunk);
  3167. }
  3168. else if (entryPoint != Js::CrossSite::ProfileThunk && entryPoint != ProfileEntryThunk)
  3169. {
  3170. function->SetEntryPoint(ProfileEntryThunk);
  3171. }
  3172. }
  3173. // static
  3174. void ScriptContext::RestoreEntryPointFromProfileThunk(JavascriptFunction* function)
  3175. {
  3176. JavascriptMethod entryPoint = function->GetEntryPoint();
  3177. if (entryPoint == Js::CrossSite::ProfileThunk)
  3178. {
  3179. function->SetEntryPoint(Js::CrossSite::DefaultThunk);
  3180. }
  3181. else if (entryPoint == ProfileEntryThunk)
  3182. {
  3183. function->SetEntryPoint(function->GetFunctionInfo()->GetOriginalEntryPoint());
  3184. }
  3185. }
  3186. JavascriptMethod ScriptContext::GetProfileModeThunk(JavascriptMethod entryPoint)
  3187. {
  3188. #if ENABLE_NATIVE_CODEGEN
  3189. Assert(!IsIntermediateCodeGenThunk(entryPoint));
  3190. #endif
  3191. if (entryPoint == DefaultDeferredParsingThunk || entryPoint == ProfileDeferredParsingThunk)
  3192. {
  3193. return ProfileDeferredParsingThunk;
  3194. }
  3195. if (entryPoint == DefaultDeferredDeserializeThunk || entryPoint == ProfileDeferredDeserializeThunk)
  3196. {
  3197. return ProfileDeferredDeserializeThunk;
  3198. }
  3199. if (CrossSite::IsThunk(entryPoint))
  3200. {
  3201. return CrossSite::ProfileThunk;
  3202. }
  3203. return ProfileEntryThunk;
  3204. }
  3205. #endif // defined(ENABLE_SCRIPT_PROFILING) || defiend(ENABLE_SCRIPT_DEBUGGING)
  3206. #if _M_IX86
  3207. __declspec(naked)
  3208. Var ScriptContext::ProfileModeDeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...)
  3209. {
  3210. // Register functions
  3211. __asm
  3212. {
  3213. push ebp
  3214. mov ebp, esp
  3215. lea eax, [esp + 8]
  3216. push eax
  3217. call ScriptContext::ProfileModeDeferredParse
  3218. #ifdef _CONTROL_FLOW_GUARD
  3219. // verify that the call target is valid
  3220. mov ecx, eax
  3221. call[__guard_check_icall_fptr]
  3222. mov eax, ecx
  3223. #endif
  3224. pop ebp
  3225. // Although we don't restore ESP here on WinCE, this is fine because script profiler is not shipped for WinCE.
  3226. jmp eax
  3227. }
  3228. }
  3229. #elif defined(_M_X64) || defined(_M_ARM32_OR_ARM64)
  3230. // Do nothing: the implementation of ScriptContext::ProfileModeDeferredParsingThunk is declared (appropriately decorated) in
  3231. // Language\amd64\amd64_Thunks.asm and Language\arm\arm_Thunks.asm and Language\arm64\arm64_Thunks.asm respectively.
  3232. #else
  3233. Var ScriptContext::ProfileModeDeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...)
  3234. {
  3235. Js::Throw::NotImplemented();
  3236. return nullptr;
  3237. }
  3238. #endif
  3239. Js::JavascriptMethod ScriptContext::ProfileModeDeferredParse(ScriptFunction ** functionRef)
  3240. {
  3241. #if ENABLE_DEBUG_CONFIG_OPTIONS
  3242. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3243. #endif
  3244. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::ProfileModeDeferredParse FunctionNumber : %s, startEntrypoint : 0x%08X\n"), (*functionRef)->GetFunctionProxy()->GetDebugNumberSet(debugStringBuffer), (*functionRef)->GetEntryPoint());
  3245. BOOL fParsed = FALSE;
  3246. JavascriptMethod entryPoint = Js::JavascriptFunction::DeferredParseCore(functionRef, fParsed);
  3247. #ifdef ENABLE_SCRIPT_PROFILING
  3248. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("\t\tIsParsed : %s, updatedEntrypoint : 0x%08X\n"), IsTrueOrFalse(fParsed), entryPoint);
  3249. //To get the scriptContext we only need the functionProxy
  3250. FunctionProxy *pRootBody = (*functionRef)->GetFunctionProxy();
  3251. ScriptContext *pScriptContext = pRootBody->GetScriptContext();
  3252. if (pScriptContext->IsProfiling() && !pRootBody->GetFunctionBody()->HasFunctionCompiledSent())
  3253. {
  3254. pScriptContext->RegisterScript(pRootBody, FALSE /*fRegisterScript*/);
  3255. }
  3256. // We can come to this function even though we have stopped profiling.
  3257. Assert(!pScriptContext->IsProfiling() || (*functionRef)->GetFunctionBody()->GetProfileSession() == pScriptContext->GetProfileSession());
  3258. #endif
  3259. return entryPoint;
  3260. }
  3261. #if _M_IX86
  3262. __declspec(naked)
  3263. Var ScriptContext::ProfileModeDeferredDeserializeThunk(RecyclableObject* function, CallInfo callInfo, ...)
  3264. {
  3265. // Register functions
  3266. __asm
  3267. {
  3268. push ebp
  3269. mov ebp, esp
  3270. push[esp + 8]
  3271. call ScriptContext::ProfileModeDeferredDeserialize
  3272. #ifdef _CONTROL_FLOW_GUARD
  3273. // verify that the call target is valid
  3274. mov ecx, eax
  3275. call[__guard_check_icall_fptr]
  3276. mov eax, ecx
  3277. #endif
  3278. pop ebp
  3279. // Although we don't restore ESP here on WinCE, this is fine because script profiler is not shipped for WinCE.
  3280. jmp eax
  3281. }
  3282. }
  3283. #elif defined(_M_X64) || defined(_M_ARM32_OR_ARM64)
  3284. // Do nothing: the implementation of ScriptContext::ProfileModeDeferredDeserializeThunk is declared (appropriately decorated) in
  3285. // Language\amd64\amd64_Thunks.asm and Language\arm\arm_Thunks.asm respectively.
  3286. #endif
  3287. Js::JavascriptMethod ScriptContext::ProfileModeDeferredDeserialize(ScriptFunction *function)
  3288. {
  3289. #if ENABLE_DEBUG_CONFIG_OPTIONS
  3290. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3291. #endif
  3292. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::ProfileModeDeferredDeserialize FunctionNumber : %s\n"), function->GetFunctionProxy()->GetDebugNumberSet(debugStringBuffer));
  3293. JavascriptMethod entryPoint = Js::JavascriptFunction::DeferredDeserialize(function);
  3294. #ifdef ENABLE_SCRIPT_PROFILING
  3295. //To get the scriptContext; we only need the FunctionProxy
  3296. FunctionProxy *pRootBody = function->GetFunctionProxy();
  3297. ScriptContext *pScriptContext = pRootBody->GetScriptContext();
  3298. if (pScriptContext->IsProfiling() && !pRootBody->GetFunctionBody()->HasFunctionCompiledSent())
  3299. {
  3300. pScriptContext->RegisterScript(pRootBody, FALSE /*fRegisterScript*/);
  3301. }
  3302. // We can come to this function even though we have stopped profiling.
  3303. Assert(!pScriptContext->IsProfiling() || function->GetFunctionBody()->GetProfileSession() == pScriptContext->GetProfileSession());
  3304. #endif
  3305. return entryPoint;
  3306. }
  3307. #ifdef ENABLE_SCRIPT_PROFILING
  3308. BOOL ScriptContext::GetProfileInfo(
  3309. JavascriptFunction* function,
  3310. PROFILER_TOKEN &scriptId,
  3311. PROFILER_TOKEN &functionId)
  3312. {
  3313. BOOL fCanProfile = (m_pProfileCallback != nullptr && m_fTraceFunctionCall);
  3314. if (!fCanProfile)
  3315. {
  3316. return FALSE;
  3317. }
  3318. Js::FunctionInfo* functionInfo = function->GetFunctionInfo();
  3319. if (functionInfo->GetAttributes() & FunctionInfo::DoNotProfile)
  3320. {
  3321. return FALSE;
  3322. }
  3323. Js::FunctionBody * functionBody = functionInfo->GetFunctionBody();
  3324. if (functionBody == nullptr)
  3325. {
  3326. functionId = GetFunctionNumber(functionInfo->GetOriginalEntryPoint());
  3327. if (functionId == -1)
  3328. {
  3329. // Dom Call
  3330. return m_fTraceDomCall && (m_pProfileCallback2 != nullptr);
  3331. }
  3332. else
  3333. {
  3334. // Builtin function
  3335. scriptId = BuiltInFunctionsScriptId;
  3336. return m_fTraceNativeFunctionCall;
  3337. }
  3338. }
  3339. else if (!functionBody->GetUtf8SourceInfo()->GetIsLibraryCode() || functionBody->IsPublicLibraryCode()) // user script or public library code
  3340. {
  3341. scriptId = (PROFILER_TOKEN)functionBody->GetUtf8SourceInfo()->GetSourceInfoId();
  3342. functionId = functionBody->GetFunctionNumber();
  3343. return TRUE;
  3344. }
  3345. return FALSE;
  3346. }
  3347. #endif // ENABLE_SCRIPT_PROFILING
  3348. bool ScriptContext::IsForceNoNative()
  3349. {
  3350. bool forceNoNative = false;
  3351. if (this->IsScriptContextInSourceRundownOrDebugMode())
  3352. {
  3353. forceNoNative = this->IsInterpreted();
  3354. }
  3355. else if (!Js::Configuration::Global.EnableJitInDebugMode())
  3356. {
  3357. forceNoNative = true;
  3358. this->ForceNoNative();
  3359. }
  3360. return forceNoNative;
  3361. }
  3362. #ifdef ENABLE_SCRIPT_DEBUGGING
  3363. void ScriptContext::InitializeDebugging()
  3364. {
  3365. if (!this->IsScriptContextInDebugMode()) // If we already in debug mode, we would have done below changes already.
  3366. {
  3367. this->GetDebugContext()->SetDebuggerMode(Js::DebuggerMode::Debugging);
  3368. if (this->IsScriptContextInDebugMode())
  3369. {
  3370. // Note: for this we need final IsInDebugMode and NativeCodeGen initialized,
  3371. // and inside EnsureScriptContext, which seems appropriate as well,
  3372. // it's too early as debugger manager is not registered, thus IsDebuggerEnvironmentAvailable is false.
  3373. this->RegisterDebugThunk(false/*calledDuringAttach*/);
  3374. // TODO: for launch scenario for external and WinRT functions it might be too late to register debug thunk here,
  3375. // as we need the thunk registered before FunctionInfo's for built-ins, that may throw, are created.
  3376. // Need to verify. If that's the case, one way would be to enumerate and fix all external/winRT thunks here.
  3377. }
  3378. }
  3379. }
  3380. #endif
  3381. // Combined profile/debug wrapper thunk.
  3382. // - used when we profile to send profile events
  3383. // - used when we debug, only used for built-in functions
  3384. // - used when we profile and debug
  3385. Var ScriptContext::DebugProfileProbeThunk(RecyclableObject* callable, CallInfo callInfo, ...)
  3386. {
  3387. #if defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  3388. RUNTIME_ARGUMENTS(args, callInfo);
  3389. Assert(!WasmScriptFunction::Is(callable));
  3390. JavascriptFunction* function = JavascriptFunction::FromVar(callable);
  3391. ScriptContext* scriptContext = function->GetScriptContext();
  3392. // We can come here when profiling is not on
  3393. // e.g. User starts profiling, we update all thinks and then stop profiling - we don't update thunk
  3394. // So we still get this call
  3395. #if defined(ENABLE_SCRIPT_PROFILING)
  3396. bool functionEnterEventSent = false;
  3397. char16 *pwszExtractedFunctionName = NULL;
  3398. size_t functionNameLen = 0;
  3399. const char16 *pwszFunctionName = NULL;
  3400. HRESULT hrOfEnterEvent = S_OK;
  3401. PROFILER_TOKEN scriptId = -1;
  3402. PROFILER_TOKEN functionId = -1;
  3403. const bool isProfilingUserCode = scriptContext->GetThreadContext()->IsProfilingUserCode();
  3404. const bool isUserCode = !function->IsLibraryCode();
  3405. const bool fProfile = (isUserCode || isProfilingUserCode) // Only report user code or entry library code
  3406. && scriptContext->GetProfileInfo(function, scriptId, functionId);
  3407. if (fProfile)
  3408. {
  3409. Js::FunctionBody *pBody = function->GetFunctionBody();
  3410. if (pBody != nullptr && !pBody->HasFunctionCompiledSent())
  3411. {
  3412. pBody->RegisterFunction(false/*changeThunk*/);
  3413. }
  3414. #if DEBUG
  3415. { // scope
  3416. Assert(scriptContext->IsProfiling());
  3417. if (pBody && pBody->GetProfileSession() != pBody->GetScriptContext()->GetProfileSession())
  3418. {
  3419. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3420. OUTPUT_TRACE_DEBUGONLY(Js::ScriptProfilerPhase, _u("ScriptContext::ProfileProbeThunk, ProfileSession does not match (%d != %d), functionNumber : %s, functionName : %s\n"),
  3421. pBody->GetProfileSession(), pBody->GetScriptContext()->GetProfileSession(), pBody->GetDebugNumberSet(debugStringBuffer), pBody->GetDisplayName());
  3422. }
  3423. AssertMsg(pBody == NULL || pBody->GetProfileSession() == pBody->GetScriptContext()->GetProfileSession(), "Function info wasn't reported for this profile session");
  3424. }
  3425. #endif // DEBUG
  3426. if (functionId == -1)
  3427. {
  3428. Var sourceString = function->GetSourceString();
  3429. // SourceString will be null for the Js::BoundFunction, don't throw Enter/Exit notification in that case.
  3430. if (sourceString != NULL)
  3431. {
  3432. if (TaggedInt::Is(sourceString))
  3433. {
  3434. PropertyId nameId = TaggedInt::ToInt32(sourceString);
  3435. pwszFunctionName = scriptContext->GetPropertyString(nameId)->GetSz();
  3436. }
  3437. else
  3438. {
  3439. // it is string because user had called in toString extract name from it
  3440. Assert(JavascriptString::Is(sourceString));
  3441. const char16 *pwszToString = ((JavascriptString *)sourceString)->GetSz();
  3442. const char16 *pwszNameStart = wcsstr(pwszToString, _u(" "));
  3443. const char16 *pwszNameEnd = wcsstr(pwszToString, _u("("));
  3444. if (pwszNameStart == nullptr || pwszNameEnd == nullptr || ((int)(pwszNameEnd - pwszNameStart) <= 0))
  3445. {
  3446. functionNameLen = ((JavascriptString *)sourceString)->GetLength() + 1;
  3447. pwszExtractedFunctionName = HeapNewArray(char16, functionNameLen);
  3448. wcsncpy_s(pwszExtractedFunctionName, functionNameLen, pwszToString, _TRUNCATE);
  3449. }
  3450. else
  3451. {
  3452. functionNameLen = pwszNameEnd - pwszNameStart;
  3453. AssertMsg(functionNameLen < INT_MAX, "Allocating array with zero or negative length?");
  3454. pwszExtractedFunctionName = HeapNewArray(char16, functionNameLen);
  3455. wcsncpy_s(pwszExtractedFunctionName, functionNameLen, pwszNameStart + 1, _TRUNCATE);
  3456. }
  3457. pwszFunctionName = pwszExtractedFunctionName;
  3458. }
  3459. functionEnterEventSent = true;
  3460. Assert(pwszFunctionName != NULL);
  3461. hrOfEnterEvent = scriptContext->OnDispatchFunctionEnter(pwszFunctionName);
  3462. }
  3463. }
  3464. else
  3465. {
  3466. hrOfEnterEvent = scriptContext->OnFunctionEnter(scriptId, functionId);
  3467. }
  3468. scriptContext->GetThreadContext()->SetIsProfilingUserCode(isUserCode); // Update IsProfilingUserCode state
  3469. }
  3470. #endif // ENABLE_SCRIPT_PROFILING
  3471. Var aReturn = NULL;
  3472. JavascriptMethod origEntryPoint = function->GetFunctionInfo()->GetOriginalEntryPoint();
  3473. if (scriptContext->IsEvalRestriction())
  3474. {
  3475. if (origEntryPoint == Js::GlobalObject::EntryEval)
  3476. {
  3477. origEntryPoint = Js::GlobalObject::EntryEvalRestrictedMode;
  3478. }
  3479. else if (origEntryPoint == Js::JavascriptFunction::NewInstance)
  3480. {
  3481. origEntryPoint = Js::JavascriptFunction::NewInstanceRestrictedMode;
  3482. }
  3483. else if (origEntryPoint == Js::JavascriptGeneratorFunction::NewInstance)
  3484. {
  3485. origEntryPoint = Js::JavascriptGeneratorFunction::NewInstanceRestrictedMode;
  3486. }
  3487. else if (origEntryPoint == Js::JavascriptFunction::NewAsyncFunctionInstance)
  3488. {
  3489. origEntryPoint = Js::JavascriptFunction::NewAsyncFunctionInstanceRestrictedMode;
  3490. }
  3491. }
  3492. __TRY_FINALLY_BEGIN // SEH is not guaranteed, see the implementation
  3493. {
  3494. Assert(!function->IsScriptFunction() || function->GetFunctionProxy());
  3495. // No need to wrap script functions, also can't if the wrapper is already on the stack.
  3496. // Treat "library code" script functions, such as Intl, as built-ins:
  3497. // use the wrapper when calling them, and do not reset the wrapper when calling them.
  3498. bool isDebugWrapperEnabled = scriptContext->IsScriptContextInDebugMode() && IsExceptionWrapperForBuiltInsEnabled(scriptContext);
  3499. bool useDebugWrapper =
  3500. isDebugWrapperEnabled &&
  3501. function->IsLibraryCode() &&
  3502. !AutoRegisterIgnoreExceptionWrapper::IsRegistered(scriptContext->GetThreadContext());
  3503. OUTPUT_VERBOSE_TRACE(Js::DebuggerPhase, _u("DebugProfileProbeThunk: calling function: %s isWrapperRegistered=%d useDebugWrapper=%d\n"),
  3504. function->GetFunctionInfo()->HasBody() ? function->GetFunctionBody()->GetDisplayName() : _u("built-in/library"), AutoRegisterIgnoreExceptionWrapper::IsRegistered(scriptContext->GetThreadContext()), useDebugWrapper);
  3505. if (scriptContext->IsDebuggerRecording())
  3506. {
  3507. scriptContext->GetDebugContext()->GetProbeContainer()->StartRecordingCall();
  3508. }
  3509. if (useDebugWrapper)
  3510. {
  3511. // For native use wrapper and bail out on to ignore exception.
  3512. // Extract try-catch out of hot path in normal profile mode (presence of try-catch in a function is bad for perf).
  3513. aReturn = ProfileModeThunk_DebugModeWrapper(function, scriptContext, origEntryPoint, args);
  3514. }
  3515. else
  3516. {
  3517. if (isDebugWrapperEnabled && !function->IsLibraryCode())
  3518. {
  3519. // We want to ignore exception and continue into closest user/script function down on the stack.
  3520. // Thus, if needed, reset the wrapper for the time of this call,
  3521. // so that if there is library/helper call after script function, it will use try-catch.
  3522. // Can't use smart/destructor object here because of __try__finally.
  3523. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3524. bool isOrigWrapperPresent = threadContext->GetDebugManager()->GetDebuggingFlags()->IsBuiltInWrapperPresent();
  3525. if (isOrigWrapperPresent)
  3526. {
  3527. threadContext->GetDebugManager()->GetDebuggingFlags()->SetIsBuiltInWrapperPresent(false);
  3528. }
  3529. __TRY_FINALLY_BEGIN // SEH is not guaranteed, see the implementation
  3530. {
  3531. aReturn = JavascriptFunction::CallFunction<true>(function, origEntryPoint, args);
  3532. }
  3533. __FINALLY
  3534. {
  3535. threadContext->GetDebugManager()->GetDebuggingFlags()->SetIsBuiltInWrapperPresent(isOrigWrapperPresent);
  3536. }
  3537. __TRY_FINALLY_END
  3538. }
  3539. else
  3540. {
  3541. // Can we update return address to a thunk that sends Exit event and then jmp to entry instead of Calling it.
  3542. // Saves stack space and it might be something we would be doing anyway for handling profile.Start/stop
  3543. // which can come anywhere on the stack.
  3544. aReturn = JavascriptFunction::CallFunction<true>(function, origEntryPoint, args);
  3545. }
  3546. }
  3547. }
  3548. __FINALLY
  3549. {
  3550. #if defined(ENABLE_SCRIPT_PROFILING)
  3551. if (fProfile)
  3552. {
  3553. if (hrOfEnterEvent != ACTIVPROF_E_PROFILER_ABSENT)
  3554. {
  3555. if (functionId == -1)
  3556. {
  3557. // Check whether we have sent the Enter event or not.
  3558. if (functionEnterEventSent)
  3559. {
  3560. scriptContext->OnDispatchFunctionExit(pwszFunctionName);
  3561. if (pwszExtractedFunctionName != NULL)
  3562. {
  3563. HeapDeleteArray(functionNameLen, pwszExtractedFunctionName);
  3564. }
  3565. }
  3566. }
  3567. else
  3568. {
  3569. scriptContext->OnFunctionExit(scriptId, functionId);
  3570. }
  3571. }
  3572. scriptContext->GetThreadContext()->SetIsProfilingUserCode(isProfilingUserCode); // Restore IsProfilingUserCode state
  3573. }
  3574. #endif
  3575. if (scriptContext->IsDebuggerRecording())
  3576. {
  3577. scriptContext->GetDebugContext()->GetProbeContainer()->EndRecordingCall(aReturn, function);
  3578. }
  3579. }
  3580. __TRY_FINALLY_END
  3581. return aReturn;
  3582. #else
  3583. return nullptr;
  3584. #endif // defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  3585. }
  3586. #if defined(ENABLE_SCRIPT_DEBUGGING) || defined(ENABLE_SCRIPT_PROFILING)
  3587. // Part of ProfileModeThunk which is called in debug mode (debug or debug & profile).
  3588. Var ScriptContext::ProfileModeThunk_DebugModeWrapper(JavascriptFunction* function, ScriptContext* scriptContext, JavascriptMethod entryPoint, Arguments& args)
  3589. {
  3590. AutoRegisterIgnoreExceptionWrapper autoWrapper(scriptContext->GetThreadContext());
  3591. Var aReturn = HelperOrLibraryMethodWrapper<true>(scriptContext, [=] {
  3592. return JavascriptFunction::CallFunction<true>(function, entryPoint, args);
  3593. });
  3594. return aReturn;
  3595. }
  3596. #endif
  3597. #ifdef ENABLE_SCRIPT_PROFILING
  3598. HRESULT ScriptContext::OnScriptCompiled(PROFILER_TOKEN scriptId, PROFILER_SCRIPT_TYPE type, IUnknown *pIDebugDocumentContext)
  3599. {
  3600. // TODO : can we do a delay send of these events or can we send an event before doing all this stuff that could calculate overhead?
  3601. Assert(m_pProfileCallback != NULL);
  3602. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnScriptCompiled scriptId : %d, ScriptType : %d\n"), scriptId, type);
  3603. HRESULT hr = S_OK;
  3604. if ((type == PROFILER_SCRIPT_TYPE_NATIVE && m_fTraceNativeFunctionCall) ||
  3605. (type != PROFILER_SCRIPT_TYPE_NATIVE && m_fTraceFunctionCall))
  3606. {
  3607. m_inProfileCallback = TRUE;
  3608. hr = m_pProfileCallback->ScriptCompiled(scriptId, type, pIDebugDocumentContext);
  3609. m_inProfileCallback = FALSE;
  3610. }
  3611. return hr;
  3612. }
  3613. HRESULT ScriptContext::OnFunctionCompiled(
  3614. PROFILER_TOKEN functionId,
  3615. PROFILER_TOKEN scriptId,
  3616. const WCHAR *pwszFunctionName,
  3617. const WCHAR *pwszFunctionNameHint,
  3618. IUnknown *pIDebugDocumentContext)
  3619. {
  3620. Assert(m_pProfileCallback != NULL);
  3621. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3622. if (scriptId != BuiltInFunctionsScriptId || Js::Configuration::Global.flags.Verbose)
  3623. {
  3624. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnFunctionCompiled scriptId : %d, functionId : %d, FunctionName : %s, FunctionNameHint : %s\n"), scriptId, functionId, pwszFunctionName, pwszFunctionNameHint);
  3625. }
  3626. #endif
  3627. HRESULT hr = S_OK;
  3628. if ((scriptId == BuiltInFunctionsScriptId && m_fTraceNativeFunctionCall) ||
  3629. (scriptId != BuiltInFunctionsScriptId && m_fTraceFunctionCall))
  3630. {
  3631. m_inProfileCallback = TRUE;
  3632. hr = m_pProfileCallback->FunctionCompiled(functionId, scriptId, pwszFunctionName, pwszFunctionNameHint, pIDebugDocumentContext);
  3633. m_inProfileCallback = FALSE;
  3634. }
  3635. return hr;
  3636. }
  3637. HRESULT ScriptContext::OnFunctionEnter(PROFILER_TOKEN scriptId, PROFILER_TOKEN functionId)
  3638. {
  3639. if (m_pProfileCallback == NULL)
  3640. {
  3641. return ACTIVPROF_E_PROFILER_ABSENT;
  3642. }
  3643. OUTPUT_VERBOSE_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnFunctionEnter scriptId : %d, functionId : %d\n"), scriptId, functionId);
  3644. HRESULT hr = S_OK;
  3645. if ((scriptId == BuiltInFunctionsScriptId && m_fTraceNativeFunctionCall) ||
  3646. (scriptId != BuiltInFunctionsScriptId && m_fTraceFunctionCall))
  3647. {
  3648. m_inProfileCallback = TRUE;
  3649. hr = m_pProfileCallback->OnFunctionEnter(scriptId, functionId);
  3650. m_inProfileCallback = FALSE;
  3651. }
  3652. return hr;
  3653. }
  3654. HRESULT ScriptContext::OnFunctionExit(PROFILER_TOKEN scriptId, PROFILER_TOKEN functionId)
  3655. {
  3656. if (m_pProfileCallback == NULL)
  3657. {
  3658. return ACTIVPROF_E_PROFILER_ABSENT;
  3659. }
  3660. OUTPUT_VERBOSE_TRACE(Js::ScriptProfilerPhase, _u("ScriptContext::OnFunctionExit scriptId : %d, functionId : %d\n"), scriptId, functionId);
  3661. HRESULT hr = S_OK;
  3662. if ((scriptId == BuiltInFunctionsScriptId && m_fTraceNativeFunctionCall) ||
  3663. (scriptId != BuiltInFunctionsScriptId && m_fTraceFunctionCall))
  3664. {
  3665. m_inProfileCallback = TRUE;
  3666. hr = m_pProfileCallback->OnFunctionExit(scriptId, functionId);
  3667. m_inProfileCallback = FALSE;
  3668. }
  3669. return hr;
  3670. }
  3671. HRESULT ScriptContext::FunctionExitSenderThunk(PROFILER_TOKEN functionId, PROFILER_TOKEN scriptId, ScriptContext *pScriptContext)
  3672. {
  3673. return pScriptContext->OnFunctionExit(scriptId, functionId);
  3674. }
  3675. HRESULT ScriptContext::FunctionExitByNameSenderThunk(const char16 *pwszFunctionName, ScriptContext *pScriptContext)
  3676. {
  3677. return pScriptContext->OnDispatchFunctionExit(pwszFunctionName);
  3678. }
  3679. #endif // ENABLE_SCRIPT_PROFILING
  3680. Js::PropertyId ScriptContext::GetFunctionNumber(JavascriptMethod entryPoint)
  3681. {
  3682. return (m_pBuiltinFunctionIdMap == NULL) ? -1 : m_pBuiltinFunctionIdMap->Lookup(entryPoint, -1);
  3683. }
  3684. #if defined(ENABLE_SCRIPT_PROFILING)
  3685. HRESULT ScriptContext::RegisterLibraryFunction(const char16 *pwszObjectName, const char16 *pwszFunctionName, Js::PropertyId functionPropertyId, JavascriptMethod entryPoint)
  3686. {
  3687. #if DEBUG
  3688. const char16 *pwszObjectNameFromProperty = const_cast<char16 *>(GetPropertyName(functionPropertyId)->GetBuffer());
  3689. if (GetPropertyName(functionPropertyId)->IsSymbol())
  3690. {
  3691. // The spec names functions whose property is a well known symbol as the description from the symbol
  3692. // wrapped in square brackets, so verify by skipping past first bracket
  3693. Assert(!wcsncmp(pwszFunctionName + 1, pwszObjectNameFromProperty, wcslen(pwszObjectNameFromProperty)));
  3694. Assert(wcslen(pwszFunctionName) == wcslen(pwszObjectNameFromProperty) + 2);
  3695. }
  3696. else
  3697. {
  3698. Assert(!wcscmp(pwszFunctionName, pwszObjectNameFromProperty));
  3699. }
  3700. Assert(m_pBuiltinFunctionIdMap != NULL);
  3701. #endif
  3702. // Create the propertyId as object.functionName if it is not global function
  3703. // the global functions would be recognized by just functionName
  3704. // e.g. with functionName, toString, depending on objectName, it could be Object.toString, or Date.toString
  3705. char16 szTempName[70];
  3706. if (pwszObjectName != NULL)
  3707. {
  3708. // Create name as "object.function"
  3709. swprintf_s(szTempName, 70, _u("%s.%s"), pwszObjectName, pwszFunctionName);
  3710. functionPropertyId = GetOrAddPropertyIdTracked(szTempName, (uint)wcslen(szTempName));
  3711. }
  3712. Js::PropertyId cachedFunctionId;
  3713. bool keyFound = m_pBuiltinFunctionIdMap->TryGetValue(entryPoint, &cachedFunctionId);
  3714. if (keyFound)
  3715. {
  3716. // Entry point is already in the map
  3717. if (cachedFunctionId != functionPropertyId)
  3718. {
  3719. // This is the scenario where we could be using same function for multiple builtin functions
  3720. // e.g. Error.toString, WinRTError.toString etc.
  3721. // We would ignore these extra entrypoints because while profiling, identifying which object's toString is too costly for its worth
  3722. return S_OK;
  3723. }
  3724. // else is the scenario where map was created by earlier profiling session and we are yet to send function compiled for this session
  3725. }
  3726. else
  3727. {
  3728. #if DBG
  3729. m_pBuiltinFunctionIdMap->MapUntil([&](JavascriptMethod, Js::PropertyId propertyId) -> bool
  3730. {
  3731. if (functionPropertyId == propertyId)
  3732. {
  3733. Assert(false);
  3734. return true;
  3735. }
  3736. return false;
  3737. });
  3738. #endif
  3739. // throws, this must always be in a function that handles OOM
  3740. m_pBuiltinFunctionIdMap->Add(entryPoint, functionPropertyId);
  3741. }
  3742. // Use name with "Object." if its not a global function
  3743. if (pwszObjectName != NULL)
  3744. {
  3745. return OnFunctionCompiled(functionPropertyId, BuiltInFunctionsScriptId, szTempName, NULL, NULL);
  3746. }
  3747. else
  3748. {
  3749. return OnFunctionCompiled(functionPropertyId, BuiltInFunctionsScriptId, pwszFunctionName, NULL, NULL);
  3750. }
  3751. }
  3752. #endif // ENABLE_SCRIPT_PROFILING
  3753. void ScriptContext::BindReference(void * addr)
  3754. {
  3755. Assert(!this->isClosed);
  3756. Assert(this->guestArena);
  3757. Assert(recycler->IsValidObject(addr));
  3758. #if DBG
  3759. Assert(!bindRef.ContainsKey(addr)); // Make sure we don't bind the same pointer twice
  3760. bindRef.AddNew(addr);
  3761. #endif
  3762. javascriptLibrary->BindReference(addr);
  3763. #ifdef RECYCLER_PERF_COUNTERS
  3764. this->bindReferenceCount++;
  3765. RECYCLER_PERF_COUNTER_INC(BindReference);
  3766. #endif
  3767. }
  3768. #ifdef PROFILE_STRINGS
  3769. StringProfiler* ScriptContext::GetStringProfiler()
  3770. {
  3771. return stringProfiler;
  3772. }
  3773. #endif
  3774. void ScriptContext::FreeFunctionEntryPoint(Js::JavascriptMethod codeAddress, Js::JavascriptMethod thunkAddress)
  3775. {
  3776. #if ENABLE_NATIVE_CODEGEN
  3777. FreeNativeCodeGenAllocation(this, codeAddress, thunkAddress);
  3778. #endif
  3779. }
  3780. void ScriptContext::RegisterProtoInlineCache(InlineCache *pCache, PropertyId propId)
  3781. {
  3782. hasProtoOrStoreFieldInlineCache = true;
  3783. #if DBG
  3784. this->inlineCacheAllocator.Unlock();
  3785. #endif
  3786. threadContext->RegisterProtoInlineCache(pCache, propId);
  3787. }
  3788. void ScriptContext::InvalidateProtoCaches(const PropertyId propertyId)
  3789. {
  3790. threadContext->InvalidateProtoInlineCaches(propertyId);
  3791. // Because setter inline caches get registered in the store field chain, we must invalidate that
  3792. // chain whenever we invalidate the proto chain.
  3793. threadContext->InvalidateStoreFieldInlineCaches(propertyId);
  3794. #if ENABLE_NATIVE_CODEGEN
  3795. threadContext->InvalidatePropertyGuards(propertyId);
  3796. #endif
  3797. threadContext->InvalidateProtoTypePropertyCaches(propertyId);
  3798. }
  3799. void ScriptContext::InvalidateAllProtoCaches()
  3800. {
  3801. threadContext->InvalidateAllProtoInlineCaches();
  3802. // Because setter inline caches get registered in the store field chain, we must invalidate that
  3803. // chain whenever we invalidate the proto chain.
  3804. threadContext->InvalidateAllStoreFieldInlineCaches();
  3805. #if ENABLE_NATIVE_CODEGEN
  3806. threadContext->InvalidateAllPropertyGuards();
  3807. #endif
  3808. threadContext->InvalidateAllProtoTypePropertyCaches();
  3809. }
  3810. void ScriptContext::RegisterStoreFieldInlineCache(InlineCache *pCache, PropertyId propId)
  3811. {
  3812. hasProtoOrStoreFieldInlineCache = true;
  3813. #if DBG
  3814. this->inlineCacheAllocator.Unlock();
  3815. #endif
  3816. threadContext->RegisterStoreFieldInlineCache(pCache, propId);
  3817. }
  3818. void ScriptContext::InvalidateStoreFieldCaches(const PropertyId propertyId)
  3819. {
  3820. threadContext->InvalidateStoreFieldInlineCaches(propertyId);
  3821. #if ENABLE_NATIVE_CODEGEN
  3822. threadContext->InvalidatePropertyGuards(propertyId);
  3823. #endif
  3824. }
  3825. void ScriptContext::InvalidateAllStoreFieldCaches()
  3826. {
  3827. threadContext->InvalidateAllStoreFieldInlineCaches();
  3828. }
  3829. void ScriptContext::RegisterIsInstInlineCache(Js::IsInstInlineCache * cache, Js::Var function)
  3830. {
  3831. Assert(JavascriptFunction::FromVar(function)->GetScriptContext() == this);
  3832. hasIsInstInlineCache = true;
  3833. #if DBG
  3834. this->isInstInlineCacheAllocator.Unlock();
  3835. #endif
  3836. threadContext->RegisterIsInstInlineCache(cache, function);
  3837. }
  3838. #if DBG
  3839. bool ScriptContext::IsIsInstInlineCacheRegistered(Js::IsInstInlineCache * cache, Js::Var function)
  3840. {
  3841. return threadContext->IsIsInstInlineCacheRegistered(cache, function);
  3842. }
  3843. #endif
  3844. void ScriptContext::CleanSourceListInternal(bool calledDuringMark)
  3845. {
  3846. bool fCleanupDocRequired = false;
  3847. for (int i = 0; i < sourceList->Count(); i++)
  3848. {
  3849. if (this->sourceList->IsItemValid(i))
  3850. {
  3851. RecyclerWeakReference<Utf8SourceInfo>* sourceInfoWeakRef = this->sourceList->Item(i);
  3852. Utf8SourceInfo* strongRef = nullptr;
  3853. if (calledDuringMark)
  3854. {
  3855. strongRef = sourceInfoWeakRef->FastGet();
  3856. }
  3857. else
  3858. {
  3859. strongRef = sourceInfoWeakRef->Get();
  3860. }
  3861. if (strongRef == nullptr)
  3862. {
  3863. this->sourceList->RemoveAt(i);
  3864. fCleanupDocRequired = true;
  3865. }
  3866. }
  3867. }
  3868. #ifdef ENABLE_SCRIPT_PROFILING
  3869. // If the sourceList got changed, in we need to refresh the nondebug document list in the profiler mode.
  3870. if (fCleanupDocRequired && m_pProfileCallback != NULL)
  3871. {
  3872. Assert(CleanupDocumentContext != NULL);
  3873. CleanupDocumentContext(this);
  3874. }
  3875. #endif // ENABLE_SCRIPT_PROFILING
  3876. }
  3877. void ScriptContext::ClearScriptContextCaches()
  3878. {
  3879. // Prevent reentrancy for the following work, which is not required to be done on every call to this function including
  3880. // reentrant calls
  3881. if (this->isPerformingNonreentrantWork || !this->hasUsedInlineCache)
  3882. {
  3883. return;
  3884. }
  3885. class AutoCleanup
  3886. {
  3887. private:
  3888. ScriptContext *const scriptContext;
  3889. public:
  3890. AutoCleanup(ScriptContext *const scriptContext) : scriptContext(scriptContext)
  3891. {
  3892. scriptContext->isPerformingNonreentrantWork = true;
  3893. }
  3894. ~AutoCleanup()
  3895. {
  3896. scriptContext->isPerformingNonreentrantWork = false;
  3897. }
  3898. } autoCleanup(this);
  3899. if (this->isScriptContextActuallyClosed)
  3900. {
  3901. return;
  3902. }
  3903. Assert(this->guestArena);
  3904. if (EnableEvalMapCleanup())
  3905. {
  3906. // The eval map is not re-entrant, so make sure it's not in the middle of adding an entry
  3907. // Also, don't clean the eval map if the debugger is attached
  3908. if (!this->IsScriptContextInDebugMode())
  3909. {
  3910. if (this->Cache()->evalCacheDictionary != nullptr)
  3911. {
  3912. this->CleanDynamicFunctionCache<Js::EvalCacheTopLevelDictionary>(this->Cache()->evalCacheDictionary->GetDictionary());
  3913. }
  3914. if (this->Cache()->indirectEvalCacheDictionary != nullptr)
  3915. {
  3916. this->CleanDynamicFunctionCache<Js::EvalCacheTopLevelDictionary>(this->Cache()->indirectEvalCacheDictionary->GetDictionary());
  3917. }
  3918. if (this->Cache()->newFunctionCache != nullptr)
  3919. {
  3920. this->CleanDynamicFunctionCache<Js::NewFunctionCache>(this->Cache()->newFunctionCache);
  3921. }
  3922. if (this->hostScriptContext != nullptr)
  3923. {
  3924. this->hostScriptContext->CleanDynamicCodeCache();
  3925. }
  3926. }
  3927. }
  3928. if (REGEX_CONFIG_FLAG(DynamicRegexMruListSize) > 0)
  3929. {
  3930. GetDynamicRegexMap()->RemoveRecentlyUnusedItems();
  3931. }
  3932. CleanSourceListInternal(true);
  3933. }
  3934. void ScriptContext::ClearInlineCaches()
  3935. {
  3936. if (this->hasUsedInlineCache)
  3937. {
  3938. this->inlineCacheAllocator.ZeroAll();
  3939. this->hasUsedInlineCache = false;
  3940. this->hasProtoOrStoreFieldInlineCache = false;
  3941. }
  3942. DebugOnly(this->inlineCacheAllocator.CheckIsAllZero(true));
  3943. }
  3944. void ScriptContext::ClearIsInstInlineCaches()
  3945. {
  3946. if (this->hasIsInstInlineCache)
  3947. {
  3948. isInstInlineCacheAllocator.ZeroAll();
  3949. this->hasIsInstInlineCache = false;
  3950. }
  3951. DebugOnly(isInstInlineCacheAllocator.CheckIsAllZero(true));
  3952. }
  3953. void ScriptContext::ClearForInCaches()
  3954. {
  3955. forInCacheAllocator.ZeroAll();
  3956. DebugOnly(forInCacheAllocator.CheckIsAllZero(false));
  3957. }
  3958. #ifdef PERSISTENT_INLINE_CACHES
  3959. void ScriptContext::ClearInlineCachesWithDeadWeakRefs()
  3960. {
  3961. if (this->hasUsedInlineCache)
  3962. {
  3963. this->inlineCacheAllocator.ClearCachesWithDeadWeakRefs(this->recycler);
  3964. Assert(this->inlineCacheAllocator.HasNoDeadWeakRefs(this->recycler));
  3965. }
  3966. }
  3967. #endif
  3968. #if ENABLE_NATIVE_CODEGEN
  3969. void ScriptContext::RegisterConstructorCache(Js::PropertyId propertyId, Js::ConstructorCache* cache)
  3970. {
  3971. this->threadContext->RegisterConstructorCache(propertyId, cache);
  3972. }
  3973. JITPageAddrToFuncRangeCache *
  3974. ScriptContext::GetJitFuncRangeCache()
  3975. {
  3976. return jitFuncRangeCache;
  3977. }
  3978. #endif
  3979. void ScriptContext::RegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext()
  3980. {
  3981. Assert(!IsClosed());
  3982. if (registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr)
  3983. {
  3984. DoRegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext();
  3985. }
  3986. }
  3987. void ScriptContext::DoRegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext()
  3988. {
  3989. Assert(!IsClosed());
  3990. Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext == nullptr);
  3991. // this call may throw OOM
  3992. registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext = threadContext->RegisterPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext(this);
  3993. }
  3994. void ScriptContext::ClearPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesCaches()
  3995. {
  3996. Assert(registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext != nullptr);
  3997. if (!isFinalized)
  3998. {
  3999. javascriptLibrary->NoPrototypeChainsAreEnsuredToHaveOnlyWritableDataProperties();
  4000. }
  4001. // Caller will unregister the script context from the thread context
  4002. registeredPrototypeChainEnsuredToHaveOnlyWritableDataPropertiesScriptContext = nullptr;
  4003. }
  4004. JavascriptString * ScriptContext::GetLastNumberToStringRadix10(double value)
  4005. {
  4006. if (value == lastNumberToStringRadix10)
  4007. {
  4008. return Cache()->lastNumberToStringRadix10String;
  4009. }
  4010. return nullptr;
  4011. }
  4012. void
  4013. ScriptContext::SetLastNumberToStringRadix10(double value, JavascriptString * str)
  4014. {
  4015. lastNumberToStringRadix10 = value;
  4016. Cache()->lastNumberToStringRadix10String = str;
  4017. }
  4018. bool ScriptContext::GetLastUtcTimeFromStr(JavascriptString * str, double& dbl)
  4019. {
  4020. Assert(str != nullptr);
  4021. if (str != Cache()->lastUtcTimeFromStrString)
  4022. {
  4023. if (Cache()->lastUtcTimeFromStrString == nullptr
  4024. || !JavascriptString::Equals(str, Cache()->lastUtcTimeFromStrString))
  4025. {
  4026. return false;
  4027. }
  4028. }
  4029. dbl = lastUtcTimeFromStr;
  4030. return true;
  4031. }
  4032. void
  4033. ScriptContext::SetLastUtcTimeFromStr(JavascriptString * str, double value)
  4034. {
  4035. lastUtcTimeFromStr = value;
  4036. Cache()->lastUtcTimeFromStrString = str;
  4037. }
  4038. #if ENABLE_NATIVE_CODEGEN
  4039. BOOL ScriptContext::IsNativeAddress(void * codeAddr)
  4040. {
  4041. return this->GetThreadContext()->IsNativeAddress(codeAddr, this);
  4042. }
  4043. #endif
  4044. #ifdef ENABLE_SCRIPT_PROFILING
  4045. bool ScriptContext::SetDispatchProfile(bool fSet, JavascriptMethod dispatchInvoke)
  4046. {
  4047. if (!fSet)
  4048. {
  4049. this->javascriptLibrary->SetDispatchProfile(false, dispatchInvoke);
  4050. return true;
  4051. }
  4052. else if (m_fTraceDomCall)
  4053. {
  4054. this->javascriptLibrary->SetDispatchProfile(true, dispatchInvoke);
  4055. return true;
  4056. }
  4057. return false;
  4058. }
  4059. HRESULT ScriptContext::OnDispatchFunctionEnter(const WCHAR *pwszFunctionName)
  4060. {
  4061. if (m_pProfileCallback2 == NULL)
  4062. {
  4063. return ACTIVPROF_E_PROFILER_ABSENT;
  4064. }
  4065. HRESULT hr = S_OK;
  4066. if (m_fTraceDomCall)
  4067. {
  4068. m_inProfileCallback = TRUE;
  4069. hr = m_pProfileCallback2->OnFunctionEnterByName(pwszFunctionName, PROFILER_SCRIPT_TYPE_DOM);
  4070. m_inProfileCallback = FALSE;
  4071. }
  4072. return hr;
  4073. }
  4074. HRESULT ScriptContext::OnDispatchFunctionExit(const WCHAR *pwszFunctionName)
  4075. {
  4076. if (m_pProfileCallback2 == NULL)
  4077. {
  4078. return ACTIVPROF_E_PROFILER_ABSENT;
  4079. }
  4080. HRESULT hr = S_OK;
  4081. if (m_fTraceDomCall)
  4082. {
  4083. m_inProfileCallback = TRUE;
  4084. hr = m_pProfileCallback2->OnFunctionExitByName(pwszFunctionName, PROFILER_SCRIPT_TYPE_DOM);
  4085. m_inProfileCallback = FALSE;
  4086. }
  4087. return hr;
  4088. }
  4089. #endif // ENABLE_SCRIPT_PROFILING
  4090. void ScriptContext::SetBuiltInLibraryFunction(JavascriptMethod entryPoint, JavascriptFunction* function)
  4091. {
  4092. if (!isClosed)
  4093. {
  4094. if (builtInLibraryFunctions == NULL)
  4095. {
  4096. Assert(this->recycler);
  4097. builtInLibraryFunctions = RecyclerNew(this->recycler, BuiltInLibraryFunctionMap, this->recycler, 131);
  4098. Cache()->builtInLibraryFunctions = builtInLibraryFunctions;
  4099. }
  4100. builtInLibraryFunctions->Item(entryPoint, function);
  4101. }
  4102. }
  4103. #if ENABLE_NATIVE_CODEGEN
  4104. void ScriptContext::InitializeRemoteScriptContext()
  4105. {
  4106. Assert(JITManager::GetJITManager()->IsOOPJITEnabled());
  4107. if (!JITManager::GetJITManager()->IsConnected())
  4108. {
  4109. return;
  4110. }
  4111. ScriptContextDataIDL contextData;
  4112. contextData.nullAddr = (intptr_t)GetLibrary()->GetNull();
  4113. contextData.undefinedAddr = (intptr_t)GetLibrary()->GetUndefined();
  4114. contextData.trueAddr = (intptr_t)GetLibrary()->GetTrue();
  4115. contextData.falseAddr = (intptr_t)GetLibrary()->GetFalse();
  4116. contextData.undeclBlockVarAddr = (intptr_t)GetLibrary()->GetUndeclBlockVar();
  4117. contextData.scriptContextAddr = (intptr_t)this;
  4118. contextData.emptyStringAddr = (intptr_t)GetLibrary()->GetEmptyString();
  4119. contextData.negativeZeroAddr = (intptr_t)GetLibrary()->GetNegativeZero();
  4120. contextData.numberTypeStaticAddr = (intptr_t)GetLibrary()->GetNumberTypeStatic();
  4121. contextData.stringTypeStaticAddr = (intptr_t)GetLibrary()->GetStringTypeStatic();
  4122. contextData.objectTypeAddr = (intptr_t)GetLibrary()->GetObjectType();
  4123. contextData.objectHeaderInlinedTypeAddr = (intptr_t)GetLibrary()->GetObjectHeaderInlinedType();
  4124. contextData.regexTypeAddr = (intptr_t)GetLibrary()->GetRegexType();
  4125. contextData.arrayConstructorAddr = (intptr_t)GetLibrary()->GetArrayConstructor();
  4126. contextData.arrayTypeAddr = (intptr_t)GetLibrary()->GetArrayType();
  4127. contextData.nativeIntArrayTypeAddr = (intptr_t)GetLibrary()->GetNativeIntArrayType();
  4128. contextData.nativeFloatArrayTypeAddr = (intptr_t)GetLibrary()->GetNativeFloatArrayType();
  4129. contextData.charStringCacheAddr = (intptr_t)&GetLibrary()->GetCharStringCache();
  4130. contextData.libraryAddr = (intptr_t)GetLibrary();
  4131. contextData.globalObjectAddr = (intptr_t)GetLibrary()->GetGlobalObject();
  4132. contextData.builtinFunctionsBaseAddr = (intptr_t)GetLibrary()->GetBuiltinFunctions();
  4133. contextData.sideEffectsAddr = optimizationOverrides.GetAddressOfSideEffects();
  4134. contextData.arraySetElementFastPathVtableAddr = (intptr_t)optimizationOverrides.GetAddressOfArraySetElementFastPathVtable();
  4135. contextData.intArraySetElementFastPathVtableAddr = (intptr_t)optimizationOverrides.GetAddressOfIntArraySetElementFastPathVtable();
  4136. contextData.floatArraySetElementFastPathVtableAddr = (intptr_t)optimizationOverrides.GetAddressOfFloatArraySetElementFastPathVtable();
  4137. contextData.recyclerAddr = (intptr_t)GetRecycler();
  4138. contextData.recyclerAllowNativeCodeBumpAllocation = GetRecycler()->AllowNativeCodeBumpAllocation();
  4139. contextData.numberAllocatorAddr = (intptr_t)GetNumberAllocator();
  4140. #ifdef RECYCLER_MEMORY_VERIFY
  4141. contextData.isRecyclerVerifyEnabled = (boolean)recycler->VerifyEnabled();
  4142. contextData.recyclerVerifyPad = recycler->GetVerifyPad();
  4143. #else
  4144. // TODO: OOP JIT, figure out how to have this only in debug build
  4145. contextData.isRecyclerVerifyEnabled = FALSE;
  4146. contextData.recyclerVerifyPad = 0;
  4147. #endif
  4148. #ifdef ENABLE_SCRIPT_DEBUGGING
  4149. contextData.debuggingFlagsAddr = GetDebuggingFlagsAddr();
  4150. contextData.debugStepTypeAddr = GetDebugStepTypeAddr();
  4151. contextData.debugFrameAddressAddr = GetDebugFrameAddressAddr();
  4152. contextData.debugScriptIdWhenSetAddr = GetDebugScriptIdWhenSetAddr();
  4153. #endif
  4154. contextData.numberAllocatorAddr = (intptr_t)GetNumberAllocator();
  4155. #ifdef ENABLE_SIMDJS
  4156. contextData.isSIMDEnabled = GetConfig()->IsSimdjsEnabled();
  4157. #endif
  4158. CompileAssert(VTableValue::Count == VTABLE_COUNT); // need to update idl when this changes
  4159. auto vtblAddresses = GetLibrary()->GetVTableAddresses();
  4160. for (unsigned int i = 0; i < VTableValue::Count; i++)
  4161. {
  4162. contextData.vtableAddresses[i] = vtblAddresses[i];
  4163. }
  4164. bool allowPrereserveAlloc = true;
  4165. #if !_M_X64_OR_ARM64
  4166. if (this->webWorkerId != Js::Constants::NonWebWorkerContextId)
  4167. {
  4168. allowPrereserveAlloc = false;
  4169. }
  4170. #endif
  4171. #ifndef _CONTROL_FLOW_GUARD
  4172. allowPrereserveAlloc = false;
  4173. #endif
  4174. // The EnsureJITThreadContext() call could fail if the JIT Server process has died. In such cases, we should not try to do anything further in the client process.
  4175. if (this->GetThreadContext()->EnsureJITThreadContext(allowPrereserveAlloc))
  4176. {
  4177. HRESULT hr = JITManager::GetJITManager()->InitializeScriptContext(&contextData, this->GetThreadContext()->GetRemoteThreadContextAddr(), &m_remoteScriptContextAddr);
  4178. JITManager::HandleServerCallResult(hr, RemoteCallType::StateUpdate);
  4179. }
  4180. }
  4181. #endif
  4182. intptr_t ScriptContext::GetNullAddr() const
  4183. {
  4184. return (intptr_t)GetLibrary()->GetNull();
  4185. }
  4186. intptr_t ScriptContext::GetUndefinedAddr() const
  4187. {
  4188. return (intptr_t)GetLibrary()->GetUndefined();
  4189. }
  4190. intptr_t ScriptContext::GetTrueAddr() const
  4191. {
  4192. return (intptr_t)GetLibrary()->GetTrue();
  4193. }
  4194. intptr_t ScriptContext::GetFalseAddr() const
  4195. {
  4196. return (intptr_t)GetLibrary()->GetFalse();
  4197. }
  4198. intptr_t ScriptContext::GetUndeclBlockVarAddr() const
  4199. {
  4200. return (intptr_t)GetLibrary()->GetUndeclBlockVar();
  4201. }
  4202. intptr_t ScriptContext::GetEmptyStringAddr() const
  4203. {
  4204. return (intptr_t)GetLibrary()->GetEmptyString();
  4205. }
  4206. intptr_t ScriptContext::GetNegativeZeroAddr() const
  4207. {
  4208. return (intptr_t)GetLibrary()->GetNegativeZero();
  4209. }
  4210. intptr_t ScriptContext::GetNumberTypeStaticAddr() const
  4211. {
  4212. return (intptr_t)GetLibrary()->GetNumberTypeStatic();
  4213. }
  4214. intptr_t ScriptContext::GetStringTypeStaticAddr() const
  4215. {
  4216. return (intptr_t)GetLibrary()->GetStringTypeStatic();
  4217. }
  4218. intptr_t ScriptContext::GetObjectTypeAddr() const
  4219. {
  4220. return (intptr_t)GetLibrary()->GetObjectType();
  4221. }
  4222. intptr_t ScriptContext::GetObjectHeaderInlinedTypeAddr() const
  4223. {
  4224. return (intptr_t)GetLibrary()->GetObjectHeaderInlinedType();
  4225. }
  4226. intptr_t ScriptContext::GetRegexTypeAddr() const
  4227. {
  4228. return (intptr_t)GetLibrary()->GetRegexType();
  4229. }
  4230. intptr_t ScriptContext::GetArrayTypeAddr() const
  4231. {
  4232. return (intptr_t)GetLibrary()->GetArrayType();
  4233. }
  4234. intptr_t ScriptContext::GetNativeIntArrayTypeAddr() const
  4235. {
  4236. return (intptr_t)GetLibrary()->GetNativeIntArrayType();
  4237. }
  4238. intptr_t ScriptContext::GetNativeFloatArrayTypeAddr() const
  4239. {
  4240. return (intptr_t)GetLibrary()->GetNativeFloatArrayType();
  4241. }
  4242. intptr_t ScriptContext::GetArrayConstructorAddr() const
  4243. {
  4244. return (intptr_t)GetLibrary()->GetArrayConstructor();
  4245. }
  4246. intptr_t ScriptContext::GetCharStringCacheAddr() const
  4247. {
  4248. return (intptr_t)&GetLibrary()->GetCharStringCache();
  4249. }
  4250. intptr_t ScriptContext::GetSideEffectsAddr() const
  4251. {
  4252. return optimizationOverrides.GetAddressOfSideEffects();
  4253. }
  4254. intptr_t ScriptContext::GetArraySetElementFastPathVtableAddr() const
  4255. {
  4256. return optimizationOverrides.GetArraySetElementFastPathVtableAddr();
  4257. }
  4258. intptr_t ScriptContext::GetIntArraySetElementFastPathVtableAddr() const
  4259. {
  4260. return optimizationOverrides.GetIntArraySetElementFastPathVtableAddr();
  4261. }
  4262. intptr_t ScriptContext::GetFloatArraySetElementFastPathVtableAddr() const
  4263. {
  4264. return optimizationOverrides.GetFloatArraySetElementFastPathVtableAddr();
  4265. }
  4266. intptr_t ScriptContext::GetBuiltinFunctionsBaseAddr() const
  4267. {
  4268. return (intptr_t)GetLibrary()->GetBuiltinFunctions();
  4269. }
  4270. intptr_t ScriptContext::GetLibraryAddr() const
  4271. {
  4272. return (intptr_t)GetLibrary();
  4273. }
  4274. intptr_t ScriptContext::GetGlobalObjectAddr() const
  4275. {
  4276. return (intptr_t)GetLibrary()->GetGlobalObject();
  4277. }
  4278. intptr_t ScriptContext::GetGlobalObjectThisAddr() const
  4279. {
  4280. return (intptr_t)GetLibrary()->GetGlobalObject()->ToThis();
  4281. }
  4282. intptr_t ScriptContext::GetNumberAllocatorAddr() const
  4283. {
  4284. return (intptr_t)&numberAllocator;
  4285. }
  4286. intptr_t ScriptContext::GetRecyclerAddr() const
  4287. {
  4288. return (intptr_t)GetRecycler();
  4289. }
  4290. #ifdef ENABLE_SCRIPT_DEBUGGING
  4291. intptr_t ScriptContext::GetDebuggingFlagsAddr() const
  4292. {
  4293. return this->threadContext->GetDebugManager()->GetDebuggingFlagsAddr();
  4294. }
  4295. intptr_t ScriptContext::GetDebugStepTypeAddr() const
  4296. {
  4297. return (intptr_t)this->threadContext->GetDebugManager()->stepController.GetAddressOfStepType();
  4298. }
  4299. intptr_t ScriptContext::GetDebugFrameAddressAddr() const
  4300. {
  4301. return (intptr_t)this->threadContext->GetDebugManager()->stepController.GetAddressOfFrameAddress();
  4302. }
  4303. intptr_t ScriptContext::GetDebugScriptIdWhenSetAddr() const
  4304. {
  4305. return (intptr_t)this->threadContext->GetDebugManager()->stepController.GetAddressOfScriptIdWhenSet();
  4306. }
  4307. #endif
  4308. bool ScriptContext::GetRecyclerAllowNativeCodeBumpAllocation() const
  4309. {
  4310. return GetRecycler()->AllowNativeCodeBumpAllocation();
  4311. }
  4312. #ifdef ENABLE_SIMDJS
  4313. bool ScriptContext::IsSIMDEnabled() const
  4314. {
  4315. return GetConfig()->IsSimdjsEnabled();
  4316. }
  4317. #endif
  4318. bool ScriptContext::IsPRNGSeeded() const
  4319. {
  4320. return GetLibrary()->IsPRNGSeeded();
  4321. }
  4322. intptr_t ScriptContext::GetAddr() const
  4323. {
  4324. return (intptr_t)this;
  4325. }
  4326. #if ENABLE_NATIVE_CODEGEN
  4327. void ScriptContext::AddToDOMFastPathHelperMap(intptr_t funcInfoAddr, IR::JnHelperMethod helper)
  4328. {
  4329. m_domFastPathHelperMap->Add(funcInfoAddr, helper);
  4330. }
  4331. IR::JnHelperMethod ScriptContext::GetDOMFastPathHelper(intptr_t funcInfoAddr)
  4332. {
  4333. IR::JnHelperMethod helper = IR::HelperInvalid;
  4334. m_domFastPathHelperMap->LockResize();
  4335. m_domFastPathHelperMap->TryGetValue(funcInfoAddr, &helper);
  4336. m_domFastPathHelperMap->UnlockResize();
  4337. return helper;
  4338. }
  4339. #endif
  4340. intptr_t ScriptContext::GetVTableAddress(VTableValue vtableType) const
  4341. {
  4342. Assert(vtableType < VTableValue::Count);
  4343. return GetLibrary()->GetVTableAddresses()[vtableType];
  4344. }
  4345. bool ScriptContext::IsRecyclerVerifyEnabled() const
  4346. {
  4347. #ifdef RECYCLER_MEMORY_VERIFY
  4348. return recycler->VerifyEnabled() != FALSE;
  4349. #else
  4350. return false;
  4351. #endif
  4352. }
  4353. uint ScriptContext::GetRecyclerVerifyPad() const
  4354. {
  4355. #ifdef RECYCLER_MEMORY_VERIFY
  4356. return recycler->GetVerifyPad();
  4357. #else
  4358. return 0;
  4359. #endif
  4360. }
  4361. JavascriptFunction* ScriptContext::GetBuiltInLibraryFunction(JavascriptMethod entryPoint)
  4362. {
  4363. JavascriptFunction * function = NULL;
  4364. if (builtInLibraryFunctions)
  4365. {
  4366. builtInLibraryFunctions->TryGetValue(entryPoint, &function);
  4367. }
  4368. return function;
  4369. }
  4370. #if ENABLE_PROFILE_INFO
  4371. template<template<typename> class BarrierT>
  4372. void ScriptContext::AddDynamicProfileInfo(
  4373. FunctionBody * functionBody, BarrierT<DynamicProfileInfo>& dynamicProfileInfo)
  4374. {
  4375. Assert(functionBody->GetScriptContext() == this);
  4376. Assert(functionBody->HasValidSourceInfo());
  4377. DynamicProfileInfo * newDynamicProfileInfo = dynamicProfileInfo;
  4378. // If it is a dynamic script - we should create a profile info bound to the threadContext for its lifetime.
  4379. SourceContextInfo* sourceContextInfo = functionBody->GetSourceContextInfo();
  4380. SourceDynamicProfileManager* profileManager = sourceContextInfo->sourceDynamicProfileManager;
  4381. if (sourceContextInfo->IsDynamic())
  4382. {
  4383. if (profileManager != nullptr)
  4384. {
  4385. // There is an in-memory cache and dynamic profile info is coming from there
  4386. if (newDynamicProfileInfo == nullptr)
  4387. {
  4388. newDynamicProfileInfo = DynamicProfileInfo::New(this->GetRecycler(), functionBody, true /* persistsAcrossScriptContexts */);
  4389. profileManager->UpdateDynamicProfileInfo(functionBody->GetLocalFunctionId(), newDynamicProfileInfo);
  4390. dynamicProfileInfo = newDynamicProfileInfo;
  4391. }
  4392. profileManager->MarkAsExecuted(functionBody->GetLocalFunctionId());
  4393. newDynamicProfileInfo->UpdateFunctionInfo(functionBody, this->GetRecycler());
  4394. }
  4395. else
  4396. {
  4397. if (newDynamicProfileInfo == nullptr)
  4398. {
  4399. newDynamicProfileInfo = functionBody->AllocateDynamicProfile();
  4400. }
  4401. dynamicProfileInfo = newDynamicProfileInfo;
  4402. }
  4403. }
  4404. else
  4405. {
  4406. if (newDynamicProfileInfo == nullptr)
  4407. {
  4408. newDynamicProfileInfo = functionBody->AllocateDynamicProfile();
  4409. dynamicProfileInfo = newDynamicProfileInfo;
  4410. }
  4411. Assert(functionBody->GetInterpretedCount() == 0);
  4412. #if DBG_DUMP || defined(DYNAMIC_PROFILE_STORAGE) || defined(RUNTIME_DATA_COLLECTION)
  4413. if (this->Cache()->profileInfoList)
  4414. {
  4415. this->Cache()->profileInfoList->Prepend(this->GetRecycler(), newDynamicProfileInfo);
  4416. }
  4417. #endif
  4418. if (!startupComplete)
  4419. {
  4420. Assert(profileManager);
  4421. profileManager->MarkAsExecuted(functionBody->GetLocalFunctionId());
  4422. }
  4423. }
  4424. Assert(dynamicProfileInfo != nullptr);
  4425. }
  4426. template void ScriptContext::AddDynamicProfileInfo<WriteBarrierPtr>(FunctionBody *, WriteBarrierPtr<DynamicProfileInfo>&);
  4427. #endif
  4428. CharClassifier const * ScriptContext::GetCharClassifier(void) const
  4429. {
  4430. return this->charClassifier;
  4431. }
  4432. void ScriptContext::OnStartupComplete()
  4433. {
  4434. JS_ETW(EventWriteJSCRIPT_ON_STARTUP_COMPLETE(this));
  4435. SaveStartupProfileAndRelease();
  4436. }
  4437. void ScriptContext::SaveStartupProfileAndRelease(bool isSaveOnClose)
  4438. {
  4439. // No need to save profiler info in JSRT scenario at this time.
  4440. if (GetThreadContext()->IsJSRT())
  4441. {
  4442. return;
  4443. }
  4444. if (!startupComplete && this->Cache()->sourceContextInfoMap)
  4445. {
  4446. #if ENABLE_PROFILE_INFO
  4447. this->Cache()->sourceContextInfoMap->Map([&](DWORD_PTR dwHostSourceContext, SourceContextInfo* info)
  4448. {
  4449. Assert(info->sourceDynamicProfileManager);
  4450. uint bytesWritten = info->sourceDynamicProfileManager->SaveToProfileCacheAndRelease(info);
  4451. if (bytesWritten > 0)
  4452. {
  4453. JS_ETW(EventWriteJSCRIPT_PROFILE_SAVE(info->dwHostSourceContext, this, bytesWritten, isSaveOnClose));
  4454. OUTPUT_TRACE(Js::DynamicProfilePhase, _u("Profile saving succeeded\n"));
  4455. }
  4456. });
  4457. #endif
  4458. }
  4459. startupComplete = true;
  4460. }
  4461. void ScriptContext::SetFastDOMenabled()
  4462. {
  4463. fastDOMenabled = true; Assert(globalObject->GetDirectHostObject() != NULL);
  4464. }
  4465. #if DYNAMIC_INTERPRETER_THUNK
  4466. JavascriptMethod ScriptContext::GetNextDynamicAsmJsInterpreterThunk(PVOID* ppDynamicInterpreterThunk)
  4467. {
  4468. #ifdef ASMJS_PLAT
  4469. return (JavascriptMethod)this->asmJsInterpreterThunkEmitter->GetNextThunk(ppDynamicInterpreterThunk);
  4470. #else
  4471. __debugbreak();
  4472. return nullptr;
  4473. #endif
  4474. }
  4475. JavascriptMethod ScriptContext::GetNextDynamicInterpreterThunk(PVOID* ppDynamicInterpreterThunk)
  4476. {
  4477. return (JavascriptMethod)this->interpreterThunkEmitter->GetNextThunk(ppDynamicInterpreterThunk);
  4478. }
  4479. #if DBG
  4480. BOOL ScriptContext::IsDynamicInterpreterThunk(JavascriptMethod address)
  4481. {
  4482. return this->interpreterThunkEmitter->IsInHeap((void*)address);
  4483. }
  4484. #endif
  4485. void ScriptContext::ReleaseDynamicInterpreterThunk(BYTE* address, bool addtoFreeList)
  4486. {
  4487. this->interpreterThunkEmitter->Release(address, addtoFreeList);
  4488. }
  4489. void ScriptContext::ReleaseDynamicAsmJsInterpreterThunk(BYTE* address, bool addtoFreeList)
  4490. {
  4491. #ifdef ASMJS_PLAT
  4492. this->asmJsInterpreterThunkEmitter->Release(address, addtoFreeList);
  4493. #else
  4494. Assert(UNREACHED);
  4495. #endif
  4496. }
  4497. #endif
  4498. bool ScriptContext::IsExceptionWrapperForBuiltInsEnabled()
  4499. {
  4500. return ScriptContext::IsExceptionWrapperForBuiltInsEnabled(this);
  4501. }
  4502. // static
  4503. bool ScriptContext::IsExceptionWrapperForBuiltInsEnabled(ScriptContext* scriptContext)
  4504. {
  4505. Assert(scriptContext);
  4506. return CONFIG_FLAG(EnableContinueAfterExceptionWrappersForBuiltIns);
  4507. }
  4508. bool ScriptContext::IsExceptionWrapperForHelpersEnabled(ScriptContext* scriptContext)
  4509. {
  4510. Assert(scriptContext);
  4511. return CONFIG_FLAG(EnableContinueAfterExceptionWrappersForHelpers);
  4512. }
  4513. void ScriptContextBase::SetGlobalObject(GlobalObject *globalObject)
  4514. {
  4515. #if DBG
  4516. ScriptContext* scriptContext = static_cast<ScriptContext*>(this);
  4517. Assert(scriptContext->IsCloningGlobal() && !this->globalObject);
  4518. #endif
  4519. this->globalObject = globalObject;
  4520. }
  4521. void ConvertKey(const FastEvalMapString& src, EvalMapString& dest)
  4522. {
  4523. dest.str = src.str;
  4524. dest.strict = src.strict;
  4525. dest.moduleID = src.moduleID;
  4526. dest.hash = TAGHASH((hash_t)dest.str);
  4527. }
  4528. void ScriptContext::PrintStats()
  4529. {
  4530. #ifdef PROFILE_TYPES
  4531. if (Configuration::Global.flags.ProfileTypes)
  4532. {
  4533. ProfileTypes();
  4534. }
  4535. #endif
  4536. #ifdef PROFILE_BAILOUT_RECORD_MEMORY
  4537. if (Configuration::Global.flags.ProfileBailOutRecordMemory)
  4538. {
  4539. Output::Print(_u("CodeSize: %6d\nBailOutRecord Size: %6d\nLocalOffsets Size: %6d\n"), codeSize, bailOutRecordBytes, bailOutOffsetBytes);
  4540. }
  4541. #endif
  4542. #ifdef PROFILE_OBJECT_LITERALS
  4543. if (Configuration::Global.flags.ProfileObjectLiteral)
  4544. {
  4545. ProfileObjectLiteral();
  4546. }
  4547. #endif
  4548. #ifdef PROFILE_STRINGS
  4549. if (stringProfiler != nullptr)
  4550. {
  4551. stringProfiler->PrintAll();
  4552. Adelete(MiscAllocator(), stringProfiler);
  4553. stringProfiler = nullptr;
  4554. }
  4555. #endif
  4556. #ifdef PROFILE_MEM
  4557. if (profileMemoryDump && MemoryProfiler::IsTraceEnabled())
  4558. {
  4559. MemoryProfiler::PrintAll();
  4560. #ifdef PROFILE_RECYCLER_ALLOC
  4561. if (Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::AllPhase)
  4562. || Js::Configuration::Global.flags.TraceMemory.IsEnabled(Js::RunPhase))
  4563. {
  4564. GetRecycler()->PrintAllocStats();
  4565. }
  4566. #endif
  4567. }
  4568. #endif
  4569. #if DBG_DUMP
  4570. if (PHASE_STATS1(Js::ByteCodePhase))
  4571. {
  4572. Output::Print(_u(" Total Bytecode size: <%d, %d, %d> = %d\n"),
  4573. byteCodeDataSize,
  4574. byteCodeAuxiliaryDataSize,
  4575. byteCodeAuxiliaryContextDataSize,
  4576. byteCodeDataSize + byteCodeAuxiliaryDataSize + byteCodeAuxiliaryContextDataSize);
  4577. }
  4578. if (Configuration::Global.flags.BytecodeHist)
  4579. {
  4580. Output::Print(_u("ByteCode Histogram\n"));
  4581. Output::Print(_u("\n"));
  4582. uint total = 0;
  4583. uint unique = 0;
  4584. for (int j = 0; j < (int)OpCode::ByteCodeLast; j++)
  4585. {
  4586. total += byteCodeHistogram[j];
  4587. if (byteCodeHistogram[j] > 0)
  4588. {
  4589. unique++;
  4590. }
  4591. }
  4592. Output::Print(_u("%9u Total executed ops\n"), total);
  4593. Output::Print(_u("\n"));
  4594. uint max = UINT_MAX;
  4595. double pctcume = 0.0;
  4596. while (true)
  4597. {
  4598. uint upper = 0;
  4599. int index = -1;
  4600. for (int j = 0; j < (int)OpCode::ByteCodeLast; j++)
  4601. {
  4602. if (OpCodeUtil::IsValidOpcode((OpCode)j) && byteCodeHistogram[j] > upper && byteCodeHistogram[j] < max)
  4603. {
  4604. index = j;
  4605. upper = byteCodeHistogram[j];
  4606. }
  4607. }
  4608. if (index == -1)
  4609. {
  4610. break;
  4611. }
  4612. max = byteCodeHistogram[index];
  4613. for (OpCode j = (OpCode)0; j < OpCode::ByteCodeLast; j++)
  4614. {
  4615. if (OpCodeUtil::IsValidOpcode(j) && max == byteCodeHistogram[(int)j])
  4616. {
  4617. double pct = ((double)max) / total;
  4618. pctcume += pct;
  4619. Output::Print(_u("%9u %5.1lf %5.1lf %04x %s\n"), max, pct * 100, pctcume * 100, j, OpCodeUtil::GetOpCodeName(j));
  4620. }
  4621. }
  4622. }
  4623. Output::Print(_u("\n"));
  4624. Output::Print(_u("Unique opcodes: %d\n"), unique);
  4625. }
  4626. #endif
  4627. #if ENABLE_NATIVE_CODEGEN
  4628. #ifdef BGJIT_STATS
  4629. // We do not care about small script contexts without much activity - unless t
  4630. if (PHASE_STATS1(Js::BGJitPhase) && (this->interpretedCount > 50 || Js::Configuration::Global.flags.IsEnabled(Js::ForceFlag)))
  4631. {
  4632. #define MAX_BUCKETS 15
  4633. uint loopJitCodeUsed = 0;
  4634. uint bucketSize1 = 20;
  4635. uint bucketSize2 = 100;
  4636. uint size1CutOffbucketId = 4;
  4637. uint totalBuckets[MAX_BUCKETS] = { 0 };
  4638. uint nativeCodeBuckets[MAX_BUCKETS] = { 0 };
  4639. uint usedNativeCodeBuckets[MAX_BUCKETS] = { 0 };
  4640. uint rejits[MAX_BUCKETS] = { 0 };
  4641. uint zeroInterpretedFunctions = 0;
  4642. uint oneInterpretedFunctions = 0;
  4643. uint nonZeroBytecodeFunctions = 0;
  4644. Output::Print(_u("Script Context: 0x%p Url: %s\n"), this, this->url);
  4645. FunctionBody* anyFunctionBody = this->FindFunction([](FunctionBody* body) { return body != nullptr; });
  4646. if (anyFunctionBody)
  4647. {
  4648. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("Function list\n"));
  4649. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("===============================\n"));
  4650. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("%-24s, %-8s, %-10s, %-10s, %-10s, %-10s, %-10s\n"), _u("Function"), _u("InterpretedCount"), _u("ByteCodeInLoopSize"), _u("ByteCodeSize"), _u("IsJitted"), _u("IsUsed"), _u("NativeCodeSize"));
  4651. this->MapFunction([&](FunctionBody* body)
  4652. {
  4653. bool isNativeCode = false;
  4654. // Filtering interpreted count lowers a lot of noise
  4655. if (body->GetInterpretedCount() > 1 || Js::Configuration::Global.flags.IsEnabled(Js::ForceFlag))
  4656. {
  4657. body->MapEntryPoints([&](uint entryPointIndex, FunctionEntryPointInfo* entryPoint)
  4658. {
  4659. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4660. char rejit = entryPointIndex > 0 ? '*' : ' ';
  4661. isNativeCode = entryPoint->IsNativeCode() | isNativeCode;
  4662. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("%-20s %16s %c, %8d , %10d , %10d, %-10s, %-10s, %10d\n"),
  4663. body->GetExternalDisplayName(),
  4664. body->GetDebugNumberSet(debugStringBuffer),
  4665. rejit,
  4666. body->GetInterpretedCount(),
  4667. body->GetByteCodeInLoopCount(),
  4668. body->GetByteCodeCount(),
  4669. entryPoint->IsNativeCode() ? _u("Jitted") : _u("Interpreted"),
  4670. body->GetNativeEntryPointUsed() ? _u("Used") : _u("NotUsed"),
  4671. entryPoint->IsNativeCode() ? entryPoint->GetCodeSize() : 0);
  4672. });
  4673. }
  4674. if (body->GetInterpretedCount() == 0)
  4675. {
  4676. zeroInterpretedFunctions++;
  4677. if (body->GetByteCodeCount() > 0)
  4678. {
  4679. nonZeroBytecodeFunctions++;
  4680. }
  4681. }
  4682. else if (body->GetInterpretedCount() == 1)
  4683. {
  4684. oneInterpretedFunctions++;
  4685. }
  4686. // Generate a histogram using interpreted counts.
  4687. uint bucket;
  4688. uint intrpCount = body->GetInterpretedCount();
  4689. if (intrpCount < 100)
  4690. {
  4691. bucket = intrpCount / bucketSize1;
  4692. }
  4693. else if (intrpCount < 1000)
  4694. {
  4695. bucket = size1CutOffbucketId + intrpCount / bucketSize2;
  4696. }
  4697. else
  4698. {
  4699. bucket = MAX_BUCKETS - 1;
  4700. }
  4701. // Explicitly assume that the bucket count is less than the following counts (which are all equal)
  4702. // This is because min will return MAX_BUCKETS - 1 if the count exceeds MAX_BUCKETS - 1.
  4703. __analysis_assume(bucket < MAX_BUCKETS);
  4704. totalBuckets[bucket]++;
  4705. if (isNativeCode)
  4706. {
  4707. nativeCodeBuckets[bucket]++;
  4708. if (body->GetNativeEntryPointUsed())
  4709. {
  4710. usedNativeCodeBuckets[bucket]++;
  4711. }
  4712. if (body->HasRejit())
  4713. {
  4714. rejits[bucket]++;
  4715. }
  4716. }
  4717. body->MapLoopHeaders([&](uint loopNumber, LoopHeader* header)
  4718. {
  4719. char16 loopBodyName[256];
  4720. body->GetLoopBodyName(loopNumber, loopBodyName, _countof(loopBodyName));
  4721. header->MapEntryPoints([&](int index, LoopEntryPointInfo * entryPoint)
  4722. {
  4723. if (entryPoint->IsNativeCode())
  4724. {
  4725. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4726. char rejit = index > 0 ? '*' : ' ';
  4727. OUTPUT_VERBOSE_STATS(Js::BGJitPhase, _u("%-20s %16s %c, %8d , %10d , %10d, %-10s, %-10s, %10d\n"),
  4728. loopBodyName,
  4729. body->GetDebugNumberSet(debugStringBuffer),
  4730. rejit,
  4731. header->interpretCount,
  4732. header->GetByteCodeCount(),
  4733. header->GetByteCodeCount(),
  4734. _u("Jitted"),
  4735. entryPoint->IsUsed() ? _u("Used") : _u("NotUsed"),
  4736. entryPoint->GetCodeSize());
  4737. if (entryPoint->IsUsed())
  4738. {
  4739. loopJitCodeUsed++;
  4740. }
  4741. }
  4742. });
  4743. });
  4744. });
  4745. }
  4746. Output::Print(_u("** SpeculativelyJitted: %6d FunctionsJitted: %6d JittedUsed: %6d Usage:%f ByteCodesJitted: %6d JitCodeUsed: %6d Usage: %f \n"),
  4747. speculativeJitCount, funcJITCount, funcJitCodeUsed, ((float)(funcJitCodeUsed) / funcJITCount) * 100, bytecodeJITCount, jitCodeUsed, ((float)(jitCodeUsed) / bytecodeJITCount) * 100);
  4748. Output::Print(_u("** LoopJITCount: %6d LoopJitCodeUsed: %6d Usage: %f\n"),
  4749. loopJITCount, loopJitCodeUsed, ((float)loopJitCodeUsed / loopJITCount) * 100);
  4750. Output::Print(_u("** TotalInterpretedCalls: %6d MaxFuncInterp: %6d InterpretedHighPri: %6d \n"),
  4751. interpretedCount, maxFuncInterpret, interpretedCallsHighPri);
  4752. Output::Print(_u("** ZeroInterpretedFunctions: %6d OneInterpretedFunctions: %6d ZeroInterpretedWithNonZeroBytecode: %6d \n "), zeroInterpretedFunctions, oneInterpretedFunctions, nonZeroBytecodeFunctions);
  4753. Output::Print(_u("** %-24s : %-10s %-10s %-10s %-10s %-10s\n"), _u("InterpretedCounts"), _u("Total"), _u("NativeCode"), _u("Used"), _u("Usage"), _u("Rejits"));
  4754. uint low = 0;
  4755. uint high = 0;
  4756. for (uint i = 0; i < _countof(totalBuckets); i++)
  4757. {
  4758. low = high;
  4759. if (i <= size1CutOffbucketId)
  4760. {
  4761. high = low + bucketSize1;
  4762. }
  4763. else if (i < (_countof(totalBuckets) - 1))
  4764. {
  4765. high = low + bucketSize2; }
  4766. else
  4767. {
  4768. high = 100000;
  4769. }
  4770. Output::Print(_u("** %10d - %10d : %10d %10d %10d %7.2f %10d\n"), low, high, totalBuckets[i], nativeCodeBuckets[i], usedNativeCodeBuckets[i], ((float)usedNativeCodeBuckets[i] / nativeCodeBuckets[i]) * 100, rejits[i]);
  4771. }
  4772. Output::Print(_u("\n\n"));
  4773. }
  4774. #undef MAX_BUCKETS
  4775. #endif
  4776. #ifdef REJIT_STATS
  4777. if (PHASE_STATS1(Js::ReJITPhase))
  4778. {
  4779. uint totalBailouts = 0;
  4780. uint totalRejits = 0;
  4781. WCHAR buf[256];
  4782. // Dump bailout data.
  4783. Output::Print(_u("%-40s %6s\n"), _u("Bailout Reason,"), _u("Count"));
  4784. bailoutReasonCounts->Map([&totalBailouts](uint kind, uint val) {
  4785. WCHAR buf[256];
  4786. totalBailouts += val;
  4787. if (val != 0)
  4788. {
  4789. swprintf_s(buf, _u("%S,"), GetBailOutKindName((IR::BailOutKind)kind));
  4790. Output::Print(_u("%-40s %6d\n"), buf, val);
  4791. }
  4792. });
  4793. Output::Print(_u("%-40s %6d\n"), _u("TOTAL,"), totalBailouts);
  4794. Output::Print(_u("\n\n"));
  4795. // Dump rejit data.
  4796. Output::Print(_u("%-40s %6s\n"), _u("Rejit Reason,"), _u("Count"));
  4797. for (uint i = 0; i < NumRejitReasons; ++i)
  4798. {
  4799. totalRejits += rejitReasonCounts[i];
  4800. if (rejitReasonCounts[i] != 0)
  4801. {
  4802. swprintf_s(buf, _u("%S,"), RejitReasonNames[i]);
  4803. Output::Print(_u("%-40s %6d\n"), buf, rejitReasonCounts[i]);
  4804. }
  4805. }
  4806. Output::Print(_u("%-40s %6d\n"), _u("TOTAL,"), totalRejits);
  4807. Output::Print(_u("\n\n"));
  4808. // If in verbose mode, dump data for each FunctionBody
  4809. if (
  4810. #if defined(FLAG) || defined(FLAG_REGOVR_EXP)
  4811. Configuration::Global.flags.Verbose &&
  4812. #endif
  4813. rejitStatsMap != nullptr)
  4814. {
  4815. // Aggregated data
  4816. Output::Print(_u("%-30s %14s %14s\n"), _u("Function (#),"), _u("Bailout Count,"), _u("Rejit Count"));
  4817. rejitStatsMap->Map([](Js::FunctionBody const *body, RejitStats *stats, RecyclerWeakReference<const Js::FunctionBody> const*) {
  4818. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4819. for (uint i = 0; i < NumRejitReasons; ++i)
  4820. stats->m_totalRejits += stats->m_rejitReasonCounts[i];
  4821. stats->m_bailoutReasonCounts->Map([stats](uint kind, uint val) {
  4822. stats->m_totalBailouts += val;
  4823. });
  4824. WCHAR buf[256];
  4825. swprintf_s(buf, _u("%s (%s),"), body->GetExternalDisplayName(), (const_cast<Js::FunctionBody*>(body))->GetDebugNumberSet(debugStringBuffer)); //TODO Kount
  4826. Output::Print(_u("%-30s %14d, %14d\n"), buf, stats->m_totalBailouts, stats->m_totalRejits);
  4827. });
  4828. Output::Print(_u("\n\n"));
  4829. // Per FunctionBody data
  4830. rejitStatsMap->Map([](Js::FunctionBody const *body, RejitStats *stats, RecyclerWeakReference<const Js::FunctionBody> const *) {
  4831. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4832. WCHAR buf[256];
  4833. swprintf_s(buf, _u("%s (%s),"), body->GetExternalDisplayName(), (const_cast<Js::FunctionBody*>(body))->GetDebugNumberSet(debugStringBuffer)); //TODO Kount
  4834. Output::Print(_u("%-30s\n\n"), buf);
  4835. // Dump bailout data
  4836. if (stats->m_totalBailouts != 0)
  4837. {
  4838. Output::Print(_u("%10sBailouts:\n"), _u(""));
  4839. stats->m_bailoutReasonCounts->Map([](uint kind, uint val) {
  4840. if (val != 0)
  4841. {
  4842. WCHAR buf[256];
  4843. swprintf_s(buf, _u("%S,"), GetBailOutKindName((IR::BailOutKind)kind));
  4844. Output::Print(_u("%10s%-40s %6d\n"), _u(""), buf, val);
  4845. }
  4846. });
  4847. }
  4848. Output::Print(_u("\n"));
  4849. // Dump rejit data.
  4850. if (stats->m_totalRejits != 0)
  4851. {
  4852. Output::Print(_u("%10sRejits:\n"), _u(""));
  4853. for (uint i = 0; i < NumRejitReasons; ++i)
  4854. {
  4855. if (stats->m_rejitReasonCounts[i] != 0)
  4856. {
  4857. swprintf_s(buf, _u("%S,"), RejitReasonNames[i]);
  4858. Output::Print(_u("%10s%-40s %6d\n"), _u(""), buf, stats->m_rejitReasonCounts[i]);
  4859. }
  4860. }
  4861. Output::Print(_u("\n\n"));
  4862. }
  4863. });
  4864. }
  4865. }
  4866. this->ClearBailoutReasonCountsMap();
  4867. this->ClearRejitReasonCountsArray();
  4868. #endif
  4869. #ifdef FIELD_ACCESS_STATS
  4870. if (PHASE_STATS1(Js::ObjTypeSpecPhase))
  4871. {
  4872. FieldAccessStats globalStats;
  4873. if (this->fieldAccessStatsByFunctionNumber != nullptr)
  4874. {
  4875. this->fieldAccessStatsByFunctionNumber->Map([&globalStats](uint functionNumber, FieldAccessStatsEntry* entry)
  4876. {
  4877. FieldAccessStats functionStats;
  4878. entry->stats.Map([&functionStats](FieldAccessStatsPtr entryPointStats)
  4879. {
  4880. functionStats.Add(entryPointStats);
  4881. });
  4882. if (PHASE_VERBOSE_STATS1(Js::ObjTypeSpecPhase))
  4883. {
  4884. FunctionBody* functionBody = entry->functionBodyWeakRef->Get();
  4885. const char16* functionName = functionBody != nullptr ? functionBody->GetDisplayName() : _u("<unknown>");
  4886. Output::Print(_u("FieldAccessStats: function %s (#%u): inline cache stats:\n"), functionName, functionNumber);
  4887. Output::Print(_u(" overall: total %u, no profile info %u\n"), functionStats.totalInlineCacheCount, functionStats.noInfoInlineCacheCount);
  4888. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  4889. functionStats.monoInlineCacheCount, functionStats.emptyMonoInlineCacheCount, functionStats.clonedMonoInlineCacheCount);
  4890. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  4891. functionStats.polyInlineCacheCount, functionStats.highUtilPolyInlineCacheCount, functionStats.lowUtilPolyInlineCacheCount,
  4892. functionStats.nullPolyInlineCacheCount, functionStats.emptyPolyInlineCacheCount, functionStats.ignoredPolyInlineCacheCount, functionStats.disabledPolyInlineCacheCount,
  4893. functionStats.equivPolyInlineCacheCount, functionStats.nonEquivPolyInlineCacheCount, functionStats.clonedPolyInlineCacheCount);
  4894. }
  4895. globalStats.Add(&functionStats);
  4896. });
  4897. }
  4898. Output::Print(_u("FieldAccessStats: totals\n"));
  4899. Output::Print(_u(" overall: total %u, no profile info %u\n"), globalStats.totalInlineCacheCount, globalStats.noInfoInlineCacheCount);
  4900. Output::Print(_u(" mono: total %u, empty %u, cloned %u\n"),
  4901. globalStats.monoInlineCacheCount, globalStats.emptyMonoInlineCacheCount, globalStats.clonedMonoInlineCacheCount);
  4902. Output::Print(_u(" poly: total %u (high %u, low %u), null %u, empty %u, ignored %u, disabled %u, equivalent %u, non-equivalent %u, cloned %u\n"),
  4903. globalStats.polyInlineCacheCount, globalStats.highUtilPolyInlineCacheCount, globalStats.lowUtilPolyInlineCacheCount,
  4904. globalStats.nullPolyInlineCacheCount, globalStats.emptyPolyInlineCacheCount, globalStats.ignoredPolyInlineCacheCount, globalStats.disabledPolyInlineCacheCount,
  4905. globalStats.equivPolyInlineCacheCount, globalStats.nonEquivPolyInlineCacheCount, globalStats.clonedPolyInlineCacheCount);
  4906. }
  4907. #endif
  4908. #ifdef MISSING_PROPERTY_STATS
  4909. if (PHASE_STATS1(Js::MissingPropertyCachePhase))
  4910. {
  4911. Output::Print(_u("MissingPropertyStats: hits = %d, misses = %d, cache attempts = %d.\n"),
  4912. this->missingPropertyHits, this->missingPropertyMisses, this->missingPropertyCacheAttempts);
  4913. }
  4914. #endif
  4915. #ifdef INLINE_CACHE_STATS
  4916. if (PHASE_STATS1(Js::PolymorphicInlineCachePhase))
  4917. {
  4918. Output::Print(_u("%s,%s,%s,%s,%s,%s,%s,%s,%s\n"), _u("Function"), _u("Property"), _u("Kind"), _u("Accesses"), _u("Misses"), _u("Miss Rate"), _u("Collisions"), _u("Collision Rate"), _u("Slot Count"));
  4919. cacheDataMap->Map([this](Js::PolymorphicInlineCache const *cache, InlineCacheData *data) {
  4920. cache->PrintStats(data);
  4921. });
  4922. }
  4923. #endif
  4924. #if ENABLE_REGEX_CONFIG_OPTIONS
  4925. if (regexStatsDatabase != 0)
  4926. regexStatsDatabase->Print(GetRegexDebugWriter());
  4927. #endif
  4928. OUTPUT_STATS(Js::EmitterPhase, _u("Script Context: 0x%p Url: %s\n"), this, this->url);
  4929. OUTPUT_STATS(Js::EmitterPhase, _u(" Total thread committed code size = %d\n"), this->GetThreadContext()->GetCodeSize());
  4930. OUTPUT_STATS(Js::ParsePhase, _u("Script Context: 0x%p Url: %s\n"), this, this->url);
  4931. OUTPUT_STATS(Js::ParsePhase, _u(" Total ThreadContext source size %d\n"), this->GetThreadContext()->GetSourceSize());
  4932. #endif
  4933. #ifdef ENABLE_BASIC_TELEMETRY
  4934. if (this->telemetry != nullptr)
  4935. {
  4936. // If an exception (e.g. out-of-memory) happens during InitializeAllocations then `this->telemetry` will be null and the Close method will still be called, hence this guard expression.
  4937. this->telemetry->OutputPrint();
  4938. }
  4939. #endif
  4940. Output::Flush();
  4941. }
  4942. void ScriptContext::SetNextPendingClose(ScriptContext * nextPendingClose) {
  4943. this->nextPendingClose = nextPendingClose;
  4944. }
  4945. #ifdef ENABLE_MUTATION_BREAKPOINT
  4946. bool ScriptContext::HasMutationBreakpoints()
  4947. {
  4948. if (this->GetDebugContext() != nullptr && this->GetDebugContext()->GetProbeContainer() != nullptr)
  4949. {
  4950. return this->GetDebugContext()->GetProbeContainer()->HasMutationBreakpoints();
  4951. }
  4952. return false;
  4953. }
  4954. void ScriptContext::InsertMutationBreakpoint(Js::MutationBreakpoint *mutationBreakpoint)
  4955. {
  4956. this->GetDebugContext()->GetProbeContainer()->InsertMutationBreakpoint(mutationBreakpoint);
  4957. }
  4958. #endif
  4959. #ifdef REJIT_STATS
  4960. void ScriptContext::LogDataForFunctionBody(Js::FunctionBody *body, uint idx, bool isRejit)
  4961. {
  4962. if (rejitStatsMap == NULL)
  4963. {
  4964. rejitStatsMap = RecyclerNew(this->recycler, RejitStatsMap, this->recycler);
  4965. BindReference(rejitStatsMap);
  4966. }
  4967. RejitStats *stats = NULL;
  4968. if (!rejitStatsMap->TryGetValue(body, &stats))
  4969. {
  4970. stats = Anew(GeneralAllocator(), RejitStats, this);
  4971. rejitStatsMap->Item(body, stats);
  4972. }
  4973. if (isRejit)
  4974. {
  4975. stats->m_rejitReasonCounts[idx]++;
  4976. }
  4977. else
  4978. {
  4979. if (!stats->m_bailoutReasonCounts->ContainsKey(idx))
  4980. {
  4981. stats->m_bailoutReasonCounts->Item(idx, 1);
  4982. }
  4983. else
  4984. {
  4985. uint val = stats->m_bailoutReasonCounts->Item(idx);
  4986. ++val;
  4987. stats->m_bailoutReasonCounts->Item(idx, val);
  4988. }
  4989. }
  4990. }
  4991. void ScriptContext::LogRejit(Js::FunctionBody *body, RejitReason reason)
  4992. {
  4993. byte reasonIndex = static_cast<byte>(reason);
  4994. Assert(reasonIndex < NumRejitReasons);
  4995. rejitReasonCounts[reasonIndex]++;
  4996. #if defined(FLAG) || defined(FLAG_REGOVR_EXP)
  4997. if (Js::Configuration::Global.flags.Verbose)
  4998. {
  4999. LogDataForFunctionBody(body, reasonIndex, true);
  5000. }
  5001. #endif
  5002. }
  5003. void ScriptContext::LogBailout(Js::FunctionBody *body, uint kind)
  5004. {
  5005. if (!bailoutReasonCounts->ContainsKey(kind))
  5006. {
  5007. bailoutReasonCounts->Item(kind, 1);
  5008. }
  5009. else
  5010. {
  5011. uint val = bailoutReasonCounts->Item(kind);
  5012. ++val;
  5013. bailoutReasonCounts->Item(kind, val);
  5014. }
  5015. #if defined(FLAG) || defined(FLAG_REGOVR_EXP)
  5016. if (Js::Configuration::Global.flags.Verbose)
  5017. {
  5018. LogDataForFunctionBody(body, kind, false);
  5019. }
  5020. #endif
  5021. }
  5022. void ScriptContext::ClearBailoutReasonCountsMap()
  5023. {
  5024. if (this->bailoutReasonCounts != nullptr)
  5025. {
  5026. this->bailoutReasonCounts->Clear();
  5027. }
  5028. if (this->bailoutReasonCountsCap != nullptr)
  5029. {
  5030. this->bailoutReasonCountsCap->Clear();
  5031. }
  5032. }
  5033. void ScriptContext::ClearRejitReasonCountsArray()
  5034. {
  5035. if (this->rejitReasonCounts != nullptr)
  5036. {
  5037. for (UINT16 i = 0; i < NumRejitReasons; i++)
  5038. {
  5039. this->rejitReasonCounts[i] = 0;
  5040. }
  5041. }
  5042. if (this->rejitReasonCountsCap != nullptr)
  5043. {
  5044. for (UINT16 i = 0; i < NumRejitReasons; i++)
  5045. {
  5046. this->rejitReasonCountsCap[i] = 0;
  5047. }
  5048. }
  5049. }
  5050. #endif
  5051. #ifdef ENABLE_BASIC_TELEMETRY
  5052. ScriptContextTelemetry& ScriptContext::GetTelemetry()
  5053. {
  5054. return *this->telemetry;
  5055. }
  5056. bool ScriptContext::HasTelemetry()
  5057. {
  5058. return this->telemetry != nullptr;
  5059. }
  5060. #endif
  5061. #ifdef ENABLE_SCRIPT_DEBUGGING
  5062. DebugContext* ScriptContext::GetDebugContext() const
  5063. {
  5064. Assert(this->debugContext != nullptr);
  5065. if (this->debugContext->IsClosed())
  5066. {
  5067. // Once DebugContext is closed we should assume it's not there
  5068. // The actual deletion of debugContext happens in ScriptContext destructor
  5069. return nullptr;
  5070. }
  5071. return this->debugContext;
  5072. }
  5073. #endif
  5074. bool ScriptContext::IsScriptContextInNonDebugMode() const
  5075. {
  5076. #ifdef ENABLE_SCRIPT_DEBUGGING
  5077. if (this->GetDebugContext() != nullptr)
  5078. {
  5079. return this->GetDebugContext()->IsDebugContextInNonDebugMode();
  5080. }
  5081. #endif
  5082. return true;
  5083. }
  5084. bool ScriptContext::IsScriptContextInDebugMode() const
  5085. {
  5086. #ifdef ENABLE_SCRIPT_DEBUGGING
  5087. if (this->GetDebugContext() != nullptr)
  5088. {
  5089. return this->GetDebugContext()->IsDebugContextInDebugMode();
  5090. }
  5091. #endif
  5092. return false;
  5093. }
  5094. bool ScriptContext::IsScriptContextInSourceRundownOrDebugMode() const
  5095. {
  5096. #ifdef ENABLE_SCRIPT_DEBUGGING
  5097. if (this->GetDebugContext() != nullptr)
  5098. {
  5099. return this->GetDebugContext()->IsDebugContextInSourceRundownOrDebugMode();
  5100. }
  5101. #endif
  5102. return false;
  5103. }
  5104. #ifdef ENABLE_SCRIPT_DEBUGGING
  5105. bool ScriptContext::IsDebuggerRecording() const
  5106. {
  5107. if (this->GetDebugContext() != nullptr)
  5108. {
  5109. return this->GetDebugContext()->IsDebuggerRecording();
  5110. }
  5111. return false;
  5112. }
  5113. void ScriptContext::SetIsDebuggerRecording(bool isDebuggerRecording)
  5114. {
  5115. if (this->GetDebugContext() != nullptr)
  5116. {
  5117. this->GetDebugContext()->SetIsDebuggerRecording(isDebuggerRecording);
  5118. }
  5119. }
  5120. #endif
  5121. bool ScriptContext::IsIntlEnabled()
  5122. {
  5123. #ifdef ENABLE_INTL_OBJECT
  5124. if (GetConfig()->IsIntlEnabled())
  5125. {
  5126. #ifdef INTL_WINGLOB
  5127. // This will try to load globalization dlls if not already loaded.
  5128. Js::DelayLoadWindowsGlobalization* globLibrary = GetThreadContext()->GetWindowsGlobalizationLibrary();
  5129. return globLibrary->HasGlobalizationDllLoaded();
  5130. #else
  5131. return true;
  5132. #endif
  5133. }
  5134. #endif
  5135. return false;
  5136. }
  5137. #ifdef INLINE_CACHE_STATS
  5138. void ScriptContext::LogCacheUsage(Js::PolymorphicInlineCache *cache, bool isGetter, Js::PropertyId propertyId, bool hit, bool collision)
  5139. {
  5140. if (cacheDataMap == NULL)
  5141. {
  5142. cacheDataMap = RecyclerNew(this->recycler, CacheDataMap, this->recycler);
  5143. BindReference(cacheDataMap);
  5144. }
  5145. InlineCacheData *data = NULL;
  5146. if (!cacheDataMap->TryGetValue(cache, &data))
  5147. {
  5148. data = Anew(GeneralAllocator(), InlineCacheData);
  5149. cacheDataMap->Item(cache, data);
  5150. data->isGetCache = isGetter;
  5151. data->propertyId = propertyId;
  5152. }
  5153. Assert(data->isGetCache == isGetter);
  5154. Assert(data->propertyId == propertyId);
  5155. if (hit)
  5156. {
  5157. data->hits++;
  5158. }
  5159. else
  5160. {
  5161. data->misses++;
  5162. }
  5163. if (collision)
  5164. {
  5165. data->collisions++;
  5166. }
  5167. }
  5168. #endif
  5169. #ifdef FIELD_ACCESS_STATS
  5170. void ScriptContext::RecordFieldAccessStats(FunctionBody* functionBody, FieldAccessStatsPtr fieldAccessStats)
  5171. {
  5172. Assert(fieldAccessStats != nullptr);
  5173. if (!PHASE_STATS1(Js::ObjTypeSpecPhase))
  5174. {
  5175. return;
  5176. }
  5177. FieldAccessStatsEntry* entry;
  5178. if (!this->fieldAccessStatsByFunctionNumber->TryGetValue(functionBody->GetFunctionNumber(), &entry))
  5179. {
  5180. RecyclerWeakReference<FunctionBody>* functionBodyWeakRef;
  5181. this->recycler->FindOrCreateWeakReferenceHandle(functionBody, &functionBodyWeakRef);
  5182. entry = RecyclerNew(this->recycler, FieldAccessStatsEntry, functionBodyWeakRef, this->recycler);
  5183. this->fieldAccessStatsByFunctionNumber->AddNew(functionBody->GetFunctionNumber(), entry);
  5184. }
  5185. entry->stats.Prepend(fieldAccessStats);
  5186. }
  5187. #endif
  5188. #ifdef MISSING_PROPERTY_STATS
  5189. void ScriptContext::RecordMissingPropertyMiss()
  5190. {
  5191. this->missingPropertyMisses++;
  5192. }
  5193. void ScriptContext::RecordMissingPropertyHit()
  5194. {
  5195. this->missingPropertyHits++;
  5196. }
  5197. void ScriptContext::RecordMissingPropertyCacheAttempt()
  5198. {
  5199. this->missingPropertyCacheAttempts++;
  5200. }
  5201. #endif
  5202. bool ScriptContext::IsIntConstPropertyOnGlobalObject(Js::PropertyId propId)
  5203. {
  5204. return intConstPropsOnGlobalObject->ContainsKey(propId);
  5205. }
  5206. void ScriptContext::TrackIntConstPropertyOnGlobalObject(Js::PropertyId propertyId)
  5207. {
  5208. intConstPropsOnGlobalObject->AddNew(propertyId);
  5209. }
  5210. bool ScriptContext::IsIntConstPropertyOnGlobalUserObject(Js::PropertyId propertyId)
  5211. {
  5212. return intConstPropsOnGlobalUserObject->ContainsKey(propertyId) != NULL;
  5213. }
  5214. void ScriptContext::TrackIntConstPropertyOnGlobalUserObject(Js::PropertyId propertyId)
  5215. {
  5216. intConstPropsOnGlobalUserObject->AddNew(propertyId);
  5217. }
  5218. void ScriptContext::AddCalleeSourceInfoToList(Utf8SourceInfo* sourceInfo)
  5219. {
  5220. Assert(sourceInfo);
  5221. RecyclerWeakReference<Js::Utf8SourceInfo>* sourceInfoWeakRef = nullptr;
  5222. this->GetRecycler()->FindOrCreateWeakReferenceHandle(sourceInfo, &sourceInfoWeakRef);
  5223. Assert(sourceInfoWeakRef);
  5224. if (!calleeUtf8SourceInfoList)
  5225. {
  5226. Recycler *recycler = this->GetRecycler();
  5227. calleeUtf8SourceInfoList.Root(RecyclerNew(recycler, CalleeSourceList, recycler), recycler);
  5228. }
  5229. if (!calleeUtf8SourceInfoList->Contains(sourceInfoWeakRef))
  5230. {
  5231. calleeUtf8SourceInfoList->Add(sourceInfoWeakRef);
  5232. }
  5233. }
  5234. #ifdef ENABLE_JS_ETW
  5235. void ScriptContext::EmitStackTraceEvent(__in UINT64 operationID, __in USHORT maxFrameCount, bool emitV2AsyncStackEvent)
  5236. {
  5237. // If call root level is zero, there is no EntryExitRecord and the stack walk will fail.
  5238. if (GetThreadContext()->GetCallRootLevel() == 0)
  5239. {
  5240. return;
  5241. }
  5242. Assert(EventEnabledJSCRIPT_STACKTRACE() || EventEnabledJSCRIPT_ASYNCCAUSALITY_STACKTRACE_V2() || PHASE_TRACE1(Js::StackFramesEventPhase));
  5243. BEGIN_TEMP_ALLOCATOR(tempAllocator, this, _u("StackTraceEvent"))
  5244. {
  5245. JsUtil::List<StackFrameInfo, ArenaAllocator> stackFrames(tempAllocator);
  5246. Js::JavascriptStackWalker walker(this);
  5247. unsigned short nameBufferLength = 0;
  5248. Js::StringBuilder<ArenaAllocator> nameBuffer(tempAllocator);
  5249. nameBuffer.Reset();
  5250. OUTPUT_TRACE(Js::StackFramesEventPhase, _u("\nPosting stack trace via ETW:\n"));
  5251. ushort frameCount = walker.WalkUntil((ushort)maxFrameCount, [&](Js::JavascriptFunction* function, ushort frameIndex) -> bool
  5252. {
  5253. ULONG lineNumber = 0;
  5254. LONG columnNumber = 0;
  5255. UINT32 methodIdOrNameId = 0;
  5256. UINT8 isFrameIndex = 0; // FALSE
  5257. const WCHAR* name = nullptr;
  5258. if (function->IsScriptFunction() && !function->IsLibraryCode())
  5259. {
  5260. Js::FunctionBody * functionBody = function->GetFunctionBody();
  5261. functionBody->GetLineCharOffset(walker.GetByteCodeOffset(), &lineNumber, &columnNumber);
  5262. methodIdOrNameId = EtwTrace::GetFunctionId(functionBody);
  5263. name = functionBody->GetExternalDisplayName();
  5264. }
  5265. else
  5266. {
  5267. if (function->IsScriptFunction())
  5268. {
  5269. name = function->GetFunctionBody()->GetExternalDisplayName();
  5270. }
  5271. else
  5272. {
  5273. name = walker.GetCurrentNativeLibraryEntryName();
  5274. }
  5275. ushort nameLen = ProcessNameAndGetLength(&nameBuffer, name);
  5276. methodIdOrNameId = nameBufferLength;
  5277. // Keep track of the current length of the buffer. The next nameIndex will be at this position (+1 for each '\\', '\"', and ';' character added above).
  5278. nameBufferLength += nameLen;
  5279. isFrameIndex = 1; // TRUE;
  5280. }
  5281. StackFrameInfo frame((DWORD_PTR)function->GetScriptContext(),
  5282. (UINT32)lineNumber,
  5283. (UINT32)columnNumber,
  5284. methodIdOrNameId,
  5285. isFrameIndex);
  5286. OUTPUT_TRACE(Js::StackFramesEventPhase, _u("Frame : (%s : %u) (%s), LineNumber : %u, ColumnNumber : %u\n"),
  5287. (isFrameIndex == 1) ? (_u("NameBufferIndex")) : (_u("MethodID")),
  5288. methodIdOrNameId,
  5289. name,
  5290. lineNumber,
  5291. columnNumber);
  5292. stackFrames.Add(frame);
  5293. return false;
  5294. });
  5295. Assert(frameCount == (ushort)stackFrames.Count());
  5296. if (frameCount > 0) // No need to emit event if there are no script frames.
  5297. {
  5298. auto nameBufferString = nameBuffer.Detach();
  5299. if (nameBufferLength > 0)
  5300. {
  5301. // Account for the terminating null character.
  5302. nameBufferLength++;
  5303. }
  5304. if (emitV2AsyncStackEvent)
  5305. {
  5306. JS_ETW(EventWriteJSCRIPT_ASYNCCAUSALITY_STACKTRACE_V2(operationID, frameCount, nameBufferLength, sizeof(StackFrameInfo), &stackFrames.Item(0), nameBufferString));
  5307. }
  5308. else
  5309. {
  5310. JS_ETW(EventWriteJSCRIPT_STACKTRACE(operationID, frameCount, nameBufferLength, sizeof(StackFrameInfo), &stackFrames.Item(0), nameBufferString));
  5311. }
  5312. }
  5313. }
  5314. END_TEMP_ALLOCATOR(tempAllocator, this);
  5315. OUTPUT_FLUSH();
  5316. }
  5317. // Info: Append sourceString to stringBuilder after escaping charToEscape with escapeChar.
  5318. // "SomeBadly\0Formed\0String" => "SomeBadly\\\0Formed\\\0String"
  5319. // Parameters: stringBuilder - The Js::StringBuilder to which we should append sourceString.
  5320. // sourceString - The string we want to escape and append to stringBuilder.
  5321. // sourceStringLen - Length of sourceString.
  5322. // escapeChar - Char to use for escaping.
  5323. // charToEscape - The char which we should escape with escapeChar.
  5324. // Returns: Count of chars written to stringBuilder.
  5325. charcount_t ScriptContext::AppendWithEscapeCharacters(Js::StringBuilder<ArenaAllocator>* stringBuilder, const WCHAR* sourceString, charcount_t sourceStringLen, WCHAR escapeChar, WCHAR charToEscape)
  5326. {
  5327. const WCHAR* charToEscapePtr = wcschr(sourceString, charToEscape);
  5328. charcount_t charsPadding = 0;
  5329. // Only escape characters if sourceString contains one.
  5330. if (charToEscapePtr)
  5331. {
  5332. charcount_t charsWritten = 0;
  5333. charcount_t charsToAppend = 0;
  5334. while (charToEscapePtr)
  5335. {
  5336. charsToAppend = static_cast<charcount_t>(charToEscapePtr - sourceString) - charsWritten;
  5337. stringBuilder->Append(sourceString + charsWritten, charsToAppend);
  5338. stringBuilder->Append(escapeChar);
  5339. stringBuilder->Append(charToEscape);
  5340. // Keep track of this extra escapeChar character so we can update the buffer length correctly below.
  5341. charsPadding++;
  5342. // charsWritten is a count of the chars from sourceString which have been written - not count of chars Appended to stringBuilder.
  5343. charsWritten += charsToAppend + 1;
  5344. // Find next charToEscape.
  5345. charToEscapePtr++;
  5346. charToEscapePtr = wcschr(charToEscapePtr, charToEscape);
  5347. }
  5348. // Append the final part of the string if there is any left after the final charToEscape.
  5349. if (charsWritten != sourceStringLen)
  5350. {
  5351. charsToAppend = sourceStringLen - charsWritten;
  5352. stringBuilder->Append(sourceString + charsWritten, charsToAppend);
  5353. }
  5354. }
  5355. else
  5356. {
  5357. stringBuilder->AppendSz(sourceString);
  5358. }
  5359. return sourceStringLen + charsPadding;
  5360. }
  5361. /*static*/
  5362. ushort ScriptContext::ProcessNameAndGetLength(Js::StringBuilder<ArenaAllocator>* nameBuffer, const WCHAR* name)
  5363. {
  5364. Assert(nameBuffer);
  5365. Assert(name);
  5366. ushort nameLen = (ushort)wcslen(name);
  5367. // Surround each function name with quotes and escape any quote characters in the function name itself with '\\'.
  5368. nameBuffer->Append('\"');
  5369. // Adjust nameLen based on any escape characters we added to escape the '\"' in name.
  5370. nameLen = (unsigned short)AppendWithEscapeCharacters(nameBuffer, name, nameLen, '\\', '\"');
  5371. nameBuffer->AppendCppLiteral(_u("\";"));
  5372. // Add 3 padding characters here - one for initial '\"' character, too.
  5373. nameLen += 3;
  5374. return nameLen;
  5375. }
  5376. #endif
  5377. Field(Js::Var)* ScriptContext::GetModuleExportSlotArrayAddress(uint moduleIndex, uint slotIndex)
  5378. {
  5379. Js::SourceTextModuleRecord* moduleRecord = this->GetModuleRecord(moduleIndex);
  5380. Assert(moduleRecord != nullptr);
  5381. // Require caller to also provide the intended access slot so we can do bounds check now.
  5382. if (moduleRecord->GetLocalExportCount() + 1 <= slotIndex)
  5383. {
  5384. Js::Throw::FatalInternalError();
  5385. }
  5386. return moduleRecord->GetLocalExportSlots();
  5387. }
  5388. #if ENABLE_NATIVE_CODEGEN
  5389. void JITPageAddrToFuncRangeCache::ClearCache()
  5390. {
  5391. if (jitPageAddrToFuncRangeMap != nullptr)
  5392. {
  5393. jitPageAddrToFuncRangeMap->Map(
  5394. [](void* key, RangeMap* value) {
  5395. HeapDelete(value);
  5396. });
  5397. HeapDelete(jitPageAddrToFuncRangeMap);
  5398. jitPageAddrToFuncRangeMap = nullptr;
  5399. }
  5400. if (largeJitFuncToSizeMap != nullptr)
  5401. {
  5402. HeapDelete(largeJitFuncToSizeMap);
  5403. largeJitFuncToSizeMap = nullptr;
  5404. }
  5405. }
  5406. void JITPageAddrToFuncRangeCache::AddFuncRange(void * address, uint bytes)
  5407. {
  5408. AutoCriticalSection autocs(GetCriticalSection());
  5409. if (bytes <= AutoSystemInfo::PageSize)
  5410. {
  5411. if (jitPageAddrToFuncRangeMap == nullptr)
  5412. {
  5413. jitPageAddrToFuncRangeMap = HeapNew(JITPageAddrToFuncRangeMap, &HeapAllocator::Instance, 1027);
  5414. }
  5415. void * pageAddr = GetPageAddr(address);
  5416. RangeMap * rangeMap = nullptr;
  5417. bool isPageAddrFound = jitPageAddrToFuncRangeMap->TryGetValue(pageAddr, &rangeMap);
  5418. if (rangeMap == nullptr)
  5419. {
  5420. Assert(!isPageAddrFound);
  5421. rangeMap = HeapNew(RangeMap, &HeapAllocator::Instance);
  5422. jitPageAddrToFuncRangeMap->Add(pageAddr, rangeMap);
  5423. }
  5424. uint byteCount = 0;
  5425. Assert(!rangeMap->TryGetValue(address, &byteCount));
  5426. rangeMap->Add(address, bytes);
  5427. }
  5428. else
  5429. {
  5430. if (largeJitFuncToSizeMap == nullptr)
  5431. {
  5432. largeJitFuncToSizeMap = HeapNew(LargeJITFuncAddrToSizeMap, &HeapAllocator::Instance, 1027);
  5433. }
  5434. uint byteCount = 0;
  5435. Assert(!largeJitFuncToSizeMap->TryGetValue(address, &byteCount));
  5436. largeJitFuncToSizeMap->Add(address, bytes);
  5437. }
  5438. }
  5439. void* JITPageAddrToFuncRangeCache::GetPageAddr(void * address)
  5440. {
  5441. return (void*)((uintptr_t)address & ~(AutoSystemInfo::PageSize - 1));
  5442. }
  5443. void JITPageAddrToFuncRangeCache::RemoveFuncRange(void * address)
  5444. {
  5445. AutoCriticalSection autocs(GetCriticalSection());
  5446. void * pageAddr = GetPageAddr(address);
  5447. RangeMap * rangeMap = nullptr;
  5448. uint bytes = 0;
  5449. if (jitPageAddrToFuncRangeMap && jitPageAddrToFuncRangeMap->TryGetValue(pageAddr, &rangeMap))
  5450. {
  5451. Assert(rangeMap->Count() != 0);
  5452. rangeMap->Remove(address);
  5453. if (rangeMap->Count() == 0)
  5454. {
  5455. HeapDelete(rangeMap);
  5456. rangeMap = nullptr;
  5457. jitPageAddrToFuncRangeMap->Remove(pageAddr);
  5458. }
  5459. return;
  5460. }
  5461. else if (largeJitFuncToSizeMap && largeJitFuncToSizeMap->TryGetValue(address, &bytes))
  5462. {
  5463. largeJitFuncToSizeMap->Remove(address);
  5464. }
  5465. else
  5466. {
  5467. AssertMsg(false, "Page address not found to remove the func range");
  5468. }
  5469. }
  5470. bool JITPageAddrToFuncRangeCache::IsNativeAddr(void * address)
  5471. {
  5472. AutoCriticalSection autocs(GetCriticalSection());
  5473. void * pageAddr = GetPageAddr(address);
  5474. RangeMap * rangeMap = nullptr;
  5475. if (jitPageAddrToFuncRangeMap && jitPageAddrToFuncRangeMap->TryGetValue(pageAddr, &rangeMap))
  5476. {
  5477. if (rangeMap->MapUntil(
  5478. [&](void* key, uint value) {
  5479. return (key <= address && (uintptr_t)address < ((uintptr_t)key + value));
  5480. }))
  5481. {
  5482. return true;
  5483. }
  5484. }
  5485. return largeJitFuncToSizeMap && largeJitFuncToSizeMap->MapUntil(
  5486. [&](void *key, uint value) {
  5487. return (key <= address && (uintptr_t)address < ((uintptr_t)key + value));
  5488. });
  5489. }
  5490. JITPageAddrToFuncRangeCache::JITPageAddrToFuncRangeMap * JITPageAddrToFuncRangeCache::GetJITPageAddrToFuncRangeMap()
  5491. {
  5492. return jitPageAddrToFuncRangeMap;
  5493. }
  5494. JITPageAddrToFuncRangeCache::LargeJITFuncAddrToSizeMap * JITPageAddrToFuncRangeCache::GetLargeJITFuncAddrToSizeMap()
  5495. {
  5496. return largeJitFuncToSizeMap;
  5497. }
  5498. #endif
  5499. } // End namespace Js