ScriptContext.cpp 221 KB

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