ScriptContext.cpp 263 KB

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