ScriptContext.cpp 222 KB

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