2
0

ScriptContext.cpp 216 KB

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