ScriptContext.cpp 255 KB

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